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 |
|---|---|---|---|---|---|
Journal Journal: Rant: Android namespaces and ids 2.
However, if you want to refer to an object, you need its id. The way to add an id is to add the android:id attribute to the layout, or via the object's setId() method. In either case, the id is kept under R.id. This makes for a common line of code Button button = (Button) findViewById(R.id.id_of_button);
The reason is, in order to get a reference to the button, you have to find it first, and that is done via the button's id. Of course, since everything is stuffed under R.id, it must be cast to the appropriate type. (Ultimately, it's just an int.) This makes sense, as long as you are braindead.
First of all, there ought to be a way to directly reference an object by its container, if not an array of all similar objects. At the very least, this would provide a sensible naming scheme, for the object or container would be the parent. By shoving everything into R.id, people add the object type to the object name. A certifiable scheme by the Department of Redundancy Department. Furthermore, if i'm adding an id, i shouldn't need a method to find it, i should be able to refer to R.id.id_of_button directly. Instead, R.id.id_of_button is just a pointer, and findViewById() turns that pointer into a value. Really?! What morons come up with this stuff? Instead of the name being a reference to the object, it is a reference to a reference to the object.
But a reference to a reference isn't convoluted enough. We're going to put them all in the same namespace, so you have to add the type to the name, and even after that, cast it to make sure you have the right type.
It hurts when i see tables Customer.CustomerId. Even if the name is to avoid naming the table in each reference, at most you saved a period, and in many cases, you have to put it back in anyway, if only for clarity (so you know that it's from a table of the same name, and not just an attribute in another table) or when there are more than one column of the same name (much as they try to avoid it). Why do they do this? The solution creates the problem.
I'm beginning to think you have to be braindead before coding for Android. | http://slashdot.org/~Chacham/journal/522373/funny-comments | CC-MAIN-2016-07 | refinedweb | 420 | 72.87 |
Answer: The setEchoCharacter() method within the TextField class allows you
to do precisely that. It lets you specify the character that is
to display on the screen within the textfield area when the user
types something in it. So if you set that character to something
like '*', the password doesn't appear on the screen.
For example, the following applet creates a name and password
prompt. For the user name, the characters are echoed back normally, but
for the password only asterisks appear. To know when the
user is done entering a password, you can simply watch for ACTION_EVENT
events in the action() method of the applet.
import java.applet.*;
import java.awt.*;
public class PasswordPrompt extends Applet {
TextField username, password;
public void init() {
setLayout(new BorderLayout());
// add a username text field
Panel namePanel = new Panel();
Label nameLabel = new Label("User name: ");
namePanel.add(nameLabel);
username = new TextField(20);
namePanel.add(username);
add("North", namePanel);
// add a password text field
Panel pwPanel = new Panel();
Label pwLabel = new Label("Password: ");
pwPanel.add(pwLabel);
password = new TextField(20);
// set the echo character to be an asterisk
password.setEchoCharacter('*');
pwPanel.add(password);
add("South", pwPanel);
}
public synchronized boolean action(Event e, Object what) {
if (e.target == password && e.id == Event.ACTION_EVENT) {
// the user has pressed enter in the password
// text field. You can choose to catch ACTION_EVENTs
// for the username area as well.
showStatus("User: " + username.getText() +
", Password: " + password.getText());
return true;
}
return false;
}
}
Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.
Your name/nickname
Your email
WebSite
Subject
(Maximum characters: 1200). You have 1200 characters left. | http://www.devx.com/tips/Tip/23203 | CC-MAIN-2017-43 | refinedweb | 271 | 58.48 |
The QTextLayout class is used to lay out and render text. More...
#include <QTextLayout>
Note: All functions in this class are reentrant.:
QPainter painter(this); textLayout.draw(&painter, QPoint(0, 0));.
Constructs an empty text layout.
Constructs a text layout to lay out the given text.
Constructs a text layout to lay out the given text with the specified font.
All the metric and layout calculations will be done in terms of the paint device, paintdevice. If paintdevice is 0 the calculations will be done in screen metrics.ats().
Clears the line information in the layout. After having called this function, lineCount() returns 0.
This function was introduced in Qt 4.4.)..
Returns the current font that is used for the layout, or a default font if none is set..
Returns the i-th line of text in this text layout.
See also lineCount() and lineForTextPosition().
Returns the number of lines in this text layout.
Returns the line that contains the cursor position specified by pos.
See also isValidCursorPosition() and lineAt().
The maximum width the layout could expand to; this is essentially the width of the entire text.
Warning: This function only returns a valid value after the layout has been done.
See also minimumWidth().
The minimum width the layout needs. This is the width of the layout's smallest non-breakable substring.
Warning: This function only returns a valid value after the layout has been done.
See also maximumWidth().
Returns the next valid cursor position after oldPos that respects the given cursor mode.().().
Sets the layout's font to the given font. The layout is invalidated and must be laid out again.
See also font() and text().
Moves the text layout to point p.
Sets the position and text of the area in the layout that is processed before editing occurs.() and QTextOption.
Returns the layout's text.
Returns the current text option used to control the layout process.
See also setTextOption() and QTextOption. | http://idlebox.net/2010/apidocs/qt-everywhere-opensource-4.7.0.zip/qtextlayout.html | CC-MAIN-2014-15 | refinedweb | 325 | 70.6 |
Help with photos module and http post?
Hello Everyone,
I am currently messing around with the Kairos API and am trying to use Pythonista to take a new photo on my iPad and then upload that photo to the Kairos enroll API. I am able to get this to work fine with a URL image but for the life of me I am unable to get this to work by taking a photo with the photos module. From my understanding the photos module returns a PIL Image and I think I need to base64 encode that before uploading to the Kairos API??
Here is my code without using the photos module:
#import photos import requests #img = photos.capture_image() url = "" values = """ { "image": "URL for image", "subject_id": "test", "gallery_name": "test" } """ headers = { 'Content-Type': 'application/json', 'app_id': '********', 'app_key': '************************' } request = requests.post(url, data=values, headers=headers) response = request.content print(response)
Im hoping that someone can help me out by showing me what I need to do to be able to accomplish this task. Any help is greatly appreciated.
Thank you in advance,
Colin
A common approach is to use BytesIO:
import io with io.BytesIO() as output: img.save(output) contents = output.getvalue()
You might need to then pass contents through base64.b64encode
Thanks jonB
Its interesting because I have tried that as well and am not having good results. Maybe I just dont understand how to use io well enough yet...
@inzel, what do the Kairos API docs say about uploaded image formats, sizes etc., any gotchas there?
Here is the only real info I have from their docs:
POST /enroll
Takes a photo, finds the faces within it, and stores the faces into a gallery you create.
To enroll someone into a gallery, all you need to do is submit a JPG or PNG photo. You can submit the photo either as a publicly accessible URL, Base64 encoded photo or as a file upload.
-inzel
@inzel, ok, thanks. Can you share the relevant piece of the actual code where you are trying to upload the image?
The code is basically what I put in my original post. I have tried many many different things but havent been saving my code each time as I havent fully understood the modules. I guess I should just comment it all out in the future instead of deleting it. My main question is how I could take the image obtained from photos.capture_image() and then base64 encode it and send it in POST data.
If you have any thoughts on that I would love to hear about it :) Or if you have any thoughts on another way of accomplising the same task that would be great as well.
Thank you in advance!
-inzel
so, did you try the bytesio code, followed by b64encode? Post that completed attempt, then we can work from there. You might need to pass that through .decode('ascii') after that. you might need json= instead of data=.
I found a complete python api:
which uses those two other modifications I mentioned (they read the file directly, but the important thing is just getting the bytes out into b64encode)
@inzel Perhaps reading here could help.
See pyimgur/init.py upload_image
This module allows to post an image to imgur, using base64...
I am trying to use bytesio and base64 but cant get past the img.save line:
import photos import requests import io import base64 #img = photos.capture_image() with io.BytesIO() as output: img = photos.capture_image() img.save(output) contents = output.getvalue() image = base64.b64encode(contents) url = "``` 10, in <module> img.save(output) 1697, in save format = EXTENSION[ext] KeyError Appears that the save function requires me to have an extension. I then tried another angle and am getting a new error:
img = photos.capture_image()
contents = io.BytesIO(img)
binary_data = contents.getvalue()
image = base64.b64encode(binary_data)``` 8, in <module>
contents = io.BytesIO(img)
TypeError: 'Image' does not have the buffer interface
I tried that as well as:
img.save(output, format = ‘JPG’)
And I get errors each time:
img.save(output,'
img.save(output, format =, format = '
Maybe my syntax is wrong?
Ah perfect. That part works now.
with io.BytesIO() as output: img = photos.capture_image() img.save(output,'JPEG') contents = output.getvalue() image = base64.b64encode(contents)
I feel we are very close. I believe the final step now is determining the proper syntax to POST the payload. This would be much easier if I was able to use wireshark or another packet capture tool to see how the POST looks as its being sent but I cant do that on my iPad. This is what I am trying for my payload line but the syntax is incorrect:
payload = '{'"image": + image + "',"' + '\n' + '"subject_id": "test" + ","' + '\n' + '"gallery_name": "test"'}'
I need it to look like this when its sent:
{
“image”: image,
“subject_id”: “test”,
“gallery_name”:”test”
}
My apologies for all the new guy questions. I really appreciate all the help you guys have provided me so far. Im learning...
I got it to work!
import photos import requests import io import base64 import json with io.BytesIO() as output: img = photos.capture_image() img.save(output,'JPEG') contents = output.getvalue() image = base64.b64encode(contents) url = "" values = { 'image': image, 'subject_id': 'test', 'gallery_name': 'test' } headers = { 'Content-Type': 'application/json', 'app_id': '*********', 'app_key': '*************************' } request = requests.post(url, data=json.dumps(values), headers=headers) response = request.content print(response)``` Thanks everyone!
I decided to clean it up a bit and use some functions. I havent added my comments yet but here is a fully working solution:
import photos import requests import io import base64 import json img = photos.capture_image() def getPhoto(): with io.BytesIO() as output: img.save(output, 'JPEG') contents = output.getvalue() image = base64.b64encode(contents) return image def enrollPhoto(): subject_id = raw_input("Hello, What is your name: ? ") print("Thank you " + subject_id + "." + " Analyzing...") image = getPhoto() url = "" values = { 'image': image, 'subject_id': subject_id, 'gallery_name': subject_id } headers = { 'Content-Type': 'application/json', 'app_id': '***********', 'app_key': '****************************' } r = requests.post(url, data=json.dumps(values), headers = headers) parsed_json = json.loads(r.content) attr = parsed_json['images'][0]['attributes'] img.show() print(json.dumps(attr, indent=2)) enrollPhoto()
Just need to put in your actual app_id and app_key. Should work right away. My next step will be getting a simple interface built and then comparing the pic of the user to existing pics of the same user to determine whether or not they gain access. Something like that anyways. Turned out to be a fun endeavor!
fwiw,
requestslets you use req.json() rather than json.loads(req.contents). also, you can use json=values instead of json.dumps(values) in the request. | https://forum.omz-software.com/topic/5088/help-with-photos-module-and-http-post/?page=1 | CC-MAIN-2022-27 | refinedweb | 1,102 | 60.11 |
I am just starting to learn C++ and having a wonderful time with it.
Here are my questions:
1: How could I use 1 function to do the work of getting and returning both names, the shortest way possible?
2: I can not find how to compare strings in the if (which is why it compares 1 & 2 rather than Y & N)
3: I would like to find out how to return to verify name if an invalid answer is given.
Thank you in advance for helping me learn C++Thank you in advance for helping me learn C++Code:// Hello World! V 3_00_00 // Use of functions and variables // by SRS #include <iostream.h> #include <string> using namespace std; string firstName; string lastName; void first_name() { cout << "Please Enter Your First Name:" << endl; cin >> firstName; } void last_name() { cout << "Please Enter Your Last Name:" << endl; cin >> lastName; } // I am sure there is a way to use 1 function to return both names individually void main() { first_name(); last_name(); string fullName = firstName + " " + lastName; cout << "Please verify your correct name is " << fullName << endl; cout << "By entering '1' if it is correct" << endl; cout << "or '2' if it is incorrect:" << endl; // *Returning Point int verify; cin >> verify; if(verify == 1) // Can not figure out how to compare strings { cout << "Hello World, from " << firstName << " " << lastName << "!!"<< endl; cin.get(); } else if(verify == 2) // Can not figure out how to compare strings { cout << "Please try again:\n" << endl; main(); } else { cout << "I have no idea how to return to the verify from here" << endl; // Would like to know if it is possible to jump from here to *Returning Point cin.get(); } cin.get(); } | http://cboard.cprogramming.com/cplusplus-programming/95388-hello-world-v-3-a.html | CC-MAIN-2014-52 | refinedweb | 274 | 58.39 |
Creating MCN Employee Record Form in
Expression Blend
Hi guys in this article I will
demonstrate how to create forms in Expression Blend. This article also shows how
to implement validation to fields.
It is quite easy here as compared to that in
asp.net so hope you will enjoy creating the application in Expression Blend.
You have to follow the following steps :
Step 1 : First of all create a WPF application and name it as "MCN Employee Record Form ".
Step 2 : Now add a label to show the
instruction for directing the user to goto to next form for adding record. Type
the following text to the label "Enter MCN Employee Record"
Step 3 : Now add a button to create an
event for next form navigation. Type "Click here" on the content of the button.
Step 4 : Now to generate event on button
click. Select the button and goto event palette and on Click event type the name
of the event, here I have used Form_Load " as a name for the click event. Press
enter.
Step 5 : As soon as you press Enter, the code
behind window opens up just write the following lines in the event method.
private void
form_load(object
sender, System.Windows.RoutedEventArgs e)
{ // TODO: Add event handler
implementation here. MainWindow MainWindow = new
MainWindow();
MainWindow.Show(); this.Visibility
= System.Windows.Visibility.Hidden;
}
Also dont forget to add the namespace below as this provides form to form
navigation:
using System.Windows.Navigation ;
The XAML code for the start window is :
Step 6 : Now create a new window for
this goto File--> Add new item. and add a new window named "MainWindow" (note
this is the same name as you have written in the code lines above).
Now in the new window add labels and textboxes.
Labels to type the name of the field and textboxes to receive user input. Also
use combobox for the State field to show a list of items to the user. Here I
have used following fields :
Step 7 : Also add a button named
"Submit" to generate an event for checking the validation of the input fields.
Step 8 : To implement validation
Property in the form you have to add Labels as much in number as much fields you
wish to validate. Here I have used Five labels to validate the following fields:
Now since you have added all the validating
labels, give them a name like "* Field cannot be lift blank" etc and also change
the font to red so that it appears like a real error message. Then select all
the labels and goto the appearance property and set the visibility of all the
labels to false.
Step 9 : Now we have to generate an
event to check the validation, for this select the button control and on the
Click event type the name of event (here I have named it as "validate") and hit
enter. Now in the method write the following line of code :
private void
validate(object
sender, System.Windows.RoutedEventArgs e)
{ // TODO: Add event handler
implementation here. bool
errorFlag = false; if(
tbnation.Text =="")
{
v1.Visibility =System.Windows.Visibility.Visible;
errorFlag =true;
} else
{
v1.Visibility =System.Windows.Visibility.Hidden;
} if(
tbadd.Text =="")
{
v2.Visibility =System.Windows.Visibility.Visible;
errorFlag =true;
} else
{
v2.Visibility =System.Windows.Visibility.Hidden;
} if(
cbstate.Text =="")
{
v3.Visibility =System.Windows.Visibility.Visible;
errorFlag =true;
} else
{
v3.Visibility =System.Windows.Visibility.Hidden;
} if(
tbmail.Text =="")
{
v4.Visibility =System.Windows.Visibility.Visible;
errorFlag =true;
} else
{
v4.Visibility =System.Windows.Visibility.Hidden;
} if(
tbzip.Text =="")
{
v5.Visibility =System.Windows.Visibility.Visible;
errorFlag =true;
} else
{
v5.Visibility =System.Windows.Visibility.Hidden;
} if(errorFlag) return;
}
Meaning of terms in the code code above:
Now just hit F5 and the following output screen
flashes in:
This output shows how the validation errors
pops in as sson as the submit button is clicked with the required fields left
blank. At the same time if all the fields are filled there is no validation
error.
View All | http://www.c-sharpcorner.com/UploadFile/cd80b9/creating-mcn-employee-record-form-and-adding-validation-to-i/ | CC-MAIN-2018-09 | refinedweb | 665 | 55.74 |
Hi, I need a javascript component or widget that can display drag and drop markers over a Text area
which a user can then use to define the range for the columns in the input text area.
Similar to Microsoft Excel's functionality when we try to import data into an excel sheet using the
import from text button and selecting the fixed width import, as shown in the attachment.
Please let me know if such a component exists, or a sample code to possibly implement one.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Forum Rules | http://www.webdeveloper.com/forum/showthread.php?289529-Javascript-component-similar-to-excel-import-from-text&p=1310211 | CC-MAIN-2016-44 | refinedweb | 102 | 67.89 |
Super simplicity with React Hooks
Hooks launched with great fanfare and community excitement in February 2019. A whole new way to write React components.
Not a fundamental change, the React team would say, but a mind shift after all. A change in how you think about state, side effects, and component structure. You might not like hooks at first. With a little practice they're going to feel more natural than the component lifecycle model you're used to now.
Hooks exist to:
- help you write less code for little bits of logic
- help you move logic out of your components
- help you reuse logic between components
Some say it removes complexity around the
this keyword in JavaScript and I'm
not sure that it does. Yes, there's no more
this because everything is a
function, that's true. But you replace that with passing a lot of function
arguments around and being careful about function scope.
My favorite React Hooks magic trick is that you can and should write your own. Reusable or not, a custom hook almost always cleans up your code.
Oh and good news! Hooks are backwards compatible. You can write new stuff with hooks and keep your old stuff unchanged. 👌
In this section we're going to look at the core React hooks, talk about the most important hook for dataviz, then refactor our big example from earlier to use hooks.
useState, useEffect, and useContext
React comes with a bunch of basic and advanced hooks.
The core hooks are:
useStatefor managing state
useEffectfor side-effects
useContextfor React's context API
Here's how to think about them in a nutshell 👇
useState
The
useState hook replaces pairs of state getters and setters.
class myComponent extends React.Component {state = {value: "default",}handleChange = (e) =>this.setState({value: e.target.value,})render() {const { value } = this.statereturn <input value={value} onChange={handleChange} />}}
👇
const myComponent = () => {const [value, setValue] = useState("default")const handleChange = (e) => setValue(e.target.value)return <input value={value} onChange={handleChange} />} subscribes:
class myComp extends Component {state = {value: 'default'}handleChange = (e) => this.setState({value: e.target.value})saveValue = () => fetch('/my/endpoint', {method: 'POST'body: this.state.value})componentDidMount() {this.saveValue();}componentDidUpdate(prevProps, prevState) {if (prevState.value !== this.state.value) {this.saveValue()}}render() {const { value } = this.state;return <input value={value} onChange={handleChange} />}}
👇
const myComponent = () => {const [value, setValue] = useState('default');const handleChange = (e) => setValue(e.target.value)const saveValue = () => fetch('/my/endpoint', {method: 'POST'body: value})useEffect(saveValue, [value]);return <input value={value} onChange={handleChange} />}
So much less code!
useEffect runs your function on
componentDidMount and
componentDidUpdate.
And that second argument, the
[value] part, tells it to run only when:
const [mouseX, setMouseX] = useState()const handleMouse = (e) => setMouseX(e.screenX)useEffect(() => {window.addEventListener("mousemove", handleMouse)return () => window.removeEventListener(handleMouse)})
Neat 👌
useContext
useContext cleans up your render prop callbacky hell.
const SomeContext = React.createContext()// ...<SomeContext.Consumer>{state => ...}</SomeContext.Consumer>
👇
const state = useContext(SomeContext)
Context state becomes just a value in your function. React auto subscribes to all updates.
And those are the core hooks. useState, useEffect, and useContext. You can use them to build almost everything. 👌
React, D3, and hooks
Now that you know the basics of hooks, and you've got the mental models of combining D3 and React for modern dataviz, let's try an exercise. Learn how to combine that knowledge into using React, D3, and hooks for dataviz.
Blackbox components with hooks
We'll start with blackbox components. Take the final blackbox example below and refactor it to using hooks.
You'll need the
useRef hook to reference a rendered
<g> element and the
useEffect hook to trigger D3 rendering when the component changes. Don't forget to update React version to latest.
Try solving it yourself before watching my video. Helps you learn :)
My solution
my useD3 hook for blackbox components
Even better than doing it yourself is using the ready-made
useD3 hook I opensourced for you :)
Read the full docs at d3blackbox.com
It works as a combination of
useRef and
useEffect. Hooks into component
re-renders, gives you control of the anchor element, and re-runs your D3 render
function on every component render.
You use it like this:
import { useD3 } from "d3blackbox"function renderSomeD3(anchor) {d3.select(anchor)// ...}const MyD3Component = ({ x, y }) => {const refAnchor = useD3((anchor) => renderSomeD3(anchor))return <g ref={refAnchor} transform={`translate(${x}, ${y})`} />}
You'll see how this works in more detail when we build the big example project. We'll use
useD3 to build axes.
Here's how the above example looks when you use
useD3 ✌️
Full integration components with hooks
The core mental shift with hooks comes in where your D3 code lives 👉 in the main render.
Where we used to spread D3 code around the whole component class, hooks let us do it all in the main render method. Because that's all there is to our component - the main render method.
Anything bound to component lifecycle goes into
useEffect, anything we need every time, goes in the function body. When a lot of logic builds up, extract it to a custom hook.
If you're worried about performance or have a large dataset 👉 wrap in
useMemo.
Take this Scatterplot example from before and try to refactor it using hooks. After you gave it a shot, watch the video to check my solution.
useMemo is your new best dataviz friend
My favorite hook for making React and D3 work together is
useMemo. It's like
a combination of
useEffect and
useState.
Remember how the rest of this course focused on syncing D3's internal state with React's internal state and complications around large datasets and speeding up your D3 code to avoid recomputing on every render?
All that goes away with
useMemo – it memoizes values returned from a function
and recomputes them when particular props change. Think of it like a cache.
Say you have a D3 linear scale. You want to update its range when your component's width changes.
function MyComponent({ data, width }) {const scale = useMemo(() =>d3.scaleLinear().domain([0, 1]).range([0, width])), [width])return <g> ... </g>}
useMemo takes a function that returns a value to be memoized. In this case
that's the linear scale.
You create the scale same way you always would. Initiate a scale, set the domain, update the range. No fancypants trickery.
useMemo's second argument works much like useEffect's does: It tells React
which values to observe for change. When that value changes,
useMemo reruns
your function and gets a new scale.
Don't rely on
useMemo running only once however. Memoization is meant as a
performance optimization, a hint if you will, not as a syntactical guarantee of
uniqueness.
And that's exactly what we want. No more futzing around with
getDerivedStateFromProps and
this.state. Just
useMemo and leave the rest
to React. ✌️ | https://reactfordataviz.com/building-blocks/5/ | CC-MAIN-2022-40 | refinedweb | 1,140 | 58.38 |
grunt-iconpack是什么
什么是grunt-iconpack,Package SVG icons as an SVG sprite.
grunt-iconpack使用教程帮助文档
grunt-iconpack
Package SVG icons as an SVG sprite. Support for webfonts is planned.
Gettingpack --save-dev
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
grunt.loadNpmTasks('grunt-iconpack');
The “iconpack” task
Overview
In your project’s Gruntfile, add a section named
iconpack to the data object passed into
grunt.initConfig().
grunt.initConfig({ iconpack: { options: { // Task-specific options go here. }, your_target: { // Target-specific options and configuration go here. }, }, });
Options
options.loadPaths
Type:
Array Default value:
false
An array of directory paths in which to search for source files. For each
src path defined in the normal Grunt files config, load paths are searched (in array order) for matching files. Once a match is found, successive load paths for that
src are skipped.
This makes it easy to combine icon sets without having to write out the paths for each icon individually. The
src property can hold an array of filenames, and the
loadPaths option will load preferentially from the first path, then the second, and so on.
When using this option, the
src files can contain any normal Grunt globbing patterns which will be expanded under each load path,
loadPaths values can themselves contain glob patterns.
options.svgPrefix
Type:
String Default value:
''
Add a prefix to the beginning of
<symbol> ids. Useful as a namespace to avoid id attribute collisions. Example value:
'icon-'.
options.removeTitleElement
Type:
Boolean Default value:
true
By default, SVG
<title> elements are removed. Change this option to
false to keep them.
Other Configuration
In addition to the
loadPaths option, this module allows you to leave off extensions in
src file paths. If absent,
.svg will automatically be appended.
Usage Examples
Build an SVG sprite from a single set of source files
In this example, the normal Grunt files array is used to build an SVG sprite from a single set of source SVGs.
grunt.initConfig({ iconpack: { basic_example: { files: [{ expand: true, cwd: 'assets/icons/src', src: [ 'menu.svg', 'search.svg', 'chevron-*.svg', ], dest: 'assets/icons/sprite.svg' }] } }, });
Build an SVG sprite from several SVG sources
In this example, two sets of SVGs from different sources (here, a Bower component and some local files) are combined into one sprite.
The
loadPaths option allows conditional loading of icons from several sets. In this example, if
menu.svg is present in both load paths, the one found first (in this case, in
assets/icons/src) will be used instead of any
menu.svg provided by the Bower component.
Note that file extensions can be left off for source files; they will be appended automatically if absent.
grunt.initConfig({ iconpack: { using_load_paths: { options: { loadPaths: [ 'assets/icons/src/**', 'bower_components/some-icon-set/svg/**' ] }, files: [{ src: [ 'menu', 'search', 'chevron-*', ], dest: 'assets/icons/sprite.svg' }] } }, });
Load icon definitions from an external file
The following example doesn’t demonstrate any unique functionality but it does show what is made possible by features such as the
loadPaths option.
grunt.initConfig({ iconpack: { build_svg_sprite: { options: { loadPaths: [ 'assets/icons/src/**', 'bower_components/some-icon-set/svg/**' ] }, files: [{ src: grunt.file.readJSON('assets/icons.json'), dest: 'assets/icons/sprite.svg' }] } }, });
icons.json might look like this:
[ "menu", "search", "chevron-*" ]
This makes it easy to change which icons will be built into a sprite once
loadPaths are defined.
Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt: just run the following command in the project root:
grunt
Release History
(Nothing yet):grunt-iconpack | https://www.javascriptcn.com/read-79348.html | CC-MAIN-2019-51 | refinedweb | 605 | 56.45 |
Opened 7 years ago
Closed 6 years ago
#2818 closed defect (fixed)
Trac crashes after installing the XMLRPC plugin
Description
After installing the XMLPRC plugin, trac crashes with the following the error below.
This issue was reported by other users on the main Trac site: Ticket 4280 at the Edgewall Trac system.
Error:-x86_64/egg/tracrpc/web_ui.py", line 76, in get_templates_dirs File "/usr/lib/python2.4/site-packages/setuptools-0.6c8-py2.4.egg/pkg_resources.py", line 16, in ?
import sys, os, zipimport, time, re, imp, new
File "/usr/lib64/python2.4/os.py", line 48, in ?
import posixpath as path
ImportError: No module named posixpath
Attachments (0)
Change History (2)
comment:1 Changed 6 years ago by osimons
- Owner changed from athomas to osimons
comment:2 Changed 6 years ago by osimons
- Resolution set to fixed
- Status changed from new to closed
(In [6106]) XmlRpcPlugin: Removing use of posixpath and replacing with os.path. Also added tests for wiki attachments where this code was used.
I'll fix this. Next on the list. | http://trac-hacks.org/ticket/2818 | CC-MAIN-2015-18 | refinedweb | 175 | 56.45 |
Hi guys. So, i have this small plugin that replace # chars with numbers. The problem is that it never worked on ST3 and today i decided to allocate some time to fix it.
Here is the full code: gist.github.com/iamntz/5546478
So, when i run the command, i get this error raised:
ValueError: Edit objects may not be used after the TextCommand's run method has returned
There is some weird issue on this code:!
You lose the edit object when the command returns. You will have to call another command to perform the actual insert. You can use something like
class BatchReplaceCommand(sublime_plugin.TextCommand):
def run(self, edit, replace_text, begin_region_point, end_region_point):
self.view.replace(edit, region, sublime.Region(begin_region_point, end_region_point))
I didn't test that, so you may need to modify it a bit to get it work, but you should be able to get your plugin running. | https://forum.sublimetext.com/t/little-help-with-show-input-panel/10013/1 | CC-MAIN-2016-36 | refinedweb | 151 | 66.03 |
Introduction
This command line tool extracts C/C++ constants, predefinitions, structs, and enums from a C/C++ header file and then outputs it to a C# file. This tool is not a full featured C/C++ to C# converter - it does not convert functions to C#. This tool is meant to copy header information from a C/C++ file to a C# file so that constants, predefinitions, structs, and enums can be shared between C/C++ project and C# projects. This conversion would typically be done using Visual Studio's pre-build command line events. The goal is to keep one set of constants and enums for both a C/C++ and C# project. These constants and enums are extracted from a given C/C++ file, converted, and are then written to a generated C# file that is usually already added to a C# project. The conversion is extremely quick so it should not have much impact on your total compile time.
Since C# does not support predefinitions at the same level as C/C++, the program converts #define values to C# constants in a default class. Since the C/C++ #define values are typeless, CppHeader2CS tries to figure out the best constant type to use for the C# output. In a nutshell, it first tries parsing an int, followed by a float, followed by bool, and if all else fails it just saves it as a string. Example: #Define cat 5 is translated into public const int cat = 5; whereas #define cat 5.0 is translated into public const float cat = 5;. Any type can also be forced by appending the C2CS_TYPE command in a comment following the #define. For Example, #Define cat 5 // C2CS_TYPE: float is translated to public const float cat = 5;.
#Define cat 5
public const int cat = 5;
#define cat 5.0
public const float cat = 5;
C2CS_TYPE
#Define cat 5 // C2CS_TYPE: float
public const float cat = 5;
To accomplish the conversions Regular Expressions are used to gather the information, then the data is converted into to its C# equivalent and then saved into one of three destination areas. The three C# destination areas are the top, namespace, and class area. (see orange boxes in diagram) StringBuilders are used to gather the converted three areas. The first, 'Top Area' StringBuilder writes to the very top of the C# file. This can be something like using system.IO; and added by using a special command in the C/C++ source file, //C2CS_Top_Write using system.IO;. The second StringBuilder outputs to the namespace area and would typically consist of structs and enums. The final location is in a default class area and this mainly holds constants. In the end, these are merged into one document and are outputted either to a file or to the console. Below you will find an output image with some orange boxes on it. Each orange box represents a StringBuilder.
using system.IO;
//C2CS_Top_Write using system.IO;
In the past, I have had many instances where I had a need to pass constants, enums or simple structures from a C/C++ to a C# project. Searching online, I could not find anything that would do what I wanted. Other solutions were full C/C++ to C# conversions that were too slow to run on each compile. I did find a nice T2 templates project that did some of the stuff I wanted but overall the T2 template was hard to read and do not support the functionality I needed. I decided on a regular expressions approach. RegEx can be a little annoying and hard to read but they work great for some problems.
CppHeader2CS.exe input_file [output_file]
input_file - this is the C/C++ source header file. It should be a simple file meant for the C/C++ to C# sharing.
output_file - (optional) This is the name of the C# output file. If a name is not supplied it will use the input filename with a cs extension.
This program supports a number of commands that can be entered in the source file. The commands are added by adding them like comments. Example: // C2CS_TYPE MyType These can be used to write or adjust the output. The three C2CS_*_Write commands can be used to write anything in the C# file using comments in the C/C++ source file. The other options can be used to set a custom namespace or class name as well as force a type or skip a line in the source all together.
// C2CS_TYPE MyType
// C2CS_TOP_Write text to write - C2CS_TOP_Write is a direct pass-through that writes text above the namespace. This can be useful whenever there is a need to print at the top of the output file. Example: //C2CS_TOP_Write using System.IO;
// C2CS_NS_Write text to write - C2CS_NS_Write is a direct pass-through that writes text above the default class but in the namespace area. This area usually contains enums and structs.
// C2CS_Class_Write text to write - C2CS_Class_Write is a direct pass-through that writes text in the class area. CppHeader2CS writes only to a single class.
// C2CS_Set_Namespace MyNsName - C2CS_Set_Namespace sets the namespace name. This is optional and if unspecified defaults to C2CS.
// C2CS_Set_ClassName MyClass - C2CS_Set_ClassName sets the class name to use. This is optional and if unspecified defaults to Constants.
// C2CS_TYPE MyType - C2CS_TYPE is used in the comments after a #define to specify what type to use. This is required if the automatic detection does not work as expected or the programmer wants to force a type. Example: #Default mySum (2+1) //C2CS_TYPE int;
// C2CS_SKIP - Adding C2CS_SKIP in any comment forces CppHeader2CS to ignore the current line.
#DEFINE Cars 10
...gets added to the class area as...
public const int Cars = 10;
#DEFINE MyDouble 3.2
public const double MyDouble = 3.2f;
#DEFINE
#DEFINE MyFloat 3.2f
#DEFINE MyFloat 3.2d
Given my_float is an existing float...
#DEFINE expr1 my_float + 2
public const float expr1 = my_float + 2;
// C2CS_TYPE MyType
#DEFINE MyString New World Test!
public const string MyString = "New World Test!";
int.TryParse
float.TryParse
bool.TryParse
#DEFINE FullDebug
is slightly modified and moved to the top...
#define FullDebug
#define
// C2CS_NS_Write [StructLayout(LayoutKind.Sequential)]
struct SomeStruct1{unsigned char a; unsigned char b;};
...gets added to the namespace area as...
[StructLayout(LayoutKind.Sequential)]
public struct SomeStruct1
{
public byte a;
public byte b;
}
// C2CS_NS_Write [StructLayout(LayoutKind.Sequential)]
struct SomeStruct1{
unsigned long long test123; //some comments
public long test124;
} someStruct1Instance; // my instance notes
public struct SomeStruct1
{
public ulong test123; //some comments
public long test124;
}
...and the following also get added to the class section...
public SomeStruct1 someStruct1Instance; // my instance notes
public enum MyEnum {
test1 = 33,
test2 = 5,
test3 = test2 };
[Flags]
enum MyEnum
{
test1 = 33,
test2 = 5,
test3 = test2,
};
[Flags]
protected static char myChar = -100; // my notes
public const SByte myChar = -100; // my notes
public const...
Performance was an important component for this project. Since this tool would typically be called with each compile, it is important to keep it fast. I used some RegEx tips that I found, StringBuilders, a fast white-space remover, and a Dictionary to help with this. The conversion is relatively fast. The entire read, convert, and write for the 224-line demo file takes around 12 to 30ms depending on what system I use. Shorter files of about 40 lines take about 5ms.
StringBuilders
Dictionary
One thing I learned in some online 'RegEx Tips' is to make sure there is not any catastrophic backtracking. In a nutshell it’s a good idea to be more specific in the RegEx expressions and to avoid the ketch-all ".*". I had no major issues but I did find being more specific did help performance by about 50% for the demo file. There were some other tips I implemented also that can easily be found online. During the build though, I had a couple opportunities to increase the performance slightly, however, I gave those up for more readable code.
The file is also only 37kb and this should help out with its performance. 39 copies would fit on one 1986 1.44MB floppy disk. =)
typedef
bitfields
int add(int a, int b){ return (a+b);}
If you would like to contribute, please feel free to post the changes in the comments or submit a pull request on GitHub. To post on GitHub: (1) Fork the repository to your account by clicking the Fork button. (2) Make the changes and push your changes back to your own branch (3) create a Pull Request to include those changes in the original repository.
Being able to recognize and parse a C/C++ file so easily and quickly is a great testament to Regular Expressions. While a non-RegEx C/C++/C# parser would have probably had better performance and control, the RegEx solution was much easier and quicker to get running. RegEx is a great tool when the programmer wants to get any pattern matching done quickly and reliably. Without RegEx, the code would have been taken much longer to build and it’s possible that I would have lost interest in the project before I finished it! =)
P/Invoke Interop Assistant - This is a tool that was brought to my attention that does something similar to what cppHeader2CS does. The P/Invoke Interop Assistant is a tool that generates C# or VB P/Invoke code from a c++ file but it also emits structs, enums, #defines, and other items. Depending on your needs, this tool might be a better fit. Here are some advantages of each:
P/Invoke Interop Assistant advantages over cppHeader2CS:
windows.h
Summary: Use Interop Assistant if any of the above requirements are needed. This tool can be run at build time but it is slower and will always update the destination file. Having the destination file updated can be annoying if the file is open as visual studio will prompt you to reload it.
cppHeader2CS advantages:
Summary: Use cppHeader2CS for simpler header files that get modified often and are updated during the build process. This tool does not support char arrays, typedef, custom types, and include files.
Instructions for those that might want to try this tool in place of cppHeader2CS:
Using T4 Templates - This is another way to perform build time C/C++ to C# conversions. It is just a simple T4 file. The example in the link below just handles #define to constant conversions and will auto-detect simple integers. I am including this because this is the tool I used before cppHeader2CS. Link:
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
int myFunc1(int param1) { return 1; }
int myFunction2(double param1);
// C2CS_NS_Write abstract class
// C2CS_NS_Write {
// C2CS_NS_Write public virtual int myFunc1(int param1) { return 1; }
// C2CS_NS_Write public virtual int myFunction2(double param1);
// C2CS_NS_Write }
#ifndef _FILE_H_
#define _FILE_H_
// stuff here
#endif
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Articles/800111/Passing-C-Cplusplus-Constants-e?msg=5250055 | CC-MAIN-2020-40 | refinedweb | 1,835 | 63.39 |
Hello again, I've replaced "-o /dev/null" with a tempfile and it still didn't compile on hppa, so I took a more pragmatic approach and completely removed the checks for the include files and libs, but it fails to build again. The original code in the Makefile is: cc-include = $(shell $(CC) $(INCLUDES) -include $(1) -S -o /dev/null -xc /dev/null > /dev/null 2>&1 && echo "-D$(2)") cc-library = $(shell echo 'int main () { return 0; }' |$(CC) -l$(1:lib%=%) -o /dev/null -xc - > /dev/null 2>&1 && echo yes) ifeq ($(call cc-library,libasound),yes) LIBS += -lasound -lrt else $(error No libasound in linkage path please install alsa and alsa-devel packages) endif I modified cc-include and cc-library to: cc-include = $(shell echo "-D$(2)") cc-library = $(shell echo yes) ...but it still throws the error. So it seems, the hppa-make doesn't like the way 'call' and 'shell' are used here. Any ideas on that? Tobias | https://lists.debian.org/debian-hppa/2008/08/msg00027.html | CC-MAIN-2016-30 | refinedweb | 164 | 60.38 |
Important Note
This page is related is not related to the official Mogre sources!
It's related to a modified bundle of Mogre and some add-ons. This bundle was offered by the Mogre maintainer mstoyke.
Instructions for compiling the official Mogre sources you find in a text file inside the Mogre repository:
For instructions for other Mogre versions, look to the overview page Building MOGRE from source.
Build the modified Mogre 1.7 version
This tutorial describes how to build a modified Mogre 1.7.x from its sources. The repository was created by the Mogre maintainer mstoyke.
In the repository everything is already wrapped and patched. It also includes all dependecies which are needed to compile Ogre.
It has be designed for and tested with Visual Studio 2010 and the .NET 4.0 Framework. Other combinations may work but then the steps below must be adjusted accordingly.
For now this tutorial uses the code from an unofficial code repositories. The benefit of this repository is that it already contains compilable code (that is including all dependencies, auto-generated code, and Visual Studio solution files). For a more "manual" way see ((|#Building_Mogre_from_scratch|Building Mogre from scratch below)).
This tutorial assumes that all files are place in a single folder. For better recognition this folder is called:
C:\MyMogreBuild
Of course you can place this folder whereever you like but then you need to adjust the commands below (which isn't difficult).
For questions about building Mogre 1.7 please refer to this forum thread.
Prerequisites
For using this tutorial you need the following pieces of software:
- Visual Studio (preferably in version 2010)
- Mercurial for accessing the code repository. The command line client will suffice but for newbies to Mercurial the GUI client TortoiseHG is recommended.
- The DirectX SDK (February 2010). Other versions may work but in this case some paths in the "RenderSystem_Direct3D9" project needs to be adjusted manually.
The repositories
A pre-wrapped version of the Mogre sources can be found here: My Mogre repository
To clone the repository and get the right version use:
hg clone -u MST C:\MyMogreBuild
Then we need to grab the Ogre sources and put them in the right place. A pre-patched version of Ogre can be found here: My Ogre repository
To clone the repository and get the right version use:
hg clone -u MST C:\MyMogreBuild\Main\OgreSrc\ogre
Building Mogre
First build Ogre without any references to Mogre. To do this, open the solution file "C:\MyMogreBuild\Main\OgreSrc\ogre\lib\OGRE.sln" in Visual Studio 2010. In Visual Studio open the file "CLRConfig.h" in "OgreMain->Header Files" and change the define "LINK_TO_MOGRE 1" to "LINK_TO_MOGRE 0".
Depending on where you installed the DirectX SDK, and your operating system's default program files path, you may need to alter some of the preset values for the projects in the ogre solution: "Linker" -> "additional input" -> "additional dependencies" -> change paths with "C:\Program Files (x86)\" to "C:\Program Files\" this change may also need to be applied to the DirectX paths in "C/C++" -> "General" -> "Additional Include Directories"
I recommend using batch build now to rebuild all projects in the solution. Make some coffee, this will take some time.
After some time Ogre will be compiled and we can now build the Mogre wrapper. Open the solution file "C:\MyMogreBuild\Main\Mogre_vs2010.sln" in Visual Studio 2010
By default Mogre will be targeting the .NET Framework v4.0 How to change the target .NET Framework Make sure Visual Studio 2008 is installed if targeting 2.0/3.0/3.5 Project references must also be changed to the respective target .NET Framework version WARNING: choosing v2.0 will result in several linker errors and wasted time (I haven't tested v3 or v3.5 yet)
Use batch build to rebuild all projects in the solution.
When Mogre finished compiling, go back to Ogre solution file "mogre\Main\OgreSrc\ogre\lib\OGRE.sln" and change back the define "LINK_TO_MOGRE 0" to "LINK_TO_MOGRE 1" in "CLRConfig.h".
This time only use batch build to do a normal build for all projects. Rebuild all would just take too long this time because it's not necessary to rebuild everything completely.
Where are the compiled binaries?
Ogre binaries can be found here:
- C:\MyMogreBuild\Main\OgreSrc\ogre\lib\bin\debug
- C:\MyMogreBuild\Main\OgreSrc\ogre\lib\bin\release
Mogre binaries can be found here:
- C:\MyMogreBuild\Main\lib\Debug
- C:\MyMogreBuild\Main\lib\Release
Important: You need either to copy all Ogre .dlls to your application/project folders or put the Ogre folder in your PATH variable. You should also make sure that no other Ogre folder is included in your PATH (as this might lead to loading the wrong dlls). Note also that the Mogre dll(s) don't need to be placed in the PATH variable.
MogreFramework classes
The classes from the MogreFramework namespace (which are used in the tutorials) are not part of the official Mogre sources. Instead they're developed by the Mogre SDK project. The sources then can be found in the folder:
MogreSDK\smiley80\mogre_basic_tutorials\MogreFramework
Building Mogre manually from scratch
In my repositories everything is already wrapped and patched. I will add some instructions how to patch Ogre and rebuild the wrapper files later. I also included all dependecies needed to compile Ogre. Except for Boost, because I didn't use it.
A more common manual for building Mogre should be added here later. Alternatively you could look to Building MOGRE 1.6 from source.
ToDo
Things to do on this page:
- Include an description of how to build Mogre from scratch.
- Currently the binaries don't seem to contain any documentation (DocumentXML). This needs to be reenabled somehow.
- Change instructions to match steps for bitbucket/mogre repositories instead of obsolete bitbucket/mstoyke repositories
Alias: Building_MOGRE_1.7_from_source | https://wiki.ogre3d.org/Building+MOGRE+1.7+from+source | CC-MAIN-2022-40 | refinedweb | 981 | 57.06 |
[Petter Reinholdtsen]Hi. I notice that the latest insserv package fail to build on kfreebsd, because several posix_fadvise() arguments are unknown. The code in question is protected with #ifdefs like this: #if defined _XOPEN_SOURCE && (_XOPEN_SOURCE - 0) >= 600 else if ((dfd = dirfd(rcdir)) != 0) { (void)posix_fadvise(dfd, 0, 0, POSIX_FADV_WILLNEED); (void)posix_fadvise(dfd, 0, 0, POSIX_FADV_SEQUENTIAL); } #endif Why is this test not sufficient on kfreebsd? Can any of you provide patches to get insserv working on kfreebsd? I hope to make dependency based boot sequencing a core part of the boot system in Debian and then insserv should work on all archs.I made this patch based on the changes done to startpar in sysvinit, but fail to understand why this is needed. Can anyone confirm that this work on kfreebsd? --- insserv-1.12.0.orig/insserv.c +++ insserv-1.12.0/insserv.c @@ -40,6 +40,13 @@ #endif /* USE_RPMLIB */ #include "listing.h" +#if defined _XOPEN_SOURCE && (_XOPEN_SOURCE - 0) >= 600 +/* kfreebsd fail to provide working posix_fadvise +# ifndef POSIX_FADV_SEQUENTIAL +# define posix_fadvise(fd, off, len, adv) (-1) +# endif +#endif + #ifdef SUSE # define DEFAULT_START_LVL "3 5" # define DEFAULT_STOP_LVL "3 5"posix_fadvise is optional per POSIX, so checking that that builds if you use autoconf or for the macro is better.
See
APPLICATION USAGE The posix_fadvise() function is part of the Advisory Information option and need not be provided on all implementations. The "#define posix_fadvise(fd, off, len, adv) (-1)" is sufficient for GNU/kFreeBSD build. Petr | https://lists.debian.org/debian-bsd/2009/06/msg00088.html | CC-MAIN-2021-49 | refinedweb | 241 | 51.58 |
Description.
prop-sets alternatives and similar libraries
Based on the "Testing Frameworks" category.
Alternatively, view prop-sets alternatives based on common mentions on social networks and blogs.
puppeteer9.9 9.2 prop-sets VS puppeteerHeadless Chrome Node.js API
jest9.7 9.5 L3 prop-sets VS jestDelightful JavaScript Testing.
phantomjs9.6 0.0 prop-sets VS phantomjsScriptable Headless Browser
Cypress9.5 9.9 prop-sets VS CypressFast, easy and reliable testing for anything that runs in a browser.
mocha9.2 8.3 prop-sets VS mocha☕️ simple, flexible, fun javascript test framework for node.js & the browser
ava9.0 8.0 L4 prop-sets VS avaNode.js test runner that lets you develop with confidence 🚀
Enzyme9.0 6.4 L4 prop-sets VS EnzymeJavaScript Testing utilities for React
Nightmare8.9 0.0 L4 prop-sets VS NightmareA high-level browser automation library.
jasmine8.8 8.5 L3 prop-sets VS jasmineSimple JavaScript testing framework for browsers and node.js
karma8.4 6.9 L4 prop-sets VS karmaSpectacular Test Runner for JavaScript
Protractor8.3 0.0 L5 prop-sets VS ProtractorE2E test framework for Angular apps
nightwatch8.1 8.8 L4 prop-sets VS nightwatchEnd-to-end testing framework written in Node.js and using the Webdriver API
WebdriverIO7.7 9.8 L5 prop-sets VS WebdriverIONext-gen browser and mobile automation test framework for Node.js
TestCafe7.6 9.4 L4 prop-sets VS TestCafeA Node.js tool to automate end-to-end web testing.
Sinon.JS7.4 8.5 L2 prop-sets VS Sinon.JSTest spies, stubs and mocks for JavaScript.
casperjs7.4 0.0 L5 prop-sets VS casperjsNavigation scripting & testing utility for PhantomJS and SlimerJS.
istanbul7.4 0.0 L2 prop-sets.
chai7.1 5.3 L2 prop-sets VS chaiBDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.
zombie6.5 0.0 L4 prop-sets VS zombieInsanely fast, full-stack, headless browser testing using node.js
tape6.3 8.4 L5 prop-sets VS tapetap-producing test harness for node and browsers
qunit6.1 8.8 L2 prop-sets VS qunit🔮 An easy-to-use JavaScript unit testing framework.
intern5.9 3.6 L5 prop-sets VS internA next-generation code testing stack for JavaScript.
slimerjs5.2 0.0 L2 prop-sets VS slimerjsA scriptable browser like PhantomJS, based on Firefox
taiko5.1 9.2 prop-sets VS taikoA node.js library for testing modern web applications
expect.js4.7 0.0 L2 prop-sets VS expect.jsMinimalistic BDD-style assertions for Node.JS and the browser.
proxyquire4.6 1.9 prop-sets VS proxyquire🔮 Proxies nodejs require in order to allow overriding dependencies during testing.
blanket3.8 0.0 L2 prop-sets VS blanketblanket.js is a simple code coverage library for javascript. Designed to be easy to install and use, for both browser and nodejs.
halower/vue-tree3.3 0.0 prop-sets VS halower/vue-treetree and multi-select component based on Vue.js 2.0
DalekJS2.9 0.0 L5 prop-sets VS DalekJS[unmaintained] DalekJS Base framework
totoro2.9 0.0 L5 prop-sets VS totoroA simple and stable cross-browser testing tool. 简单稳定的跨浏览器测试工具。
FrintJS2.7 0.0 prop-sets VS FrintJSModular JavaScript framework for building scalable and reactive applications
autochecker2.6 0.0 L5 prop-sets VS autochecker♻️ Test your libraries in many different versions of NodeJS, Ruby, Java and many other languages
Nullstack2.6 8.9 prop-sets VS NullstackFull-stack javascript components for one-dev armies.
Webix UI2.5 3.0 prop-sets VS Webix UIStable releases of Webix UI - JavaScript library for building mobile and desktop web apps
JSCover2.5 7.2 L4 prop-sets VS JSCoverJSCover is a JavaScript Code Coverage Tool that measures line, branch and function coverage
Liquor Tree2.4 0.0 prop-sets VS Liquor TreeTree component based on Vue.js
prova2.0 0.0 L5 prop-sets VS provaTest runner based on Tape and Browserify
ChaoSocket.js1.8 0.0 L5 prop-sets VS ChaoSocket.js:boom: Mock WebSockets and create chaos :boom:
consolemock1.2 0.0 prop-sets VS consolemockA tool for testing console logs
yolpo1.0 0.0 L1 prop-sets VS yolpoAn environment to visualize JavaScript code execution in a browser
vue-trees0.7 0.0 prop-sets VS vue-trees🎄 ui base on vue
Vuex module generatorVuex store module generator plugin for vue-cli 3
react testing librarySimple and complete React DOM testing utilities that encourage good testing practices. prop-sets or a related project?
README
prop-sets.
Benefits
Let's say you have a React component called Button with the props
disabled and
color, as well as a test that asserts the button is gray when
disabled is true and
color otherwise. Here's how to use
prop-sets to assert the component renders the correct color:
const Button = props => ( <button disabled={props.disabled} style={{ backgroundColor: props.disabled ? "gray" : props.color }} /> ); it("is gray when disabled, props.color otherwise", () => { propSets({ color: ["red", "blue"], disabled: [true, false] }).forEach(props => { const component = <Button {...props} />; const color = getColor(component); expect(color).toBe(props.disabled ? "gray" : props.color); }); });
prop-sets helps you easily write tests for assertions that are based on multiple input values (in this case,
disabled and
color) without greatly increasing the amount of code you have to write.
Without
prop-sets, this test will need to be expanded to three assertions:
it("is gray when disabled", () => { const component = <Button disabled; const color = getColor(component); expect(color).toBe("gray"); }); it("is red when props.color is red", () => { const component = <Button color="red" />; const color = getColor(component); expect(color).toBe("red"); }); it("is blue when props.color is blue", () => { const component = <Button color="blue" />; const color = getColor(component); expect(color).toBe("blue"); });
Because
backgroundColor's value is determined by both the
disabled and
color prop, we need to have all three assertions to be sure the component behaves as expected. Here are some implementations of
Button that will only pass certain tests but fail all others.
// Passes 'is gray when disabled', fails all others const Button = props => <button style={{ backgroundColor: "gray" }} />; // Passes 'is red when color is red', fails all others const Button = props => <button style={{ backgroundColor: "red" }} />; // Passes 'is blue when color is blue', fails all others const Button = props => <button style={{ backgroundColor: "blue" }} />; // Passes 'is gray when disabled', 'is red when color is red', fails all others const Button = props => ( <button style={{ backgroundColor: props.disabled ? "gray" : "red" }} /> );
The amount of combinations
prop-sets generates is the Cartesian product of all the values passed in (
a.length * b.length * c.length * ...), so as the amount of props grows,
prop-sets reduces your test's complexity at an exponential rate.
For example, if you have a component that only behaves a certain way if all 5 of its boolean props are true, the amount of tests you would need to write to formally assert that behavior is 32. With
prop-sets, just one!:
it("does something if all props are true, false otherwise", () => { const tf = [true, false]; propSets({ a: tf, b: tf, c: tf, d: tf, e: tf }).forEach(props => { expect(/* something */).toBe( props.a && props.b && props.c && props.d && props.e ); }); });
Use
Install
yarn add prop-sets or
npm install prop-sets
Import
import propSets from "prop-sets";
API
propSets(object)
Arguments
Return
TypeScript
prop-sets comes typed but works perfectly fine without TypeScript.
declare const propSets: < T extends Readonly<{ [key: string]: ReadonlyArray<any>; }> >( obj: T ) => { [key in keyof T]: T[key] extends (infer ElementType)[] ? ElementType : any }[];
Further reading
Why Don't People Use Formal Methods? by Hillel Wayne
Combinatorial explosion (state explosion problem)
License
[MIT](./license)
*Note that all licence references and agreements mentioned in the prop-sets README section above are relevant to that project's source code only. | https://js.libhunt.com/prop-sets-alternatives | CC-MAIN-2021-43 | refinedweb | 1,304 | 58.58 |
I built a python library and uploaded it to Databricks as a python .egg. The problem is that when uploading a new version, the old version is still imported into notebooks rather than the latest uploaded version.
These are the steps I follow to upload a new version:
import my_library print my_library.__version__ Out[1]: old_version_number
module from .egg not recognizing a module installed from another cell in the same notebook 0 Answers
How do I run a command in python egg from REST API? 1 Answer
reuse other notebook functions without uploading an egg file as library 1 Answer
importing nltk and downloding corpus 4 Answers
How do I use a newer version of a Python library that is not natively available within Databricks Cloud? 1 Answer
Databricks Inc.
160 Spear Street, 13th Floor
San Francisco, CA 94105
info@databricks.com
1-866-330-0121 | https://forums.databricks.com/questions/9549/how-to-force-databricks-to-remove-third-party-libr.html | CC-MAIN-2020-50 | refinedweb | 146 | 62.27 |
Norm.
One interesting point Norm raised is how come this glitch happened:
I think what pains me most about this situation is that XInclude was in development for just over five years. It went through eleven drafts[1] including three Candidate Recommendations.
Why didn't we notice this until several months after XInclude was a Recommendation?
615587 Support xml:base.
TrackBack URL:
It's time to update and say that finally the flag was added to .NET 2.0 and now XInclude can be used with XSD validation in .NET!!! :D
basically this seems to me to be related to xml schemas not taking into account a common extensibility methodology of xml, that being the ignoring of unknown namespaces, currently to get this functionality you need to use any at each level, you can not use it in a reasonable way with sequences, and if you do any namespace = other your extensibility model is going to be screwed up if you try to reuse this schema in a schema with another target namespace. this is one of the main and most irritating ways in which xml schema is broken, irritating in that this way of working with disparate namespaces was a very widespread strategy before xml schema was finalized.
This page contains a single entry by Oleg Tkachenko published on April 3, 2005 3:28 PM.
wbloggar site hacked? was the previous entry in this blog.
XML Indexing Article went live is the next entry in this blog.
Find recent content on the main index or look in the archives to find all content. | http://www.tkachenko.com/blog/archives/000414.html | CC-MAIN-2018-05 | refinedweb | 264 | 59.84 |
Created on 2008-09-18 22:27 by forest, last changed 2008-09-19 02:08 by josiahcarlson. This issue is now closed.
In python 2.6rc2, the async_chat.__init__() parameters have changed.
The first arg was called 'conn' in python 2.5, and it is now called
'sock'. This change breaks code that worked with previous python 2.x
versions, if that code followed the example in the official docs:
class http_request_handler(asynchat.async_chat):
def __init__(self, conn, addr, sessions, log):
asynchat.async_chat.__init__(self, conn=conn)
The change also breaks the 2.6 docs, as they have not been updated to
reflect the newly renamed parameter.
The change appears to come from Nadeem Vawda as part of issue1519. (See
msg57989.)
I expect that existing python code could be modified to work around the
problem by using positional args instead of keyword args. However, I
didn't expect to have to update my working code to accommodate such a
change in the python 2.x code line. I agree that 'sock' is a better
name for the parameter, especially since it matches the same in
asyncore.dispatcher, but should the change really happen before python
3.0? If so, let's at least update the docs.
Fixed documentation in revision 66510. Also, the parameters changed
long before rc2. ;) | https://bugs.python.org/issue3904 | CC-MAIN-2020-34 | refinedweb | 219 | 70.5 |
import "github.com/ethereum/go-ethereum/p2p/netutil"
Package netutil contains extensions to the net package.
addrutil.go error.go iptrack.go net.go toobig_notwindows.go
AddrIP gets the IP address contained in addr. It returns nil if no address is present.
CheckRelayIP reports whether an IP relayed from the given sender IP is a valid connection target.
There are four rules:
- Special network addresses are never valid. - Loopback addresses are OK if relayed by a loopback host. - LAN addresses are OK if relayed by a LAN host. - All other addresses are always acceptable.
IsLAN reports whether an IP is a local network address.
IsSpecialNetwork reports whether an IP is located in a special-use network range This includes broadcast, multicast and documentation addresses.
IsTemporaryError checks whether the given error should be considered temporary.
SameNet reports whether two IP addresses have an equal prefix of the given bit length.
type DistinctNetSet struct { Subnet uint // number of common prefix bits Limit uint // maximum number of IPs in each subnet // contains filtered or unexported fields }
DistinctNetSet tracks IPs, ensuring that at most N of them fall into the same network range.
func (s *DistinctNetSet) Add(ip net.IP) bool
Add adds an IP address to the set. It returns false (and doesn't add the IP) if the number of existing IPs in the defined range exceeds the limit.
func (s DistinctNetSet) Contains(ip net.IP) bool
Contains whether the given IP is contained in the set.
func (s DistinctNetSet) Len() int
Len returns the number of tracked IPs.
func (s *DistinctNetSet) Remove(ip net.IP)
Remove removes an IP from the set.
func (s DistinctNetSet) String() string
String implements fmt.Stringer
IPTracker predicts the external endpoint, i.e. IP address and port, of the local host based on statements made by other hosts.
NewIPTracker creates an IP tracker.
The window parameters configure the amount of past network events which are kept. The minStatements parameter enforces a minimum number of statements which must be recorded before any prediction is made. Higher values for these parameters decrease 'flapping' of predictions as network conditions change. Window duration values should typically be in the range of minutes.
AddContact records that a packet containing our endpoint information has been sent to a certain host.
AddStatement records that a certain host thinks our external endpoint is the one given.
PredictEndpoint returns the current prediction of the external endpoint.
PredictFullConeNAT checks whether the local host is behind full cone NAT. It predicts by checking whether any statement has been received from a node we didn't contact before the statement was made.
Netlist is a list of IP networks.
ParseNetlist parses a comma-separated list of CIDR masks. Whitespace and extra commas are ignored.
Add parses a CIDR mask and appends it to the list. It panics for invalid masks and is intended to be used for setting up static lists.
Contains reports whether the given IP is contained in the list.
MarshalTOML implements toml.MarshalerRec.
UnmarshalTOML implements toml.UnmarshalerRec.
Package netutil imports 8 packages (graph) and is imported by 712 packages. Updated 2019-11-22. Refresh now. Tools for package owners. | https://godoc.org/github.com/ethereum/go-ethereum/p2p/netutil | CC-MAIN-2020-29 | refinedweb | 524 | 60.01 |
Hi,
I’m working on an embedded system (Jetson Nano). I have connected a RaspiCam, and i grab frames using gstreamer and cv2.VideoCapture.
For now i have been saving images using cv2.imsave(), and open_image() to parse it into my learn.predict().
I want to avoid saving the file because it seens very inefficient. I have adapted a method from here but the predictions are not the same.
from PIL import Image as PImage from fastai.vision import * frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) pil_im = PImage.fromarray(frame) pil_im = 255-pil_im x = pil2tensor(pil_im ,np.float32) preds_num = learn.predict(Image(x))[2].numpy()
If i run:
Image(x).show()
then i see the same image as the one saved with cv2.imwrite(), but the prediction is way different. And if i run:
Image(x).save() frame = open_image()
I get a third prediction.
Does anyone know how to do this without saving the image first? | https://forums.fast.ai/t/analyzing-frames-from-opencv-cv2-videocapture/55696 | CC-MAIN-2020-05 | refinedweb | 155 | 72.12 |
Suppose you wanted to take over one or more CPUs on the system. The first
step is to establish a hog function:
#include <linux/cpuhog.h>
typedef int (*cpuhog_fn_t)(void *arg);
When hog time comes, this function will be called at the highest possible
priority. If the intent is truly to hog the CPU, the function should
probably spin in a tight loop. But one should take care to ensure that
this loop will end at some point; one does not normally want to take the
CPU out of commission permanently.
The monopolization of processors is done with any of:
int hog_one_cpu(unsigned int cpu, cpuhog_fn_t fn, void *arg);
void hog_one_cpu_nowait(unsigned int cpu, cpuhog_fn_t fn, void *arg,
struct cpuhog_work *work_buf);
int hog_cpus(const struct cpumask *cpumask, cpuhog_fn_t fn, void *arg);
int try_hog_cpus(const struct cpumask *cpumask, cpuhog_fn_t fn, void *arg);
A call to hog_one_cpu() will cause the given fn() to be
run on cpu in full hog mode; the calling process will wait until
fn() returns; at which point the return value from fn()
will be passed back. Should there be other useful work to do (on a
different CPU, one assumes), hog_one_cpu_nowait() can be called
instead; it will return immediately, while fn() may still be
running. The work_buf structure must be allocated by the caller
and be unused, but the caller need not worry about it beyond that.
Sometimes, total control over one CPU is not enough; in that case,
hog_cpus() can be called to run fn() simultaneously on
all CPUs indicated by cpumask. The try_hog_cpus()
variant is similar, but, unlike hog_cpus(), it will not wait if
somebody else got in and started hogging CPUs first.
So what might one use this mechanism for? One possibility is
stop_machine(), which is called to ensure that absolutely nothing
of interest is happening anywhere in the system for a while. Calls to
stop_machine() usually happen when fundamental changes are being
made to the system - examples include the insertion of dynamic probes,
loading of kernel modules, or the removal of CPUs. It has always worked
in the same way as the CPU hog functions do - by running a high-priority
thread on each processor.
The new stop_machine() implementation, naturally, uses
hog_cpus(). Unlike the previous implementation, though (which
used workqueues), the new code takes advantage of the CPU hog threads which
already exist. That eliminates a performance
bug reported by Dimitri Sivanich, whereby the amount of time required
to boot a system would be doubled by the extra overhead of various
stop_machine() calls.
Another use for this facility is to force all CPUs to quickly go through
the scheduler; that can be useful if the system wants to force a transition
to a new read-copy-update grace period. Formerly, this task was bundled
into the migration thread, which already runs on each CPU, in a bit of an
awkward way; now it's a straightforward CPU hog call.
The migration thread itself is also a user of the single-CPU hogging
function. This thread comes into play when the system wants to migrate a
process which is running on a given CPU. The first thing that needs to
happen is to force that process out of the CPU - a job for which the CPU
hog is well suited. Once the hog has taken over the CPU, the
just-displaced process can be moved to its new home.
The end result is the removal of a fair amount of code, a cleaned-up
migration thread implementation, and improved performance in
stop_machine().
Some concerns were raised that passing a
blocking function as a CPU hog could create problems in some situations.
But blocking in a CPU hog seems like an inherently contradictory thing to
do; one assumes that the usual response will be "don't do that". And, in fact, version 2 of the patch
disallows sleeping in hog functions. Of
course, the "don't do that" response will also apply to most uses of CPU hogs in general;
taking over processors in the kernel is still considered to be an
antisocial thing to do most of the time.
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/378859/ | CC-MAIN-2013-20 | refinedweb | 693 | 64.75 |
By default, Journalbeat reads log events from the default systemd journals. To
specify other journal files, set the
paths option in
the
journalbeat.inputs section of the
journalbeat.yml file. Each path
can be a directory path (to collect events from all journals in a directory), or
a file path. For example:
journalbeat.inputs: - paths: - "/dev/log" - "/var/log/messages/my-journal-file.journal"
Within the configuration file, you can also specify options that control how Journalbeat reads the journal files and which fields are sent to the configured output. See Configuration options for a list of available options.
The following examples show how to configure Journalbeat for some common use cases.
Example 1: Monitor multiple journals under the same directoryThis example configures Journalbeat to read from multiple journals that are
stored under the same directory. Journalbeat merges all journals under the
directory into a single event stream and reads the events. With
seek set to
cursor, Journalbeat starts reading at the beginning of the journal, but will
continue reading at the last known position after a reload or restart.
journalbeat.inputs: - paths: ["/path/to/journal/directory"] seek: cursor
Example 2: Fetch log events for Redis running on Docker (uses field names from systemd)This example configures Journalbeat to fetch log events for Redis running in a Docker container. The fields are matched using field names from the systemd journal.
journalbeat.inputs: - paths: [] include_matches: - "CONTAINER_TAG=redis" - "_COMM=redis"
Example 3: Fetch log events for Redis running on Docker (uses translated field names)This example also configures Journalbeat to fetch log events for Redis running in a Docker container. However, in this example the fields are matched using the translated field names provided by Journalbeat.
journalbeat.inputs: - paths: [] include_matches: - "container.image.tag=redis" - "process.name=redis"
Configuration optionsedit
You can specify the following options to configure how Journalbeat reads the journal files.
idedit
An optional unique identifier for the input. By providing a unique
id you can
operate multiple inputs on the same journal. This allows each input’s cursor
to be persisted independently in the registry file.
{beatname_lc}.inputs: - id: consul.service paths: [] include_matches: - _SYSTEMD_UNIT=consul.service - id: vault.service paths: [] include_matches: - _SYSTEMD_UNIT=vault.service
pathsedit
A list of paths that will be crawled and fetched. Each path can be a directory path (to collect events from all journals in a directory), or a file path. If you specify a directory, Journalbeat merges all journals under the directory into a single journal and reads them.
If no paths are specified, Journal, Journalbeat resends all log messages in the journal.
tail: Starts reading at the end of the journal. After a restart, Journalbeat resends the last message, which might result in duplicates. If multiple log messages are written to a journal while Journalbeat is down, only the last log message is sent on restart.
cursor: On first read, starts reading at the beginning of the journal. After a reload or restart, continues reading at the last known position.
When specified under
paths, the
seek setting applies to all journals under
the configured paths. When specified directly under the
journalbeat
namespace, the setting applies to all journals read by Journalbeat.
If you have old log files and want to skip lines, start Journalbeat with
seek: tail specified. Then stop Journalbeat, set
seek: cursor, and restart
Journalbeat.
include_matchesedit
A list of filter expressions used to match fields. The format of the expression
is
field=value. Journalbeat fetches all events that exactly match the
expressions. Pattern matching is not supported.
To reference fields, use one of the following:
- The field name used by the systemd journal. For example,
CONTAINER_TAG=redis(see a full example).
- The translated field name used by Journalbeat. For example,
container.image.tag=redis(see a full example). Journalbeat does not translate all fields from the journal. For custom fields, use the name specified in the systemd journal.
When specified under
paths, the
include_matches filter is applied to all
journals under the configured paths. When specified directly under the
journalbeat namespace, the setting applies to all journals read by
Journalbeat.
Translated field namesedit
You can use the following translated names in filter expressions to reference journald fields:
The following translated fields for Docker are also available:
"journalbeat-myindex-2019.12.13". | https://www.elastic.co/guide/en/beats/journalbeat/master/configuration-journalbeat-options.html | CC-MAIN-2021-39 | refinedweb | 710 | 50.02 |
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.
Martin Sebor <sebor@roguewave.com> writes: | Matt Austern wrote: | | > On Monday, July 14, 2003, at 05:02 PM, Doug Gregor wrote: | > | ... | > Stupid question: is there any other place in the compiler where we change | > the behavior of the driver based on whether the user defines a special | > macro? | > If so, if we're just carrying on with something we've done already, | > then | > I don't have a problem with this. If not, then I'm a bit uncomfortable | > with it. -D is documented to define a macro. Having it do other things | > as well, for special macros, strikes me as non-obvious. | | FWIW, the MSVC #pragma comment feature allows program source | to embed commands for the linker in the object file, so there | is existing practice for this non-obvious feature. E.g., | | #ifdef FOO | # pragma comment (lib,libfoo) | #else | # pragma comment (lib,libbar) | #endif I'm not really found of the idea of having pragmas (or any CPP hack) silently change portions of program semantics. I believe in compiler switch controlling whole translation units (or better the whole program) for that purpose. -- Gaby | https://gcc.gnu.org/ml/libstdc++/2003-07/msg00298.html | CC-MAIN-2019-47 | refinedweb | 202 | 64.2 |
setlinebuf
Stream buffering operations <span class="Dv">stdin</span>). The function reference:fflush may be used to force the block out early. See also fclose. Normally all files are block buffered. When the first <span class="Tn">I/O</span> operation occurs on a file, reference:malloc is called, and an optimally-sized buffer is obtained. If a stream refers to a terminal (as <span class="Dv">stdout</span> normally does) it is line buffered. The standard error stream <span class="Dv">stderr</span> is always unbuffered. The code below creates a buffered stream and writes some text to it.
Example 1
#include <stdio.h> int main() { FILE *f = fopen("fred.txt", "wt"); // make f a buffered stream char buffer[100]; setbuf(f, buffer); // write some data to the buffer fputs("blar blar blar", f); // flush the buffer into the stream // (no data is written to the file until the first call to fflush) fflush(f); fclose(f); return 0; }The setvbuf function may be used to alter the buffering behavior of a stream. The
modeargument must be one of the following three macros: <table cellspacing="0" class="refpage" style="margin-left:25px"> <tr> <td valign="top" nowrap> <span class="Dv">_IONBF</span> </td> <td valign="top"> unbuffered </td> </tr> <tr> <td valign="top" nowrap> <span class="Dv">_IOLBF</span> </td> <td valign="top"> line buffered </td> </tr> <tr> <td valign="top" nowrap> <span class="Dv">_IOFBF</span> </td> <td valign="top"> fully buffered </td> </tr> </table> The
sizeargument may be given as zero to obtain deferred optimal-size buffer allocation as usual. If it is not zero, then except for unbuffered files, the
bufargument should point to a buffer at least ;c size bytes long; this buffer will be used instead of the current buffer. If
bufis not NULL, it is the caller's responsibility to free this buffer after closing the stream. (If the
sizeargument is not zero but
bufis <span class="Dv">NULL</span>, a buffer of the given size will be allocated immediately, and released on close. This is an extension to ANSI C; portable code should use a size of 0 with any <span class="Dv">NULL</span> buffer.) The setvbuf function may be used at any time, but may have peculiar side effects (such as discarding input or flushing output) if the stream is 'active'. Portable applications should call it only once on any given stream, and before any <span class="Tn">I/O</span> <span class="Dv">BUFSIZ</span>. The setlinebuf function is exactly equivalent to the call:
setvbuf(stream, (char *)NULL, _IOLBF, 0); | http://www.codecogs.com/library/computing/c/stdio.h/setbuf.php?alias=setlinebuf | CC-MAIN-2018-34 | refinedweb | 431 | 60.14 |
How to Use Python Pointers
Have you ever worked in programming languages like C++ or C?
If yes, you would have definitely come across the term
pointers.
Every variable has a corresponding memory location and every memory location has a corresponding address defined for it. Pointers store the address of other variables.
Surprisingly, pointers don't really exist in Python. If that is the case, what am I writing about here?
Everything is an object in Python. In this article, we will look at the object model of Python and see how we can fake pointers in Python.
Table of Contents:
You can skip to any specific section of this Python pointers tutorial using the table of contents below.
- Why Don’t Pointers Exist in Python?
- Variables in C vs Variables in Python
- Pointer Behavior in Python
- Pointers Using ctypes
- Final Thoughts
Why Don’t Pointers Exist in Python?
Nobody knows why pointers don't exist in Python.
Yes, you read that right…
The reason is unknown.
Even in basic programming languages like C and C++, pointers are considered complex.
This complexity is against the Zen of Python and this could be the reason why Python doesn't speak about why it doesn’t include pointers.
Said differently, the objective of Python is to keep things simple. Pointers aren’t considered simple.
Though the concept of pointers is alien to Python, the same objective can be met with the help of objects. Before we discuss further on this, let us first understand the role of objects in Python.
What are Objects?
Everything is an object in Python.
If you are just getting started with Python, use any REPL and explore the
isinstance() method to understand this.
More specifically, the following code proves that the
int,
str,
list, and
bool data types are each objects in Python.
print(isinstance(int, object)) print(isinstance(str, object)) print(isinstance(list, object)) print(isinstance(bool, object))
Output:
True True True True
This proves that everything in Python is an object.
So what is an object?
A Python object comprises of three parts:
- Reference count
- Type
- Value
Reference count is the number of variables that refer to a particular memory location.
Type refers to the object type. Examples of Python types include
int,
float,
string, and
boolean.
Value is the actual value of the object that is stored in the memory.
Objects in Python are of two types – Immutable and Mutable.
It is important to understand the difference between immutable and mutable objects to implement pointer behavior in Python.
Let's first segregate the data types in Python into immutable and mutable objects.
Immutable objects cannot be changed post creation. In the above table, you can see that data types that are commonly used in Python are all immutable objects. Let's look at the below example.
x = 34 y = id(x) print(y)
When you run this script in your REPL environment, you will get the memory address of value.
Output:
94562650443584
Now, let's modify the value of x and see what happens. The value of x in the memory 94562650443584 is 34 and that cannot be changed. If we alter the value of x, it will create a new object.
x = 34 y = id(x) print(y) x += 1 y= id(x) print(y)
Output:
94169658712736
94169658712768
Use the is() to verify if two objects share the same memory address. Let's look at an example.
x = y x is y
If the output is true, it indicates that x and y share the same memory address.
Mutable objects can be edited even after creation. Unlike in immutable objects, no new object is created when a mutable object is modified. Let's use the list object that is a mutable object.
numbs = [1, 1, 2, 3, 5] print("---------Before Modification------------") print(id(numbs)) print() ## element modification numbs[0] += 1 print("-----------After Element Modification-------------") print(id(numbs)) print()
Output:
---------Before Modification------------ 140469873815424
-----------After Element Modification------------- 140469873815424
Note that the address of the object remains the same even after performing an operation on the list.
This happens because list is a mutable object. The same concept applies to other mutable objects like
dict or
set mentioned in the table presented earlier in this tutorial.
Now that we have understood the difference between mutable and immutable objects, let us look at Python's object model.
Variables in C vs Variables in Python
Variables in Python are very different from those in C or C++.
More specifically, Python doesn't have variables. They are called names instead. To understand how variables in Python differ from that in fundamental programming languages like C and C++, let's look at an example.
First, let's define a variable in C.
int v = 10;
What does the above code actually do?
This single line of code:
- Allocates a memory for the defined data type, which in this case is
int
- Allocates a value
10to the memory location, say
0x5f3
- Indicates that the variable
vtakes the value
10
In C, if you want to change the value of v at a later point, you can do this.
int v = 20;
Now, the value 20 is allocated to the memory location
0x5f3. Since the variable v is a mutable object, the location of the variable did not change though the value of it changed. That is, the
v defined here is not just the name of the variable but also its memory location.
Now, let's assign the value of v to a new variable.
int new = v;
A new variable new is now created with the value 20 but this variable will have its own memory location and will not take the memory location of the variable whose value it copied.
In Python, names work in a contrasting way than what we just saw.
Let’s rewrite the Python equivalent of the above code to see this principle in action.
v = 10
This single line of code:
- Creates a new Python object
- Sets the data type for the Python object as integer
- Assigns a value 10 to the PyObject
- Creates a name
v
- Points
vto the newly created PyObject
- Increases the refcount of the newly created Python object by 1
Let's visualize and make our understanding simple.
Unlike in C, a new object is created and that objects owns the memory location of the variable.
The name defined
v, does now own any memory location.
Now let's assign a different value to
v.
int v = 20
Let's see what happens here:
- First this creates a new PyObject
- Sets the data type for the PyObject as integer
- Assigns a value 20 to the PyObject
- Points v to the newly created PyObject
- Increases the refcount of the newly created PyObject by 1
- Decreases the refcount of the already existing PyObject by 1
The variable name
v now points to the newly created object. The first object which had a value
10 now has a refcount equal to zero. This will be cleaned by the garbage collector.
Let's now assign the value of
v to a new variable.
int new = v
In Python, this creates a new name and not a new object.
You can validate this by using the below script.
new is x
The output will be true. Note that
new is still an immutable object. You can perform any operation on
new and it will create a new object.
Pointer Behavior in Python
Now that we have a fair understanding of what mutable objects are let us see how we can use this object behavior to simulate pointers in Python. We will also discuss how we can use custom Python objects.
Using Mutable Object:
We can treat mutable objects like pointers. Let's see how to replicate the below C code in Python.
#include <stdio.h> void add(int *a) { *a += 10; } void main() { int v = 10; printf("%d\n", v); add(&v); // to extract the address of the variable printf("%d\n", v); }
In the above code,
v is assigned with a value
10. The current value is printed and then the value of
v is increased by 10 before printing the new value. The output of this code would be:
v = 10 v = 20
Let's duplicate this behavior in Python using a mutable object. We will use a list and modify the first element of the list.
def add(v): v[0] += 1 new = [10] add(v) v[0]
Output:
20
Here,
add() increments the first elements value by one. So, does this mean pointers are present in Python? No! This was possible because we used a mutable type, list. Try the same code using tuple. You will get an error.
new = (10,) add(new)
Output:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in add_one TypeError: 'tuple' object does not support item assignment
This is because tuple is an immutable type. Try using other mutable objects to get similar desired output. It is important to understand that we are only faking pointer behavior using mutable objects.
Pointers Using ctypes
We can create real pointers in Python using the built in
ctype modules. To start, store your functions that use pointers in a
.c file and compile it.
Write the below function into your
.c file.
void add(int *a) { *a += 10; }
Assume our file name is
pointers.c. Run the below commands.
$ gcc -c -Wall -Werror -fpic pointers.c $ gcc -shared -o libpointers.so pointers.o
In the first command,
pointers.c is compiled to an object
pointers.o. Then, this object file is taken to produce
*libpointers.so to work with
ctypes.
import ctypes ## libpointers.so must be present in the same directory as this program lib = ctypes.CDLL("./libpointers.so") lib.pointers
Output:
<_FuncPtr object at 0x7f23bf4e3561>
ctypes.CDLL returns the shared object
libpointers.so. Let us define
add() function in the
libinc.so shared object. We have to use ctypes to pass a pointer to the functions defined in a shared object.
add = lib.pointers ## define argtypes add.argtypes = [ctypes.POINTER(ctypes.c\_add)]
We will get an error if we try calling this function using a different type.
add(10)
Output:
Traceback (most recent call last): File "<stdin>", line 1, in <module> ctypes.ArgumentError: argument 1: <class 'TypeError'>: expected LP_c_int instance instead of in
The error states that a pointer is required by the function. You must use a C variable in ctypes to pass the variable reference.
v = ctypes.c_add(10) add(ctypes.byref(v)) v
Here
v is the C variable and
byref passes the variable reference.
Output:
c_add(20)
Final Thoughts
As we saw in this tutorial, pointer behavior can be implemented in Python though they are technically not available in the Python language.
While we used mutable objects to simulate pointer behavior, the ctype pointers are real pointers. | https://nickmccullum.com/python-pointers/ | CC-MAIN-2020-29 | refinedweb | 1,821 | 65.12 |
World Expo 2003
World Expo 2003
Trading Connection would like to thank everyone for stopping by our booth at the World Expo in Las Vegas. It sure was a pleasure to meet everyone from the industry and especially for myself Tony Zulmai since it was my first time attending the World Expo. I hope it was a great success for everyone as much as it was for us, can’t wait to see all of you again next year at the World Expo 2004.
< ?xml:namespace prefix = o
We are always looking to Buy & Sell empty toner and inkjet cartridges, so if you are looking to Buy empties or if you are looking to Sell empties then Trading Connection is your answer. We carry a wide selection of some of the most popular models in HP, Canon, Lexmark, IBM, Xerox, and many more both in virgin and non-virgin.
Let us never negotiate out of fear. But let us never fear to negotiate.
*** LET US BE PART OF YOUR SUCCESS ***
Best Regards,
Tony Zulmai | https://tonernews.com/forums/topic/webcontent-archived-1019/ | CC-MAIN-2017-30 | refinedweb | 174 | 66.67 |
This is a candidate entry for The Code Project's Lean and Mean competition to write an efficient text delta tool.
I was checking my emails while on vacation and I came across a Code Project daily mailing with a reminder for the LCS competition. I have enjoyed reading The Code Project articles for many years now, but until this moment I never had the opportunity to contribute.
When I first started with C# I decided to write a diff program in order to really learn the language. I call this program, DeltaScope. What started out as a simple console-based diff tool has gone through many iterations. When I finally stopped work on it, I had a reusable delta engine with GDI+ front-end controls.
Unfortunately, I have not touched this code since 2005. Thankfully my fiancé is very understanding of my “coding time” and I was able to take some time to write this article and bring the code up to C# 3.0 specifications.
Many of the entries have excellent explanations of the LCS algorithm. When I wrote my DeltaScope I referred to this paper extensively.[^]
I find the best way to understand the LCS algorithm, is to think of it like this: The output of a delta operation is a sequence of instructions to transform file 1 into file 2.
The core of the system is the DeltaEngine class. The DeltaScope application wraps up the engine in the DeltaScopeEngine class.
public class DeltaScopeEngine
{
public bool IgnoreCase { get; set; }
public bool IgnoreTabs { get; set; }
public TimeSpan ElapsedTime { get; private set; }
public long PeakMemoryUsage { get; private set; }
public List<DeltaBlock> Compare(string tsLeftFile, string tsRightFile)
{
var process = Process.GetCurrentProcess();
process.Refresh();
var peakWorkingSet64 = process.PeakWorkingSet64;
var timer = DateTime.Now;
var deltaEngine = new DeltaEngine();
var result = deltaEngine.GetDifferences(RipFile(tsLeftFile),
RipFile(tsRightFile), hashSideDelegate);
ElapsedTime = DateTime.Now - timer;
PeakMemoryUsage = process.PeakWorkingSet64 - peakWorkingSet64;
return result;
}
private static string RipFile(string tsFileName)
{
...
}
private List<DeltaString> hashSideDelegate(string sideValues)
{
const string blockLineTerminator = @"\r\n";
var values = new List<string>(Regex.Split(sideValues, blockLineTerminator));
var results = new List<DeltaString>();
for (var lnCnt = 0; lnCnt < values.Count; lnCnt++)
{
var lnHashCode = _GenerateHashFromString(values[lnCnt]);
if (lnHashCode >= 0)
results.Add(new DeltaString(values[lnCnt], lnHashCode));
}
return results;
}
private int _GenerateHashFromString(string tsLine)
{
var lnHash = 0;
var lnRealPtr = 0;
// Handle the upper casing issue...
var lcaLine = IgnoreCase ?
tsLine.ToUpper().ToCharArray() : tsLine.ToCharArray();
// hash_string(ABCW) = 65*1 + 66*2 + 67*3 + 87*4
var lnMaxLength = lcaLine.Length;
for (var lnCnt = 0; lnCnt < lnMaxLength; lnCnt++)
{
// Handle the white space characters...
if (lcaLine[lnCnt] == '\t' && IgnoreTabs)
continue;
lnRealPtr++;
lnHash += ((byte)lcaLine[lnCnt] * lnRealPtr);
}
// return the hash value...
return (lnHash);
}
}
The hashAlgorithm delegate lets the developer control how each string is parsed into a list of DeltaStrings. In this simple example we can choose to make the difference case sensative or case insensative, and we can choose to ignore tab characters.
The average run timing is 13ms. I do not include any screen rendering in my timings. As for memory consumption, I always come up with 0 memory used. Which means I am either not using process.PeakWorkingSet64 correctly, or my code is magical. ;)
process.PeakWorkingSet64
Many diff tools allow the user to merge the 2 files into 1 new file. With the list of delta blocks that the DeltaEngine generates, it should be possible to allow the user to build a new file. This would require some sort of block choosing ability along with perhaps text editing. Unfortunately the current GDI+ controls are display only.
When I initially wrote this, GDI+ was a pretty new technology, and WPF did not yet exist. I think a good next step would be to use WPF as the display technology for the display. With WPF the swirl block control can be rewritten to include editing abilities.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
public List<DeltaBlock> Compare(string tsLeftFile, string tsRightFile) {
GC.Collect();
var process = Process.GetCurrentProcess();
process.Refresh();
var peakWorkingSet64 = process.PeakWorkingSet64;
Stopwatch sw=new Stopwatch();
sw.Start();
//var timer = DateTime.Now;
var deltaEngine = new DeltaEngine();
var result = deltaEngine.GetDifferences(RipFile(tsLeftFile), RipFile(tsRightFile), hashSideDelegate);
//ElapsedTime = DateTime.Now - timer;
sw.Stop();
ElapsedTime = sw.Elapsed;
process.Refresh();
PeakMemoryUsage = process.PeakWorkingSet64 - peakWorkingSet64;
return result;
}
private static readonly StringBuilder sb = new StringBuilder(64000);
private static readonly StringBuilder sb = new StringBuilder();
private List<DeltaString> hashSideDelegate(string sideValues)
{
var values = sideValues.Split(new [] {"\r\n"}, StringSplitOptions.None);
var results = new List<DeltaString>();
for (var lnCnt = 0; lnCnt < values.Length; lnCnt++)
results.Add(new DeltaString(values[lnCnt]));
return results;
}
/[_LLineCnt].ToString());
// Add any remaining right lines...
for (var lnCnt = _RLineCnt; lnCnt <= _MaxRLine; lnCnt++)
block.Right.Add(Right[_RLineCnt].ToString());
}
/[lnCnt].ToString());
// Add any remaining right lines...
for (var lnCnt = _RLineCnt; lnCnt <= _MaxRLine; lnCnt++)
block.Right.Add(Right[lnCnt].ToString());
}
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Articles/42007/DeltaScope?fid=1548697&df=10000&mpp=50&noise=1&prof=True&sort=Position&view=None&spc=Relaxed | CC-MAIN-2018-05 | refinedweb | 832 | 51.14 |
Hello to all the Java Gurus....Please help!
I am very close to completing this assignment and I can not figure out what I am doing wrong. The output is suppose to be my 3 initials(Capitalized) and then a 2 digit random number after the initials. my output is giving me 2 digits after each initial. Can some one please help me. OUTPUT is suppose to look like this......DES34.
import java.util.Random;
import java.util.Scanner;
import java.lang.String;
public class UserID
{
public static void main(String args[]) {
Scanner login = new Scanner(System.in);
System.out.println("Enter your full Name: ");
String Fullname = login.nextLine();
Fullname = (Fullname).toUpperCase();
String[] splits = Fullname.split(" ");
for(String Fname: splits){;
char Finame = Fname.charAt(0);
char endname = Finame;
Random r = new Random();
String userid = "";
for (int i = 10; i < 90;++i){
int rand = r.nextInt(1) + 90;
userid = String.valueOf(rand);}
String User = ("" + endname + userid);
System.out.print(User);
}
}
}
Output:
Enter your full Name:
dan eben stevens
D90E90S90
Last edited by dstevens; January 20th, 2013 at 06:43 PM.
Reason: Misspelling
View Tag Cloud
Forum Rules | http://forums.codeguru.com/showthread.php?533459-point-me-in-the-right-direction-would-be-very-helpful-Java-HELP-PLEASE&p=2101693&mode=threaded | CC-MAIN-2013-48 | refinedweb | 186 | 62.64 |
Further auto-completion testing on wing in debug mode for aiida package.
Hi,
This is some further tests for using wing to give auto-completion suggestions for aiida package in debug mode.
For testing it, you should still from within virtualbox vm described here:...
from aiida import load_profile load_profile() from aiida.orm import load_node node=load_node('be52abbf-8e3a-4e64-afc0-cb6fd471ad94') for i in dir(node.inputs): if not i.startswith('_'): print(i)
The above code snippet should gives the following output:
code kpoints parameters parent_folder pseudos__As pseudos__Ga structure
But when I enable the debug mode, I cannot find auto-completions for them. For example, when I input
node.inputs.c<tab>, wing won't give
code as one of the candidates.
Any hints for this problem?
Regards
I haven't been able to reproduce (downloading the virtualbox image is taking hours), but could you try checking Allow Calls in Data Inspection on the Debugger: Data Inspection page of the Preferences dialog? This will allow __dir__() methods to be called when getting symbols for autocomplete lists. It's off by default because a __dir__() method could potentially be buggy and you don't want the debugger displaying incorrect info when you're trying to debug something.
Try this directly in the host's aiida without using virtualbox vm:
$ curl -L '' -o arithmetic.add.aiida
$ verdi import arithmetic.add.aiida
For test, revise the code snippet given by me as following:
change
node=load_node('be52abbf-8e3a-4e64-afc0-cb6fd471ad94')
to
node= load_node('9d3fda4f-6782-4441-a276-b8965aa3f97f')
Side note, I've enable the preference
Allow Calls in Data Inspection, but has no effect on this problem. Another note, I also noted that even in ipython, it also not gives suggestions on these names.
Did you try changing your Allow Calls in Data Inspection preference? I think there's a good chance that it will fix your problem. I did get the image to download and will be looking at it tomorrow.
I unchecked the preference
Allow Calls in Data Inspection, now only the names begin with
_are suggested. But it's obviously then I don't want these at all. I want to obtain the suggestions starting without
_. | https://ask.wingware.com/question/1892/further-auto-completion-testing-on-wing-in-debug-mode-for-aiida-package/ | CC-MAIN-2021-17 | refinedweb | 369 | 57.06 |
is not a useful metric, so even if Celery did consist of 50k lines of code you would is also the library that enables us to support many different message brokers. It is also used by the OpenStack project, and many others, validating the choice to separate it from the Celery codebase.
Billiard is a fork of the Python multiprocessing module containing many performance and stability improvements. It is an eventual goal that these improvements will be merged back into Python one day.
It is also used for compatibility with older Python versions that
Kombu depends on the following packages:
The underlying pure-Python amqp client implementation. AMQP being the default broker this is a natural dependency.
anyjson is an utility library to select the best possible JSON implementation.
Note
For compatibility reasons additional packages may be installed
if you are running on older Python versions,
for example Python 2.6 depends on the
importlib,
and
ordereddict libraries.
Also, to handle the dependencies for popular configuration choices Celery defines a number of “bundle” packages, see Bundles.
Is Celery heavy-weight?¶
Celery poses very little overhead both in memory footprint and performance.
But please note that the default configuration is not optimized for time nor space, see the Optimizing guide for more information.
Is Celery dependent on pickle?¶
Answer: No.
Celery can support any serialization scheme and has built-in support for JSON, YAML, Pickle and msgpack. Also, as every task is associated with a content type, you can even send one task using pickle, and another using JSON.
The default serialization format is pickle simply because it is convenient (it supports sending complex Python objects as task arguments).
If you need to communicate with other languages you should change to a serialization format that is suitable for. There are also experimental transports available such as MongoDB, Beanstalk, CouchDB, or using SQL databases. See Brokers for more information.
The experimental transports may have reliability problems and limited broadcast and event functionality. For example remote control commands only works with AMQP and Redis.
Redis or a database won’t perform as well as an AMQP broker. If you have strict reliability requirements you are encouraged to use RabbitMQ or another AMQP broker. Some transports also uses polling, so they are likely to consume more resources. However, if you for some reason are is to use REST tasks, instead of your tasks being functions, they’re URLs. With this information you can even create simple web servers that enable preloading of code. See: User Guide: Remote which 'atically:
>>>
worker with the
--purge argument, to purge messages when the worker starts.
I’ve purged messages, but there are still messages left in the queue?¶
Answer: Tasks are acknowledged (removed from the queue) as soon
as they are actually executed. After the worker has received a task, it will
take some time until it is actually executed, especially if there are a lot
of tasks already waiting for execution. Messages that are: Yes, indeed it is.
You are right to have a security concern, as this can indeed be a real issue. It is essential that you protect against unauthorized access to your broker, databases and other services transmitting pickled data.
For the task messages you can set the
CELERY_TASK_SERIALIZER
setting to “json” or “yaml” instead of pickle. There is
currently no alternative solution for task results (but writing a
custom result backend using JSON is a simple task)
Note that this is not just something you should be aware of with Celery, for example also Django uses pickle for its cache client.
Can messages be encrypted?¶
Answer: Some AMQP brokers supports using SSL (including RabbitMQ).
You can enable this using the
BROKER_USE_SSL setting.
It is very important that you are aware of the common pitfalls.
- Events.
Running
worker with the
-E/
--events.
Results expire after 1 day by default. It may be a good idea
to lower this value by configuring the
CELERY_TASK_RESULT_EXPIRES
setting.
If you don’t use the results for a task, make sure you set the ignore_result option:
Can I use Celery with ActiveMQ/STOMP?¶
Answer: No. It used to be supported by Carrot, but is not currently supported in Kombu.
What features are is a sudo configuration option that makes it illegal for process without a tty to run sudo:
Defaults requiretty
If you have this configuration in your
/etc/sudoers file then
tasks will not be able to call sudo when the worker is running as a daemon.
If you want to enable that, then you need to remove the line from sudoers.
See:
Why do workers delete tasks from the queue if they are unable to process them?¶
Answer:
The worker rejects unknown tasks, messages with encoding errors and messages that don’t contain the proper fields (as per the task message protocol).
If it did
Answer: You can safely launch a task inside a task. Also,flows for more information.
Answer: To receive broadcast remote control commands, every worker node uses its host name to create a unique queue name to listen to, so responsive system.
Should I use retry or acks_late?¶ acknowledged! is acknowledgement).().
Or to schedule a periodic task at a specific time, use the
celery.schedules.crontab schedule behavior:
from celery.schedules import crontab from celery.task import periodic_task @periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon")) def every_monday_morning(): print("This is run every Monday morning at 7:30")
How can I safely shut down the worker?¶
Answer: Use the
TERM signal, and the worker will finish all currently
executing jobs and shut down as soon as possible. No tasks should be lost.
You should never stop
worker with the
KILL signal
(
-9), unless you’ve tried
TERM a few times and waited a few
minutes to let it get a chance to shut down., there are also several other helper tables (
IntervalSchedule,
CrontabSchedule,
PeriodicTasks).
Task results
The database result backend is enabled by default when using django-celery (this is for historical reasons, and thus for backward compatibility).
The results are stored in the
TaskMetaand
TaskSetMetamodels. these tables are not created if another result backend is configured.
Windows¶
The -B / –beat option to worker doesn’t work?¶
Answer: That’s right. Run celery beat and celery worker as separate services instead. | http://celery.readthedocs.org/en/latest/faq.html | CC-MAIN-2015-32 | refinedweb | 1,049 | 56.05 |
$ cnpm install codebase-npm
A NodeJS library for the CodebaseHQ API
This library creates objects for users, projects, tickets etc. When you make a query to retrieve tickets (this is just an example, it can apply to other classes too) it will attempt to look up the users and link the ticket assignee/reporter with the user. If you haven't already retrieved users then your ticket will have no assignee or reporter assigned to it. Because of this, the best steps to take are:
Instructions for each of these steps can be found below.
There is also an examples project with some demos to help understand the code and how it functions. This can be found here.
In order to connect to and query the codebase API you need to create a CodebaseHQAccount object
import { codebase } from 'codebase-npm'; let codebaseConnection = new codebase(apiUser, apiKey, apiHostname);
Users are pulled at the account level
let users = await codebaseConnection.users();
This returns a
UserCollection - searching should be done on the collection, the class has a few helper methods for this. This is also built from the library 'collectionsjs' which can be found here.
Projects can be pulled as a whole for the account, or individually by permalink. Projects are populated with all of their categories, priorities, statuses and types.
Projects are also pulled at the account level
let projects = await codebaseConnection.projects();
This returns a
ProjectCollection - searching should be done on the collection, the class has a few helper methods for this again this is extended from the CollectionsJS node module.
You can pull an individual project by the permalink (note the method name is singular)
let project = await codebaseConnection.project('project-permalink');
This returns a
Project model - not a collection
Tickets can only be retrieved if you have a
Project object.
await codebaseConnection.tickets(project, pageNo); project.getTickets();
The tickets method returns a boolean indicating whether there are further results (as the results are paginated). The tickets themselves are added to a
TicketCollection in the project. As always, searching should be done on the collection, the class has a few helper methods for this
Tickets are paginated, with 20 per page. You can write a simple loop to pull all tickets for the project
let pageNo = 1; let moreResultsToRetrieve = true; while (moreResultsToRetrieve) { moreResultsToRetrieve = await codebaseConnection.tickets(project, pageNo); pageNo++; }
Time Sessions can only be retrieved if you have a
Project object. You must also pass through a period to retrieve the times for, this can be a day/week/month or all - classes exist for each one.
// can be All|Day|Week|Month import {All, Day, Week, Month} from 'codebase' await codebaseConnection.times(project, new Week());
Time sessions will be associated with the project, the ticket and the user if you have populated those collections.
// times for the project project.getTimeSessions(); // times associated to a user user.getTimeSessions(); // times associated to a ticket ticket.getTimeSessions(); | https://developer.aliyun.com/mirror/npm/package/codebase-npm/v/1.0.3 | CC-MAIN-2020-29 | refinedweb | 485 | 54.22 |
Greg Ewing wrote: > Ron Adam wrote: > >> I'm still not sure why "__round__" should be preferred in place of >> "round" as a method name. There isn't an operator associated to >> rounding so wouldn't the method name not have underscores? > > I was thinking there would be functions such as round(), > trunc(), etc. that use __round__ to do their work. That's > why I called it a protocol and not just a method. > > -- > Greg I understood your point. :-) If you look at the methods in int, long, and float, there are no methods that do not have double underscores. While there are many that don't in unicode and string. There also are many methods in Decimal that do not use the double underscore naming convention. I am just curious why not in general for the builtin numeric types. The style guide says... > - __double_leading_and_trailing_underscore__: "magic" objects or > attributes that live in user-controlled namespaces. E.g. __init__, > __import__ or __file__. Never invent such names; only use them > as documented. So would __round__ interact with the interpreter in some "magic" way? I take "magic" to mean the interpreter calls the method directly at times without having python coded instructions to do so. Such as when we create an object from a class and __init__ gets called by the interpreter directly. The same goes for methods like __add__ and __repr__, etc.... Cheers, Ron | https://mail.python.org/pipermail/python-3000/2006-August/002755.html | CC-MAIN-2019-35 | refinedweb | 231 | 75.81 |
Amazon Route 53 Metrics and Dimensions
When you create a health check, Amazon Route 53 starts to send metrics and dimensions once a minute to CloudWatch about the resource that you specify. The Route 53 console lets you view the status of your health checks. You can also use the following procedures to view the metrics in the CloudWatch console or view them by using the AWS Command Line Interface (AWS CLI).
To view metrics using the CloudWatch console
Open the CloudWatch console at.
In the navigation pane, choose Metrics.
On the All Metrics tab, choose Route 53.
Choose Health Check Metrics.
To view metrics using the AWS CLI
At a command prompt, use the following command:
aws cloudwatch list-metrics --namespace "AWS/Route53"
Route 53 Metrics
The
AWS/Route53 namespace includes the following metrics.
Dimensions for Route 53 Metrics
Route 53 metrics use the
AWS/Route53 namespace and provide metrics for
HealthCheckId. When retrieving metrics,
you must supply the
HealthCheckId dimension.
In addition, for
ConnectionTime,
SSLHandshakeTime, and
TimeToFirstByte, you can optionally
specify
Region. If you omit
Region, CloudWatch returns metrics across all regions. If you include
Region,
CloudWatch returns metrics only for the specified region.
For more information, see Monitoring Health Checks Using CloudWatch in the Amazon Route 53 Developer Guide. | https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/metrics_dimensions.html | CC-MAIN-2018-17 | refinedweb | 212 | 64.81 |
WPF is great--really. NHibernate is great, too. But they don't like each other—at all. At a recent Microsoft training class, the instructor was asked a question about using WPF with NHibernate. His response was “Yeah—good luck making that work!” Well, in this article, we're going to provide you with the skills and tools to make it work, and to make it easy to do so.
One of the greatest things about WPF is its data-binding capabilities. I don't know if WPF is actually Rev. 3 of data-binding, but Microsoft finally got it right. But to use WPF data-binding, you need to set up your domain model just so. Individual properties need to implement the PropertyChanged event, and collections need to raise the CollectionChanged event. That seems like a fairly harmless requirement, but developers who use Domain-Driven Design (DDD) hate it. You see, to a DDD developer, WPF pollutes the domain model and destroys Separation of Concerns. From a DDD purist’s point of view, WPF is just another bad Microsoft technology.
PropertyChanged
CollectionChanged
NHibernate really hates the collection constraint. While the preferred collection type for WPF is ObservableCollection<T>, NHibernate absolutely requires that domain collections be of type IList<T> (or IESI.ISet<T>), which provide no change notification whatsoever. If you use NHibernate as your ORM, the conventional wisdom has said that you are pretty much locked out of WPF, at least until now.
ObservableCollection<T>
IList<T>
IESI.ISet<T>
So, how do we make WPF and NHibernate play nice together? And, how do we make WPF palatable to DDD developers? DDD purists offer this approach: Wrap domain model objects that you want to expose in your view—wrap them in view model wrappers (VM wrappers), classes that provide the functionality that WPF requires. Now, that sounds straightforward enough. But if you have ever tried to actually do this, you know what a mind-numbing, stultifying, time-consuming chore this task can be. The rest of you, just think of dental work.
This article demonstrates a toolkit that gets everyone to play nice together, and makes the task of creating VM wrapper classes almost trivial. The heart of the toolkit is VM Wrapper Express 2.0, a utility that generates wrapper classes in the blink of an eye. The article also includes a demo app, VM Collection Demo, that shows how the wrapper classes work, and how to use them in your own applications.
VM Wrapper Express has been updated since the original version of this article. The changes from Version 1.0 to Version 2.0 are discussed in the body of the article. But let’s start with some background first—a look at the Separation of Concerns issues presented by the combination of NHibernate and WPF.
VM Wrapper Express has been updated to Version 2.1. While using the application, I discovered that the WPF DataGrid became uneditable when I used it with wrapper classes generated by VMWE. Version 2.1 fixes the problem; I discuss the problem and the fix below.
DataGrid
VM Wrapper Express has an installer project. If you simply want to install the program, you can find the installer in the SetupVmWrapperExpress\bin\Release folder.
The principle of Separation of Concerns says that a class should do one thing and do it well. View classes should be concerned with the view, data access classes should be concerned with data access, and the domain model should be concerned with modelling the problem domain. The domain model shouldn't concern itself with either data access or display—to the extent we have to bend the domain model out of shape to meet the requirements of either our ORM or our display technology, we are polluting our domain model with extraneous concerns.
There seems to be a general consensus among DDD developers (except for the real purists, and they scare the rest of us) that NHibernate’s requirement that all collections be IList<T> or IESI.ISet<T> collections does no real violence to Separation of Concerns where the domain model is concerned. IList<T> is a lowest-common-denominator interface for .NET collections, as is ISet<T>. Even if an application does not use NHibernate, odds are that whatever collection type is used will implement IList<T>. So, we have no real concern here.
ISet<T>
WPF requires individual objects to implement the PropertyChanged event, and it requires collection properties to implement the CollectionChanged event. In effect, those requirements mean that classes that interact with WPF must implement the INotifyPropertyChanged interface, and their collection properties must be of type ObservableCollection<T>. Arguably, those constraints are no more onerous than NHibernate’s constraint to IList<T>. Maybe they are, and maybe they aren't. But, we can all agree that a class that works with WPF absolutely will not work with NHibernate.
INotifyPropertyChanged
Even without the NHibernate problems, I would be concerned about the extent to which WPF bends a domain model out of shape. The entire idea behind object-oriented programming (and Separation of Concerns) is to minimize the coupling between the different portions of a program. If I keep my domain model (and my other business logic) separated from both WPF and NHibernate, then I can replace either of them down the road, should the need arise, without having to make major changes to the other two components. If Microsoft hits a home run with Version 2 of the Entity Framework, I should be able to replace NHibernate without having to tear apart either my domain model or my user interface. And, if another display technology supplants WPF down the road, I should be able to update the UI without tearing up the back end of my application.
The ability to make these kinds of changes convinces me that some additional work is well-worth the effort involved. It’s all a question of how much work is required to maintain a separation of concerns. The WPF-NHibernate Toolkit is designed to minimize the extra work involved in separating your user interface from the back end of your program.
Paulo Quicoli brought up a great point when this article was first published. Paulo is the author of WPF + M-V-VM + NHibernate + NHibernate Validator = Fantastic Four! It’s a great article, one that I would recommend to anyone learning WPF. Anyway, Paulo asked, in effect, if you could accomplish the same result much more easily using the following approach:
As Paulo pointed out, this solution will work, as he demonstrates in his article.
Paulo is absolutely correct, and in a small-scale application, that approach will work very well. However, in a large-scale application, it will result in a performance hit. Here’s why: NHibernate takes a snapshot of the objects that you retrieve, and caches the snapshot in the ISession object. When you persist back to the database, NHibernate compares the current state of your objects to the snapshots in its cache. It only writes the objects that have actually changed.
ISession
To enable NHibernate to perform this trick, you must maintain object identity throughout your session. In other words, you have to pass the same objects back to NHibernate that it originally passed to you. When you inject your IList<T> into an ObservableCollection<T>, you are creating a new collection, which breaks object identity. So, when you cast the ObservableCollection<T> back to an IList<T>, you will have a faithful copy of your original collection, but you will not have the original. As a result, NHibernate will fall back to writing everything back to the database. So, even if you change only one object in a collection of one thousand, the entire collection gets written back to the database.
It is worth noting that if you do decide to implement INotifyPropertyChanged on your individual objects, it would eliminate the need to wrap those objects. As a result, you could probably simplify VmCollectionBase<VM, DM>, since it will have access to domain objects, instead of wrappers. I like to keep my domain models as clean as possible, so at this point, I am wrapping all of my individual domain objects. But it’s a close call—I can see the merits of the argument that implementing INotifyPropertyChanged does not pollute my domain model in any meaningful way.
VmCollectionBase<VM, DM>
Most WPF gurus recommend using the Model-View-ViewModel (MVVM) pattern to organize WPF applications. The idea behind MVVM is that we create a view model class for each view in our application. The view model provides an abstract representation of the commands and data needed by the view, as well as the programming logic required to drive the display. The tremendous advantage to this pattern is that WPF can data-bind to both commands and data in a very simple, easy-to-implement way.
I won't spend any time on MVVM in this article. There are a number of good articles about MVVM on the web. And Jason Dolinger, of WPF developer Lab 49, did a very good screencast on the subject that can be found on the Lab 49 blog. But, there are a couple of points I would like to make about MVVM before we move on:
IConverter
DataContext
In this article, when we refer to a view model (in lower case), we are referring to the groups of classes that make up the view model for a particular view. When we refer to the ViewModel, we are referring to the Façade class. Now, on to the toolkit.
One of the design goals in Version 2.0 of VM Wrapper Express is to improve the encapsulation of domain objects. Ideally, a wrapper object should hide the domain object from the view. In other words, the view should only see the wrapper objects in the view model, not the domain objects inside the wrappers. That approach prevents a developer from mistakenly accessing domain objects and breaking data binding in the UI. In the original version of VM Wrapper Express, wrapped objects exposed the domain object in a public property, DomainObject. As a result, domain objects were not hidden from the view by their wrappers.
public
DomainObject
The need for a public DomainObject property stemmed from the fact that the VmCollectionBase class needs access to wrappers' domain objects. New VM objects can be created in the view by data binding operations—for example, see the Add and Remove buttons in the VM Wrapper Demo application. These new objects are typically added to VM collections. In that case, the VmCollectionBase class responds to the change in the VM class and pushes the change out to the domain model. To do that, the VmCollectionBase class needs access to the domain object in the new or deleted VM, to push the change out to the domain model.
public DomainObject
VmCollectionBase
Version 2.0 improves on the situation somewhat by making the DomainObject property internal. So long as the view model is compiled in a separate assembly from the view, the VM object will hide the domain object from the view, while still making it accessible to the VmCollectionBase class. The VM Wrapper Demo solution utilizes this approach.
internal
However, if the view and the view model are contained in the same assembly, the DomainObject property will be visible to the view. For this reason, while Version 2.0 improves on the original version of VM Wrapper Express, I am not entirely happy with the result. If any reader can recommend a better approach to encapsulating the domain object, I would be very open to the suggestion.
Note that in the VM Wrapper Demo application, we break the rule about hiding the domain object. In fact, the view model exposes the entire domain model as a property, where it is readily accessible by the view. It does this so that the view can inspect domain objects in order to demonstrate that changes have been pushed out to the domain model. Note that I do not recommend doing this as a general practice. As we discussed above, the view model should provide the view's sole access to the properties of the domain model.
There are two parts to the toolkit:
VM Wrapper Express does not wrap all objects that are contained in a domain model. Instead, it wraps only those objects that you want to expose in a view model. The wrappers are implementations of the Gang of Four Adapter pattern.
VM wrappers fall into two categories:
Customer
Order
Customers
Orders
Prior to Version 2.1, VM Wrapper Express did not generate individual wrapper classes for collection classes. Instead, it used a generic VmCollection<VM, DM> class. To wrap a collection, the developer simply declared a property to be of type VmCollection<VM, DM> (VM and DM are explained below). This worked well in most scenarios. However, for reasons that are not entirely clear, this approach caused the WPF DataGrid to become uneditable when it was bound to a property of this type. For some reason, the WPF DataGrid sets the IEditableCollectionView.CanAddNew property to false whenever it is bound to a generic class with more than one generic parameter.
VmCollection<VM, DM>
VM
DM
IEditableCollectionView.CanAddNew
false
The solution turns out to be rather simple. We simply declare a skeletal collection wrapper for each collection class. The wrapper derives from the VmCollectionBase<VM, DM> class. The collection wrapper does not need to implement any separate functionality, since its sole purpose is to work around the WPF DataGrid bug. So, as of Version 2.1, we have a VmCollectionBase<VM, DM> class, and individual collection wrappers derived from that base class. The new base class behaves identically to the old generic class.
The VmCollectionBase class has two generic type variables (which behave identically to their counterparts in the old generic class):
We put quotes around ‘wraps’ when discussing collection wrappers because VmCollectionBase<VM, DM> doesn't really wrap an IList<T> collection. Rather it duplicates it, to hold a collection of object wrappers. But, the effect is the same as if it had wrapped the collection.
The object and collection wrappers are designed so that any changes made to the wrapper object’s properties flow back to the corresponding properties in the wrapped domain object. There are two types of changes involved:
These methods keep the view model and domain model collections synchronized with each other.
Note that VM Wrapper Express creates both an individual object wrapper and a collection wrapper for each domain object selected in the main window. Generated wrappers are placed in three subfolders under the folder selected in the main window: BaseClasses, CollectionWrappers, and ObjectWrappers. Once you have used VM Wrapper Express to generate wrapper classes, you can decide which wrappers you need to use in your view model. In my applications, I normally generate classes to a Wrappers folder in the view model project, then move the base classes from that folder to wherever the other base classes for the project are stored. This is the approach used in the VmWrapperDemo app.
Note that the direction of flow for changes remains one-way in Version 2.0; that is, changes to a wrapped object or collection flow to the wrapped domain object or collection, but not vice versa. As a result, after a domain object or collection is wrapped, changes to the domain object or collection do not flow to their wrappers. This approach is based on the idea that once an object is wrapped, it should only be accessed via its wrapper. The demo app’s Add Customer command reflects this approach. A new object wrapper (which contains a new domain object) is added to the view model collection; the wrapper collection then pushes the new wrapped object out to the wrapped collection.
I discovered a bug in Version 1.0 of VM Wrapper Express that arose whenever a domain class had a property that was typed to another domain class. Let’s say you have a domain class whose properties are all simple .NET types; strings, ints, and the like. When the UI calls a wrapped property, it wants the string or its value that the property wraps. But what if a domain class has a property that is another domain type? For example, a Customer class may have an Address property that is typed to a domain class called Address. This latter class has properties for StreetNumber, StreetName, City, State, and Zip (assuming it’s a USA address). In that case, what the UI wants is the wrapped address object, from which it can then get the information it needs.
Address
StreetNumber
StreetName
City
State
Zip
The object wrappers generated by the original version of VM Wrapper Express didn't make this distinction—if a domain class property was typed to another domain class, it simply tried to return the second domain object. Version 2.x of VM Wrapper Express wraps the second domain object in a VM wrapper before it passes it to the caller, which is the expected behavior.
CodeProject member Skendrot posted a message in response to the original article pointing out that the original solution did not account for lazy loading. He suggested a fix that I liked so well that I incorporated it without change in Version 2.0. You can find his original message at the end of this article. Thanks, Skendrot!
The demo application is changed slightly in Version 2.1--it now uses individual collection wrappers, rather than the generic collection wrapper from Version 2.0. Its behavior is identical to Version 2.0. The demo shows how the wrapper classes are used in a simple application:
The demo app is built on the Model-View-ViewModel pattern; code-behind is kept to a minimum, and most control logic is contained in the app’s view model classes, which are found in the view model folder.
Each of the buttons in the main window demonstrates a different type of operation on the domain model. When you click a button, the demo app applies the operation to the wrapper class (not the wrapped domain class). The list boxes will update immediately, which shows that the operation has been propagated from the wrapper class to the view. The app then shows a message box which shows the results of the operation as read from the appropriate wrapper class property, and separately from the corresponding domain class property. The results should be the same from both sources, showing that the operation has been propagated from the wrapper class to the wrapped domain class.
The domain model is intentionally simplistic. The demo model offers the barest minimum of a Customers-Orders model, just enough to show how multi-level domain object wrapping works. Domain objects can be found in the Domain envelope. The main window for the application can be found in the view folder.
The view model is made up of a number of different classes. MainWindowViewModel (the Façade class) acts as a container for many of these classes; it is bound to the main window’s DataContext property on startup (in App.xaml.cs). The Commands folder contains the ICommand objects for the app’s commands. These objects are exposed as ICommand properties in the view model class. The Converters folder contains several IValueConverter classes that are used in data-binding operations between the view and the view model. The BaseClasses folder holds the base classes used by the view model and its wrappers:
MainWindowViewModel
DataContext
ICommand
IValueConverter
ViewModelBase
VmWrapperBase
VMCollectionBase
Finally, the Wrappers folder contains object wrappers for the domain objects exposed in the view model. These wrappers are generated by the VM Wrapper Express utility.
The demo app is initialised in the App.xaml.cs class, in an override to the OnStartup() event handler. The demo app mocks NHibernate, rather than implement it to any degree. It simply creates a couple of Customer objects, each of which has a couple of Order objects, and then wraps these collections in IList<T> collections, to emulate what we would get from NHibernate. If you need to know how to use NHibernate to get these objects from a database, I would suggest my article, NHibernate Made Simple, also on CodeProject.
OnStartup()
When the demo app launches, it presents a rather ordinary master-detail view, made up of two list boxes. The top list box lists customers, and the bottom list box lists orders for the selected customer. A series of buttons appear below the list boxes; each button demonstrates a different task involving wrapped objects.
The buttons are bound to the demo app’s ICommand objects, which (as we noted above) are exposed as command properties on the view model. The command logic is all rather straightforward, so I won't belabor it here.
The main object wrapping is done in App.xaml.cs. The OnStartup() override creates a couple of Customer objects and populates them with Order objects; then, it passes the IList<Customer> it has created to the view model:
IList<Customer>
// Create view model
MainWindowview model mainWindowview model = new MainWindowview model(customers);
The view model constructor initializes its Customers property as a new CustomersVM collection class, and passes the IList<Customer> to the collection’s constructor:
CustomersVM
// Initialize collections
this.Customers = new CustomersVM(customers);
At that point, VmCollectionBase gets down to work:
// Populate this collection with VM objects
VM wrapperObject = default(VM);
foreach (DM domainObject in domainCollection)
{
wrapperObject = new VM();
wrapperObject.DomainObject = domainObject;
this.Add(wrapperObject);
}
The code traverses the IList<Customer> and creates an object wrapper for each Customer object, injecting the domain object into the wrapper’s constructor, and adds these wrapper objects to its own internal collection. Pretty simple stuff, really. The process continues in a recursive chain that ensures that the entire object graph is wrapped to its deepest level.
The demo is more-or-less self-explanatory. The master-detail data binding is done in XAML, using the ItemsSource properties of the two list boxes. The top list box is bound to the view model’s Customers property, like this:
ItemsSource
<ListBox x:Name="listBoxCustomers" ItemsSource="{Binding Path=Customers}" … >
Then, the Orders list box is bound to the current Customer.Orders property, like this:
Customer.Orders
<ListBox x:Name="listBoxOrders" ItemsSource="{Binding Path=Customers/Orders}" … >
Note that the IsSynchronizedWithCurrentItem property is set to "True" for both list boxes. This ensures that both list boxes are set to the same Customer object.
IsSynchronizedWithCurrentItem
True
You might notice that the UI has buttons to create new objects. These buttons invoke an operation that reverses the normal creation of a wrapper object. Normally, the domain object comes first, and it is injected into the wrapper object’s constructor. But when wrapper object creation is invoked from the UI, there is no pre-existing domain object. We need to create a new domain object to wrap in the VM wrapper. The UI does this by calling a second, parameterless constructor on the Wrapper object. This constructor instantiates a new domain object of the appropriate types and injects the new domain object into its own primary constructor.
Wrapper
You will notice that we bind the SelectedIndex property of both list boxes to view model properties. These properties are used by several of the ICommands, to get the currently selected objects (see the Add Order and Remove Order ICommands). At first glance, this may seem a needless complication—why not simply have the view model read the ListBox property directly?
SelectedIndex
In a Model-View-ViewModel design, the view model should have no direct dependencies on the view. In fact, in production apps, I put all my view classes in one project, and all my view model classes in a separate view model project. The .NET compiler will not allow circular references, and my view project obviously has a reference to the view model project. As a result, the .NET compiler will not let me create a reference to the view in my view model, which means I can have no direct dependencies running from the view model back to the view. This approach goes a long way towards keeping my view models untangled from the views that are bound to them.
Is the extra work worth the effort? Let’s say I could call listBoxCustomer.SelectedIndex in the view model. Now, suppose a designer came along after I was done, and wanted to replace my rather drab looking list box with something more attractive. Unfortunately, they wouldn't be able to do so, since my view model is hard-coded to a list box. For the designer to be able to make that change, I would have to reopen my code and tie it to whatever the new control might be.
listBoxCustomer.SelectedIndex
If I remove this dependency on a list box control, I increase the flexibility of my design. So, instead of binding my view model to a list box, I let the view bind to a property in the view model that provides the index of the object I want. And, I separate my views and view models into separate projects. That way, a designer can replace the list box with anything they want, so long as they provide the view model with the index in the Customers collection of the currently selected customer. That means I won't have to reopen my code, no matter what the designer wants to do.
The VM Wrapper Express utility generates custom object wrappers for domain model classes. Here is the main window, showing the domain classes for the VmWrapperDemo project:
Here are the steps to create view model classes with VM Wrapper Express:
You will probably find yourself re-generating wrappers a number of times during the course of development. You can save the configuration for a particular assembly by clicking the Save Settings button and saving the current settings in the Save File dialog that appears. The next time you need to generate wrappers for your project, you can reopen your previous session by clicking Open Settings, instead of Load Assembly. Express will load the assembly, select the previously-selected classes, and enter the view model namespace for you. All you have to do is click the Generate Classes button.
The demo app shows how to use the wrapper classes generated by VM Wrapper Express. First, add the wrapper classes you need to your development project-- I generally put them in a 'Wrappers' folder outside the project and import the wrappers I need into the project. In the demo app, the wrapper classes imported into the project are included in the View Model folder, distributed in three subfolders; BaseClasses, ObjectWrappers, and CollectionWrappers.
VM Wrapper Express generates all wrapper classes and base classes. So, all you have to do is import the classes you need (which should include all base classes) into your project. Once that is done, you can use wrapper classes just like you would use domain classes. The key difference is that the wrapped classes now implement the PropertyChanged and CollectionChanged events, so WPF will data bind with them nicely.
As we noted above, the wrapped domain objects, and the domain collections that contain them, retain their identities and characteristics. In other words, a wrapped domain class can be referenced directly, even when the class is wrapped inside a view model wrapper class. Simply retain a reference to your domain class. That way, when the time comes to persist the domain objects, they can be saved in the normal manner.
Note that persisting objects does not break the link between a domain object and its wrapper—there is no need to extract the wrapped domain object in any way. So, if you need to continue using the wrapper after saving the wrapped object, you may do so without having to take any additional steps.
In fact, the demo app shows most aspects of working with wrapped classes. Once you understand how it works, you should have no trouble integrating wrapped domain objects into your own development process.
The original version of VM Wrapper Express used property injection to inject a domain object into a newly-created VM wrapper. Normally, one would use constructor injection for this task, but .NET does not allow the use of parameterized constructors when using the new keyword to create a new object. Version 2.x of the VmCollectionBase class uses System.Reflection.Activator.CreateInstance(), which allows parameterized constructors, to create new VM objects. So, all wrapper classes now provide two constructors:
new
System.Reflection.Activator.CreateInstance()
The first constructor is used when initialising a view model; the second constructor is used when a new VM object is created as the result of an operation in the view.
We have discussed the notion of wrapping domain classes primarily as a way of adapting NHibernate-friendly classes to make them WPF-friendly. However, there is an argument to be made that wrapping domain objects is a good idea whether one uses NHibernate or not. That’s because the wrappers free the domain model from any display or data-binding concerns. That promotes Separation of Concerns, and that’s always a Good Thing. If Microsoft changes its display or data-binding technologies in the future (and at some point, they certainly will), it will be much easier to rewrite wrapper classes than an entire domain model.
Put another way, VM wrapper classes enable the use of “POCO” objects (Plain Old CLR Objects) in a domain model. Domain-Driven-Design proponents will tell you that’s what keeps domain models flexible and focused on their sole job of modelling a problem domain. And ultimately, that makes applications easier and less expensive to maintain over time.
Please post comments regarding any bugs that you find in either the demo app or VM Wrapper Express, or with any suggestions for improving either program. I will post updates to the article to incorporate significant suggestions or bug fixes. I will be happy to answer questions regarding the article and the included applications, but I am unable to help with other programming problems. I hope you find the article and VM Wrapper Express as useful as I have.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
public class AVM : VmObjectBase<A>
{
(...)
public BVM b
{
get { return new BVM(base.DomainObject.b); }
(...)
}
}
public class BVM : VmObjectBase
{
(...)
public int value
{
get { return base.DomainObject.value; }
(...)
}
}
AVM a = new AVM(new A() { b = null });
<TextBlock Grid.
NullReferenceException
return base.DomainObject.value;
null
a.b == null
VmWrapperExpress\VmWrapperExpress\Templates
get { return new $view_model_property_type$(base.DomainObject.$property_name$); }
get { return (base.DomainObject.$property_name$ == null) ? null : new $view_model_property_type$(base.DomainObject.$property_name$); }
public class AVM : VmObjectBase<A>
{
(...)
public BVM b
{
get { return new BVM(base.DomainObject.b); }
(...)
}
}
public class AVM : VmObjectBase<A>
{
(...)
public BVM b
{
get { return (base.DomainObject.b == null) ? null : new BVM(base.DomainObject.b); }
(...)
}
}
Icon="/VmWrapperExpress;component/VmWrapperExpress.ico"
VmCollection[LT]boolVM,bool[GT] ReminderSent {get; set; }
this.DoB = new VmCollection[LT]DateTimeVM,DateTime[GT](p_DomainObject.DoB);
InitializeCollectionProperties()
public Guid Id
{
get { return this.DomainObject.Id; }
set
{
this.DomainObject.Id = value;
this.FirePropertyChangedEvent("Id");
}
}
public PersonVM Person
{
get { return this.DomainObject.Person; }
set
{
this.DomainObject.Person = value;
this.FirePropertyChangedEvent("Person");
}
}
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/36109/The-WPF-NHibernate-Toolkit?msg=3503888 | CC-MAIN-2015-14 | refinedweb | 5,261 | 54.42 |
Packaging with ADT
Every AIR application must, at a minimum,
have an application descriptor file and a main SWF or HTML file.
Any other assets to be installed with the application must be packaged
in the AIR file as well.
This article discusses packaging an AIR application using the
command-line tools included with the SDK. For information about
package an application using one of the Adobe authoring tools, see
the following:
Adobe® Flex® Builder™, see Packaging AIR applications with Flex Builder.
Adobe® Flash® Builder™, see Packaging AIR applications with Flash Builder.
Adobe® Flash® Professional, see Publishing for Adobe AIR.
Adobe® Dreamweaver® see Creating an AIR application in Dreamweaver.
All AIR installer files must be signed using a digital certificate.
The AIR installer uses the signature to verify that your application
file has not been altered since you signed it. You can use a code
certificate.
When you use a certificate issued by a trusted certification
authority, you give users of your application some assurance of
fact that your identity is verified by the certificate authority:
When you use a self-signed certificate, users cannot verify your
identity as the signer. A self-signed certificate also weakens the
assurance that the package hasn’t been altered. (This is because
a legitimate installation file could be substituted with a forgery
before it reaches the user.) The installation dialog reflects the fact
that the publisher’s identity cannot be verified. Users are taking
a greater security risk when they install your application:
You can package and sign an AIR file in a single step using the
ADT -package command. You can also create an intermediate,
unsigned package with the -prepare command, and
sign the intermediate package with the -sign command
in a separate step.
When signing the installation package, ADT automatically contacts
a time-stamp authority server to verify the time. The time-stamp
information is included in the AIR file. An AIR file that includes
a verified time stamp can be installed at any point in the future.
If ADT cannot connect to the time-stamp server, then packaging is
canceled. You can override the time-stamping option, but without a
time stamp, an AIR application ceases to be installable after the
certificate used to sign the installation file expires.
If you are creating a package to update an existing AIR application,
the package must be signed with the same certificate as the original
application. If the original certificate has been renewed or has
expired within the last 180 days, or if you want to change to a
new certificate, you can apply a migration signature. A migration
signature involves signing the application AIR file with both the
new and the old certificate. Use the -migrate command
to apply the migration signature as described in ADT migrate command.
Before AIR 1.1, migration signatures were not supported. You
must package an application with an SDK of version 1.1 or later
to apply a migration signature.
Applications deployed using AIR files are known as desktop profile
applications. You cannot use ADT to package a native installer for
an AIR application if the application descriptor file does not support
the desktop profile. You can restrict this profile using the supportedProfiles element
in the application descriptor file. See Device profiles and supportedProfiles.
As of AIR 1.5.3, publisher
IDs are deprecated. New applications (originally published with
AIR 1.5.3 or later) do not need and should not specify a publisher ID.
When
updating applications published with earlier versions of AIR, you
must specify the original publisher ID in the application descriptor
file. Otherwise, the installed version of your application and the
update version are treated as different applications. If you use
a different ID or omit the publisherID tag, a user must uninstall
the earlier version before installing the new version..
For applications
published before AIR 1.5.3 — or that are published with the AIR 1.5.3
SDK, while specifying an earlier version of AIR in the application
descriptor namespace — a publisher ID is computed based on the signing
certificate. This ID is used, along with the application ID, to
determine the identity of an application. The publisher ID, when
present, is used for the following purposes:
Verifying
that an AIR file is an update rather than a new application to install)
Before AIR 1.5.3, the publisher ID of
an application could change if you signed an application update
with migration signature using a new or renewed certificate..
In AIR 1.5.3, or later, the
publisher ID is not based on the signing certificate and is only
assigned if the publisherID tag is included in the application descriptor.
An application cannot be updated if the publisher ID specified for
the update AIR package does not match its current publisher ID.
You can use the AIR ADT command-line tool to package an
AIR application. Before packaging, all your ActionScript, MXML,
and any extension code must be compiled. You must also have a code
For a detailed reference on ADT commands and options see AIR Developer Tool (ADT).
To create an AIR
package, use the ADT package command, setting the target type to air for
release builds.
adt -package -target air -storetype pkcs12 -keystore ../codesign.p12 myApp.air myApp-app.xml myApp.swf icons
The
example assumes that the path to the ADT tool is on your command-line shell’s
path definition. (See Path environment variables for help.)
You must run the command
from the directory containing the application files. The application
files in the example are myApp-app.xml (the application descriptor
file), myApp.swf, and an icons directory.
When you run the
command as shown, ADT will prompt you for the keystore password.
(The password characters you type are not always displayed; just
press Enter when you are done typing.)
You
can create sign an AIRI file to create an installable AIR package:
adt -sign -storetype pkcs12 -keystore ../codesign.p12 myApp.airi myApp.air
Twitter™ and Facebook posts are not covered under the terms of Creative Commons. | http://help.adobe.com/en_US/air/build/WS5b3ccc516d4fbf351e63e3d118666ade46-7f66.html | CC-MAIN-2017-30 | refinedweb | 1,013 | 55.95 |
How to remove duplicate elements from a NumPy array in Python
In this post, we are going to learn about how to remove duplicate elements from a NumPy array in Python.
NumPy in Python: NumPy which stands for Numerical Python is a library for the Python programming, adding support for large, multi-dimensional arrays and matrices. It is one of the popular modules in Python.
Here we have various useful mathematical functions to operate different operations with the arrays.
For removing elements we use an in-build function numpy.unique(parameters) or if we have imported numpy pakage we can directly write uniques.
To import NumPy in our program we can simply use this line: import numpy as np
Here are some examples below:
Example1: remove duplicate elements from a NumPy array in Python
import numpy as np print(np.unique([1, 1, 2, 2, 3, 3])
Output:
[1 2 3]
Example2: Print unique values from a NumPy array in Python
import numpy as np array = np.array([[2,4,3,3], [9,5,6,7], [13,3,4],[2,4,3,3]]) print(np.unique(array))
Output:
array([[2,4,3,3], [9,5,6,7], [13,3,4]])
Here we have imported the package so simply we write:
->unique
np.unique(array)
Explanation:
For example1 we have removed duplicate in a single array. The function unique check each element and discard the duplicate element.
Example2 illustrates that if we have nested array and two arrays have the same content then it removes one array so duplicates are removed.
You may also read: | https://www.codespeedy.com/remove-duplicate-elements-from-a-numpy-array-in-python/ | CC-MAIN-2020-40 | refinedweb | 264 | 54.83 |
Render Fast with Virtualized Data Grids
Introduction
The Ultimate UI Controls for Xamarin data grid can handle unlimited data — rows or columns — with its virtual rendering capability. With this comes the fastest rendering, smooth touch interactions, and customized column and row interactions. In this lesson you’ll see the code to set up a data grid connected to an OData service and you’ll experience the incredible performance of the grid on iOS and Android.
With a few lines of sample code, you can connect to a publicly available data source from the Northwind service. You can use XamDataGrid to bind to an available data source (in this example an OData service), and display the data in a high-performance data grid.
Lesson Objectives
At the end of this lesson, you will have a high-performance grid using an OData data source. The major steps you’ll perform to do this are:
- Set up the project
- Define the data source
- Bind the source to the view
- Test the solution
For more information on the control used in this lesson, see the see the Xamarin Data Grid Control page.
Step 1: Setting up the Project
You can download the project used in this lesson by clicking here.
Then, to run the projects for the first time after un-zipping, load the entire solution into Visual Studio, right-click on the Solution, and select Restore Packages.
Once that is complete, add a reference to both the Portable Class Library and the Android project to DataSource.DataProviders.OData.Core.dll. This file is in the OtherDependencies folder that is part of the ZIP download. You can do this by right-clicking the Reference folder in the Project, browsing to the OtherDependencies folder, and selecting the DataSource.DataProviders.OData.Core.dll.
Do this for both projects in the solution. Then, finally, ensure the Target Android Version is set to "Use Compile using SDK version." You can find this setting by right-clicking on the Android project and selecting Properties.
Step 2 Define the Data Source
Now you’re going to bind the Northwind service data source in GridRemoteDataViewModel. In the XFPerfSamples project, expand ViewModels, and then open the GridRemoteDataViewModel.cs source file.
The sample project has already created GridRemoteDataViewModel, and defined the data source as being OData. In the source, add the following code segment to define the data source.
BaseUri="", EntitySet="Orders", PageSizeRequested=25, MaxCachedPages=5
The BaseUri defines the Northwind server as the OData source. From the Northwind service, the EntitySet defines what data is pulled from the service. The PageSizeRequested is the number of items per page that is returned every time a page is requested. The MaxCachedPages is how many pages are cached after being requested.
After defining the data source, the next step is to bind that source to the view.
Step 3 Bind the Data Source
After defining the source, you need to bind the source to the view. In the Visual Studio project, expand Views, and then open the GridRemoteData.xaml file. The requires the namespace for the Infragistics data grid. You can use the Infragistics Toolbox, which would automate the development of the necessary code. For the purpose of this lesson, we will write the code manually.
<igDataGrid:XamDataGrid x: <igDataGrid:XamDataGrid.Columns> <igDataGrid:TextColumn <igDataGrid:TextColumn <igDataGrid:TextColumn <igDataGrid:TextColumn </igDataGrid:XamDataGrid.Columns> </igDataGrid:XamDataGrid>
In this example, we set the AutoGenerateColumns property to false. Setting the property to True would inspect the data source and then create the necessary columns. This can present some problems for mobile apps, depending on the data set that is being used. The above code segment specifies the columns manually as TextColumns.
Step 4 Test the Solution
With the data source and binding configured, Grid – Remote Data.
Depending on the device or emulator, the Grid will be blank initially as it loads the source data. The data will be populated in the grid after it loads, and as you scroll. Test the grid by scrolling with your mouse or finger to load multiple pages. If the data has not been sourced to load, a temporary cell will be displayed within the interface while the data is loaded.
Conclusion
The XamDataGrid is used with a variety of data source types Xamarin mobile apps. This enables you to create a high-performance data grid using the data source of your choice, resulting in a seamless experience for the end user. | https://www.infragistics.com/products/xamarin/run-fast/virtual-data-grid | CC-MAIN-2018-30 | refinedweb | 739 | 54.83 |
It’s a good idea for all the assemblies in a single solution to have the same version number, but the default in Visual Studio is for each project to have it’s own AssemblyInfo.cs file, each with it’s own version number. However it’s easy to share a single Version.cs file between all the projects.
First create the Version.cs file as a solution item (right click on the solution, Add, New Item). It should look something like this:
using System.Reflection; [assembly: AssemblyVersion("2.0.1.442")] [assembly: AssemblyFileVersion("2.0.1.442")]
Now remove those same lines (AssemblyVersion and AssemblyFileVersion) from the AssemblyInfo.cs file in each project in the solution.
The next step to add a link to the Version.cs file to each project. Right click on the project and choose ‘Add New Item’ and then ‘Existing Item’. Browse to the Version.cs file in the solution root directory and add it as a link (click on the little drop down arrow on the ‘Add’ button in the file dialogue):
Do this to all your projects. Now you only have to maintain the version number for the whole solution in one place. Nice!
It’s common practice to integrate version numbering with continuous integration. This usually works by having the CI build process update the version number with the build number before each build. Having the number represented in one place makes that much easier.
One last thing you should always do is provide a way for anyone to discover the version number of a running instance of your application. With an ASP.NET MVC web application, it’s a simple as this little controller action:
public ActionResult Version() { var version = Assembly.GetExecutingAssembly().GetName().Version; var versionMessage = string.Format("Suteki Shop. Version {0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.MinorRevision); return Content(versionMessage); }
Now if ever I need to know the version of a running instance I can just type the …/Version URL:
12 comments:
This does seem to be the best way in VS.Net. For some reason our developers often mix C++ or VB.net and C# in the same solution requiring up to 3 files. If you have a deployment project it also needs updating with a separate file.
FYI: I blogged on a closely related subject a few months back.
Hi Michael, Yeah, I didn't consider the multi-language solution story here. I guess there's no option but to have multiple version files.
Hi Alan, Thanks for that. A very nice demonstration of how to integrate build number versioning into the build process.
Hi Mike
You can make it even more simpler.
Remove AssemblyFileVersion
If not given, the AssemblyVersion is used.
.peter.gfader.
Hi Peter, Great suggestion, thanks for that.
Hi Mike... MadManWriting here (aka Robin Harris). Like the Blog - good to see you're still banging out the code... Hope all is well with you and yours.
Hi Robin, Great to hear from you, please drop me a line: mikehadlow at yahoo dot com.
Very, very helpful! Thank you.
You can do search and replace across the AssemblyInfo files in your solution using this regular expression to remove the entries that you're replacing with the common version.cs
^\[assembly\: Assembly(Company|Product|Copyright|Version|FileVersion)\(".*"\)\]$
Hi,
Great post I am very keen on standardising version numbers across a project when creating major releases so this is very helpful.
It's nice because you can modify the "Assembly Information" properties within Visual Studio and the version numbers are just left blank. If a developer mistakenly enters a version number it fails to build with a duplicate version error.
Very nice.
Thanks,
Dave
I have a website project and added a assemblyinfo.cs file to the appcode. When i deployed the files, the page level dlls were all 0.0.0.0
Thanks for posting this, it's exactly what I was looking for. | http://mikehadlow.blogspot.com/2010/10/use-single-version-file-for-all.html | CC-MAIN-2017-13 | refinedweb | 662 | 67.65 |
I have a base class
line which has a child class
arc (note that additional classes will inherit from
line)... I need to store a list, or
vector of
line objects that may be a
line or an
arc.
arc has an additional property that
line does not. So as I'm working with my lists, or
vector of
line objects, how do I determine whether the object is a
line or an
arc?
I have prepared a small sample program and put in comments with pseudo-code a sample of what I would be trying to accomplish. Is this even possible?
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
struct point
{
double x;
double y;
};
class line
{
public:
point start;
point end;
};
class arc: public line
{
public:
point center;
};
int main( int argc, char* argv[] )
{
vector<line*> a;
a.push_back( new line );
a.push_back( new arc );
for( vector<line*>::iterator i = a.begin(); i < a.end(); i++ )
{
(*i)->start.x = 10;
(*i)->start.y = 11;
(*i)->end.x = 101;
(*i)->end.y = 102;
//if( type of (*i) is arc )
//{
// (i)->center.x = 111;
// (i)->center.y = 112;
// }
}
return 0;
}
In your loop, try this:
arc *ar = dynamic_cast<arc *>(*i); if ( NULL != ar ) { // it's an arc! }else { // it's just a line }
Sid is also right...use virtual functions for this instead. Using dynamic_cast for simple cases such as this is generally considered poor style.
class curve { public: typedef void * type; public: virtual type rtti() const = 0; }; #define DEFINE_RTTI \ public: \ virtual type rtti() const { return desc(); } \ public: \ inline static type desc() { return &desc; } \ class line : public curve { DEFINE_RTTI; }; class arc : public curve { DEFINE_RTTI; }; /////////////////////////////////////////////////////////////////////////////// // Main program int main() { arc arc_; line line_; curve *curve_ = new arc(); _ASSERT(arc_.rtti() == arc::desc()); _ASSERT(arc_.rtti() != line::desc()); _ASSERT(line_.rtti() != arc::desc()); _ASSERT(line_.rtti() == line::desc()); return 0; }
This rtti works inside one module (exe or dll), if you want use it in several modules you have to build class dictionary
Why do you need to determine? If you absolutely need to you can use the typeid field via RTTI. But normally if you use virtual methods, if your program is well designed you shouldn't need to know what a class is. Calling a virtual function on a base class reference or pointer will call the appropriate instance's method based on what it is pointing to. That's the whole point of having polymorphism via class hierarchies.
But again, use typeid if you absolutely need to know what class an instance belongs to.
Also, you can't access derived class member data via base class pointers. you can only talk via the base class interface. that's the whole point of abstraction. One ugly way around is to create a fat interface that is give accessors/mutators to these data members in your base class interface as virtual member functions. | http://www.dlxedu.com/askdetail/3/dec677a76c85c1822d4a60407ae7e368.html | CC-MAIN-2018-39 | refinedweb | 483 | 74.9 |
[Version FR disponible ici]
Thanks to the universal apps, we can now share much more than PCLs between applications targeting different platforms.
In Visual Studio, a universal solution is composed of at least 3 projects : one for Windows Store, one for Windows Phone and another one for the shared components.
In the shared project, you don’t share binaries (like in PCLs) but files such as resources, images, xml, XAML, code, … which will then be used in each platform-specific project.
In this article, we will focus on sharing XAML code.
Regarding to this new exciting possibility, the aim will not be to share all of your XAML in your apps : we still need to adapt the UI to provide the best user experience according to the platform, device usage, form factor, ...
So instead, we will see common strategies to keep some UI platform specificities while having some of the XAML shared.
Don’t think I encourage you to share the maximum percentage of your XAML code : this can be very tricky and difficult to undestand what styles, datatemplates and usercontrols are shared or not, and how they relate to each other. This is an overview of the main technical possibilities, to help you do your own choices.
The article is divided in 2 parts:
- Part 1 : Starting a new Universal project and see what can be shared and how (this article)
- Part 2 : Going Platform specific : beyond the system controls and styles that can be shared and will behave differently on each platform, how to have custom behavior in the UI now that we have shared our XAML ?
You can download the source code here:
Let’s start a new Universal Projet
You can use the new templates provided in Visual Studio 2013 Update 2 to create a universal Hub app or empty app, or you can start with an existing Windows Store app and add a new Windows phone project (or the opposite).
Here we’ll use a blank project:
Here is what the solution looks like. You have one shared file : the app.xaml.
<Application x: </Application>
Sharing XAML
You can still share the MainPage.xaml : remove it from the specific projects to put it in the shared one : the compilation process will succeed.
Let’s add some controls to this common MainPage !
As Tim Heuer explained it in his Build session, the majority of the UI API are now common between Windows Store 8.1 Refresh and Windows Phone 8.1 (most of the differences are about Automation and picker controls specificities).
Common API doesn’t means same UI user experience and most controls will look and behave differently according to the Platform. Some of them are quite similar, some other are very different. Tim covers these différences in his slides:
Some controls are still platform specific:
We won’t cover all of them here, we will just try to illustrate the sharing capabilities in a concrete basic example.
Let’s start by adding a few controls in MainPage.xaml:
<Page x: <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <StackPanel> <TextBlock TextWrapping="Wrap" Text="TextBlock" Margin="30" FontSize="28"/> <DatePicker Margin="30"/> <CheckBox Content="CheckBox" Margin="30"/> <Button Content="Button" Margin="30"/> </StackPanel> </Grid> </Page>
You can adapt the preview of the resulting UI, according to the form factor, resolution, orientation, contrast, theme, … This is a new feature of Visual Studio 2013 Update 2.
While having a shared XAML page, the controls included in it will look and behave differently on Windows 8.1 and Windows Phone 8.1, according to their specific implementation (the date picker is a great example) :
Let’s add a FlipView control to show some of the pictures I have taken at //Build:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <FlipView Margin="0,9,0,-9" ItemsSource="{Binding Items}"> <FlipView.ItemTemplate> <DataTemplate > <Grid> <Image Source="{Binding Path}" VerticalAlignment="Top" /> <StackPanel> <TextBlock TextWrapping="Wrap" Text="{Binding Title}" Margin="30" FontSize="28"/> <DatePicker Margin="30"/> <CheckBox Content="I like that" Margin="30"/> <Button Content="Share" Margin="30"/> </StackPanel> </Grid> </DataTemplate> </FlipView.ItemTemplate> </FlipView> </Grid>
I will also create a shared folder ViewModels with a MainViewModel and ItemViewModel to bind an image source to the items path.
Creating the basic ViewModel stuff
You may skip this step if you want to focus on XAML : it’s just plumbery stuff to bind my view to some data…
I didn’t implement all the two-way binding stuff because it’s not the subject of this article, but I encourage you to use the MVVMLight lib which will give you automatic INotifyPropertyChanged mechanism in a ViewModelBase class, RelayCommands, etc…
Laurent Bugnion wrote a short article to start with MVVMLight in universal apps.
using System; using System.Collections.Generic; using System.Text;using GalaSoft.MvvmLight;namespace BuildMemories.ViewModels { // Making it partial can help sharing code too... public partial class MainPageVM : ViewModelBase { ItemVM[] _items = { new ItemVM() { Path = "Assets/WP_1.jpg", Title="SF From the bay"}, new ItemVM() { Path = "Assets/WP_2.jpg", Title="I <3 Xamarin"}, new ItemVM() { Path = "Assets/WP_3.jpg", Title="XBox session"}, new ItemVM() { Path = "Assets/WP_4.jpg", Title="Which was that one ?"}, new ItemVM() { Path = "Assets/WP_5.jpg", Title="Sunny, lucky me !"}, }; public MainPageVM() { } public ItemVM[] Items { get { return _items; } } } }ItemVM.csusing System; using System.Collections.Generic; using System.Text;using GalaSoft.MvvmLight;namespace BuildMemories.ViewModels
{
// Using a partial class will help sharing VM accross shared and platform specific projects
public partial class ItemVM: ViewModelBase
{
public string Path { get; set; }
public string Title { get; set; }
}
In the xaml file, we instanciate the MainPageVM and bind it to the Datacontext:<Page x: <Page.Resources> <vm:MainPageVM x: </Page.Resources> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" DataContext="{StaticResource dc}">…</Page>
My shared project looks like that now:
To get all the detailed code, you can download the complete source code at the end of the article.
The app at this point
Now here is what the Windows Phone and Windows Store app look like.
The FlipView gets its nice specific behavior on each platform and is also working well with the mouse on Windows 8.1.
But maybe we should adapt the behavior and the position of what we could call the “banner command controls” in these two views. What I want is to bottom align my controls, but also have an horizontal alignment of the controls in the Stackpanel in the Windows app.
Tweak the view according to width/height ratio with the SizeChanged event
A first approach could be to keep that xaml code in the shared project and adapt the layout according to the portrait/lanscape mode, whether the app executes on Windows Phone or Windows 8. A simple way to do that would be to evaluate the width/height ratio and change the layout in the SizeChanged event.
Basic
In my case, I just change the orientation of my StackPanel.private void Page_SizeChanged(object sender, SizeChangedEventArgs e) { if(e.NewSize.Width < e.NewSize.Height) { spActions.Orientation = Orientation.Vertical; } else { spActions.Orientation = Orientation.Horizontal; } }
The interesting result is that the narrow view in Windows 8 will get benefit of that and behave the same when the width gets smaller than the window height.
With Visual States
You can also have more flexibility with a visual state for each just like it is suggested in the guidelines since Windows 8.1. Here is an example from the MSDN:/// If the page is resized to less than 500 pixels, use the layout for narrow widths. /// If the page is resized so that the width is less than the height, use the tall (portrait) layout. /// Otherwise, use the default layout. void Page_SizeChanged(object sender, SizeChangedEventArgs e) { if (e.NewSize.Width < 500) { VisualStateManager.GoToState(this, "MinimalLayout", true); } else if (e.NewSize.Width < e.NewSize.Height) { VisualStateManager.GoToState(this, "PortraitLayout", true); } else { VisualStateManager.GoToState(this, "DefaultLayout", true); } }
Sharing the Accent Color resource
I can now use a common ThemeResource to use the accent color of each device with the SystemColorControlAccentBrush. To illustrate this, I will add a background set to the accent color, to my existing stackpanel:<StackPanel x:
And more…
You have yet more things to share such as animations and app bars, but here, I wanted to focus on how to add platform specific behavior while having some XAML shared. which is the second part of this article.
Next >> Strategies for sharing XAML code in Universal Apps (2/2)
really useful, thanks!
Glad you like it 🙂
Where are you finding SystemColorControlAccentBrush? That doesn't seem to be defined for me. I took a Win8 app and added a phone app to it. The universal app is generally working but that doesn't seem to be defined at all…
Visual Studio undelines it in red but it does compile and run fine. You can find a full working example in the source code attached to this article.
Found this great as a simple rundown for continues #code-pressing. Solid and thanks
Helps a lot to understand Universal App. Thanks.
if you have the mainpage out in the shared directory, but wanted to navigate to a phone specific page contained in the phone project, how could you accomplish that?
Hello jhealy,
You could do this in many different ways, for example use #if, or use a variable initialized with the page name, or use IOC, …
I also notice thee error of VS related to SystemColorControlAccentBrush (that also the intellisense doesn't suggest as a possible value!)
Dont't you think it is quite strange that Visual Studio undelines it in red but it does compile and run fine? It is not the first time I have "strange" errors in VS using Universal app template …. :-/
Hello Stephanie,
I notice that the following line of code in the XAML code is causing an error: `<local:BannerUserControl …/>`. The error message is: "Cannot create an instance of 'BannerUserControl'". I notice that your post is based on Visual Studio 2013 Update 2 while I am compiling your example with Visual Studio 2013 Update 5. My guess is that Visual Studio change the way it handles the user-defined controls now? Will you be able to update the same code or give a work around in the comments here?
Thanks,
Yuchen | https://blogs.msdn.microsoft.com/stephe/2014/04/16/strategies-for-sharing-xaml-code-in-universal-apps-12/?replytocom=1113 | CC-MAIN-2018-22 | refinedweb | 1,698 | 60.65 |
How run the new client?
Asked by Nhomar - Vauxoo
Hello.
I compile documentation on new web client and it is not indacated there.
When i trie to run this error appear.
Traceback (most recent call last):
File "./openerp-web.py", line 41, in <module>
import web.common.dispatch
File "/home/
import common
File "/home/
from dispatch import *
File "/home/
import werkzeug.urls
ImportError: No module named urls
I now the architecture has changed, can you help me how do i need to run the new web client please.
Regards.
Question information
- Language:
- English Edit question
- Status:
- Solved
- Assignee:
- No assignee Edit question
- Solved by:
- Valentin Lab
- Solved:
-
- Last query:
-
- Last reply:
- | https://answers.launchpad.net/openobject-client-web/+question/170585 | CC-MAIN-2021-31 | refinedweb | 111 | 67.96 |
Sometimes bit of extra work to get similar behaviour in a Jupyter notebook (and a Kaggle Kernel notebook).
Here is an example of a visualisation that I find useful during runtime:
Now, if we want to have these real-time updates to our plots in Jupyter (including Kaggle Kernel notebooks), we need to import display and clear_output from IPython.display:
import numpy as np import matplotlib.pyplot as plt from IPython.display import display, clear_output
Now we can update our plots with two different approaches. This approach clears the axes before plotting:
fig = plt.figure() ax = fig.add_subplot(1, 1, 1) for i in range(20): x = np.arange(0, i, 0.1); y = np.sin(x) ax.set_xlim(0, i) ax.cla() ax.plot(x, y) display(fig) clear_output(wait = True) plt.pause(0.5)
The other approach doesn’t clear the axes before plotting:
fig = plt.figure() ax = fig.add_subplot(1, 1, 1) for i in range(21): ax.set_xlim(0, 20) ax.plot(i, 1,marker='x') display(fig) clear_output(wait = True) plt.pause(0.5)
I’ve found these snippets to be incredibly useful in order to get some real-time feedback when using Jupyter notebooks. These are just simple examples, but they can be used to create some interesting “animations” that can give you insight into your experiments during runtime. | https://blog.shahinrostami.com/2018/10/jupyter-notebook-and-updating-plots/ | CC-MAIN-2018-43 | refinedweb | 225 | 61.63 |
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).
Hi,
I have a very simple scene:
Null Object
In-/Exclusion User Data
Python Tag
import c4d
def main():
obj = op.GetObject()
objList = obj[c4d.ID_USERDATA,1] # point to the In-/Exclusion User Data
print(objList.GetObjectCount())
If I add scene objects into In-/Exclusion User Data, or remove object within In-/Exclusion User Data, Python Tag will print correct object count.
But if I remove an object from the Object Manager which had been added into the In-/Exclusion User Data before, I can see object has been removed in In-/Exclusion User Data, but Python Tag report wrong object count (as if the object has not been removed).
Object Manager
And only if I make some change within the In-/Exclusion User Data directly, that the Python Tag report correct count number again.
I wonder if there is something I'm missing from the script for forcing InExclusionData update, or it's a bug in the "updating system"?
InExclusionData
Thanks!
Hi,
The InExcludeData object count does not always reflect the accurate number of valid objects depending on the scenarios.
Additionally to calling GetObjectCount() the returned value from ObjectFromIndex() should be checked if it's not None.
InExcludeData
GetObjectCount()
ObjectFromIndex()
Hi, y_puech!
Thank you for replying!
I use
i = 0
while True:
obj = InExData.ObjectFromIndex(doc,i)
if obj == None:
break
i += 1
to get right result.
Just a quick note on your code. A pythonic solution could be:
count = inExData.GetObjectCount()
for i in xrange(count):
obj = inExData.ObjectFromIndex(doc, i)
if obj is None:
continue
Why are you breaking out from the loop with the first invalid object in the InExcludeData?
Oh! Sorry! I know what you mean in the previous post now. I'm doing the wrong way. Your solution is correct!
By the way, I wonder if there is a situation where the actual object counts are greater than GetObjectCount() returned?
By the way, I wonder if there is a situation where the actual object counts are greater than GetObjectCount() returned?
This should never happen.
Thanks for marking the topic as solved. Note that you can mark a specific post as the correct answer or solution. See step 5 in Q&A New Functionality.
Hi, @y_puech I may find a bug of the forum about "mark a post correct answer", discussion post here: Cannot mark post as answer
Once this bug solved, I will re-edit this topic and posts correctly. | https://plugincafe.maxon.net/topic/11034/force-inexclusiondata-update-after-remove-object-outside-of-in-exclusion-user-data/4?lang=en-US | CC-MAIN-2021-43 | refinedweb | 449 | 57.27 |
This post written by Sergiy Oryekhov and Andrew Pardoe
The C++ Core Guidelines can help improve your code and decrease your cost of maintenance by offering a wide range of recommendations: encouraging use of the standard library, avoiding use of unsafe practices whenever possible, maintaining a consistent style, and helping you to enforce reasonable design decisions. The number of Core Guidelines recommendations may look discouraging for those who own legacy code, but even a gradual cleanup process will provide immediate improvements to your code without requiring a total rewrite.
We’ve implemented a set of code analysis checks in Visual Studio that should help you to start moving towards safer code. We are continuing to improve these checks and add more checks specific to the C++ Core Guidelines, but the current set allows you to start today on the work of making existing code better and adopting new standards of writing modern C++.
The C++ Core Guidelines Checker is not new: it was released as a NuGet package first, and it is included in Visual Studio 2017. It’s built on top of the C++ code analysis tools that are included in all editions of Visual Studio.
In Visual Studio 2017 15.3 we added more checks and fixed several bugs. We’ll provide more details about these checks in future blog posts. In this post we’ll take a quick look at how to use the tool and the kind of problems it can catch.
Running the C++ Core Guidelines Checker
The checker is a part of the C++ code analysis tools. Let’s assume we have a native C++ project. To enable code analysis, we can use the IDE:
- Select the project and in the context menu choose ‘Properties’.
- In the ‘Configuration Properties’ tree expand the ‘Code Analysis’ node.
- On the ‘General’ tab check ‘Enable Code Analysis on Build’.
- Switch to the ‘Extensions’ node and enable ‘C++ Core Check (Released)’.
- Save properties.
- Now, each effective build of the project (when there is any change) should run code analysis with extended checks.
Filtering rules
If you are interested in viewing a subset of rules you can use rulesets to manage the warnings you will see for a project. Use the same ‘General’ tab (see “How to run C++ Core Check”) to pick an appropriate ruleset and then rebuild your project:
You can also get more granular control over the rules by using macros in combination with #pragma warning. For example, here’s how to enable only the type-safety rules:
#include <CppCoreCheck/Warnings.h> #pragma warning(disable: ALL_CPPCORECHECK_WARNINGS) #pragma warning(default: CPPCORECHECK_CONST_WARNINGS)
You can also enable individual rules to make it easier to handle when code produces a lot of results:
#pragma warning(default: WARNING_NO_REINTERPRET_CAST)
Problems detected by the C++ Core Guidelines Checker
What kind of problems can be detected by the C++ Core Guidelines Checker? Here’s a sample of rules that are available in the checker. The issues detected by these rules are usually scoped and can be fixed without large code churn. You can focus on one kind of warnings and resolve them one file at a time.
Some of the following fixes make use of a small library of facilities, known as the Guidelines Support Library, designed to support the C++ Core Guidelines.
- Unsafe type conversions:
// Don't use reinterpret_cast. It is hard to maintain safely. auto data = reinterpret_cast<char*>(buffer);
The following fix can be applied here:
// To avoid buffer overruns use gsl::as_writeable_bytes which returns gsl::span. auto data = gsl::as_writeable_bytes<int>(gsl::make_span(buffer));
- Unsafe low-level resource management:
// Avoid calling new and delete explicitly. Unique pointers are safer. auto buffer = new int[buffer_size]; if (read_data(buffer, buffer_size) == read_status::insufficient_space) // Likely leaking memory here unless read_data deallocates it. buffer = new int[max_buffer_size]; if (read_data(buffer, max_buffer_size) == read_status::insufficient_space) { delete[] buffer; return nullptr; }
To avoid problems with memory management we can rewrite this code:
// std::unique_pointer will own and manage this object and dispose of it auto buffer = std::make_unique<int[]>(buffer_size); if (read_data(buffer.get(), buffer_size) == read_status::insufficient_space) buffer = std::make_unique<int[]>(max_buffer_size); if (read_data(buffer.get(), max_buffer_size) == read_status::insufficient_space) return nullptr;
- Missing constness specifications which may lead to unexpected data modifications with later code changes:
// If variable is assigned only once, mark it as const. auto buffer_size = count * sizeof(data_packet); auto actual_size = align(buffer_size); if (use_extension) actual_size += extension_size; encrypt_bytes(buffer, actual_size);
The fix is trivial:
// Now buffer_size is protected from unintentional modifications. const auto buffer_size = count * sizeof(data_packet);
- C++ Core Guidelines Checker can even detect many complex problems such as this code that is missing resource cleanup in one of the code paths. In this example the code is using a
gsl::ownertype from the C++ Core Guidelines GSL.
gsl::owner<int*> sequence = GetRandomSequence(); // This is not released. try { StartSimulation(sequence); } catch (const std::exception& e) { if (KnownException(e)) return; // Skipping resource cleanup here. ReportException(e); } delete [] sequence;
In this case
GetRandomSequence()should be redesigned to return a smart pointer instead of
gsl::ownerso that it is automatically released when it goes out of scope.
In closing
Good tools can help you to maintain and upgrade your code. The C++ Core Guidelines are a great place to start, and the C++ Core Guidelines Checker can help you to clean up your code and keep it clean. Try out the C++ Core Guidelines Checker in Visual Studio 2017
Ideally, would like to get these warnings as we are writing code instead of while building. But, C++ grammar makes it difficult to do it I guess.
Yes, it is difficult to parse C++ quickly enough to maintain a responsive experience in the editor. We can find some warnings at edit time–the question is whether these warnings are valuable enough to developers to surface them in the IDE. We’re actually investigating this feature right now. Thank you for the vote of support for this kind of feature!
As per this article would we get in foreseeable future an ability to check format specifiers for user defined functions? For example when the print_f being macro’ed?
This should be on by default. As someone who get to maintain legacy code, I’d like the IDE to bug me about legacy crust on it’s own, without me having to ask.
Hi Kirill,
I wish we could turn this on by default! Unfortunately many build systems can’t deal with extra warnings.
Andrew
Is it possible to enable this for makefile builds?
Hi chrisd,
There’s a post coming out tomorrow about how to use these tools outside of Visual Studio.
Andrew
See
I have made the recommended changed to several of the suggested changed and even with the changes I keep getting the same message. I think the suggestions are very good. However it does not do much good if the suggestions get repeated after the suggested change is implemented. For example the suggestion was to make const a variable that was assigned only once. Good Suggestion however even after making it const the suggestion remains on the next build. I am about to try and exit the p
Is the gsl library and the gsl.natvis included in this version of VC++?
The GSL is a separate library, like Boost or Zlib. You can get it from GitHub, or install it in VS with VCPkg:
This is a fantastic addition to Visual C++! Can we write and include our own rule sets as extention? | https://blogs.msdn.microsoft.com/vcblog/2017/08/11/c-core-guidelines-checker-in-visual-studio-2017/ | CC-MAIN-2017-34 | refinedweb | 1,242 | 53.41 |
In this series we are building a Twitter client for the Android platform using the Twitter4J library. In this tutorial we will prepare our user interface elements for the app and handle signing the user into Twitter to allow access to their account.
Step 1: Authorize the App to Access the User's Twitter Account
Before we can access the user's Twitter account, we need them to sign in and grant the app permission. Open the main Activity class for your application, creating it now if Eclipse did not generate it automatically when you started the project. Alter your class declaration opening line as follows, and change the name of the class to suit your own if necessary:
public class TwitNiceActivity extends Activity implements OnClickListener
The OnClickListener will detect various button clicks. You will need the following import statements added above your class declaration, although Eclipse may have added some automatically:
import android.app.Activity; import android.os.Bundle; import android.view.View.OnClickListener;
Inside the class, add the following instance variables:
/**developer account key for this app*/ public final static String TWIT_KEY = "your key"; /**developer secret for the app*/ public final static String TWIT_SECRET = "your secret"; /**app url*/ public final static String TWIT_URL = "tnice-android:///";
Alter the Key and Secret variables to store the values you copied from your Twitter Developer account last time. Notice that the URL is an extended version of the data element we added to the Manifest, so make sure to alter it if you used a different value there. Add the following additional instance variables for connecting to Twitter:
/**Twitter instance*/ private Twitter niceTwitter; /**request token for accessing user account*/ private RequestToken niceRequestToken; /**shared preferences to store user details*/ private SharedPreferences nicePrefs; //for error logging private String LOG_TAG = "TwitNiceActivity";//alter for your Activity name
When the user grants permission, we will add the resulting data to the Shared Preferences. Each time the app runs, it will check whether these details have been set. If so it will use them to fetch the user's timeline straight away. If the details have not been set it will prompt the user to sign in and grant permission. You will need the following import statements:
import twitter4j.Twitter; import twitter4j.auth.RequestToken; import android.content.SharedPreferences;
Find out if the user has already authorized the app
In the Activity onCreate method, after the call to the superclass method, add the following code:
//get the preferences for the app nicePrefs = getSharedPreferences("TwitNicePrefs", 0); //find out if the user preferences are set if(nicePrefs.getString("user_token", null)==null) { //no user preferences so prompt to sign in setContentView(R.layout.main); } else { //user preferences are set - get timeline setupTimeline(); }
Here we get a reference to the application Shared Preferences object to establish whether the user has already granted the app permission or not. The "user_token" preferences string is going to store the access token we use for accessing Twitter, so if it has already been set, we know the user has previously signed in for the app. If the preferences have not been set, we need to prompt the user to sign into Twitter, which we will do in the "if" statement - for the moment we simply set the main content view.
In the "else" block we take care of users who have already signed in and authorized the app. Here we call a helper method named "setupTimeline" which we will implement in the next tutorial.
Handle the First Run
Let's create our main layout, which we have set in the "if" statement. Normally Eclipse creates a file at "res/layout/main.xml" automatically, if not you can create it yourself by right-clicking the layout folder in the Package Explorer (or selecting it and then choosing the File menu), then choosing "New" and "File." Open the main layout file and enter the following XML code:
<LinearLayout xmlns: <TextView android: <TextView android: <Button android: </LinearLayout>
This is a LinearLayout with two text-fields and a button. The text-fields are simply informative, while the button will take the user to the Twitter sign-in Web page. The button has an ID attribute so that we can identify it in the Java code.
Now back to our onCreate method for the main app Activity to implement signing in first time users. You will need the following import:
import android.util.Log;
Inside the "if" block, after the line in which we set the main content view, add the following:
//get a twitter instance for authentication niceTwitter = new TwitterFactory().getInstance(); //pass developer key and secret niceTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
Here we create an instance of the Twitter class from the Twitter4J library, which we already declared as an instance variable. This class is required for pretty much everything we do with Twitter. To verify our credentials, we pass the Key and Secret from the developer interface where the app was registered, for both of which we created class constants. Next we need to get a request token from the Twitter object so that we can attempt to authorize the app for the user's account:
//try to get request token try { //get authentication request token niceRequestToken = niceTwitter.getOAuthRequestToken(TWIT_URL); } catch(TwitterException te) { Log.e(LOG_TAG, "TE " + te.getMessage()); }
We are here attempting to instantiate the request token for which we created an instance variable. The method can throw an exception, so we surround it in a try block and output an error message to the Android Log if the exception is thrown. Notice that the code uses the "LOG_TAG" constant we created - you can see the resulting messages in the Eclipse LogCat panel.
Send to Twitter
To finish the "if" block, set up a click listener for the sign-in button we included in our "main.xml" layout file:
//setup button for click listener Button signIn = (Button)findViewById(R.id.signin); signIn.setOnClickListener(this);
The click listener for the button is the Activity class itself, so we now need to implement the onClick method anywhere in the class file:
/** * Click listener handles sign in and tweet button presses */ public void onClick(View v) { //find view switch(v.getId()) { //sign in button pressed case R.id.signin: //take user to twitter authentication web page to allow app access to their twitter account String authURL = niceRequestToken.getAuthenticationURL(); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authURL))); break; //other listeners here default: break; } }
The method uses a switch statement to tailor what happens to particular button presses. We will be adding a case statement for another button later, but for the moment all we need is the sign-in process. The code retrieves the authentication URL from the Twitter request token object, then opens the page in the Web browser.
Don't worry too much about how these Twitter4J methods are implemented. This is simply the process you need to follow if you use the API. Not having to concern yourself with the implementation details of connecting to Twitter is one of the main benefits to using an external library.
Return From Sign-In
We need to handle what will happen when the user is returned to the app after signing into Twitter to authorize it. When the user signs in successfully, Twitter will return them along with some data to verify and facilitate the app's access to their account. The "onNewIntent" method will fire, so let's implement it now:
/* * onNewIntent fires when user returns from Twitter authentication Web page */ @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); //get the retrieved data Uri twitURI = intent.getData(); //make sure the url is correct if(twitURI!=null && twitURI.toString().startsWith(TWIT_URL)) { //is verifcation - get the returned data String oaVerifier = twitURI.getQueryParameter("oauth_verifier"); } }
The method retrieves the verification data from Twitter, which we will later use to access the user's tweets. So that we only need to carry out the sign-in process once, we store the required data in the application Shared Preferences. Still inside the "if" statement, add the following:
//attempt to retrieve access token try { //try to get an access token using the returned data from the verification page AccessToken accToken = niceTwitter.getOAuthAccessToken(niceRequestToken, oaVerifier); //add the token and secret to shared prefs for future reference nicePrefs.edit() .putString("user_token", accToken.getToken()) .putString("user_secret", accToken.getTokenSecret()) .commit(); //display the timeline setupTimeline(); } catch (TwitterException te) { Log.e(LOG_TAG, "Failed to get access token: " + te.getMessage()); }
This is another method that can cause an exception to be thrown. The code inside the try block first retrieves the Access Token from Twitter using the data returned from the Web page. Then it uses the Shared Preferences object to store the Token and Secret necessary for Twitter access. Finally, the code calls the method to display the timeline, which we have not yet implemented.
If you want to test the sign in process just now, provide the "setupTimeline" method, simply including a message output to the Log, for example:
private void setupTimeline() { Log.v(LOG_TAG, "setting up timeline"); }
We will implement the method fully in the following tutorials.
Step 2: Create the Application Layouts
Now that we have handled signing users in the first time they run the application, we can turn to the user interface for the app as it runs subsequently. We will be using various resources in the user interface design for this app, including drawables, colors, and layouts. The layout XML files will refer to drawable resources which we will create in the next step. Don't worry if Eclipse alerts you to errors because the resources are not yet present. When you create the layout files, simply notice the references to resources you still have to create.
The app is going to use four layout files, one of which ("main.xml") we have already created for the sign-in screen which only appears on first run. We also need layouts to define the appearance of the main timeline, the Tweet screen and each update within the timeline. In each layout file, you will notice that many of the elements have ID attributes. This is so that we can refer to these elements within the Java application code, particularly when handling user interaction.
Timeline
The timeline layout is going to be the main interface users see when they launch the app, after authorizing it. The home timeline shows the list of recent tweets from those accounts the user follows. At the top of the screen, the user will see a header and the Tweet button, for switching to the Tweet screen to send a tweet. The content of each update in the home timeline will be defined in a separate layout file, but in the timeline layout we will take care of the container for the list of updates as a whole.
Create a new file in your "res/layout" folder, with "timeline.xml" as the file-name. Open the new file and add the following outline, which we will extend:
<LinearLayout xmlns: <TableLayout xmlns: <TableRow> </TableRow> </TableLayout> <ListView android: </LinearLayout>
The View is defined by a LinearLayout. Inside this we have a TableLayout and a ListView. We will be adding elements inside the TableRow next. The ListView is going to hold the list of update tweets to display within the user's home timeline. The list will be populated with those tweets when the application executes. For the moment we simply define the View that will hold them.
Add content inside the TableLayout TableRow element:
<LinearLayout android:
This creates a header for the home timeline. The text "Home" is laid out next to a drawable resource named "home". Notice that the section also has a background which is another drawable resource named "homebg".
Next add the tweet button, still inside the TableRow but after the LinearLayout you just added:
<LinearLayout android: </LinearLayout>
As you can see, this is similar to the Home header, but in this case the View is going to function as a button - the LinearLayout has its "clickable" attribute set to true. The button will include the text "Tweet" displayed next to an image. When users click this button they will be taken to the Tweet screen.
At the moment when you choose the Graphical Layout tab for your timeline XML in Eclipse, you won't see much. Once we have created the drawables and the update layout file, it will look like this:
Since the content of the timeline is only built at runtime, you cannot really see what the interface will look like until you are able to run the app.
Update
We are going to use a layout file to model a single update within the home timeline. Create a new file in your layout directory, naming it "update.xml". Enter the following outline:
<LinearLayout xmlns: <ImageView android: <LinearLayout android: </LinearLayout> </LinearLayout>
The layout contains a section for the profile image of the account whose tweet is being displayed, then a section for the tweet content. Inside the second LinearLayout element we will add the tweet content and the buttons for retweeting/replying. Start with the tweet content:
<LinearLayout android: <TextView android: <TextView android: </LinearLayout> <TextView android:
Each tweet includes the screen name of the tweeting account, the time the tweet was sent, and the tweet itself. Each TextView has an ID attribute, as the Java code is going to map the incoming tweet data to these Views when the app runs. The final TextView, for the tweet text itself, has the "autoLink" attribute set so that users can click links in the tweets. The user screen name view is also clickable, so that users can browse to the profile page of each account in their timeline. Notice that these Views also include references to color resources we have not yet created.
Now let's add the retweet and reply buttons, after the TextView we just added:
<LinearLayout android: <Button android: <Button android: </LinearLayout>
Every tweet in the timeline is going to be accompanied by these buttons, each with a little text and a background. Here is a snapshot of a single update in the finished app.
Tweet
Now we turn to the other main screen in our app, the Tweet screen. Create another new file in your Layout folder, naming it "tweet.xml". Enter the following outline:
<LinearLayout xmlns: <TableLayout xmlns: <TableRow > <LinearLayout android: <LinearLayout android: </LinearLayout> </TableRow> </TableLayout> </LinearLayout>
We will add more elements after the TableLayout next. Don't worry about adding all of this code at once - if you compare it to the timeline layout above you'll see that it's almost identical. The top section with the Home header and Tweet button will appear similarly in both the home timeline and Tweet screens. Apart from some small cosmetic differences to distinguish the two, the main difference is that in the Tweet screen, the Home header functions as a button to take the user back to their home timeline, whereas in the timeline layout, the Tweet View functions as a button.
After the TableLayout, add the following:
<TextView android: <EditText android: <Button android:
This is the main content for the Tweet screen. A small amount of informative text precedes the editable text-field for the user to enter their tweet text, then we have a button for them to go ahead and send the tweet. Once we create our drawable resources, in the Graphical Layout tab for the tweet layout you will see something like this:
Step 3: Create the Application Drawables
Now let's create the visual elements in our interface, most of which we have already referred to in our layout resources. Some of our drawables will be defined in XML files and some will be created outside the application, using a graphic design or image editing program. You can of course alter any of the visual elements you like, but I would recommend starting with the steps outlined in this tutorial, then making changes once you understand how the various ingredients relate to one another.
Images
For this application we are using three images created outside Eclipse, for the app icon, the home timeline, and the tweet button. You can create your own versions of these if you like, or not bother using images at all if you prefer. The home timeline is a simple drawing, while the tweet button and app icon use the official Twitter resources, which also include retweet, reply and favorite icons.
When you have your drawables ready, copy them into your application workspace folder, in "res/drawables-*". Eclipse should have created three drawables folders in your project workspace, for low, medium, and high resolution devices. The images must be saved as "ic_launcher" for the icon, "home" and "tweet" for the buttons. Make sure each image is saved with the same name in each folder, e.g. the tweet image could be named "tweet.png" in all three folders, although the images in each folder are actually different sizes, to suit the different resolutions.
You may need to instruct Eclipse to refresh your workspace before your code can refer to the new images successfully. To do so, select the project in the Package Explorer, right-click or choose File, then Refresh.
Colors
Other than black, white, and gray, the app interface mainly uses two colors, shades of green and blue. Let's define these as color resources. In Eclipse, create a new file in the "res/values" directory named "colors.xml":
In the colors XML file, enter the following code to define the two main colors in the app:
<resources> <color name="control_one">#FF006699</color> <color name="control_two">#FF009933</color> <color name="control_one_opaque">#66006699</color> <color name="control_two_opaque">#66009933</color> </resources>
This code indicates two colors plus opaque versions of each. Now if you want to change the color scheme for the application buttons, you can do it in a single location.
Backgrounds
Finally, let's get our backgrounds created to complete the user interface design. We will run through each drawable file in turn, but remember that you need to copy every one into all three drawable folders in your app's resources directory.
Create a new file in your drawables folder(s) named "homebg.xml" with the following content:
<shape xmlns: <gradient android: <padding android: </shape>
This defines a simple drawable shape with padding and a gradient fill. If you look back at your timeline XML layout code, you will see this drawable referred to as the background for a LinearLayout.
Create another new file named "homebtnbg.xml" in your drawables with the following content:
<shape xmlns: <gradient android: <padding android: </shape>
This background is used for the Home button in the Tweet screen. Next create a file named "profilebg.xml" with the following content:
<shape xmlns: <gradient android: <padding android: <corners android: </shape>
This time we define rounded corners as well as padding and gradient fill. This background is for displaying behind the profile images in the timeline.
The final two drawables are slightly more complex. For the Tweet button and the buttons in each update (for replying or retweeting) we are going to define different appearances for selection states so that the buttons change in appearance when the user presses them. Create a file named "tweetbtnbg.xml" with the following content:
<selector xmlns: <item android: <shape xmlns: <gradient android: <stroke android: <padding android: <corners android: </shape> </item> <item> <shape xmlns: <gradient android: <stroke android: <padding android: <corners android: </shape> </item> </selector>
This code defines two slightly different shapes, one for when the button is pressed. The only difference between them is in the colors, which are defined as the color resources we created. Finally, create a similar file named "updatebtnbg.xml" with the following content:
<selector xmlns: <item android: <shape xmlns: <gradient android: <padding android: <corners android: </shape> </item> <item> <shape xmlns: <gradient android: <padding android: <corners android: </shape> </item> </selector>
Once you have these copied into each of your drawables folders, you can choose to alter them to suit different screen sizes if you wish. Your drawable resources should look something like this, with all files in all three folders:
Eclipse should now stop displaying error messages for your layout files, as all referenced resources are present.
Now our user interface design is complete! In the next tutorial we will create a database to store the update tweets, then use an Adapter to map these updates to the View elements so that the user can see them.
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/creating-a-twitter-client-for-android-building-the-interface--pre-29577 | CC-MAIN-2018-13 | refinedweb | 3,431 | 59.43 |
Introducing enRoute 1.0 – the new OSGi Framework
Version 1.0 of OSGi enRoute framework was launched in September 2015. enRoute inventor and OSGi mastermind Peter Kriens explains the project in a two-part article..
The following sections provide details about what OSGi enRoute offers today and our planned enhancements, as well as an excellent introduction to OSGi best practices.
Background
When Ericsson sent me to Raleigh NC in November 1998 I had no idea what I was getting myself into. Open source was in its infancy, embedded meant 256K, WiFi was a glimmer in someone’s eyes, Mark Zuckerberg was only 14 and only mean to girls in his high school, Apple introduced the iMac, Windows 95 was dominant, command lines were on their way out, and a ‘cloud design’ was only used in a derogatory sense. And something almost unimaginable for the youngest readers: there were no smartphones!
That day in Raleigh we got together with Ericsson, IBM, Sun and other major companies to talk about standards for Home Gateways. Small computers that were soon (!) going to be in everybody’s home, operated by the telcos. At least that is what they told us.
The rather violent dot com implosion in 2001 (right at the time that OSGi v1 was released, though I do not think we were to blame), basically removed the motivation for continuing to develop these specifications. However, the OSGi Alliance founders had discovered other usages for the specifications and still wanted to continue the technical work because of its quality. The OSGi specifications have rarely taken shortcuts. In almost all situations we chose to do it right; unlike some other specifications that shall not be named. So we went on and released version 2 and 3 over the following years.
Some people will now indicate that the success of OSGi in the enterprise world was mixed. Though all the major application servers adopted OSGi, the bundle never replaced the WAR. There are reasons for this. Open source definitely destructed the economic landscape that the founders of OSGi were used to; which changed their incentives. It took time to embrace open source and collaborate with them, and even today specifications and open source do not seem to be completely comfortable with each other.
There was also a technical reason. The fact that the specification still exists today is largely because we were too far ahead when we started. (Several of us came from research, not development.) To show exactly how close we were to the edge: At Ericsson Research we got Java and OSGi’s predecessor running on an 8Mb Linux box. Cool, except for this small detail: there was no space for the applications. Same happened as far as dynamics, modularity, and services were concerned. Very cool but uncomfortably far out for developers in the trenches at the time.
But the most important reason was probably an impedance mismatch. When OSGi wandered into the enterprise space it bumped right into Java Enterprise Edition (EE). While Java EE had lots of domain APIs which OSGi lacked, it did not have two important architectural concepts that OSGi actually did have. We thought it was a match made in heaven.
The obvious concept that OSGi could provide was modularity. OSGi provided strong encapsulation and control of the class path. Java EE applications generally ended up on long and winding class paths that were utterly unprotected, hard to get right, and mostly brittle. OSGi bundles provide solid modules that are properly fenced off and enough metadata to verify consistency before anything runs. This part is loved by almost all Java developers when they first learn of it. Even fervent OSGi haters have to admit that the class loader model is outstanding.
However, the disadvantage of strong modules is that they are, eh, strong. Using the modules in classic Java environments exposed the fact that most applications were (ab)using class loaders to create their own extension/wiring mechanisms. (And Java already had a large number of class loader hack variations built-in for this purpose.)
SEE ALSO: OSGi enRoute – a new framework for OSGi applications
A bit of background about this. Object-oriented technologies became prevalent in the early 90s. They were initially highly successful, though the promise of reuse was not really materialized due to coupling. In real life systems almost any object was transitively reachable from any other object. Java’s main innovation, interfaces, changed this because interfaces broke the coupling between the implementer and the client. Now even though they were not dependent on each other, they could still be used separately in a type safe way. The interface was only the contract.
The interface concept was a highly needed and very desirable solution but it did create a new problem. Since the implementation and client were no longer coupled, someone had to wire them together in runtime. The client could not just ‘new’ the implementation class because this would recreate the coupling. This created a cotton industry of solutions in Java based on class loaders. First there were properties, then we started looking for class name patterns, then we got XML with Spring, and one day Java 6 offered the service loader and I guess today we have CDI with annotations.
Unfortunately, all these tricks were not very modular as OSGi was telling people with Class Not Found Exceptions. If someone is telling you that your baby is ugly then it is a lot more comfortable to blame the internet than to modify your code to use a proper solution. The fact that modularizing your application is hard work is clearly not well understood. Too often OSGi is unjustly blamed for this.
As I said earlier, OSGi provided two missing pieces to the Java EE architecture. The second part was the OSGi service model. This service model was designed to solve the runtime wiring problem in a truly modular way. Truly because it created a peer-to-peer broker model. Services are offered by the implementers and are bound to the clients when they request such a service. However, services were even less understood than the modular story and thus ignored. The fact that services were dynamic was unfortunately not recognized as an asset but a seen as a potential risk.
Working with many of the major players we wrote specifications that mapped popular Java EE specifications to OSGi. This made us run into the problem that these specifications were a bit awkward. Things that would translate to a very simple Service API had to be done in a way that just looked not completely right in OSGi. There is clearly an impedance mismatch.
So we had a very good model with modules and services but in practice the step was too big for most enterprise developers to make. The result was that Java EE developed many APIs that were just not very cohesive and did not properly support modularity.
Here is an example. OSGi specifications strictly separate configuration and API. It turns out that the API needed to collaborate is actually quite small in most cases. However, the configuration needed to set each side up can be quite extensive. Let’s say you need to talk to a queue. In a classic app the producer and consumer need to agree on a name and somehow tell the queue manager what name to use. In OSGi you can use a service that is anonymously used by both parties; all the details are in the configuration. Since configuration management is standardized, this tends to work very well in OSGi. It still frequently amazes me how this can simplify modules and services while at the same time making each of them much more reusable.
In 2012 I decided to take a sabbatical. After editing the specifications for so many years while so many things were changing in the field I felt the need to go back to the trenches. I missed the deep knowledge that you get when you actually use a technology instead of just reading. What I also missed was a bit of playing during the weekend.
So during my sabbatical I decided to build a website: jpm4j.org. I took the OSGi Extreme approach. Everything had to be properly service-based and leverage OSGi to the hilt. To be honest, I wanted to prove to myself that I had not been talking nonsense during all those conferences where I said that OSGi is an awesome development environment.
The message was mixed. I definitely proved to myself that OSGi is awesome, especially the service model! (Which I guess the web-based microservices are helping to prove now as well since that model is based on the same concept; OSGi services are just magnitudes lighter weight).
However, I found that a number of specifications were missing which I had to develop from scratch. There were also many other bundles that did not seem to be available anywhere
I also found that building up a tool chain and runtime environment was not trivial. It definitely made me understand the challenges people faced when they wanted to get started with OSGi.
The OSGi Alliance had been discussing ways in which they could improve the developer experience for a long time. So when I shared my experiences with them it was agreed to put together OSGi enRoute, with the goal of making it easier to get started with OSGi.
OSGi enRoute
Today there is an incredibly elegant programming model in OSGi and amazing tooling available but unfortunately when you search the web you are confronted with a graveyard of dead tutorials and stale blogs. And there is a scary amount of bad advice out there. The intent of OSGi enRoute is to make it really easy to get started with OSGi in the right way.
In the following sections we describe OSGi enRoute from the different aspects that it encompasses.
Components
The OSGi enRoute programming model is based on components. Ok, that is a very generic word. A component is in this context a Declarative Services component.
In practice this means that a component is a plain old Java object with some annotations on it. At first sight these annotations resemble CDI and they do have a similar purpose. However, OSGi services embrace dynamic dependencies and have built-in configuration support. It turns out that these two dimensions make a lot of patterns in software easier to implement than working in a statically wired world.
Here is an example. A simple component that provides a Speaker service, gets configured through Configuration Admin, and (dynamically) depends on the Event Admin service, could look like this:
@Component public class MyComponent implements Speaker { @Reference EventAdmin eventAdmin; interface @Config { int port(); String host(); } @Activate void start(Config config) { } }
Components are quite liberating because they do not require central registration. You want to start a listener on a socket? Just create an immediate component and you can start your server. Need to wait until some important services are ready? Just add a reference to these services.
Components are cheap, almost as cheap as objects. There are systems that have hundreds of thousands of components. If you’ve never used services then these new dimensions that are provided by OSGi components are hard to explain.You’ll have to trust me that they are really worth many times their small cost.
Components are the principal part of a design in OSGi enRoute. They abstract some part of the problem domain and communicate with other components through services. Components often have a set of associated objects that act as helpers which are developed with standard Java mechanisms. In practice, a significant number of these classes can stay package private.
Services
Components, in general, register a service. A service is named by its interface and has a number of properties that describe it. However, don’t confuse a service with only an object with an interface. A service has a contract. In OSGi, that contract is specified in a package. We need a package because in almost all cases there is a need for helper objects and additional interfaces although good contracts try to limit the number by keeping the packages highly cohesive.
Services have been part of OSGi since 1998. A service is beneficial because it concentrates the coupling between different parties on a single point with a set of well defined operations. Both sides of the fence can evolve independently as long as their contract is obeyed. It is hard to overestimate the benefit of this indirection for larger systems since complexity tends to be exponential to the number of connections a module has. Service contracts do for modules what interfaces did for classes: Solve the transitive coupling problem.
Service Oriented Architecture’s were a big trend some years ago; today microservices are the new fashion. These services are web services; they require a communication protocol and are mute about a lot of important things like for example the lifecycle of the service. In contrast OSGi µservices are extremely lightweight, fully dynamic, and can be fully lifecycle aware. Though web services, microservices, and µservices share the same benefits of the service model, it is only the OSGi model that can be transparently mapped to web or microservices.
Services are the architectural primitive of OSGi designs. The service diagram provides a very high level overview of an architecture, it is almost an architecture reified. To document designs, we developed over time the following diagramming technique:
Distributed OSGi takes the service model and makes it possible to call services in other frameworks. A topology manager discovers services in other frameworks and then based on its policy registers a proxy to the remote service in the local registry. Since services are dynamic, the topology manager can also unregister these services when it loses the connection to the remote framework. This is almost completely transparent. However, it does require that services are designed with distribution in mind. Before distributed OSGi was available, all OSGi service designs used properly encapsulated objects. However, those very object oriented objects are quite difficult to deserialize/unmarshal since the implementation classes are private. (Rule 1 of modularity, hide implementations.) Since distributed OSGi became a major force services have been designed with serialization in mind. The most popular pattern today is to use DTOs in the API. DTOs are objects with public fields that use a small set of Java types, including other DTOs. DTOs are a corner stone of OSGi enRoute.
Services are reified in runtime. As shown with the Declarative Services example it is trivial to use services to implement software patterns. One of the most popular patterns is the white board pattern, which is a corner stone of all modern OSGi service APIs. In classic Java it is common to get some server object and then register a listener to that object. For example in Android you must first get the Location Manager and then register a Location Listener to get the GPS positions. And if you are a clean programmer, you should of course also cleanup when your code is deactivated.
We initially copied this listener pattern in the OSGi Http Service and Log Service but soon realized that just registering the Location Listener in the service registry would suffice. An anonymous Location Manager could then easily discover those Location Listener services. Using this pattern often halves the number of types in a service contract.
Reifying the services also gives another huge advantage: visualization. Since the services are the joints of an application, a visualization of the services in a framework provides a very high level overview of the application’s architecture. OSGi enRoute contains the XRay Apache Felix Web Console plugin to show the services in the framework.
Dynamism
The earlier example component was fully dynamic. It gets activated when the Event Admin service is registered and is deactivated when it goes away. As you can see, the dynamics do not cost anything since they are not visible in most cases. That said, because the component is dynamic we can update the configuration anytime and do not have to worry about the initialization sequence since this is handled with the same dynamic mechanism.
Dynamism is crucial in an IoT world where the software interacts with the real world. Dynamism seems not that important in the enterprise world since in a single computer process everything lives and dies together. (Then again, in OSGi there is no extra cost for the dynamics.) However, dynamics are crucial in a distributed world. Most enterprise software goes out of its way to ignore these dynamics generally resulting in brittle systems. OSGi embraces failure because it embraced the dynamics from the beginning. For example, imagine you have a service that is implemented on a number of other systems but you want to return the result of the fastest invocation.
@Component(property=“service.ranking=1000”) public class MyComponent implements Foo { @Reference volatile List<Foo> foos= new CopyOnWriteArrayList<>(); @Override Promise<String> foo(int n) { Deferred<String> deferred = new Deferred(); AtomicBoolean first = new AtomicBoolean(false); for ( Foo foo : foos ) { if ( foo == this ) continue; foo.foo(n).then( (p)-> { if (first.getAndSet(true)==false) deferred.resolve( p.getValue() ); return null; }); } return deferred.getPromise(); }
This surprisingly small piece of code is actually complete. The foos list is automatically provisioned with the matching services from the OSGi service registry by the Declarative Services runtime. So whenever the payload method is called, we try the latest set of services that are visible.
Packaging
Components cannot be directly deployed in OSGi, they need to be packaged in bundles. Bundles are the modules of OSGi. Bundles contain Java packages (basically folders in a JAR/ZIP file). The manifest in this JAR file describes what packages from that bundle are exported and what packages are imported. Packages not listed are private; they are not directly accessible by other bundles.
There is only one mandatory header in OSGi but over time we’ve added additional manifest headers to provide more metadata. These are useful in some cases but they are all optional. We’ve tried to make the bundles as self describing as possible in a single ZIP file.
Bundles are reified in runtime. Over time this gave rise to the extender pattern. Since bundles can be discovered it is possible to look into a bundle to see if you recognize something. If so, you can take data from the bundle and do your thing. The intent of this pattern is to allow bundles to only provide the minimum and leave the boilerplate to another bundle. Since the observer can observe the complete lifecycle, whatever functionality it creates on behalf of that bundle, it can properly tear it down or uninstall it.
The archetypical example of the extender board pattern is Declarative Services. The runtime of Declarative Services listens to bundles that become active. It then checks if they have any Declarative Service components by looking at the manifest. If so, they read the corresponding XML and orchestrate the component accordingly. If the bundle is stopped, all components are deactivated.
Another example is the Configurator provided by OSGi enRoute. This is an extender that reads configuration data from bundles. Just activating a bundle will make the Configurator read the configuration data from the /configuration folder in the bundle’s JAR. This configuration is then installed via the Configuration Admin service.
There is even a special Bundle Tracker utility to simplify using this pattern.
Capabilities & Requirements
After we started with an initial dependency model based on packages only, some parties (that shall not be named here) more or less forced us to add bundles and fragments as additional dependency types. Let’s call these package, bundle, fragments semantic dependencies. Around 2005 we started to develop a repository model where these semantic dependencies had to be well understood to provide the proper artifacts on a request. Using these semantic dependencies felt very awkward because we also needed to model additional dependencies like the version of the VM, the operating system, and the hardware. Thinking further, it became quite clear that the things we wanted to depend on were basically open ended.
We therefore developed a language to represent capabilities and requirements. The language is powerful and surprisingly simple. A capability consists of a namespace that defines the type of the capability and a set of properties (key value pairs). For example:
namespace = ‘osgi.wiring.package’ { osgi.wiring.package=com.example.foo,version=1.2.3 }
A requirement consists of a namespace and an OSGi filter expression. For example:
namespace = ‘osgi.wiring.package’ (osgi.wiring.package=com.example.foo)
Though the language to express capabilities and requirements looks very simple, it is surprisingly powerful. Mostly because OSGi filters are quite complete; they can have any depth of subexpressions and support wildcards and magnitude comparisons.
This work on repositories was fed back into the core specifications and today all the OSGi framework implementations are based on this Capability model. Using the capabilities and requirements the frameworks wire the bundles together; the wires are reified in the API so they can be used in runtime to find out what a bundle a is wired to.
For example, web resources are bundles that contain resources like javascript, css, html, images, etc. OSGi enRoute provides a web resource namespace. This allows a web resource bundle to provide a capability that can then be required by the application bundle. The web resources are then included in the runtime so that we always have the proper version installed.
In OSGi enRoute the Capability model is one of the architectural corner stones. An OSGi enRoute bundle should fully describe the capabilities it provides and requires.
To make this as easy and natural for the Java developer as possible we’ve developed a lot of support in bnd. This tool analyzes the byte codes to automatically create the requirements on the JVM and the imported packages. We’ve also added support in bnd for creating requirements with annotations.
For example, a specific web resource can design an annotation that requires a version or version range of that web resource. This allows the Java developer that relies on that web resource to annotate a class with a simple annotation and be assured that its bundle has the proper requirement. An annotation to require the Bootstrap CSS web resource will automatically add the necessary Require-Capability header in the bundle’s manifest.
@RequireBootstrapWebResource(resource = “css/bootstrap.css")
Deployment
There two types of deployments. The most common type, which is kind of exclusive to the Java world, is the classic WAR model. The application is intended to be deployed in a Java EE Application server that will cherish and nurture the application. The application WAR can rely on the environment to provide it with a very rich and extensive API but must bring any additional dependencies.
The other deploy type is the executable JAR where the only dependency is a proper JVM. In that case the JAR must contain all the dependencies, including an OSGi Framework. Since the trend is towards more self contained units (see for example Docker), OSGi enRoute primarily focuses on the executable JAR. However, we will soon provide exports to most popular application servers that support OSGi.
In a component system the focus is to make the components as reusable, and thus uncoupled, as possible. Java developers intuitively feel this in their guts whenever they use interfaces instead of classes; life is so much easier when you can easily mock classes and use your code in different applications. Decoupling is liberating.
Couplings are, however, like balloons. You can press the air out of one place only for it to go somewhere else. Very uncoupled components shift part of the problem to the assembly phase where a set of components must be selected to form the application. This is a really hard problem since it must ensure that each component is satisfied in the runtime and will not have its assumptions violated.
For example, maven uses transitive dependencies to calculate a class path. However, transitive dependencies can (and usually do) have multiple versions. Ordering in such class paths can make a difference in runtime behavior. Worst of all, the only dependency type maven uses is the module name. This mostly puts the onus on the developers to understand what they actually get on their class path. With todays large reuse of software this can mean understanding the implications of hundreds to thousands of components.
Since we have a fine grained capability model in OSGi, we can actually largely automate this process. Given a set of initial requirements, a resolver can calculate the minimal set of bundles needed to satisfy the aggregated requirements of that set.
The second part of the article will be published on our portal soon. Stay tuned! | https://jaxenter.com/introducing-enroute-1-0-new-osgi-framework-123466.html | CC-MAIN-2017-34 | refinedweb | 4,143 | 55.24 |
OPEN_HASH(3) BSD Programmer's Manual OPEN_HASH(3)
ohash_init, ohash_delete, ohash_lookup_interval, ohash_lookup_memory, ohash_find, ohash_remove, ohash_insert, ohash_first, ohash_next, ohash_entries - light-weight open hashing
#include <sys/types.h> #include <stddef.h> #include <ohash.h> void ohash_init(struct ohash *h, unsigned int size, struct ohash_info *info); void ohash_delete(struct ohash *h); unsigned int ohash_lookup_interval(struct ohash *h, const char *start, const char *end, u_int32_t hv); unsigned int ohash_lookup_memory(struct ohash *h, const char *k, size_t s, u_int32_t hv); void * ohash_find(struct ohash *h, unsigned int i); void * ohash_remove(struct ohash *h, unsigned int i); void * ohash_insert(struct ohash *h, unsigned int i, void *p); void * ohash_first(struct ohash *h, unsigned int *i); void * ohash_next(struct ohash *h, unsigned int *i); unsigned int ohash_entries(struct ohash *h);
These functions have been designed as a fast, extensible alternative to the usual hash table functions. They provide storage and retrieval of records indexed by keys, where a key is a contiguous sequence of bytes at a fixed position in each record. Keys can either be NUL-terminated strings or fixed-size memory areas. All functions take a pointer to an ohash structure as the h function argument. Storage for this structure should be provided by user code. ohash_init() initializes the table to store roughly 2 to the power size elements. info holds the position of the key in each record, and two pointers to calloc(3) and free(3)-like functions, to use for managing the table internal storage. ohash_delete() frees storage internal to h. Elements themselves should be freed by the user first, using for instance ohash_first() and ohash_next(). ohash_lookup_interval() and ohash_lookup_memory() are the basic look-up element functions. The hashing function result is provided by the user as hv. These return a "slot" in the ohash table h, to be used with ohash_find(), ohash_insert(), or ohash_remove(). This slot is only valid up to the next call to ohash_insert() or ohash_remove(). ohash_lookup_interval() handles string-like keys. ohash_lookup_interval() assumes the key is the interval between start and end, exclusive, though the actual elements stored in the table should only contain NUL- terminated keys. ohash_lookup_memory() assumes the key is the memory area starting at k of size s. All bytes are significant in key comparison. ohash_find() retrieves an element from a slot i returned by the ohash_lookup*() functions. It returns NULL if the slot is empty. ohash_insert() inserts a new element p at slot i. Slot i must be empty and element p must have a key corresponding to the ohash_lookup*() call. ohash_remove() removes the element at slot i. It returns the removed ele- ment, for user code to dispose of, or NULL if the slot was empty. ohash_first() and ohash_next() can be used to access all elements in an ohash table, like this: for (n = ohash_first(h, &i); n != NULL; n = ohash_next(h, &i)) do_something_with(n); i points to an auxiliary unsigned integer used to record the current po- sition in the ohash table. Those functions are safe to use even while en- tries are added to/removed from the table, but in such a case they don't guarantee that new entries will be returned. As a special case, they can safely be used to free elements in the table. ohash_entries() returns the number of elements in the hash table.
Only ohash_init(), ohash_insert(), ohash_remove() and ohash_delete() may call the user-supplied memory functions. It is the responsibility of the user memory allocation code to verify that those calls did not fail. If memory allocation fails, ohash_init() returns a useless hash table. ohash_insert() and ohash_remove() still perform the requested operation, but the returned table should be considered read-only. It can still be accessed by ohash_lookup*(), ohash_find(), ohash_first() and ohash_next() to dump relevant information to disk before aborting.
The open hashing functions are not thread-safe by design. In particular, in a threaded environment, there is no guarantee that a "slot" will not move between a ohash_lookup*() and a ohash_find(), ohash_insert() or ohash_remove() call. Multi-threaded applications should explicitly protect ohash table access.
ohash_interval(3) Donald E. Knuth, The Art of Computer Programming, Vol. 3, pp 506-550, 1973.
Those functions are completely non-standard and should be avoided in portable programs.
Those functions were designed and written for OpenBSD make(1) by Marc Espie in 1999. MirOS BSD #10-current November. | http://mirbsd.mirsolutions.de/htman/sparc/man3/ohash_next.htm | crawl-003 | refinedweb | 716 | 64.71 |
It’s very typical for a program to have to walk a file tree. In Recursion Example — Walking a file tree, I demonstrated how to use recursion to traverse a file system. Although it’s totally possible to walk through a file system in that fashion, it’s less than ideal because Python provides os.walk for this purpose.
The following script is a modified example borrowed from Programming Python: Powerful Object-Oriented Programming
that demonstrates how to traverse a file system using os.walk.
import os import sys def lister(root): # os.walk returns a tuple with the current_folder, a list of sub_folders, # and a list of files in the current_folder for (current_folder, sub_folders, files) in os.walk(root): print('[' + current_folder + ']') for sub_folder in sub_folders: # Unix uses / as path separators, while Windows uses \ # If we use os.path.join, we don't need to worry about which # path separator to use since os.path.join tracks that for us. path = os.path.join(current_folder, sub_folder) print('\t' + path) for file in files: path = os.path.join(current_folder, file) print('\t' + path) if __name__ == '__main__': lister(sys.argv[1])
When run, this code prints out all of the files and directories starting at the specified root folder.
Explanation
os.walk
The os.walk function does the work of traversing a file system. The function generates a tuple with three fields. The first field is the current directory that os.walk is processing. The second field is a list of sub folders found in the current folder and the last field is a list of files found in the current folder.
Combining os.walk with a for loop is a very common technique (shown on line 8). The loop continues to iterate until os.walk finishes walking through the file system. The tuple declared in the for loop is updated on each iteration of the loop, providing developers with all of the information needed to process the contents of the directory.
os.path.join
Line 15 shows an example of using os.path.join to assemble a full path to a target folder or file. It’s import to use os.path.join to assemble file paths because Unix-like system use ‘/’ to separate file paths, while Windows systems use ‘\’. Tracking the path separator could be tedious work since it requires making a determination about which operating system is running the script. That’s not very ideal so Python provides os.path.join to take care of such work. As long as os.path.join is used, the assembled file paths will use the proper path separator for the os.
References
Lutz, Mark. Programming Python. Beijing, OReilly, 2013. | https://stonesoupprogramming.com/2017/08/25/python-os-walk/ | CC-MAIN-2022-05 | refinedweb | 447 | 59.4 |
Hi I'm trying to add a DLL reference to my project, actually I want to communicate with microchip called MCP2210 that is supported with dll file used in Visual Studio projects. The problem that after adding that dll file to my project through MonoDevelop then I should add "using MCP2210" (based on their instructions in Microchip website) I always get the
the following error: error CS0246: The type or namespace name1 alreadyFoundAssemblies, System.String[] allAssemblyPaths, System.String[] foldersToSearch, System.Collections.Generic.Dictionary`2 cache, BuildTarget target) (at C:/BuildAgent/work/d63dfc6385190b60/Editor/Mono/AssemblyHelper.cs:137) UnityEditor.AssemblyHelper.AddReferencedAssembliesRecurse (System.String assemblyPath, System.Collections.Generic.List`1 alreadyFoundAssemblies, System.String[] allAssemblyPaths, System.String[] foldersToSearch, System.Collections.Generic.Dictionary`2 cache, BuildTarget target) (at C:/BuildAgent/work/d63dfc6385190b60/Editor/Mono/AssemblyHelper.cs:140) UnityEditor.AssemblyHelper.FindAssembliesReferencedBy (System.String[] paths, System.String[] foldersToSearch, BuildTarget target) (at C:/BuildAgent/work/d63dfc6385190b60/Editor/Mono/AssemblyHelper.cs:172) UnityEditor.BuildPlayerWindow:BuildPlayerAndRun().
(by the way "USBDLLCLASS" is the name of the new dll file created by vs, and "MCP2210DLL-M" is the name of the dll file that supported by microchip for vs projects.(Iam using csharp in unity)).
knowing that I re-added the both dll references to Mono-Develop and I pasted the dll references in new folder inside the assets folder called Plugins!! can anyone help me with this?.
I know that I didn't add any script with the question cause I think it is not related to that!! Thanks in Advance
Well, is the DLL you've added a managed .net assembly or is it a real native code DLL? To be able to use native code DLLs you need unity pro for standalone builds.
How does the api of the DLL look like?
I used microchip pic controllers a lot in the past, but I never used a library from mc.
Usually you don't need to manually add DLL references in mono develop since unity recreates the project every time something changes. If it's à managed assembly you should be able to use the imported namespace with using. If it's a native code DLL you should have some function definitions with DllImport attribute
It could be that your dll has a reference that is not included in Unity. You may need to add the referenced dll as well as your own. Also make sure your dll is using .Net 3.5 or lower, a .Net 4 dll wont work :(
Its managed DLL file, even though I still get the first error where unity think that there is a directive missing. BTY, I'm using a DLL file which support .net 2.0 or higher based on microchip instruction.
Answer by luayahdab
·
Apr 27, 2015 at 01:28 AM
I solved the problem!! I added the DLL file to the root of unity if this directory C:\Program Files (x86)\Unity\Editor, after building the game I added the same file to the folder called mono .....I didn't get what i need till this moment but at least that error doesn't appear anymore
I am having the same problem. How exactly did you solve it? You just put MCP2210-M-dotNet2.dll in the editor directory and then Unity detected it automatically and you could write "using MCP2210;"?
Answer by RKSandswept
·
Jan 28, 2016 at 03:44 PM
Some steps to getting a C++ dll into Unity on Windows:
Make the Visual Studio project
Make a visual studio DLL project. This is the version of projects where no .exe is generated.
Write your code. Get it to build and get it debugged.
Build it correctly
Unity has 2 version, x86 (32 bit) and x64 (64 bit) you need to build the correct version
In the editor a debug build will work. On your end deployment machine, such as a gamer's PC they may only have the Visual studio runtime, so debug will not work. So in the end you MUST have a release version of the DLL.
Deploying - You must put the dll file in the correct place. The best is in Plugins directory under Assets.
Add the dll to you Assets folder in Unity Editor. This way you can set any special settings, and it bets bundled up when you do a release build.
Make sure the visual studio runtime gets installed. If your game is on Steam then you need to include the VS runtime as one of the required parts in the application setup screens in Steam. I usualy include both x86 and x64 runtimes but that may not be needed depeding on what your C++ code is doing.
Make the C# bridge from the C++
Make a C# class that is ALL static public functions.
Bind all the methods in your C++ dll to declarations in C#
Make any other helper code that is also static. Remember, static functions are in effect global singletons.
The declaration of a function in C# from the C++ dll might look like this...
public class CustomSerialBridge {
public const string LibFile = "CustomSerial";
[DllImport(LibFile)]
public static extern void VS_InitVoidSerial();
... etc...
}
About the DLL name
It appears that the ".dll" does not need to be on the end but can be.
Debugging
So you dll won't load. Possible problems...
Not in a findable place. Maybe not in the Plugins directory? You can also put the dll in the same directory as the .exe for your game, but that is harder to deploy correctly.
Typo in the dll name?
Not correctly 32 bit or 64 bit to match Unity?
Your dll is Debug and should be Release for releases to outside gamers? If it works fine on your machine in the debugger, but not on people's machies that bought your game, this might be why.
Not included in Unity so it gets deployed. This would show up as the dll not being in the Plugins directory in your deployment.
Missing other dependant dlls? Maybe your DLL depends on some other dll that is not getting included. Since Unity does not give meaningful error messages you need to get better error messages. One good way to do this is to make a completely separate C++ project, console application that loads your dll and calls one method in it. Then when it fails you get much better indication as to why. Run the resulting .exe in the same folder as you .dll and see what happens. If the missing DLL is VCRUNTIME140D.dll or some such with that 'd' just before the '.dll' then it means your dll is Debug instead of Release.
Sample code...
#include "stdafx.h"
#include <stdio.h>
#include <Windows.h>
int main()
{
printf("Custom Serial test");
HMODULE libHandle;
if ((libHandle = LoadLibrary(TEXT("CustomSerial.dll"))) == NULL)
{
printf("load failed: CustomSerial.dll\n");
printf("%d\n", GetLastError());
getchar();
return 1;
}
printf("Load DLL ok");
if (GetProcAddress(libHandle, "VS_InitVoidSerial") == NULL)
{
printf("VS_InitVoidSerial failed\n");
printf("%d\n", GetLastError());
getchar();
return 1;
}
printf("Done.");
getchar();
return 0;
}
Blah, crappy code formatting in this forum application. You need to include Window.h stdio.h stdafx.h
As last resort go get the depends progam off the net and run it on your dll to see what might be missing.
thank you so much! I was checking for like hours why my DLL loaded in the editor but not in exe. Turns out the DLL was meant for x64 so the only problem was that the build was x86... I am very glad I came across your troubleshooting list. I think this should be included in Unity.
Why can't I build Web Player in Unity while I have no problems with building standalone versions?
2
Answers
How to set unity for finding the c# dll?
1
Answer
How to debug c++ dll code
4
Answers
Unity 3d C++ run time error
0
Answers
Webplayer includes some DLL's for no apparent reason
1
Answer | https://answers.unity.com/questions/890902/add-dll-reference.html | CC-MAIN-2018-43 | refinedweb | 1,326 | 67.15 |
Introduction: ESP8266 + Confused.com Brian Toy Robot
I thought it would be fun to add an ESP8266 to a Brian toy robot from confused.com to play the voice samples that are usually played when pressing the confused.com button on the front of the toy.
The ESP8266 will be powered by a single cell lipo that I got with a quad copter, but everything for this build should be pretty easy to get your hands on.
Step 1: What You Will Need
You will need the follow to make this Instructable:
- confused.com toy robot
- esp8266 board
- relay
- vero board
- vero board pins or PC fan headers
- dupont socket headers
- 3.7v single cell lipo battery
- toggle switch to switch the esp8266 on and off
- short wires
- solder
- soldering iron
- wire strippers
- wire cutters
- screw driver
- drill with drill bit to make hole for toggle switch
You could do this same thing with any toy that speaks if there was room inside it for the extra bits. This robot has a very large empty bottom half which can hold all the extra electronics with ease.
Step 2: Take the Robot Apart and Connect the Wires
The first thing to do is to take the robot apart and solder two wires onto where the button is pressing again the PCB.
The robot is held together with a few screws in the top and bottom parts.
Once the robot is apart you can undo the two screws holding the ball joint in place, so that the bottom of the robot comes away from the top.
I then soldered the two wires onto the PCB. I did this with the board still screwed into the robot as it kept the board still.
One wire is connected to a switch pin labelled sw1 and the other is on a pad on the PCB right next to the blobbed chip.
Step 3: Feed the Wires Into the Bottom of the Robot
I made two little holes in the top of the base of the robot to feed the wires through from the PCB into the bottom of the robot where the esp8266, relay and lipo will be.
I used my soldering iron tip to do this, it made a bit of a mess of the job and also of my soldering iron, but I cleaned the tip up quite well and its a pretty old tip that needs replacing anyway really.
If you want a nicer way of getting the wires through, use a small drill to make two holes into the top of the base of the robot instead.
Feed the two wire into the base, and then make a small hole / slot in the top of the robot on one side (I did it on the right hand side when looking at the robot) and push the cables into the hole / slot - again I did this with my soldering iron.
Step 4: Screw the Robot Back Together
I then screwed the ball join back together and also screwed the top of the robot back together too - fitting the head back in at the same time.
The bottom half I left unscrewed and with the front and wheels still left out so that I've got room to work and install the extra electronics.
Step 5: ESP8266 With Relay
Next we need to build the ESP8266 relay, as I'm using a NodeMCU Devkit for this I found that you also need a few other bits of electronics to switch the relay on and off. I dont know if this is because my relay isn't very good or if this will happen for everyone, but its pretty simple to wire up.
I first set this out on a breadboard to make sure it would work. Then I moved this onto the vero board.
For the circuit that I used you can see this in my other instructable :
I've used dupont header pins on the vero board so that the ESP8266 can be removed at a later date if needed.
I've also used old PC fan headers for the power to the ESP8266 and for connecting the relay to the vero board, but this is only because I have loads of these and don't believe in soldering wires straight to the vero board. When I do run out of these fan headers I'll go back to using vero pins.
Step 6: Install ESP8266, Relay, Battery and Toggle Switch Into the Robot
This is pretty straight forward, you just need to get everything inside. It took a bit of fiddling to get everything to stay in but once its all screwed back together nothing will fall out anyway.
Step 7: Sketch for the ESP8266 and Webpage to Control It (using MQTT)
The sketch I wrote to control the robot is pretty simple, it just connects to my Wifi then subscribes to the MQTT broker and waits for it to send a message of confused/speech 'ON'. Once it gets this message it will switch the relay on for 0.5 seconds (which will make the robot say something) then send 'OFF' back to the MQTT broker so that the robot doesn't go into a loop of saying stuff :)
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "wifi-ssid"; const char* password = "wifi-password"; const char* mqtt_server = "mqtt-broker-ip";
WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0; int lastvalue = 0; float temp = 0; int inPin = 5; int speechpin = 4; String speech; String strTopic; String strPayload;) { payload[length] = '\0'; strTopic = String((char*)topic); if(strTopic == "confused/speech") { speech = String((char*)payload); if(speech == "ON") { Serial.println("ON"); digitalWrite(speechpin, HIGH); delay(100); client.publish("confused/speech","OFF",1); } else { Serial.println("OFF"); digitalWrite(speechpin, LOW); } } } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("arduinoClient_confused")) { Serial.println("connected"); // Once connected, publish an announcement... client.subscribe("confused/#"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void setup() { Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); pinMode(speechpin, OUTPUT); digitalWrite(speechpin, LOW);
} void loop() { if (!client.connected()) { reconnect(); } client.loop();
}
Then I wrote a simply webpage in php to send the MQTT the 'ON' message as follows:
<?php $say = $_GET['submit'];
if($say == "Say Something")
{ system("mosquitto_pub -h 127.0.0.1 -t 'confused/speech' -m 'ON'"); } ?>
<form method=get action=index.php>
<input name="submit" type="submit" value="Say Something" style="display: block; width: 100%; height: 100%;">
</form>
Step 8: Its Alive!
If everything is working as it should, you just need to load the webpage (that you're serving from a webserver) - and click the button and your robot should speak :)
Recommendations
We have a be nice policy.
Please be positive and constructive. | http://www.instructables.com/id/ESP8266-Confusedcom-Brian-Toy-Robot/ | CC-MAIN-2018-17 | refinedweb | 1,168 | 68.81 |
JtestR bundles the Ruby mocking framework Mocha. This is the mocking framework used for mocking in both Test/Unit and RSpec tests. For several reasons the RSpec way of mocking doesn't fit well with mocking of Java classes. Mocha on the other hand supports this quite easily.
Let's first take a lock at the regular workings of Mocha. Mocha have a syntax that's quite close to Java frameworks like JMock or SchMock. One of the major differences between Mocha and other Ruby based mocking frameworks is that Mocha allows you to work on instances of real classes. Let's take a typical example of testing the constructor of java.util.HashMap, that takes another Map as argument. This constructor should first call size on the map, and then get the entry set from the map, and finally get the iterator from the entry set and call next as many times as the size from the map. Using only interfaces, we can express it like this with Mocha:
import java.util.Map import java.util.Iterator import java.util.Set import java.util.HashMap functional_tests do test "that a new HashMap can be created based on another map" do map = Map.new map.expects(:size).returns(0) iter = Iterator.new iter.expects(:hasNext).returns(false) set = Set.new set.expects(:iterator).returns(iter) map.expects(:entrySet).returns(set) assert_equal 0, HashMap.new(map).size end end
We are using the JRuby feature that allows us to instantiate interfaces as instances. The returned object will throw exceptions for any call made to it. But when you use the Mocha expects method to specify methods that should be called, this works as expected. Now, this way of doing it has worked with JRuby and Mocha for a long time. It's been another story using concrete Java classes, where this way of doing things doesn't work as expected. JtestR includes a way of fixing this using the mock-method. So with JtestR you can mock a concrete class too:
import java.util.Iterator import java.util.Set import java.util.HashMap functional_tests do test "that a new HashMap can be created based on another map" do map = mock(HashMap) map.expects(:size).returns(0) iter = Iterator.new iter.expects(:hasNext).returns(false) set = Set.new set.expects(:iterator).returns(iter) map.expects(:entrySet).returns(set) assert_equal 0, HashMap.new(map).size end end
For symmetry, you can use the mock method on interfaces too, so if you always write mock(SomeJavaClassOrInterface), you'll be fine. Currently, the behavior of the mock method is to throw an exception for any method call that hasn't been expected. If this causes problems for people, I'm considering adding a mode that retains all the original functionality of the mocked class too. Note that the mock method will not work for final classes, or for mocking methods marked final.
Mocha supports a bit more than the features you can see here.
stubs
The difference between expects and stubs is that stubbed methods will not cause a test failure if they aren't called. Except for that they work the same as expects:
map.stubs(:size).returns(42)
with
If you need to check that arguments sent to a method are correct you can use the with method:
map.expects(:put).with("hello", "world").returns(nil)
In this case the expectation will fail unless the put method gets the arguments "hello" and "world".
any_instance
In Ruby, any_instance is incredibly powerful. With Java classes it's not as useful, but can still be good. The thing to remember is this: when using any_instance, you still need to create objects using the mock method, otherwise the methods stubbed with any_instance will not work.
You use it like this:
java.util.HashMap.any_instance.stubs(:size).returns(42) assert_equal 42, mock(java.util.HashMap).size assert_equal 42, mock(java.util.HashMap).size
at_least, at_least_once, at_most, at_most_once, never, once, times
There are several modifiers you can put at the end of expectations to modify how many times they should fire. Some examples of this:
map.expects(:size).at_least(3) map.expects(:size).at_least_once map.expects(:size).at_most(4) map.expects(:size).at_most_once map.expects(:size).never map.expects(:size).once map.expects(:size).times(2) map.expects(:size).times(2..4)
These are all fairly self explanatory.
returns
As you saw above, returns can be used to specify what value should be returned from an instance. You can also supply several values to it:
map.expects(:size).returns(1, 2) assert_equal 1, map.size assert_equal 2, map.size
You can also call returns several times in the same invocation for subsequent values:
map.expects(:size).returns(1).then.returns(2) assert_equal 1, map.size assert_equal 2, map.size
Note that the then method doesn't do anything, it's just there to make it easier to read.
Parameter matchers
When matching parameter arguments with the with-method, Mocha can take literal values, but you can also specify matchers on the argument with either a block or parameter matchers. That way you can do things like this:
map.expects(:get).with(is_a(String)) map.expects(:put).with{|first, second| first.is_a?(String) && second == 3}
The second example could have been done easier without the block, but this shows how you can use a block to make any kind of matching on parameters possible. There are quite a few parameters matchers, but the most interesting except for those you have seen is probably anything and any_parameters. Anything will match any one parameter, while any_parameters will match any number of arguments with any value.
Creating mocks and stubs
As mentioned, JtestR has changed some of the methods of Mocha to make it easier to work with Java integration features. The mock-method is one of them. There are some other things that might be good to know about:
- JtestR::Mocha::revert_mocking(clazz): If you want to get rid of mocking settings for a class, you can use this method
- mock(type, preserved_methods = JtestR::Mocha::METHODS_TO_LEAVE_ALONE): When creating a mocking of a class, you sometimes need to leave methods alone so the standard behavior works. This can be done with the second parameter to the mock method.
- mock_class(type, preserved_methods = JtestR::Mocha::METHODS_TO_LEAVE_ALONE)): If you want to use a custom constructor, you need to get this mocking class with this method and create it explicitly. It takes the same parameters as the mock-method.
Mocking methods that return primitive values
There is one little gotcha that might actually be very hard to identify. You can get basically any kind of exception, and the line number doesn't necessarily make sense either. This usually happens when you have set up an expectation on a method that returns a primitive Java value, but you don't actually returns something from the expectation, so the return value will be nil. Say we have a Java method like this:
public boolean foo() { return true; }
And you set up the expectation like this:
obj.expects(:foo)
This will blow up in very strange ways. The reason for this is that the Java stack expects a primitive return value, but you're giving it a null instead. So when setting expectations on methods that return primitive values, you must always return a value that maps to that domain. The example above can be fixed by:
obj.expects(:foo).returns(false)
More information
More information about Mocha can be found at. | http://docs.codehaus.org/display/JTESTR/Mocks | CC-MAIN-2015-14 | refinedweb | 1,252 | 57.47 |
AVR Internet Radio
Introduction
This tutorial presents a step by step guide on how to build an stand-alone Embedded Internet Radio. The device will be attached to a local Ethernet and connects MP3 streaming servers. If an Internet gateway (router) is available, you can listen to public radio stations listed at, for example.
Note, that this document refers to Medianut Board Version 1 (VS1001). In the meantime a new board revision 2 (VS1011) became available.
Required Hardware
Ethernut board, preferably version 2 or similar hardware. It's possible to run the code on version 1 boards, but because of the lack of sufficient RAM, the bitrates for MP3 streaming are limited.
Medianut board or similar hardware using a VS1001, VS1002 or VS1011 for MP3 decoding. These chips are manufactured by VLSI Solution Oy, Finland,
The Medianut can be mounted on top of the Ethernut board.
Assembled and tested boards as well as components may be purchased from egnite GmbH, Germany,
Required Software
The presented code had been tested on Nut/OS 3.9.2.1pre, but should also work on earlier releases of version 3.
Follow the instructions presented in the Nut/OS Software Manual to create the Nut/OS libraries and a sample application directory for your specific environment.
Step 1: Connecting an Internet Radio Station
We will utilize an
RS232 port
for debug messages. Nut/OS provides
a rich set of stdio routines such as printf, scanf etc., which are
fairly similar to Windows and Linux. However, the initialization
is a bit different. There are no predefined devices for stdin, stdout
and stderr. Devices used by an application have to be registered first
by calling
NutRegisterDevice(). We choose
devDebug0, which is a very simple UART driver for RS232
output. Due to its simplicity it's possible to produce debug messages
even from within interrupt routines.
After device registration, we are able to open a C stdio stream
on this device. The function
freopen() will attach
the resulting stream to stdout. Thus we can use simple calls like
printf(),
puts() or
putchar().
The
_ioctl() routine provides device specific control
functions like setting the baudrate.
We place an endless loop at the end of
main().
In opposite to programs written for desktop computers, the
main()
function will not return because there is nothing to return to.
#include <dev/debug.h> #include <stdio.h> #include <io.h> #define DBG_DEVICE devDebug0 #define DBG_DEVNAME "uart0" #define DBG_BAUDRATE 115200 int main(void) { NutRegisterDevice(&DBG_DEVICE, 0, 0); freopen(DBG_DEVNAME, "w", stdout); _ioctl(_fileno(stdout), UART_SETSPEED, &baud); puts("Reset me!"); for(;;); }
The need for device registration also applies to the Ethernet device. The Ethernut hardware supports two different LAN controller chips, the LAN91C111 and the RTL8019AS.
#ifdef ETHERNUT2 #include <dev/lanc111.h> #else #include <dev/nicrtl.h> #endif NutRegisterDevice(&DEV_ETHER, 0x8300, 5);
ETHERNUT2is typically defined in the file UserConf.mk located in the application directory.
HWDEF += -DETHERNUT2
TCP/IP over Ethernet interfaces typically require some sort of configuration, like the unique MAC address, local IP address, the network mask, routing information etc. The most comfortable way to define these variables is to make use of a local DHCP server. If there is none available in your local network, then you can install a simple one on your Windows PC. DHCP servers are also available on all Linux systems.
If you can't or don't want to install a DHCP server, you need to provide the required parameters in your application code defining them as preprocessor macros, for example.
#define MY_MAC { 0x00, 0x06, 0x98, 0x10, 0x01, 0x10 } #define MY_IPADDR "192.168.192.100" #define MY_IPMASK "255.255.255.0" #define MY_IPGATE "192.168.192.1"
MY_MAC specifies the Ethernet address, which must be
unique in your local Ethernet.
MY_IPADDR is the local TCP/IP address of the Ethernut
board, which needs to be unique too, but not only in the local
network. If you are connecting to the Internet, no other node in
the Internet should have the same one. Fortunately, your Internet
access provider will assign a unique address to your router and the
router translates local IP addresses to this unique address. Special
address ranges are reserved for local networks, like 192.168.x.y.
So you only have to take care, that the address is not used by
another computer in your local Ethernet.
MY_IPMASK must be equal on all computers in your local
network. Note, that if your network uses 255.255.255.0 for example,
then the first three parts of the
MY_IPADDR must be
equal on all computers too, 192.168.192 in our example.
MY_IPGATE should be set to the IP address of your
router. If you don't intend to connect to the Internet, then set
this parameter to
"0.0.0.0".
We use a specific routine to configure the network interface in three trial and error steps. The advantage is, that this code will work with DHCP, hard coded values and, not mentioned yet, previously saved EEPROM values.
int ConfigureLan(char *devname) { if (NutDhcpIfConfig(devname, 0, 60000)) { u_char mac[6] = MY_MAC; if (NutDhcpIfConfig(devname, mac, 60000)) { u_long ip_addr = inet_addr(MY_IPADDR); u_long ip_mask = inet_addr(MY_IPMASK); u_long ip_gate = inet_addr(MY_IPGATE); if(NutNetIfConfig(devname, mac, ip_addr, ip_mask)) { return -1; } if(ip_gate) { if(NutIpRouteAdd(0, 0, ip_gate, &DEV_ETHER) == 0) { return -1; } } } } return 0; }
NutDhcpIfConfig()assumes, that a complete configuration is available in the ATmega EEPROM already. This may be the case, if you previously ran the Basemon application and entered these parameters before starting the sample Webserver. If the fuse "Preserve EEPROM Contents" has been enabled in the ATmega128, then the network configuration remains intact when erasing the device during the programming cycle, while uploading a new application.
This first call will fail, if the EEPROM is empty. A second call
is done, which provides the MAC address. Again, this will fail,
if DHCP is not available in the local network. The final call
to
NutNetIfConfig() will provide all required parameters,
except the default route to our Internet gateway. If this parameter
is not zero, a call to
NutIpRouteAdd() will pass
the IP address of the router.
After having configured the network interface, we can use it to establish a TCP/IP connection to an MP3 streaming server. Three items are required to specify an MP3 stream.
- The server's IP address.
- The server's TCP port.
- The server's URL.
[playlist] numberofentries=2 File1= Title1=(#1 - 90/29131) Smoothjazz.Com Length1=-1 File2= Title2=(#2 - 124/38816) Smoothjazz.Com Length2=-1 Version=2
File1(alternative
File2) entry contains the information we need to create the proper parameters in our radio application.
#define RADIO_IPADDR "64.236.34.196" #define RADIO_PORT 80 #define RADIO_URL "/stream/1020"
TCPSOCKET *sock; u_long ip = inet_addr(RADIO_IPADDR); sock = NutTcpCreateSocket(); NutTcpConnect(sock, ip, RADIO_PORT); stream = _fdopen((int) sock, "r+b"); fprintf(stream, "GET %s HTTP/1.0\r\n", RADIO_URL); fprintf(stream, "Host: %s\r\n", inet_ntoa(ip)); fprintf(stream, "User-Agent: Ethernut\r\n"); fprintf(stream, "Accept: */*\r\n"); fprintf(stream, "Icy-MetaData: 1\r\n"); fprintf(stream, "Connection: close\r\n\r\n"); fflush(stream); line = malloc(512); while(fgets(line, 512, stream)) { cp = strchr(line, '\r'); if(cp == 0) continue; *cp = 0; if(*line == 0) break; printf("%s\n", line); } free(line);
mnut01-041111.zip
Contains complete source code and binaries of step 1. Here's a sample output:
Medianut Tutorial Part 1 - Nut/OS 3.9.2.1 pre - AVRGCC 29877 bytes free Configure eth0...OK MAC : 00-06-98-21-02-B0 IP : 192.168.192.202 Mask: 255.255.255.0 Gate: 192.168.192.1 Connecting 64.236.34.196:80...OK GET /stream/1040 HTTP/1.0 ICY 200 OK icy-notice1: <BR>This stream requires <Winamp</a><BR> icy-notice2: SHOUTcast Distributed Network Audio Server/SolarisSparc v1.9.4<BR> icy-name: CLUB 977 The 80s Channel (HIGH BANDWIDTH) icy-genre: 80s Pop Rock icy-url: icy-pub: 1 icy-metaint: 8192 icy-br: 128 icy-irc: #shoutcast icy-icq: 0 icy-aim: N/A Reset me!
Step 2: Playing an MP3 Stream
Following the empty line, which marks the end of the header, the streaming server will send an endless stream of binary data, the MP3 encoded audio data. Reading this data into a buffer is nothing special.
int got; u_char *buf; buf = malloc(2048); got = fread(buf, 1, 2048, stream);
Nut/OS includes a device driver for the VS1001K decoder chip. Actually this is not a common device driver with a NUTDEVICE structure and support for stdio read and write. This wouldn't make much sense, because tiny systems like Ethernut suffer from buffer copying. The following code would result in low performance.
/* Bad example */ got = fread(buf, 1, 2048, stream); fwrite(buf, 1, got, decoder); /* Not available */
- From the Ethernet Controller to the TCP buffer.
- From the TCP buffer to the application buffer.
- From the application buffer to the decoder buffer.
- From the decoder buffer to the decoder chip.
NutSegBufInit(8192); NutSegBufReset(); for(;;) { buf = NutSegBufWriteRequest(&rbytes); got = fread(buf, 1, rbytes, stream); NutSegBufWriteCommit(got); }
NutSegBufInit() initializes the buffer. For the banked
memory on Ethernut 2 boards, the parameter is ignored. All memory
banks are automatically occupied. For Ethernut 1 boards the specified
number of bytes are taken from heap memory to create the buffer.
NutSegBufReset() clears the buffer.
NutSegBufWriteRequest() returns the continous
buffer space available at the current write position.
NutSegBufWriteCommit() commits the specified number
of bytes written.
With this scheme, data copying is reduced by 25% and takes place
- From the Ethernet Controller to the TCP buffer.
- From the TCP buffer to the segmented buffer.
- From the segmented buffer to the decoder chip.
As stated above, the VS1001 driver doesn't support stdio read and write routines. Instead a number of individual routines are provided to control the decoding process.
VsPlayerInit() resets the decoder hardware and software
and should be the first routine called by our application.
VsPlayerReset() initializes the decoder and must be
called before decoding a new data stream.
VsGetStatus() can be used to query the current status
of the driver.
VsSetVolume() sets the analog output attenuation of
both stereo channels.
VsPlayerKick() finally starts decoding the data
in the segmented buffer.
It is possible to access the segmented buffer from within interrupt
routines and the Nut/OS VS1001 driver makes use of this feature.
However, calling
NutSegBufReset(),
NutSegBufWriteRequest()
or
NutSegBufWriteCommit() modifies certain multibyte
values using non-atomic operations, which needs to be protected
from access during interrupts. We could use the Nut/OS
NutEnterCritical() and
NutExitCritical()
calls, but this disables all interrupts, system-wide. This includes
interrupts initiated by out Ethernet controller, leading to a degradation
of our TCP response time and overall transfer rate. Luckily, the
VS1001 driver offers a routine named
VsPlayerInterrupts(),
which disables/enables decoder interrupts only.
u_char ief; ief = VsPlayerInterrupts(0); /* Exclusive call here. */ VsPlayerInterrupts(ief);
mnut02-041111.zip
Contains complete source code and binaries of step 2. A sample output is here:
Medianut Tutorial Part 2 - Nut/OS 3.9.2.1 pre - AVRGCC 29743 bytes free Configure eth0...OK MAC : 00-06-98-21-02-B0 IP : 192.168.192.202 Mask: 255.255.255.0 Gate: 192.168.192.1 Connecting 64.236.34.196:80...OK GET /stream/1020 HTTP/1.0 ICY 200 OK icy-notice1: <BR>This stream requires <a href="">Winamp</a><BR> icy-notice2: SHOUTcast Distributed Network Audio Server/SolarisSparc v1.9.4<BR> icy-name: Smoothjazz.Com - The worlds best Smooth Jazz - Live From Monterey Bay icy-genre: smooth jazz icy-url: icy-pub: 1 icy-metaint: 8192 icy-br: 32 icy-irc: #shoutcast icy-icq: 0 icy-aim: N/A Read 594 of 16384 Read 512 of 15790 Read 512 of 15278 Read 512 of 14766 Read 512 of 14254 Read 512 of 13742 Read 512 of 13230 Read 512 of 12718 Read 512 of 12206 Read 144 of 11694 4834 buffered
Step 3: Refining the Player
The default setup of the Nut/Net TCP stack is optimized for tiny
embedded systems with data exchange in both directions at minimal
memory usage. We can use
NutTcpSetSockOpt() to
optimize two of the parameters for MP3 streaming.
u_short tcpbufsiz = 8760; NutTcpSetSockOpt(sock, SO_RCVBUF, &tcpbufsiz, sizeof(tcpbufsiz));
u_short mss = 1460; NutTcpSetSockOpt(sock, TCP_MAXSEG, &mss, sizeof(mss));
Another problem appears, when the server or the connection dies.
In such a case our MP3 player, the TCP client, may never return
from the
fread(). Setting a socket read timeout
solves this problem. After the specified number of milliseconds
fread() will return with zero bytes read.
u_long rx_to = 3000; NutTcpSetSockOpt(sock, SO_RCVTIMEO, &rx_to, sizeof(rx_to));
As we found out in the last step, audio output contains hiccups or may even become completely scrambled. The reason is, that the stream contains some additional information, the so called metadata tags. In the previous step we passed this unfiltered to the decoder chip, which is of course quite picky about extra bytes included in the MP3 stream.
The server sends an information about how many bytes of MP3 data are between the metadata tags in the initial header lines.
icy-metaint: 8192
The metadata tag begins with a single byte, which indicates the total size of the tag when multiplied by 16. Here's an example of the contents of such a metadata tag.
StreamTitle='Alphaville, Big in Japan';StreamUrl='';
StreamTitletypically informs us about the music title currently transmitted. For now we print this to our debug device.
mnut03-041111.zip
Contains complete source code and binaries of step 3.
Quite often we will something like this after starting the player.
Connecting 64.236.34.196:80...Error: Connect failed with 10060 Reset me!
- LCD connector
- 4 button keyboard connector
- Infrared remote control receiver connector
Wireless radio prototype with Ethernut, Datanut and Medianut.
| http://ethernut.de/en/documents/webradio.html | CC-MAIN-2021-43 | refinedweb | 2,297 | 57.37 |
>>.
Down to the street level (Score:5, Funny)
There, that moped is doing it. That one. That little moped is why 20 million people literally cannot live off the air they breathe.
Re: (Score:2)
just think if we could take out that moped and save the world...
you sir, are clearly not an ibmer
Re: (Score:1)
Yeah, let's all get him.
Let me be the first to say it (Score:2)
Air pollution stinks.
no supercomputer needed (Score:5, Informative)
already known that coal makes the number one pollutant of the air in in China, of the PM2.5 that makes up most the rest, 22 percent from transportation, 16 percent from industry, 17 percent from coal.....the sources are known, the percents are known. How and if they are going to clean up these known sources is the question, no need for modeling
Re:no supercomputer needed (Score:4, Insightful)
yes but if we spend the next 5-20 years modeling we don't actually have to do anything real about it.
Re: (Score:3, Informative)
Actually it was another president long before Bush who snubbed a U.S. ally to make relationship with China so jobs and wealth production could be "outsourced". That was the start of the present day pollution problem in China
Re: (Score:2)
Yes, it's all America's fault that China didn't ever implement air scrubbing devices.
Re: (Score:2)
uhm, aren't China being pretty diligent with installing filters and what-nut on coal-plants?
Re: (Score:2)
Yeah, that explains the worst air pollution on earth.
Re: (Score:1)
it's funny really, they did put in filters that cut emissions from coal plants in half, but also doubled the number of plants.
Re: (Score:2)
yes but if we spend the next 5-20 years modeling we don't actually have to do anything real about it.
China isn't like the USA.
They tend to move purposefully and quickly when goals are set.
In the run up to the Olympics, China unilaterally closed coal power plants, various heavy industries, and took cars off the road, all in a bid to reduce pollution in Beijing.
It took the USA 40 years to tell grandfathered coal plants to either shape up or shut down.
Compare to China: [businessinsider.com]
Beijing plans to limit the total number of cars on the road to 5.6 million this year, with the number allowed to rise to 6 million by 2017, the local government has said.
It will also aim to meet its 2011-2015 targets to cut outdated capacity in sectors like steel, glassmaking and cement by the end of this year, one year ahead of schedule. On top of the original targets, it will also close an additional 15 million tonnes of steel smelting capacity and 100 million tonnes of cement making capacity next year.
The key idea here is that all this is happening unilaterally.
Their actions probably wouldn't even be constitutional in the USA.
Re: (Score:2)
And they don't seem to care how many people they kill in order to do it. See the 'Great Leap Forward' or break neck economic development in the present as examples.
Re: (Score:2)
I can only assume that this is another project under the aegis of IBM's 'smarter planet' [wikipedia.org]
IBM.... (Score:3)
is protecting it's future employees, customers, and H1B visa holders.
Re: (Score:2)
well they have to have communist customers now that they lost their Nazi one
Re: (Score:2)
They used a machine for census taking and made under license by a German company.
That is like blaming IBM for all the things that people did with IBM PCs.
only way to fix it is nuke Beijing (Score:2)
only way to fix it is nuke Beijing and then the Watson starts to log into the missile silos systems that had hand the people with the keys taken out of the loop.
Re: (Score:2)
Obvious (Score:1)
I can predict the air quality of Beijing at any time for at least the next 5 years and I can do it for free. The quality is BAD. July 10, 2018? BAD. Simple.
Always clear skies over the US embassy (Score:5, Interesting)
The Chinese government HATES it when people measure and publish "unofficial" pollution level readings...you can bet that pollution controls upwind of the US embassy are especially strict.
Re:Always clear skies over the US embassy (Score:5, Funny)
The Chinese government HATES it when people measure and publish "unofficial" pollution level readings...you can bet that pollution controls upwind of the US embassy are especially strict.
Which is pretty amusing since it's pretty easy to design an algorith that will predict pollution levels for most major Chinese cities with pretty much 100% accuracy every day of the year:
#include <stdio.h>
#include <unistd.h>
int main()
{
while(1)
{
printf("Predicted polution level for today: Very High\n");
printf("Health hazard: Extreme\n");
sleep(86400);
}
return 1;
}
Re: (Score:2)
Re: (Score:2)
Very amusing. However, as someone who's actually been in Beijing several times (I held a work permit in China for 3 years among other things), I can tell that things are a bit more nuanced. It can be grim, sometimes, but most of what is claimed to be smog in the stereotypical press-photo, is actually dust from the arid north-west of China (Inner Mongolia); when the weather is dry and the wind is from that corner, everything gets coated in very fine powder. I don't remember pollution being a huge problem - i
Big computer generated map of coalstacks. (Score:1)
And some weather-related forecasting. Big whoop. Good luck DOING ANYTHING ABOUT IT instead of just knowing when to shut down cities.
Got To Be A Ritual (Score:4, Insightful)
Re: (Score:2)
If that happens to shut down almost every business in town then great.
But won't you think of the economy? We must enable mankind to engage in economic activity, no matter the cost!
Re: (Score:2)
You pollute. Where's your "off" switch?
Once you've realized that there's no way to completely eliminate pollution, and that markets work most efficiently when negative externalities are internalized into prices, the solution becomes obvious: charge the polluters for the damage they cause, and give the revenue to those injured by pollution. This will give polluters the proper incentive to curb their emissions and it will pay the medical costs and lost sick days of those inju
Re: (Score:2)
More like it will allow the misfortune (probably poor) to be able to afford the products and services you just made super expensive. I mean seriously, a scheme like this will never result in anything other then the costs bein
Re: (Score:2)
Who is more likely to be injured by pollution, the poor or the rich? (The poor, because they tend to live in dirtier areas.) And therefore who stands to gain the most, relative to their discretionary income, from recouping the medical costs and lost sick days from that pollution? (Also the poor, because they have little to no discretionary income.)
So you are correct that it wi
Re: (Score:2)
Not really. The poor tend to be the source of their own pollution moreso than suffering other people's pollution. They mix chemicals like Bleach and Lime away in
Re: (Score:2)
Why is that relevant in any discussion about whether the rich should pay their fair share for the pollution they cause?
Again, not relevant, unless you are arguing that welfare should pay the poor's medical bills and not those who injure the poor.
Or they spend the day at the mall or the lib
Re: (Score:2)
Because you specifically brought up helping the poor as if it somehow secured your position. I can see you are abandoning that now I guess.
Again, you brought this up as a benefit to the poor. welfare already pays the poor's medical bills so should is not an operativ
Re: (Score:2)
Not there only if you don't price externalities in to energy prices.
Think of it this way, if I produce something and dump super toxic byproducts into a river, it's great for me. I don't pay to handle the toxic byproducts. However, while I save money, the families down stream who all get cancer are much worse off.
So, as a society, we don't allow chemical plants to save money by poisoning others.
Coal plants also have poisonous byproducts, but they are not required to care. They kill people, but they are no
Re: (Score:2)
Lol... and everyone who has ever seen a coal power plant has died. Coal is not some super goxic material and neither is the byproducts.
I could think of it your way, i could also think the moon is made of green cheese and be just as wrong. Your solution, despite being largely fictional will disproportionately harm the poor and make middle class poor.
Some of you people just seem to not care about the poor and don't mind tge poor getting poorer as long as yoh can make the rich less rich.
Re: (Score:2)
It's a fact that coal plants pollute and those pollutants result in increases of disease and a decrease of the health of a population downwind.... [forbes.com]
There's my citation. Maybe you'd care to share yours?
Re: (Score:2)
Those death rates for coal contain illnesses from mining and transporting coal which is a bit unconnected to burning it for energy. In most situations, those outside related deaths or illnesses can be attributed to improperly following MSHA regulations.
Needless to say, neither your article or you have provided any evidence that coal is super toxic. It simply isn't. More people die and need health care related to car accidents per year than from coal. But lets look at the real numbers for a minute. According
Re: (Score:2)
Specious argument. If you're burning coal the process required to burn the coal (whether you're telling me it's the actual flame, or the upstream mining) is killing people.
The number of people being greater than or less than the number of deaths for heart disease or diabetes is also irrelevant to the discussion. Deaths are not something economical you can just decide are acceptable[1]. Can I say that, if I shoot someone, say it's OK because I only take one life, and suicide and heart disease both take so
Re: (Score:2)
Actually, it shows how specious you argument was.
You would do well to pay attention to what I actually say and not suppose things in my stead. I have said it twice now so pay attention. Coal is not some super toxic mat
Re: (Score:2)
It's a natural component of the atmosphere, produced every time an animal breaths or respirates in any manner (fish do it too.)
Now, focus on the real pollution for a moment and realize that there are still very real and enormous costs to your proposed policy of 'If it pollutes simply end it.'
So what are you going to use for power, Solar? Do you have any idea how much pollution you have to create BEFORE you get a PV cell ready to START producing a miniscule trickle of electr
Re: (Score:2)
Oxygen isn't a pollutant either, unless you breath too much of it. Similarly for nitrogen.'t think that's a problem? The ocean is the base of the food chain. Surely, you care about that, eh? Nah? Okay, please go back to sleep.
Re: (Score:1)
How much you breath has absolutely nothing to do with it. Oxygen, Nitrogen, and CO2 are the natural components of the atmosphere, not pollutants.
Re: (Score:2)
You're a bit too literal. "Noise pollution," "heat pollution," and "light pollution" also involve an excess of something that naturally occurs in the environment.
That does not mean that, for instance, the effects to the environment are not detrimental. Which is why, despite the fact that in a natural ecosystem animals make noises, NYC fines drivers who honk their horn excessively. And why there are rules about when you can land your airplane because it's not nice to wake up residents within a hundred mil
Re: (Score:1)
And you are a bit too soft-headed, at least on this issue.
"Noise pollution," "heat pollution," and "light pollution" also involve an excess of something that naturally occurs in the environment.
And all three are BS terms. Marketing terms, where they verbally associate item X with item Y even though it does not belong, simply because they believe it will provoke the emotional response they want. THIS is real pollution - of the language. This fits in the same bucket with the 'wars'
And the answer is... (Score:3)
...please insert another $1M to continue this contract.
heritage report (Score:2)."
Re: (Score:2)
C'mon, the Heritage Foundation is not THAT sophisticated. Actually, the Heritage Foundation has been taken over by Libertards. They rather take offense at big business. I'm not sure they are all wrong to take offense, but I'm fairly sure it is for the wrong reasons.
Re: (Score:2)
How the hell is China having awful pollution the fault of IBM? By golly I know IBM is not perfect, but all the cases I have personally seen, customers dump a pile of crap into IBM's hands, then hamstring them while demanding they polish the turd. | http://news.slashdot.org/story/14/07/07/1530213/ibm-tries-to-forecast-and-control-beijings-air-pollution?sdsrc=prev | CC-MAIN-2015-14 | refinedweb | 2,301 | 70.53 |
But Stan says he tried something like that (see the comment in his code) and it was still not working. I would still need a more complete code example to reproduce the problem and figure out what went wrong. Dan "Mel Wilson" <mwilson at the-wire.com> wrote in message news:9YvPBls/KvrF089yn at the-wire.com... > In article <mailman.3029.1094638477.5135.python-list at python.org>, > Egbert Bouwman <egbert.list at hccnet.nl> wrote: > >On Wed, Sep 08, 2004 at 03:59:26AM +0000, Stan Cook wrote: > >> I was trying to take a list of files in a directory and remove all but the ".dbf" files. I used the following to try to remove the items, but they would not remove. Any help would be greatly appreciated. > >> > >> x = 0 > >> for each in _dbases: > >> if each[-4:] <> ".dbf": > >> del each # also tried: del _dbases[x] > >> x = x + 1 > >> > >> I must be doing something wrong, but it acts as though it is.... > >> > >The answers you received don't tell you what you are doing wrong. > >If you replace 'del each' with 'print each' it works, > >so it seems that you can not delete elements of a list you are > >looping over. But I would like to know more about it as well. > > One use of `del` is to remove a name from a namespace, > and that's what it's doing here: removing the name 'each'. > > A paraphrase of what's going on is: > > for i in xrange (len (_dbases)): > each = _dbases[i] > if each[-4:] <> ".dbf": > del each > > and we happily throw away the name 'each' without touching > the item in the list. > > The way to remove items from a list is (untested code): > > for i in xrange (len (a_list)-1, -1, -1): > if i_want_to_remove (a_list[i]): > del a_list[i] > > Going through the list backwards means that deleting an item > doesn't change the index numbers of items we've yet to > process. `del a_list[i]` removes from the list the > reference to the object that was the i'th item in the list > (under the hood, a Python list is implemented as an array of > references.) > > This is one reason list comprehensions became popular so > fast. > > Regards. Mel. | https://mail.python.org/pipermail/python-list/2004-September/278188.html | CC-MAIN-2014-15 | refinedweb | 370 | 81.22 |
ok so im trying to learn switch cases so i tried to write this program to see if i understood how to write them and i wrote both my variables the same exact way and its only giving me an undeclared variable for 1 of them. here's my code, please help.
Code:#include <iostream> using namespace std; int main () { int a; int b (b = 1); int c (c = 2); for (a = 0; a < 3; a++) { switch (a) { case b: { cout<< "wow this is really confusing\n"; } break; case c: { cout<< "now it's a little easier\n"; } break; default: { cout<< "X-P\n"; } break; } } } | http://cboard.cprogramming.com/cplusplus-programming/120552-error-c2065-undeclared-identifier-please-help.html | CC-MAIN-2014-41 | refinedweb | 105 | 72.12 |
![if !IE]> <![endif]>
Bandwidth Sharing Between Cores
Bandwidth is another resource shared between threads. The bandwidth capacity of a sys-tem depends on the design of the processor and the memory system as well as the memory chips and their location in the system. A consequence of this is that two systems can contain the same processor and same motherboard yet have two different measurements for bandwidth. Typically, a system configuring a system for best possible performance requires expensive memory chips.
The bandwidth a processor can consume is a function of the number of outstanding memory requests and the rate at which these can be returned. These memory requests can come from either hardware or software prefetches, as well as from load or store operations. Since each thread can issue memory requests, the more threads that a proces-sor can run, the more bandwidth the processor can consume.
Many of the string-handling library routines such as strlen() or memset() can be large consumers of memory bandwidth. Since these routines are provided as part of the operating system, they are often optimized to give the best performance for a given system. The code in Listing 9.17 uses multiple threads calling memset() on disjoint regions of memory in order to estimate the available memory bandwidth on a system. Bandwidth can be measured by dividing the amount of memory accessed by the time taken to complete the accesses.
Listing 9.17 Using memset to Measure Memory Bandwidth
#include <stdio.h> #include <stdlib.h> #include <strings.h> #include <pthread.h> #include <sys/time.h>
#define BLOCKSIZE 1024*1025 int nthreads = 8;
char * memory;
double now()
{
struct timeval time; gettimeofday( &time, 0 );
return (double)time.tv_sec + (double)time.tv_usec / 1000000.0;
}
void *experiment( void *id )
{
unsigned int seed = 0; int count = 20000;
for( int i=0; i<count; i++ )
{
memset( &memory[BLOCKSIZE * (int)id], 0, BLOCKSIZE );
}
if ( seed == 1 ){ printf( "" ); }
}
int main( int argc, char* argv[] )
{
pthread_t threads[64];
memory = (char*)malloc( 64*BLOCKSIZE );
if ( argc > 1 ) { nthreads = atoi( argv[1] ); } double start = now();
for( int i=0; i<nthreads; i++ )
{
pthread_create( &threads[i], 0, experiment, (void*)i );
}
for ( int i=0; i<nthreads; i++ )
{
pthread_join( threads[i], 0 );
}
double end = now();
printf( "%i Threads Time %f s Bandwidth %f GB/s\n", nthreads, (end – start) ,
( (double)nthreads * BLOCKSIZE * 20000.0 ) / ( end – start) / 1000000000.0 );
return 0;
}
The results in Listing 9.18 show the bandwidth measured by the test code for one to eight virtual CPUs on a system with 64 virtual CPUs. For this particular system, the bandwidth scales nearly linearly with the number of threads until about six threads. After six threads, the bandwidth reduces. This might seem like a surprising result, but there are several effects that can cause this.
Listing 9.18 Memory Bandwidth Measured on a System with 64 Virtual CPUs
1 Threads Time 7.082376 s Bandwidth 2.76 GB/s
2 Threads Time 7.082576 s Bandwidth 5.52 GB/s
3 Threads Time 7.059594 s Bandwidth 8.31 GB/s
4 Threads Time 7.181156 s Bandwidth 10.89 GB/s
5 Threads Time 7.640440 s Bandwidth 12.79 GB/s
6 Threads Time 11.252412 s Bandwidth 10.42 GB/s
7 Threads Time 14.723671 s Bandwidth 9.29 GB/s
8 Threads Time 17.267288 s Bandwidth 9.06 GB/s
One possibility is that the threads are interfering on the processor. If multiple threads are sharing a core, the combined set of threads might be fully utilizing the instruction issue capacity of the core. We will discuss the sharing of cores between multiple threads in the section “Pipeline Resource Starvation.” A second interaction effect is if the threads start interfering in the caches, such as multiple threads attempting to load data to the same set of cache lines.
One other effect is the behavior of memory chips when they become saturated. At this point, the chips start experiencing queuing latencies where the response time for each request increases. Memory chips are arranged in banks. Accessing a particular address will lead to a request to a particular bank of memory. Each bank needs a gap between returning two responses. If multiple threads happen to hit the same bank, then the response time becomes governed by the rate at which the bank can return memory.
The consequence of all this interaction is that a saturated memory subsystem may end up returning data at less than the peak memory bandwidth. This is clearly seen in the example where the bandwidth peaks at five threads.
Listing 9.19 shows memory bandwidth measured on system with four virtual CPUs. This is a very different scenario. In this case, adding a second thread does not increase the memory bandwidth consumed. The system is already running at peak bandwidth consumption. Adding additional threads causes the system memory subsystem to show reduced bandwidth consumption for the reasons previously discussed.
Listing 9.19 Memory Bandwidth Measured on a System with Four Virtual CPUs
1 Threads Time 7.437563 s Bandwidth 2.63 GB/s
2 Threads Time 15.238317 s Bandwidth 2.57 GB/s
3 Threads Time 24.580981 s Bandwidth 2.39 GB/s
4 Threads Time 37.457352 s Bandwidth 2.09 GB/s
Related Topics
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai. | https://www.brainkart.com/article/Bandwidth-Sharing-Between-Cores_9529/ | CC-MAIN-2019-30 | refinedweb | 895 | 67.96 |
Hey,
I've been going insane with a question I've been doing all day.
Creating an application that prompts a user to enter a date.
I have to use arrays to store the number of days in each month i.e 31 for January, 28 for February etc..
I have created a loop so that if someone entered incorrectly, the "33rd of the 5th month" or the 12th of the 20th month, that the user will be prompted to re-enter the date.
When I run the programme it will re-prompt if the user enters a wrong month but not the date. If for example I enter 35 for the day, it will go ahead instead of returning to loop and re-prompting.
Now I have to store the days of the months in an array as that is part of the question.
I was wondering if anyone could help me to get the app. to re-prompt when the wrong day is entered? I have a feeling the arrays are the problem.
import javax.swing.*; class partbq1a { public static void main(String[] args) { int day; int month; int year; int[] lastDay = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; boolean valid = true; // prompt user input do { String input1 = JOptionPane.showInputDialog("Enter Date in number format here:"); day = Integer.parseInt (input1); String input2 = JOptionPane.showInputDialog("Enter Month in number format here:"); month = Integer.parseInt (input2); // sort out days if (day > 0 && day <= lastDay[11]) valid = true; else valid = false; // sort out months here if (month >= 1 && month <= 12) valid = true; else valid = false; } while (!valid); String input3 = JOptionPane.showInputDialog(" Enter Year in number format here:"); year = Integer.parseInt(input3); System.out.println(" The Date is: " + day + "day, " + month + "month, " + year + "year."); } } | https://www.daniweb.com/programming/software-development/threads/251573/java-noob | CC-MAIN-2017-26 | refinedweb | 297 | 73.68 |
2 files are needed:
Files:wiki_insecure/users/ArielManzur/tolua++/virtual_method_hooks.lua
Files:wiki_insecure/users/ArielManzur/tolua++/tolua_base.h
Create a .pkg file
// mypackage.pkg $#include "tolua_base.h" class Widget { protected: virtual bool input_event(Event* e); public: virtual void add_child(Widget* child); void close(); Widget(string p_name); };
Generate the package
tolua++ -L virtual_method_hooks.lua mypackage.pkg > mypackage.cpp (compile 'mypackage.cpp' with the rest of the code)
Use the class Lua__Widget from your lua script
-- custom_widget.lua require "mypackage" local CustomWidget = {} CustomWidget.__index = CustomWidget function CustomWidget:input_event(e) if e.type = Event.KEY_PRESS and e.key_code == KEY_ESCAPE then -- close the widget when escape is pressed self:close() return true end -- call Widget::input_event return self:Widget__input_event(e) end function CustomWidget:new(name) -- create a table and make it an 'instance' of CustomWidget local t = {} setmetatable(t, CustomWidget) -- create a Lua__Widget object, and make the table inherit from it local w = Lua__Widget:new(name) tolua.setpeer(w, t) -- use 'tolua.inherit' on lua 5.0 -- 'w' will be the lua object where the virtual methods will be looked up w:tolua__set_instance(w) return w -- return 't' on lua 5.0 with tolua.inherit end
In this example, the class 'Lua__Widget' is generated. Lua__Widget has all the constructors of Widget, and a method 'tolua__set_instance', to provide the lua object where the virtual methods will be looked up (in this case, we use the same userdata object used for the c++ object, because our lua functions override the c++ functions). This object will be passed as
self on the lua methods. Lua__Widget also exposes the virtual methods from Widget to be called directly.
A subclass that inherits from a class with virtual methods will also generate code to implement those methods from lua, but only if the subclass has any virtual methods itself. For example, if we add the following to our pkg:
class Label : public Widget { public: void set_text(string p_text); };
this will not generate a
Lua__Label class. For that, we need to add at least one virtual method. Consider the following example:
class Label : public Widget { private: virtual void add_child(Widget* child); public: void set_text(string p_text); };
In this case, the only virtual method available for the class Lua__Label will be
input_event (inherited from Widget). The reason to declare
add_child as private on the pkg is because if the method is actually private and we don't declare it as such on the pkg, the generated code will try to use it on Lua__Label, and that will produce a compile error.
The file virtual_method_hooks.lua has 3 flags that can be changed (found at the beginning of the file).
disable_virtual_hooks: a quick flag to disable the whole thing. If it's set to
true, no special code will be generated for virtual methods.
enable_pure_virtual: enables support for pure virtual methods. If it's set to
false, the output code will be more "conservative" when it comes to classes with pure virtual methods. No constructors will be output, and the code will only compile with GCC 4 (through a preprocessor switch), which is more permissive with pure virtual classes.
default_private_access: this is a flag to fully enable the code from ToluappClassAccessLabels. By default, tolua++ treats the contents of a class a
public, but since we can have
privatevirtual methods, there is an option to set the access to
privateby default on pkg files too.
Since lua doesn't enforce signatures for functions, the only way to lookup a function is by its name, so when there are more than 1 c++ methods with the same name, your lua function should be prepared to handle all versions of the functions.
Also, when looking for methods on parent classes, only the names are used to match them (this is a limitation of the current version). For example, if you add this to the example package:
class Button : public Widget { public: virtual void add_child(Label* child); };
only the last version of
add_child will be available for the class
Lua__Button.
Only one level of namespaces is supported for the moment. To avoid infinite recursion, only lua functions (and not lua_cfunctions) are called from the virtual methods.
Some versions of tolua++ (like 1.0.92) have problems with the 'default_private_access' flag. If the methods on your virtual class are not being exported, try setting the flag to
false. You'll have to add a
private: label to the class declarations that have private stuff by default at the beginning.
Send questions, bugs, or comments to mailto:puntob@gmail.com | http://lua-users.org/wiki/ImplementingVirtualMethodsWithToluapp | CC-MAIN-2022-05 | refinedweb | 751 | 55.13 |
This preview shows
pages
1–2. Sign up
to
view the full content.
CSE 459.24 – Programming in C# Roger Crawfis In-Class Worksheet #2 Overview For this worksheet, we will create a class library and then use the resulting dll in a console application. This worksheet is a start on your next programming assignment, where we will build a directed acyclic graph (a DAG) and traverse it using an interface (which we will call IVisitor). Each node in the graph will be of type ISceneNode. The goal here is to allow multiple implementations of the IVisitor that can be determined at run-time. It uses method overloading to resolve the scenenode’s type at runtime. We will have several different flavors of ISceneNode’s and will define interfa ces for each of these flavors. Before You Start In Programming Assignment #2 you will be implementing a scene graph. I would advise you to take a look at the assignment before you begin this worksheet. Things to understand before you begin: What a scene graph is. The visitor design pattern. In addition to the resources listed on the assignment you may find the details section of this wiki page helpful. A basic understanding of the class hierarchy in the assignment. Creating a Class Library You should have Visual Studio 2008 open. 1. Create a new Project either from the shortcut on the Start page or through the file menu, 2. Select the type to be a C# Class Library. This will create a .dll file rather than an .exe file. Dll’s are loaded at runtime. Where the runtime finds these dll’s is a rather complex set of paths. This was touched upon in the early material for the course, but is not important for this level. Here the .dll will be in the same directory as the .exe file. For more information on dll’s go to . Note, that for the most part dll’s are being used in place of statically linked in libraries (.lib files). In C++, we probably would have implemented a library rather than a dll. 3. In the Location textbox, enter your desired hard drive location. Note that this will be on the mounted z: drive in the CSE environment. 4. Name the library ISceneGraph. 5. Select OK. 6. You will notice that Visual Studio has created a file called Class1.cs and opened it in the Code View. Note the namespace used and the class name. Right-click on this file in the Solution Explorer and Delete it. 7. Select the menu item Project->ISceneGraph Properties . Here you will see that it is building a class library, the name of the library (dll), the environment support it needs, etc. 8. Change the Default Namespace to your lastname.SceneGraph (e.g., Crawfis.SceneGraph). Now any new files added (to this project) will be encapsulated in this namespace. You can always change this in the .cs file to another namespace or class name.
View Full
Document
This
preview
has intentionally blurred sections.
This note was uploaded on 02/27/2012 for the course CSE 459.24 taught by Professor Crawfis during the Winter '11 term at Ohio State.
- Winter '11
- CRAWFIS
Click to edit the document details | https://www.coursehero.com/file/6819330/Worksheet2/ | CC-MAIN-2017-17 | refinedweb | 543 | 76.01 |
Java Interview Questions – 28
1.
2.
3.How would you display “validation fail” errors on a JSP page?
Following tag displays all the errors: <html:errors/>
4., return mapping.findForward(“testAction”);}}
6.
7.How can one enable front-end validation based on the xml in validation.xml?.
8.
9.What is the Jakarta Struts Framework?
Jakarta Struts is an open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications.
Jakarta Struts is a robust architecture and can be used for the development of applications of any size. The “Struts framework” makes it easier to design scalable, reliable Web applications.
10.What is an ActionServlet?
The class org.apache.struts.action.ActionServlet is called the ActionServlet. In the Jakarta Struts Framework this class plays the role of controller. All the requests to the server go through the “Controller”. The “Controller” is responsible for handling all the requests.
11.How can one make any “Message Resources” definitions file available to the “Struts Framework” environment?
“Message Resources” definitions file are simple .properties files and these files contain the messages that can be used in the struts project. “Message Resources” definition files can be added to the struts-config.xml file through <message-resources /> tag. Example: <message-resources parameter=”MessageResources” /.
12.
13.
14
15.
16. What is Struts Validator Framework?:o Validator-Rules.xml file o Validation.xml file
17. What is the need of Struts?
18.Provide an overview of web container.
The web container is used to implement the web components functionality. The functionality specifies an environment, called as runtime environment which the web components security, deployment, life-cycle management transaction management, request-response services. A container manages the servlet / JSP/ EJB functionality. J2EE server runs the components and the containers. A web container will also manage the database connection pooling, data persistence and access to the J2EE API.
19.Explain the Java Servlet programming model.
The servlets are server side components in a web application. These components platform independent and on any server as the java technology is platform independence. The servlets are dynamically loaded by the JRE of servlets. When a request is received from a client the web container / web server will ignite the servlet. The servlet processes the request the sends the response back to the container / web server which in turn sends the response back to the client.
20.Describe in brief about deployment descriptors.
A deployment descriptor describes the configuration information to deploy a web application. For a web application, it directs the deployment tool that is to deploy a module for a specific container such as ejb container / servlet/jsp container. For web applications the deployment descriptor is web.xml and must be placed in a WEB-INF directory of a web application root directory. For EE deployment descriptor the name should be application.xml and must be placed in a META-INF directory at the top level of the application .ear file.
21.
22.
23.What are the core classes of Struts?
Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs.
24.
25.How Struts control data flow?
Struts implements the MVC/Layers pattern through the use of ActionForwards and ActionMappings to keep control-flow decisions out of presentation layer.
26.What configuration files are used in Struts?
ApplicationResources.propertiesstruts-config.xml These two files are used to bridge the gap between the Controller and the Model.
27. Is ActionForm part of the Model in MVC?
People think the ActionForm is part of the Model. They read the MVC description and think… Hey!… this is the Model’s state, lets move this as parameters all over the Model. Now you have a tight coupling between the Model and the Struts framework.There are plenty of examples in which the ActionForm properties are mapped 1:1 on DTO POJO objects and those used instead, but people think its a waste of code and time and just pass it along to the Model.
28.
29 ‘implements ActionForm’
30.
31
32.
33.
34.
35.
36.
37.Are the Struts tags XHTML compliant ?
If you use an <html:html xhtml=”true> or <html:xhtml/> element on your page, the tags will render as XHTML (since Struts 1.1)..
39.
40.
41.
42.Why is it called Struts?
It’s a reference to struts in the architectural sense, a reminder of the nearly invisible pieces that hold up buildings, houses, and bridges.
43.
44.Where can I get a copy of Struts?
The best place to download Struts is at struts.apache.org. The nightly builds are very stable, and recommended as the best place to start today.
45.
46]
47.
48.)
49.
50 * <[email protected]/msg03206.html >* <[email protected]/msg00495.html >
* < >
51.
52.
53/ >
54.
55.
56.Is Struts compatible with other Java technologies?
Yes. Struts is committed to supporting industry standards. Struts acts as an integrator of Java technologies so that they can be used in the “real world”.
57.
58.
59.Who makes the Struts?
Struts is hosted by the Apache Software Foundation(ASF) as part of its Jakarta project, like Tomcat, Ant and Velocity.
60.What helpers in the form of JSP pages are provided in Struts framework?
–struts-html.tld–struts-bean.tld –struts-logic.tld 61
62.
63.
64 / >
65.What is the different actions available in Struts?
The different kinds of actions in Struts are:
1.ForwardAction
2.IncludeAction
3.DispatchAction
4.LookupDispatchAction
5.SwitchAction
66.What is Dispatch.
67. How to use DispatchAction?
68.What is the difference between ForwardAction and IncludeAction?
The difference between ForwardAction and InculdeAction are:
IncludeAction is used when any other action is going to intake that action whereas ForwardAction is used move the request from one resource to another resource.
69.What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction are given below:
LookupDispatchAction is the subclass of the DispatchActionActual method that gets called in LookupDispatchAction whereas DispatchAction dispatches the action based on the parameter value.
70.What is LookupDispatchAction?
The LookupDispatchAction class is a subclass of DispatchActionThe LookupDispatchAction is used to call the actual method.For using LookupDispatchAction, first we should generate a subclass with a set of methods.
It control the forwarding of the request to the best resource in its subclassIt does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.
71. What is the use of ForwardAction?
72.What is IncludeAction?.
73. What are the various Struts tag libraries?
The various Struts tag libraries are:
i.HTML Tags: used to create the struts input forms and GUI of web page.
ii.Bean Tags: used to access bean and their properties.
iii.Logic Tags: used to perform the logical operation like comparison
iv.Template Tags: used to changes the layout and view.
v.Nested Tags: used to perform the nested functionality
vi.Tiles Tags: used to manages the tiles of the application
74. What is the life cycle of ActionForm?.
75. What are the loop holes of Struts?
The drawbacks of Struts are following:Absence of backward flow mechanism,Only one single controller Servlets is used,Bigger learning curve,Worst documentatio,No exception present in this framework
Less transparent,Rigid approach.With struts 1, embedding application into JSP can’t be prevented.Non-XML compliance of JSP syntax
76. Difference between Html tags and Struts specific HTML Tags
Difference between HTML tag and Struts specific HTLM.
77..
78. How to display validation errors on JSP page?/>
79. How to use forward action to restrict a strut application to MVC?
We can use the ForwarAction to restrict the Struts application to Model View Controller by following coding:
<global-forwards>
<statements>
<forward name=”CitizenDetailsPage”
path=”/gotoCitizenDetails.do” />
</global-forwards>
<action-mappings>
<statements>
<action path=”/gotoCitizenDetails”
parameter=”/CitizenDetails.jsp”
type=”org.apache.struts.actions.ForwardAction” />
</action-mappings>
80. What is ActionMapping?”/>
</action-mappings>
81. What is role of Action Class?.
82. How to combine the Struts with Velocity Template?
We can combine Struts and Velocity template by performing following steps:
1. Set classpath to Velocity JARs
2. Make web.xml file to identify the Velocity servlet.
3. Select Velocity toolbox.xml in WEB-INF directory.
4. Modify struts-config to point its views to Velocity templates instead of JSPs.
5. Create a Velocity template for each page you want to render.
83. In how many ways duplicate form submission can occurs?
The submission form can be duplicated by the any of the following ways:
Using refresh button.By clicking submit button more than once before the server sent back the response.By clicking back navigation button present in browser.The browser is restores to submit the form again.
By clicking multiple times on a transaction that is delayed than usual.
84. What is the difference between Struts 1 and struts2?
The.
85. What are the steps used to setup dispatch action?
86. What is difference between Interceptors and Filters?.
87. What are the Custom tags?.
88. What is the difference between empty default namespace and root namespace?.
89. What is the difference between RequestAware and ServletRequestAware interface?.
90. What are inner class and anonymous class?
Inner class: classes that are defined within other classes.
The nesting is a relationship performed between two different classes.
An inner class can access private members and data.
Inner classes have clearly two benefits:
o Name control
o Access control.
Anonymous class: Anonymous class is a class defined inside a method without a name.
It is instantiated and declared in the same method.It does not have explicit constructors.
91.What is the difference between ActionForm and DynaActionForm?
In action form, you need to define the form class that extends ActionForm explicitly, whereas you can define the form dynamically inside the struts-config file when using DynaActionForm.
92.
93.
94.
95”
96.
97.What are the components provided in J2EE to perform authentication and authorization?
Authentication – RequestProcessor and/or Filter.
Authorization – DTO, JDO or Java or Action classes.
98.
99.What is the XML parser provided in struts? Can you use it for other purposes?
‘Digester’ framework. Yes we can use for our applications to store and parse our application-related data.
100.Difference between Struts 1.0 and 1.1?
Perform() method was replaced by execute()
DynaActionForms are introduced.
Tiles Concept is introduced
We can write our own Controller by Inheriting RequestProcessor
101.What are the ways in which resource file can be used in struts?
Defining message resources in struts-config file.
Programmatically using resource files in Java classes or in JSP files.
102. | https://www.lessons99.com/java-interview-questions-28.html | CC-MAIN-2020-05 | refinedweb | 1,774 | 60.41 |
Johan Danforth's Blog
From the last days of playing around with and learning NHibernate it's quite clear to me that NHibernate is not a perfect match for a WCF solution. I'm perfectly aware of the fact that I'm still a total NH newbie, so please correct me or help me out if you can.
From the moment I heard of Hibernate years ago I thought it was best made for stateful solutions and not web apps or web services, and from what I can see that is still the case. I like many of the things I see in NH, especially the way you can map existing and bad looking databases to better looking domain entities, and the work on NHibernate Fluent looks promising.
You have to understand how lazy loading does (not) work with web services and serializing problems you may run into. But I think the biggest problem lies in the session management of NHibernate and where to open and close your NHibernate session. I won't even go into the different options proposed by hundreds of bloggers, just Google it. The thing is I don't want to be dependant on more 3rd party or open source components than necessary - it can easily get out of control.
I still want to use NHibernate for our WCF project because I do think can help us map the old, existing database we have to work with to decent domain entities, but I'm afraid we will run into weird problems later on. This approach seems to be one of the best so far, but I need to test it out some more and I'm not sure it will handle lazy loaded/HasMany data. Quite a few projects have run into problems with the session being closed before the serialization of lazy loaded objects happens :/
We may have to use EF instead.
Remoting entities is generally a bad idea (remember EJB?). Entities should not cross context boundaries (i.e. web services, remoting, etc).
You can also turn off lazy-loading. But again, all these are smells pointed towards the larger problem which is "remoting entities across context boundaries."
I strongly urge you NOT to do this as this is only the tip of the iceberg of problems you will face with this approach.
I can also pretty much guarantee you that moving to EF is NOT going to make your problems any easier (quite the contrary).
I have to agree with Chad. It seems you have a design problem somewhere rather than an NH problem.
I use NH in WCF with a fair degree of ease. Set this as your data contract surrogate. Just left/inner join in relations that you want to send across the pipe.
public class NhDataContractSurrogate : IDataContractSurrogate {
#region IDataContractSurrogate Members
public object GetObjectToSerialize(object obj, Type targetType) {
INHibernateProxy proxy = obj as INHibernateProxy;
if (proxy != null) {
ILazyInitializer li = proxy.HibernateLazyInitializer;
obj = (li.IsUninitialized ? null : li.GetImplementation());
}
return obj;
}
public object GetCustomDataToExport(Type clrType, Type dataContractType) {
return null;
public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType) {
public Type GetDataContractType(Type type) {
return type;
public object GetDeserializedObject(object obj, Type targetType) {
public void GetKnownCustomDataTypes(Collection<Type> customDataTypes) {
public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData) {
public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit) {
return typeDeclaration;
#endregion
}
@Chad - Yes, I do remember EJB, but I'm not doing remoting here. This is stateless and I usually map internal entities to data contracts that go on the wire. I'm just trying things out here and thought that just maybe I could use NH's great mapping features to create entities that *could* go on the wire when dealing with simpler services.
I tried to turn off lazy loading, but it seems that I ran into an issue/fault in the latest NHibernate Fluent release according to people on the Google group for Fluent. So typical me.
Would be interesting to hear why EF would make things harder for me.
@Allan - Thanks for the tip on using IDataContractSurrogat. I'll look at it! I saw some people using NetDataContractSerializer, but that's not an option for me.
NHibernate's ORM mapping shouldn't be used in the message that you use for wire transfers. You should build your messages with the data from NHibernate's serialization classes that you've created.
NHibernate's sessions are lightweight and you should create and release in as short statements as possible (smallest possible transactions). A lot of developers use some kind of unit of work pattern.
Only thing to care about is that you should just create the factory once.
@Ramon - As I wrote to Chad, we're normally not/never exposing internal entities from a service on the wire like this, this was something we did now when trying out NH with WCF.
What we will do next is to set up a proper solution for a Unit of Work were the session is opened and closed and map NH entities to WCF data contracts to be sent on the wire.
Thanks for the concerns about the creation of the factory. We're using Unity as our container and the factory is created only once as a singleton and that part seems to work just fine. Just have to figure out the best possible way to create and close the session :) | http://weblogs.asp.net/jdanforth/archive/2008/12/22/nhibernate-and-wcf-is-not-a-perfect-match.aspx | crawl-002 | refinedweb | 892 | 52.19 |
This action might not be possible to undo. Are you sure you want to continue?
04/10/2013
text
original
Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding on Java.
Java Overview:
• •
• •.
•
•
• •
•
• • •
Architectural- neutral :Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence Java runtime system. Portable :being architectural neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler and Java is written in ANSI C with a clean portability boundary which is a POSIX subset. opensource,:
• • •
Linux 7.1 or Windows 95/98/2000/XP operating system. Java JDK 5 Microsoft Notepad or any other text editor
This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Java.
What is Next ?
Next chapter will guide you to where you can obtain Java and its documentation. Finally, it instructs you on how to install Java and prepare an environment to develop Java applications.
Java Environment Setup
Before we proceed further it is important that we set up the java environment correctly.:
• • •:
•
Edit the 'C:\autoexec.bat' file and add the following line at the end: 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
netbeans. eating. Eclipse : is also a java IDE developed by the eclipse open source community and can be downloaded from. Let us now briefly look into what do class.Setting up the path for Linux. Methods .org/index. UNIX. . An object is an instance of a class.Each object has its unique set of instant variables. An object. A class can contain many methods. methods and instant variables mean. Java Basic Syntax When we consider a Java program it can be defined as a collection of objects that communicate via invoking each others methods. Solaris. Refer to your shell documentation if you have trouble doing this.org/. name. Example: A dog has states-color. object. barking.s state is created by the values assigned to these instant variables. But for now. There are even more sophisticated IDE available in the market. TextPad.eclipse. breed as well as behaviors -wagging. if you use bash as your shell. It is in methods where the logics are written. Example. you can consider one of the following: • • • Notepad : On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial).html. then you would add the following line to the end of your '. Class . Netbeans :is a Java IDE that is open source and free which can be downloaded from have states and behaviors. FreeBSD: Environment variable PATH should be set to point to where the java binaries have been installed.A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support. What is Next ? Next chapter will teach you how to write and run your first java program and some of the important basic syntaxes in java needed for developing applications. • • • • Object .bashrc: export PATH=/path/to/java:$PATH' Popular Java Editors: To write your java programs you will need a text editor. Instant Variables . data is manipulated and all the actions are executed.A method is basically a behavior.
Class Names . Open notepad and add the code as above. If several words are used to form a name of the class each inner words first letter should be in Upper Case.println("Hello World"). Type ' javac MyFirstJavaProgram.First Java Program: Let us look at a simple code that would print the words Hello World.( Assumption : The path variable is set).java ' and press enter to compile your code. Open a command prompt window and go o the directory where you saved the class. * This will print 'Hello World' as the output */ public static void main(String []args){ System. 3. • • Case Sensitivity . Assume its C:\. 6. it is very important to keep in mind the following points.All method names should start with a Lower Case letter. C : > javac MyFirstJavaProgram. Please follow the steps given below: 1. compile and run the program.Java is case sensitive which means identifier Hello and hello would have different meaning in Java. 4.For all class names the first letter should be in Upper Case. Now type ' java MyFirstJavaProgram ' to run your program. 2. . 5.java C : > java MyFirstJavaProgram Hello World Basic Syntax: About Java programs. You will be able to see ' Hello World ' printed on the window. If there are no errors in your code the command prompt will take you to the next line.out. Save the file as : MyFirstJavaProgram. public class MyFirstJavaProgram{ /* This is my first java program. // prints Hello World } } Lets look at how to save the file. • Example class MyFirstJavaClass Method Names .java.
. In java there are several points to remember about identifiers. $salary. Example : Assume 'MyFirstJavaProgram' is the class name. currency character ($) or an underscore (-). then each inner word's first letter should be in Upper Case. • • Access Modifiers : defualt. (if the file name and the class name do not match your program will not compile). When saving the file you should save it using the class name (Remember java is case sensitive) and append '. abstract. They are as follows: • • • • • • All identifiers should begin with a letter (A to Z or a to z ). There are two categories of modifiers.If several words are used to form the name of the method. public .java program processing starts from the main() method which is a mandatory part of every java program. Names used for classes. • Example public void myMethodName() Program File Name . -salary Java Modifiers: Like other languages it is possible to modify classes. A key word cannot be used as an identifier. Then the file should be saved as 'MyFirstJavaProgram. Most importantly identifiers are case sensitive.Name of the program file should exactly match the class name. variables and methods are called identifiers. After the first character identifiers can have any combination of characters.java' to the end of the name. _value. • Java Identifiers: All java components require names. private Non-access Modifiers : final. __1_value Examples of illegal identifiers : 123abc. methods etc by using modifiers. strictfp We will be looking into more details about modifiers in the next section. protected. Examples of legal identifiers:age. Java Variables: .java' public static void main(String args[]) .
0. We will look into how to declare. construct and initialize in the upcoming chapters. Java Keywords: The following list shows the reserved words in Java. juice. } } Note: enums can be declared as their own or inside a class. FreshJuiceSize. Example: class FreshJuice{ enum FreshJuiceSize{ SIZE. MEDUIM. Methods.We would see following type of variables in Java: • • • Local Variables Class Variables (Static Variables) Instance Variables (Non static variables) Java Arrays: Arrays are objects that store multiple variables of the same type. LARGE } FreshJuiceSize size. This would make sure that it would not allow anyone to order any size other than the small. However an Array itself is an object on the heap. variables. } public class FreshJuiceTest{ public static void main(String args[]){ FreshJuice juice = new FreshJuice(). Enums restrict a variable to have one of only a few predefined values.size = FreshJuice. medium and Large. With the use of enums it is possible to reduce the number of bugs in your code. . medium or large.MEDUIM . The values in this enumerated list are called enums. These reserved words may not be used as constant or variable or any other identifier names. For example if we consider an application for a fresh juice shop it would be possible to restrict the glass size to small. Java Enums: Enums were introduced in java 5. constructors can be defined inside enums as well.
public class MyFirstJavaProgram{ /* This is my first java program. * This will print 'Hello World' as the output * This is an example of multi-line comments.println("Hello World"). */ public static void main(String []args){ // This is an example of single line comment /* This is also an example of single line comment. All characters available inside any comment are ignored by Java compiler++. } } Using Blank Lines: .out. */ System.
Basically if you need to create a new class and here is already a class that has some of the code you require. What is Next ? The next section explains about Objects and classes in Java programming.A line containing only whitespace. An interface defines the methods. Interfaces: In Java language an interface can be defined as a contract between objects on how to communicate with each other. This concept allows you to reuse the fields and methods of the existing class with out having to rewrite the code in a new class. Inheritance: In java classes can be derived from classes. is known as a blank line. a deriving class(subclass) should use. and Java totally ignores it. But the implementation of the methods is totally up to the subclass. possibly with a comment. As a language that has the Object Oriented feature Java supports the following fundamental concepts: • • • • • • • • • Polymorphism Inheritance Encapsulation Abstraction Classes Objects Instance Method Message Parsing . Interfaces play a vital role when it comes to the concept of inheritance. then it is possible to derive your new class from the already existing code. At the end of the session you will be able to get a clear picture as to what are objects and what are classes in java. In this scenario the existing class is called the super class and the derived class is called the subclass. Java Objects and Classes Java is an Object Oriented Language.
eating. All these objects have a state and behavior. If we consider the real-world we can find many objects around us. barking. barking. Cars. name. they have very similar characteristics. and the behavior is . An object is an instance of a class. breed as well as behaviors -wagging. String color.Objects have states and behaviors. A software object's state is stored in fields and behavior is shown via methods.In this chapter we will look into the concepts Classes and Objects. So in software development methods operate on the internal state of an object and the object-to-object communication is done via methods. name. Humans etc. • • Object . Software objects also have a state and behavior. void barking(){ } void hungry(){ } void sleeping(){ } } .A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support. If we consider a dog then its state is . running If you compare the software object with a real world object. Classes in Java: A class is a blue print from which individual objects are created. A sample of a class is given below: public class Dog{ String breed. Example: A dog has states-color. Class . int age. Objects in Java: Let us now look deep into what are objects. Dogs. color. breed. wagging.
A class can have more than one constructor. The main rule of constructors is that they should have the same name as the class. Each time a new object is created at least one constructor will be invoked. Class variables are variables declared with in a class. These variables are instantiated when the class is loaded. constructors or blocks are called local variables. Below mentioned are some of the important topics that need to be discussed when looking into classes of the Java Language. Instance variables are variables within a class but outside any method. name. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Constructors: When discussing about classes one of the most important sub topic would be constructors. In the above example. outside any method. with the static keyword. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class. barking(). } } Java also supports Singleton Classes where you would be able to create only one instance of a class.A class can contain any of the following variable types. Instance variables can be accessed from inside any method. hungry() and sleeping() are variables. Instance variables . • • • Local variables . variables defined inside methods. constructor or blocks of that particular class. A class can have any number of methods to access the value of various kind of methods. Example of a constructor is given below: class Puppy{ public puppy(){ } public puppy(String name){ // This constructor has one parameter. Class variables . Creating an Object: . Every class has a constructor.
So basically an object is created from a class. A variable declaration with a variable name with an object type. /* Now call a variable as follows */ ObjectReference.println("Passed Name is :" + name ).MethodName(). Instantiation . In java the new key word is used to create new objects.As mentioned previously a class provides the blueprints for objects. System. To access an instance variable the fully qualified path should be as follows: /* First create an object */ ObjectReference = new Constructor(). Example: This example explains how to access instance variables and methods of a class: . name. /* Now you can call a class method as follows */ ObjectReference.variableName. } } If we compile and run the above program then it would produce following result: Passed Name is :tommy Accessing Instance Variables and Methods: Instance variables and methods are accessed via created objects. Initialization . This call initializes the new object. Example of creating an object is given below: class Puppy{ public Puppy(String name){ // This constructor has one parameter. The 'new' key word is used to create the object. } public static void main(String []args){ // Following statement would create an object myPuppy Puppy myPuppy = new Puppy( "tommy" ).out. There are three steps when creating an object from a class: • • • Declaration . The 'new' keyword is followed by a call o a constructor.
setAge( 2 ).java.class Puppy{ int puppyAge. public class Employee{} Then the source file should be as Employee. . } } If we compile and run the above program then it would produce following result: Passed Name is :tommy Puppy's age is :2 Variable Value :2 Source file declaration rules: As the last part of this section lets us now look into the source file declaration rules. public Puppy(String name){ // This constructor has one parameter.println("Variable Value :" + myPuppy.out. import statements and package statements in a source file. } public static void main(String []args){ /* Object creation */ Puppy myPuppy = new Puppy( "tommy" ).getAge( ).out. The public class name should be the name of the source file as well which should be appended by . } public setAge( int age ){ puppyAge = age. /* Call class method to set puppy's age */ myPuppy. /* Call another class method to get puppy's age */ myPuppy.puppyAge ). /* You can access instance variable as follows as well */ System. These rules are essential when declaring classes. A source file can have multiple non public classes.java at the end. then the package statement should be the first statement in the source file. For example : The class name is .out. name. If the class is defined inside a package. System.println("Passed Name is :" + name ). • • • • There can be only one public class per source file. return puppyAge.println("Puppy's age is :" + puppyAge ). } public getAge( ){ System.
When developing applications in Java. hundreds of classes and interfaces will be written. is given then the compiler can easily locate the source code or classes.io. I will be explaining about all these in the access modifiers chapter. designation and salary. Import statements: In java if a fully qualified name. First open notepad and add the following code.io. import java. . public class Employee{ String name. They are Employee and EmployeeTest. For example following line would ask compiler to load all the classes available in directory java_installation/java/io : import java. Import and package statements will imply to all the classes present in the source file. therefore categorizing these classes is a must as well as makes life much easier. Java also has some special classes called Inner classes and Anonymous classes. Classes have several access levels and there are different types of classes. Java Package: In simple it is a way of categorizing the classes and interfaces. Apart from the above mentioned types of classes. Remember this is the Employee class and the class is a public class. If there are no package statements then the import statement should be the first line in the source file. Now save this source file with the name Employee. It is not possible to declare different import and/or package statements to different classes in the source file. final classes etc. age. A Simple Case Study: For our case study we will be creating two classes.*. abstract classes. The Employee class has four class variables name. The class has one explicitly defined constructor which takes a parameter.*. Import statement is a way of giving the proper location for the compiler to find that particular class.• • If import statements are present then they must be written between the package statement and the class declaration. which includes the package and the class name.java.
empTwo. Therefore in-order for us to run this Employee class there should be main method and objects should be created. We will be creating a separate class for these tasks.out. double salary.out.*. System. empOne.println("Salary:" + salary). System. } /* Assign the designation to the variable designation.empAge(21).*/ public void empDesignation(String empDesig){ designation = empDesig. empOne.println("Name:"+ name ). } } As mentioned previously in this tutorial processing starts from the main method. .java file import java.empDesignation("Senior Software Engineer"). // Invoking methods for each object created empOne.empAge(26). empTwo. public class EmployeeTest{ public static void main(String args[]){ /* Create two objects using constructor */ Employee empOne = new Employee("James Smith"). // This is the constructor of the class Employee public Employee(String name){ this.printEmployee().out. } /* Assign the salary to the variable salary.out.io. Employee empTwo = new Employee("Mary Anne"). } // Assign the age of the Employee to the variable age.empDesignation("Software Engineer"). Given below is the EmployeeTest class which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.println("Designation:" + designation ). String designation.empSalary(1000).int age.println("Age:" + age ). System. } /* Print the Employee details */ public void printEmployee(){ System.name = name. empOne. Save the following code in EmployeeTest. public void empAge(int empAge){ age = empAge.*/ public void empSalary(double empSalary){ salary = empSalary.
There are two data types available in Java: 1. the operating system allocates memory and decides what can be stored in the reserved memory. Java Basic Data Types Variables are nothing but reserved memory locations to store values. Based on the data type of a variable. Therefore. by assigning different data types to variables.java C :> javac EmployeeTest. or characters in these variables. Let us now look into detail about the eight primitive data types.0 Name:Mary Anne Age:21 Designation:Software Engineer Salary:500. empTwo. Now compile both the classes and then run EmployeeTest to see the result as follows: C :> javac Employee. Reference/Object Data Types Primitive Data Types: There are eight primitive data types supported by Java. This means that when you create a variable you reserve some space in memory.printEmployee().java C :> vi EmployeeTest. Primitive Data Types 2. Primitive data types are predefined by the language and named by a key word. . decimals. you can store integers.} } empTwo.empSalary(500).0 What is Next ? Next session will discuss basic data types in java and how they can be used when developing java applications.java C :> java EmployeeTest Name:James Smith Age:26 Designation:Senior Software Engineer Salary:1000.
0f.223.854. since a byte is four times smaller than an int.(-2^63) Maximum value is 9. Float data type is never used for precise values such as currency.223. A short is 2 times smaller than an int Default value is 0.byte: • • • • • • Byte data type is a 8-bit signed two.648.854. Example : int a = 100000.775.372.036.(-2^31) Maximum value is 2. . short r = -20000 int: • • • • • • Int data type is a 32-bit signed two's complement integer.767(inclusive) (2^15 -1) Short data type can also be used to save memory as byte data type.775. Default value is 0L. Default value is 0.372.807 (inclusive). int b = -200000L float: • • • • Float data type is a single-precision 32-bit IEEE 754 floating point. Example : int a = 100000L.2.483.147. Minimum value is -128 (-2^7) Maximum value is 127 (inclusive)(2^7 -1) Default value is 0 Byte data type is used to save space in large arrays.768 (-2^15) Maximum value is 32.483. (2^63 -1) This type is used when a wider range than int is needed.147. mainly in place of integers. byte b = -50 short: • • • • • • Short data type is a 16-bit signed two's complement integer. Example : byte a = 100 . Minimum value is -9.808.(2^31 -1) Int is generally used as the default data type for integral values unless there is a concern about memory. Minimum value is -32.036. Float is mainly used to save memory in large arrays of floating point numbers. The default value is 0.647(inclusive). Example : short s= 10000 .s complement integer. int b = -200000 long: • • • • • • Long data type is a 64-bit signed two's complement integer. Minimum value is .
Example : boolean one = true char: • • • • • char data type is a single 16-bit Unicode character. There are only two possible values : true and false. Default value is false. generally the default choice. Example . This data type is used for simple flags that track true/false conditions. Default value of any reference variable is null. Double data type should never be used for precise values such as currency.4 boolean: • • • • • boolean data type represents one bit of information. Java Literals: A literal is a source code representation of a fixed value. Default value is 0. Maximum value is '\uffff' (or 65. They are used to access objects. They are represented directly in the code without any computation. Example : double d1 = 123. This data type is generally used as the default data type for decimal values. These variables are declared to be of a specific type that cannot be changed.0d. Literals can be assigned to any primitive type variable. and various type of array variables come under reference data type. For example. char letterA ='A' Reference Data Types: • • • • • Reference variables are created using defined constructors of the classes. For example: .5f double: • • • • • double data type is a double-precision 64-bit IEEE 754 floating point. Example : Animal animal = new Animal("giraffe").• Example : float f1 = 234. Employee.535 inclusive). Char data type is used to store any character. A reference variable can be used to refer to any object of the declared type or any compatible type. Class objects. Puppy etc. Minimum value is '\u0000' (or 0).
They are: Notation \n \r \f \b \s \t \" \' \\ Character represented Newline (0x0a) Carriage return (0x0d) Formfeed (0x0c) Backspace (0x08) Space (0x20) tab Double quote Single quote backslash . int octal = 0144. For example: char a = '\u0001'. int. long. Examples of string literals are: "Hello World" "two\nlines" "\"This is in quotes\"" String and char types of literals can contain any Unicode characters. and short can be expressed in decimal(base 10).byte a = 68. char a = 'A' byte.hexadecimal(base 16) or octal(base 8) number systems as well. Java language supports few special escape sequences for String and char literals as well. String a = "\u0001". For example: int decimal = 100. int hexa = 0x64. Prefix 0 is used to indicates octal and prefix 0x indicates hexadecimal when using these number systems for literals. String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes.
// the variable x has the value 'x'. b. constructor or block.14159. // declares three ints. f = 5. The identifier is the name of the variable. Local variables are visible only within the declared method. identifier [= value] .\ddd \uxxxx Octal character (ddd) Hexadecimal UNICODE character (xxxx) What is Next ? This chapter explained you various data types. Local variables are created when the method. constructors.. constructor or block is entered and the variable will be destroyed once it exits the method. The type is one of Java's datatypes. Here are several examples of variable declarations of various types.. constructor or block. char x = 'x'. // declares an approximation of pi. The basic form of a variable declaration is shown here: type identifier [ = value][. Instance variables 3. Class/static variables Local variables : • • • • Local variables are declared in methods. int a. byte z = 22. use a comma-separated list.] . Next topic explains different variable types and their usage. interfaces etc. // initializes z. c. Local variables 2. To declare more than one variable of the specified type. double pi = 3. all variables must be declared before they can be used. a. This chapter will explain varioys variable types available in Java Language. initializing // d and f. and c. int d = 3. e. Note that some include an initialization. Access modifiers cannot be used for local variables. or blocks. // declares three more ints. Java Variable Types In Java. b. This will give you a good understanding about how they can be used in the java classes. . There are three kinds of variables in Java: 1.
There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use. age = age + 7. Test. public class Test{ public void pupAge(){ int age = 0. ^ . Example: Here age is a local variable.• • Local variables are implemented at stack level internally. Test. System.pupAge(). } } This would produce following result: Puppy age is: 7 Example: Following example uses age without initializing it. System. } } This would produce following error while compiling it: Test.println("Puppy age is : " + age) } public static void main(String args[]){ Test test = new Test().println("Puppy age is : " + age) } public static void main(String args[]){ Test test = new Test().pupAge().out. age = age + 7.out. This is defined inside pupAge() method and its scope is limited to this method only. public class Test{ public void pupAge(){ int age.java:4:variable number might not have been initialized age = age + 7. so it would give an error at the time of compilation.
or essential parts of an object. The instance variables are visible for all methods. constructor or any block. constructor or block.*.VariableName. public Employee (String empName){ name = empName. // salary variable is visible in Employee class only. ObjectReference. // The name variable is assigned in the constructor. public void setSalary(double empSal){ salary = empSal. private double salary. Instance variables hold values that must be referenced by more than one method. Values can be assigned during the declaration or within the constructor. constructors and block in the class. Instance variables can be declared in class level before or after use. When a space is allocated for an object in the heap a slot for each instance variable value is created. public String name. However within static methods and different class ( when instance variables are given accessibility) the should be called using the fully qualified name . For numbers the default value is 0.However visibility for subclasses can be given for these variables with the use of access modifiers. } // The salary variable is assigned a value. Normally it is recommended to make these variables private (access level). for Booleans it is false and for object references it is null.io. Instance variables have default values. } // This method prints the employee details. class Employee{ // this instance variable is visible for any child class. . but outside a method. Access modifiers can be given for instance variables.1 error Instance variables : • • • • • • • • • Instance variables are declared in a class. Instance variables can be accessed directly by calling the variable name inside the class.s state that must be present through out the class. Example: import java. Instance variables are created when an object is created with the use of the key word 'new' and destroyed when the object is destroyed.
VariableName.printEmp(). Static variables can be accessed by calling with the class name . empOne. then variables names (constants) are all in upper case. Values can be assigned during the declaration or within the constructor. Default values are same as instance variables.io. Visibility is similar to instance variables. but outside a method. } public static void main(String args[]){ Employee empOne = new Employee("Ransika"). When declaring class variables as public static final.out.public void printEmp(){ System. It is rare to use static variables other than declared final and used as either public or private constants. If the static variables are not public and final the naming syntax is the same as instance and local variables.0 Class/static variables : • • • • • • • • • Class variables also known as static variables are declared with the static keyword in a class.out. constructor or a block.setSalary(1000). Additionally values can be assigned in special static initializer blocks. Static variables are rarely used other than being declared as constants. System. For numbers the default value is 0. empOne. However. Constant variables never change from their initial value.*.println("salary :" + salary). Constants are variables that are declared as public/private. Static variables are created when the program starts and destroyed when the program stops. regardless of how many objects are created from it. for Booleans it is false and for object references it is null. class Employee{ . There would only be one copy of each class variable per class. Static variables are stored in static memory. most static variables are declared public since they must be available for users of the class. ClassName. Example: import java. } } This would produce following result: name : Ransika salary :1000.println("name : " + name ). final and static.
you include its keyword in the definition of a class.// salary variable is a private static variable private static double salary. public static void main(String[] arguments) { // body of method } . public static void main(String args[]){ salary = 1000.println(DEPARTMENT+"average salary:"+salary).out. System.DEPARTMENT What is Next ? You already have used access modifiers ( public & private ) in this chapter. including the following: • • Java Access Modifiers Non Access Modifiers To use a modifier. as in the following examples (Italic ones): public class className { // . The next chapter will explain you Access Modifiers and Non Access Modifiers in detail. // DEPARTMENT is a constant public static final String DEPARTMENT = "Development". } } This would produce following result: Development average salary:1000 Note: If the variables are access from an outside class the constant should be accessed as Employee. } private boolean myFlag. protected static final int BOXWIDTH = 42. Java Modifier Types Modifiers are keywords that you add to those definitions to change their meanings.. The modifier precedes the rest of the statement. method. or variable.5.. The Java language has a wide variety of modifiers. static final double weeks = 9.
• • • • The static modifier for creating class methods and variables The final modifier for finalizing the implementations of classes. What is Next ? In the next section I will be discussing about Basic Operators used in the Java Language. methods. 4. The chapter will give you an overview of how these operators can be used during application development. Visible to the class only (private). variables. and variables. We can divide all the Java operators into the following groups: • • • • • • Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Misc Operators The Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. which are used for threads. the default. No modifiers are needed. The four access levels are: 1. The following table lists the arithmetic operators: . Java Basic Operators Java provides a rich set of operators to manipulate variables. Non Access Modifiers: Java provides a number of non-access modifiers to achieve many other functionality. 3. Visible to the world (public). The abstract modifier for creating abstract classes and methods. methods and constructors. 2. Visible to the package and all subclasses (protected). Visible to the package. The synchronized and volatile modifiers.Access Control Modifiers: Java provides a number of access modifiers to set access levels for classes.
Example (A == B) is not true.Assume integer variable A holds 10 and variable B holds 20 then: Show Examples Operator + * / Description Addition .Decrease the value of operand by 1 Example A + B will give 30 A .Multiplies values on either side of the operator Division . .B will give -10 A * B will give 200 B / A will give 2 % B % A will give 0 ++ -- B++ gives 21 B-.Divides left hand operand by right hand operand Modulus .Divides left hand operand by right hand operand and returns remainder Increment .Increase the value of operand by 1 Decrement . Checks if the value of two operands are equal or not. != (A != B) is true.Subtracts right hand operand from left hand operand Multiplication .Adds values on either side of the operator Subtraction . if yes then condition becomes true.gives 19 The Relational Operators: There are following relational operators supported by Java language Assume variable A holds 10 and variable B holds 20 then: Show Examples Operator == Description Checks if the value of two operands are equal or not. if values are not equal then condition becomes true.
yes then condition becomes true.> Checks if the value of left operand is greater than the value of right operand. Checks if the value of left operand is greater than or equal to the value of right operand. >= (A >= B) is not true. and byte. operand. char. (A > B) is not true. if yes then condition becomes true. <= Checks if the value of left operand is less than or equal to the value of right (A <= B) is true. int. and b = 13. Assume if a = 60. < Checks if the value of left operand is less than the value of right operand. if yes then condition becomes true. short. long. The Bitwise Operators: Java defines several bitwise operators which can be applied to the integer types. if yes then condition becomes true.: . Bitwise operator works on bits and perform bit by bit operation. if (A < B) is true.
The left operands value is moved right by the number of bits specified by the right operand. The left operands value is moved left by the number of bits specified by the right operand. Shift right zero fill operator. A << 2 will give 240 which is 1111 0000 ~ << >> A >> 2 will give 15 which is 1111 >>> A >>>2 will give 15 which is 0000 1111 The Logical Operators: The following table lists the logical operators: Assume boolean variables A holds true and variable B holds false then: Show Examples Operator && Description Example Called Logical AND operator.Show Examples Operator & | ^ Description Example Binary AND Operator copies a bit to (A & B) will give 12 which is 0000 the result if it exists in both operands. . If both the operands are non zero then then (A && B) is false. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. Binary Left Shift Operator. (A | B) will give 61 which is 0011 1101 Binary XOR Operator copies the bit if (A ^ B) will give 49 which is 0011 it is set in one operand but not both. condition becomes true. 1100 Binary OR Operator copies a bit if it exists in eather operand. 0001 Binary Ones Complement Operator is (~A ) will give -60 which is 1100 unary and has the efect of 'flipping' 0011 bits. Binary Right Shift Operator.
A *= Multiply AND assignment operator. It multiplies right C *= A is equivalent to C = C * A operand with the left operand and assign the result to left operand Divide AND assignment operator. If a condition is true then !(A && B) is true.|| Called Logical OR Operator. It divides left operand C /= A is equivalent to C = C / A with the right operand and assign the result to left operand Modulus AND assignment operator. Use to reverses the logical state of its operand. It adds right operand to the left operand and assign the result to left operand Subtract AND assignment operator. Called Logical NOT Operator. It takes modulus using C %= A is equivalent to C = C % A /= %= . then condition becomes true. Assigns values from right side operands to left side operand Add AND assignment operator. Logical NOT operator will make false. It subtracts right operand from the left operand and assign the result to left operand Example C = A + B will assigne value of A + B into C += C += A is equivalent to C = C + A -= C -= A is equivalent to C = C . If any of the two operands are non zero then (A || B) is true. ! The Assignment Operators: There are following assignment operators supported by Java language: Show Examples Operator = Description Simple assignment operator.
The goal of the operator is to decide which value should be assigned to the variable. b = (a == 1) ? 20: 30. } } b = (a == 10) ? 20: 30.println( "Value of b is : " + b ).two operands and assign the result to left operand <<= >>= &= ^= |= Left shift AND assignment operator Right shift AND assignment operator Bitwise AND assignment operator bitwise exclusive OR and assignment operator bitwise inclusive OR and assignment operator. This operator consists of three operands and is used to evaluate boolean expressions.println( "Value of b is : " + b ). Conditional Operator ( ? : ): Conditional operator is also known as the ternary operator. The operator is written as : variable x = (expression) ? value if true : value if false Following is the example: public class Test { public static void main(String args[]){ int a . b. System.out.out. System. a = 10. This would produce following result: .
out. Following is one more example: class Vehicle {} public class Car extends Vehicle { public static void main(String args[]){ Vehicle a = new Car(). } } This would produce following result: true Precedence of Java Operators: Operator precedence determines the grouping of terms in an expression. Certain operators have higher precedence than others. Here x is assigned 13. System. Following is the example: String name = = 'James'. boolean result = a instanceof Car. boolean result = s instanceOf String. This affects how an expression is evaluated.. for example.Value of b is : 30 Value of b is : 20 instanceOf Operator: This operator is used only for object reference variables. . the multiplication operator has higher precedence than the addition operator: For example x = 7 + 3 * 2. not 20 because operator * has higher precedenace than + so it first get multiplied with 3*2 and then adds into 7. // This will return true since name is type of String This operator will still return true if the object being compared is the assignment compatible with the type on the right. The operator checks whether the object is of a particular type(class type or interface type).println( result).
.! ~ */% +>> >>> << > >= < <= == != & ^ | && || ?: = += -= *= /= %= >>= <<= &= ^= |= .. those with the lowest appear at the bottom. higher precedenace operators will be evaluated first. Category Postfix Unary Multiplicative Additive Shift Relational Equality Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Assignment Comma Operator () [] . Within an expression. (dot operator) ++ . and is often referred to as a loop.Here operators with the highest precedence appear at the top of the table. The chapter will describe various types of loops and how these loops can be used in Java program development and for what purposes they are being used. Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left Left to right What is Next ? Next chapter would explain about loop control in Java programming. . Java Loops ..while There may be a sitution when we need to execute a block of code several number of times.for. while and do.
Java has very flexible three looping mechanisms. Syntax: The syntax of a while loop is: while(Boolean_expression) { //Statements } When executing. When the expression is tested and the result is false.out. while( x < 20 ){ System. System.print("value of x : " + x ).while Loop for Loop As of java 5 the enhanced for loop was introduced. Here key point of the while loop is that the loop might not ever run. if the boolean_expression result is true then the actions inside the loop will be executed. You can use one of the following three loops: • • • while Loop do. The while Loop: A while loop is a control structure that allows you to repeat a task a certain number of times..print("\n").. x++.out. } } } This would produce following result: value of x : 10 . This will continue as long as the expression result is true. Example: public class Test { public static void main(String args[]){ int x= 10. This is mainly used for Arrays. the loop body will be skipped and the first statement after the while loop will be executed.
. This process repeats until the Boolean expression is false.while loop is guaranteed to execute at least one time.while Loop: A do.. } } This would produce following result: value of x : 10 . Notice that the Boolean expression appears at the end of the loop.print("\n"). and the statements in the loop execute again.out.out... Example: public class Test { public static void main(String args[]){ int x= 10. If the Boolean expression is true.. System. the flow of control jumps back up to do. so the statements in the loop execute once before the Boolean is tested.. x++. }while( x < 20 )..while loop is similar to a while loop.while loop is: do { //Statements }while(Boolean_expression). except that a do. do{ System.value value value value value value value value value of of of of of of of of of x x x x x x x x x : : : : : : : : : 11 12 13 14 15 16 17 18 19 The do..print("value of x : " + x ). Syntax: The syntax of a do.
the for loop terminates. the body of the loop is executed.value value value value value value value value value of of of of of of of of of x x x x x x x x x : : : : : : : : : 11 12 13 14 15 16 17 18 19 The for Loop: A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. the flow of control jumps back up to the update statement. update) { //Statements } Here is the flow of control in a for loop: 1. After the body of the for loop executes. as long as a semicolon appears. This step allows you to declare and initialize any loop control variables.then Boolean expression). A for loop is useful when you know how many times a task is to be repeated. If it is true. and only once. 3. The initialization step is executed first. Boolean_expression. Syntax: The syntax of a for loop is: for(initialization. After the Boolean expression is false. If it is true. the loop executes and the process repeats itself (body of loop. 2. Next. If it is false. 4. as long as a semicolon appears after the Boolean expression. The Boolean expression is now evaluated again. the Boolean expression is evaluated. the body of the loop does not execute and flow of control jumps to the next statement past the for loop. Example: public class Test { public static void main(String args[]){ . You are not required to put a statement here. This statement allows you to update any loop control variables. This statement can be left blank. then update step.
} }
for(int x = 10; x < 20; x = x+1){ System.out.print("value of x : " + x ); System.out.print("\n"); }
This would produce following result:
value value value value value value value value value value of of of of of of of of of of x x x x x x x x x x : : : : : : : : : : 10 11 12 13 14 15 16 17 18 19
Enhanced for loop in Java:
As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression) { //Statements } •
•
Declaration . The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element. Expression . This evaluate would produce following result:
10,20,30,40,50, James,Larry,Tom,Lacy,:
break;
Example:
public class Test { public static void main(String args[]){ int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){ if( x == 30 ){ break; } System.out.print( x ); System.out.print("\n"); }
} }
This would produce following result:
10 20
The continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
• •"); }
} }
This would produce following result:
10 20 40 50
What is Next ?
In the following chapter we will be learning about decision making statements in Java programming.
Java Decision Making
Syntax: The syntax of an if statement is: if(Boolean_expression) { //Statements will execute if the Boolean expression is true } If the boolean expression evaluates to true then the block of code inside the if statement will be executed. } } } This would produce following result: This is if statement The if.out. . They are: • • if statements switch statements The if Statement: An if statement consists of a Boolean expression followed by one or more statements..There are two types of decision making statements in Java.print("This is if statement").else Statement: An if statement can be followed by an optional else statement.. If not the first set of code after the end of the if statement(after the closing curly brace) will be executed. Example: public class Test { public static void main(String args[]){ int x = 10. which executes when the Boolean expression is false. if( x < 20 ){ System.
else is: if(Boolean_expression){ //Executes when the Boolean expression is true }else{ //Executes when the Boolean expression is false } Example: public class Test { public static void main(String args[]){ int x = 30.Syntax: The syntax of a if. Syntax: The syntax of a if....out..out.else.print("This is if statement")... }else{ System.print("This is else statement").else if statement. } } } This would produce following result: This is else statement The if.else statement.else Statement: An if statement can be followed by an optional else if... which is very usefull to test various conditions using single if.. } .. if( x < 20 ){ System...
if( x == 10 ){ System.. else if .. An if can have zero to many else if's and they must come before the else.out. . else statements there are few points to keep in mind..out.print("Value of X is 10").print("Value of X is 20").print("Value of X is 30"). }else if( x == 20 ){ System.else in the similar way as we have nested if statement..out...print("This is else statement"). }else{ System. none of he remaining else if's or else's will be tested. Syntax: The syntax for a nested if.Example: public class Test { public static void main(String args[]){ int x = 30. When using if .else is as follows: if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true } } You can nest else if. Once an else if succeeds. }else if( x == 30 ){ System. • • • An if can have zero or one else's and it must come after any else if's.out. } } } This would produce following result: Value of X is 30 Nested if. Example: public class Test { public static void main(String args[]){ int x = 30.else Statement: It is always legal to nest if-else statements.
out. The value for a case must be the same data type as the variable in the switch. Each value is called a case. the statements following that case will execute until a break statement is reached. When a break statement is reached.int y = 10. //optional case value : //Statements break. the switch terminates.print("X = 30 and Y = 10"). and it must be a constant or a literal. the flow of control will fall through to subsequent cases until a break is reached. } } } This would produce following result: X = 30 and Y = 10 The switch Statement: A switch statement allows a variable to be tested for equality against a list of values. You can have any number of case statements within a switch. Syntax: The syntax of enhanced for loop is: switch(expression){ case value : //Statements break. Each case is followed by the value to be compared to and a colon. int. default : //Optional //Statements } The following rules apply to a switch statement: • • • • • • The variable used in a switch statement can only be a byte. if( x == 30 ){ if( y == 10 ){ System. or char. and the variable being switched on is checked for each case. When the variable being switched on is equal to a case. and the flow of control jumps to the next line following the switch statement. //optional //You can have any number of case statements. . Not every case needs to contain a break. If no break appears. short.
which must appear at the end of the switch.println("Better try again"). No break is needed in the default case. switch(grade) { case 'A' : System.println("Your grade is " + grade). .println("Invalid grade").out. break. break.out. case 'F' : System.• A switch statement can have an optional default case.out. } System.println("Excellent!"). Example: public class Test { public static void main(String args[]){ char grade = args[0].println("You passed"). The default case can be used for performing a task when none of the cases is true.println("Well done").out.out. case 'B' : case 'C' : System.lang package) and its subclasses in Java Language. This would produce following result: $ java Test a Invalid grade Your grade is a a $ java Test A Excellent! Your grade is a A $ java Test C Well done Your grade is a C $ What is Next ? Next chapter discuses about the Number class (in the java. } } Compile and run above program using various command line arguments. default : System. case 'D' : System. break.out.charAt(0).
double etc. Here is an example of boxing and unboxing: public class Test{ public static void main(String args[]){ Integer x = 5. float gpa = 13. This wrapping is taken care of by the compiler The process is called boxing. Java .We will be looking into some of the situations where you would use instantiations of these classes rather than the primitive data types. Byte. Similarly the compiler unboxes the object to a primitive as well.out. Float. In-order to achieve this Java provides wrapper classes for each primitive data type.lang package. Long. as well as classes such as formatting.Number Class Normally. The Number is part of the java. // boxes int to an Integer object x = x + 10. Double. However in development we come across situations were we need to use objects instead of primitive data types.65. Example: int i = 5000. } } . int. // unboxes the Integer to a int System. we use primitive data types such as byte. All the wrapper classes ( Integer. So when a primitive is used when an object is required the compiler boxes the primitive type in its wrapper class. mathematical functions that you need to know about when working with Numbers.println(x). Short) are subclasses of the abstract class Number. byte mask = 0xaf. long. when we work with Numbers.
Later. Returned as a double. valueOf() Returns an Integer object holding the value of the specified primitive. rint() Returns the integer that is closest in value to the argument.This would produce following result: 5 When x is assigned integer values. Returned as a double. round() 8 9 10 11 . x is unboxed so that they can be added as integers. ceil() Returns the smallest integer that is greater than or equal to the argument. parseInt() This method is used to get the primitive data type of a certain String. toString() Returns a String object representing the value of specified int or Integer. floor() Returns the largest integer that is less than or equal to the argument. abs() Returns the absolute value of the argument. compareTo() Compares this Number object to the argument. Returned as a double. equals() Determines whether this number object is equal to the argument. Number Methods: Here is the list of the instance methods that all the subclasses of the Number class implement: SN 1 2 3 4 5 6 7 Methods with Description xxxValue() Converts the value of this Number object to the xxx data type and returned it. the compiler boxes the integer because x is integer objects.
atan2() Converts rectangular coordinates (x. e. sin() Returns the sine of the specified double value. exp() Returns the base of the natural logarithms. as indicated by the method's return type. . to the argument. y) to polar coordinate (r. log() Returns the natural logarithm of the argument. pow() Returns the value of the first argument raised to the power of the second argument. acos() Returns the arccosine of the specified double value.Returns the closest long or int. toDegrees() Converts the argument to degrees toRadians() Converts the argument to radians. sqrt() Returns the square root of the argument. 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 min() Returns the smaller of the two arguments. asin() Returns the arcsine of the specified double value. atan() Returns the arctangent of the specified double value. to the power of the argument. tan() Returns the tangent of the specified double value. theta) and returns theta. cos() Returns the cosine of the specified double value. max() Returns the larger of the two arguments. random() Returns a random number.
. 'b'. 'c'. Escape Sequences: . // an array of chars char[] charArray ={ 'a'. we use primitive data types char. Java . the compiler automatically converts the char to a Character for you. if the conversion goes the other way. You will be learning how to use object Characters and primitive data type char in Java.Character Class N ormally. However in development we come across situations were we need to use objects instead of primitive data types.What is Next ? In the next section we will be going through the Character class in Java. The Java compiler will also create a Character object for you under some circumstances. // Here primitive 'x' is boxed for method test. This feature is called autoboxing or unboxing. when we work with characters. // return is unboxed to char 'c' char c = test('x'). Example: // Here following primitive char 'a' // is boxed into the Character object ch Character ch = 'a'. 'd'. static) methods for manipulating characters. Example: char ch = 'a'.e. For example. In-order to achieve this Java provides wrapper classe Character for primitive data type char. 'e' }. if you pass a primitive char into a method that expects an object. You can create a Character object with the Character constructor: Character ch = new Character('a'). The Character class offers a number of useful class (i. // Unicode for uppercase Greek omega character char uniChar = '\u039A'.
println() statements to advance to the next line after the string is printed. Insert a backslash character in the text at this point. Insert a form feed in the text at this point.A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. When an escape sequence is encountered in a print statement. Insert a newline in the text at this point.println("She said \"Hello!\" to me.out.out. Insert a double quote character in the text at this point. Insert a single quote character in the text at this point. \". Insert a backspace in the text at this point. Insert a carriage return in the text at this point. the compiler interprets it accordingly. Following table shows the Java escape sequences: Escape Sequence \t \b \n \r \f \' \" \\ Description Insert a tab in the text at this point. on the interior quotes: public class Test{ public static void main(String args[]){ System. The newline character (\n) has been used frequently in this tutorial in System. Character Methods: . } } This would produce following result: She said "Hello!" to me."). Example: If you want to put quotes within quotes you must use the escape sequence.
which are widely used in Java programming. toLowerCase() Returns the lowercase form of the specified char value. isWhitespace() Determines whether the specified char value is white space. are a sequence of characters. isUpperCase() Determines whether the specified char value is uppercase. In the Java programming language.String Class Strings. toString() Returns a String object representing the specified character valuethat is.lang. 8 For a complete list of methods. The Java platform provides the String class to create and manipulate strings. toUpperCase() Returns the uppercase form of the specified char value.Character API specification. What is Next ? In the next section we will be going through the String class in Java. Java . a onecharacter string. isLowerCase() Determines whether the specified char value is lowercase.Here is the list of the important instance methods that all the subclasses of the Character class implement: SN 1 2 3 4 5 6 7 Methods with Description isLetter() Determines whether the specified char value is a letter. strings are objects. isDigit() Determines whether the specified char value is a digit. You will be learning how to declare and use Strings efficiently as well as some of the important methods in the String class. please refer to the java. .
'l'. } } .'}. so that once it is created a String object cannot be changed. } } This would produce following result: hello Note: The String class is immutable. '. System. 'o'. "Hello world!'. If there is a necessity to make alot of modifications to Strings of characters then you should use String Buffer & String Builder Classes. Whenever it encounters a string literal in your code. len equals 17: public class StringDemo{ public static void main(String args[]){ String palindrome = "Dot saw I was Tod".out. String helloString = new String(helloArray). String Length: Methods used to obtain information about an object are known as accessor methods. the compiler creates a String object with its valuein this case.println( helloString ). you can create String objects by using the new keyword and a constructor. such as an array of characters: public class StringDemo{ public static void main(String args[]){ char[] helloArray = { 'h'. One accessor method that you can use with strings is the length() method.Creating Strings: The most direct way to create a string is to write: String greeting = "Hello world!". As with any other object. int len = palindrome. 'e'.length(). 'l'. The String class has eleven constructors that allow you to provide the initial value of the string using different sources.println( "String Length is : " + len ).out. After the following two lines of code have been executed. System. which returns the number of characters contained in the string object.
that returns a String object rather than a PrintStream object. The String class has an equivalent class method. } } This would produce following result: Dot saw I was Tod Creating Format Strings: You have printf() and format() methods to print output with formatted numbers.out.concat(string2). format(). as in: "Hello.concat("Zara"). You can also use the concat() method with string literals. as in: "My name is ". world!" Let us look at the followinge example: public class StringDemo{ public static void main(String args[]){ String string1 = "saw I was ". Strings are more commonly concatenated with the + operator. System.This would produce following result: String Length is : 17 Concatenating Strings: The String class includes a method for concatenating two strings: string1. This returns a new string that is string1 with string2 added to it at the end. .println("Dot " + string1 + "Tod")." + " world" + "!" which results in: "Hello.
System. static String copyValueOf(char[] data) Returns a String that represents the character sequence in the array specified. floatVar. intVar. stringVar). instead of: System. int count) Returns a String that represents the character sequence in the array specified. int compareToIgnoreCase(String str) Compares two strings lexicographically. fs = String. as opposed to a one-time print statement. while the value of the integer " + "variable is %d.out. you can write: String fs. and the string " + "is %s".println(fs). boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.Using String's static format() method allows you to create a formatted string that you can reuse.printf("The value of the float variable is " + "%f.format("The value of the float variable is " + "%f. while the value of the integer " + "variable is %d.out. stringVar). ignoring case differences. int compareTo(String anotherString) Compares two strings lexicographically. int compareTo(Object o) Compares this String to another Object. For example. floatVar. String Methods: Here is the list methods supported by String class: SN 1 2 3 4 5 Methods with Description char charAt(int index) Returns the character at the specified index. String concat(String str) Concatenates the specified string to the end of this string. int offset. intVar. static String copyValueOf(char[] data. and the string " + "is %s". 6 7 8 .
starting the search at the specified index. int indexOf(String str. int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character. int srcEnd. storing the result into a new byte array. int fromIndex) Returns the index within this string of the last occurrence of the specified character. char[] dst. byte getBytes() Encodes this String into a sequence of bytes using the platform's default charset. int indexOf(int ch. int dstBegin) Copies characters from this string into the destination character array. int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. String intern() Returns a canonical representation for the string object. boolean equalsIgnoreCase(String anotherString) Compares this String to another String. byte[] getBytes(String charsetName Encodes this String into a sequence of bytes using the named charset. int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character. void getChars(int srcBegin. ignoring case considerations. boolean equals(Object anObject) Compares this string to the specified object. int lastIndexOf(int ch. int fromIndex) Returns the index within this string of the first occurrence of the specified character.9 10 11 boolean endsWith(String suffix) Tests if this string ends with the specified suffix. starting at the specified index. storing the result into a new byte array. int hashCode() Returns a hash code for this string. int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified 12 13 14 15 16 17 18 19 20 21 22 23 . int fromIndex) Returns the index within this string of the first occurrence of the specified substring. searching backward starting at the specified index.
int toffset) Tests if this string starts with the specified prefix beginning a specified index. int len) Tests if two string regions are equal. int toffset. boolean regionMatches(int toffset. String[] split(String regex) Splits this string around matches of the given regular expression. String substring(int beginIndex) Returns a new string that is a substring of this string. searching backward starting at the specified index. 24 int lastIndexOf(String str. boolean regionMatches(boolean ignoreCase. String replaceFirst(String regex. boolean startsWith(String prefix. int endIndex) 25 26 27 28 29 30 31 32 33 34 35 36 37 38 . boolean matches(String regex) Tells whether or not this string matches the given regular expression. boolean startsWith(String prefix) Tests if this string starts with the specified prefix. int fromIndex) Returns the index within this string of the last occurrence of the specified substring. String replacement Replaces each substring of this string that matches the given regular expression with the given replacement. int ooffset. CharSequence subSequence(int beginIndex.substring. char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement. int length() Returns the length of this string. String other. int len) Tests if two string regions are equal. String substring(int beginIndex. String[] split(String regex. int limit) Splits this string around matches of the given regular expression. String replace(char oldChar. int ooffset. String replaceAll(String regex. String other. int endIndex) Returns a new character sequence that is a subsequence of this sequence.
and process arrays using indexed variables. An array is used to store a collection of data. String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale.Arrays Java provides a data structure.. and . This tutorial introduces how to declare array variables. tring toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale. such as number0. 40 41 42 43 44 45 46 Java . with leading and trailing whitespace omitted. numbers[99] to represent individual variables. but it is often more useful to think of an array as a collection of variables of the same type. String toUpperCase(Locale locale) Converts all of the characters in this String to upper case using the rules of the given Locale. number1.. 39 char[] toCharArray() Converts this string to a new character array. Instead of declaring individual variables. create arrays. String toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale.... . the array. String toString() This object (which is already a string!) is itself returned. Declaring Array Variables: . numbers[1]. you declare one array variable such as numbers and use numbers[0].. static String valueOf(primitive data type x) Returns the string representation of the passed data type argument.Returns a new string that is a substring of this string. String trim() Returns a copy of the string. and number99. which stores a fixed-size sequential collection of elements of the same type.
// works but not preferred way.To use an array in a program. The above statement does two things: • • It creates an array using new dataType[arraySize]. or dataType arrayRefVar[].. Here is the syntax for declaring an array variable: dataType[] arrayRefVar. you must declare a variable to reference the array. and assigning the reference of the array to the variable can be combined in one statement. // preferred way. value1.. as shown below: dataType[] arrayRefVar = new dataType[arraySize]. or double myList[]. Alternatively you can create arrays as follows: dataType[] arrayRefVar = {value0. valuek}. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.. // works but not preferred way. . Example: The following code snippets are examples of this syntax: double[] myList. and you must specify the type of array the variable can reference. // preferred way. Declaring an array variable. Note: The style dataType[] arrayRefVar is preferred. Creating Arrays: You can create an array by using the new operator with the following syntax: arrayRefVar = new dataType[arraySize]. It assigns the reference of the newly created array to the variable arrayRefVar. . creating an array.
: double[] myList = new double[10]. Here myList holds ten double values and the indices are from 0 to 9. Array indices are 0-based.length-1. i < myList. myList. Example: Following statement declares an array variable. Following picture represents array myList. we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known. . and assigns its reference to myList. } // Summing all elements double total = 0.5}. i++) { System.The array elements are accessed through the index. Processing Arrays: When processing array elements.length. initialize and process arrays: public class TestArray { public static void main(String[] args) { double[] myList = {1.println(myList[i] + " "). // Print all the array elements for (int i = 0.out.9. 2. they start from 0 to arrayRefVar. Example: Here is a complete example of showing how to create.4. that is. 3. creates an array of 10 elements of double type. 3.9.
5 Total is 11.println("Total is " + total).println(element).5}.9.9 2.out.4. } } } This would produce following result: 1.5 The foreach Loops: JDK 1.length. } System. // Finding the largest element double max = myList[0].9 3. 2. i < myList.9. Example: The following code displays all the elements in the array myList: public class TestArray { public static void main(String[] args) { double[] myList = {1.out.4 3.9 2.5 introduced a new for loop. i < myList.5 . i++) { total += myList[i].4 3. This would produce following result: 1.7 Max is 3. for (int i = 1. known as foreach loop or enhanced for loop.length.9 3. } System.} } for (int i = 0. // Print all the array elements for (double element: myList) { System.println("Max is " + max).out. which enables you to traverse the complete array sequentially without using an index variable. 3. i++) { if (myList[i] > max) max = myList[i]. 3.
Arrays class contains various static methods for sorting and searching arrays. i++) { System. j--) { result[j] = list[i]. double etc) for the specified value using the binary search algorithm. for (int i = 0. The array must be sorted prior to making this call. and 2: printArray(new int[]{3. } result result. 1 . These methods are overloaded for all primitive types. 2. For example. SN Methods with Description public static int binarySearch(Object[] a.length]. i = result.Passing Arrays to Methods: Just as you can pass primitive type values to methods. 2. For example.util. you can also pass arrays to methods. i < array. For example. } } You can invoke it by passing an array.out. 1. Object key) Searches the specified array of Object ( Byte. } The Arrays Class: The java. i < list.1. ((insertion point + 1). 2}). 6. i++.print(array[i] + " "). the following method displays the elements in an int array: public static void printArray(int[] array) { for (int i = 0.length. the method shown below returns an array that is the reversal of another array: public static int[] reverse(int[] list) { int[] result = new int[list. Int .length. 4. 4. Returning an Array from a Method: A method may also return an array. and filling array elements. if it is contained in the list. 1.length . 6. the following statement invokes the printArray method to display 3. comparing arrays. This returns index of the search key. otherwise.
Int etc. otherwise. you can call any of the following support methods to play with dates: SN 1 Methods with Description boolean after(Date date) Returns true if the invoking Date object contains a date that is later than the one specified by date. this class encapsulates the current date and time. Date( ) The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight. otherwise. and all corresponding pairs of elements in the two arrays are equal.2 public static boolean equals(long[] a. according to the natural ordering of its elements. it returns false.) public static void sort(Object[] a) Sorts the specified array of objects into ascending order. January 1. Same method could be used by all other premitive data types ( Byte.) 3 4 Java . The Date class supports two constructors. it returns false. Two arrays are considered equal if both arrays contain the same number of elements. The first constructor initializes the object with the current date and time. int val) Assigns the specified int value to each element of the specified array of ints. short. This returns true if the two arrays are equal. Same method could be used by all other premitive data types ( Byte. boolean before(Date date) Returns true if the invoking Date object contains a date that is earlier than the one specified by date. Int etc. Same method could be used by all other premitive data types ( Byte. short.Date & Time Java provides the Date class available in java. short. long[] a2) Returns true if the two specified arrays of longs are equal to one another. 1970 Date(long millisec) Once you have a Date object available.util package.) public static void fill(int[] a. 2 . Int etc.
1970. 4 5 6 7 8 9 10 Getting Current Date & Time This is very easy to get current date and time in Java. Otherwise. class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date().util. which represents an elapsed time in milliseconds from midnight. int hashCode( ) Returns a hash code for the invoking object.out.Date. 1970 String toString( ) Converts the invoking Date object into a string and returns the result. int compareTo(Date date) Compares the value of the invoking object with that of date. } } This would produce following result: . boolean equals(Object date) Returns true if the invoking Date object contains the same time and date as the one specified by date. long getTime( ) Returns the number of milliseconds that have elapsed since January 1. int compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date. Returns a positive value if the invoking object is later than date. void setTime(long time) Sets the time and date as specified by time. it returns false. Returns a negative value if the invoking object is earlier than date.println(date.3 Object clone( ) Duplicates the invoking Date object. January 1. otherwise. // display time and date using toString() System. it throws a ClassCastException. You can use a simple Date object with toString() method to print current date and time as follows: import java. Returns 0 if the values are equal.toString()).
18)) returns true. } } System. This would produce following result: Sun 2004. Date Formatting using SimpleDateFormat: SimpleDateFormat is a concrete class for formatting and parsing dates in a localesensitive manner. after( ).MM. 12).text.18 at 04:14:09 PM PDT Simple DateFormat format codes: To specify the time format use a time pattern string. 1970.before(new Date (99. For example: import java.*. which are defined as the following: . class DateDemo { public static void main(String args[]) { Date dNow = new Date( ). new Date(99.07. and equals( ).println("Current Date: " + ft. You can use the methods before( ). SimpleDateFormat ft = new SimpleDateFormat ("E yyyy. In this pattern. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.out. You can use the compareTo( ) method.util. for both objects and then compare these two values. 2. January 1. Because the 12th of the month comes before the 18th. which is defined by the Comparable interface and implemented by Date. 2. for example.format(dNow)).*. all ASCII letters are reserved as pattern letters.Mon May 04 09:51:52 CDT 2009 Date Comparison: There are following three ways to compare two dates: • • • You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight.dd 'at' hh:mm:ss a zzz"). import java.
Character G y M d h H m s S E D F w W a k K z ' " Description Era designator Year in four digits Month in year Day in month Hour in A. For example: import java.M.M. You use a twoletter format.util./P.M. marker Hour in day (1~24) Hour in A.M./P. (1~12) Hour in day (0~23) Minute in hour Second in minute Millisecond Day in week Day in year Day of week in month Week in year Week in month A. starting with t and ending in one of the letters of the table given below.M. .M. (0~11) Time zone Escape for text Single quote AD 2001 July or 07 10 12 22 30 55 234 Tuesday 360 Example 2 (second Wed.Date. in July) 40 1 PM 24 10 Eastern Standard Time Delimiter ` Date Formatting using printf: Date and time formatting can be done very easily using printf method./P.
util. For that reason.Date. date).out. } } This would produce following result: Due date: February 09. "Due date:".printf("%tc". "Current Time : ". you can use the < flag. For example: import java. date). 2004 Alternatively.out. %<tY". // display time and date using toString() System.printf("%s %tB %<te. The index must immediately follow the %.out.util. . For example: import java.Date.class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(). // display formatted date System. It indicates that the same argument as in the preceding format specification should be used again. %2$tY". class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(). // display time and date using toString() System. class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(). } } This would produce following result: Current Time: Mon May 04 09:51:52 CDT 2009 It would be a bit silly if you had to supply the date multiple times to format each part. and it must be terminated by a $. a format string can indicate the index of the argument to be formatted.printf("%1$s %2$tB %2$td.
date). formatted date (month/day/year) 02/09/2004 24-hour time 12-hour time 24-hour time. } } This would produce following result: Due date: February 09.S."Due date:". no seconds Four-digit year (with leading zeroes) Last two digits of the year (with leading zeroes) First two digits of the year (with leading zeroes) Full month name Abbreviated month name Two-digit month (with leading zeroes) Two-digit day (with leading zeroes) Two-digit day (without leading zeroes) Full weekday name Abbreviated weekday name Three-digit day of year (with leading zeroes) 18:05:19 06:05:19 pm 18:05 2004 04 20 February Feb 02 03 9 Monday Mon 069 . 2004 Date and Time Conversion Characters: Character c F D T r R Y y C B b n d e A a j Description Complete date and time ISO 8601 date Example Mon May 04 09:51:52 CDT 2009 2004-02-09 U.
06 between 01 and 12 Two-digit hour (without leading zeroes). For more detail you can refer to Java Standard documentation. Parsing Strings into Dates: The SimpleDateFormat class has some additional methods.H k I l M S L N P p z Z s Q Two-digit hour (with leading zeroes). notably parse( ) . between 1 and 12 Two-digit minutes (with leading zeroes) Two-digit seconds (with leading zeroes) Three-digit milliseconds (with leading zeroes) 6 05 19 047 Nine-digit nanoseconds (with leading 047000000 zeroes) Uppercase morning or afternoon marker Lowercase morning or afternoon marker RFC 822 numeric offset from GMT Time zone Seconds since 1970-01-01 00:00:00 GMT Milliseconds since 1970-01-01 00:00:00 GMT PM pm -0800 PST 1078884319 1078884319047 There are other useful classes related to Date and time. which tries to parse a string according to the format stored in the given SimpleDateFormat object. between 0 and 23 18 Two-digit hour (with leading zeroes). For example: . 18 between 00 and 23 Two-digit hour (without leading zeroes).
class SleepDemo { public static void main(String args[]) { try { System.println("Got an exception!"). } } } A sample run of the above program would produce following result: $ java DateDemo 1818-11-11 Parses as Wed Nov 11 00:00:00 GMT 1818 $ java DateDemo 2007-12-01 2007-12-01 Parses as Sat Dec 01 00:00:00 GMT 2007 Sleeping for a While: You can sleep for any period of time from one millisecond up to the lifetime of your computer.out. try { t = ft.out.out.*. } } } This would produce following result: . } catch (Exception e) { System. Date t. following program would sleep for 10 seconds: import java.parse(input). System.println(new Date( ) + "\n").sleep(5*60*10).out. For example. class DateDemo { public static void main(String args[]) { SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"). import java.println(t).println("Unparseable using " + formatter).out.util.import java. String input = args.length == 0 ? "1818-11-11" : args[0].out.util.println(new Date( ) + "\n"). System. } catch (ParseException e) { System.print(input + " Parses as "). Thread.*. System.text.*.
long diff = end . class DiffDemo { public static void main(String args[]) { try { long start = System. The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the default locale and time zone.sleep(5*60*10). System.println(new Date( ) + "\n"). There are also several constructors for GregorianCalendar objects: . } catch (Exception e) { System.out. I did not discuss Calender class in this tutorial. These represent the two eras defined by the Gregorian calendar.util.*. long end = System.println("Difference is : " + diff).start.Sun May 03 18:04:41 GMT 2009 Sun May 03 18:04:51 GMT 2009 Measuring Elapsed Time: Sometime you may need to measure point in time in milliseconds.out. System.println("Got an exception!").out.out.currentTimeMillis( ).currentTimeMillis( ). So let's re-write above example once again: import java. System. Thread. you can look standard Java documentation for this. } } } This would produce following result: Sun May 03 18:16:51 GMT 2009 Sun May 03 18:16:57 GMT 2009 Difference is : 5993 GregorianCalendar Class: GregorianCalendar is a concrete implementation of a Calendar class that implements the normal Gregorian calendar with which you are familiar. GregorianCalendar defines two fields: AD and BC.println(new Date( ) + "\n").
int month. GregorianCalendar(int year. int month.SN 1 Constructor with Description GregorianCalendar() Constructs a default GregorianCalendar using the current time in the default time zone with the default locale. int month. based on the calendar's rules. GregorianCalendar(TimeZone zone. int hour. 2 3 4 . GregorianCalendar(int year. protected void computeFields() Converts UTC as milliseconds to time field values. int amount) Adds the specified (signed) amount of time to the given time field. boolean equals(Object obj) Compares this GregorianCalendar to an object reference. int date) Constructs a GregorianCalendar with the given date set in the default time zone with the default locale. int date. int second) Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. GregorianCalendar(TimeZone zone) Constructs a GregorianCalendar based on the current time in the given time zone with the default locale. GregorianCalendar(Locale aLocale) Constructs a GregorianCalendar based on the current time in the default time zone with the given locale. Locale aLocale) Constructs a GregorianCalendar based on the current time in the given time zone with the given locale. int minute. int minute) Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. GregorianCalendar(int year. 2 3 4 5 6 7 Here is the list of few useful support methods provided by GregorianCalendar class: SN 1 Medthos with Description void add(int field. int date. int hour. protected void computeTime() Overrides Calendar Converts time field values to UTC as milliseconds.
Date getTime() Gets this Calendar's current time. int hashCode() Override hashCode. void roll(int field. int getLeastMaximum(int field) Returns lowest maximum value for the given field if varies. void set(int year. int value) Sets the time field with the given value. void set(int field. given the current date. boolean up) Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields. void set(int year. int getGreatestMinimum(int field) Returns highest minimum value for the given field if varies. int hour. int date. long getTimeInMillis() Gets this Calendar's current time as a long. and date. int date) Sets the values for the fields year. TimeZone getTimeZone() Gets the time zone. int month. int getActualMaximum(int field) Return the maximum value that this field could have. int getMaximum(int field) Returns maximum value for the given field. given the current date. int minute) 18 19 20 21 . Date getGregorianChange() Gets the Gregorian Calendar change date. boolean isLeapYear(int year) Determines if the given year is a leap year. int month. int getActualMinimum(int field) Return the minimum value that this field could have. month. int getMinimum(int field) Returns minimum value for the given field.5 6 7 8 9 10 11 12 13 14 15 16 17 int get(int field) Gets the value for a given time field.
hour.print(months[gcalendar.print(" " + gcalendar. "May".print("Date: "). Example: import java.out. int minute.*.get(Calendar. month. "Sep".out. System.out.println(gcalendar. System. "Aug". int year. // Display current time and date information.util.out.Sets the values for the fields year.out.get(Calendar. void setTimeInMillis(long millis) Sets this Calendar's current time from the given long value.out.get(Calendar. System. void setTime(Date date) Sets this Calendar's current time with the given Date.MONTH)]).MINUTE) + ":"). date. System. } else { System. "Mar". "Nov". 22 23 24 25 26 27 void set(int year. String toString() Return a string representation of this calendar. // Create a Gregorian calendar initialized // with the current date and time in the // default locale and timezone. GregorianCalendar gcalendar = new GregorianCalendar().println(year = gcalendar.println("The current year is not a leap year"). hour.print(gcalendar.HOUR) + ":"). // Test if the current year is a leap year if(gcalendar. "Apr". System. "Jun".isLeapYear(year)) { System.out. and second. int second) Sets the values for the fields year.out. System. date. "Jul".YEAR)).SECOND)). System. System. class GregorianCalendarDemo { public static void main(String args[]) { String months[] = { "Jan".out. and minute. "Feb". minute.get(Calendar. void setGregorianChange(Date date) Sets the GregorianCalendar change date.print(gcalendar.get(Calendar. "Dec"}.print("Time: "). int date.DATE) + " "). "Oct". } . int month.println("The current year is a leap year"). int hour.get(Calendar. month. void setTimeZone(TimeZone value) Sets the time zone with the given time zone value.out.
using a specialized syntax held in a pattern.regex package primarily consists of the following three classes: • • • Pattern Class: A Pattern object is a compiled representation of a regular expression.regex package for pattern matching with regular expressions. which will then return a Pattern object. They are created by placing the characters to be grouped inside a set of parentheses. You obtain a Matcher object by invoking the matcher method on a Pattern object. or manipulate text and data. A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings. Java regular expressions are very similar to the Perl programming language and very easy to learn. Like the Pattern class. Matcher defines no public constructors. The Pattern class provides no public constructors. They can be used to search. In the expression ((A)(B(C))). Matcher Class: A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Capturing Groups: Capturing groups are a way to treat multiple characters as a single unit.util.} } This would produce following result: Date: Apr 22 2009 Time: 11:25:27 The current year is not a leap year For a complete list of constant available in Calender class. These methods accept a regular expression as the first argument. you must first invoke one of its public static compile methods. edit. To create a pattern.util. the regular expression (dog) creates a single group containing the letters "d". PatternSyntaxException: A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.Regular Expressions Java provides the java. there are four such groups: . Capturing groups are numbered by counting their opening parentheses from left to right. for example. you can refer to standard Java documentation. and "g". The java. "o". Java . For example.
matcher(line). 3.util.group(0) ). Example: Following example illustrate how to find a digit string from the given alphanumeric string: import java. call the groupCount method on a matcher object.regex. 2. public class RegexMatches { public static void main( String args[] ){ // String to be scanned to find the pattern.println("NO MATCH").Pattern.println("Found value: " + m. System. } } } This would produce following result: Found value: This order was places for QT3000! OK? Found value: This order was places for QT300 Found value: 0 .1. which always represents the entire expression. // Now create matcher object. This group is not included in the total reported by groupCount.out. // Create a Pattern object Pattern r = Pattern. There is also a special group. import java. if (m.out.*)(\\d+)(. } else { System. String pattern = "(. The groupCount method returns an int showing the number of capturing groups present in the matcher's pattern.out. group 0.*)".compile(pattern).println("Found value: " + m.out. System.println("Found value: " + m. ((A)(B(C))) (A) (B(C)) (C) To find out how many groups are present in the expression. String line = "This order was places for QT3000! OK?".group(2) ). 4.util.group(1) ).find( )) { System.Matcher. Matcher m = r.regex.
Matches at least n and at most m occurrences of preceding expression. Using m option allows it to match newline as well.Regular Expression Syntax: Here is the table listing down all the regular expression metacharacter syntax available in Java: Subexpression ^ $ .. Matches word characters. Groups regular expressions without remembering matched text. Groups regular expressions and remembers matched text. Matches any single character not in brackets Beginning of entire string End of entire string End of entire string except allowable final line terminator.] [^. Matches whitespace. Equivalent to [\t\n\r\f].] \A \z \Z re* re+ re? re{ n} re{ n. Matches . Matches any single character in brackets. Matches either a or b. Matches end of line.} re{ n. Matches independent pattern without backtracking. Matches 0 or more occurrences of preceding expression.. Matches 1 or more of the previous thing Matches 0 or 1 occurrence of preceding expression. Matches exactly n number of occurrences of preceding expression. [.. m} a| b (re) (?: re) (?> re) \w \W \s Matches beginning of line. Matches n or more occurrences of preceding expression.. Matches nonword characters. Matches any single character except newline.
\S \d \D \A \Z \z \G \n \b \B \n, \t, etc. \Q \E
Matches nonwhitespace. Matches digits. Equivalent to [0-9]. Matches nondigits. Matches beginning of string. Matches end of string. If a newline exists, it matches just before newline. Matches end of string. Matches point where last match finished. Back-reference to capture group number "n" Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. Matches nonword boundaries. Matches newlines, carriage returns, tabs, etc. Escape (quote) all characters up to \E Ends quoting begun with \Q
Methods of the Matcher Class:
Here is the lists of useful instance methods:
Index Methods:
Index methods provide useful index values that show precisely where the match was found in the input string: SN 1 Methods with Description public int start() Returns the start index of the previous match. public int start(int group) Returns the start index of the subsequence captured by the given group during the previous match operation. public int end()
2 3: SN 1 Methods with Description public boolean lookingAt() Attempts to match the input sequence, starting at the beginning of the region, against the pattern. public boolean find() Attempts to find the next subsequence of the input sequence that matches the pattern. public boolean find(int start Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index. public boolean matches() Attempts to match the entire region against the pattern.
2
3
4
Replacement Methods:
Replacement methods are useful methods for replacing text in an input string: SN 1 2 Methods with Description public Matcher appendReplacement(StringBuffer sb, String replacement) Implements a non-terminal append-and-replace step. public StringBuffer appendTail(StringBuffer sb) Implements a terminal append-and-replace step. public String replaceAll(String replacement) Replaces every subsequence of the input sequence that matches the pattern with the given replacement string. public String replaceFirst(String replacement) Replaces the first subsequence of the input sequence that matches the pattern with the given replacement string.
3
4 following result:
Match number start(): 0 end(): 3 Match number start(): 4 end(): 7 Match number start(): 8 end(): 11 Match number start(): 19 end(): 22 1 2 3 4
} } This would produce following result: Current REGEX is: foo Current INPUT is: fooooooooooooooooo lookingAt(): true matches(): false The replaceFirst and replaceAll Methods: . The matches and lookingAt Methods: The matches and lookingAt methods both attempt to match an input sequence against a pattern. System. It also gives some useful information about where in the input string the match has occurred.println("Current INPUT is: "+INPUT). private static Matcher matcher.regex. however. System.Pattern.Matcher. plus one. public class RegexMatches { private static final String REGEX = "foo".out.regex.You can see that this example uses word boundaries to ensure that the letters "c" "a" "t" are not merely a substring in a longer word.out. Both methods always start at the beginning of the input string. and end returns the index of the last character matched.println("Current REGEX is: "+REGEX). Here is the example explaining the functionality: import java. matcher = pattern. public static void main( String args[] ){ pattern = Pattern. System.util.out.compile(REGEX).println("matches(): "+matcher. private static final String INPUT = "fooooooooooooooooo". System. while lookingAt does not.matches()). private static Pattern pattern.out. import java.lookingAt()).println("lookingAt(): "+matcher. The difference. The start method returns the start index of the subsequence captured by the given group during the previous match operation.matcher(INPUT).util. is that matches requires the entire input sequence to be matched.
Here is the example explaining the functionality: import java.The replaceFirst and replaceAll methods replace text that matches a given regular expression.Matcher. public static void main(String[] args) { Pattern p = Pattern. } } This would produce following result: The cat says meow. public class RegexMatches { private static String REGEX = "a*b".util. private static String INPUT = "aabfooaabfooabfoob".regex. private static String REPLACE = "-". private static String INPUT = "The dog says meow.matcher(INPUT).regex. The appendReplacement and appendTail Methods: The Matcher class also provides appendReplacement and appendTail methods for text replacement. " + "All dogs say meow.compile(REGEX). public static void main(String[] args) { Pattern p = Pattern. // get a matcher object .Pattern. As their names indicate. private static String REPLACE = "cat". import java.regex.out.compile(REGEX).util. // get a matcher object Matcher m = p.Matcher.Pattern.".replaceAll(REPLACE). All cats say meow.println(INPUT).util. Here is the example explaining the functionality: import java. import java.regex. replaceFirst replaces the first occurrence. public class RegexMatches { private static String REGEX = "dog". and replaceAll replaces all occurences.util. INPUT = m. System.
and a visual indication of the error index within the pattern. invoke a method with or without parameters. the system actually executes several statements in order to display a message on the console. Now you will learn how to create your own methods with or without return values. public int getIndex() Retrieves the error index.find()){ m.toString()).REPLACE). public String getMessage() Returns a multi-line string containing the description of the syntax error and its index. public String getPattern() Retrieves the erroneous regular expression pattern. overload methods using the same names. System.Matcher m = p. When you call the System.appendReplacement(sb. . The PatternSyntaxException class provides the following methods to help you determine what went wrong: SN 1 2 3 Methods with Description public String getDescription() Retrieves the description of the error.appendTail(sb). for example.println method.out. StringBuffer sb = new StringBuffer(). while(m. and apply method abstraction in the program design. the erroneous regular expression pattern.Methods A Java method is a collection of statements that are grouped together to perform an operation.println(sb.out. } m. } } This would produce following result: -foo-foo-foo- PatternSyntaxException Class Methods: A PatternSyntaxException is an unchecked exception that indicates a syntax error in a regular expression pattern.matcher(INPUT). 4 Java .
Method Name: This is the actual name of the method. a method has the following syntax: modifier returnValueType methodName(list of parameters) { // Method body. Method Body: The method body contains a collection of statements that define what the method does. This value is referred to as actual parameter or argument. Here are all the parts of a method: • • • • • Modifiers: The modifier. Note: In certain other languages. Return Type: A method may return a value. The parameter list refers to the type.Creating a Method: In general. the returnValueType is the keyword void. Parameters: A parameter is like a placeholder. The method name and the parameter list together constitute the method signature. that is. A method with a nonvoid return value type is called a function. This defines the access type of the method. tells the compiler how to call the method. The returnValueType is the data type of the value the method returns. methods are referred to as procedures and functions. order. and number of the parameters of a method. When a method is invoked. which is optional. } A method definition consists of a method header and a method body. Parameters are optional. a method may contain no parameters. Some methods perform the desired operations without returning a value. In this case. a method with a void return value type is called a procedure. you pass a value to the parameter. .
int num2) { int result. For example. a call to the method must be a statement. . 40). } Calling a Method: In creating a method. int k = max(i. For example: int larger = max(30. program control is transferred to the called method. the choice is based on whether the method returns a value or not. if (num1 > num2) result = num1. you have to call or invoke it. else result = num2. int j = 2.Example: Here is the source code of the above defined method called max(). The following call is a statement: System.out. you give a definition of what the method is to do. This method takes two parameters num1 and num2 and returns the maximum between the two: /** Return the max between two numbers */ public static int max(int num1. To use a method. Example: Following is the example to demonstrate how to define a method and how to call it: public class TestMax { /** Main method */ public static void main(String[] args) { int i = 5. When a program calls a method.println("Welcome to Java!"). return result. If the method returns a value. j). the method println returns void. There are two ways to call a method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached. If the method returns void. a call to the method is usually treated as a value.
println("The maximum between " + i + " and " + j + " is " + k). method name main. } else if (score >= 80.out.out.0) { System. return value type void.println('D'). System.0) { System.out. and a parameter of the String[] type. Following example gives a program that declares a method named printGrade and invokes it to print the grade for a given score. } return result. Example: public class TestVoidMethod { public static void main(String[] args) { printGrade(78. with the modifiers public and static. int num2) { int result. } public static void printGrade(double score) { if (score >= 90. The main method is just like any other method except that it is invoked by the JVM.out.println('A').5). .println('C'). This would produce following result: The maximum between 5 and 2 is 5 This program contains the main method and the max method. else result = num2.out.0) { System. The main method's header is always the same. String[] indicates that the parameter is an array of String.0) { System. if (num1 > num2) result = num1. The void Keyword: This section shows how to declare and invoke a void method.} /** Return the max between two numbers */ public static int max(int num1. } else if (score >= 60.println('B'). } else if (score >= 70. like the one in this example.
passes 3 to n. you need to provide arguments. When you invoke a method with a parameter. the following method prints a message n times: public static void nPrintln(String message. A call to a void method must be a statement. i < n. the value of the variable is passed to the parameter. It does not return any value. } This would produce following result: C Here the printGrade method is a void method. The variable is not affected.println(message). you can use nPrintln("Hello". "Hello". } Here.out. "Hello") would be wrong. 3) to print "Hello" three times. which actually means passing the value of x to y. For example. So. If the argument is a variable rather than a literal value. This statement is like any Java statement terminated with a semicolon. Java programmers often say passing an argument x to a parameter y. regardless of the changes made to the parameter inside the method. to the parameter. This is referred to as pass-by-value. i++) System. the statement nPrintln(3. The swap method is invoked by passing . 3) statement passes the actual string parameter. and prints "Hello" three times.out.println('F'). it is invoked as a statement in line 3 in the main method. Passing Parameters by Values: When calling a method. This is known as parameter order association. the value of the argument is passed to the parameter. message. which must be given in the same order as their respective parameters in the method specification. Example: Following is a program that demonstrates the effect of passing by value. However. The program creates a method for swapping two variables. For simplicity. int n) { for (int i = 0.} } } else { System. The nPrintln("Hello".
int num2 = 2.println("Before swap method. System. as shown in the following code: public static double max(double num1. } /** Method to swap two variables */ public static void swap(int n1. num1 is 1 and num2 is 2 Overloading Methods: The max method that was used earlier works only with the int data type.println("\tInside the swap method"). Interestingly. public class TestPassByValue { public static void main(String[] args) { int num1 = 1. num2). else . num1 is 1 and num2 is 2 Inside the swap method Before swapping n1 is 1 n2 is 2 After swapping n1 is 2 n2 is 1 After swap method. n1 = n2. the values of the arguments are not changed after the method is invoked.out. n2 = temp. System.println("\t\tAfter swapping n1 is " + n1 + " n2 is " + n2). } } This would produce following result: Before swap method.out. int n2) { System.out.println("\t\tBefore swapping n1 is " + n1 + " n2 is " + n2). But what if you need to find which of two floating-point numbers has the maximum value? The solution is to create another method with the same name but different parameters.println("After swap method. num1 is " + num1 + " and num2 is " + num2). double num2) { if (num1 > num2) return num1. System.two arguments. // Swap n1 with n2 int temp = n1.out.out. System. num1 is " + num1 + " and num2 is " + num2). // Invoke the swap method swap(num1.
Methods that perform closely related tasks should be given the same name.return num2. The Java compiler determines which method is used based on the method signature. This is referred to as ambiguous invocation. The Scope of Variables: The scope of a variable is the part of the program where the variable can be referenced. A parameter is actually a local variable. Sometimes there are two or more possible matches for an invocation of a method due to similar method signature. if you call max with double parameters. so the compiler cannot determine the most specific match. A local variable must be declared before it can be used. that is. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. the max method that expects double parameters will be invoked. This is referred to as method overloading. } If you call max with int parameters. the max method that expects int parameters will be invoked. Overloaded methods must have different parameter lists. Overloading methods can make programs clearer and more readable. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration to the end of the block that contains the variable as shown below: . You cannot overload methods based on different modifiers or return types. A variable defined inside a method is referred to as a local variable. A variable declared in the initial action part of a for loop header has its scope in the entire loop. The scope of a method parameter covers the entire method. two methods have the same name but different parameter lists within one class.
} } } Try executing this program. i<args. i++){ System.they are stored as strings in the String array passed to main( ).length. To access the command-line arguments inside a Java program is quite easy. constructors have no explicit return type. However. but you cannot declare a local variable twice in nested blocks. This is accomplished by passing command-line arguments to main( ).out. It has the same name as its class and is syntactically similar to a method. .You can declare a local variable with the same name multiple times in different nonnesting blocks in a method. Example: The following program displays all of the command-line arguments that it is called with: class CommandLine { public static void main(String args[]){ for(int i=0. as shown here: java CommandLine this is a command line 200 -100 This would produce following result: args[0]: args[1]: args[2]: args[3]: args[4]: args[5]: args[6]: this is a command line 200 -100 The Constructors: A constructor initializes an object when it is created.println("args[" + i + "]: " + args[i]). Using Command-Line Arguments: Sometimes you will want to pass information into a program when you run it. A command-line argument is the information that directly follows the program's name on the command line when it is executed.
// Following is the constructor MyClass() { x = 10. All classes have constructors.Typically. class MyClass { int x. // Following is the constructor MyClass(int i ) { x = 10. System.x + " " + t2.println(t1. Example: Here is a simple example that uses a constructor: // A simple constructor. the default constructor is no longer used. Example: Here is a simple example that uses a constructor: // A simple constructor. whether you define one or not. because Java automatically provides a default constructor that initializes all member variables to zero. However.x). } } Most often you will need a constructor that accepts one or more parameters.out. Parameters are added to a constructor in the same way that they are added to a method:just declare them inside the parentheses after the constructor's name. once you define your own constructor. } } You would call constructor to initialize objects as follows: class ConsDemo { public static void main(String args[]) { MyClass t1 = new MyClass(). } } . or to perform any other startup procedures required to create a fully formed object. class MyClass { int x. you will use a constructor to give initial values to the instance variables defined by the class. MyClass t2 = new MyClass().
3. i < numbers.x + " " + t2. } } .) Only one variable-length parameter may be specified in a method. The parameter in the method is declared as follows: typeName.println(t1. 2. and this parameter must be the last parameter.println("The max value is " + result)..5). numbers) { if (numbers.x).. Any regular parameters must precede it.out.. you specify the type followed by an ellipsis (. System. 3}). } } This would produce following result: 10 20 Variable Arguments(var-args): JDK 1. i++) if (numbers[i] > result) result = numbers[i].out.You would call constructor to initialize objects as follows: class ConsDemo { public static void main(String args[]) { MyClass t1 = new MyClass( 10 ). printMax(new double[]{1.length. 3. MyClass t2 = new MyClass( 20 ).out..5 enables you to pass a variable number of arguments of the same type to a method. parameterName In the method declaration. return. } public static void printMax( double. 56. Example: public class VarargsDemo { public static void main(String args[]) { // Call method with variable args printMax(34. } double result = numbers[0]. System. 2.println("No argument passed")..length == 0) { System. for (int i = 1..
you might use finalize( ) to make sure that an open file owned by that object is closed. To add a finalizer to a class. All these streams represent an input source and an output destination.This would produce following result: The max value is 56. This method is called finalize( ). The stream in the java. Java .io package supports many data such as primitives. Files and I/O The java. A stream can be defined as a sequence of data. This means that you cannot know when.Streams. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Object. Inside the finalize( ) method you will specify those actions that must be performed before an object is destroyed. localized characters etc. and it can be used to ensure that an object terminates cleanly. For example. The Java runtime calls that method whenever it is about to recycle an object of that class. if your program ends before garbage collection occurs.5 The max value is 3.0 The finalize( ) Method: It is possible to define a method that will be called just before an object's final destruction by the garbage collector. the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. .io package contains nearly every class you might ever need to perform input and output (I/O) in Java. The finalize( ) method has this general form: protected void finalize( ) { // finalization code here } Here. finalize( ) will not execute. For example.finalize( ) will be executed. you simply define the finalize( ) method.or even if.
class BRRead { public static void main(String args[]) throws IOException { char c. 'q' to quit.out. we can use read( ) method to reach a character or readLine( ) method to read a string from the console.println(c).1 when the end of the stream is encountered. to create a character stream.io. Reading Characters from Console: To read a character from a BufferedReader. System. As you can see.in. we would read( ) method whose sytax is as follows: int read( ) throws IOException Each time that read( ) is called.println("Enter characters. To obtain a characterbased stream that is attached to the console.").out. you wrap System. . Once BufferedReader is obtained.in BufferedReader br = new BufferedReader(new InputStreamReader(System.read(). it reads a character from the input stream and returns it as an integer value.Java does provide strong. Here is most common syntax to obtain BufferedReader: BufferedReader br = new BufferedReader(new InputStreamReader(System. System. The following program demonstrates read( ) by reading characters from the console until the user types a "q": // Use a BufferedReader to read characters from the console. // read characters do { c = (char) br. We would see most commonly used example one by one: Reading Console Input: Java input console is accomplished by reading from System. flexible support for I/O as it relates to files and networks but this tutorial covers very basic functionlity related to streams and I/O.in)).*. It returns . // Create a BufferedReader using System. import java.in)). it can throw an IOException.in in a BufferedReader object.
String str. do { str = br. 'q' to quit. System.out. The program reads and displays lines of text until you enter the word "end": // Read a string from console using a BufferedReader. } while(!str.in BufferedReader br = new BufferedReader(new InputStreamReader(System.println("Enter 'end' to quit.io. import java.out. Its general form is shown here: String readLine( ) throws IOException The following program demonstrates BufferedReader and the readLine( ) method. This is line one This is line one .out. System. } } Here is a sample run: Enter lines of text.} while(c != 'q').").").equals("end")). } } Here is a sample run: Enter characters.println("Enter lines of text.in)). use the version of readLine( ) that is a member of the BufferedReader class.println(str). Enter 'end' to quit. 123abcq 1 2 3 a b c q Reading Strings from Console: To read a string from the keyboard. class BRReadLines { public static void main(String args[]) throws IOException { // Create a BufferedReader using System.readLine().*. System.
write('\n'). described earlier.out. System.write(b). Example: Here is a short example that uses write( ) to output the character "A" followed by a newline to the screen: import java. The simplest form of write( ) defined by PrintStream is shown here: void write(int byteval) This method writes to the stream the byte specified by byteval.write(). // Demonstrate System. . write( ) can be used to write to the console. System. A Note: You will not often use write( ) to perform console output because print( ) and println( ) are substantially easier to use. Because PrintStream is an output stream derived from OutputStream.out is a byte stream.io.This is line two This is line two end end Writing Console Output: Console output is most easily accomplished with print( ) and println( ).*. } } This would produce simply 'A' character on the output screen.out. These methods are defined by the class PrintStream which is the type of the object referenced by System. class WriteDemo { public static void main(String args[]) { int b.out. it also implements the low-level method write( ).out. Thus. using it for simple program output is still acceptable. Although byteval is declared as an integer. b = 'A'. Even though System. only the low-order eight bits are written.
Here is a hierarchy of classes to deal with Input and Output streams. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. InputStream f = new FileInputStream(f). First we create a file object using File() method as follows: File f = new File("C:/java/hello"). The two important streams are FileInputStream and FileOutputStream which would be discussed in this tutorial: FileInputStream: This stream is used for reading data from the files.Reading and Writing Files: As described earlier. A stream can be defined as a sequence of data.: InputStream f = new FileInputStream("C:/java/hello"). Following constructor takes a file name as a string to create an input stream object to read the file. Objects can be created using the keyword new and there are several types of constructors available. . Following constructor takes a file object to create an input stream object to read the file.
if it doesn't already exist. Returns the total number of bytes read.Once you have InputStream object in hand then there is a list of helper methods which can be used to read to stream or to do other operations on the stream. Ensures that the close method of this file output stream is called when there are no more references to this stream. Following constructor takes a file name as a string to create an input stream object to write the file. public int read(int r)throws IOException{} This method reads the specified byte of data from the InputStream. Throws an IOException.length bytes from the input stream into an array.: OutputStream f = new FileOutputStream("C:/java/hello") Following constructor takes a file object to create an output stream object to write the file. Returns the next byte of data and -1 will be returned if it's end of file. Here are two constructors which can be used to create a FileOutputStream object. Releases any system resources associated with the file. before opening it for output. public int read(byte[] r) throws IOException{} This method reads r.The stream would create a file. public int available() throws IOException{} Gives the number of bytes that can be read from this file input stream. If end of file -1 will be returned. Returns an int. 2 3 4 5 There are other important input streams available. protected void finalize()throws IOException {} This method cleans up the connection to the file. for more detail you can refer to the following links: • • ByteArrayInputStream DataInputStream FileOutputStream: FileOutputStream is used to create a file and write data into it. SN 1 Methods with Description public void close() throws IOException{} This method closes the file output stream. First we create a file object using File() method as follows: . Throws an IOException. Returns an int.
40. protected void finalize()throws IOException {} This method cleans up the connection to the file. OutputStream os = new FileOutputStream("C:/test.io. OutputStream f = new FileOutputStream(f). public void write(byte[] w) Writes w.txt").length . SN 1 Methods with Description public void close() throws IOException{} This method closes the file output stream. Throws an IOException.3. Ensures that the close method of this file output stream is called when there are no more references to this stream. x < bWrite. for more detail you can refer to the following links: • • ByteArrayOutputStream DataOutputStream Example: Following is the example to demonstrate InputStream and OutputStream: import java.close(). Throws an IOException. Once you have OutputStream object in hand then there is a list of helper methods which can be used to write to stream or to do other operations on the stream.txt"). // writes the bytes } os. .File f = new File("C:/java/hello"). x++){ os.length bytes from the mentioned byte array to the OutputStream. for(int x=0.21. public void write(int w)throws IOException{} This methods writes the specified byte to the output stream. 2 3 4 There are other important output streams available.*. InputStream is = new FileInputStream("C:/test. Releases any system resources associated with the file.write( bWrite[x] ).5}. public class fileStreamTest{ public static void main(String args[]){ try{ byte bWrite [] = {11.
Failure indicates that the path specified in the File object already exists. } The above code would create file test.read() + " } is.print("Exception").print((char)is. for(int i=0.available().close(). The mkdirs() method creates both a directory and all the parents of the directory.int size = is. Following example creates "/tmp/user/java/bin" directory: import java. d. i< size. • • • File Class FileReader Class FileWriter Class Directories in Java: Creating Directories: There are two useful File utility methods which can be used to create directories: • • The mkdir( ) method creates a directory. } } ").out.File. File d = new File(dirname). // Create directory now. or that the directory cannot be created because the entire path does not exist yet.io. class CreateDir { public static void main(String args[]) { String dirname = "/tmp/user/java/bin". } } . File Navigation and I/O: There are several other classes that we would be going through to get to know the basics of File Navigation and I/O. i++){ System. Same would be output on the stdout screen.txt and would write given numbers in binary format.mkdirs(). }catch(IOException e){ System.out. returning true on success and false on failure.
Reading Directories: A directory is a File that contains a list of other files and directories. When you create a File object and it is a directory.out. String s[] = f1.list(). If you use a forward slash (/) on a Windows version of Java.out.isDirectory()) { System.txt is a file README is a file index.println(dirname + " is not a directory"). } } } else { System. File f1 = new File(dirname).println( "Directory of " + dirname). i < s. if (f1.length. i++) { File f = new File(dirname + "/" + s[i]).println(s[i] + " is a file"). Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. if (f.Compile and execute above code to create "/tmp/user/java/bin".out. for (int i=0. } else { System.File.io.isDirectory()) { System. the path will still resolve correctly.html is a file include is a directory .println(s[i] + " is a directory"). The program shown here illustrates how to use list( ) to examine the contents of a directory: import java. class DirList { public static void main(String args[]) { String dirname = "/java". You can call list( ) on that object to extract the list of other files and directories inside.out. } } } This would produce following result: Directory of /mysql bin is a directory lib is a directory demo is a directory test. the isDirectory( ) method will return true.
They are also ignored at the time of compilation. which are not handled by the java programs. or the JVM has run out of memory. an exception occurs. Errors are not normally trapped form the Java programs. if a file is to be opened. For example. but problems that arise beyond the control of the user or the programmer. you need to understand the three categories of exceptions: • • • Checked exceptions: Achecked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. An exception can occur for many different reasons. Other than the exception class there is another subclass called Error which is derived from the Throwable class.lang. including the following: • • • A user has entered invalid data. . A file that needs to be opened cannot be found. The exception class is a subclass of the Throwable class. These exceptions cannot simply be ignored at the time of compilation. Errors are typically ignored in your code because you can rarely do anything about an error. Exception Hierarchy: All exception classes are subtypes of the java. Some of these exceptions are caused by user error.Java . To understand how exception handling works in Java. For example.Exceptions Handling An exception is a problem that arises during the execution of a program. As opposed to checked exceptions. A network connection has been lost in the middle of communications. Normally programs cannot recover from errors. an error will arise. runtime exceptions are ignored at the time of compliation. Errors are generated to indicate errors generated by the runtime environment.Exception class. Example : JVM is out of Memory. These conditions normally happen in case of severe failures. The Exception class has two main subclasses : IOException class and RuntimeException Class. others by programmer error. and others by physical resources that have failed in some manner. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. if a stack overflow occurs. Errors: These are not exceptions at all. but the file cannot be found.
public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace.err. adding to any previous information in the stack trace. and the last element in the array represents the method at the bottom of the call stack. 2 3 4 5 6 . the error output stream. The element at index 0 represents the top of the call stack. Exceptions Methods: Following is the list of important medthods available in the Throwable class. This message is initialized in the Throwable constructor. SN 1 Methods with Description public String getMessage() Returns a detailed message about the exception that has occurred.Here is a list of most common checked and unchecked Java's Built-in Exceptions. public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. public String toString() Returns the name of the class concatenated with the result of getMessage() public void printStackTrace() Prints the result of toString() along with the stack trace to System.
A try/catch block is placed around the code that might generate an exception. Example: The following is an array is declared with 2 elements.lang. and the syntax for using try/catch looks like the following: try { //Protected code }catch(ExceptionName e1) { //Catch block } A catch statement involves declaring the type of exception you are trying to catch.println("Out of the block").io.out. } System. }catch(ArrayIndexOutOfBoundsException e){ System. If an exception occurs in protected code. // File Name : ExcepTest.ArrayIndexOutOfBoundsException: 3 Multiple catch Blocks: . the catch block (or blocks) that follows the try is checked. Code within a try/catch block is referred to as protected code. If the type of exception that occurred is listed in a catch block.Catching Exceptions: A method catches an exception using a combination of the try and catch keywords. } } This would produce following result: Exception thrown Out of the block :java. the exception is passed to the catch block much as an argument is passed into a method parameter.out. Then the code tries to access the 3rd element of the array which throws an exception. System.out.*.println("Access element three :" + a[3]). public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2].java import java.println("Exception thrown :" + e).
A try block can be followed by multiple catch blocks. }catch(FileNotFoundException f) //Not valid! { f. return -1. If an exception occurs in the protected code. it gets caught there.read(). try { file = new FileInputStream(fileName). the exception is thrown to the first catch block in the list. }catch(IOException i) { i. but you can have any number of them after a single try. If the data type of the exception thrown matches ExceptionType1. Example: Here is code segment showing how to use multiple try/catch statements. If not. The throws keyword appears at the end of a method's signature. .printStackTrace().printStackTrace(). } The throws/throw Keywords: If a method does not handle a checked exception. the exception passes down to the second catch statement. in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. return -1. The syntax for multiple catch blocks looks like the following: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block } The previous statements demonstrate three catch blocks. the method must declare it using the throws keyword. x = (byte) file. This continues until the exception either is caught or falls through all catches.
public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException().*. A finally block of code always executes. For example. either a newly instantiated one or an exception that you just caught.io. the following method declares that it throws a RemoteException and an InsufficientFundsException: import java. Using a finally block allows you to run any cleanup-type statements that you want to execute. by using the throw keyword.You can throw an exception. in which case the exceptions are declared in a list separated by commas. InsufficientFundsException { // Method implementation } //Remainder of class definition } The finally Keyword The finally keyword is used to create a block of code that follows a try block. public class className { public void withdraw(double amount) throws RemoteException. } //Remainder of class definition } Amethod can declare that it throws more than one exception.*. no matter what happens in the protected code. whether or not an exception has occurred. The following method declares that it throws a RemoteException: import java. A finally block appears at the end of the catch blocks and has the following syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch block . Try to understand the different in throws and throw keywords.io.
finally blocks.lang. }catch(ArrayIndexOutOfBoundsException e){ System. System.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed Note the followings: • • • • A catch clause cannot exist without a try statement. catch.out.println("Access element three :" + a[3]). . Declaring you own Exception: You can create your own exceptions in Java. System.println("Exception thrown :" + e). The try block cannot be present without either catch clause or finally clause.out.out.println("First element value: " +a[0]).out.println("The finally statement is executed"). Any code cannot be present in between the try.}catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. try{ System. } } } This would produce following result: Exception thrown :java. It is not compulsory to have finally clauses when ever a try/catch block is present. Keep the following points in mind when writing your own exception classes: • All exceptions must be a child of Throwable. } finally{ a[0] = 6. } Example: public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2].
java import java. public InsufficientFundsException(double amount) { this.• • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule. you need to extend the RuntimeException class. An exception class is like any other class. public class InsufficientFundsException extends Exception { private double amount. If you want to write a runtime exception. public class CheckingAccount { private double balance. } } To demonstrate using our user-defined exception.java import java.io. The following InsufficientFundsException class is a user-defined exception that extends the Exception class. the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException. public CheckingAccount(int number) { this. // File Name CheckingAccount. } public void deposit(double amount) { balance += amount. containing useful fields and methods. } public double getAmount() { return amount. private int number. We can define our own Exception class as below: class MyException extends Exception{ } You just need to extend the Exception class to create your own Exception class.amount = amount. . you need to extend the Exception class. These are considered to be checked exceptions. making it a checked exception.*.io.*. Example: // File Name InsufficientFundsException.number = number.
.println("\nWithdrawing $100.out. try { System.getAmount()). c..println("Depositing $500.00). System.printStackTrace(). c.. // File Name BankDemo.} } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount.").out. } } } Compile all the above three files and run BankDemo. } The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.deposit(500. } else { double needs = amount .").java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101). System.balance. c... }catch(InsufficientFundsException e) { System. this would produce following result: . e. throw new InsufficientFundsException(needs)."). but you are short $" + e. } } public double getBalance() { return balance.println("\nWithdrawing $600.out..withdraw(600.00).withdraw(100.out.00). } public int getNumber() { return number.println("Sorry.
. Programmatic exceptions .. ArrayIndexOutOfBoundsException. Withdrawing $600.0 InsufficientFundsException at CheckingAccount. • • JVM Exceptions: .java:25) at BankDemo. By using these keywords we can make one object acquire the properties of another object. ClassCastException. Java Object Oriented Java . Examples : NullPointerException.. IllegalStateException.These are exceptions/errors that are exclusively or logically thrown by the JVM. With the use of inheritance the information is made manageable in a hierarchical order..java:13) Common Exceptions: In java it is possible to define two catergories of Exceptions and Errors. Let us see how the extends keyword is used to achieve inheritance. Withdrawing $100. When we talk about inheritance the most commonly used key words would be extends and implements.Inheritance Inheritance can be defined as the process where one object acquires the properties of another.main(BankDemo. public class Animal{ } public class Mammal extends Animal{ } public class Reptile extends Animal{ . These words would determine whether one object IS-A type of another..Depositing $500. but you are short $200.. IS-A Relationship: IS-A is a way of saying : This object is a type of that object.withdraw(CheckingAccount. These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException. Sorry.
Mammal m = new Mammal(). Example: public class Dog extends Mammal{ public static void main(String args[]){ Animal a = new Animal().println(d instanceof Mammal). Animal is the superclass of Reptile class. System. } } This would produce following result: true true true Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship. System. In Object Oriented terms following are true: • • • • Animal is the superclass of Mammal class.out.out. We can assure that Mammal is actually an Animal with the use of the instance operator. Now if we consider the IS-A relationship we can say: • • • • Mammal IS-A Animal Reptile IS-A Animal Dog IS-A Mammal Hence : Dog IS-A Animal as well With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass. .println(m instanceof Animal).println(d instanceof Animal).} public class Dog extends Mammal{ } Now based on the above example. System. Dog d = new Dog().out. Mammal and Reptile are sub classes of Animal class. Dog is the subclass of both Mammal and Animal classes.
println(d instanceof Animal). System.out. This relationship helps to reduce duplication of code as well as bugs. System. Lets us look into an example: public class Vehicle{} public class Speed{} .println(d instanceof Mammal).out.The implements keyword is used by classes by inherit from interfaces.out. System. } } This would produce following result: true true true HAS-A relationship: These relationships are mainly based on the usage. and dog is actually an Animal interface Animal{} class Mammal implements Animal{} class Dog extends Mammal{ public static void main(String args[]){ Mammal m = new Mammal(). This determines whether a certain class HAS-A certain thing.println(m instanceof Animal). Dog d = new Dog(). Example: public interface Animal {} public class Mammal implements Animal{ } public class Dog extends Mammal{ } The instanceof Keyword: Let us use the instanceof operator to check determine whether Mammal is actually an Animal. Interfaces can never be extended.
A very important fact to remember is that Java only supports only single inheritance. } } . } This shows that class Van HAS-A Speed. class Animal{ public void move(){ System. SO basically what happens is the users would ask the Van class to do a certain action and the Vann class will either do the work by itself or ask another class to perform the action.. Therefore following is illegal: public class extends Animal. Which means a subclass can implement a parent calss method based on its requirement. Mammal{} However a class can implement one or more interfaces. Example: Let us look at an example. To achieve this.out.println("Animals can move"). The benefit of overriding is: ability to define a behavior that's specific to the sub class type. In object oriented terms. the Van class hides the implementation details from the users of the Van class. If a class inherits a method from its super class. This has made Java get rid of the impossibility of multiple inheritance Java .public class Van extends Vehicle{ private Speed sp. overriding means to override the functionality of any existing method. This means that a class cannot extend more than one class.Overriding In the previous chapter we talked about super classes and sub classes. By having a separate class for Speed we do not have to put the entire code that belongs to speed inside the Van class. then there is a chance to override the method provided that it is not marked final. In Object Oriented feature the users do not need to bother about which object is doing the real work. which makes it possible to reuse the Speed class in multiple applications.
println("Dogs can walk and run").class Dog extends Animal{ public void move(){ System.println("Dogs can bark"). } } class Dog extends Animal{ public void move(){ System.//Runs the method in Dog class } } This would produce following result: Animals can move Dogs can walk and run In the above example you can see that the even though b is a type of Animal it runs the move method in the Dog class.move().out.println("Dogs can walk and run"). } } . However in the runtime JVM figures out the object type and would run the method that belongs to that particular object. // Animal reference but Dog object a.out. The reason for this is : In compile time the check is made on the reference type. } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(). Consider the following example : class Animal{ public void move(){ System. Therefore in the above example. the program will compile properly since Animal class has the method move.out.println("Animals can move"). // Animal reference and object Animal b = new Dog().// runs the method in Animal class b.out.move(). } public void bark(){ System. Then at the runtime it runs the method specific for that object.
A method declared final cannot be overridden. An overriding method can throw any uncheck exceptions.// runs the method in Animal class b. Instance methods can be overridden only if they are inherited by the subclass. The access level cannot be more restrictive than the overridden method's access level. Rules for method overriding: • • • • • • • • • • • The argument list should be exactly the same as that of the overridden method. However the overridden method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the super class. If a method cannot be inherited then it cannot be overridden.move(). Constructors cannot be overridden. // Animal reference and object Animal b = new Dog(). The overriding method can throw narrower or fewer exceptions than the overridden method.bark(). } } This would produce following result: TestDog. A method declared static cannot be overridden but can be re-declared. However the access level can be less restrictive than the overridden method's access level. A subclass in a different package can only override the non-final methods declared public or protected. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. // Animal reference but Dog object a. regardless of whether the overridden method throws exceptions or not. . ^ This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or public.//Runs the method in Dog class b.bark().public class TestDog{ public static void main(String args[]){ Animal a = new Animal().move().java:30: cannot find symbol symbol : method bark() location: class Animal b.
Polymorphism Polymorphism is the ability of an object to take on many forms. all java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.out. It is important to know that the only possible way to access an object is through a reference variable.move(). class Animal{ public void move(){ System. // Animal reference but Dog object b. } } class Dog extends Animal{ public void move(){ super.//Runs the method in Dog class } } This would produce following result: Animals can move Dogs can walk and run Java . .Using the super keyword: When invoking a superclass version of an overridden method the super keyword is used. // invokes the super class method System.move(). In Java.println("Animals can move"). A reference variable can be of only one type. } } public class TestDog{ public static void main(String args[]){ Animal b = new Dog().println("Dogs can walk and run"). Any java object that can pass more than on IS-A test is considered to be polymorphic.out. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Once declared the type of a reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared final.java */ public class Employee { private String name. A reference variable can be declared as a class or interface type. Vegetarian v = d. . An overridden method is essentially hidden in the parent class. /* File name : Employee. Example: Let us look at an example. and is not invoked unless the child class uses the super keyword within the overriding method.a. Following are true for the above example: • • • • A Deer IS-A aAnimal A Deer IS-A Vegetarian A Deer IS-A Deer A Deer IS-A Object When we apply the reference variable facts to a Deer object reference.o refer to the same Deer object in the heap. Animal a = d. We already have discussed method overriding. Virtual Methods: In this section. I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes. Object o = d. The type of the reference variable would determine the methods that it can invoke on the object. where a child class can override a method in its parent. public interface Vegetarian{} public class Animal{} public class Deer extends Animal implements Vegetarian{} Now the Deer class is considered to be polymorphic since this has multiple inheritance. the following declarations are legal: Deer d = new Deer(). All the reference variables d. A reference variable can refer to any object of its declared type or any subtype of its declared type.v.
} public String getAddress() { return address. } public void mailCheck() { System. } public int getNumber() { return number.address).out. } public double getSalary() . address. int number) { System.address = address. } public void mailCheck() { System.out.println("Mailing check to " + getName() + " with salary " + salary). int number. public Employee(String name. this.println("Mailing a check to " + this. //Annual salary public Salary(String name.name + " " + this. System. } } Now suppose we extend Employee class as follows: /* File name : Salary.number = number. double salary) { super(name.private String address.out. private int number. this.java */ public class Salary extends Employee { private double salary. this. } public String getName() { return name. setSalary(salary).println("Constructing an Employee"). } public void setAddress(String newAddress) { address = newAddress. number). } public String toString() { return name + " " + address + " " + number. String address.out.println("Within mailCheck of Salary class ").name = name. String address.
MA".out. and the other using an Employee reference e. System. UP". System. 2. .out. 2400.out. s.mailCheck().println("Computing salary pay for " + getName()).0) { salary = newSalary.mailCheck(). Employee e = new Salary("John Adams".{ return salary.0 Call mailCheck using Employee reference-Within mailCheck of Salary class Mailing check to John Adams with salary 2400.00). } } Now you study the following program carefully and try to determine its output: /* File name : VirtualDemo. "Ambehta. } } This would produce following result: Constructing an Employee Constructing an Employee Call mailCheck using Salary reference -Within mailCheck of Salary class Mailing check to Mohd Mohtashim with salary 3600. 3600. } public void setSalary(double newSalary) { if(newSalary >= 0. 3.println("Call mailCheck using Salary reference --"). one using a Salary reference s.println("\n Call mailCheck using Employee reference--"). return salary/52.00). } } public double computePay() { System.0 Here we instantiate two Salary objects . "Boston. e.java */ public class VirtualDemo { public static void main(String [] args) { Salary s = new Salary("Mohd Mohtashim".
println("Constructing an Employee"). this. int number) { System. the class does not have much use unless it is subclassed. however. private int number. no matter what data type the reference is that was used in the source code at compile time.Abstraction Abstraction refers to the ability to make a class abstract in OOP.name = name. } public double computePay() .number = number. and the methods are referred to as virtual methods. You just cannot create an instance of the abstract class.mailCheck() the compiler sees mailCheck() in the Salary class at compile time. A parent class contains the common functionality of a collection of child classes. The keyword appears in the class declaration somewhere before the class keyword. This behavior is referred to as virtual method invocation.mailCheck(). and the JVM invokes mailCheck() in the Salary class at run time.address = address. the compiler sees the mailCheck() method in the Employee class. Here. Abstract Class: Use the abstract keyword to declare a class abstract. the compiler used mailCheck() in Employee to validate this statement. the JVM invokes mailCheck() in the Salary class. /* File name : Employee. An abstract class is one that cannot be instantiated. and constructors are all accessed in the same manner. but the parent class itself is too abstract to be used on its own. At run time. whereby an overridden method is invoked at run time. If a class is abstract and cannot be instantiated. String address.out.While invoking s. This is typically how abstract classes come about during the design phase. All methods in Java behave in this manner. Invoking mailCheck() on e is quite different because e is an Employee reference. public Employee(String name.java */ public abstract class Employee { private String name. at compile time. private String address. this. this. and its fields. Java . All other functionality of the class still exists. When the compiler seese. methods.
} public String getAddress() { return address. Now if you would try as follows: /* File name : AbstractDemo.mailCheck(). 43).0.address). } public void setAddress(String newAddress) { address = newAddress. but it still has three fields.". } public int getNumber() { return number.println("\n Call mailCheck using Employee reference--"). and one constructor.out. return 0. seven methods.java */ public class AbstractDemo { public static void main(String [] args) { /* Following is not allowed and would raise error */ Employee e = new Employee("George W.out. The class is now abstract.out. } public String toString() { return name + " " + address + " " + number. e.println("Inside Employee computePay"). } public void mailCheck() { System. System. } public String getName() { return name. } } Notice that nothing is different in this Employee class.println("Mailing a check to " + this. "Houston. TX". } } When you would compile above class then you would get following error: .name + " " + this.{ System.
UP".out.println("Computing salary pay for " + getName()).java */ public class Salary extends Employee { private double salary.out. ^ 1 error1 Extending Abstract Class: We can extend Employee class in normal way as follows: /* File name : Salary. return salary/52. but if we instantiate a new Salary object.0) { salary = newSalary.java:46: Employee is abstract.Employee. 43).out. /* File name : AbstractDemo.println("Within mailCheck of Salary class ").00). } public void mailCheck() { System. cannot be instantiated Employee e = new Employee("George W. setSalary(salary). } } public double computePay() { System. number). 3600.". double salary) { super(name. System. } } Here we cannot instantiate a new Employee. address.println("Mailing check to " + getName() + " with salary " + salary). "Houston. "Ambehta. String address. 3. TX". the Salary object will inherit the three fields and seven methods from Employee. } public void setSalary(double newSalary) { if(newSalary >= 0. //Annual salary public Salary(String name. int number. .java */ public class AbstractDemo { public static void main(String [] args) { Salary s = new Salary("Mohd Mohtashim". } public double getSalary() { return salary.
mailCheck(). but no method body.mailCheck(). System.println("Call mailCheck using Salary reference --"). you can declare the method in the parent class as abstract. public abstract double computePay(). private int number. s. System. 2400. } } This would produce following result: Constructing an Employee Constructing an Employee Call mailCheck using Salary reference -Within mailCheck of Salary class Mailing check to Mohd Mohtashim with salary 3600. "Boston. The abstract keyword is also used to declare a method as abstract. and its signature is followed by a semicolon.Salary e = new Salary("John Adams".println("\n Call mailCheck using Employee reference--"). e. MA".00). Abstract method would have no definition. Abstract Methods: If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes.out.out. not curly braces as follows: public abstract class Employee { private String name. 2. //Remainder of class definition } Declaring a method as abstract has two results: .An abstract methods consist of a method signature.0 Call mailCheck using Employee reference-Within mailCheck of Salary class Mailing check to John Adams with salary 2400. private String address.
out.• • The class must also be declared abstract.java */ public class Salary extends Employee { private double salary. otherwise. Any child class must either override the abstract method or declare itself abstract. If they do not. and abstraction. The other three are inheritance. If Salary is extending Employee class then it is required to implement computePay() method as follows: /* File name : Salary.and any of their children must override it. a descendant class has to implement the abstract method. . you would have a hierarchy of abstract classes that cannot be instantiated. The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. Access to the data and code is tightly controlled by an interface. For this reason. With this feature Encapsulation gives maintainability.println("Computing salary pay for " + getName()). it cannot be accessed by anyone outside the class. polymorphism. encapsulation is also referred to as data hiding. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. they must be abstract. //Annual salary public double computePay() { System. If a field is declared private. A child class that inherits an abstract method must override it.Encapsulation Encapsulation is one of the four fundamental OOP concepts. flexibility and extensibility to our code. If a class contains an abstract method. thereby hiding the fields within the class. Eventually. } } //Remainder of class definition Java . the class must be abstract as well. return salary/52. Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class..s following result:
Name : James Age : 20
Benefits of Encapsulation:
• • •.
Java - Interfaces
An interface is a collection of abstract methods. Aclass implements an interface, thereby inheriting the abstract methods of the interface. An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface is similar to a class in the following ways:
• • • •.
However, an interface is different from a class in several ways, including:
• • • • • •.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an interface: : NameOfInterface.java */ import java.lang.*; //Any number of import statements public interface NameOfInterface { //Any number of final, static fields //Any number of abstract method declarations\ }
Interfaces have the following properties:
• • •();
}
println("Mammal eats"). Aclass uses the implements keyword to implement an interface. When implementation interfaces there are several rules: • A class can implement more than one interface at a time. If a class does not perform all the behaviors of the interface. the class must declare itself as abstract. The signature of the interface method and the same return type or subtype should be maintained when overriding the methods. An implementation class itself can be abstract and if so interface methods need not be implemented. } public void travel(){ System. m.java */ public class MammalInt implements Animal{ public void eat(){ System. . you can think of the class as signing a contract.out. } public static void main(String args[]){ MammalInt m = new MammalInt().out. /* File name : MammalInt. } public int noOfLegs(){ return 0.eat(). m. The implements keyword appears in the class declaration following the extends portion of the declaration.Implementing Interfaces: When a class implements an interface. agreeing to perform the specific behaviors of the interface.println("Mammal travels").travel(). } } This would produce following result: Mammal eats Mammal travels When overriding methods defined in interfaces there are several rules to be followed: • • • Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.
public void endOfPeriod(int period). and the parent interfaces are declared in a commaseparated list. public void overtimePeriod(int ot).java public interface Sports { public void setHomeTeam(String name). public void visitingGoalScored().java public interface Football extends Sports { public void homeTeamScored(int points). The extends keyword is used once. An interface itself can extend another interface. and an interface can extend more than one parent interface. similarly to the way that a class can extend another class. } The Hockey interface has four methods. Extending Multiple Interfaces: A Java class can only extend one parent class. but it inherits two from Sports. //Filename: Sports. a class that implements Hockey needs to implement all six methods. public void visitingTeamScored(int points).• • A class can extend only one class. public void setVisitingTeam(String name). public void endOfQuarter(int quarter). } //Filename: Football. } //Filename: Hockey. . The following Sports interface is extended by Hockey and Football interfaces. Multiple inheritance is not allowed. a class that implements Football needs to define the three methods from Football and the two methods from Sports. Similarly. but implement many interface. however. An interface cannot extend another interface. The extends keyword is used to extend an interface. and the child interface inherits the methods of the parent interface. Interfaces are not classes. thus. Extending Interfaces: An interface can extend another interface.java public interface Hockey extends Sports { public void homeGoalScored().
but the class becomes an interface type through polymorphism. Some of the existing packages in Java are:: • • java.awt.Packages Packages are used in Java in-order to prevent naming conflicts. to control access. enumerations and annotations easier etc.classes for input . to make searching/locating and usage of classes. output functions are bundled in this package . Adds a data type to a class: This situation is where the term tagging comes from. you can use a tagging interface to create a common parent among a group of interfaces.bundles the fundamental classes java. enumerations and annotations ) providing access protection and name space management. it would be declared as: public interface Hockey extends Sports.event package extended java. public interface EventListener {} An interface with no methods in it is referred to as a tagging interface.EventListener. There are two basic design purposes of tagging interfaces: Creates a common parent: As with the EventListener interface.io . interfaces. interfaces.util. when an interface extends EventListener. A class that implements a tagging interface does not need to define any methods (since the interface does not have any).util. A Package can be defined as a grouping of related types(classes. Java . For example. Event Tagging Interfaces: The most common use of extending interfaces occurs when the parent interface does not contain any methods. the MouseListener interface in the java. which is extended by dozens of other interfaces in the Java API. if the Hockey interface extended both Sports and Event. which is defined as: package java.lang . the JVM knows that this particular interface is going to be used in an event delegation scenario. For example.For example.
Programmers can define their own packages to bundle group of classes/interfaces etc. interface Animal { public void eat(). and annotation types will be put into an unnamed package. enumerations. Put an interface in the package animals: /* File name : Animal. It is common practice to use lowercased names of packages to avoid any conflicts with the names of classes. It is a good practice to group related classes implemented by you so that a programmers can easily determine that the classes.java */ package animals. interfaces. annotations are related. } public void travel(){ . The package statement should be the first line in the source file. } Now put an implementation in the same package animals: package animals. enumerations. and annotation types that you want to include in the package. it is easier to provide access control and it is also easier to locate the related classed. Example: Let us look at an example that creates a package called animals. Using packages. interfaces. There can be only one package statement in each source file. you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes.java */ public class MammalInt implements Animal{ public void eat(){ System. Creating a package: When creating a package. If a package statement is not used then the class. enumerations. and it applies to all types in the file.out. /* File name : MammalInt. Since the package creates a new namespace there won't be any name conflicts with names in other packages.println("Mammal eats"). interfaces. public void travel(). interfaces.
the package name does not need to be used. } } Now you compile these two files and put them in a sub-directory called animals and try to run as follows: $ mkdir animals $ cp Animal. } public int noOfLegs(){ return 0. public class Boss { public void payEmployee(Employee e) { e.out. package payroll.eat().mailCheck().class MammalInt. m. For example: . • The fully qualified name of the class can be used.println("Mammal travels"). Example: Here a class named Boss is added to the payroll package that already contains Employee. } public static void main(String args[]){ MammalInt m = new MammalInt().class animals $ java animals/MammalInt Mammal eats Mammal travels The import Keyword: If a class wants to use another class in the same package. } } What happens if Boss is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package. as demonstrated by the following Boss class. The Boss can then refer to the Employee class without using the payroll prefix.travel(). m.System. Classes in the same package find each other without any special syntax.
• The class itself can be imported using the import keyword. For example: import payroll. Note: A class file can contain any number of import statements. interface. enumeration.java (in windows) . The name of the package must match the directory structure where the corresponding bytecode resides.Employee. The Directory Structure of Packages: Two major results occur when a class is placed in a package: • • The name of the package becomes a part of the name of the class... The import statements must appear after the package statement and before the class declaration.java Now put the source file in a directory whose name reflects the name of the package to which the class belongs: . Here is simple way of managing your files in java: Put the source code for a class.java Now the qualified class name and pathname would be as below: • • Class name -> vehicle.Employee • The package can be imported using the import keyword and the wild card (*). as we just discussed in the previous section. or annotation type in a text file whose name is the simple name of the type and whose extension is .\vehicle\Car.payroll.java. For example: // File Name : package vehicle. } Car. For example: import payroll.. public class Car { // Class implementation.*.Car Path name -> vehicle\Car.
interface and enumeration defined in it. then all its package names would start with com.java source file.\com\apple\computers\Dell.\com\apple\computers\Dell. However.computers package that contained a Dell.java source files.apple.com.computers.java At the time of compilation.. public class Dell{ } class Ups{ } Now compile this file as follows using -d option: $javac -d .java source files..class You can import all the classes or interfaces defined in \com\apple\computers\ as follows: import com. the path to the .apple. Dell.*. it would be contained in a series of subdirectories like this: . and its extension is . Each component of the package name corresponds to a subdirectory. Example: A company's Internet domain name is apple. the compiler creates a different output file for each class. as: <path-one>\sources\com\apple\computers\Dell.java package com.class files does not have to be the same as the path to the .java . the compiled .class files should be in a series of directories that reflect the package name. Like the .In general a company uses its reversed Internet domain name for its package names..apple.class For example: // File Name: Dell. The base name of the output file is the name of the type.\com\apple\computers\Ups.computers.java This would put compiled files as follows: . You can arrange your source and class directories separately.apple.class . Example: The company had a com.
Say <path-two>\classes is the class path. The full path to the classes directory. By default. use the following commands in Windows and Unix (Bourne shell): • • In Windows -> C:\> set CLASSPATH In Unix -> % echo $CLASSPATH To delete the current contents of the CLASSPATH variable. Both the compiler and the JVM construct the path to your . A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path. <path-two>\classes. and is set with the CLASSPATH system variable.The Hashtable Class .class files by adding the package name to the class path. use : • • In Windows -> C:\> set CLASSPATH= In Unix -> % unset CLASSPATH.apple.computers.class files in <pathtwo>\classes\com\apple\comptuers.<path-two>\classes\com\apple\computers\Dell. and the package name is com. is called the class path. export CLASSPATH Java Advanced Java – Data Structures Java . it is possible to give the classes directory to other programmers without revealing your sources. then the compiler and JVM will look for .class By doing this. export CLASSPATH To set the CLASSPATH variable: • • In Windows -> set CLASSPATH=C:\users\jack\java\classes In Unix -> % CLASSPATH=/home/jack/java/classes. Set CLASSPATH System Variable: To display the current CLASSPATH variable. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.
check The Enumeration. These data structures consist of the following interface and classes: • • • • • • • Enumeration BitSet Vector Stack Dictionary Hashtable Properties All these classes are now legacy and Java-2 has introcuded a new framework called Collections Framework which is discussed in next tutorial: The Enumeration: The Enumeration interface isn't itself a data structure. The Enumeration interface defines a means to retrieve successive elements from a data structure. .The data structures provided by the Java utility package are very powerful and perform a wide range of functions. Enumeration defines a method called nextElement that is used to get the next element in a data structure that contains multiple elements. To have more detail about this class. Like an array. To have more detail about this interface. check The BitSet. except that it can grow as necessary to accommodate new elements. The Vector The Vector class is similar to a traditional Java array. The BitSet The BitSet class implements a group of bits. elements of a Vector object can be accessed via an index into the vector. but it is very important within the context of other data structures. that can be set and cleared individually. you just assign a bit to each value and set or clear it as appropriate. For example. This class is very useful in cases where you need to keep up with a set of boolean values. or flags.
. The Dictionary The Dictionary class is an abstract class that defines a data structure for mapping keys to values. For example. To have more detail about this class. check The Vector. In other words. the last element you added to the stack is the first one to come back off. it gets stacked on top of the others. The specific meaning of keys in regard to hash tables is totally dependent on the usage of the hash table and the data it contains. The Stack The Stack class implements a last-in-first-out (LIFO) stack of elements. This is useful in cases where you want to be able to access data via a particular key rather than an integer index. check The Hashtable. The Hashtable The Hashtable class provides a means of organizing data based on some user-defined key structure. When you pull an element off the stack. To have more detail about this class. check The Dictionary. To have more detail about this class. To have more detail about this class. in an address list hash table you could store and sort data based on a key such as ZIP code rather than on a person's name.The nice thing about using the Vector class is that you don't have to worry about setting it to a specific size upon creation. it comes off the top. check The Stack. it provides only the framework for a key-mapped data structure rather than a specific implementation. it shrinks and grows automatically when necessary. when you add a new element. Since the Dictionary class is abstract. You can think of a stack literally as a vertical stack of objects.
The Properties class is used by many other Java classes. A collections framework is a unified architecture for representing and manipulating collections. unifying theme. The collections framework was designed to meet several goals.The Properties Properties is a subclass of Hashtable. Java provided ad hoc classes such as Dictionary. and Properties to store and manipulate groups of objects. The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability. Thus. For example. 2. Interfaces: These are abstract data types that represent collections. 2. The framework had to be high-performance. on objects that implement collection interfaces. Vector. In essence. they lacked a central. if you choose. The implementations for the fundamental collections (dynamic arrays. Algorithms: These are the methods that perform useful computations. the same method can be used on many different implementations of the appropriate collection interface.getProperties( ) when obtaining environmental values. Toward this end. Java . .Collections Framework P rior to Java 2. Classes: These are the concrete implementations of the collection interfaces. it is the type of object returned by System. Stack. they are reusable data structures. Extending and/or adapting a collection had to be easy. linked lists. In object-oriented languages. All collections frameworks contain the following: 1. Implementations i. 3. The algorithms are said to be polymorphic: that is. trees. 3. such as searching and sorting. Although these classes were quite useful. Several standard implementations such as LinkedList. the way that you used Vector was different from the way that you used Properties. HashSet. and hash tables) are highly efficient. the entire collections framework is designed around a set of standard interfaces.e. It is used to maintain lists of values in which the key is a String and the value is also a String. 1. interfaces generally form a hierarchy. Interfaces allow collections to be manipulated independently of the details of their representation. and TreeSet. of these interfaces are provided that you may use as-is and you may also implement your own collection.
Some of the classes provide full implementations that can be used as-is and others are abstract class. the framework defines several map interfaces and classes. The Collection Interfaces: The collections framework defines several interfaces. 2 3 4 5 6 7 8 The Collection Classes: Java provides a set of standard collection classes that implement Collection interfaces.In addition to collections. . This is an inner class of Map. The Set This extends Collection to handle sets. it is at the top of the collections hierarchy. This legacy interface has been superceded by Iterator. Although maps are not collections in the proper use of the term. providing skeletal implementations that are used as starting points for creating concrete collections. The Enumeration This is legacy interface and defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.Entry This describes an element (a key/value pair) in a map. This section provides an overview of each interface: SN 1 Interfaces with Description The Collection Interface This enables you to work with groups of objects. The List Interface This extends Collection and an instance of List stores an ordered collection of elements. but they are fully integrated with collections. which must contain unique elements The SortedSet This extends Set to handle sorted sets The Map This maps unique keys to values. The SortedMap This extends Map so that the keys are maintained in ascending order. The Map. Maps store key/value pairs.
Extends AbstractSet. LinkedHashSet Extends HashSet to allow insertion-order iterations. HashMap Extends AbstractMap to use a hash table. TreeMap Extends AbstractMap to use a tree. AbstractMap Implements most of the Map interface. LinkedHashMap Extends HashMap to allow insertion-order iterations. AbstractSet Extends AbstractCollection and implements most of the Set interface.The standard collection classes are summarized in the following table: SN 1 2 Classes with Description AbstractCollection Implements most of the Collection interface. IdentityHashMap Extends AbstractMap and uses reference equality when comparing documents. AbstractList Extends AbstractCollection and implements most of the List interface. HashSet Extends AbstractSet for use with a hash table. LinkedList Implements a linked list by extending AbstractSequentialList. 3 4 5 6 7 8 9 10 11 12 13 14 15 . AbstractSequentialList Extends AbstractList for use by a collection that uses sequential rather than random access of its elements. WeakHashMap Extends AbstractMap to use a hash table with weak keys. ArrayList Implements a dynamic array by extending AbstractList. TreeSet Implements a set stored in a tree.
Dictionary Dictionary is an abstract class that represents a key/value storage repository and operates much like Map. The following legacy classes defined by java. Several of the methods can throw a ClassCastException. EMPTY_LIST. SN Algorithms with Description . These algorithms are defined as static methods within the Collections class. AbstractList.The AbstractCollection. It is similar to ArrayList. 2 3 4 5 6 The Collection Algorithms: The collections framework defines several algorithms that can be applied to collections and maps. AbstractSet. BitSet A BitSet class creates a special type of array that holds bit values.util and is a concrete implementation of a Dictionary. Properties Properties is a subclass of Hashtable. or an UnsupportedOperationException. and EMPTY_MAP. All are immutable. first-out stack. Hashtable Hashtable was part of the original java. which occurs when an attempt is made to compare incompatible types. to minimize the effort required to implement them. Collections defines three static variables: EMPTY_SET.util has been discussed in previous tutorial: SN 1 Classes with Description Vector This implements a dynamic array. which occurs when an attempt is made to modify an unmodifiable collection. but with some differences. AbstractSequentialList and AbstractMap classes provide skeletal implementations of the core collection interfaces. Stack Stack is a subclass of Vector that implements a standard last-in. It is used to maintain lists of values in which the key is a String and the value is also a String. This array can increase in size as needed.
1 The Collection Algorithms Here is a list of all the algorithm implementation. . which is an object that implements either the Iterator or the ListIterator interface. A collection is an object that can hold references to other objects. This interface lets us sort a given collection any number of different ways. you might want to display each element. How to use an Comparator ? Both TreeSet and TreeMap store elements in sorted order. Also this interface can be used to sort any instances of any class. obtaining or removing elements. However. SN 1 Iterator Methods with Description Using Java Iterator Here is a list of all the methods with examples provided by Iterator and ListIterator interfaces. SN 1 Iterator Methods with Description Using Java Comparator Here is a list of all the methods with examples provided by Comparator Interface. The collection interfaces declare the operations that can be performed on each type of collection. and the modification of elements. it is the comparator that defines precisely what sorted order means. ListIterator extends Iterator to allow bidirectional traversal of a list.(even classes we cannot modify). you will want to cycle through the elements in a collection. For example. Iterator enables you to cycle through a collection. How to use an Iterator ? Often. Summary: The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them. The easiest way to do this is to employ an iterator.
Example: Following example illustrate how we can print array of different type using a single Generic method: public class GenericMethodTest . to sort the array elements. Using Java Generic concept we might write a generic method for sorting an array of objects.The classes and interfaces of the collections framework are in package java. Note that type parameters can represent only reference types not primitive types (like int. is an identifier that specifies a generic type name. Double arrays. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method. Based on the types of the arguments passed to the generic method. a set of related types. a String array or an array of any type that supports ordering. with a single method declaration. Generic Methods: You can write a single generic method declaration that can be called with arguments of different types. respectively. a set of related methods or. then invoke the generic method with Integer arrays.util. Java . Java Generic methods and generic classes enable programmers to specify. double and char). which are known as actual type arguments. String arrays and so on. Each type parameter section contains one or more type parameters separated by commas. also known as a type variable. Following are the rules to define Generic Methods: • • • • All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time. A generic method's body is declared like that of any other method.Generics It would be nice if we could write a single sort method that could sort the elements in an Integer array. A type parameter. the compiler handles each method call appropriately. with a single class declaration.
Character[] charArray = { 'H'.out.println( "Array integerArray contains:" ). 3. } public static void main( String args[] ) { // Create arrays of Integer. . list the type parameter's name. 2.out. // pass a Character array } } This would produce following result: Array integerArray contains: 1 2 3 4 5 6 Array doubleArray contains: 1. For example.2 3. 3. Double and Character Integer[] intArray = { 1. followed by its upper bound. 'L'. element ). 4. System. Double[] doubleArray = { 1.4 }.println( "\nArray doubleArray contains:" ).println( "\nArray characterArray contains:" ). 'L'. printArray( integerArray ).3 4. followed by the extends keyword.1.1 2.println(). 4. // pass an Integer array System.3.out. This is what bounded type parameters are for. printArray( doubleArray ). // pass a Double array System. To declare a bounded type parameter.2. 'O' }.4 Array characterArray contains: H E L L O Bounded Type Parameters: There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. } System. 5 }.{ // generic method printArray public static < E > void printArray( E[] inputArray ) { // Display array elements for ( E element : inputArray ){ System.out. a method that operates on numbers might only want to accept instances of Number or its subclasses.printf( "%s ". 'E'.out. printArray( characterArray ). 2.
5. // y is the largest so far } if ( z. 6.printf( "Maxm of %.6. These classes are known as parameterized classes or parameterized types because they accept one or more parameters. maximum( 6. 8. 8.%.7 is 8. 7. As with generic methods.7 ) ). "orange" ) ). // z is the largest now } return max. maximum( "pear". // assume x is initially the largest if ( y. T z) { T max = x. 4 and 5 is 5 Maximum of 6.compareTo( max ) > 0 ){ max = y.printf( "Max of %d. %s and %s is %s\n".6. System. "apple". apple and orange is pear Generic Classes: A generic class declaration looks like a non-generic class declaration.8 Maximum of pear. 7. T y.8 and 7. 4. "orange". "apple".1f is %.1f\n\n"."pear".1f and %.6. maximum( 3. %d and %d is %d\n\n". This example is Generic method to return the largest of three Comparable objects: public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x.out.out. 3. System. except that the class name is followed by a type parameter section.out.8. 4. // returns the largest object } public static void main( String args[] ) { System.printf( "Max of %s. 5 ) ).compareTo( max ) > 0 ){ max = z. .1f. 8.7. the type parameter section of a generic class can have one or more type parameters separated by commas.Example: Following example illustrate how extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). } } This would produce following result: Maximum of 3.8.
t = t.out. public void add(T t) { this.printf("String Value :%s\n". System. Most impressive is that the entire process is JVM independent.out. After a serialized object has been written into a file.add(new String("Hello World")). System. called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. } } This would produce following result: Integer Value :10 String Value :Hello World Java . } public T get() { return t. stringBox. integerBox. it can be read from the file and deserialized that is. } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(). meaning an object can be serialized on one platform and deserialized on an entirely different platform. the type information and bytes that represent the object and its data can be used to recreate the object in memory.Serialization Java provides a mechanism.Example: Following example illustrate how we can define a generic class: public class Box<T> { private T t.get()). stringBox.add(new Integer(10)).printf("Integer Value :%d\n\n". Box<String> stringBox = new Box<String>().get()). . integerBox.
Similarly. The return value is Object.io. then it is serializable. public int number. To demonstrate how serialization works in Java. The test is simple: If the class implements java.Serializable.Serializable interface. ClassNotFoundException This method retrieves the next Object out of the stream and deserializes it. otherwise.Serializable { public String name. but one method in particular stands out: public final void writeObject(Object x) throws IOException The above method serializes an Object and sends it to the output stream.Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object. If a field is not serializable. public void mailCheck() { System. the ObjectInputStream class contains the following method for deserializing an object: public final Object readObject() throws IOException.println("Mailing a check to " + name + " " + address). it's not. check the documentation for the class. All of the fields in the class must be serializable.io. Serializing an Object: . public String address. If you are curious to know if a Java Satandard Class is serializable or not. which implements the Serializable interface: public class Employee implements java. Suppose that we have the following Employee class. so you will need to cast it to its appropriate data type.out. } } Notice that for a class to be serialized successfully. I am going to use the Employee class that we discussed early on in the book. The ObjectOutputStream class contains many write methods for writing various data types. it must be marked transient. two conditions must be met: • • The class must implement the java.io. public int transient SSN.
The ObjectOutputStream class is used to serialize an Object.close(). try { FileOutputStream fileOut = new FileOutputStream("employee.printStackTrace(). }catch(IOException i) { i. When the program is done executing.close(). } } } Deserializing an Object: The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. e.ser is created.ser").*. try { .name = "Reyan Ali". fileOut. The program does not generate any output. public class DeserializeDemo { public static void main(String [] args) { Employee e = null. e. import java.address = "Phokka Kuan.ser extension. Note: When serializing an object to a file. the standard convention in Java is to give the file a .*.number = 101. The following SerializeDemo program instantiates an Employee object and serializes it to a file. but study the code and try to determine what the program is doing. e. e. Ambehta Peer". public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee().io. out. ObjectOutputStream out = new ObjectOutputStream(fileOut). out. a file named employee.writeObject(e).io. Study the program and try to determine its output: import java.SSN = 11122333.
return. return. it throws a ClassNotFoundException. Java .out. fileIn.ser"). c.out. If the JVM can't find a class during the deserialization of an object. e = (Employee) in.Employee class not found. }catch(IOException i) { i.address).println("Number: " + e.printStackTrace().close(). this value was not sent to the output stream. System. which is declared by the readObject() method.out. System. System.name). .. ObjectInputStream in = new ObjectInputStream(fileIn). Name: Reyan Ali Address:Phokka Kuan.number).println(.Networking (Socket Programming) The term network programming refers to writing programs that execute across multiple devices (computers).. Ambehta Peer SSN: 0 Number:101 Here are following important points to be noted: • • • The try/catch block tries to catch a ClassNotFoundException.out.println("Deserialized Employee. but because the field is transient. } System. For a JVM to be able to deserialize an object.println("Address: " + e.println("SSN: " + e. in which the devices are all connected to each other using a network.readObject().").close().out.println("Name: " + e. in.printStackTrace(). } } This would produce following result: Deserialized Employee.FileInputStream fileIn = new FileInputStream("employee.SSN). System.out. The value of the SSN field was 11122333 when the object was serialized.). The SSN field of the deserialized Employee object is 0.. }catch(ClassNotFoundException c) { System. it must be able to find the bytecode for the class. Notice that the return value of readObject() is cast to an Employee reference..
A client program creates a socket on its end of the communication and attempts to connect that socket to a server. The java.The java. This tutorial gives good understanding on the following two subjects: 1. a connection-less protocol that allows for packets of data to be transmitted between applications.net package provides support for the two common network protocols: • • TCP: TCP stands for Transmission Control Protocol. 3. The server instantiates a ServerSocket object. . specifying the server name and port number to connect to. TCP is typically used over the Internet Protocol. UDP: UDP stands for User Datagram Protocol. a client instantiates a Socket object. This method waits until a client connects to the server on the given port. Click here to learn about URL Processing in Java language.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them. URL Processing: This would be covered separately. When the connection is made. the client now has a Socket object capable of communicating with the server. 4.Socket class represents a socket.net. 2.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details. denoting which port number communication is to occur on. and the java. The client and server can now communicate by writing to and reading from the socket. which is referred to as TCP/IP. allowing you to write programs that focus on solving the problem at hand. the server creates a socket object on its end of the communication. Socket Programming: This is most widely used concept in Networking and it has been explained in very detail. The constructor of the Socket class attempts to connect the client to the specified server and port number. The following steps occur when establishing a TCP connection between two computers using sockets: 1. which allows for reliable communication between two applications. If communication is established. The java. 2. Socket Programming: Sockets provide the communication mechanism between two computers using TCP. After the server is waiting. The server invokes the accept() method of the ServerSocket class.net.
5. On the server side. Here are some of the common methods of the ServerSocket class: . public ServerSocket(int port. allowing the server to specify which of its IP addresses to accept client requests on public ServerSocket() throws IOException Creates an unbound server socket. the accept() method returns a reference to a new socket on the server that is connected to the client's socket.ServerSocket class is used by server applications to obtain a port and listen for client requests The ServerSocket class has four constructors: SN 1 Methods with Description public ServerSocket(int port) throws IOException Attempts to create a server socket bound to the specified port. The client's OutputStream is connected to the server's InputStream. The InetAddress is used for servers that may have multiple IP addresses. There are following usefull classes providing complete set of methods to implement sockets. TCP is a twoway communication protocol. communication can occur using I/O streams. After the connections are established. When using this constructor. InetAddress address) throws IOException Similar to the previous constructor. int backlog) throws IOException Similar to the previous constructor. Each socket has both an OutputStream and an InputStream. public ServerSocket(int port. the backlog parameter specifies how many incoming clients to store in a wait queue. An exception occurs if the port is already bound by another application.net. so data can be sent across both streams at the same time. use the bind() method when you are ready to bind the server socket 2 3 4 If the ServerSocket constructor does not throw an exception. the InetAddress parameter specifies the local IP address to bind to. and the client's InputStream is connected to the server's OutputStream. ServerSocket Class Methods: The java. int backlog. it means that your application has successfully bound to the specified port and is ready for client requests.
this method blocks indefinitely public void setSoTimeout(int timeout) Sets the time-out value for how long the server socket waits for a client during the accept().SN 1 Methods with Description public int getLocalPort() Returns the port that the server socket is listening on. the method does not return until a client connects. public void bind(SocketAddress host. public Socket(InetAddress host. public Socket(String host.net. IOException. Use this method if you instantiated the ServerSocket using the no-argument constructor. except that the host is denoted by an InetAddress object. The client obtains a Socket object by instantiating one. Otherwise. A TCP connection now exists between the client and server. whereas the server obtains a Socket object from the return value of the accept() method. the connection is successful and the client is connected to the server. InetAddress localAddress. int localPort) 1 2 3 . 2 3 4 When the ServerSocket invokes accept(). If this constructor does not throw an exception. This method blocks until either a client connects to the server on the specified port or the socket times out. assuming that the time-out value has been set using the setSoTimeout() method. Socket Class Methods: The java. and communication can begin. int port. the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket.Socket class represents the socket that both the client and server use to communicate with each other. This method attempts to connect to the specified server at the specified port. After a client does connect. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you. int port) throws IOException This method is identical to the previous constructor. The Socket class has five constructors that a client uses to connect to a server: SN Methods with Description public Socket(String host. int port) throws UnknownHostException. public Socket accept() throws IOException Waits for an incoming client. int backlog) Binds the socket to the specified server and port in the SocketAddress object.
except that the host is denoted by an InetAddress object instead of a String public Socket() Creates an unconnected socket. InetAddress localAddress. int localPort) throws IOException. Connects to the specified host and port. public Socket(InetAddress host.throws IOException. creating a socket on the local host at the specified address and port. int port. so these methods can be invoked by both the client and server. public InetAddress getInetAddress() This method returns the address of the other computer that this socket is connected to. This method is identical to the previous constructor. public SocketAddress getRemoteSocketAddress() Returns the address of the remote socket. Some methods of interest in the Socket class are listed here. 4 5 When the Socket constructor returns. public int getLocalPort() Returns the port the socket is bound to on the local machine. public InputStream getInputStream() throws IOException Returns the input stream of the socket. The input stream is connected to the output stream of the remote socket. public int getPort() Returns the port the socket is bound to on the remote machine. The output stream is connected to the input stream of the remote socket 2 3 4 5 6 7 . This method is needed only when you instantiated the Socket using the no-argument constructor. SN 1 Methods with Description public void connect(SocketAddress host. Use the connect() method to connect this socket to a server. public OutputStream getOutputStream() throws IOException Returns the output stream of the socket. int timeout) throws IOException This method connects the socket to the specified host. Notice that both the client and server have a Socket object. it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port.
net. String getHostName() Gets the host name for this IP address. String toString() Converts this IP address to a String. byte[] addr) Create an InetAddress based on the provided host name and IP address.java import java.io. String getHostAddress() Returns the IP address string in textual presentation. Socket Client Example: The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting. static InetAddress InetAddress getLocalHost() Returns the local host.*. given the host's name.*. Here are following usefull methods which you would need while doing socket programming: SN 1 2 3 4 5 6 7 Methods with Description static InetAddress getByAddress(byte[] addr) Returns an InetAddress object given the raw IP address . public class GreetingClient { public static void main(String [] args) { String serverName = args[0]. // File Name GreetingClient.8 public void close() throws IOException Closes the socket. . and then waits for a response. static InetAddress getByAddress(String host. static InetAddress getByName(String host) Determines the IP address of a host. import java. which makes this Socket object no longer capable of connecting again to any server InetAddress Class Methods: This class represents an Internet Protocol (IP) address.
getInputStream().close(). client. DataInputStream in = new DataInputStream(inFromServer).io. import java.printStackTrace().java import java.out. } public void run() { while(true) { try { System.out.readUTF()). }catch(IOException e) { e. public GreetingServer(int port) throws IOException { serverSocket = new ServerSocket(port).println("Just connected to " + client.*.*.int port = Integer. System. serverSocket.getRemoteSocketAddress()). InputStream inFromServer = client.net. Socket client = new Socket(serverName. public class GreetingServer extends Thread { private ServerSocket serverSocket.println("Server says " + in.getOutputStream().println("Waiting for client on port " + . port). OutputStream outToServer = client. out.println("Connecting to " + serverName + " on port " + port). DataOutputStream out = new DataOutputStream(outToServer).out.getLocalSocketAddress()).writeUTF("Hello from " + client. try { System.parseInt(args[1]).setSoTimeout(10000). System. } } } Socket Server Example: The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument: // File Name GreetingServer.out.
System.Sending Email .println("Just connected to " + server. server. try { Thread t = new GreetingServer(port).out.writeUTF("Thank you for connecting to " + server.0. } } } Compile client and server and then start server as follows: $ java GreetingServer 6066 Waiting for client on port 6066.0. out.printStackTrace(). Socket server = serverSocket. }catch(SocketTimeoutException s) { System. break.readUTF()).close().getLocalPort() + ". }catch(IOException e) { e.. }catch(IOException e) { e.1:6066 Goodbye! Java .println(in.parseInt(args[0]).getOutputStream()). System.serverSocket. break.accept().getRemoteSocketAddress()).out.printStackTrace(). DataInputStream in = new DataInputStream(server.0.getInputStream()).. Check client program as follows: $ java GreetingClient localhost 6066 Connecting to localhost on port 6066 Just connected to localhost/127.start().")..println("Socket timed out!"). } } } public static void main(String [] args) { int port = Integer.1:6066 Server says Thank you for connecting to /127.0.out.getLocalSocketAddress() + "\nGoodbye!"). DataOutputStream out = new DataOutputStream(server.. t.
internet. Here it is assumed that your localhost is connected to the internet and capable enough to send an email. • • You can download latest version of JavaMail (Version 1. public class SendEmail { public static void main(String [] args) { // Recipient's email ID needs to be mentioned. Download and unzip these files.host".com".mail. javax. javax.smtp.*.2) from Java's standard website.setProperty("mail. // File Name SendEmail.jar and activation.jar files in your CLASSPATH. javax. // Sender's email ID needs to be mentioned String from = "web@gmail. in the newly created top level directories you will find a number of jar files for both the applications. // Get the default Session object. // Get system properties Properties properties = System. You can download latest version of JAF (Version 1.java import import import import java. Send a Simple Email: Here is an example to send a simple email from your machine.util. String to = "abcd@gmail.mail. Session session = Session.com". .*.1. host). try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session).To send an email using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine. // Setup mail server properties. // Assuming you are sending email from localhost String host = "localhost".getProperties().1) from Java's standard website.*. You need to add mail.*.activation.getDefaultInstance(properties).
println("Sent message successfully.setSubject("This is the Subject Line!"). new InternetAddress(to)).send(message). CC or BCC. .RecipientType type.").RecipientType. // Set Subject: header field message.out. // Now set the actual message message.RecipientType.TO addresses: This is the array of email ID. }catch (MessagingException mex) { mex. System.setFrom(new InternetAddress(from)). If you want to send an email to multiple recipients then following methods would be used to specify multiple email IDs: void addRecipients(Message. message.. Example Message.// Set From: header field of the header.. // Set To: header field of the header..printStackTrace().setText("This is actual message"). Here CC represents Carbon Copy and BCC represents Black Carbon Copy. message. You would need to use InternetAddress() method while specifying email IDs Send an HTML Email: Here is an example to send an HTML email from your machine.. Here it is assumed that your localhost is connected to the internet and capable enough to send an email.TO. } } } Compile and run this program to send a simple email: $ java SendEmail Sent message successfully. Address[] addresses) throws MessagingException Here is the description of the parameters: • • type: This would be set to TO. // Send message Transport...addRecipient(Message.
setFrom(new InternetAddress(from)).java import import import import java. message.TO.setProperty("mail. public class SendHTMLEmail { public static void main(String [] args) { // Recipient's email ID needs to be mentioned.RecipientType. // Set To: header field of the header.util.activation. message. try{ // Create a default MimeMessage object. // Set From: header field of the header.getProperties(). "text/html" ). // Send message . Using this example.setContent("<h1>This is actual message</h1>".*.mail. // Sender's email ID needs to be mentioned String from = "web@gmail. you can send as big as HTML content you like.com".setSubject("This is the Subject Line!").*. host).host". javax. String to = "abcd@gmail. // File Name SendHTMLEmail. // Setup mail server properties. except here we are using setContent() method to set content whose second argument is "text/html" to specify that the HTML content is included in the message. javax.getDefaultInstance(properties).smtp. Session session = Session.*. // Assuming you are sending email from localhost String host = "localhost".internet. // Set Subject: header field message.com".mail. // Send the actual HTML message.This example is very similar to previous one. new InternetAddress(to)). // Get system properties Properties properties = System. // Get the default Session object.*.addRecipient(Message. as big as you like message. javax. MimeMessage message = new MimeMessage(session).
println("Sent message successfully. System.util.out.*. javax..printStackTrace(). // File Name SendFileEmail. Send Attachment in Email: Here is an example to send an email with attachment from your machine. public class SendFileEmail { public static void main(String [] args) { // Recipient's email ID needs to be mentioned.com".getDefaultInstance(properties). // Setup mail server properties..send(message).activation.Transport. } } } Compile and run this program to send an HTML email: $ java SendHTMLEmail Sent message successfully.mail. try{ // Create a default MimeMessage object.. // Get the default Session object. Here it is assumed that your localhost is connected to the internet and capable enough to send an email. Session session = Session.*.*.. .internet.mail.setProperty("mail.*.java import import import import java. javax. // Assuming you are sending email from localhost String host = "localhost".. }catch (MessagingException mex) { mex. javax.smtp. // Sender's email ID needs to be mentioned String from = "web@gmail. // Get system properties Properties properties = System. host)."). String to = "abcd@gmail.host"..getProperties().com".
setDataHandler(new DataHandler(source)). // Set To: header field of the header... // Fill the message messageBodyPart.out.println("Sent message successfully..setFileName(filename). }catch (MessagingException mex) { mex. // Send message Transport. User Authentication Part: . // Send the complete message parts message. // Set text message part multipart. // Set From: header field of the header. messageBodyPart. message. new InternetAddress(to)).").send(message).RecipientType. // Set Subject: header field message. messageBodyPart. // Part two is attachment messageBodyPart = new MimeBodyPart().addBodyPart(messageBodyPart).setSubject("This is the Subject Line!").TO. // Create a multipar message Multipart multipart = new MimeMultipart(). System.setContent(multipart ). multipart.setFrom(new InternetAddress(from)). String filename = "file.txt". message.setText("This is message body")..addRecipient(Message.MimeMessage message = new MimeMessage(session)..printStackTrace(). // Create the message part BodyPart messageBodyPart = new MimeBodyPart(). DataSource source = new FileDataSource(filename).addBodyPart(messageBodyPart).. } } } Compile and run this program to send an HTML email: $ java SendFileEmail Sent message successfully.
Java .If it is required to provide user ID and Password to the email server for authentication purpose then you can set these properties as follows: props.user". Each part of such a program is called a thread. and each thread defines a separate path of execution.setProperty("mail. "mypwd"). and then dies. A multithreading is a specialized form of multitasking. started. A thread cannot exist on its own. A multithreaded program contains two or more parts that can run concurrently. . because idle time can be kept to a minimum.password". For example. Life Cycle of a Thread: A thread goes through various stages in its life cycle. A process remains running until all of the non-daemon threads are done executing. "myuser"). props. Following diagram shows complete life cycle of a thread.Multithreading Java provides built-in support for multithreaded programming. runs. Rest of the email sending mechanism would remain as explained above. Multithreading enables you to write very efficient programs that make maximum use of the CPU. Multitasking threads require less overhead than multitasking processes. a thread is born.setProperty("mail. it must be a part of a process. I need to define another term related to threads: process: A process consists of the memory space allocated by the operating system that can contain one or more threads.
Above mentioned stages are explained here: • • • • • New: A new thread begins its life cycle in the new state. every thread is given priority NORM_PRIORITY (a constant of 5). Thread Priorities: Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. By default.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. the thread becomes runnable. Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. A thread in this state is considered to be executing its task. Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task. Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). It is also referred to as a born thread. Runnable: After a newly born thread is started. Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates. . It remains in this state until the program starts the thread.
itself. a class need only implement a single method called run( ). After the new thread is created. Creating a Thread: Java defines two ways in which this can be accomplished: • • You can implement the Runnable interface. you will instantiate an object of type Thread from within that class. After you create a class that implements Runnable. thread priorities cannot guarantee the order in which threads execute and very much platform dependentant. use other classes. which is declared like this: public void run( ) You will define the code that constitutes the new thread inside run() method. The one that we will use is shown here: Thread(Runnable threadOb.Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. it will not start running until you call its start( ) method. and declare variables. It is important to understand that run() can call other methods. You can extend the Thread class. Thread defines several constructors. To implement Runnable. just like the main thread can. Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName. Create Thread by Implementing Runnable: The easiest way to create a thread is to create a class that implements the Runnable interface. . Example: Here is an example that creates a new thread and starts it running: // Create a new thread. However. The start( ) method is shown here: void start( ). String threadName). which is declared within Thread.
. i--) { System.out."). Thread. Thread. "Demo Thread").class NewThread implements Runnable { Thread t.start().main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread.println("Child Thread: " + i).out. i--) { System.out.out.5. // create a new thread try { for(int i = 5.println("Main thread interrupted.sleep(500).").sleep(1000).out. i > 0. } } catch (InterruptedException e) { System. Main Thread: 2 Main Thread: 1 Main thread exiting. second thread t = new Thread(this. } } This would produce following result: Child thread: Thread[Demo Thread. } } class ThreadDemo { public static void main(String args[]) { new NewThread().").out.println("Child thread: " + t).out.println("Exiting child thread. } System.println("Main thread exiting. public void run() { try { for(int i = 5. } System. t."). // Start the thread } // This is the entry point for the second thread. } } catch (InterruptedException e) { System. NewThread() { // Create a new.println("Child interrupted. System. i > 0.println("Main Thread: " + i). // Let the thread sleep for a while.
println("Child thread: " + this). } } catch (InterruptedException e) { System.out."). // create a new thread try { for(int i = 5.println("Exiting child thread. Example: Here is the preceding program rewritten to extend Thread: // Create a second thread by extending Thread class NewThread extends Thread { NewThread() { // Create a new. } } class ExtendThread { public static void main(String args[]) { new NewThread(). which is the entry point for the new thread."). Thread.out.sleep(500). // Start the thread } // This is the entry point for the second thread.println("Main thread exiting.Create Thread by Extending Thread: The second way to create a thread is to create a new class that extends Thread. i > 0.out. } System.out.out. System. i--) { System.sleep(1000).out.println("Child interrupted. The extending class must override the run( ) method. Thread. public void run() { try { for(int i = 5. } } This would produce following result: . second thread super("Demo Thread"). start(). i > 0. // Let the thread sleep for a while.out.println("Main Thread: " + i)."). } System. } } catch (InterruptedException e) { System.println("Child Thread: " + i). It must also call start( ) to begin execution of the new thread."). and then to create an instance of that class.println("Main thread interrupted. i--) { System.
Thread Methods: Following is the list of important medthods available in the Thread class.Child thread: Thread[Demo Thread. public final boolean isAlive() 2 3 4 5 6 7 8 . the run() method is invoked on that Runnable object. public void interrupt() Interrupts this thread. causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. public final void join(long millisec) The current thread invokes this method on a second thread. public void run() If this Thread object was instantiated using a separate Runnable target. Main Thread: 2 Main Thread: 1 Main thread exiting. The possible values are between 1 and 10. causing it to continue execution if it was blocked for any reason. then invokes the run() method on this Thread object. public final void setPriority(int priority) Sets the priority of this Thread object. There is also a getName() method for retrieving the name.5. public final void setName(String name) Changes the name of the Thread object. public final void setDaemon(boolean on) A parameter of true denotes this Thread as a daemon thread. SN 1 Methods with Description public void start() Starts the thread in a separate path of execution.
} public void run() { while(true) { System.java // Create a thread to implement Runnable public class DisplayMessage implements Runnable { private String message. The following methods in the Thread class are static.out. which is the thread that invokes this method. public static void dumpStack() Prints the stack trace for the currently running thread. which is any time after the thread has been started but before it runs to completion. public DisplayMessage(String message) { this. 2 3 4 5 Example: The following ThreadClassDemo program demonstrates some of these methods of the Thread class: // File Name : DisplayMessage.println(message). } .Returns true if the thread is alive. public static Thread currentThread() Returns a reference to the currently running thread.message = message. The previous methods are invoked on a particular Thread object. Invoking one of the static methods performs the operation on the currently running thread SN 1 Methods with Description public static void yield() Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled public static void sleep(long millisec) Causes the currently running thread to block for at least the specified number of milliseconds public static boolean holdsLock(Object x) Returns true if the current thread holds the lock on the given Object. which is useful when debugging a multithreaded application.
setPriority(Thread.out.number = number. }catch(InterruptedException e) { System. } } // File Name : ThreadClassDemo. System.println("Starting hello thread. } public void run() { int counter = 0."). System. System. Thread thread2 = new Thread(hello).out.random() * 100 + 1). public GuessANumber(int number) { this. thread1.**"). try { thread3. int guess = 0.setDaemon(true). Thread thread1 = new Thread(hello).. Runnable bye = new DisplayMessage("Goodbye")..join().. thread2.println("Starting thread3..out.java public class ThreadClassDemo { public static void main(String [] args) { Runnable hello = new DisplayMessage("Hello").java // Create a thread to extentd Thread public class GuessANumber extends Thread { private int number. thread1. thread3.out.} } // File Name : GuessANumber.setName("hello").println("Starting goodbye thread. do { guess = (int) (Math. thread2.println("Thread interrupted. counter++..")..getName() + " guesses " + guess).getName() + " in " + counter + " guesses.").start().out.println("** Correct! " + this.").println(this. thread1. System.MIN_PRIORITY).start(). Thread thread3 = new GuessANumber(27). System.out. }while(guess != number). . thread2.start().setDaemon(true).
when you have two subsystems within a program that can execute concurrently.. Stop and Resume Using Multithreading: The key to utilizing multithreading support effectively is to think concurrently rather than serially.println("Starting thread4..println("main() is ending. You can try this example again and again and you would get different result every time. make them individual threads. For example.start(). Hello Hello .remaining result produced.. Hello Hello Hello Hello Hello Hello Hello Hello Hello Thread-2 guesses 27 Hello ** Correct! Thread-2 in 102 guesses.. Major Thread Concepts: While doing Multithreading programming.} System. .. Starting hello thread.** Hello Starting thread4.out. } } This would produce following result.....").. Thread thread4 = new GuessANumber(75).... Starting goodbye thread.out..."). you would need to have following concepts very handy: • • • • Thread Synchronization Interthread Communication Thread Deadlock Thread Control: Suspend.. thread4... System..
With the careful use of multithreading, you can create very efficient programs. A word of caution is in order, however: If you create too many threads, you can actually degrade the performance of your program rather than enhance it. Remember, some overhead is associated with context switching. If you create too many threads, more CPU time will be spent changing contexts than executing your program!
Java - Applets Basics:
• • • • • • •
•
An applet is a Java class that extends the java.applet.Applet class.:
• •
•.
•
•:
• •:
• • • • • • • •:
• • • • • •" height="120">.
The second color and the size of each square may be specified as parameters to the applet within the document. For example: <applet code="mypackage. However. instead of at every refresh.TestApplet.// initialized to default size .class" width="320" height="120"> Getting Applet Parameters: The following example demonstrates how to make an applet respond to setup parameters specified in the document. The Applet. The viewer or browser looks for the compiled Java code at the location of the document. class CheckerApplet extends Applet squareSize = 50.class" width="320" height="120"> If an applet resides in a package other than the default. To specify otherwise.applet. is convenient and efficient. java.java: import import public { int java. The applet viewer or browser calls the init() method of each applet it runs. Therefore. immediately after loading the applet.*.com/applets" code="HelloWorldApplet.subpackage. use the codebase attribute of the <applet> tag as shown: <applet codebase=". not related to the applet. This applet displays a checkerboard pattern of black and a second color.) to separate package/class components.getParameter() method fetches a parameter given the parameter's name (the value of a parameter is always a string). If the value is numeric or other non-character data. CheckerApplet gets its parameters in the init() method. The viewer calls init() once.) Override the default implementation to insert custom initialization code. The following is a skeleton of CheckerApplet. the string must be parsed. (Applet. getting the values and saving the settings once at the start of the applet. It may also get its parameters in the paint() method. the holding package must be specified in the code attribute using the period character (.*.init() is implemented to do nothing. is visible in non-Java-enabled browsers.Non-Java-enabled browsers do not process <applet> and </applet>. anything that appears between the tags.
parseInt(). The HTML file specifies both parameters to the applet by means of the <param> tag. } private void parseSquareSize (String param) { if (param == null) return. parseColor() does a series of string comparisons to match the parameter value to the name of a predefined color. Therefore. which parses a string and returns an integer.}").black). parseSquareSize() catches exceptions. The applet calls parseColor() to parse the color parameter into a Color value.class" width="480" height="320"> . You need to implement these methods to make this applet works. Specifying Applet Parameters: The following is an example of an HTML file with a CheckerApplet embedded in it.parseInt (param). Color fg = parseColor (colorParam). <html> <title>Checkerboard Applet</title> <hr> <applet code="CheckerApplet. setForeground (fg). parseSquareSize() calls the library method Integer. rather than allowing the applet to fail on bad input. } catch (Exception e) { // Let default value remain } } The applet calls parseSquareSize() to parse the squareSize parameter. String colorParam = getParameter ("color"). Integer. try { squareSize = Integer. setBackground (Color. parseSquareSize (squareSizeParam).parseInt() throws an exception whenever its argument is invalid.
An applet cannot be closed. import java. using the HTML title tag.awt. the applet cannot be loaded.MouseEvent. of course. Your application will be displayed inside the browser. Move any initialization code from the frame window constructor to the init method of the applet. it terminates when the browser exits. If the application calls setTitle. Otherwise. Inorder to react an event. 2. for handling particular types of events. 7.) 8. Eliminate the main method in the application. The Container class defines several methods. 6. 3. Application Conversion to Applets: It is easy to convert a graphical Java application (that is. Event Handling: Applets inherit a group of event-handling methods from the Container class. Here are the specific steps for converting an application to an applet.the browser instantiates it for you and calls the init method. an applet must override the appropriate event-specific method. an application that uses the AWT and that you can start with the java program launcher) into an applet that you can embed in a web page. import java. such as processKeyEvent and processMouseEvent. You don't need to explicitly construct the applet object. Don't call setVisible(true).MouseListener. eliminate the call to the method. The applet is displayed automatically. 4. for applets.<param name="color" value="blue"> <param name="squaresize" value="30"> </applet> <hr> </html> Note: Parameter names are not case sensitive. Applets cannot have title bars. and then one catch-all method called processEvent.Applet. sizing is done with the width and height parameters in the HTML file. . import java. Remove the call to setDefaultCloseOperation. title the web page itself. Make an HTML page with the appropriate tag to load the applet code.applet. Remove the call to setSize.event. 5.awt. 1. Make this class public. Do not construct a frame window for the application. (You can. Supply a subclass of the JApplet class.event.
} void addItem(String word) { System. strBuffer = new StringBuffer(). } public void stop() { addItem("stopping the applet ").awt. 0.append(word). public void init() { addMouseListener(this). addItem("initializing the apple "). g.drawRect(0.import java. getHeight() . repaint(). } public void destroy() { addItem("unloading the applet"). } } . public class ExampleEventHandling extends Applet implements MouseListener { StringBuffer strBuffer. } public } public } public } public } void mouseEntered(MouseEvent event) { void mouseExited(MouseEvent event) { void mousePressed(MouseEvent event) { void mouseReleased(MouseEvent event) { public void mouseClicked(MouseEvent event) { addItem("mouse clicked! ").Graphics.toString().drawString(strBuffer.1). g.println(word).1. strBuffer.out. } public void start() { addItem("starting the applet "). 20). getWidth() . //display the string inside the rectangle. } public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. 10.
String imageURL = this. you use the drawImage() method found in the java. To display an image within the applet.*.awt. and others. here is the live applet example: Applet Example. Displaying Images: An applet can display images of the format GIF. // Display in browser status bar context. import java. JPEG.getParameter("image"). import java.printStackTrace().Graphics class.net.Now let us call this applet as follows: <html> <title>Event Handling</title> <hr> <applet code="ExampleEventHandling. private AppletContext context.getDocumentBase().*. } } .applet.getAppletContext(). imageURL). image = context.jpg". Following is the example showing all the steps to show images: import java. }catch(MalformedURLException e) { e. if(imageURL == null) { </applet> <hr> </html> Initially the applet will display "initializing the applet. public void init() { context = this.awt. Starting the applet." Then once you click inside the rectangle "mouse clicked" will be displayed as well.getImage(url).
whether or not the URL resolves to an actual audio file. 100).javalicense.net.class" width="300" height="200"> <param name="image" value="java.*. .getAppletContext(). g. import java.drawString("("Displaying image").applet package. Following is the example showing all the steps to play an audio: import java. import java.jpg"> </applet> <hr> </html> Based on the above examples. g. The getAudioClip() method returns immediately.getParameter("audio"). public void init() { context = this.applet. 200. here is the live applet example: Applet Example. String audioURL = this. public class AudioDemo extends Applet { private AudioClip clip. public void loop(): Causes the audio clip to replay continually. 84.*.com". null). public void stop(): Stops playing the audio clip. from the beginning.drawImage(image. 0. } Now let us call this applet as follows: <html> <title>The ImageDemo applet</title> <hr> <applet code="ImageDemo.awt. The audio file is not downloaded until an attempt is made to play the audio clip. To obtain an AudioClip object.*. private AppletContext context. including: • • • public void play(): Plays the audio clip one time. Playing Audio: An applet can play an audio file represented by the AudioClip interface in the java. you must invoke the getAudioClip() method of the Applet class. 35.} public void paint(Graphics g) { context. The AudioClip interface has three methods. 0.
getAudioClip(url). } try { URL url = new URL(this. } } public void stop() { if(clip != null) { clip.loop().wav at your PC to test the above example. } } } Now let us call this applet as follows: <html> <title>The ImageDemo applet</title> <hr> <applet code="ImageDemo.au". }catch(MalformedURLException e) { e.wav"> </applet> <hr> </html> You can use your test.class" width="0" height="0"> <param name="audio" value="test. context.stop().if(audioURL == null) { audioURL = "default. It begins with the character sequence /** and it ends with */. audioURL).printStackTrace(). } } public void start() { if(clip != null) { clip. The first two are the // and the /* */.showStatus("Could not load audio file!"). clip = context. The third type is called a documentation comment. Java Documentation Comments Java supports three types of comments. .getDocumentBase().
The javadoc Tags: The javadoc utility recognizes the following tags: Tag @author @deprecated Description Identifies the author of a class. but the link is displayed in a plain-text font. explanation Inherits a comment from the immediate superclass. {@link name text} Inserts an in-line link to another topic. You can then use the javadoc utility program to extract the information and put it into an HTML file. Documents a default serializable field. Specifies that a class or member is deprecated. Documents the data written by the writeObject( ) or writeExternal( ) methods Inherits a comment from the immediate surperclass. Inserts an in-line link to another topic. Specifies the path to the root directory of the current documentation Example @author description @deprecated description {@docRoot} Directory Path @exception {@inheritDoc} {@link} Identifies an exception thrown by a @exception exception-name method. Documents a method's return value. Inserts an in-line link to another topic. Specifies a link to another topic. Documents a method's parameter. Documentation comments make it convenient to document your programs. @param parameter-name explanation @return explanation @see anchor @serial description {@linkplain} @param @return @see @serial @serialData @serialData description .Documentation comments allow you to embed information about your program into the program itself.
which must be a static field. After that. @serialField name type description @since release The @throws tag has the same meaning as the @exception tag. . Same as @exception. if you have three @see tags. Multiple tags of the same type should be grouped together. Other HTML files can be generated. variable. Specifies the version of a class. States the release when a specific change was introduced. @version info Documentation Comment: After the beginning /**.2 */ What javadoc Outputs? The javadoc program takes as input your Java program's source file and outputs several HTML files that contain the program's documentation. which must be a static field. * @author Zara Ali * @version 1. Since different implementations of javadoc may work differently. Here is an example of a documentation comment for a class: /** * This class draws a bar chart. Displays the value of a constant. you will need to check the instructions that accompany your Java development system for details specific to your version. put them one after the other. Each @ tag must start at the beginning of a new line or follow an asterisk (*) that is at the start of a line. you can include one or more of the various @ tags. For example.@serialField @since @throws {@value} @version Documents an ObjectStreamField component. Java utility javadoc will also output an index and a hierarchy tree. Information about each class will be in its own HTML file. the first line or lines become the main description of your class. Displays the value of a constant. or method.
Example: Following is a sample program that uses documentation comments. Notice the way each comment immediately precedes the item that it describes. * @author Ayan Amhed * @version 1.in).2 */ public class SquareNum { /** * This method returns the square of num. /** * This class demonstrates documentation comments. * @exception IOException On input error. * @see IOException */ public double getNumber() throws IOException { InputStreamReader isr = new InputStreamReader(System.html. */ public double square(double num) { return num * num. * This is a multiline description. * @param args Unused.*. After being processed by javadoc. double val.readLine(). } /** * This method inputs a number from the user. } /** * This method demonstrates square(). * @exception IOException On input error. BufferedReader inData = new BufferedReader(isr). * @return Nothing. String str. System. You can use * as many lines as you like. return (new Double(str)).getNumber().out.out. import java. the documentation about the SquareNum class will be found in SquareNum. * @see IOException */ public static void main(String args[]) throws IOException { SquareNum ob = new SquareNum(). * @return The value input as a double. val = ob.doubleValue(). str = inData. System.println("Enter value to be squared: "). * @param num The value to be squared.square(val). .io. * @return num squared.println("Squared value is " + val). val = ob.
1 warning $ Java Useful References Java ....Quick Reference Guide What is Java? Java is: • • • • • • • • • Object Oriented Platform independent: Simple Secure Architectural. Building index for all classes...java file using javadoc utility as follows: $ javadoc SquareNum. Generating SquareNum.. Generating package-frame...java... Standard Doclet version 1.html.html.. Generating allclasses-noframe.html. Generating allclasses-frame..} } Now process above SquareNum.... Constructing Javadoc information. Generating constant-values.... Generating deprecated-list. Generating package-tree.html. Generating overview-tree..html.0_13 Building tree for all the packages and classes...@return tag cannot be used\ in method with void return type.html.html.html....java Loading source file SquareNum.. Building index for all the packages and classes.neutral Portable Robust Multi-threaded Interpreted ...5... Generating help-doc..html.html.css.. Generating package-summary.java:39: warning ...html. Generating index-all.html.... Generating stylesheet. SquareNum. Generating index.
s state is created by the values assigned to these instant variables. name.println("Hello World"). Java Basic Syntax: • • • • Object . barking. Class Names . An object is an instance of a class. breed as well as behaviors -wagging. Methods . data is manipulated and all the actions are executed. Instant Variables . An object.• • • High Performance Distributed Dynamic Java Environment Setup: Java SE is freely available from the link Download Java.Each object has its unique set of instant variables. public class MyFirstJavaProgram{ /* This is my first java program.A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.Java is case sensitive which means identifier Hello and hello would have different meaning in Java.Objects have states and behaviors. It is in methods where the logics are written. Example: A dog has states-color. You can refere to installation guide for a complete detail. * This will print 'Hello World' as the output */ public static void main(String []args){ System. it is very important to keep in mind the following points.A method is basically a behavior. So you download a version based on your operating system. eating. // prints Hello World } } About Java programs.For all class names the first letter should be in Upper Case. A class can contain many methods. • • Case Sensitivity . First Java Program: Let us look at a simple code that would print the words Hello World. Class .out. .
Most importantly identifiers are case sensitive. strictfp . variables and methods are called identifiers. then each inner word's first letter should be in Upper Case. private Non-access Modifiers : final. $salary. Examples of legal identifiers:age. public .Name of the program file should exactly match the class name. There are two categories of modifiers. If several words are used to form the name of the method. (if the file name and the class name do not match your program will not compile). Names used for classes. currency character ($) or an underscore (-).If several words are used to form a name of the class each inner words first letter should be in Upper Case. • Java Identifiers: All java components require names. __1_value Examples of illegal identifiers : 123abc. After the first character identifiers can have any combination of characters. Example : Assume 'MyFirstJavaProgram' is the class name. • Example public void myMethodName() Program File Name . abstract. A key word cannot be used as an identifier. -salary Java Modifiers: Like other languages it is possible to modify classes. In java there are several points to remember about identifiers.. methods etc by using modifiers.java program processing starts from the main() method which is a mandatory part of every java program.java' public static void main(String args[]) . protected. Then the file should be saved as 'MyFirstJavaProgram. When saving the file you should save it using the class name (Remember java is case sensitive) and append '. • • Access Modifiers : defualt.java' to the end of the name. _value. They are as follows: • • • • • • All identifiers should begin with a letter (A to Z or a to z ).All method names should start with a Lower Case letter. • Example class MyFirstJavaClass Method Names .
. Java Enums: Enums were introduced in java 5. LARGE } FreshJuiceSize size. medium and Large. For example if we consider an application for a fresh juice shop it would be possible to restrict the glass size to small. } } Note: enums can be declared as their own or inside a class.We will be looking into more details about modifiers in the next section. FreshJuiceSize. This would make sure that it would not allow anyone to order any size other than the small. construct and initialize in the upcoming chapters.MEDUIM . Java Variables: We would see following type of variables in Java: • • • Local Variables Class Variables (Static Variables) Instance Variables (Non static variables) Java Arrays: Arrays are objects that store multiple variables of the same type. } public class FreshJuiceTest{ public static void main(String args[]){ FreshJuice juice = new FreshJuice(). MEDUIM. With the use of enums it is possible to reduce the number of bugs in your code. We will look into how to declare. variables. However an Array itself is an object on the heap. Methods.size = FreshJuice. medium or large. The values in this enumerated list are called enums. juice. Example: class FreshJuice{ enum FreshJuiceSize{ SIZE. constructors can be defined inside enums as well.0. Enums restrict a variable to have one of only a few predefined values.
out. * This will print 'Hello World' as the output * This is an example of multi-line comments. } . These reserved words may not be used as constant or variable or any other identifier names. All characters available inside any comment are ignored by Java compiler. */ System. */ public static void main(String []args){ // This is an example of single line comment /* This is also an example of single line comment.println("Hello World"). public class MyFirstJavaProgram{ /* This is my first java program.Java Keywords: The following list shows the reserved words in Java.++.
} Data Types in Java There are two data types available in Java: 1. Class objects. Let us now look into detail about the eight primitive data types. Puppy etc. For example: . Primitive Data Types 2. • • • • • • • • byte short int long float double boolean char Reference Data Types: • • • • • Reference variables are created using defined constructors of the classes. Reference/Object Data Types Primitive Data Types: There are eight primitive data types supported by Java. Java Literals: A literal is a source code representation of a fixed value. Primitive data types are predefined by the language and named by a key word. These variables are declared to be of a specific type that cannot be changed. They are used to access objects. and various type of array variables come under reference data type. Example : Animal animal = new Animal("giraffe"). For example. They are represented directly in the code without any computation. Literals can be assigned to any primitive type variable. Default value of any reference variable is null. Employee. A reference variable can be used to refer to any object of the declared type or any compatible type.
2. Visible to the world (public). the default. They are: Notation \n \r \f \b \s \t \" \' \\ \ddd \uxxxx Character represented Newline (0x0a) Carriage return (0x0d) Formfeed (0x0c) Backspace (0x08) Space (0x20) tab Double quote Single quote backslash Octal character (ddd) Hexadecimal UNICODE character (xxxx) Java Access Modifiers: Java provides a number of access modifiers to set access levels for classes. Visible to the package. No modifiers are needed. variables. . The four access levels are: 1. Examples of string literals are: "Hello World" "two\nlines" "\"This is in quotes\"" Java language supports few special escape sequences for String and char literals as well. 3. Visible to the class only (private). 4. char a = 'A' String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Visible to the package and all subclasses (protected). methods and constructors.byte a = 68.
. != > (A != B) is true. (A > B) is not true. if yes then condition becomes true.Java Basic Operators: Java provides a rich set of operators to manipulate variables.gives 19 The Relational Operators: Operator == Description Checks if the value of two operands are equal or not.Adds values on either side of the operator Subtraction .B will give -10 A * B will give 200 B / A will give 2 % B % A will give 0 ++ -- B++ gives 21 B-. Checks if the value of two operands are equal or not.Increase the value of operand by 1 Decrement .Divides left hand operand by right hand operand and returns remainder Increment .Decrease the value of operand by 1 Example A + B will give 30 A . We can divide all the Java operators into the following groups: The Arithmetic Operators: Operator + * / Description Addition .Subtracts right hand operand from left hand operand Multiplication . if values are not equal then condition becomes true.Multiplies values on either side of the operator Division .Divides left hand operand by right hand operand Modulus . Checks if the value of left operand is Example (A == B) is not true.
if yes then condition becomes true. Checks if the value of left operand is greater than or equal to the value of right operand. The Bitwise Operators: Operator & | ^ Description Example Binary AND Operator copies a bit to (A & B) will give 12 which is 0000 the result if it exists in both operands. <= Checks if the value of left operand is less than or equal to the value of right (A <= B) is true. 0001 Binary Ones Complement Operator is (~A ) will give -60 which is 1100 unary and has the efect of 'flipping' 0011 bits. Binary Right Shift Operator. The left A << 2 will give 240 which is 1111 0000 ~ << >> A >> 2 will give 15 which is 1111 >>> A >>>2 will give 15 which is 0000 . The left operands value is moved left by the number of bits specified by the right operand. 1100 Binary OR Operator copies a bit if it exists in eather operand. Shift right zero fill operator. operand. >= (A >= B) is not true. if yes then condition becomes true. Binary Left Shift Operator. yes then condition becomes true. (A | B) will give 61 which is 0011 1101 Binary XOR Operator copies the bit if (A ^ B) will give 49 which is 0011 it is set in one operand but not both. < Checks if the value of left operand is less than the value of right operand.greater than the value of right operand. if yes then condition becomes true. if (A < B) is true. The left operands value is moved right by the number of bits specified by the right operand.
Called Logical NOT Operator. 1111 The Logical Operators: Operator && Description Example Called Logical AND operator.operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. If a condition is true then !(A && B) is true. It multiplies right Example C = A + B will assigne value of A + B into C += C += A is equivalent to C = C + A -= C -= A is equivalent to C = C . then condition becomes true. || ! The Assignment Operators: Operator = Description Simple assignment operator. It subtracts right operand from the left operand and assign the result to left operand Multiply AND assignment operator. Called Logical OR Operator. If any of the two operands are non zero then (A || B) is true. If both the operands are non zero then then (A && B) is false. Assigns values from right side operands to left side operand Add AND assignment operator. condition becomes true.A *= C *= A is equivalent to C = C * A . Logical NOT operator will make false. Use to reverses the logical state of its operand. It adds right operand to the left operand and assign the result to left operand Subtract AND assignment operator.
The operator checks whether the object is of a particular type(class type or interface type). The operator is written as : variable x = (expression) ? value if true : value if false instanceOf Operator: This operator is used only for object reference variables. The goal of the operator is to decide which value should be assigned to the variable. It takes modulus using two operands and assign the result to left operand Left shift AND assignment operator Right shift AND assignment operator Bitwise AND assignment operator bitwise exclusive OR and assignment operator bitwise inclusive OR and assignment operator /= %= C %= A is equivalent to C = C % A <<= >>= &= ^= |=. Conditional Operator ( ? : ): Conditional operator is also known as the ternary operator. instanceOf operator is wriiten as: . This operator consists of three operands and is used to evaluate boolean expressions.operand with the left operand and assign the result to left operand Divide AND assignment operator. It divides left operand C /= A is equivalent to C = C / A with the right operand and assign the result to left operand Modulus AND assignment operator.
( Object reference variable ) instanceOf (class/interface type) Precedence of Java Operators: Category Postfix Unary Multiplicative Additive Shift Relational Equality Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Assignment Comma Operator () [] .! ~ */% +>> >>> << > >= < <= == != & ^ | && || ?: = += -= *= /= %= >>= <<= &= ^= |= . (dot operator) ++ . Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left Left to right The while Loop: A while loop is a control structure that allows you to repeat a task a certain number of times.. Syntax: The syntax of a while loop is: while(Boolean_expression) { .
A for loop is useful when you know how many times a task is to be repeated. The for Loop: A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. except that a do. Syntax: The syntax of enhanced for loop is: for(declaration : expression) { ....while loop is: do { //Statements }while(Boolean_expression).. Boolean_expression. This is mainly used for Arrays..//Statements } The do.while loop is guaranteed to execute at least one time. Syntax: The syntax of a do. Syntax: The syntax of a for loop is: for(initialization.while Loop: A do. update) { //Statements } Enhanced for loop in Java: As of java 5 the enhanced for loop was introduced...while loop is similar to a while loop..
The break keyword must be used inside any loop or a switch statement. In a while loop or do/while loop. The continue Keyword: The continue keyword can be used in any of the loop control structures.. the continue keyword causes flow of control to immediately jump to the update statement.. • • In a for loop.//Statements } The break Keyword: The break keyword is used to stop the entire loop. Syntax: The syntax of a continue is a single statement inside any loop: continue. The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block. Syntax: The syntax of an if statement is: if(Boolean_expression) { //Statements will execute if the Boolean expression is true } The if. flow of control immediately jumps to the Boolean expression. The if Statement: An if statement consists of a Boolean expression followed by one or more statements.else Statement: . It causes the loop to immediately jump to the next iteration of the loop.
An if can have zero to many else if's and they must come before the else. When using if ....else is: if(Boolean_expression){ //Executes when the Boolean expression is true }else{ //Executes when the Boolean expression is false } The if.. Once an else if succeeds.... • • • An if can have zero or one else's and it must come after any else if's...else statement.An if statement can be followed by an optional else statement... none of he remaining else if's or else's will be tested.... else if . Syntax: The syntax of a if. Syntax: The syntax for a nested if.else if statement. else statements there are few points to keep in mind. } Nested if..else is as follows: . which is very usefull to test various conditions using single if. which executes when the Boolean expression is false..else if.else Statement: An if statement can be followed by an optional else if.else Statement: It is always legal to nest if-else statements..
println method. the system actually executes several statements in order to display a message on the console. which is optional. //optional //You can have any number of case statements. . When you call the System. Each value is called a case. and the variable being switched on is checked for each case. for example. Here are all the parts of a method: • Modifiers: The modifier. //optional case value : //Statements break.if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true } } The switch Statement: A switch statement allows a variable to be tested for equality against a list of values. In general. default : //Optional //Statements } Java Methods: A Java method is a collection of statements that are grouped together to perform an operation. tells the compiler how to call the method. a method has the following syntax: modifier returnValueType methodName(list of parameters) { // Method body. } A method definition consists of a method header and a method body. This defines the access type of the method. Syntax: The syntax of enhanced for loop is: switch(expression){ case value : //Statements break.out.
Instance . The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. An object is an instance of a class. Instance variables are variables within a class but outside any method. Example: A dog has states-color. void barking(){ } void hungry(){ } void sleeping(){ } } A class can contain any of the following variable types. breed as well as behaviors -wagging. variables defined inside methods. barking. int age. Method Body: The method body contains a collection of statements that define what the method does. The parameter list refers to the type. eating. Parameters are optional. name. A sample of a class is given below: public class Dog{ String breed. a method may contain no parameters. order. Parameters: A parameter is like a placeholder. String color. The method name and the parameter list together constitute the method signature. In this case.Objects have states and behaviors. These variables are instantiated when the class is loaded. Class .• • • • Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. that is. you pass a value to the parameter. Some methods perform the desired operations without returning a value. This value is referred to as actual parameter or argument. Instance variables . Method Name: This is the actual name of the method.A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support. and number of the parameters of a method. constructors or blocks are called local variables. Java Classes & Objects: • • Object . When a method is invoked. the returnValueType is the keyword void. • • Local variables .
outside any method.• variables can be accessed from inside any method. constructor or blocks of that particular class. . Code within a try/catch block is referred to as protected code. Class variables are variables declared with in a class. with the static keyword. A try/catch block is placed around the code that might generate an exception. The syntax for multiple catch blocks looks like the following: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block } The throws/throw Keywords: If a method does not handle a checked exception. Class variables . and the syntax for using try/catch looks like the following: try { //Protected code }catch(ExceptionName e1) { //Catch block } Multiple catch Blocks: A try block can be followed by multiple catch blocks. Exceptions Handling: A method catches an exception using a combination of the try and catch keywords. The throws keyword appears at the end of a method's signature. the method must declare it using the throws keyword.
either a newly instantiated one or an exception that you just caught. . Using a finally block allows you to run any cleanup-type statements that you want to execute.You can throw an exception. by using the throw keyword. Try to understand the different in throws and throw keywords. no matter what happens in the protected code. } For a complete detail of the Java Programming language. whether or not an exception has occurred. A finally block appears at the end of the catch blocks and has the following syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. The finally Keyword The finally keyword is used to create a block of code that follows a try block. it is recommended to go through our simple Java Tutorial. A finally block of code always executes.
This action might not be possible to undo. Are you sure you want to continue? | https://www.scribd.com/doc/48059147/41804049-Java-Tutorial | CC-MAIN-2016-07 | refinedweb | 40,667 | 60.72 |
28 December 2011 20:39 [Source: ICIS news]
LONDON (ICIS)--The French government promised on Wednesday to help independent refiner Petroplus in its negotiations with banks.
The announcement came after Petroplus said this week that banks had frozen some $1bn (€770m) in “critical” credit lines, raising the spectre that the company may not be able to buy crude oil to keep its five refineries in ?xml:namespace>
French economics and industry ministers, François Baroin and Eric Besson, said in a joint statement while Petroplus is based in
"Even though Petroplus is a Swiss company and the banks are mainly foreign banks,
The participating French banks had expressed a willingness to help fund Petroplus as part of an overall deal to be agreed by all of the company's lenders, he said.
In their statement, the ministers added that the French and the overall European refining sector needed to take steps to strengthen their competitiveness.
In addition to Petit-Couronne, Petroplus owns and operates refineries at Coryton
Petroplus' refineries have a combined throughput capacity of about 667,000 bbl/day.
For the nine months ended 30 September 2011, Petroplus reported a net loss of $413m, compared with a net loss of $250m in the same period in 2010.
Petroplus' shares were down 10.8% to Swiss francs (Swfr) 1.65 on
($1 = €0.77)
Paul Hodges studies key influences shaping the chemical industry in | http://www.icis.com/Articles/2011/12/28/9519402/french-government-pledges-help-for-troubled-swiss-refiner-petroplus.html | CC-MAIN-2014-42 | refinedweb | 233 | 57.3 |
Getting Started with Developer Studio Tools
Introduction to Using Red Hat Developer Studio Tools
Abstract
Chapter.
Chapter 2. Configuring Maven Basics
In the context of application development, Maven provides a standardized build system for projects. One of the main benefits of using Maven with your project is that it facilitates fetching dependencies from one or more repositories. This article serves as an introduction to using Maven with the IDE.
Root Maven projects can serve as aggregators for multiple Maven modules, also known as sub-projects. For each module that is part of a maven project, a <module> entry is added to the project’s pom.xml file. A pom.xml that contains <module> entries is often referred to as an aggregator pom.
When modules are included into a project it is possible to execute Maven goals across all of the modules by a single command issued from the parent project directory.
The provided instructions pertain to the creation of a parent+module project structure. If you prefer to create a simple project, simply start with an archetype or don’t use the pom packaging in step 2.i of the Section 2.1, “Creating a New Maven Project” section.
2.1. Creating a New Maven Project
Use the following instructions to create the parent project of a multi-module Maven project. The instructions provided ensure that the packaging option is set to
pom, which is a requirement for multi-module Maven projects. Alternately, to create a standalone Maven project instead, set the packaging option to an option other than
pom.
To create a new Maven project:
- In the workspace, click File > New > Other.
- In the Filter field, type maven and then click Maven Project from the search results.
- Click Next to continue.
Enter the initial project details:
- Click the Create a simple project (skip archetype selection) check box. If this check box is selected, the Select an Archetype step of the wizard is skipped and the project type is set to pom, which is required to create a Maven Module based on this Maven project. Alternately, to create a standalone project, clear the Create a simple project (skip archetype selection) check box and follow the instructions in the wizard.
- Ensure that the Use default Workspace location check box is clear and specify a non-default location for your workspace files using the Browse button. Using a non-default workspace location is recommended because this allows other tools to access the workspace location easily.
- Optional, click the Add project(s) to working set check box to add the newly created projects to a working set.
Optional, project names in the workspace by prepending or appending the group ID or SCM branch names to the default artifact ID.
Figure 2.1. Create a New Maven Project
- When the configuration is complete, click Next to continue.
To configure the project details:
- In the Group Id field, enter the desired group ID, which is similar to an organization namespace (for example, com.company.businessunit.project).
- In the Artifact Id field, enter the desired artifact ID value, which is the name for your project. This value must not include any spaces and the only special characters allowed are periods ('.'), underscores ('_'), and dashes ('-').
- In the Version list, click 0.0.1-SNAPSHOT or a similar value. For details about the appropriate version build numbers, see Project Versions
- In the Packaging list, click pom.
- Optionally, in the Name field, add a name for your project.
Optionally, in the Description field, add a description for your project.
Figure 2.2. Configure Project Details
- Click Finish to conclude the new Maven project creation. Your new Maven project is created and appears in the Project Explorer view.
2.2. Creating a New Maven Module
Each Maven project with a packaging pom can include multiple Maven modules. Follow the instructions here to create your first Maven module.
Prerequisites
- You must have an existing Maven project available with the packaging type pom. See Section 2.1, “Creating a New Maven Project” for instructions to create a new Maven project.
To create a new Maven module:
- In the Project Explorer view, right-click the recently created pom project and click New > Project.
- In the New Project wizard, expand Maven and click Maven Module.
- Click Next to continue.
To enter the initial module details:
- Ensure that the Create a simple project (skip archetype selection) check box is clear. If this check box is clicked, the Select an Archetype step of the wizard is skipped.
- In the Module Name field, enter the desired module name. This value corresponds to the Maven project’s Project ID.
- Use the Browse button to locate the desired parent project and select it.
- Optionally, clikc the Add project(s) to working set check box to add the newly created projects to a working set.
Optionally, projects names in the workspace by prepending or appending the group ID or SCM branch names to the default artifact ID.
Figure 2.3. Set the Module Name and Parent
- When the configuration is complete, click Next to continue.
To enter the module archetype information:
- Ensure that the Show the last version of Archetype only check box is clicked. This ensures that only the latest version of each archetype displays.
Select an archetype based on the purpose of the project you are creating. Use the keyword maven-archetype-quickstart in the Filter field to locate a sample Maven project archetype.
Figure 2.4. Select a Module Archetype
- Click Next to continue.
To enter the module details:
- In the Group Id field, add the same group ID value that was used for the Maven project.
- In the Version field, add the desired version number. For details about the appropriate version build numbers, see Project Versions
The Artefact Id and Package fields are automatically populated based on the parent project details. Click Finish to conclude setting up the Maven module.
Figure 2.5. Configure the Module Archetype Parameters
Optionally, to change the settings for the created Maven module, expand the module name in the Project Explorer view and double click pom.xml from the expanded list. An Overview tab appears for you to chnage the settings if you wish to.
Figure 2.6. Change the Module Settings from the Overview View
Your new Maven module is created and appears in the Project Explorer view. Additionally, a hierarchical view of the nested projects is now available in the Project Explorer view as well (see Nested/Hierarchical view of projects).
2.3. Adding Maven Support to an Existing Non-Maven Project
For an existing application that was not created with Maven support, use the following instructions to add Maven support to the non-Maven project:
- In the Project Explorer view, right-click the project name and click Configure > Convert to Maven Project.
To configure details for the new
pomfile:
- The basic fields for the new
pomfile are prepopulated based on the project details. If required, edit the existing values:
- Optionally, in the Name field, add a name for the new project.
Optionally, in the Description field, add a brief description for the project.
Figure 2.7. Create a New Pom Descriptor
- Click Finish to finalize the pom information.
- If the project references java dependencies, a wizard appears displaying all these dependencies and a green check mark when each dependency is identified. Learn more about dependency identification in the Troubleshooting section.
Check the Delete original references from project check box to avoid retaining duplicate or stale dependencies in your project.
Figure 2.8. Identify Maven Dependencies
- Click Finish when all dependencies are converted. The existing project is now configured for Maven support.
2.4. Troubleshooting
2.4.1. Unidentifiable Dependency
Figure 2.9. Unidentifiable Dependency
Issue:
Either:
- The jar file is corrupted/invalid.
- The jar file is valid but does not contain any metadata used for identification.
Resolution:
- Ensure that jar exists as a Maven artifact. If needed, you can install it to your local repository and then click .
- Double-click the dependency, or clickand set the expected maven coordinates.
2.4.2. Some selected dependencies can not be resolved. Click here to configure repositories in your settings.xml.
Figure 2.10. Dependencies Can Not Be Resolved Error
Issue: This error displays when a dependency can be identified (that is, whether it contains the pom properties or other metadata) but the dependency is not available in any repository defined in your settings.xml file.
Resolution: Click the here link in the error message and compare the old and new settings for the dependency and add a new and correct repository. Users may choose to use one of the predefined repositories from Red Hat.
Additional Resources
The wizard used to convert a non-Maven project to a Maven project attempts to identify all the project’s classpath entries and their equivalent Maven dependencies. From the list of identified dependencies, users can select which ones will be added to the generated Maven
pom.xmlfile. When identifying dependencies, one of several strategies may be used:
- Checking if the jar contains the relevant maven metadata.
- Identify the dependency using the Nexus indexer.
- Identify the dependency using the JBoss Nexus instance REST API (if we are online) via a SHA1 search.
- Identify the dependency using the
search.maven.orgREST API (if we are online) via a SHA1 search.
- All unchecked dependencies will be ignored and are not added to the generated
pom.xml. However, some of these can be added as transitive dependencies to your project. For instance, if you add
jsp-apibut remove
servlet-api, the latter appears in the project classpath, as it is a dependency of
jsp-api.
- You can double-click on a dependency from a list (or click the
Editbutton) to edit its Maven coordinates or scope. Selecting several dependencies (ctrl+click) and clicking the
Editbutton allows batch editing of their scope.
Chapter 3. Developing First Applications with Developer Studio Tools
3.1. Configuring Developer Studio for use with JBoss EAP and JBoss Web Framework Kit
This article provides details for new and existing users who need to configure a fresh install of the IDE or upgrade the versions of Red Hat JBoss Enterprise Application Platform or JBoss Web Framework Kit in use.
The IDE supports application development and deployment with JBoss EAP and JBoss Web Framework Kit only after you configure the IDE for use with JBoss EAP and JBoss Web Framework Kit. This configuration is essential for using the enterprise versions of the example Maven projects provided in Red Hat Central. These projects are intended for deployment to JBoss EAP and necessitate IDE access to the JBoss EAP and JBoss Web Framework Kit Maven repositories.
3.1.1. Setting up JBoss EAP
To set up JBoss EAP for use in the IDE, you must direct the IDE to the local or remote runtime servers. This establishes a communication channel between the IDE and the JBoss EAP server for efficient deployment and server management workflows.
3.1.1.1. Downloading, Installing, and Setting Up JBoss EAP from within the IDE
If you have the IDE already installed but not JBoss EAP, you can download, install, and set up JBoss EAP from within the IDE. With this option, you can choose from a range of supported JBoss EAP versions; for details of supported JBoss EAP versions, see.
To download, install, and set up JBoss EAP from within the IDE:
- Start the IDE.
- Click
Window>
Preferences, expand
JBoss Tools, and then click
JBoss Runtime Detection.
- In the
Pathspane, click
Download.
In the
Download Runtimeswindow, from the
Download Runtimestable select the JBoss EAP version that you want to download and click
Next.Note
For JBoss EAP 6.1.x and later, continue to follow the steps given here. For JBoss EAP 6.0.x and earlier, follow the on-screen instructions for downloading JBoss EAP from the Red Hat Customer Portal and after JBoss EAP is installed continue to Section 3.1.1.2, “Using Runtime Detection to Set Up JBoss EAP from within the IDE”.
Figure 3.1. Download Runtimes Window Listing Available JBoss EAP Versions
- In the
JBoss.org Credentialswindow, enter your credentials and click
- In the
Runtime JBoss EAP_versionwindow, read the terms and conditions, and then click
I accept the terms of the license agreementand then click
Next. Note that if you have previously accepted the terms and conditions in the IDE or through the jboss.org website, this window is skipped.
- In the
Download Runtimewindow, in the
Install Folderfield, click
Browseand choose a location in which to install JBoss EAP and click
Finish. The
Download 'JBoss EAP 1window shows the progress of the downlaod.
- Click
Apply and Closeto close the
Preferenceswindow. The server is listed in the
Serversview in stopped mode.
3.1.1.2. Using Runtime Detection to Set Up JBoss EAP from within the IDE
If the IDE and JBoss EAP are already installed, you can use runtime detection to set up JBoss EAP from within the IDE. The runtime detection feature automatically identifies the JBoss EAP instance installed on your local system and generates a corresponding default server setup for use in the IDE. This feature makes getting started with a default JBoss EAP server very quick.
Specific JBoss EAP versions are supported by each IDE release; for details of supported JBoss EAP versions, see.
To use runtime detection to set up JBoss EAP for use in the IDE:
- Start the IDE.
- Click
Window→
Preferences, expand
JBoss Tools, and then select
JBoss Runtime Detection.
- Click
Add.
- Navigate to
path/to/jboss-eapand click
OK. JBoss Server Tools recursively scans the path searching for installed servers and displays a list of those it finds.
Ensure the
jboss-eap-versioncheck box is selected, where version denotes the JBoss EAP version, and click
OK.
Figure 3.2. Selecting a Runtime
- Click
Apply and Closeto close the
Preferenceswindow. The server is listed in the
Serversview in stopped mode.
3.1.2. Configuring Maven for JBoss EAP and JBoss Web Framework Kit Maven Repositories
To configure Maven to use the JBoss EAP and JBoss Web Framework Kit Maven repositories when working inside the IDE, you must ensure that the IDE knows the location of your Maven configuration
settings.xml file and that the necessary profiles for the JBoss EAP and JBoss Web Framework Kit Maven repositories are contained in that file. This ensures that Maven knows where to search for project dependencies when it is called to build Maven projects from within the IDE.
3.1.2.1. Specifying Maven settings.xml File Location
If you have multiple Maven
settings.xml files or you are using a shared
settings.xml file, then this file may not be in the default location expected by the IDE. In this case, you must inform the IDE of the file location.
To specify the Maven settings.xml file location:
- Start the IDE.
- Click
Window→
Preferences, expand
Maven, and then click
User Settings.
- For the
User Settingsfield, click
Browseand locate the
settings.xmlfile.
- Click
Update Settings.
- Click
Applyand then click
OK.
3.1.3. Using JBoss EAP and JBoss Web Framework Kit Maven Repositories
You can either download the JBoss EAP and JBoss Web Framework Kit Maven repositories from the Red Hat Customer Portal or use the online Maven repository located at.
3.1.3.1. Using the Offline Maven Repositories
If you have not previously used these versions of JBoss EAP and JBoss Web Framework Kit, you must configure your Maven
settings.xml file to use the associated product Maven repositories. You can manually edit your
settings.xml file in a text editor or use the Developer Studio Maven integration feature to automatically detect the JBoss repositories and appropriately edit your
settings.xml file.
The JBoss EAP and JBoss Web Framework Kit Maven repositories must be already obtained from the Red Hat Customer Portal and located on a system that you can access.
To specify the JBoss EAP and JBoss Web Framework Kit Maven repositories locations using the IDE:
- Start the IDE.
- Click
Window→
Preferences, expand
JBoss Tools, and then click
JBoss Maven Integration.
- Click
Configure Maven Repositories.
- Click
Add Repository.
- Click
Recognize JBoss Maven Enterprise Repositories.
- Navigate to
path/to/jboss-eap-maven-repositoryand click
OK. JBoss Maven Tools recursively scans the path searching for a Maven repository.
Modify the information in the
IDand
Namefields as desired, ensure the
Active by defaultcheck box is selected, and then click
OK.
Figure 3.3. Details of the Selected Maven Repository
- Click
Add Repository.
- Click
Recognize JBoss Maven Enterprise Repositories.
- Navigate to
path/to/jboss-wfk-maven-repositoryand click
OK. JBoss Maven Tools recursively scans the path searching for a Maven repository.
- Modify the information in the
IDand
Namefields as desired, ensure the
Active by defaultcheck box is selected, and then click
OK.
- Click
Finishand at the prompt asking if you are sure you want to update the Maven configuration file click
Yes. If the specified configuration file does not exist, JBoss Maven Tools creates it.
- Click
Applyand click
OKto close the
Preferenceswindow.
3.1.3.2. Using the Online Maven Repositories
Adding the online repository to the IDE, adds to your
settings.xml , which takes care of all the dependencies.
To use the online Maven repositories:
- Start the IDE.
- Click
Window→
Preferences, expand
JBoss Tools, and then click
JBoss Maven Integration.
- Click
Configure Maven Repositories.
- Click
Add Repository.
In the
Profile IDdrop-down list, select
redhat-ga-repository.
Figure 3.4. Add a Maven Repository
- Click
OK.
- In the
Configure Maven Repositorieswindow, click
Finish.
- Click
Applyand then click
OKto close the
Preferenceswindow.
3.2. Creating and Importing Node.js Applications
Node.js is an event-based, asynchronous I/O framework and is used to develop applications that run JavaScript on the client and server side. This allows the application to re-use parts of the code and to avoid switching contexts. Node.js is commonly used to create applications such as static file servers, messaging middleware, HTML5 game servers, web application framework, and others.
Developer Studio supports node.js application development using the npm package installer and offers a built-in debugging tool to identify and fix issues with applications.
Prerequisites
Ensure that the following prerequisites are met to start developing node.js applications in Developer Studio:
- Install npm. On Red Hat Enterprise Linux and Fedora, use the
sudo dnf install npmcommand. See the npm documentation () for installation information about other operating systems.
- Install Developer Studio. You are now ready to start developing Node.js applications with Developer Studio.
3.2.1. Creating a new JavaScript Application
To create a new JavaScript project and application in Developer Studio:
To create a new JavaScript project:
- Click JavaScript in the search text box.→ → and type
- Select JavaScript Project and click Next.
- In the Project Name field, add a name for your new project.
- Ensure that the rest of the fields, which are set to the default settings, are as required, and then click Finish to create the new project.
- If asked to view the JavaScript perspective, click Yes. Your new project is listed in the
Project Explorerview.
To interactively create a
package.jsonfile:
- Click→ → and then type
npmin the search box.
- From the search results, click npm Init.
- Set the Base directory to your JavaScript project folder in your Developer Studio workspace.
- Optionally, clear the
Use default configurationcheck box to supply non-default values for these fields.
Click Finish to continue with the default values for the
package.jsonfile or to continue after changing the default values.
Figure 3.5. Generate a New package.json File
The new
package.jsonfile is generated and displayed for editing. If required, manually edit the file in the displayed pane and save the changes.
Figure 3.6. Manually Edit the Generated package.json File
Manually edit the
package.jsonfile to add dependencies. Dependencies are modules which provide extended functionality, such as libraries and frameworks. See the following screen capture for an example of the required format for dependencies and developer dependencies.
Figure 3.7. Adding Dependencies to the package.json File
For further details about dependencies, see the NPM documentation:
Create a new JavaScript file with the required business logic:
- In the
Project Explorerview, right-click the name of your project, and select → .
- In the dialog box, add a name for the new file, for example
index.js, and click Finish to create the new file.
- The new file displays for editing in a new tab. Add the required business logic to the your JavaScript files and save the changes.
- Run the project files by right-clicking the
index.jsfile in your project and select → . The
Consoleview appears and displays details about the application as it runs, or errors if it is unable to run the application. You have created a new JavaScript project and application.
3.2.2. Importing an Existing JavaScript Project
You can import an existing JavaScript project directly into Developer Studio and then make changes and run the project as follows:
- Click→ .
- In the
Importdialog box, expand the General option.
- Click Existing Projects into Workspace and then click Next.
In the
Import Projectsdialog box:
- Click either the
Select root directoryor
Select archive fileoptions based on your project format.
- Click Browse to add the path to the project root directory or archive file.
- In the
Projectsbox, select one or more projects to import into the workspace.
- If required, click the
Search for nested projectsoption to locate nested projects in the root directory or archive file.
- Click the
Copy projects into workspaceoption to save a copy of the imported project in the workspace directory specified for Developer Studio.
- If required, select the
Add project to working setscheckbox and add the details for a new or existing working set.
- Click Finish to add the project to the workspace. The
Project Explorerview now contains your imported project.
- If required, expand the project in the
Project Explorerview and either double-click the project files to edit them, or right-click and select → to add a new JavaScript file for your project.
- Run the project files by right-clicking the
index.jsfile in your project and click → . The
Consoleview appears and displays details about the application as it runs, or errors if it is unable to run the application. You have imported an existing JavaScript project into Developer Studio.
3.2.3. Debugging a Node.js Application
After either creating a new Node.js project or importing an existing one and then running the project, some errors may appear. Developer Studio includes a debugger to help identify and resolve these issues.
To use the debugging feature:
Start the debugger for your project:
- In the
Project Explorerview, expand your project.
- Right-click the
index.jsfile for your project and click → .
- Select the
Remember my decisioncheck box in the dialog box to apply your selection to subsequent perspective shifts and then click Yes or No to continue.
Review the elements of your project’s JavaScript files to locate errors in one of two ways:
- Expand any variable listed in the
Variablestab to view additional objects and edit the details for each item.
- Hover the mouse cursor over any variables in the
index.jstab to view and edit its property details.
Make changes to the files to address the errors:
- Edit the
index.jsfile in the appropriate view.
- Save the changes. The
Consoleview runs the updated file and displays changes.
After debugging the errors, use the Resume, Suspend, and Terminate buttons (
) as follows to test your changes:
- The Resume button (green triangle) continues running the project files.
- The Suspend button (two yellow rectangles) temporarily stops running the project files to allow users to make changes.
- The Terminate button (red square) ends the running of the project files.
- Repeat steps 4 through 6 as necessary to locate and fix errors found by the debugger.
- When debugging is concluded, click→ → and select
Project Explorerfrom the options. This displays the list of projects again. You have debugged your application and returned to the
Project Explorerview.
3.3. Developing Applications Using the Forge Tool
Developer Studio offers Forge Tools for developing Java EE applications and to extend the IDE functionality in Eclipse. Start developing Java EE applications using either the Forge context menu or the command line from the IDE.
3.3.1. Creating a Forge Project
After you have created a Forge project you can set up persistence, add entities and fields, and create scaffold for the project.
To create a new project:
- Press Ctrl+4 to start Forge and open the JBoss Forge context menu.
- Click Project:New to open the Create a new project window.
In the Create a new project window:
- In the Project name field, type a project name.
- In the Top level package field, type {com.example} as the top package.
- In the Project location field, enter a target location for the Forge project.
- In the Stack list, click Java EE 7.
- Click Finish.
Figure 3.8. Create a New Forge Project
The project is listed in the Project Explorer view.
3.3.2. Setting up Persistence
Setting up the JPA prerequisites, creates the persistence.xml file in the project and adds the required dependencies to the pom.xml file.
While creating the JPA entity, the Forge console automatically detects any prerequisites that must be set up and prompts you to create those at runtime.
To set up persistence:
- Press Ctrl+4 to open the JBoss Forge context menu.
- Click JPA: New Entity. The window is populated with default values.
- Click Next to continue using the default values or edit the fields to change the values.
- In the Configure your connection settings window, ensure that the fields display the appropriate values and then click Next.
In the Create a new JPA entity window:
- The Package Name field shows the system defined name of the package, example: {your_Forge_project_name}.model. Edit the package name if desired.
- In the Type Name field, type a name for the new entity. Example: Customer.
- Click Finish. The new entity appears in the editor and is also listed in the Project Explorer view with the name: .java.
Figure 3.9. .java Displayed in the Editor
3.3.3. Adding Fields to the Entity
To add fields to the entity:
- Press Ctrl+4 to open the JBoss Forge context menu.
- Click JPA: New Field.
In the Create a new field window:
- In the Target Entity field, select {package_name.model.entity}.
- In the Field Name field, type FirstName.
Click Finish.
Figure 3.10. Add Field to the Entity
- Repeat steps 1 through 4 to add more fields to the entity.
The fields are added to the
Customer.java file.
3.3.4. Creating a Scaffold
Scaffolding is automatic code generation by a program, using available information, usually a database to generate a basic CRUD (create, read, update, delete) admin interface. The
Scaffold Generate command is used to create the scaffold.
To create the scaffold:
- Press Ctrl+4 to open the JBoss Forge context menu.
- Click Scaffold Generate.
- In the Scaffold Type list, click Angular JS and then click Next.
- If your project is not configured to use all the technologies that you want to use, Forge prompts you to set up the dependencies. Click Next.
In the Select JPA entities window:
- Click the check box in the Targets field.
- Click the Generate REST resources check box.
- Click Finish.
Figure 3.11. Select JPA Entities to Create the Scaffold
The entities are created and listed in the Project Explorer view.
3.3.5. Running and Testing the Application
In this example we use the JBoss EAP server to run the application.
To run the application:
- In the Project Explorer view, right-click the application and click Run As > Run on Server. Alternatively, drag and drop the application from the Project Explorer view to the JBoss EAP 1 server in the Servers view. The application opens in the default browser.
- Click Customers and then click Create to create a new customer.
- In the FirstName and the LastName fields, enter the first and last names and click Save. The customer is added to the application.
- Optionally, use the Search for Customers section to search for customers by their first and/or last names.
3.3.6. Creating Extensions or Add-ons
The add-ons/extensions run inside the IDE. After adding commands and features to the add-on, no further changes are required for the extensions or add-ons to run in another IDE.
Prerequisites
- Sentence or a bulleted list of pre-requisites that must be in place or done before the user starts this task.
- Delete section title and bullets if the task has no required pre-requisites.
- Text can be a link to a pre-requisite task that the user must do before starting this task.
To create an add-on:
- Press Ctrl+4 to open the JBoss Forge context menu.
- Click Project:New.
In the Create a new project window:
- In the Project name field, type a name for the add-on (example_addon, in this case).
- In the Project type list, click Forge Addon (JAR).
- Click Next.
- In the Furnace Addon Setup window, Depend on these addons section, Forge automatically selects the prerequisites. Review the dependencies and click Finish. The setting up of these dependencies may take some time to complete. The add-on is listed in the Project Explorer view.
- Press Ctrl+4 to open the Forge context menu.
- Select Java: New Class to open the Java: New Class window.
- In the Type Name field, type CustomCommand and click Finish. The
CustomCommand.javafile opens in the editor.
To change this Java class into a Forge command:
- Press Ctrl+4 to open the Forge context menu.
- Select Addon: New UI Command to open the Generates a UICommand implementation window.
In the Generates a UICommand implementation window:
- In the Type Name field, type CustomCommand.
- In the Command name field, type custom.
Click Finish.
Figure 3.12. Add a Command
The command is listed in the
CustomerCommand.javafile.
- In the Project Explorer view, click the
CustomerCommand.javafile to select the file.
- Press Ctrl+4 to open the Forge context menu.
- Select Build and Install an Addon to open the Build and install a Forge addon window. The Project directory field, by deafult, shows the path to the addon.
- Click Finish to install the add-on into the IDE.
To execute the installed command:
- Press Ctrl+4 to open the Forge context menu.
- Select custom.
Add parameters to the method in order to add user input to the command. Copy and paste the following command in the
CustomCommand.javafile and save the file.
package org.example_addon.commands; import org.jboss.forge.addon.configuration.Configuration; import org.jboss.forge.addon.resource.URLResource; import org.jboss.forge.addon.ui.command.AbstractUICommand; import org.jboss.forge.addon.ui.context.UIBuilder; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.addon.ui.context.UIExecutionContext; import org.jboss.forge.addon.ui.input.UIInput; import org.jboss.forge.addon.ui.metadata.UICommandMetadata; import org.jboss.forge.addon.ui.metadata.WithAttributes; import org.jboss.forge.addon.ui.util.Metadata; import org.jboss.forge.addon.ui.util.Categories; import org.jboss.forge.addon.ui.result.Result; import org.jboss.forge.addon.ui.result.Results; import java.lang.Override; import java.lang.Exception; import javax.inject.Inject; public class CustomCommand extends AbstractUICommand { @Inject @WithAttributes(label = "JIRA URL", required = true) private UIInput<URLResource> url; @Inject private Configuration config; @Override public UICommandMetadata getMetadata(UIContext context) { return Metadata.forCommand(getClass()) .name("JIRA: Setup") .description("Setup the JIRA Addon") .category(Categories.create("JIRA", "Setup")); } @Override public void initializeUI(UIBuilder builder) throws Exception { builder.add(url); } @Override public Result execute(UIExecutionContext context) { String targetUrl = url.getValue().getFullyQualifiedName(); Configuration subset = config.subset("jira"); subset.setProperty("url", targetUrl); return Results.success("JIRA URL set to: "+targetUrl); } }
To rebuild and install:
- In the Project Explorer view, click the created add-on (example_addon, in this case).
- Press Ctrl+4 to open the Forge context menu.
- Select Build and Install an Addon. The Project directory field, by deafult, shows the path to the addon.
- Click Finish to install the add-on into the IDE.
- Press Ctrl+4 to open the Forge context menu.
- Click JIRA: Setup.
Figure 3.13. Add-on Listed in the Forge Context Menu
The add-on is created and listed in the Forge context menu.
Additional Resources
- You can launch the Forge Console by clicking Window > Show view > Forge Console. The Forge Console view opens in an inactive state.
- You can start JBoss Forge by clicking the Start {JBoss Forge_version} button
).
- To link the Forge Console output with the open editor, click the Link with Editor button (
).
3.4. Developing Applications Using the Hibernate Tools
Hibernate Tools is a collection of tools for projects related to Hibernate version 5 and earlier. The tools provide Eclipse plugins for reverse engineering, code generation, visualization and interaction with Hibernate.
Prerequisites
Connect to the sakila-h2 databass:
- Download the sakila-h2 database from the h2 version of the Sakila database.
- On the terminal, navigate to the directory where you have saved the
sakila-h2.jarfile and run the following command to start the database:
$ ./runh2.sh.
3.4.1. Creating a JPA Project
To create a JPA project and connect to the database:
- In the workspace, click File > New > Other and then search for JPA Project and double-click it to open the New JPA Project wizard.
In the New JPA Project wizard:
- In the Project name field, type a name for the project.
- In the Target runtime field, click a runtime server that you wish to use.
- In the JPA version list, click 2.1.
Click Next.
Figure 3.14. Create a New JPA Project
- In the New JPA Project - Java window, select the source folder on the build path and click Next.
- In the JPA Facet window, click Add connection.
In the New Connection Profile window:
- Click Generic JDBC.
- In the Name field, type sakila.
- Click Next.
In the New Connection Profile window:
- Click the New Driver Definition icon (
) located next to the Drivers field to open the New Driver Definition window.
- In the Name/Type tab, click Generic JBDC Driver and then click the JAR list tab.
Click Add JAR/Zip and then select the previously downloaded
.jarfile in the sakila-h2-master folder.
Figure 3.15. Select the JAR File
Click the Properties tab and enter the following details in the Properties table:
- Click Connection URL and type jdbc:h2:tcp://localhost/sakila.
- Click Driver Class, and then click the ellipsis icon
.
- In the Available Classes from Jar List window, click Browse for class. Click OK when the required driver is found (org.h2.Driver, in this case).
- Click User ID, type sa.
- In the New Driver Definition window, click OK.
- In the New Connection Profile window, click Finish to return to the JPA Facet window.
- In the Platform list, click Hibernate (JPA 2.1).
- In the JPA implementation pane, Type list, either click User Library and to add the libraries in the Preferences (Filtered) window see, the Additional Resources, Adding Libraries section for detailed steps, OR click Disable Library Configuration.
- Click Finish.
- If you see the Open Associated Perspective window asking if you want to open the JPA perspective, click Open Perspective. The project is created and is listed in the Project Explorer view.
3.4.2. Generating DDL and Entities
DDL, Data Definition Language, is a syntax to define data structures. Generate DDL and entities to enable Hibernate runtime support in an Eclipse JPA project.
To generate DDL and Entities:
- In the Project Explorer view, right-click the .
- Click JPA Tools > Generate Tables from Entities or Generate Entities from Tables. The Generate Entities window (or the Generate Tables from Entities window) appears.
In the Generate Entities window:
- In the Output directory field, change the default directory, if required.
- Ensure that the Use Console Configuration check box is clicked.
- In the Console Configuration list, ensure that the relevant configuration is shown.
Click Finish.
Figure 3.16. Generate Entities
3.4.3. Creating a Hibernate Mapping File
Hibernate mapping files specify how your objects relate to the database tables.
To create basic mappings for properties and associations, meaning, to generate the`.hbm.xml` files:
Create a new Hibernate Mapping file:
- Click File > New > Other.
- In the New wizard, locate Hibernate and expand it. Click Hibernate XML Mapping file (hbm.xml).
- Click Next.
In the New Hibernate XML Mapping files (hbm.xml) window:
- Click Add Class to add classes or click Add Packages to add packages. You can create an empty
.hbmfile by not selecting any packages or classes. An empty .hbm file is created in the specified location.
- Click the depth control check box to define the dependency depth used when choosing classes.
- Click Next.
- Select the parent folder location.
- In the File name field, type a name for the file (example: hibernate.hbm.xml) and click Finish. The
hibernate.hbm.xmlfile opens in the default editor.
3.4.4. Creating a Hibernate Configuration File
For reverse engineering, prototype queries, or to simply use Hibernate Core, a
hibernate.properties or a
hibernate.cfg.xml file is needed. Hibernate Tools provides a wizard to generate the
hibernate.cfg.xml file if required.
To create a Hibernate Configuration file:
Create a new
cfg.xmlfile:
- Click File > New > Other.
- In the New wizard, locate Hibernate and then click Hibernate Configuration File (cfg.xml).
- Click Next.
- In the Create Hibernate Configuration File (cfg.xml) window, select the target folder for the file and then click Next.
In the Hibernate Configuration File (cfg.xml) window:
- The Container field, by default, shows the container folder.
- The File name field, by default, shows the configuration file name (hibernate.cfg.xml, in this case).
- In the Database dialect list, click the relevant database (H2, in this case).
- In the Driver class list, click the driver class depending on the database dialect that you just selected (org.h2.Driver, in this case).
- In the Connection URL list, click the relevant URL (jdbc:h2:tcp://<server>[:<port>]/<databaseName>, in this case).
- Click the Create a console configuration check box to use the
hibernate.cfg.xmlfile as the basis of the console configuration.
Click Finish.
Figure 3.17. Create a New cfg.xml File
The new
hibernate.cfg.xml file opens in the default editor.
3.4.5. Creating a Hibernate Console Configuration File
A
Console configuration file describes how the Hibernate plugin configures Hibernate. It also describes the configuration files and classpaths needed to load the POJOs, JDBC drivers, etc. It is required to make use of query prototyping, reverse engineering and code generation. You can have multiple console configurations per project, but for most requirements, one configuration is sufficient.
To create a
Hibernate console configuration file:
Create a
cfg.xmlfile:
- Click File > New > Other.
- In the New wizard, locate Hibernate and then click Hibernate Console Configuration.
- Click Next.
In the Main tab:
- In the Name field, if required, edit the generated name provided by default.
- In the Type pane, click Core.
- In the Hibernate Version list, select the relevant version.
- In the Project field, type a project name or click Browse to locate an existing project (my_JPA_project, in this case).
- In the Database connection list, click New to configure a new database connection or leave as is to use the default connection.
- In the Property file field, click Setup to set the path to the first
hibernate.propertiesfile found in the selected project (see, the Additional Resources, Setting up the Property File section for detailed steps). Once created the path of the
.propertiesfile displays in the Property file field.
- In the Configuration file field, click Setup to set the path to the first
hibernate.cfg.xmlfile found in the selected project (see, the Additional Resources, Setting up the Configuration File section for detailed steps). Once created, the path of the
hibernate.cfg.xmlfile displays in the Configuration file field.
- Click Finish.
Figure 3.18. Create Hibernate Console
3.4.6. Modifying the Hibernate Configurations
You can edit the Hibernate Configurations from the Hibernate Configurations view.
To modify the Hibernate Configurations:
- Click Window > Show View > Other. Click Hibernate Configurations and then click Open.
- In the Hibernate Configurations view, right-click the and click Edit Configuration.
- The Edit Configuration window displays. Edit the fields. Click Apply and then click OK.
3.4.7. Generating Code and Reverse Engineering
Hibernate tools’ reverse engineering and code generation features allow you to generate a range of artifacts based on a database or an existing Hibernate configuration, like mapping files or annotated classes. Among others, these generated artifacts can be POJO Java source files,
hibernate.hbm.xml files,
hibernate.cfg.xml generation and schema documentation.
To generate code:
Configure Hibernate:
- Click Window > Perspective > Open Perspective > Other.
- Search for Hibernate and double-click it. The Hibernate Configurations view appears.
View the Hibernate Code Generation Configurations:
- In the toolbar, next to the Run icon, click the down arrow.
- Click Hibernate Code Generation Configurations.
- Expand Hibernate Code Generation and then click New_configuration.
- In the Create, manage, and run configurations window, in the Name field, type a logical name for the code generation launcher. If you do not specify a name, the default name, New_Generation, is used.
In the Main tab, enter the following details:Note
The At least one exporter option must be selected warning indicates that for the launcher to work you must select an exporter on the Exporter tab. The warning disappears after you select an exporter.
- In the Console Configuration list, click the name of the console configuration to be used when generating code.
- In the Output directory field, click Browse and select an output directory. This is the default location where all output will be written. You can enter absolute directory paths, for example: d:/temp. Note that existing files will be overwritten/ if the correct directory is not specified.
- To reverse engineer the database defined in the connection information, click the Reverse engineering from JDBC connection check box. Developer Studio generates code based on the database schema when this option is used.If this option is not enabled, the code generation is based on the existing mappings specified in the Hibernate Console configuration.
- In the Package field, add a default package name for any entities found when reverse engineering.
In the reveng.xml field, click Setup to select an existing
reveng.xmlfile, or create a new one. This file controls certain aspects of the reverse engineering process, such as:
- how JDBC types are mapped to Hibernate types
- which tables are included or excluded from the process
In the reveng. strategy field, click Browse and provide an implementation of a ReverseEngineeringStrategy. this must be done if the
reveng.xmlfile does not provide enough customization; the class must be in the classpath of the Console Configuration because if not, you will get a class not found exception.Note
Refer to the Additional Resources, Creating, Managing, and Running Configurations Window, Main tab, Check Boxes section for details of the selected check boxes.
- The Exporter tab specifies the type of code that is generated. Each selection represents an Exporter that generates the code. In the Exporter tab:
Click the Use Java 5 syntax check box to use a Java 5 syntax for the Exporter
- Click the Generate EJB3 annotations check box to generate EJB 3 annotations
Select the Exporters from the Exporters table. Refer to the Additional Resources, Exporter section for details about the exporters.
Each Exporter selected in the preceding step uses certain properties that can be set up in the Properties section. In the Properties section, you can add and remove predefined or custom properties for each of the exporters.
- Click Add next to the Properties table to add a property to the chosen Exporter. In the resulting dialog box, select the property from the proposed list and the appropriate value for it. For an explanation of the property and its value, refer to the Additional Resources, Exporter Property and its Values section.
Click the Refresh tab and enter the following:
Click the Refresh resources upon completion check box to refresh the resources and click one of the following:
- The entire workspace: To refresh the entire workspace.
- The selected resource: To only refresh the selected resource
- The project containing the selected resource: To refresh the project containing the selected resource
- The folder containing the selected resource: To refresh the folder containing the selected resource
- Specific resources: To refresh specific resources; then click Specify Resources to open the Edit Working Set window and select the working set.
- Click the Recursively include sub-folders check box to refresh the sub-folders.
Click the Common tab and enter the following:
- In the Save as pane, click Local file to save the configuration as a local file, OR click Shared file and then select a shared file location.
- In the Display in favourites menu pane, click the menu to display the configuration.
- In the Encoding pane, click the format that you want the configuration to be encoded to.
- In the Standard Input and Output pane, click the Allocate console check box and optionally click the Input File and Output File check boxes and select the relevant options.
- Click the Launch in background check box to show the configuration launch progress in the background.
- Click Apply and then click Run.
3.4.8. Troubleshooting
3.4.8.1. Problems While Loading Database Driverclass
Error message: Problems while loading database driverclass (org.h2.Driver)
Resolution: To avoid this error, you must select a predefined DTP connection profile in the Database Connection dropdown. Also, the jar can be added on the Classpath page of the Console Configuration wizard if you don’t want to have it on the project classpath.
- Right-click {project_name} → Properties → Java Build Path.
- Click the Libraries tab and then click Add External JARs.
- Navigate to the downloaded database JAR file and click OK.
- In the Properties for {project_name} window, click Apply and then click OK.
Additional Resources
Adding Libraries
To add libraries:
- Download Hibernate ORM from.
- Extract the file to locate the libraries in the
lib/requiredfolder.
- In the JPA Facet window, Platform list, click * User Library*.
- Click the Manage libraries icon (
).
- In the Preferences (Filtered) window, click New.
- In the New User Library window, User library name field, type a name for the user library and click OK (user_library, in this case).
- Click the System library (added to the boot class path) check box and click OK.
- In the Preferences (Filtered), click Add External JARs and locate the extracted
hibernate-release-1/lib/requiredfolder.
- Click the first library and click OK. Repeat the above step to add all the libraries from the hibernate-release-1/lib/required` folder.
- In the Preferences (Filtered), click Apply and Close.
Setting up the Property File
To set up the property file:
- In the Create Hibernate Configuration window, Main tab, click Setup.
- In the Setup property file window, click Create new to create a new property file (or click Use existing to choose an existing file as a property file).
- In the Create Hibernate Properties file (.properties) window, click the parent folder name and then click Finish.
Setting up the Configuration File
To set up the configuration file:
- In the Create Hibernate Configuration window, Main tab, click Setup.
- In the Setup configuration file window, click Use existing to choose an existing file as a property file (or click Create new to create a new property file).
- In the Select hibernate.cfg.xml file window, expand the parent folder, choose the file to use as the hibernate.cfg.xml file, and then click OK.
Creating, Managing, and Running the Configurations Window, Main tab, Check Boxes
The following check boxes are selected by default in the Create, manage, and run configurations window, in the Main tab:
- Generate basic typed composite ids: When a table has a multi-column primary key, a <composite-id> mapping will always be created. If this option is enabled and there are matching foreign-keys, each key column is still considered a 'basic' scalar (string, long, etc.) instead of a reference to an entity. If you disable this option a <key-many-to-one> property is created instead. Note that a <many-to-one> property is still created, but is simply marked as non-updatable and non-insertable.
- Detect optimistic lock columns: Automatically detects optimistic lock columns. Controllable via reveng. strategy; the current default is to use columns named VERSION or TIMESTAMP.
- Detect many-to-many tables: Automatically detects many-to-many tables. Controllable via reveng. Strategy.
- Detect one-to-one associations: Reverse engineering detects one-to-one associations via primary key and both the hbm.xml file and annotation generation generates the proper code for it. The detection is enabled by default (except for Seam 1.2 and Seam 2.0) reverse engineering. For Hibernate Tools generation there is a check box to disable this feature if it is not required.
Exporter Property and Values
- jdj5: Generates Java 5 syntax
- ejb3: Generates EJB 3 annotations
- for_each: Specifies for which type of model elements the exporter should create a file and run through the templates. Possible values are: entity, component, configuration.
- template_path: Creates a custom template directory for this specific exporter. You can use Eclipse variables.
- template_name: Name for template relative to the template path.
- outputdir: Custom output directory for the specific exporter. You can use Eclipse variables.
- file_pattern: Pattern to use for the generated files, with a path relative to the output dir. Example: /.java.
- Dot.executable: Executable to run GraphViz (only relevant, but optional for Schema documentation).
- Drop: Output will contain drop statements for the tables, indices, and constraints.
- delimiter: Is used in the output file.
- create: Output will contain create statements for the tables, indices, and constraints.
- scriptToConsole: The script will be output to Console.
- exportToDatabase: Executes the generated statements against the database.
- outputFileName: If specified the statements will be dumped to this file.
- haltOnError: Halts the build process if an error occurs.
- Format: Applies basic formatting to the statements.
- schemaUpdate: Updates a schema.
- query: HQL Query template
Exporter
- Domain code (.java): Generates POJOs for all the persistent classes and components found in the given Hibernate configuration.
- Hibernate XML Mappings (.hbm.xml): Generate mapping (hbm.xml) files for each entity.
- DAO code (.java): Generates a set of DAOs for each entity found.
- Generic Exporter (<hbmtemplate>): Generates a fully customizable exporter that can be used to perform custom generation.
- Hibernate XML Configuration (.cfg.xml): Generates a hibernate.cfg.xml file; used to keep the hibernate.cfg.xml file updated with any newly discovered mapping files.
- Schema Documentation (.html): Generates a set of HTML pages that document the database schema and some of the mappings.
- Schema Export (.ddl): Generates the appropriate SQL DDL and allows you to store the result in a file or export it directly to the database.
- HQL Query Execution Exporter: Generates HQL Query according to given properties.
3.5. Creating a Mobile Web Application
Mobile Web Tools provides an HTML5 Project wizard that enables you to create web applications optimized for mobile devices. The HTML5 Project wizard is a useful starting point for creating all new HTML5 web applications in the IDE. The wizard generates a sample ready-to-deploy HTML5 mobile application with REST resources from a Maven archetype.
You can customize the application using the
JBoss Tools HTML Editor, deploy and view the application with the mobile browser simulator BrowserSim, and use LiveReload to refresh BrowserSim as the application source code is modified and saved in the IDE.
Prerequisites
Configuring the IDE for an Available Server
For information on configuring a local runtime server and deploying applications to it, see Deploying Applications to a Local Server.
The IDE must be configured for any servers to which you want to deploy applications, including the location and type of application server and any custom configuration or management settings. This article assumes you completed the configuration in advance, but that step can be completed at deployment.
3.5.1. Creating an HTML5 Project
The HTML5 Project wizard generates a sample project based on a Maven archetype and the project and application identifiers provided by you. The Maven archetype version is indicated in the Description field in the first page of the wizard and you can change the version, and therefore the project look and dependencies, by selecting either an enterprise or non-enterprise target runtime within the wizard.
To create an HTML5 project:
- In Red Hat Central, in the Getting Started tab, click HTML5 Project.
- In the Target Runtime list, click an IDE-ready server and click Next.
In the New Project Example window, complete the fields about the HTML5 project as follows:
- In the Project name field, type a name for the project.
- In the Package field, type an alpha-numeric package for the project.
- Click Finish.
- When prompted with 'HTML5 Project' Project is now ready, click Finish. The project is generated and listed in the Project Explorer view.
3.5.2. Building and Deploying the Application
After the HTML5 project is generated, it can be built and deployed to an application server.
To build and deploy the application:
- In the Project Explorer view, right-click {project name} and click Run As > Run on Server.
- In the Run On Server window, ensure that Choose an existing server is selected.
From the table of servers, expand localhost, select the server on which to deploy the application, and click Finish.
Figure 3.19. Selecting the Server to Run the Application
The Console view shows output from the server starting and deploying the application. When deployment is complete, an IDE default web browser opens and shows the deployed web application.
Figure 3.20. Enterprise HTML5 web application Viewed in Browser
3.5.3. Viewing the Application with BrowserSim
The HTML5 web application has an interface optimized for mobile devices. You can view and test such web pages as they would be on mobile devices using BrowserSim. This mobile device web browser simulator provides skins for different mobile devices, making it easy to test and debug web applications for mobile devices.
To view the application with BrowserSim:
- Ensure JBoss is the perspective in use. To open the JBoss perspective, click Window > Perspective > Open Perspective > Other and double-click JBoss (default).
- In the Servers view, expand the server adapter to list the application.
- Right-click
{application name}and click Show In > BrowserSim.
Figure 3.21. HTML5 Web Application Viewed with BrowserSim
3.5.4. Enabling LiveReload for BrowserSim
Mobile Web Tools supports the LiveReload protocol for automatic reloading of web pages in enabled browsers as the application source is modified and saved. LiveReload can be enabled for your system browsers and, as demonstrated here, BrowserSim. This provides an interactive web development experience.
To enable LiveReload for BrowserSim, complete the following steps:
- Close any open BrowserSim simulated devices.
- In the Servers view, right-click an existing server to display the context menu and click New > Server.
- From the list, expand Basic, click LiveReload Server and click Finish.
- In the Servers view, right-click LiveReload Server and click Start.
- In the Servers view, right-click {application name} and click Show In > BrowserSim.
LiveReload is automatically enabled for this BrowserSim simulated device and all subsequent devices opened while the LiveReload server is running.
3.5.5. Editing the Application
With LiveReload enabled for BrowserSim, you can make changes to your application source code and BrowserSim automatically reloads the application when changes are saved. This is demonstrated here by making a simple change to the project
index.html file, specifically changing the text in the application title banner.
To change your application:
- In the Project Explorer view, expand {project name} > src > main > webapp.
- Double-click
index.htmlto open it for editing with the JBoss Tools HTML Editor.
Locate the following line of code inside the <body> tags:
<title>HTML5 Quickstart</title>
and replace it with
<title>My Quickstart</title>
- Save the file by pressing Ctrl+S (or Cmd+S).
This code change modifies the heading displayed on the main application page. Notice that BrowserSim automatically reloads the web page when you save the changed file and the application modifications are immediately visible.
Additional Resources
- You can launch the HTML5 Project wizard from the JBoss perspective by clicking File > New > HTML5 Project.
- You can test an undeployed
.htmlfile with BrowserSim by right-clicking the
.htmlfile in the Project Explorer view and clicking Open With > BrowserSim.
- To set BrowserSim as the IDE default web browser, in the JBoss perspective click Window > Web Browser > BrowserSim or click Window > Preferences > General > Web Browser and from the External web browsers list select BrowserSim.
- You can also enable LiveReload for already opened BrowserSim simulated devices. After starting the LiveReload server, right-click the BrowserSim simulated device frame and click Enable LiveReload.
3.6. Generating an HTML5 Web Application Using the Mobile Web Palette
The IDE provides the Mobile Web palette that allows the user to make interactive web applications. This palette offers a wide range of features including drag-and-drop widgets for adding common web interface framework features such as HTML5, jQuery Mobile, and Ionic tags to html files. It also contains widgets like Panels, Pages, Lists, Buttons to make the applications more user friendly and efficient.
3.6.1. Adding a New HTML5 jQuery Mobile File to a Project
The HTML5
jQuery Mobile file template consists of JavaScript and CSS library references that are inserted in the file’s HTML header. The template also inserts a skeleton of the jQuery Mobile page and listview widgets in the file’s HTML body. The following procedure details the steps to insert the template into your project.
To create a new HTML5 jQuery Mobile file in an existing project:
- In the Project Explorer view, expand [project name] > src > main.
- Right-click webapp and click New > HTML File.
Complete the fields about the html file as follows:
- Ensure the parent folder field shows [project name]/src/main/webapp.
- In the File name field, type a name for the HTML5 file.
- Click Next.
- From the Templates table, select HTML5 jQuery Mobile Page (1.4) and click Finish.
Figure 3.22. Selecting the HTML5 jQuery Mobile Page (1.4) Option
The new file is listed in the
Project Explorer view under the project
webapp directory and the file opens in the editor.
3.6.2. Adding New Pages to the Web Application
Use the jQuery Mobile Page widget to add pages to your mobile web application:
- In the Project Explorer view, expand [project name] > src > main > webapp.
- Right-click the new html file and click Open With > JBoss Tools HTML Editor.
- In the Palette view, click the jQuery Mobile tab to view the available widgets and click Page.
Complete the fields about the page as follows:
- In the Header field, type a name for the page header.
- In the Footer field, type a name for the page footer.
Click Finish.
Figure 3.23. Adding a New Page
- Save the changes to the file by clicking the Save icon.
A page is added to the html file. JS and CSS references are also automatically added to the file by the
Page widget wizard.
Figure 3.24. New Page Added to the HTML File
3.6.3. Customizing the Home Page of the Web Application
Use the widgets in the jQuery Mobile palette to customize the page. Use the instructions to add a menu to the page. This menu links to three other pages: Home, Search, and the Add Contacts page.
3.6.3.1. Adding a Panel to the Page
To add a panel:
- In the
htmlfile, place the cursor where you want the panel.
- In the Palette view, in the jQuery Mobile tab, click Panel.
Complete the fields about the Panel as follows:
- In the ID field, type my panel ID.
- Clear the Add Menu check box.
- Click Finish.
- Save the
htmlfile.
Figure 3.25. Adding a New Panel
A corresponding code snippet, for the newly added panel, is added to the
html file where you had placed the cursor.
3.6.3.2. Adding a List to the Panel
To add a list:
- Within the panel’s code snippet, place your cursor at the desired location for the new list.
- In the Palette view, in the jQuery Mobile tab, click ListView.
Complete the fields about the ListView as follows:
- In the Items section, 1 tab, in the Label field, type the name for the first list item on the page.
In the URL (href) field, type a URL identifier for the label.
Figure 3.26. New Listitem Added to the Panel
- Click Finish.
- Save the html file.
The new list item name appears in the code snippet.
Figure 3.27. Code for the New Listitem in the Panel Added
3.6.4. Running and Testing the HTML5 Mobile Application Using BrowserSim
Test the newly added elements to the application by navigating to the interface on BrowserSim as follows:
- In the Project Explore view, expand [project name] > src > main > webapp.
- Right-click the changed html file and click Open With > BrowserSim.
A simulated device appears and displays the application.
Figure 3.29. The Changes Made to the HTML File Displayed on BrowserSim
Additional Resources
- To access the jQuery Mobile palette when the Palette view is not visible, click Window > Show View > Other, expand General and select Palette.
- To add BrowserSim in the toolbar by clicking Window > Customize Perspective and select BrowserSim under Command Groups Availability. It appears as a Phone icon in the toolbar.
- Use the Panel widget to create menus, collapsible columns, drawers, and more. The List View widget is an unordered list containing links to list items. jQuery Mobile applies the necessary styles to make the listview mobile friendly.
- Add contacts to the Add Contacts page by following the above listed procedure. You can add Name, Email, Phone Number fields to the Add Contacts page by using the Text Input icon in the Mobile Web palette.
3.7. Importing Projects in Developer Studio Using Git Import
The Developer Studio Git Import feature allows you to easily configure most of the settings required to make a project workable immediately after it is imported in the IDE.
Procedure
3.7.1. Importing Projects from Git with Smart Import
Use the Project from Git (with smart import) option, if you are unaware of the type of the project that you want to import.
We recommend using the Projects from Git (with smart import) option because it is the easiest and most efficient way to import projects into the IDE with minimal effort.
The Import wizard will automatically detect the type of project being imported and will configure the project so that you have to put in minimal effort to make the project workable.
The Git Import feature detects the various modules of a project that is a set of other individual projects. It detects markers such as
pom.xml,
MANIFEST.MF, etc. to determine the type of project that you are importing.
To import projects from Git with smart import:
- Click File > Import.
- In the Import window, click Projects from Git (with smart import) and click Next.
- In the Select Repository Source window, click Existing local repository or Clone URI.
- Step through the wizard and click Finish for the wizard to analyze the content of the project folder to find projects for import and import them in the IDE. The imported project is listed in the Project Explorer view.
3.7.2. Importing Projects from Git
Use the Projects from Git option when you are aware of the type of project that you want to import into the IDE. Use the Existing local repository option, if you have, at some point in time, cloned the remote Git repository and the repository is present on your local system.
Procedure
3.7.2.1. Importing Existing Eclipse Projects
Use the Existing local repositories option to import Eclipse projects in the IDE. These projects essentially have a
.project file. This
.project file contains the project description and settings needed to configure and build project in Eclipse.
To import projects as existing Eclipse projects:
- Click File > Import.
In the Import wizard:
- Expand Git and then click Projects from Git. Click Next.
- Click Existing local repository and then click Next.
- Click Git to choose one of the recently used repositories from the list or click Add to browse to any local repository. Click Next. In the Wizard for project import section, click Import existing Eclipse project. Click Next.
- In the Import Projects window, select all the projects that you want to import.
- Ensure that the Select nested projects check box is clicked to import the nested projects under the parent project that you are importing.
- Click Finish.
The imported project is listed in the Project Explorer view.
3.7.2.2. Importing Using the New Project Wizard
Use the Import using the New Project wizard option, if your repository is empty and you want to start developing a new project from scratch and then push the code to the remote repository.
To import projects using the New Project wizard:
- Click File > Import.
In the Import wizard:
- Click Git > Projects from Git. Click Next.
- Click Existing local repository and then click Next.
- Click Git and then click Next.
- In the Wizard for project import section, click Import using the New Project wizard. Click Finish.
In the New Project wizard, expand the category, and then click the project type that you want to create and import. Click Next.
- In the New <type_of_project> window, fill in the information for the new project and click Next or Finish to create the new project. The imported project is listed in the Project Explorer view.
3.7.2.3. Importing as a General Project
Use the Import as general project option if the project being imported does not have a
.project file, meaning it is not an Eclipse project. In this case Eclipse will create a clean
.project file with default settings.
To import a project as a general project:
- Click File > Import.
In the Import wizard:
- Click Git > Projects from Git. Click Next.
- Click Existing local repository and then click Next.
- Click Git and then click Next.
- In the Wizard for project import section, click Import as general project.
- Select the project and click Next.
- In the Import Projects from Git window, confirm or edit the default parameters and click Finish.
The imported project is listed in the Project Explorer view.
3.7.3. Importing Projects from the Remote Git Repository
Use the Clone URI option to clone the repository on your system if you have never cloned the Git repository; meaning, the repository does not exist on your local system.
The three options, importing existing eclipse projects, importing using the New Project wizard, and importing as a general project, are available under the Clone URI method, too. For detailed steps, see the preceding sections: Section 3.7.2.1, “Importing Existing Eclipse Projects”, Section 3.7.2.2, “Importing Using the New Project Wizard”, and Section 3.7.2.3, “Importing as a General Project”.
To import projects in the Cloned URI:
- Click File > Import.
In the Import wizard:
- Click Git > Projects from Git and then click Next.
- Click Clone URI and click Next.
In the Source Git Repository window, in the URI field, enter an existing Git repository URL, either local or remote and click Next.
In the Branch Selection window, click all the branches that you want to clone from the remote repository and click Next.
In the Local Destination window, ensure that the directory that you want to set as the local storage location for the repository is selected in the Directory field. Or, click Browse to select the location.
The Cloning from <GitHub_repository> window shows the progress of the cloning process.
- In the Select a wizard to use for importing projects window, Import as general project is selected by default. Click Next.
- In the Import Projects window, ensure that the Directory field shows the path to the directory where you want to import the projects and click Finish. The imported project is listed in the Project Explorer view. The cloned repository of the remote Git repository is now located in the local file system.
3.8. Getting Started with JavaScript Development for Neon 3
This article walks you through JavaScript Development for Neon 3. Neon 3 uses the new Esprima parser that supports ECMAScript 2015 (JavaScript 6). The intuitive Esprima parser assists in the following tasks:
- Syntax coloration
- Validation
- Content assist
- Templates for keywords
- Class definition
- Template literals
- Integration with Outline View
Prerequisites
3.8.1. Installing node.js
To install node.js:
- On Windows, macOS, and Linux, see.
- On RHEL, see .
3.8.2. Installing the Package Managers (Bower and npm)
You may choose to work with either npm or with Bower. However, if you are using npm you must use the file
package.json and if using Bower, use the file
bower.json.
If installing both npm and bower, ensure that you install npm before you install Bower.
- To install npm: When you install node.js, npm will be available for use because npm is distributed with node.js.
- To install Bower: Run the command
npm install -g boweras the root user.
Procedure
3.8.3.. However, if you are using npm you must use the file
package.json and if using Bower, use the file
bower.json.
Procedure
3.8.3.1. Creating a New Project
In this section, you create a new project so that you can later enable the dependencies and see how the Neon 3 features work with Developer Studio.
Procedure
To create a project:
- Click File > Project.
- In the New Project wizard, click General > Project. Click Next.
- In the Project name field, type the name of the project (Neon3_features, in this example).
- Edit the other fields if required and then click Finish. The new project is listed in the Project Explorer view.
3.8.3.2. Enabling Bower Init
After you have enabled Bower Init the result will be a
bower.json file listed under the project in the Project Explorer view.
Procedure. The
bower.jsonfile opens in the default editor.
Figure 3.30. Contents of the bower.json File
3.8.3.3. Enabling npm Init
Procedure. The
package.jsonfile opens in the default editor.
3.8.3.4. Creating a New index.html File
In this section, you create an
index.html file so that you can use it in Section 3.8.3.5, “Using the Bower Tool”.
Procedure.
3.8.3.5. Using the Bower Tool
Procedure 3.31. 3.32.. The page shows the bootstrap template with a responsive design.
Figure 3.33. index.html Page with Responsive Design
3.8.4..
Procedure
3.8.4 3.8.4.2, “Enabling the Gulp Plugin”.
Procedure 3.34. package.json File as Edited
3.8.4.2..
Procedure 3.35. package.json File with Gulp Enabled
- In the
package.jsonfile, click Run As > npm Install. The Console view shows the progress of the task. Overlook any warnings at this point of time. The node_modules folder displays under the project in the Project Explorer view.
3.8.4.3. Creating the gulpfile.js File
In this section, you create the
gulpfile.js file to be used in Section 3.8.4.4, “Using the Gulp Plugin”.
Procedure 3.36. gulpfile.js File
3.8.4.4. Using the Gulp Plugin
Procedure. A new directory named renamed-html is created under neon3_features. Expand the renamed-html directory to see the
renamed.htmlfile.
3.8.5. Working with the Node.js Application
In this section, you will use the project at:.
Prerequisites
- Ensure npm and node.js are installed. For details to install, see the Additional Resources section.
Procedure
3.8.5.1. Importing the jsdt-node-test-project
Procedure. The jsdt-node-test-project is listed in the Project Explorer view.
3.8.5.2. Running the index.js File
Procedure
To work with the node.js application:
- In the Project Explorer view, expand jsdt-node-test-project.
- Right-click package.json and click Run As > npm Install. The Console view shows the progress of the task.
- Right-click index.js and click Run As > Node.js Application. The Console view shows the Listening on port 3000 message. Open localhost:3000 to see the output on a web page.
Figure 3.37. Output of the index.js File
3.8.5.3. Debugging the Node.js Application
Procedure. The Console view shows the debugger listening on port <port_number> message.
Figure 3.38. Debugging the Node.js Application
Additional Resources.
Chapter 4. Deploying Your Applications
4.1. Deploying Applications to a Local Server
In order to deploy applications to a server from within the IDE, you must configure the IDE with information about the server. For a local server this information includes the following:
- A server runtime environment with details about the server location, runtime JRE, and configuration files
- A server adapter with management settings for the server runtime environment, including access parameters, launch arguments, and publishing options
JBoss Server Tools enables you to efficiently configure a local server ready for use with the IDE using Runtime Detection. As demonstrated here, this feature is useful for quickly configuring a server for deploying and testing an application.
Procedure
4.1.1. Configuring the IDE for a Local Runtime Server
Runtime Detection searches a given local system path to locate certain types of runtime servers. For any servers found, Runtime Detection automatically generates both a default server runtime environment and a default server adapter. These items can be used as they are for immediate application deployment or customized to meet your requirements.
Procedure
To configure the IDE for a local runtime server:
- Click Window > Preferences.
- In the Preferences window, locate and click JBoss Tools > JBoss Runtime Detection.
- Click Add.
- Locate the directory containing the runtime server and click OK.
- In the table of located runtimes, ensure the runtime is selected and click OK.
- Click Apply and Close to close the Preferences window. A default runtime environment and server adapter are generated for the server, with the server adapter listed in the Servers view.
4.1.2. Deploying an Application
When you have configured the IDE for the server, you can deploy applications to the server from the IDE using the server adapter. The server adapter enables runtime communication between the server and IDE for easy deployment of applications and server management.
Procedure
To deploy an application to the server:
- In the Project Explorer view, right-click {project name} and click Run As > Run on Server.
- Ensure Choose an existing server is selected.
- From the table of servers, expand localhost, select the server on which to deploy the application and click Finish. The Console view shows output from the server starting and deploying the application. When deployment is complete, an IDE default web browser opens and shows the deployed web application.
4.1.3. Changing and Republishing the Application
By default, the server adapter configures the server for automatic publishing when changed resources are saved. This automatic publishing action applies to application resources that can be interchanged in the dedicated deployment location of the server without requiring the application to stop and restart, such as
.html files. For other changed resources, such as
.java files, you need to republish the application such that it forces a rebuild of the application.
Procedure
To republish the application to the server after changes that cannot be automatically published:
- In the Servers view, expand the server adapter to list the applications allocated to the server.
- Right-click {application name} and click Full Publish. The Console view shows the output from the server replacing the deploying application. Unless LiveReload is enabled in the web browser, you must manually reload the web browser to see the changed application.
Additional Resources
- You can also configure servers by right-clicking the Servers view and selecting New > Server or by clicking Manually define a new server in the Run on Server wizard.
- Paths previously searched by Runtime Detection can be automatically searched on every workspace start. Click Window > Preferences > JBoss Tools > JBoss Runtime Detection and from the Paths table select the check boxes of the appropriate paths. Click Apply and click OK to close the Preferences window.
- You can customize the server adapter and server runtime environment with the Server Editor. In the Servers view, double-click the server adapter to open the Server Editor.
- You can initiate download and installation of runtime servers from the IDE. Click Window > Preferences > JBoss Tools > JBoss Runtime Detection. Click Download and from the table of runtime servers select the one to install and click Next. Follow the on-screen instructions to complete the download and installation process.
4.2. Configuring a Remote Server
Remote servers allow developers to access and deploy to a JBoss instance that is not a local machine. Developers can use remote servers to set up multiple environments for development and testing purposes and share them with other developers. Another reason to use a remote server with Red Hat Developer Studio is to allow developers to share and deploy automated tests to run in a non-local environment.
Procedure
4.2.1. Setting up a Remote Server
Procedure
The following instructions are used to set up a remote server for JBoss Enterprise Middleware application servers. A complete server definition requires a server adapter (or server) that allows the IDE to communicate with and manage the remote server.
- Click the Servers view. If the Servers view is not visible, click Window > Show View > Server.
Use the appropriate instructions depending on the number of existing servers listed in the Servers tab:
- If there are no existing servers, click No servers are available. Click this link to create a new server.
- If there are one or more existing servers, right-click an existing server and click New > Server.
In the New Server wizard:
- From the Select the server type list, select a JBoss Enterprise Middleware application server.
- The Server’s host name and Server name fields are completed by default. In the Server name field, you can type a custom name to later identify the server in the Servers view.
Click Next to continue.
Figure 4.1. Defining a New Remote Server
Configure the required Server Adapter details:
- In The server is list, click Remote.
In the Controlled by list, click either Filesystem and shell operations or Management Operations depending on your requirement.Note
If you select Management Operations in the Controlled by list, you must set up an administrator user on the server by using the $SERVER_HOME/bin/add-users.sh script for Linux, or the $SERVER_HOME\bin\add-users.bat file for Windows, and enter the same credentials in the server editor or during the server start.
- Click the Server lifecycle is externally managed. check box to deploy the server but to not expect the IDE to stop or start the server.
Clear the Assign a runtime to this server check box to create a remote server without assigning a runtime to it.Note
Creating a Remote Server without a runtime results in limitations. For example, the JMX connection does not work because it requires libraries from the runtime to connect via JMX. Additionally, automatic port detection occurs using the
standalone.xmlfile, which is not available if a runtime is not specified. These and other minor issues related to hard-coded minor fixes in maintenance releases may occur if no runtime is specified for the Remote Server.
From the drop-down list, click the relevant runtime server and click Next.
Figure 4.2. Creating a New Server Adapter
Add the remote system integration details as follows:
- In the Host field, the default host is Local. If required, click New Host to create a new host, which may be remote or local. Supported connection types for remote hosts are FTP Only or SSH Only.
- In the Remote Server Home field, specify a path to the directory that contains the remote server.
- In the Remote Server Base Directory field, specify the remote server’s base directory (the default value for this is the standalone directory within the server home directory).
- In the Remote Server Configuration File field, specify the file to use for the remote server’s configuration (the default value for this is the standalone.xml file). This location is within the Remote Server Home directory (specifically in the
$SERVER_HOME/$BASE_DIRECTORY/configuration/directory).
Either click Next to continue to the (optional) next step to add or remove server resources or click Finish to conclude the new remote server configuration.
Figure 4.3. Connect to a Remote System
Optional: Add or remove resources configured on the server as follows:
- To add a resource, select the appropriate resource in the Available pane and click Add. To add all available resources, click Add All.
- To remove a resource, select the appropriate resource in the Configured pane and click Remove. To remove all configured resources, click Remove All.
Click Finish to complete the server configuration.
Figure 4.4. Add and Remove Server Resources
Result: You have successfully configured a remote server. The new server is listed in the Servers view. Right-click the server to view operations, including Start to start the server.
If the Server lifecycle is externally managed. check box was selected in the steps above, clicking Start does not start the server. Instead, it marks the server to indicate that it has started and the web poller checks whether the server is running. | https://access.redhat.com/documentation/en-us/red_hat_developer_studio/12.9/html-single/getting_started_with_developer_studio_tools/index | CC-MAIN-2019-26 | refinedweb | 13,599 | 57.47 |
17 July 2009 17:29 [Source: ICIS news]
By John Richardson
SINGAPORE (ICIS news)--If you predict a collapse in any market for long enough it will surely happen - or maybe not in this case.
Many of us have had to wipe large amounts of egg off our faces as the Asian polyolefins price “bubble”, which began mid-November last year, has continued.
Asian olefin and polyolefins prices remained firm as this article was published – close to their levels for the week ending 10 July, despite the recent fall in oil prices.
High-density polyethylene (HDPE) film grade reached a low point of $750/tonne CFR (cost and freight) ?xml:namespace>
Markets have not looked back since, with prices more or less following a constant upward or stable trajectory. HDPE film for August delivery business was recently settled at $1,220-1,280/tonne CFR China.
Pessimists (or maybe realists) continue to question the sustainability of the recovery, however.
This questioning hadn’t lost any of its intensity on Friday 17 July, despite the official announcement that
“Monthly PE demand in
“It averaged 980,000 tonnes in 2007 and 970,000 tonnes in 2008 and yet soared to 1,270,000 tonnes up until May this year.”
This has occurred despite the steep fall in
The reductions seem to be far too big to be entirely replaced by stronger local demand in 2009, largely the result of huge government spending.
One often-expressed concern is that speculators, awash with credit as bank lending has risen, have poured into the local stock market (which has gone up by 75% this year) and all sorts of commodities and exchanges.
More than 80m tonnes of linear-low density PE (LLDPE) were traded on the Dalian Commodity Exchange during the second quarter – around four times global annual demand.
Rising oil prices have contributed to the polyolefins price-rally in the physical market.
“If a lot of this product has gone into storage as either as polymers or finished goods, then at sometime it will re-emerge on world markets,” adds Hodges.
“And if it all comes at one time, when 'everyone' decides prices are falling, there is clearly a risk that it might have a major deflationary impact.”
There are many other factors behind the extraordinary and largely unexpected rebound.
“I remember going to ChinaPlas in May (the big plastics exhibition). There were a lot of Doomsday scenarios being bandied about because of the coming supply surge and the unsustainability of the Chinese economic recovery,” said a Singapore-based polyolefins trader.
“I think the rally is mainly down to tight supply. Production cutbacks in Europe and the
PP has been a major beneficiary: of the 2.77m tonnes/year of capacity, or thereabouts, due on stream in
As little as 1.02m tonnes/year of the 2.77m tonnes/year was understood to have started up by mid-July.
“I think a reason has been that EPC (engineering, procurement and construction) resources were severely overstretched,” added the European source.
“You just couldn’t get enough experienced project managers to oversee these big investments.
“Cost constraints have caused problems as have efforts to commission entire complexes at once when phased start-ups might have been better.”
Gas feedstock shortages resulted in low operating rates at
A substantial maintenance shutdown programme has taken place in
“Operating rates at many crackers unaffected by maintenance were also turned down as rapidly strengthening feedstock prices squeezed cracker and integrated derivative margins close to breakeven,” added ChemSystems
The Middle East and
“When you think about the
“Despite the global economic problems the market is still growing.”
PP has also been tight because small plants in
Refineries have been running at low operating rates due to, first of all, weaker fuels demand and, more recently, higher crude prices.
Tight supply in all grades of polyolefins seems to have so far counter-balanced the $10/bbl or so decline in oil prices over the last few weeks.
“US dollar-priced material (for shipment to
He gave two further reasons for the strength of the market.
“The Chinese government has been building up stocks of goods for disaster relief. It doesn’t want to be embarrassed again by the shortages that followed last year’s
“HDPE yarn grade is very tight, for example, as it is used to manufacture tents.”
Imports of recycled or scrap plastic into
“Consumers in the West are buying fewer durable goods, such as electronics, which arrive wrapped in plastic,” continued the trader.
“During the economic mega-boom lots of this plastic was collected in the
Chinese traders handling recycled material went bust by the legion in 2008. This was the result of the great petrochemicals price collapse which left virgin resin cheaper than re-used product.
Stricter government regulations on scrap imports due to concerns over pollution have also slowed trade.
But still, you keep coming back to the apparent PE demand numbers at the beginning of this article. How can they be up on 2007-08 with the world economy still in deep crisis?
“I know - you have to be worried. Something doesn’t seem quite right,” added the
“The bonded warehouses (where US dollar material is stored) I visited in northern and southern
“But inventories of RMB-priced material held by local traders and distributors seemed to be very high indeed.”
Some contacts we spoke to want a sentiment survey on PE and PP inventory levels in
The feeling is that PP imports and production may also have also increased in 2009, but the data were not immediately available.
“I think many people are having a hard time applying logic to the current market,” the European producer added.
“This is more supply than demand driven and once the new capacities finally start up, we will face a bloodbath.”
Yes, but exactly when? Maybe, just maybe, if project delays continue and the global economic recovery is sustained the air will be gently released from the polyolefins price bubble.
Or, if we can get a handle on inventory levels in
Read John Richardson's Asian Chemical Connections blog and | http://www.icis.com/Articles/2009/07/17/9233430/insight-squeezing-the-china-polyolefins-price-bubble.html | CC-MAIN-2015-22 | refinedweb | 1,021 | 57.81 |
Styled Components: Enforcing Best Practices In Component-Based Systems
- By Max Stoiber
- January 16th, 2017
- 19 Comments
Building user interfaces on the web is hard, because the web and, thus, CSS were inherently made for documents. Some smart developers invented methodologies and conventions such as BEM1, ITCSS, SMACSS and many more, which make building user interfaces easier and more maintainable by working with components.
After this shift in mindset towards building component-based user interfaces, we are now in what we like to call the “component age.” The rise of JavaScript frameworks such as React2, Ember3 and recently Angular 2, the effort of the W3C to standardize a web-native component system, pattern libraries and style guides being considered the “right way” to build web applications, and many other things have illuminated this revolution.
ButtonReact component written with styled components. (View large version5)
Best Practices In Component-Based Systems Link
As we’ve built more and more apps with components, we’ve discovered some best practices when working with them. I want to talk about three main ones today: building small, focused and independent components; splitting container and presentational components; and having single-use CSS class names.
Further Reading on SmashingMag: Link
- Styling Web Components Using A Shared Style Sheet6
- A Glimpse Into The Future With React Native For Web7
- Finally, CSS In JavaScript! Meet CSSX8
Build-Small Components Link
Instead of relying on classes for composition, use components to your advantage and compose them together! For example, imagine a
Button component that renders
<button class="btn"> to the DOM. One could also render a bigger, more important button. Making a bigger button would be as easy as attaching the
btn--primary class in the DOM:
<button class="btn btn--primary">.
Instead of forcing users of the component to know which particular class to attach, the
Button component should have a
primary property. Making a primary button would be as easy as
<Button primary />! Here is how we could implement this:
// Button.js function Button(props) { const className = `btn${props.primary ? ' btn—-primary' : ''}` return ( <button className={className}>{props.children}</button> ); }
Now, users no longer need to know which particular class it applies; they just render a primary button! What happens when the
primary property is set is an implementation detail of the component. Changing the styling, classes or behavior of the button now requires editing only a single file where the component is created, instead of hundreds of files where it is used!
Split Container and Presentational Components Link
With React, some of your components may have state associated with them. Try to split components that handle data and/or logic (for example, data formatting) from components that handle styling. By separating these two concerns, reasoning about changes in your code base will be a lot easier!
If the back-end API format has to change, all you have to do is go into your container components and make sure you render the same presentational components as before, even with the new format, and everything will work perfectly fine!
On the other hand, if the visual design or user experiences of your app have to change, all you have to do is go into your presentational components and make sure they look correct on their own. Because these components don’t care about when and where they’re rendered, and you haven’t changed which components get rendered, everything will work perfectly fine!
By separating these two types of components, you avoid doing multiple unrelated changes at the same time, thus avoiding accidental errors!
Have Single-Use Class Names Link
Going back to our
Button component, it has a
.btn class. Changing the styles of that class should not affect anything except the
Button! If changing the
background-color in my
.btn class messes up the layout of the header and gives the footer two columns instead of three, then something is wrong. That violates the entire premise of having independent components!
This essentially boils down to using every class in your CSS only once (outside of “mixins” like
.clearfix). This way, bugs like the one above can never happen.
The problem, as always, is us humans. Ever encountered a bug in a program? It was only there because a human put it there. If programs could exist without humans, then bugs would not be a thing. Human error accounts for every single bug you’ve ever found and squashed.
There is a famous joke9 in the front-end development world:
Two CSS properties walk into a bar. A barstool in an entirely different bar falls over.
The reception and repetition this joke has gotten tells you how many developers have seen this type of bug before. It happens, especially in teams, no matter how hard you try to avoid it.
With that and a few other things in mind, Glen Maddern10 and I sat down and started thinking about styling in this new era. We didn’t want to reinvent or get rid of CSS; it’s a language that’s made for styling and that browsers natively support! Let’s instead take the best parts of CSS and make human error in component-based systems almost impossible.
Enforcing Best Practices Link
The basic idea of styled components is to enforce best practices by removing the mapping between styles and components. If you think about any styling method you’ve used, there is always a mapping between a style fragment and your HTML.
With standard CSS, this would be a class name (or maybe an ID). With styles in JavaScript libraries in React, it’s either setting a class from a variable or passing a JavaScript object to the
style property.
Because we want to use each class only once, what if we just removed that mapping?
As it turns out, by doing so, we also enforce the split between container and presentational components, and we make sure that developers can only build small and focused components!
Another interesting feature of styled components is that it allows you to write actual CSS in your JavaScript (not just CSS-as-JavaScript objects). It leverages an infrequently used feature of ECMAScript 2015 (the new version of the JavaScript standard), called tagged template literals, to make that work a pleasant experience for the developer.
The Basics Link
Now, you might be wondering what that looks like. Well, let’s take a look!
const Title = styled.h1` color: palevioletred; font-size: 1.5em; text-align: center; `;
You can now use this React component like any other:
<Wrapper> <Title>Hello World, this is my first styled component!</Title> </Wrapper>
Quite a few things are going on here, so let’s dissect this code snippet.
styled.h1 is a function that, when called, returns a React component that renders an
<h1> into the DOM. If you’re wondering, “Where do we call that function? I see only backticks, no parentheses!” that’s exactly where the ECMAScript 2015 features come into play.
What you’re seeing above is a tagged template literal14, which is a new feature of JavaScript the language! (No special tooling is needed to use styled-components.) You can call functions with backticks (like
styled.h1``), and they will receive the string passed in as the first argument. As we go along, you’ll see how this differs from calling functions normally with parentheses, but let’s leave it at this for now!
So, this
styled.h1 call returns a React component. This React component has a class attached to it that styled components automatically generates and uniquifies. This class name has the styles associated with it that you pass to the template literal!
Summed up, this means that the
styled.h1 call returns a React component that has the styles applied that you pass to the template literal!
Full CSS Support Link
Because styled-components is just CSS, it supports all of CSS perfectly fine! Media queries, pseudo-selectors, even nesting just work! We are generating a class name and injecting the CSS into the DOM; so, whatever works in CSS works with styled-components, too.
const Input = styled.input` font-size: 1.25em; border: none; background: papayawhip; /* ...more styles here... */ &:hover { box-shadow: inset 1px 1px 2px rgba(0,0,0,0.1); } @media (min-width: 650px) { font-size: 1.5em; } `;
This
Input component will now have nice hover styles and will resize itself to be a bit bigger on large screens. Let’s see what one of these inputs looks like with and without a placeholder:
As you can see, making a container component that has styling or making a presentational component that has logic is impossible. We are also building a lot of small components and combining them into bigger containers, and because there are no visible classes, we cannot use them more than once!
Essentially, by using styled-components, we have to build a good component system — there is no other way! It enforces the best practices for us — no special architectural code review needed.
Wrapping Up Link
Styled components offers a lot more great features, such as built-in theming and full React Native support. I encourage you to dive into the documentation18 and try it out on one of your projects! Not having to worry about best practices makes the development experience so much better and quicker. I’m obviously very biased, but I don’t ever want to go back to another way of styling React apps.
Here are a few miscellaneous links related to styles in JavaScript that aren’t specific to styled components but that talk about the topic more generally:
- “React JS Style Components19” (video), Michael Chan, Full Stack Talks
An amazing talk about leveraging components as a styling construct. If you’re using React and haven’t heard this talk yet, stop what you’re doing and watch it right now!
- “The magic behind 💅 styled-components20“, Max Stoiber
This article by yours truly dives deep into tagged template literals, how they work and why they are super useful, based on the example of styled-components.
- “The Future of Reusable CSS21” (video), Glen Maddern, ColdFront16
This talk by styled-components’ cocreator doesn’t talk about the library itself, but explains how theming component-based systems should work. A lot of these ideas have made their way into the library!
- “Rendering Khan Academy’s Learn Menu Wherever I Please22,” Jordan Scales
A great article that documents the move of a complex code base from a Handlebars and LESS combo to React and styles in JavaScript. Highly recommended if you’re not sure whether either React or Styles in JavaScript are for you!
(rb, vf, il, yk, al)
Footnotes Link
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11-
- 12-
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
↑ Back to top Tweet itShare on Facebook | https://www.smashingmagazine.com/2017/01/styled-components-enforcing-best-practices-component-based-systems/?utm_source=frontendfocus&utm_medium=email | CC-MAIN-2017-17 | refinedweb | 1,815 | 62.58 |
A Voice for the ICON Community
ICONSENSUS is nearly here and staking will begin in less than a week on August 26th! This will consist of a pre-vote period, in which ICONists can stake their ICX using the ICONex official ICON wallet and be rewarded with an estimated ~15% annual return (based on 30% of network staked). ICONex will allow for users to choose which P-Rep(s) to vote for. I personally recommend voting for multiple P-Reps since there will be 22 P-Reps running the ICON ecosystem as main P-Reps (and 78 sub P-Reps). ICONists will receive the same delegation rate % regardless if the P-Reps they vote for are a main P-Rep in the top 22 or a sub P-Rep. All P-Reps are expected to contribute to the ecosystem, however, the higher rank P-Reps will receive more rewards. The main P-Reps should be producing more for the ecosystem than the sub P-Reps, due to the difference in votes, and subsequent rewards. For more information on staking and FAQs, please go here.
We previously wrote about what P-Reps are and how to make good decisions in P-Rep selection in this article. For those who didn’t read it, we have a condensed TLDR: P-Reps will run and Govern the ICON network. They will be rewarded with ICX to cover their efforts and expenses. P-Reps should be expected to contribute to the ICON ecosystem beyond the minimum required roles of running an ICON node and participating in ICON Governance. P-Reps are diverse and present varying strengths, weaknesses, and proposed plans. It is important for ICONists to vote for P-Rep teams who embody their values. ICONists should also follow the team in order to keep them accountable on their promises, withdrawing votes in favor of other teams if the P-Rep does not produce. We polled the ICON community to see what they were most looking for in a P-Rep team and found community involvement as the #1 choice, followed by using rewards to improve the ICON ecosystem at #2, and involvement in ICON projects as #3. The entire poll results are shown in Figure 1.
Many P-Reps have been contributing already to ICON, through content creation, software development, and more. Many are also engaging in social media channels with ICONists. This is important for ICONists to get to know the P-Reps so they can vote properly, based on their preferences.
NorskKiwi, a mod for Reddit and member of the ICONation team actually went ahead and setup an AMA with P-Reps on Reddit. This was an event where ICONists could post questions and P-Reps would chime in to answer them. The event was a huge success, culminating in 229 comments and 10 P-Rep teams participating (ICONation, Ubik Capital, Rhizome, ICX Station, Pocket/Figment, Chainode Capital, Piconbello, Blockmove, Gilga, and Newroad Capital). There are other P-Reps who have been active in the community but unfortunately couldn’t be there due to scheduling constraints. I encourage all ICONists to engage in different mediums, watch videos about the P-Reps, read articles, and talk to them to learn more about them! The full thread from the AMA can be seen here.
This AMA gave a chance to get further insight into the practices of different teams and learn more about them. For a full overview of all P-Rep proposals, please go to the ICON Community website. This website offers a full overview of candidate proposals, as well as an interactive map showing locations of the different P-Reps. As of August 20th, there are 67 P-Rep candidates! The interactive map is shown in Figure 2. P-Rep candidate Pocket/Figment put together this community portal for P-Reps. It filters different P-Reps based on their background, experience, focus, and more! It’s a nice and easy to use tool to filter different P-Reps based on preference.
ICON is built upon Proof of Contribution, in which ICONists are supposed to vote for P-Reps that align with their ideals and have valued contributions. P-Reps will have the job of Governing the ICON ecosystem. As such, it is important for P-Reps to have a pulse on the community. Some teams have said they will vote and make decisions in accordance with those who stake / vote for them. This makes sense as a representative democracy.
Our team, Ubik Capital, took action on this and even before being elected made a courageous decision to gather community feedback and have a poll for consideration on a key decision in their proposal. The Ubik team wrote a reddit post detailing the decision to gather feedback and community input. Ubik is a community-focused team and dedicated to ICON success. Ubik has been a major contributor of content, very active in social media channels, and also active in development — even building a DApp called Breadcrmb that was announced as a winner in ICON’s Got Talent DApp contest. We have a very detailed and professional proposal. In this proposal, Ubik outlines giving 100% of their profit back to the community! An overview quad chart of Ubik Capital is shown below, including the allocation of these rewards.
Ubik received a lot of good feedback on the pros and cons of a specific area of the proposal. The specific area is one which encourages long-term staking to lower liquid supply of ICX. This increases the security of the ICON network and also the price of ICX through the economics of supply and demand. Ubik accomplishes this incentive by providing a higher staking reward for those who stake with 6 months. The intent is that this incentive will encourage ICONists to stake for longer periods of time, resulting in higher price of ICX and a more secure network. Based on the large amount of feedback received, Ubik decided to put the decision to keep this policy to a poll: continue using portions of their profit to encourage long-term staking, which is good for the price and security of ICX or, on the other hand, to move these profits instead to more software development, content creation, and marketing. Currently Ubik plans to use 50% of their profits for the long-term staking incentives and the other 50% of profit goes into SW development, content creation, and marketting. This provides a well-balanced distribution of rewards. Due to the pros and cons of each approach, the poll was inconclusive. As of August 21, the poll had 217 votes and is 50% to 50% (shown in Figure 3). Even if the votes were different by a few %, this would not be enough to make a major change on the proposal.
Regardless where you stand on the proposal, I think we can all agree that this type of behavior is what we need out of P-Reps. Ubik is the only P-Rep to offer long-term staking rewards at this time, which shows they are thinking of how to improve ICON and exploring uncharted territory. Ubik also showed a willingness to truly be a representative of the community and have the community’s best interest in engaging in a poll and gathering feedback, with the potential to change their policies if they received enough support in the other direction. This is what we need P-Reps to do: think outside the box and listen to the community.
The laws of supply and demand show that lower supply with the same demand will result in higher price. This is the aim for Ubik’s long-term staking incentives. The team is committed to ICON and will continue to work on developing software, creating content, and engaging with the community in parallel with the long-term incentives. Ubik plans to keep this proposal as a temporary measure. We will work to have a long-term staking reward added to the IISS protocol in order to incentivize long-term staking across the board, and actually lock tokens for longer periods of time (this will not only lower supply but also be a hindrance to exchanges staking with people’s coins, as the exchange cannot just stake for long periods of time. Exchanges staking ICX is not good for the ecosystem since then the ICONists are not voting and pulling their ICX off exchanges — thus it does not have the proof of contribution or the lock-up period). We believe long-term rewards across all P-Reps is the best case scenario, but since it does not yet exist, we are doing the best we can with what we have.
ICONSENSUS is less than a week away. We encourage everyone to pull their ICX off exchanges and put it into your ICONex wallet (available from ICON’s webpage). Please do your due diligence to research the different P-Rep candidates and vote for the ones who embody what you’re looking for, based on your preferences. Once you have done this, stake, monitor the candidate to make sure they’re keeping up with their promises and contribution, and let the good times roll! | https://medium.com/@thelionshire/a-voice-for-the-icon-community-4ca33dd68a17 | CC-MAIN-2020-50 | refinedweb | 1,534 | 59.23 |
Python Programming, news on the Voidspace Python Projects and all things techie.
Windows Annoyance 2.37 E+17: Automatic Updates Dialog
Yet another Windows Annoyance with a solution. This solution comes from 4sysops: Disable restart after Windows Automatic Updates. It is another thing I have to do with every new windows box and can never remember where to find the instructions.
Usually when Windows does an update it wants you to reboot the machine. It does give you a choice, but even if you select 'Restart Later' it will pop up the same dialog every few minutes until you do restart your machine. This is very annoying, especially it pops up whilst you are doing something and accidentally quick 'Restart Now' and then lose whatever you were working on!
Luckily the solution is very simple, but it does itself require a reboot unfortunately.
- Click Start -> Run
- Enter gpedit.msc
- Go to Local Computer Policy -> Computer Configuration -> Administrative Templates -> Windows Components -> Windows Update
- Double-click on No auto-restart for scheduled Automatic Update installation
- Enable it
- Reboot the computer (!)
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-10-18 13:27:19 | |
Excel, Big Numbers and Small Columns
Today at work I've been looking at (amongst other things), how Resolver should handle displaying numbers that are too wide for their column.
Excel (which we won't just be replicating) does a variety of different things, depending on what the situation is. As the range of things it does is slightly odd, I thought I would post it here. You never know, one day it might be helpful for someone...
- For large numbers (like one billion) excel adjusts the width of the column automatically. It doesn't shrink the column again if the number is then reduced.
- For very large numbers (like one hundred billion) it displays them in exponential format - 1E+11
- Large numbers with decimal places - it truncates the number so that all of it except the decimal point onwards is visible.
- For ordinary numbers with very thin columns it just displays '##' rather than the number.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-10-17 13:19:44 | |
Categories: Work, General Programming
Slow Builds: Distributed Build Instead of the Pipeline
InfoQ recently published an article by Amr Elssamadisy, on how pipelined builds are a bad solution to the problems caused by slow builds in conjunction with continuous integration: Is Pipelined Continuous Integration a Good Idea?
Continuous integration is one of the practises of eXtreme programming, the idea is that you have a machine (the continuous integration server) that monitors your central repository. When you checkin, the CI server does a fresh check-out and runs your full build - which needless to say will include a comprehensive automated test suite.
Developers will then get rapid feedback if they check-in code that breaks the build. This becomes a problem when your full build process becomes slow. Either developers run the full build before a checkin, meaning that it takes a long time before developers can check code in, or they run only a portion and wait for the CI server to warn you of breakage. When you have several teams (or pairs in full XP) working on code, they will probably already be building on top of code that now needs to be reverted or fixed.
Some teams have attempted to solve this problem with a 'pipeline build', where tests are run in a series of layers - the pipeline. This of course only delays the pain of failure, and merely gives the illusion of allowing more frequent checkins.
The article also quotes Julian Simpson of the famously agile Thoughtworks:.
At Resolver, we have exactly this problem. A full build now takes about two and a half hours on a fast machine and nearly an hour longer on our slow integration server (deliberately slow so that we always know that Resolver runs on slower hardware). Of this two and half hours our unit tests take about twenty-five minutes. A lot of these are really more like functional tests and could be made a lot faster. Learning to test has been a voyage of discovery for everyone in the Resolver team, and a lot of the unit tests have a live GUI loop, don't patch out dependencies or do real file / database IO. (We have several thousand unit tests and a few hundred functional tests.)
But, a lot of the functional tests can't easily be made faster. The point of functional tests is to test that the application works with as close to real user input as possible. I don't think that we should be mocking up database interactions in these situations - we want to be damn sure that Resolver works with real databases with all their quirks and bugs. Additionally, some of the tests are necessarily slow. We test printing with a print driver (actually pdfcreator) that outputs to an image. We do performance testing with large datasets and we have to repeat each of these several times to remove outliers. We also have Selenium tests for our server which aren't exactly speedy.
Often we revisit a functional test when improving a feature and find ways to make them faster (often they test too much), but readability of the tests and maintainability of our test framework is much more important that the time taken by individual tests.
Unfortunately this does impact on development. Slow builds make it harder to make checkins, which in turn makes conflicts more likely and you sometimes end up with several 'trees' waiting for a checkin and occasionally code gets lost. So what to do?
Well, we've long had a vision for a 'distributed build', and our latest hire (Kamil Dworakowski) has finally put one in place. It overlays our current build system and basically works like this:
- You run a 'prepare distributed build' script on any machine on our network - giving it a list of machines that will be running the tests
- This does all the prebuild stuff (runs pylint, builds the installers, builds documentation etc)
- It then copies the subversion tree it is run from into the 'buildshare' directories of all the machines that will be running tests
- It then copies a full list of all the tests into a database table
You then run a 'start scheduled build' script from all the slave machines (currently this is a manual step). The slave machine then pull batches of tests to run out of the table, marking them complete as it goes.
Our build process already has a webapp that shows us what builds are in process, how many tests have been run and allows us to look at tracebacks for test failures / errors even whilst the build is still in progress. The distributed build works within this system - all machines running the same scheduled build showing up as a single entry in the web app. The traceback messages include paths of course, so you can always tell on which machine individual failures happen. It also means that we can run several distributed builds without getting confused. When the build has finished, it is marked as complete with the total time taken and coloured green for success and red for failure.
At Resolver we practise pair programming, but we each have a desk and computer to call our own. This is down to the boss's experiences of doing XP in an IT shop that did pairing and so thought they only needed half the computers. Consequently all the developers felt homeless!
As a result though, at any one time we have several machines that aren't being used. Running a distributed build on three machines takes about an hour, which is a much more manageable time to get feedback from a code tree.
Perhaps this is just delaying the pain, and we really should be working on speeding up the build, but boy does it feel better.
We've recently hired (but they haven't started yet), which is two extra machines. We are also 'obsoleting' two machines (two years old) next month - which means two machines that we can dedicate to the 'build farm'.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-10-17 09:59:25 | |
Categories: Work, General Programming
Class Property Decorator
Last week I posted an entry on creating a class property with a metaclass. In the comments, a reader called Frank Benkstein suggested an alternative that is much more readable. (I updated the entry to include his suggestion.) It also happens to be the most straightforward use case for direct use of the descriptor protocol that I've seen so far.
It is easy to generalise from his code to a new type, called class_property, that can be used as a decorator in the same way as property:
class class_property(object):
def __init__(self, function):
self._function = function
def __get__(self, instance, owner):
return self._function(owner)
class new_datetime(datetime):
@class_property
def current(cls):
return cls.now()
>>> new_datetime.current
2007-10-15 19:07:29.930261
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-10-17 09:57:52 | |
Categories: Hacking, Python
Why the DLR and What is Python Used For?
Since Microsoft announced Silverlight 1.1, which includes support for the Dynamic Language Runtime and therefore IronPython, I have given several talks to .NET audiences about IronPython. A couple of times I've also been asked about IronPython by .NET folks who are talking about Silverlight and want to know more IronPython.
The two questions that seem to recur, are why did Microsoft include the DLR in Silverlight and what sort of things does Python get used for?
As I'm interested in Python advocacy, I thought I would post my answers to those questions here. Firstly they might be useful to someone else who gets asked similar questions, and secondly you might be able to help me improve my answers.
Why the DLR?
- Why did Microsoft create.
The DLR provides three key benefits:
- Developer choice of language
- Ready made scripting languages for embedding in C# / VB.NET applications
- Dynamic languages are more suited to places where runtime class creation / code generation / introspection (reflection without the pain) is needed
Additionally they.
What is Python Used For?
Python is a great general purpose language and so gets used for a wide variety of things. It also grew out of the Unix culture, which is reflected in some of its major uses.
Python is used for web development:
- Youtube is written almost entirely in Python
-.
- It is the embedded scripting language for applications like Blender and Maya
GIS (Geographical Information Services):
Python has become the 'scripting language of choice' for several major GIS applications (and some are starting to use IronPython).
System admin stuff:
- Gentoo (Linux) portage (package management) is written in Python
- Ubuntu and Pardus Linux distributions do everything they can in Python.
If you can think of any other major areas that Python gets used, or improved wording for any of this, then comment away.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-10-15 14:18:40 | |
Categories: Python, IronPython, Writing, General Programming
Blog Action Day: Looking Back from the Future
Today is Blog Action Day, with bloggers from all across the world blogging about the environment. This is me taking part.
This year was the bicentennial anniversary of the abolition of the slave trade in the UK. In 1807 the trade in slaves from Africa was banned, but it wasn't until 1833 that slavery was abolished completely throughout the British Empire.
It is easy to view the behaviour of our ancestors with disdain. History is bulging with the barbaric treatment of fellow humans by people who considered themselves enlightened and civilized. In the UK we particularly look back at the Victorian era and the way they treated the poor, placing them in workhouses, and also the appalling treatment of the mentally ill (the 'insane') in asylums. Thank goodness that things have changed, and that generally in Western society things aren't so bad.
But to the people of the day, this was the state of the art - reflecting their moral convictions and the capacity of society to provide welfare. The horror of the workhouses was still preferable to previous incarnations of English society that depended entirely on the kindness of strangers for the care of the poor. If this kindness was absent or withheld, then like much of the world today, poverty was brutally terminal.
With a focus on looking back at the brutishness of a bygone age, it is easy to wonder how history will view our society. We have iPhones and space travel, the internet and modern medicine, laws on human rights and a society that supposedly honours diversity - boy are we sophisticated and civilized compared our predecessors. Is it possible that hundreds of years from now, people will read about our actions and inactions; and shudder at our ignorance and barbarity?
In the UK we imprison tens of thousands of people that our own doctors have diagnosed as being mentally ill. We know that prison doesn't work: most people who go into prison will be back again. Yet the prisons are overcrowded and the popular press calls for harsher sentences and the building of more prisons. This is not just inhumane, it is stupid. This situation is rarely the fault of individuals, but the fault of us - society.
In the US, hundreds of thousands of black young men are imprisoned. However remote they may feel that politics is, they are disenfranchised from any possible input. What barbaric society would do this?
Particularly in the UK you might hear the argument that society can't bear the cost of proper care of all the mentally ill who are in prison. The alternatives are prohibitively expensive and it is an extremely difficult problem to solve. This may well be true, but more to the point is that most individuals don't know and don't really care. How will future generations look back on this?
Even more so the current state of the environment. Scientifically it seems beyond doubt that man's (our - your and mine) activity is causing great damage to the earth. If nothing is done to change this then great harm will occur, and it won't necessarily be just our children and their children who suffer the consequences - things are happening now.
So how will future generations see this? Didn't they know? Didn't they care? Did no-one tell them, what did they think was happening? The fools, the selfish idiots... Will this be humanity's epitaph, or merely the way we as a culture are remembered?
I'm afraid that I'm not a very good green activist. I'm trying to find my way forward in doing less harm to the environment, consuming less and being more aware. I care greatly for the earth. All of man's finest achievements still pale into insignificance beside the unimaginable complexity and elegance of fragile life. Let's not be the ones who destroy it.
Like this post? Digg it or Del.icio.us it.
Posted by Fuzzyman on 2007-10-15 13:28:52 | |
Categories: Life, Blog on Blogging
Archives
This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License.
Counter... | http://www.voidspace.org.uk/python/weblog/arch_d7_2007_10_13.shtml | CC-MAIN-2018-26 | refinedweb | 2,599 | 62.17 |
Memory Layout of Objects in Java
Last modified: June 29, 2020
1. Overview
In this tutorial, we're going to see how the JVM lays out objects and arrays in the heap.
First, we'll start with a little bit of theory. Then, we'll explore the different object and array memory layouts in different circumstances.. Ordinary Object Pointers (OOPs)
The HotSpot JVM uses a data structure called Ordinary Object Pointers (OOPS) to represent pointers to objects. All pointers (both objects and arrays) in the JVM are based on a special data structure called oopDesc. Each oopDesc describes the pointer with the following information:
- One mark word
- One, possibly compressed, klass word
The mark word describes the object header. The HotSpot JVM uses this word to store identity hashcode, biased locking pattern, locking information, and GC metadata.
Moreover, the mark word state only contains a uintptr_t, therefore, its size varies between 4 and 8 bytes in 32-bit and 64-bit architectures, respectively. Also, the mark word for biased and normal objects are different. However, we'll only consider normal objects as Java 15 is going to deprecate biased locking.
Additionally, the klass word encapsulates the language-level class information such as class name, its modifiers, superclass info, and so on.
For normal objects in Java, represented as instanceOop, the object header consists of mark and klass words plus possible alignment paddings. After the object header, there may be zero or more references to instance fields. So, that's at least 16 bytes in 64-bit architectures because of 8 bytes of the mark, 4 bytes of klass, and another 4 bytes for padding.
For arrays, represented as arrayOop, the object header contains a 4-byte array length in addition to mark, klass, and paddings. Again, that would be at least 16 bytes because of 8 bytes of the mark, 4 bytes of klass, and another 4 bytes for the array length.
Now that we know enough about theory, let's see how memory layout works in practice.
3. Setting Up JOL
To inspect the memory layout of objects in the JVM, we're going to use the Java Object Layout (JOL) quite extensively. Therefore, we need to add the jol-core dependency:
<dependency> <groupId>org.openjdk.jol</groupId> <artifactId>jol-core</artifactId> <version>0.10</version> </dependency>
4. Memory Layout Examples
Let's start by looking at the general VM details:
System.out.println(VM.current().details());
This will print:
# Running 64-bit HotSpot VM. # Objects are 8 bytes aligned. # Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes] # Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
This means that the references take 4 bytes, booleans and bytes take 1 byte, shorts and chars take 2 bytes, ints and floats take 4 bytes, and finally, longs and doubles take 8 bytes. Interestingly, they consume the same amount of memory if we use them as array elements.
Also, if we disable compressed references via -XX:-UseCompressedOops, only the reference size changes to 8 bytes:
# Field sizes by type: 8, 1, 1, 2, 2, 4, 4, 8, 8 [bytes] # Array element sizes: 8, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
4.1. Basic
Let's consider a SimpleInt class:
public class SimpleInt { private int state; }
If we print its class layout:
System.out.println(ClassLayout.parseClass(SimpleInt.class).toPrintable());
We would see something like:
SimpleInt object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 12 (object header) N/A 12 4 int SimpleInt.state N/A Instance size: 16 bytes Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
As shown above, the object header is 12 bytes, including 8 bytes of the mark and 4 bytes of klass. After that, we have 4 bytes for the int state. In total, any object from this class would consume 16 bytes.
Also, there is no value for the object header and the state because we're parsing a class layout, not an instance layout.
4.2. Identity Hash Code
The hashCode() is one of the common methods for all Java objects. When we don't declare a hashCode() method for a class, Java will use the identity hash code for it.
The identity hash code won't change for an object during its lifetime. Therefore, the HotSpot JVM stores this value in the mark word once it's computed.
Let's see the memory layout for an object instance:
SimpleInt instance = new SimpleInt(); System.out.println(ClassLayout.parseInstance(instance).toPrintable());
The HotSpot JVM computes the identity hash code lazily:
SimpleInt object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1) # mark 4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0) # mark 8 4 (object header) 9b 1b 01 f8 (10011011 00011011 00000001 11111000) (-134145125) # klass 12 4 int SimpleInt.state 0 Instance size: 16 bytes Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
As shown above, the mark word currently doesn't seem to store anything significant yet.
However, this will change if we call the System.identityHashCode() or even Object.hashCode() on the object instance:
System.out.println("The identity hash code is " + System.identityHashCode(instance)); System.out.println(ClassLayout.parseInstance(instance).toPrintable());
Now, we can spot the identity hash code as part of the mark word:
The identity hash code is 1702146597 SimpleInt object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 (object header) 01 25 b2 74 (00000001 00100101 10110010 01110100) (1957831937) 4 4 (object header) 65 00 00 00 (01100101 00000000 00000000 00000000) (101) 8 4 (object header) 9b 1b 01 f8 (10011011 00011011 00000001 11111000) (-134145125) 12 4 int SimpleInt.state 0
The HotSpot JVM stores the identity hashcode as “25 b2 74 65” in the mark word. The most significant byte is 65 since the JVM stores that value in little-endian format. Therefore, to recover the hash code value in decimal (1702146597), we have to read the “25 b2 74 65” byte sequence in reverse order:
65 74 b2 25 = 01100101 01110100 10110010 00100101 = 1702146597
4.3. Alignment
By default, the JVM adds enough padding to the object to make its size a multiple of 8.
For instance, consider the SimpleLong class:
public class SimpleLong { private long state; }
If we parse the class layout:
System.out.println(ClassLayout.parseClass(SimpleLong.class).toPrintable());
Then JOL will print the memory layout:
SimpleLong object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 12 (object header) N/A 12 4 (alignment/padding gap) 16 8 long SimpleLong.state N/A Instance size: 24 bytes Space losses: 4 bytes internal + 0 bytes external = 4 bytes total
As shown above, the object header and the long state consume 20 bytes in total. To make this size a multiple of 8 bytes, the JVM adds 4 bytes of padding.
We can also change the default alignment size via the -XX:ObjectAlignmentInBytes tuning flag. For instance, for the same class, the memory layout with -XX:ObjectAlignmentInBytes=16 would be:
SimpleLong object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 12 (object header) N/A 12 4 (alignment/padding gap) 16 8 long SimpleLong.state N/A 24 8 (loss due to the next object alignment) Instance size: 32 bytes Space losses: 4 bytes internal + 8 bytes external = 12 bytes total
The object header and the long variable still consume 20 bytes in total. So, we should add 12 more bytes to make it a multiple of 16.
As shown above, it adds 4 internal padding bytes to start the long variable at offset 16 (enabling more aligned access). Then It adds the remaining 8 bytes after the long variable.
4.4. Field Packing
When a class has multiple fields, the JVM may distribute those fields in such a way as to minimize padding waste. For example, consider the FieldsArrangement class:
public class FieldsArrangement { private boolean first; private char second; private double third; private int fourth; private boolean fifth; }
The field declaration order and their order in memory layout are different:
OFFSET SIZE TYPE DESCRIPTION VALUE 0 12 (object header) N/A 12 4 int FieldsArrangement.fourth N/A 16 8 double FieldsArrangement.third N/A 24 2 char FieldsArrangement.second N/A 26 1 boolean FieldsArrangement.first N/A 27 1 boolean FieldsArrangement.fifth N/A 28 4 (loss due to the next object alignment)
The main motivation behind this is to minimize padding waste.
4.5. Locking
The JVM also maintains the lock information inside the mark word. Let's see this in action:
public class Lock {}
If we create an instance of this class, the memory layout for it would be:
Lock object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 (object header) 01 00 00 00 4 4 (object header) 00 00 00 00 8 4 (object header) 85 23 02 f8 12 4 (loss due to the next object alignment) Instance size: 16 bytes
However, if we synchronize on this instance:
synchronized (lock) { System.out.println(ClassLayout.parseInstance(lock).toPrintable()); }
The memory layout changes to:
Lock object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 (object header) f0 78 12 03 4 4 (object header) 00 70 00 00 8 4 (object header) 85 23 02 f8 12 4 (loss due to the next object alignment)
As shown above, the bit-pattern for the mark word changes when we're holding the monitor lock.
4.6. Age and Tenuring
To promote an object to the old generation (in generational GCs, of course), the JVM needs to keep track of the number of survivals for each object. As mentioned earlier, the JVM also maintains this information inside the mark word.
To simulate minor GCs, we're going to create lots of garbage by assigning an object to a volatile variable. This way we can prevent possible dead code eliminations by the JIT compiler:
volatile Object consumer; Object instance = new Object(); long lastAddr = VM.current().addressOf(instance); ClassLayout layout = ClassLayout.parseInstance(instance); for (int i = 0; i < 10_000; i++) { long currentAddr = VM.current().addressOf(instance); if (currentAddr != lastAddr) { System.out.println(layout.toPrintable()); } for (int j = 0; j < 10_000; j++) { consumer = new Object(); } lastAddr = currentAddr; }
Every time a live object's address changes, that's probably because of minor GC and movement between survivor spaces. For each change, we also print the new object layout to see the aging object.
Here's how the first 4 bytes of the mark word changes over time:
09 00 00 00 (00001001 00000000 00000000 00000000) ^^^^ 11 00 00 00 (00010001 00000000 00000000 00000000) ^^^^ 19 00 00 00 (00011001 00000000 00000000 00000000) ^^^^ 21 00 00 00 (00100001 00000000 00000000 00000000) ^^^^ 29 00 00 00 (00101001 00000000 00000000 00000000) ^^^^ 31 00 00 00 (00110001 00000000 00000000 00000000) ^^^^ 31 00 00 00 (00110001 00000000 00000000 00000000) ^^^^
4.7. False Sharing and @Contended
The jdk.internal.vm.annotation.Contended annotation (or sun.misc.Contended on Java 8) is a hint for the JVM to isolate the annotated fields to avoid false sharing.
Put simply, the Contended annotation adds some paddings around each annotated field to isolate each field on its own cache line. Consequently, this will impact the memory layout.
To better understand this, let's consider an example:
public class Isolated { @Contended private int v1; @Contended private long v2; }
If we inspect the memory layout of this class, we'll see something like:
Isolated object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 12 (object header) N/A 12 128 (alignment/padding gap) 140 4 int Isolated.i N/A 144 128 (alignment/padding gap) 272 8 long Isolated.l N/A Instance size: 280 bytes Space losses: 256 bytes internal + 0 bytes external = 256 bytes total
As shown above, the JVM adds 128 bytes of padding around each annotated field. Cache line size in most modern machines is around 64/128 bytes, hence the 128 bytes padding. Of course, we can control the Contended padding size with -XX:ContendedPaddingWidth tuning flag.
Please note that the Contended annotation is JDK internal, therefore we should avoid using it.
Also, we should run our code with the -XX:-RestrictContended tuning flag; otherwise, the annotation wouldn't take effect. Basically, by default, this annotation is meant for internal-only usage, and disabling the RestrictContended will unlock this feature for public APIs.
4.8. Arrays
As we mentioned before, the array length is also part of the array oop. For instance, for a boolean array containing 3 elements:
boolean[] booleans = new boolean[3]; System.out.println(ClassLayout.parseInstance(booleans).toPrintable());
The memory layout looks like:
[Z object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 (object header) 01 00 00 00 # mark 4 4 (object header) 00 00 00 00 # mark 8 4 (object header) 05 00 00 f8 # klass 12 4 (object header) 03 00 00 00 # array length 16 3 boolean [Z.<elements> N/A 19 5 (loss due to the next object alignment) Instance size: 24 bytes Space losses: 0 bytes internal + 5 bytes external = 5 bytes total
Here, we have 16 bytes of object header containing 8 bytes of mark word, 4 bytes of klass word, and 4 bytes of length. Immediately after the object header, we have 3 bytes for a boolean array with 3 elements.
4.9. Compressed References
So far, our examples were executed in a 64-bit architecture with compressed references enabled.
With 8 bytes alignment, we can use up to 32 GB of heap with compressed references. If we go beyond this limitation or even disable the compressed references manually, then the klass word would consume 8 bytes instead of 4.
Let's see the memory layout for the same array example when the compressed oops are disabled with the -XX:-UseCompressedOops tuning flag:
[Z object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 4 (object header) 01 00 00 00 # mark 4 4 (object header) 00 00 00 00 # mark 8 4 (object header) 28 60 d2 11 # klass 12 4 (object header) 01 00 00 00 # klass 16 4 (object header) 03 00 00 00 # length 20 4 (alignment/padding gap) 24 3 boolean [Z.<elements> N/A 27 5 (loss due to the next object alignment)
As promised, now there are 4 more bytes for the klass word.
5. Conclusion
In this tutorial, we saw how the JVM lays out objects and arrays in the heap.
For a more detailed exploration, it's highly recommended to check out the oops section of the JVM source code. Also, Aleksey Shipilëv has a much more in-depth article in this area.
Moreover, more examples of JOL are available as part of the project source code.
As usual, all the examples are available over on GitHub. | https://www.baeldung.com/java-memory-layout | CC-MAIN-2021-21 | refinedweb | 2,470 | 58.32 |
On 17 March 2016 16:06:10 GMT+00:00, Paul Benedict <pbened...@apache.org> wrote: >This question is not about Tomcat per se, but it does affect it. It's >really about the EE specification in regards to any servlet container. >I'd >like to get professional opinions on this part of the specification. > >I am quoting from EE 5.0 (see link below), section 8.3.1, paragraph 3c: > >The Deployer must... "Assign a context root for each web module >included in >the Java EE application. The context root is a relative name in the web >namespace for the application. Each web module must be given a distinct >and >non-overlapping name for its context root." > >So given this scenario: >/context/something <-- context is /context >/context/something/somethingelse <-- context is /context/something > >The specification puts no limitations on the context root character set >(so >it can include a slash). With that said, would you consider these >"overlapping" contexts? I noticed one application server supporting >this >paradigm without issue, but it seems like a violation of the >specification. >Please advise. > >Also, since Tomcat doesn't support "applications" (EAR?), how should >the >specification be interpreted in the absence of that artifact? > >[1] > > >Cheers, >Paul
That requirement makes no sense as I understand it. You always have overlapping context paths because of the ROOT context. I think this is one for the EG to clarify what they meant. It is also worth noting that the servlet spec explicitly states thst requests are matched against the longest matching context path. Mark | https://www.mail-archive.com/users@tomcat.apache.org/msg121490.html | CC-MAIN-2021-25 | refinedweb | 259 | 58.58 |
I.
The setting is shown below:
If you don't know where your
php.ini file is, you can locate it by creating a
.php script that contains the following text:
The top section of the output will have a row listing where PHP is looking for
php.ini:
Figure 1. Where PHP looks for.
So, where does user input come from? The first source we'll look at is
GET,,
COOKIE will be created in the global namespace, as well as in the
$_GET,
$_POST, or
$_COOKIE arrays.
Let's look at an example of how this works, and why it's important:
Listing 1. Security with
COOKIEs:
Listing 2. Improved security with
COOKIEs.
Learn
- PHP.net is the starting point for all things PHP.
- Read the Type Juggling chapter of the PHP Manual.
- PHP Builder is popular PHP site with tutorials and code libraries.
- Zend Technologies contains plenty of useful links and information about PHP. Zend is the PHP Optimizer.
- Read Andi Gutmans', Stig Bakken's, and Derick Rethans' book PHP 5 Power Programming and its PDF version.
- Visit IBM developerWorks PHP project resources to learn more about PHP.
- Stay current with developerWorks technical events and webcasts.
- Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products.
Get products and technologies
- Get evaluation products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere® and start building applications and deploying them on IBM middleware. Select the Linux® or Windows version of the Software Evaluation Kit (SEK).
- Innovate your next open source development project with IBM trial software, available for download or on DVD.
Discuss
- Get involved in the developerWorks community by participating in developerWorks blogs.
Chuck Hagenbuch is a senior technical consultant for Zend Technologies. He's been programming in PHP for more than eight years, including founding The Horde Project. | http://www.ibm.com/developerworks/library/os-php1/ | crawl-003 | refinedweb | 320 | 58.89 |
Groovy - JSON
This chapter covers how to we can use the Groovy language for parsing and producing JSON objects.
JSON Functions
Parsing Data using JsonSlurper
JsonSlurper is a class that parses JSON text or reader content into Groovy data Structures such as maps, lists and primitive types like Integer, Double, Boolean and String.
Syntax
def slurper = new JsonSlurper()
JSON slurper parses text or reader content into a data structure of lists and maps.
The JsonSlurper class comes with a couple of variants for parser implementations. Sometimes you may have different requirements when it comes to parsing certain strings. Let’s take an instance wherein one needs to read the JSON which is returned from the response from a web server. In such a case it’s beneficial to use the parser JsonParserLax variant. This parsee allows comments in the JSON text as well as no quote strings etc. To specify this sort of parser you need to use JsonParserType.LAX parser type when defining an object of the JsonSlurper.
Let’s see an example of this given below. The example is for getting JSON data from a web server using the http module. For this type of traversal, the best option is to have the parser type set to JsonParserLax variant.
http.request( GET, TEXT ) { headers.Accept = 'application/json' headers.'User-Agent' = USER_AGENT response.success = { res, rd -> def jsonText = rd.text //Setting the parser type to JsonParserLax def parser = new JsonSlurper().setType(JsonParserType.LAX) def jsonResp = parser.parseText(jsonText) } }
Similarly the following additional parser types are available in Groovy −
The JsonParserCharArray parser basically takes a JSON string and operates on the underlying character array. During value conversion it copies character sub-arrays (a mechanism known as "chopping") and operates on them individually.
The JsonFastParser is a special variant of the JsonParserCharArray and is the fastest parser. JsonFastParser is also known as the index-overlay parser. During parsing of the given JSON String it tries as hard as possible to avoid creating new char arrays or String instances. It just keeps pointers to the underlying original character array only. In addition, it defers object creation as late as possible.
The JsonParserUsingCharacterSource is a special parser for very large files. It uses a technique called "character windowing" to parse large JSON files (large means files over 2MB size in this case) with constant performance characteristics.
Parsing Text
Let’s have a look at some examples of how we can use the JsonSlurper class.
import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() def object = jsonSlurper.parseText('{ "name": "John", "ID" : "1"}') println(object.name); println(object.ID); } }
In the above example, we are −
First creating an instance of the JsonSlurper class
We are then using the parseText function of the JsonSlurper class to parse some JSON text.
When we get the object, you can see that we can actually access the values in the JSON string via the key.
The output of the above program is given below −
John 1
Parsing List of Integers
Let’s take a look at another example of the JsonSlurper parsing method. In the following example, we are pasing a list of integers. You will notice from The following codethat we are able to use the List method of each and pass a closure to it.
import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() Object lst = jsonSlurper.parseText('{ "List": [2, 3, 4, 5] }') lst.each { println it } } }
The output of the above program is given below −
List=[2, 3, 4, 5]
Parsing List of Primitive Data types
The JSON parser also supports the primitive data types of string, number, object, true, false and null. The JsonSlurper class converts these JSON types into corresponding Groovy types.
The following example shows how to use the JsonSlurper to parse a JSON string. And here you can see that the JsonSlurper is able to parse the individual items into their respective primitive types.
import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() def obj = jsonSlurper.parseText ''' {"Integer": 12, "fraction": 12.55, "double": 12e13}''' println(obj.Integer); println(obj.fraction); println(obj.double); } }
The output of the above program is given below −
12 12.55 1.2E+14
JsonOutput
Now let’s talk about how to print output in Json. This can be done by the JsonOutput method. This method is responsible for serialising Groovy objects into JSON strings.
Syntax
Static string JsonOutput.toJson(datatype obj)
Parameters − The parameters can be an object of a datatype – Number, Boolean, character,String, Date, Map, closure etc.
Return type − The return type is a json string.
Example
Following is a simple example of how this can be achieved.
import groovy.json.JsonOutput class Example { static void main(String[] args) { def output = JsonOutput.toJson([name: 'John', ID: 1]) println(output); } }
The output of the above program is given below −
{"name":"John","ID":1}
The JsonOutput can also be used for plain old groovy objects. In the following example, you can see that we are actually passing objects of the type Student to the JsonOutput method.
import groovy.json.JsonOutput class Example { static void main(String[] args) { def output = JsonOutput.toJson([ new Student(name: 'John',ID:1), new Student(name: 'Mark',ID:2)]) println(output); } } class Student { String name int ID; }
The output of the above program is given below −
[{"name":"John","ID":1},{"name":"Mark","ID":2}] | https://www.tutorialspoint.com/groovy/groovy_json.htm | CC-MAIN-2018-05 | refinedweb | 909 | 56.96 |
In this section we will see various methods of String class that are defined for various purposes. We will use some of them methods in a simple example.
String class is belongs to the java.lang package. It is a final class i.e. it can not be extended. Because the String class is defined as final so its object are immutable however, String buffers are mutable. This class has defined various of methods to perform operations on strings. Some of these methods are as follows :
Note : Many methods in String class are overloaded. Here we have not discussed all methods of String class. To read all methods of String class please refer to Java doc.
Example
Here an example is being given which will demonstrate you about how to use methods of String class in Java. In this example I will create a Java file where I will use some of the methods of String class.
StringFunctionsExample.java
public class StringFunctionsExample { public static void main(String[] args) { String str1 = "RoseIndia"; String str2 = "roseIndia"; String str3 = "Delhi"; String str4 = "india"; System.out.println("1. Third character of String '"+str1+"' : "+str1.charAt(2)); System.out.println("2. Length of String '"+str1+"' : "+str1.length()); System.out.println("3. Unicode of "+str1.charAt(str1.length()-1)+" : "+str1.codePointAt(str1.length()-1)); int compare = str1.compareToIgnoreCase(str2); if(compare == 0) { System.out.println("4. "+str1+" and "+str2+" both string is same when compare them and ignoring case differences"); } else if(compare > 0 ) { System.out.println("4. "+str1+" is less than "+str2); } else { System.out.println("4. "+str1+" is greater than "+str2); } System.out.println("5. After Concating "+str1+" and "+str3+" : "+str1.concat(str3)); boolean bol = str1.endsWith("India"); System.out.println("6. Whether the string '"+str1+"' has suffix '"+str4+"' : "+bol); System.out.println("7. Index of character "+str1.charAt(str1.length()-2)+" in String '"+str1+"' : "+str1.indexOf(str1.charAt(str1.length()-2))); System.out.println("Converting "+str1+" to lower case : "+str1.toLowerCase()); System.out.println("Converting "+str2+" to upper case : "+str1.toUpperCase()); } }: String Functions In Java
Post your Comment | http://roseindia.net/java/beginners/string-functions-in-java.shtml | CC-MAIN-2015-35 | refinedweb | 345 | 53.27 |
Posted 08 Apr
Link to this post
Hi
Just need some help converting a VB grid to C#.
Binding is to a datatable deserialised from JSON using NewtonSoft.Json library.
I have the following line in VB that works OK:
If e.Appointment.DataItem("UsageType") = 1 Then...
However the same line in C#
if (e.Appointment.DataItem("UsageType") == 1) {
Errors with a red squiggle under DataItem with the following text:-
SchedulerEventArgs does not contain a definition for Dataitem and no extension method DataItem accepting a first argument of type SchedulerEventArgs could be found.
I have the following using statements:
using Telerik.Web.UI;
using Telerik.Web;
using System.Data;
Posted 13 Apr
Link to this post
(e.Appointment.DataItem as DataRowView).Row["UsageType"]
Posted 13 Apr
in reply to
Konstantin Dikov
Link to this post
you are trying to access (somewhere in your code) the DataItem through the event arguments directly YES in the AppointmentDataBound event, this e.Appointment.DataItem("UsageType") works OK in VB, but not C#.
This is the way I'm trying to use it:
e.Appointment.BackColor = System.Drawing.ColorTranslator.FromHtml((e.Appointment.DataItem as DataRowView).Row["Appointmentcolour"]);
The whole line is underlined, and the dataitem on hover says - Object Appointment.Dataitem{get; Set;} gets or sets the dataitem represented by tge appointment object in the radscheduler control. Canot convert from object to string.
Andy
Posted 14 Apr
Link to this post
e.Appointment.BackColor = System.Drawing.ColorTranslator.FromHtml((e.Appointment.DataItem
as
DataRowView).Row[
"Appointmentcolour"
].To | http://www.telerik.com/forums/problem-referencing-dataitem-from-c | CC-MAIN-2016-44 | refinedweb | 251 | 52.26 |
This action might not be possible to undo. Are you sure you want to continue?
11/06/2012
text
original
Jaroslav Šoltýs
Linux Kernel 2.6 Documentation
Master thesis Thesis advisor: RNDr. Jaroslav Janáček
Bratislava
2006
By this I declare that I wrote this master thesis by myself, only with the help of the referenced literature and internet resources, under the supervision of my thesis advisor. Bratislava, 2006 Jaroslav Šoltýs
Abstract
This thesis is a study of internal working and interfaces of Linux kernel version 2.6. It emphasizes differences towards kernel 2.4 and it tries to introduce this problems to reader knowledgable only in common principles of operating systems. The thesis starts with briefing of kernel subsystems and continues with deeper analysis of important issues like various locking, semaphores and other synchronization mechanisms, suitable data structures, interrupt handling, atomic operations, device driver model and memory allocation. Process management and new scheduler with support for multiprocessing and NUMA architectures and preemption are explored deeply. The core of the work is concluded with description of loadable kernel module creation together with an exemplar module.
i
The first has been achieved by merging ucLinux (branch of Linux for embedded platforms) to main kernel.6 and the final 2. I did indeed start before the stable 2. Linux now scales pretty well on both ends: embedded platforms and large servers with either SMP or NUMA support.6. shows user the difference between monolithic an mikrokernel and mentions Unix traditions. Also the documentation for older version was incosistent and scattered throughout the whole web.Preface Fall 2003 brought many testing version of Linux kernel 2.6) and write documentation. semaphores. Thesis Contents Chapter 1: An Informal Introduction to Operating Systems describes the basic ideas behind an operating system. that could help kernel beginners.6. while the new scheduler written during 2. since existing locking mechanisms has been ii .0 came out. mutexes and other synchronisation entities. Chapter 3: Synchronization and Workflow Concurrency takes care about locks.5 development branch offers now preemption inside kernel and is able to take full use of multiple CPUs.0 was released on December 17th 2003.6. My task was to study 2. There was very little documentation to be found concerning this new kernel at the time I started working on this thesis. Chapter 2: Subsystems Overview lists subsystems and describes each one with particular attention to new features introduced in 2.6 kernel (with special attention to new features in 2. This new facts (together with unified driver model) increase demands on device driver writers’ know-how. A lot of new interesting features and improved hardware support were teasing user to try it. Issues with preemption are also mentioned. It also contains the roughest introduction to Linux kernel and it’s development process. Reader is expected to have some preliminary knowledge about operating systems and some basic understanding of hardware.
iii .c]in Linux kernel source tree are enclosed in square brackets. disabling local interrupts and memory barriers. • Files and directories like [kernel/sched. • Notices are emphasized with slanted font. Chapter 10: Modules contains an exemplary loadable kernel module that exports its parameter using sysfs and explains various macros that could help with module development.h>. The last issues in this chapter are perCPU variables. such as page allocation. which are intensively used wherever possible. • Include files are shown as in ordinary C source code: <linux/list. Chapter 7: Process management and Scheduling concerns in scheduler.6 describes kernel object architecture and sysfs hierarchy. function() or MACRO definitions and related things. Typographic Conventions Typographic conventions used in this thesis are simple and intuitive: • Typewriter-like font denotes source code. • Warnings and important words are printed in bold. interface for device driver writers and user space event delivery mechanism. Chapter 4: Linked Lists mentions linked lists. manipulate strings and some other common routines.improved to cope with these issues. process life cycle and related issues. slab allocation and virtual memory allocation. Chapter 5: Memory Allocation deals with allocating and releasing memory using various approches. Also one very interesting mechanism called read-copy-update is described. Chapter 8: New Driver Model in 2. Chapter 6: Handling Interrupts contain all necessary information on how to work with hardware interrupts and tasklet interface. The complicated variation protected by RCU is also included. Chapter 9: Common Routines and Helper Macros will introduce various macros to access user space memory.
. . . 23 Read/Write Semaphores . . . . . . . . . . . . . . . . . . .9 System Calls . . . . . .3 20 Spinlock . . . . . . . . . . . . . . . . . . . Memory Management . . . . . . . . . . 17 2. . . . . . . . . . . . . . . . . . . . . . . Concerning Traditional Unix Principles .3 2. . . . . . Overview of the Linux Kernel . . . .10 Networking . . . . 1 An Informal Introduction to Operating Systems 1. . . . . . . 11 Signals and Inter-Process Communication . . 10 Synchronization and Workflow Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . .4 1. . . . . . . . . . . . . . . . . .3 1. .1 2. . . . .7 2. 12 Virtual File System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 1. . . .Contents Abstract Preface Thesis Contents . . . . 21 Semaphores . 24 iv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 2. . . 19 3 Synchronization and Workflow Concurrency 3. . . . . . . . . . Typographic Conventions . . . . .1 3. . . . i ii ii iii 1 2 3 3 5 5 7 7 8 9 2 Subsystems Overview 2. . . . User Mode and Kernel Mode . . . . . . . . . . . . . . . Interrupts and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 1. . 14 New Driver Model and Sysfs . . . . . . . . .6 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 2. . . Process Management and Execution . . . . . . . . . . . . . . . . . . . 10 Time and Timers . . . . . . . . . About Kernel and Its Development . .11 Linked Lists and Their Implementation . . . . .2 2. . . . . . . . . . . . . . . . . . . . . . . . . .8 2. .5 Monolithic or Micro Kernel? . . . . . . . . . .2 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . 58 Priority . . . . . . . 27 Futexes . . . .1. . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 39 List API . . 25 New Mutexes . 86 Waitqueues . . . . . . . . . . .2 5. 60 Runqueues . . . . . . . . . . . . . . . . . . . . . .7 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Process Forking . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . .1 7. . . . . . . . . . 63 Task State Management and Switching . 109 Thread API . . . . . . .1 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 3. . . . . . . . . . . . . . . . . . . . . . . . . . . .8 7. . . . . . . . . . . . . . 47 Page Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 RCU Protected Lists . . . . . 36 3. . 34 3. . . . . . . . . . . . .3 Slab Memory Allocation . . . . . . . . . .11 Read-copy Update . 33 3. . 29 Seqlock and Seqcount . . . . . . . . 94 Workqueues and Kernel Threads . . . .1. . . . . . . . . . . . . . . . . . . .10 Disabling Local IRQs . . . . . . . . . . . . . . . . . 30 Atomic Operations . . . . . . . . . . . . . . .4 7. . . . . . 52 56 7 Process Management and Scheduling 7.6 3. . . . . . .13 Memory Barriers . . . . . . . . . . 48 50 6 Handling Interrupts 6. . . . . . . 61 Load Balancing and Migration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9 Completions . . . . . . . . . . . . . . . .2 7. . . . . . . . . . . . . . . . . . 113 v . . . .1 4. . . . . . . . . . . . . 50 Softirqs and Tasklets . . . . . . 79 Process Termination . . . . . . . . . . . . . . . . . . . .5 7.1 5. . . . . . . . . . . . . .3. . . . . . . . . . . . . . .4 7. . . . . . . . . . . . . .3 7. . . . . . . . . . . . . . . . .8 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 44 5 Memory Allocation 5.12 Per-CPU Variables . 101 PIDs . . . . . . . . . . . . . . . . . . . .2 Hardware Interrupts . . . . . . . . . . . . . . . . . . . .5 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 Various Other Process Management Functions . . . . . . . 44 Virtual Memory Allocation . . 107 Process Accounting for Linux . . . . . . . . . . . . . . . . . .9 Scheduler . 38 4 Linked lists 4. . . . . 32 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 3.3 7. . . . . . . . . . . . .1 6. . . 28 Preemption . .6 7.2 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . 133 . .2 8. . . . . . . . . . . .6 8. .1 9. . . . . . . . 151 11 Conclusion Bibliography Glossary Abstract in Slovak Language 152 154 157 160 vi . . . . . . . . 146 10. . . . . . . . . . . . . . . . . . . . . . . . . . .2 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Exporting Symbols . . .3 String Manipulation . . . . . . . . . . . . . . . . . . 118 . . . . . . . . . .2 9.8 New Driver Model in 2. . . .3 Module Properties . . . . . . 120 Subsystem API . . . . . . .1. . . . . .1. . . . . . . . 122 Bus . . .1 8. . 146 10. . . . . . . . . . . . . . . . . . . . .6 8. . . . 140 User Space Memory Access . . . . . . . 118 Kset API . . . . . . . . . . . . . 129 Class Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. 144 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Kernel to User Space Event Delivery . . . . . . . . .5 Building Modules .8 Kref API 117 From Kobject to Sysfs . . . 123 Drivers . . . . . . . . . . .4 8. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 8. . . . . . . .3 8. . . . . . . 127 Class Devices . . . . . . . . . . .4 Module Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 10. . . . . . . . . . . . . . . . . .5 8. . . . . . .1 An Exemplary Module . . . . . . . . . . . . . . . 126 Classes . . . .7 8. . . . .1. . . . . . . . . . . . . . . . . . . . 138 Various Helper Macros . . . . . . . . . . . . . . . . . . . . . 141 144 10 Modules 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 8. . . . . 132 Devices . . . . . . . . . . . . . . . . . . .2 Kernel Purity . . . . . . . . . . .3 8. . . . 147 10. . . . . . . .4 8. . . . . . . . 136 138 Extended structures 9 Common Routines and Helper Macros 9. . . . . . . . . . 118 Kobject API . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . .
your mouse. process let kernel to take care of some details. leaving implementation to user space programs. Many operating systems exclude graphic routines from the kernel. your keyboard. Back to the mail agent: there’s no need to take care of your video card. It’s common on Unixlike systems to use X server in order to run graphical applications. Operating system uses notion of a task. with colorful icons on buttons.Chapter 1 An Informal Introduction to Operating Systems Kernel of an operating system (OS) usually remains hidden beyond common user space programs and system utilities (until some serious error occurs). The word task was often used in past. but he takes care of details of his part of the task. but users of modern Unixes prefer to use word process. that these graphic services are not provided by kernel. OS provides environment for this task/process by using some abstraction or emulation. Let’s start with describing what’s happening inside your computer: Your goal is to check for an e-mail. 1 Instead of taking care for every detail. in this case your mail user agent is a task for him. and you’ve probably noticed. You run your favorite mail user agent and order to get work done for you. Your mail agent runs in graphic mode. or details about how are the files stored on your hard drive. 1 Emulation is scarce in Linux 1 .
various BSD branches belong to this family.51 upwards). Linux.1 Monolithic or Micro Kernel? Linux was developed by Linus Torvalds in the beginning of 90s. This leads to simpler and cleaner internal architecture. Andrew Tanenbaum. Mikrokernels delegate responsibilities to user space processes instead of doing everything needed right in the kernel. it’s always there. 2 QNX is a real time operating system and was intended for use with embedded hardware 2 . while Linux is monolithic (with ability to load external modules). When you start your computer up.Chapter 1. but it is also judge and police when some of your processes breaks the law. This cache is not used efficiently during context switch. 1. Monolithic kernels proved to be much faster. when you shut it down (except for killing him with power blackout). An Informal Introduction to Operating Systems Where does the kernel fit in? It provides mechanisms for processes to communicate and to cooperate with each other. time and memory assigned to each process. handling events from outer world. developed by prof. which should improve stability of the system. The problem is that serving one syscall needs many context switches in microkernel model and modern processors can gain performance from utilizing cache. Microkernels have never gained much success in commercial sphere with probably one exception: QNX2 . Windows (from NT 3. watching over resources. These tasks (called daemons or servers) don’t run in privileged mode as kernel does. This was only a small list of kernel’s duties. Minix (providing similar syscall interface like Unix systems) was internally designed as microkernel. at the time he used Minix. And sometimes also mechanisms to prevent processes to hurt each other. providing needful trifles. How is it possible to run so many applications with only one processor ? Remember the abstraction we mentioned above: Each running task is provided environment like it’s the only one running and kernel takes care of switching between tasks so quickly that you can’t see that there is always only one task running and the others are stopped. when you access your files. They are more interesting from academic point of view. Presume you have video conference running in small window next to your mail agent and a music player. modifying one subsystem consists of modifying a user space task and not the kernel.
including various security policy enhancements. Processes don’t need to care about other processes in memory4 . Preemptible multitasking allows tasks to be switched independently on the ’willingness’ of the task. 1. output (and error output). An Informal Introduction to Operating Systems Microkernel fans often accuse Linux of having dirty internal design. but this was overcome. block and character devices. Original design offered two running processes. which can be redirected and used to automate user tasks. Files are not only regular files. virtual memory provides process more memory that could be allocated only using physical RAM. one’s wishing to have an SMP machine to feel it running.2 Concerning Traditional Unix Principles Unix was created more than 3 decades ago and it’s often thought of as father of modern operating systems. because it’s impossible to implement it efficiently without hardware support. named pipes (also called FIFOs). such as TCP/IP networking. Linux uses kernel threads and loadable kernel modules to increase flexibility. Developed in cooperation between university and commercial sector. One of the most important Unix concepts is the notion of file. This is also often criticized.6. . Instead of accessing directly keyboard and screen. The vast majority of traditional Unix tools does only one thing.3 Overview of the Linux Kernel Linux started as 386-specific system. but building operating system on ground not solid and stable does not enforce good security. Unix users sometimes mention the KISS principle: Keep it simple. all those routines and data structures. 1. but they do it perfectly. small. but soon developers from other architectures adopted the source and in time improved it to support 24 architectures. 4 This depends on hardware architecture. 3 3 . Its security increased from nothing to some of the most secure systems available today.Chapter 1. Many of these ideas seem to be low-level. Unix prefers to provide standard input. Writing Just have a look at the scheduler code in 2. . In reality kernel developers try to clean any mess in unstable branch3 . yet they provide strong instrument to developer. Kernel threads are meant only for slow things (for example swapping) because of two more context switches needed. but symbolic links and TCP streams are also treated like special files. pipes. some Unixes running on embedded hardware does not have this feature. it soon included new ideas. Pipe allow two programs to cooperate.
User also has conMemory Management Unit. Pages can be also shared to decrease memory footprint of a process and copied for each process only later. then it starts its most important internal routines and continues with hardware detection. SCP/SFTP or even local archive files and accessing them like local directories is a feature every desktop user could use. when needed. which is Installable File System. Mounting remote WebDAV. Demand loading is used to load into memory only those pages which are really needed. or only created in RAM. This problem was traditionally addressed in various user space libraries in desktop environments. Although this could be standard feature in microkernel system.other while some file systems allows administrator to use Access Control Lists (ACL). Linux provides good Hardware Abstraction Layer (HAL). Mounting NFS as root file system is also possible. floppy. An Informal Introduction to Operating Systems portable code and running Linux on many platforms helped to find and fix many bugs. and in the time of writing this. On architectures supporting CPU hot plug Linux could start and stop CPU anytime is needed and migrate assigned processes to other CPUs. Most of the features are available on all architectures. Since kernel 2. It’s important for an operating system to have some file system mounted after boot and Linux is not staying behind.group. it’s root file system / could be either real file system from your hard disk drive. Basic security on Linux is provided by trinity user. but Hardware Emulation Layer (HEL) is almost non-existent with probably except for sound support.Chapter 1. cdrom. therefore Linux is great for making disk-less network workstations. Devices drivers can be compiled statically into the kernel or dynamically loaded later. for example OpenBSD’s kernel developers deny loadable kernel modules as bad security practice. Linux supports many file-systems. Linux starts with the boot of the kernel.5 (the unstable branch) Linux has very good support for simultaneous multiprocessing. Not all Unix-like kernels support this. Device support is very broad. not many monolithic system support it now6 . FTP servers. but some (like address space protection needs MMU5 ) are not. part of the CPU Microsoft Windows supports IFS. Memory management takes care for virtual memory of all processes and also the kernel memory. USB key. other CPUs are started after boot. but the developer fees are very high and almost nobody is using it 6 5 4 . In case you have multiprocessor machine. but many Unix tools does not use these libraries. Linux started supporting general user space file system implementation. paging is used to swap out pages which are supposed to by not so important and more important ones are loaded instead.
Root is by default totally unrestricted7 . Kernel 2. but usually only 2 are used: 0 as the kernel mode and 3 as the user mode 7 5 .6. so the OS designers decided to divide OS into two levels: kernel mode should work with critical data structures and manage access to the hardware. [Documentation/SubmittingPatches] contain all necessary information how and BSD systems sometimes force root to change permissions of file when he can’t write to it. 1. the third number grows as new features are introduced. Linux root can write immediately 8 Vanilla kernel is kernel from [. The third field is number of patch. it’s not written: first patch changes 2. Patches that do not bring new features (they should be less than 100 lines in length) increase the fourth number. odd ones mean unstable i. BSD secure levels.1 and the next one to 2.16.kernel. PaX. they almost never introduce new feature in stable kernel. Patches are intended to fix some bug. Switching from user mode to kernel mode could happen in using syscall or when an interrupt or an exception occurs. development branch. the first one was the major version.11 used new numbering scheme: development is done in 2. Vanilla8 Linux kernels now include SELinux extension to the default security model. only using calls to kernel. while user mode should not access to the hardware.16. At those times a memory leak in text editor could crash whole system. Later CPUs allowed to switch between two9 privilege levels. it would only kill the crashed application (and perhaps dump the memory of the application for debugging purposes).6 branch.5 About Kernel and Its Development Past Linux version numbering consisted of three dot-separated numbers.4 User Mode and Kernel Mode The first CPUs allowed all programs to access all memory and I/O ports. Even numbers in minor version field meant stable kernel. the second one was the minor version. RSBAC or LOMAC available on Internet.6.16 to 2.org] without any 3rd party patches 9 Some processors such as i386 allowed 4 privilege levels. Submitting new patches and drivers became more formal than it was in the past.2 and so on.e. If the fourth number is zero. 1. networking security hooks and there are also any others (mostly rule-set based) extensions like GRSec.6. Crash in user mode would not cause crash of the whole system.Chapter 1. An Informal Introduction to Operating Systems trol of his processes.6.
The patches are also sent there as Cc: so this mailing list generates much traffic and many e-mails. A signature scheme exists since the beginning of the SCO-Linux lawsuit to improve tracking who did what. The Linux kernel also has its coding style defined in [Document/CodingStyle].Chapter 1.org This sign also means that the developer certifies the patch to be his own work and he has the right to submit it under open source license. The list of maintainers is in file [MAINTAINERS] in the root of the kernel source package. An Informal Introduction to Operating Systems to whom should be the patch sent.kernel. which differs from GNU coding standards. Developer rjd@example. 6 .org mailing list which contains kernel development discussion. or that the patch was provided to him (her) by someone who follows the forementioned rules. Not to be forgotten is the linux-kernel@vger. A patch arrives from developer to maintainer and if the maintainer decides not to dump the patch then he (she) signs it off: Signed-off-by: Random J.
for example memory allocation is solved through mapping Copy-On-Write (COW) pages from [/dev/zero] into address space of calling process. the code is split into subsystems logically based on the function provided (i. virtual file system (VFS) and networking.1 System Calls System call is a way for process running in user space to request some functionality implemented in kernel. These systems are bound together in monolithic kernels (such as Linux) and provide interfaces to each other.Chapter 2 Subsystems Overview Kernel comprises of various subsystems. The interface for system calls is stable on each architecture. but they sometimes call each other. communication. . . but it varies between CPU architectures. You can run old programs compiled long ago and they will still run. Kernel provides abstractions from hardware. 7 . but many others are also essential to any functional kernel: system calls. Syscall is also one of two usual ways of switching between user and kernel mode.e. 2. if the checks in kernel allow to do it. interrupts and exceptions handling. manages shared resources and perform some of the many network-related functions. file access. function concerning memory management. Not everything in libc is implemented as syscall. Details of system calls are architecture specific.). Imagine each subsystem as a library. various type of locks etc. System call (often abbreviated to syscall ) allows user mode to perform privileged operations. The most important kernel subsystems are process scheduler. the other one is hardware driven interrupt or exception. memory manager.
such as running. One CPU can execute only one task at a time2 . A processor-bound process is process doing many calculations almost all the time. Linux kernel 2. [/bin/init] or [/bin/sh] (executed in this order). 1 8 . therefore terms process and thread are sometimes mixed up in various Linux documents. The process scheduler decides which process should run when and how long should it run. Preemptive multitasking was preferred to cooperative multitasking found in some systems. but we define CPU as virtual CPU. Without preemption the code inside kernel runs until it completes its work (which is source of high latency) or it decides by itself to switch to other process (schedule() function switches processes.6 uses various techniques to distinguish between processorbound1 and I/O-bound processes and gives a slight advantage to the I/0 bound ones. while I/Obound process does very little computations but it’s operations are I/O intensive (e. It also allocates CPU for each process on machines with multiple CPUs. which will be described later in section 7.g.2 Process Management and Execution Process management is mostly about creating (forking) and terminating processes and switching between them. This way the higher priority task does its work when needed and not later.Chapter 2. [/etc/init]. Preemptible kernel aims to solve latency problem (from desktop user’s point of view this can for example cause sound to crisp or) by allowing to switch tasks also inside kernel. the preemption will make it run. One of the biggest changes (and probably the most popular besides new hardware drivers) is the new O(1) scheduler written by Ingo Molnar. this is usually done when kernel decides the thread will sleep until some event occurs. Linux 2. Since invention of multitasking (and multithreading) various approaches were tried. Subsystems Overview 2. zombie process.6 also brings better support for symmetric multiprocessing (SMP) and Non-Uniform Memory Access (NUMA) architectures. Process management is also maintaining process states. If a higher priority task becomes runnable. Linux support for multithreading can be simply described as creating more processes with shared virtual memory and some other resources. All other processes are forked from init or its children. since they are supposed to be interactive.1. so kernel must take care of properly assigning tasks to CPUs. The first process is one of [/sbin/init]. not the physical one you can buy in a shop. copying a file can be described as sequence of read/write operations) 2 This is not completely true for SMT and multicore CPUs. which aims to increase performance by making multiple CPUs available to computer. sleeping. This should improve desktop responsiveness.
kernel uses them cyclically. Linux supports multiple swap areas. whenever kernel needs to swap out page it tries to find slot in areas with bigger priority first. Process memory management is based on pages as each page has its properties (permissions. Each area is divided into slots. read-only flag. this saves write operations to swap and also saves space) and IPC shared memory pages. Pagination brought finer granularity and swapping out pieces of address space instead increased performance.3 Memory Management Routines used for memory management could be divided into two groups. Some architectures also support CPU hot-plugging.4 version offered only one daemon shared by all nodes. Pages can be shared between processes and they are the smallest elements that can be used to share or to be swapped out. The very first swapping implementation worked by monitoring amount of free memory and whenever certain threshold was passed. Subsystems Overview migrating tasks between CPUs in order to balance the load and achieve maximal performance. 2.6 to support one kswapd daemon per each CPU node. Page replacement has been extended in 2. . present flag. Which pages can be swapped out ? Anonymous memory region pages of a process. 3 9 . Systems without MMU don’t have this feature. Many modern CPUs offer segmentation as alternative to paging. those taking care of the memory belonging to process and those managing kernel memory at the lowest level. Previous 2. but Linux wishes to avoid penalty of freeing page on remote node. but Linux is not using this feature.).Chapter 2. Since pages (4 or 8KiB on most architectures) are too big for small kernel data structures. kernel includes slab allocator. This allows kernel allocate sub-page memory structures without fragmentation of memory. they put whole address space of affected process to disk. they usually also miss shared memory and process address space protection. Basics of the memory management are covered by page management3 . This is needed because the user mode stack can be swapped out. where CPUs may be added or removed and kernel must handle this situations so that no task is lost with CPU removed. the kernel change Stack Pointer register to point to kernel stack of the process. Swapping is technique used to lay aside pages from process address space. it does not affect kernel pages. Whenever the process switches from user mode to kernel mode. modified pages (non-modified are usually mmaped from some file and they can be reclaimed from that file. If there are more areas with the same priority. .
increases by value of one (the value is now 6) and stores the new value. Subsystems Overview IA-32 architecture supports more than just 4 KiB page size. interrupt 0x80). e. General Protection Fault. page fault could indicate either that page is swapped out or that process tried to address the memory not belonging to him. usually from hardware devices (IRQs. Invalid Opcode. task switch from the OS point of view) so coprocessor exceptions are used to indicate that it’s time to change the FPU stack content. Common exceptions include Page Fault. and various others concerning FPU. 2. Huge pages can be accessed using shmget() (shared memory) or mmap() (memory mapped file) on a file opened in this file system. counter of opened files.g. page fault. debugging or simply division by zero. a pseudo file system based on ramfs. interrupt requests).5 Synchronization and Workflow Concurrency Imagine two threads accessing a shared variable. The root of the implementation is a Huge TLB File System hugetlbfs. It is possible to use 4 MiB pages (referred to as huge pages) also for user space processes. IRQs are usually called when hardware device needs to notify kernel about some change. Then the scheduler 10 . so it retrieves its current value (for example 5). What if happens the following situation ? The first thread retrieves the value (5). which has its own section in this chapter) are used to handle faults concerning process. Any file that exists in that file system is backed by huge pages. e. memory.4 Interrupts and Exceptions Interrupts are used to serve requests. A bit later the second thread opens a file and does the same operation. Some of these exceptions are used not only to handle errors: FPU stack contents needs not to be reloaded on each context switch (i. but Linux uses this pages by default only for mapping the actual kernel image. e.e.Chapter 2. 2.g. Some of these faults can be intentional. while CPU invoked interrupts (save for syscall.g. then scheduler decides to give opportunity to the second one and it also retrieves the value and increases it by value of one and stores it back (6). or from CPU itself (these are the exceptions. math coprocessor used and others invoked by various instructions) or syscall (on i386 architecture. First thread opens a file and wants to increase the counter. Page faults are likewise used to bring in swapped out page. The final value of our counter is 7.
Chapter 2. Subsystems Overview resumes the first process, which increases the value it has read before and stores the new value (6). As we can see, the number of opened files is incorrect. This is the problem of mutual exclusion. A common solution is usage of critical regions: critical region is a region of code and when one is being executed other threads/processes can’t enter their critical regions. The other solutions is usage of atomic operations, (i.e. operations that can be executed so quickly that scheduler can’t interfere). The first solution allows more complex operations to be done, but is also more difficult to be used correctly. Critical regions are protected by locks. Whenever a thead enters the critical region, it locks the lock and when the other thread tries to enter the region and lock behind itself it finds out that it must wait for the lock to be unlocked (some locks prefer word ’sleep’ to word ’wait’). The most simple locks used in Linux kernel are spinlocks. When a spinlock is locked, the other process trying to lock the spinlock enters a busy loop and continually checks whether the lock did not become unlocked. This behavior condemns to be used only to protect small critical regions which are supposed to be executed quickly and without any blocking. Kernel developer with need of critical region that could block or will take longer time to execute should use semaphores (or newer mutexes). A semaphore can be locked by more than one lock-holders at the same time, this number is set at initialization. In case of being locked, the semaphore provides the advantage of switching CPU from busy loop to some other (hopefully) more important work. The disadvantage is caused by unsuccessful locker falling asleep and then taking some more time to wake up than spinlock. The 2.6 branch of Linux kernel introduced two new notions: preemption and futexes. Futex stands for fast userspace mutex and preemption is the ability to switch threads also after they have entered kernel mode. These topics will be more deeply discussed in chapter 3.
2.6
Time and Timers
Keeping current time and date and executing tasks at given time (or periodically at some interval) is essential to modern computing. Preemptive process scheduling wouldn’t work without correct use of timers. Linux periodically updates current (system) time, time since system startup (uptime), it decides for each CPU whether the process running on this CPU has drained time allocated (scheduling timeslice, or quanta), updates resource usage
11
Chapter 2. Subsystems Overview statistics (track the system load, profile kernel. . .) and make statistics for BSD process accounting and checks for elapsed software timers. Software timers are based on jiffies, each timer has associated value of how much ticks in the future (added to jiffies at timer start). The jiffie itself is constant interval of time, but it’s different on each architecture.
2.7
Signals and Inter-Process Communication
Sometimes processes need to cooperate with each other to achieve a goal, various mechanisms to solve this problem were introduced. Signals are the oldest of all inter-process communication facilities, both user space processes and kernel are using them to send a short message to process or a group of processes. This message consists only of its identifier, i.e. integral number. No arguments are used besides this number. Signals are used either to make process aware of events or to force process to deal with something. Process could specify signal handler which will handle the signal using sigaction() system call. Signals could be generated by other processes and sent to target process via system call, or by kernel (for example SIGSEGV sent to process trying to access beyond its address space). Signals can cause process to terminate, stop its execution or continue it again. Some signals could be blocked, SIGKILL and SIGSTOP can’t. Another inter-process communication facility common to all Unixes is pipe. System call pipe() returns two file descriptors. One is for reading only and the other for writing. According to POSIX standard, process must close one of them before communicating with the other one (half-duplex pipe), but Linux allows to read from one and write to another.4 Writing and reading from pipe can be blocking call and cause the process to sleep. FIFOs could be best described as extension to pipes; they’re associated with a filename on the filesystem, therefore any process knowing the name can access this pipe, which implies the name ’named pipes’. They are created by issuing mknod() system call with mode S IFIFO. IPC in Linux was inspired by SystemV IPC: semaphores, message queues and shared memory. All these entities are created/joined using key. The same key used in different processes indicate that they want to share e.g. message queue. Convenient way to generate keys is the function ftok(). Each mechanism provides ...get() function to acquire an entity and ...ctl() to change permissions and
4
Some Unixes support full duplex pipes through both file descriptors.
12
Chapter 2. Subsystems Overview remove entity (and mechanism specific things). Semaphores can be used to synchronize processes, their ’kernel-space relatives’ were described in chapter 3.2. A set of semaphores is allocated by semget(). IPC Semaphore operations (semop() and semtimedop()) work on semaphore sets, the advantage is that process is able to (un)lock arbitrary number of semaphores atomically. This could prevent some situations leading to deadlock. Semaphore sets can by controlled by semctl() function. Message Queues can be created (msgget()) in kernel to allow processes to exchange messages. Message queue is created by some process, it can overlive its creator and lives until it’s killed by msgctl(). Messages are appended to the queue in order in which they’re sent (msgsnd(). Each one has its type set upon sending (a positive number) and it’s reception (msgrcv()) is based on this type. The last of IPC mechanisms described here is shared memory. One process creates shared memory (using shmget()) and other processes refers to it by its key. Each process can map this shared memory into specific address inside its VM independently on the other processes or let shmat() choose appropriate address. Note that removing shared memory using shmctl() does not actually removes shared memory, it only marks it to be removed. The shared memory itself is removed once the last process detaches using shmdt(). If all processes detach themself without destroying shared memory, it keeps on existing. While System V introduced IPC, the BSD branch of unices has chosen sockets as their main inter-process communication primitive. They appeared first in BSD 4.2. The API taken from BSD is supported on all unix and also on many non-unix platforms. Socket is end-point for communication, it has some type and one or more associated processes. Sockets can send/receive data through streams, using datagrams, raw packets and sequenced packet. The most interesting protocol/address families are PF UNIX, PF INET, PF INET6, PF PACKET and PF NETLINK. For example infrared and bluetooth devices also has their protocol families: PF IRDA and PF BLUETOOTH. Linux implementation is based on sockfs file system and so some file operations can be applied to opened sockets. A stream socket (SOCK STREAM) can be viewed as network-transparent duplex pipes, because it connects two distinct end-points, communication is reliable and sequenced and ensures unduplicated data flow without record boundaries. A datagram socket (SOCK DGRAM) does not promises to be reliable, sequenced and unduplicated, but it allows sending broadcast or multicast packets. Data boundary are preserved. A raw socket (SOCK RAW) provides user access to the underlying protocols which 13
Chapter 2. Linux allows the use of ordinary read() and write() calls to operate on sockets after connect() or accept. This is essential for broadcasting and multicasting. to some local path (in case of PF UNIX) or local address and port (in case of PF INET). Incoming out-of-band data are indicated by SIGURG signal and normal data are indicated by SIGIO. which can be used for extended operations. but it is based on datagrams.8 Virtual File System Virtual File System (VFS) is layer providing abstraction of one file system. while there may be many file systems of different types mounted at various places in directory tree. These connections are picked from the queue using accept() call. This allows to access files independently on whether they are stored on ext2 or umsdos or even on some remote computer. Connections are closed using close(). which is logically independent transmission channel associated with each pair of stream socket endpoints. but they can be shut down prior to this call using shutdown(). just as it is with file interface. Subsystems Overview support socket abstractions. VFS separates applications 5 Not implemented by PF INET 14 . Next step could differ for SOCK STREAM and SOCK DGRAM. A sequenced packet (SOCK SEQPACET) is like stream packet with the difference that message boundaries are preserved. SOCK STREAM sockets do support out-of-band data. This socket is created without any local name and therefore it is not yet addressable. The listening SOCK STREAM side will use listen() to indicate maximum number of outstanding connections to be queued for processing. 2. socket() call creates socket descriptor for given address/protocol family. One nice advantage of having socket descriptors acting similarly to file descriptors is that they can be processed by select() call and related functions and macros. Data inside this channel are delivered independently on data inside normal transmission channel. They are usually datagram oriented and non-root user is not allowed to use these. Sockets can be further tuned by getsockopt() and setsockopt(). socket type and protocol.g. Sockets also support their own calls send() and recv(). stream oriented sockets are required to use connect() call to connect to remote endpoint.5 . while datagrams could either follow their ’stream cousins’ or use sendto() and recvfrom() without being fixed on one remote endpoint. bind() call binds the socket e.
which is file system in user space. struct dentry object stores information about linking of a directory entry with the corresponging file objects used by user mode processes. . its typical representants are ext2/3. previous objects can have their file system dependent representation on disk-based file systems). asynchronous aio . These file systems use some kind of block device to store information. but since linux is coded in plain C. Linux kernel supports one really interesting file system since 2. The largest group of file systems can be described as disk based file systems. Superblock object stores overall information about a mounted filesystem. The last group are special file systems. reiserfs. developers used structures with pointers to functions to implement methods. Other interesting are bdev (block device filesystem). Subsystems Overview from concrete implementation of file system. . Network file systems smbfs. pipefs (pipes implementation) and sockfs (sockets implementation)..Chapter 2. When user mode process opens a file. coda allow transparent access to files on remote computers. rootfs (used as root during bootstrap). nfs.6. This file system is more interesting for user space developers than kernel developers. therefore directory structure with symlinks can create cyclic graph. sysfs. like proc. Many of them do not store any real information. kernel finds the right file operations depending on the file system and newly created file structure has pointer to this structure. Each inode has its unique inode number. all data are stored in files separated into directory tree6 .. vfat. Linux also features inode cache for better performance. Kernel uses dentry cache to speed up translation of a pathname to the inode. . read(). xfs. Each file system provides its struct file operations. binfmt misc (miscellaneous binary executable file formats). but symbolic links can. . for example procfs offers information about processes in the system (usually /proc/<pid>) or various system information. File object keeps information about file opened by process (this object is only in memory. How does the VFS work? The idea is based on object oriented programming techniques: data and operations are encapsulated in objects. 7 Users complaining that they cannot umount partition with opened files on it should always think about pointers pointing to non-existing file operations structure. linux-specific sendfile().14: FUSE. 6 15 . whose root is marked as /.() operations and many others.7 Hard links can’t link to directories. inode stores information about specific files (directory is special file that contains information about other files and directories. this object offers methods such as open().
fcntl()-based file locking (from POSIX) allows to lock whole files and portions of file. 8 16 .Chapter 2. in some cases the process would lose performance while sleeping. it’s based on /dev/inotify. The buffer cache saves processes from suffering from slow block devices. It’s common to say in unix circles that everything is a file and so are devices. while udev is new way of managing devices in [/dev]. Subsystems Overview User process has its set of struct file opened files and struct fs struct.8 Structure fs struct is used to map file descriptors to struct file objects. they’re usually processed as streams). It works by building data structure in kernel first. linux caches are called page cache and buffer cache. but it is just advisory locking (affected processes must cooperate). While it is sometimes sufficient to wait for an I/O. The situation gets worse with more I/O requests pending at the same time. File locking is technique preventing simultaneous access to file. Desktop systems often need to modify user about changes to files in directory shown in opened window. This structure is built only once as opposed to forementioned syscalls. They’re treated as files and they traditionally had their major/minor numbers. Kernel developers decided to switch from dnotify mechanism to inotify. which usually go through the three arrays and check each one and add it to its wait queue. epoll() is attempt to make select() and poll() system calls in more effective way. fs struct also contains pointer to mounted filesystem of root directory and pointer to mounted file system of current working directory. Modern operating systems use various buffers to improve file system performance. Dnotify required to open one file descriptor per each directory watched and it did not notified about changes to files. pages read from block device directly. Linux kernel uses sometimes duplicity of information to gain speed. because each process has its own root directory and current working directory. then each file descriptor is added to it. This new approach allows to watch both files and directories for changes and does not cause any problems while umounting (inotify also notifies about part of directory tree being unmounted). Asynchronous I/O (AIO) allows process to do Many of these constructions are used to speed up going through many structures. shared pages from IPC etc. Linux inheritance from BSD brought flock() system call. Inotify is not implemented using syscall. Page cache keeps pages from memory-mapped files. There are two types of devices: block devices (they can be accessed randomly) and character devices (they can’t be accessed randomly. swapped-out pages from user space processes. which allows also mandatory locks (based on the file system mount flags).
power management and hot plug. Subsystems Overview some calculations while kernel performs I/O operations in the following manner: process submits one more I/O requests and uses separate interface to check for completed I/O operations.10 Networking Networking as inter-process communication solution was described in one of previous sections. maintaining sets of objects. which is able to route packets between them. Most future buses will support these operations. 2. bus drivers and device drivers. Two same devices always use one driver. This new tree-based approach evokes a directory tree. Basic sysfs interface layers are devices.Chapter 2.g. suspend and remove calls. The routing is done inside the kernel: packet arrives from one network interface adapter and kernel decides whether it belongs to this computer (e. The new model is bus-centric with orientation towards seamless Plug’n’Play.9 New Driver Model and Sysfs Past kernel versions included various disparate driver models. object set locking and userspace representation. Linux does support neither RT signals for AIO nor listio notification. sysfs is tied closely to kobject infrastructure. cancellation of IO. sockets nor pipes. Devices drivers are implemented around this infrastructure. Although according to POSIX signal can be delivered.‘ 2. The new driver model unifies them and consolidates set of data and operations into globally accessible data structures. In this new model all devices are inserted into one global tree. But strength of Linux lies also in its routing. The solution to problem how to deliver packages of data (called packets) to other network is routing. firewalling and shaping possibilities. Computer networks are interconnected. Operations common to all devices include probe. The kobject infrastructure implements basic functionality for larger data structures and subsystems: reference counting. Router is a machine connected to two networks. indeed sysfs was created to export this device tree to user space. There are ongoing project aiming to implement complete POSIX AIO. this allows users to communicate even if they aren’t in the same network. in TCP/IP networks this could be done by comparing IP address. init. resume. AIO works only with O DIRECT files and user space buffer must be aligned in memory. but there is also exception: network address 17 .
g. TCP) connections. Slowing down chosen connections. but routing is done in kernel. default target (policy) for this chain is used. IRC DCC or PPTP over NAT. Classless qdiscs don’t have any internal subdivisions. allowing short and fast bursts of packets. which will be used from now). steal data from companies. it could be forwarded (based on the settingsi. The last two tables are outside of scope of this work. to bind multiple physical links to aggregate bandwidth or 18 . Subsystems Overview translation). These decision rules are stored in chains. . The power of netfilter allowed to use connection tracking to create modules. Traffic control (or sometimes call shaping) is a mechanism to alter the traffic characteristics. routing can be disabled) to the other network. some others will be covered later. TCP/IP implementation relies on IP routing table. If the packet reaches the end of the chain. while classful ones can compose whole trees of classes. but they’re not interesting from our point of view. Stateful packet filter (from now on abbreviated to PF) is aware of state of (e. which was initiallyr stateless and later became stateful. This could not be possible (or at least not so simply) with stateless PF. bandwidth throttling. Common targets are ACCEPT. A packet is examined by classifier and sent to appropriate class and so on. but also enables malevolent forces to take over computers. of which some ones can contain further qdics (classful or not). Netfilter contains four tables: filter. mangle and raw. PF implementation for Linux is called Netfilter. packet traverses the chain from beginning til end until it is matched by some rule. Linux also has the ability to tunnel one protocol inside other protocol (or even the same protocol: IPIP). The idea of ability to look inside packets being routed to our network formed the idea of packet filter. . it all can be done using Linux. Traffic control inside Linux relies either on classless or classful queueing disciplines (from now on: qdisc). OUTPUT checks locally generated packets. INPUT chain checks the packets destined to local sockets. which is maintained from user mode. There are also user space deamons for more dynamic routing. which makes Linux popular with ISPs nowadays. nat.Chapter 2. Opening networks to whole world provides opportunities to share computing sources. that allow more complex operation. e. This approach provides very strong and flexible tool for system administrators. If the packet does not belong to this computer. Linux has the possibility to do both source and destination NAT. The simplest table is filter which has three default chains. REJECT or DROP. FORWARD chain takes care of packets trying to be routed through this machine. such as. Table nat takes care of network address translation (therefore the abbreviation NAT. Packet filter decides what to do by looking inside the packet and to the known state of this connection.
Chapter 2.h>. Subsystems Overview provide higher availability. 19 . Their API and implementation is described in chapter 4.11 Linked Lists and Their Implementation Linked lists are used throughout whole the kernel and it’s necessary for kernel developers to understand how to use them correctly. The essential file containing all the list stuff is <linux/list. 2. to bridge (almost) various network interfaces (and also filtering bridge is available).
while the semaphore itself could cause process to sleep and to schedule() another process to run. whether IRQ handlers can access protected data structures or simply whether the mutual exclusion wanted is in user mode or kernel mode. Its implementation is based on some kind of shared memory (mmap(). need to be protected. in which only spinlocks should be used (and atomic operations. but C compiler could generate code consisting of more instructions and without LOCK. Linux kernel addresses problem of mutual exclusion using many techniques. these are similiar to semaphores. Implementation of atomic operations is always architecture dependent. that modifying them by multiple writers at once could break consistency. Technique used to protect bigger pieces of code (and those. Atomic operations are simple operations (such as subtract and test) that can often be performed by one instruction with LOCK prefix. In 2. Critical region is the region of code which (when executed) cannot be interrupted/preempted by other process or thread. which will run for longer time) is semaphore. but that wouldn’t be atomic. The basic thought is to make system call only when there is contention between processes/threads accessing the same futex. shared segments or simply because the threads share VM) and threads are 20 . Some semaphore implementation uses spinlocks or atomic operations to access internals of semaphore structure. depending on many factors: how long will run the code in critical region. Solutions of this problems fall into category of mutual exclusion.Chapter 3 Synchronization and Workflow Concurrency Data structures so complex.6. This is unwanted in IRQ handler. Futex is an abbreviation for Fast Userspace muTEXes.16 new mutexes were introduced. but have better debugging support and therefore should be prefered by developers. as will be described later).
since incorrect usage could cause performance loss on SMP machines. versions of spinlock are implementation of read/write spinlock. preemption can be tought of as SMP equivalent. simply use spin lock irqsave(lock. 3. Spinlocks are implemented by set of macros.. <linux/spinlock.e. spinlock_t some_lock=SPIN_LOCK_UNLOCKED. and write.. i.h>. they use system call to arbitrate this case. UP kernels with preemption enabled use spinlocks to disable preemption.. Special forms of locking are needed for preemptible kernel: both concurrency and reentrancy could collapse kernel. If the data pro- tected by this section can be changed in an interrupt handling routine. some prevent concurrency with IRQ handlers while the other ones not.1 Spinlock to use it include The simplest and basic technique used is spinlock. This example shows us the simplest usage of spinlock. Spinlocks have been extended to support read/write spinlocks to increase performace in case of many readers and one or very few writers. Spinlock macros are in non-preemptible UP kernels evaluated to empty macros (or some of them to macros just disabling/enabling interrupts).Chapter 3. flags. Spinlocks are suitable to protect small pieces of code which are intended to run for a very short time. /* critical section goes here */ spin_unlock(&lock). spin_lock(&lock). 21 . When they find contention. However preemptive locking is based on SMP locking mechanisms and we need only few additional functions/macros for this situations: per-CPU data needs protection (protection between processors is done with SMP locking) and FPU state was saved only when user space tasks were switched. Spinlock user should always decide which one is most suitable. if they were disabled they will stay disabled and vice versa.. spin lock irqsave() saves the flags and disables IRQs and spin lock irqrestore() restores the previous state of interrupts. This mechanism prevents to enter critical section when the lock is locked by entering busy loop until lock is unlocked. This type of spinlock is very suitable when there is a lot of readers and writing is performed scarcely. The read. flags) and spin lock irqrestore(lock. which allows either multiple readers or one writer to enter the critical section at a time. Synchronization and Workflow Concurrency using atomic operations on integer. For most purposes.
flags) Lock the lock same as with spin lock() and friends. spin lock irqsave(lock. write trylock(lock). the readers counter is increased. write lock(lock) If the spinlock is unlocked. which is the older name for softIRQs). but prevents execution of softIRQs (bh is abbreviation for bottom halves. spin lock irq(lock). spin trylock bh(lock) Try to lock the lock (for details see spin lock() and friends).Chapter 3. If the lock is locked. write unlock(lock) Unlock the lock. write lock bh(lock) Same as the spin lock and derivates. 22 . spin unlock(lock). spin lock bh(lock). The read/write spinlock locked for read does not stop read lock() from entering the critical section. read unlock(lock). flags) write lock irqsave(lock. spin trylock(lock). the writer may enter the critical section. spin until it is unlocked (therefore the name spinlock). read lock irq(lock). read lock irqsave(lock. flags). Synchronization and Workflow Concurrency spin lock(lock). read trylock(lock). write lock irq(lock) Lock the lock (for details look at spin lock) and in addition disable IRQs. but in addition store whether IRQs are enabled and disable them. but if it is not possible to lock the lock exit with zero return value). read lock(lock). When this counter reaches zero. in case of read lock decrease the readers counter. lock it and enter the critical section. read lock bh(lock). Otherwise the return value is non-zero. Writer may lock r/w spinlock only if there is no reader present in the critical section.
number of sleepers in the wait queue wait. Semaphore is defined in <asm/semaphore. read unlock bh(lock) Unlock the lock locked by spin lock bh() or its appropriate cousin and allow softirqs to be processed. spin unlock irq(lock). void sema init(struct semaphore *sem. flags). write unlock bh(lock). Try to lock the critical section by decreasing sem->count. if there are already enough threads inside the critical region. The other good reason is readability. spin unlock irqrestore(lock. read unlock irq() enables IRQs after the last reader has left critical section. read unlock irqrestore(lock. Please note that spin lock irqsave() and similar macros should have their unlocking counterparts in the same funcions.2 Semaphores This locking entity is deprecated since Linux 2.16.. int val). write unlock irqrestore(lock. or together with DECLARE SEMAPHORE GENERIC(name. read unlock irq() enables IRQs after the last reader has left critical section. flags). switch context or enter idle loop. Synchronization and Workflow Concurrency spin unlock bh(lock). count). Initialize a semaphore’s counter sem->count to given value val and prepare wait queue. mark the current thread 23 . . Spinlock may not block. write unlock irq(lock) Unlock the lock and enable IRQs. this is caused by limitations of SPARC architecture.h> and it’s represented by structure struct semaphore containing counter count of threads trying to acquire the semaphore. read unlock irq(lock). inline void down(struct semaphore *sem).6. count) macro. flags) Unlock the lock and enable IRQs only if they were enabled before locking the lock. Semaphore structs can be initalized using declaration using SEMAPHORE INITIALIZER(name. 3.unlock irqrestore() is more suitable in most common cases.Chapter 3..
Synchronization and Workflow Concurrency as TASK UNINTERRUPTIBLE and sleep (schedule())until it is woken up by some thread exiting the critical section. 1 means one writer and 0 means no activity. The same operations work on mutexes as they did on semaphores (since mutex is simply a semaphore with initial count value of 1). This function does mostly the same operation as down(). The schizophrenia of lock names was strengthened with arrival of 2. This new mutex is described in its own section. There are also two functions with self-explaining names for initalize mutexes: inline void init MUTEX(struct semaphore *sem) and inline void init MUTEX LOCKED(struct semaphore *sem). inline void up(struct semaphore *sem). Release the semaphore and if there are any tasks sleeping on this semaphore. otherwise zero. or by assigning RWSEM INITIALIZER(name to variable.6. inline int down trylock(struct semaphore *sem). 24 . also called mutexes. wake them up. if it fails return non-zero value. Special case of semaphores are binary semaphores.16: a new Mutex was introduced (while this old one still exists). If there are any signals pending for the current thread.3 Read/Write Semaphores Read/Write semaphores offer the possibility to have either one writer or any number of readers at a time. void init rwsem(struct rw semaphore *sem) Initialize rw semaphore internals. Try to acquire semaphore. Then mark current thread as 3. inline int down interruptible(struct semaphore *sem). RW semaphore also features its wait queue protected by spinlock. TASK RUNNING and enter the critical section. which declares variable struct rw semaphore name.Chapter 3. which indicates current status: any positive number means number of readers. RW semaphore can be initalized either using DECLARE RWSEM(name). exit before entering sleep state. but sleeping process is marked as TASK INTERRUPTIBLE. Unlocked mutex can be declared using DECLARE MUTEX(name) macro and locked one using DECLARE MUTEX LOCKED(name). struct rw semaphore contains member variable activity.
otherwise 0. Reinitialize the completion structure: both done and wait member variables. void down write(struct rw semaphore *rwsem) Acquire semaphore for reading (up write() for writing). return 1.4 Completions Completion is simple synchronization mechanism close to semaphore. void up write(struct rw semaphore *rwsem) Release previously acquired lock and wake up waiting threads. If the 3. Synchronization and Workflow Concurrency void down read(struct rw semaphore *rwsem). 25 .Chapter 3. void downgrade write(struct rw semaphore *rwsem) Downgrade previously acquired write lock to read lock (and thus allow other readers to enter critical section). Completion API is accessible through <linux/completion. int down read trylock(struct rw semaphore *rwsem). void up read(struct rw semaphore *rwsem). If it’s not possible at the moment. sleep until some thread exiting critical section wakes us up. void init completion(struct completion *x). }. wait is a waitqueue keeping all waiters for this completion.h> A completion is declared using DECLARE COMPLETION(work) macro. Idle loop would be inefficient. Imagine two cooperating threads: thread A needs to wait for thread B to finish some work. Member variable done will be explained later. For reinitialization see INIT COMPLETION(). This function is used for dynamic initialization. int down write trylock(struct rw semaphore *rwsem) Try to acquire semaphore for reading (up write() for writing). semaphore was acquired. which declares a variable of type struct completion: struct completion { unsigned int done. thread A decides to sleep until thread B wakes him up. wait_queue_head_t wait.
unsigned long wait for completion interruptible timeout(struct completion *x. Wait for completion: the task will become TASK INTERRUPTIBLE and will sleep until woken up by someone (using complete() or complete all()). Wait for completion: the task will become TASK INTERRUPTIBLE and will sleep until woken up by someone (using complete() or complete all()) or timeout expires. Timeout is given in jiffies. Wait for completion: the task will become TASK UNINTERRUPTIBLE and will sleep until woken up by someone (using complete() or complete all()) or timeout expires. if it’s true then the second thread has already completed its part and there’s no need to sleep. unsigned long wait for completion timeout(struct completion *x. done is first checked.Chapter 3. 26 . Wake up one sleeper. void wait for completion(struct completion *x). The sleep may be interrupted (and woken up) by a signal. unsigned long timeout). This macro should be used for fast reinitialization. int wait for completion interruptible(struct completion *x). wait is untouched. This macro initializes completion: only done member variable. Wait for completion: the task will become TASK UNINTERRUPTIBLE and will sleep until woken up by someone (using complete() or complete all()). Wake up all sleepers. Why the reinitialization ? What happens if the complete()-like call is called before wait for completion()-like is called ? Nothing wrong. Synchronization and Workflow Concurrency INIT COMPLETION(x). void complete all(struct completion *). because this is the reason why completion->done exists: when a thread calls wait for completion(). void complete(struct completion *). If it’s false. Timeout is given in jiffies. unsigned long timeout). see init completion(). the thread goes to sleep.
16. Only one task may hold the lock and only the owner may unlock the mutex. then this function returns with -EINTR. mutex init(mutex). int mutex trylock(struct mutex *lock). <linux/mutex. DEFINE MUTEX(name). Multiple unlocks and recursive locking are not permitted. Lock the mutex. The non-debug version of mutex is simply a struct mutex with three fields: atomic t count holding one of following values: 1 means unlocked. The task waiting for a mutex to be unlocked is represented by struct mutex waiter control structed.h>). which helps tracking down locking bugs. Try to acquire the lock. 0 means locked and negative: locked.5 New Mutexes This new locking entity was introduced in 2. int mutex is locked(struct mutex *lock). These rules are enforced.6. return 0. Synchronization and Workflow Concurrency 3. Held mutexes must not be reinitalized and finally mutexes cannot be used in irq contexts. See include/linux/mutex. which contains only two self-explaining fields. Debug version of this function also checks if forementioned rules are obeyed. Initialize the mutex to unlocked state. A task may not exist with mutex held and memory areas where held locks reside must not be freed. when DEBUG MUTEXES is enabled. Acquire mutex.Chapter 3. 27 . int mutex lock interruptible(struct mutex *lock). If a signal arrives while waiting for the lock. Return 1 if mutex is locked and 0 otherwise. Macro to declare a struct mutex variable. Mutex must be initialized via the API. If the lock has been acquired. list head and struct task struct *task. void mutex lock(struct mutex *lock).h> should be included instead of deprecated semaphores (<asm/semaphore. possible waiters. Next field is spinlock t wait lock which protects struct list head wait list from being inconsitently modified.h for more details. but the name conflicts a bit with some macros concerning semaphores (mutexes were implemented as semaphores with limit of only 1 thread being able to entry critical section). if it’s locked then return value is 1 otherwise 0.
If the thread falls asleep and a signal occurs. From the user mode point of view the thread waking up the others does not know how many sleepers are there and which one will be woken up. When there is no contention.. The API is provided by <linux/futex. Before the thread is suspended value of *addr is compared to val and if they differ the syscall is exited with error code EWOULDBLOCK. which can be used to poll()/epoll()/select(). int val. The return value is number of threads woken up. op is the operation to be done with the futex. The utime argument indicates whether the thread will sleep for an unlimited time or whether it should be woken up with return code ETIMEDOUT. 28 . one of the processes calls sys futex(). Down and up operations are performed in userspace using atomic assembler instructions. int op. To wake up all sleepers use value of INT MAX. After the poll the revents are set to POLLIN|POLLRDNORM if there are no waiters. The meaning of the rest of the arguments is depends on the operation op specified: FUTEX WAIT The kernel is asked to suspend the thread. the return value of this syscall is file descriptor. 3. Futex was designed to be as fast as possible. u32 user *uaddr. FUTEX WAKE This operations wakes up val sleeping threads. Some inconsistency is in- troduced by mutex trylock() and mutex lock interruptible(): if the lock is successfully acquired.6 Futexes Futex is abbreviation for Fast user space mutex. return value is 0 in this case. one function returns 1 while the other one returns 0. int val3). Release previously acquired mutex. so usual val values is either 1 or INT MAX. there’s no need to use syscall (and therefore this save expensive context-switches). FUTEX FD This operation depends on val value: If it is zero. sys futex(u32 user *utime. Synchronization and Workflow Concurrency void mutex unlock(struct mutex *lock). struct timespec user *uaddr2. the syscall is exited with EINTR.Chapter 3.h>. uaddr points to 32bit inte- ger in the user-space. If one there is contention.
This would lead to heavy context switching and thus performance degradation. FUTEX REQUEUE This is predecessor to FUTEX CMP REQUEUE. Synchronization and Workflow Concurrency If the val is non-zero the kernel associates it as signal with returned file descriptor so that it is sent when the thread is woken while waiting on the futex. Existing locking primitives are preempt-compatible (for example spinlocks implementation use preempt disable() and preempt enable()). Preemption opens new locking issues inside the kernel. 3. Moreover the threads that did not woke up are removed from addr futex’s wait queue and are added to the wait queue of futex addr2. and. and bitwise or.7 Preemption The preemption is the ability to switch the threads also in kernel mode. broken and unstable. lesser or equal. where we have to obtain lock before every operation. greater or equal. FUTEX WAKE OP This is the most complicated of all futex operations: Imagine having more than one futex at the same time and a conditional variable implementation. Use FUTEX CMP REQUEUE and prevent deadlocks. Whether the wakeup actually happens depends on the result of conditional expression. Comparison operators are equivalence. The implementation is mostly based on existing SMP-locking infrastructure. Operators supported are set value. FUTEX CMP REQUEUE This operation allows to wake up a given number of waiters. but there are some special cases that need to be taken into account. The solution is to have internal sleep array and waking up the thread only when the condition is fulfilled. Pointer to timeout is typecasted to int and used to limit the amount of threads to be requeued. lesser than.Chapter 3. add. when thread is 29 Including <linux/preempt.h> will provide developer macros for disabling/enabling preemp- . otherwise the syscall will end up with return code EAGAIN. tion. but it’s now considered buggy. Problems appear. and xor. greater than. non-equivalence. Whole this operation is started only if val3 equals to *addr.
Readers never block and they are willing to retry if information changes. a simple printk() might trigger a reschedule. which initalizes the seqlock to be unlocked. Another case is when CPU state needs to be protected and some other process preempts current one. Writers do not wait for readers.g. The best practice is to disable preemption explicitly and only for small areas of atomic code. It is possible to prevent a preemption using local irq disable() and local irq save(). Beginning of critical section is marked with preempt disable(). Preemption must be enabled by the same thread that disabled it. The implementation is a struct seqlock t containing spinlock t lock and unsigned sequence. it is not recommended to call complex functions from inside these areas. otherwise it is allowed. which decreases preempt counter. There is no need to explicitly disable preemption when holding any locks. preempt enable no resched() increases the counter. Seqlock can be initialized using seqlock init() macro. so kernel routines using FPU must use kernel fpu begin() and kernel fpu end(). 30 .8 Seqlock and Seqcount Seqlock is defined in <linux/seqlock. This macros also mark end of critical section. Synchronization and Workflow Concurrency doing something CPU-dependent. Seqlocks are specialized primitive locks. The reason is that preempt count() is defined as current thread info()->preempt count. 3. The check for need for rescheduling is performed by preempt check resched() macro. Macro preempt count() is used to check preempt-counter. for example modifying per-CPU data structure. but the danger is when an event occurs that would set need resched and result int preemption check. readers and writers are distinguished. but any spin unlock() decreasing the preemption count to zero might trigger a reschedule (e. while preempt enable() unrolls forementioned macro and checks whether there is opportunity to reschedule.h>. The sequence is always initialized to be 0 and it is increased with each operation on seqlock.Chapter 3. therefore modifications to per-CPU structures are not consistent. which use preempt disable() and preempt enable(). non-zero value means that preemption is forbidden at this moment. The thread could be preempted and woken up again on another CPU. because writer could invalidate pointer that a reader was using. FPU state is saved only when switching user space tasks. which is local to this thread. This type of lock should not be used to protect pointers.
Chapter 3. Return sequence number. } while (read_seqretry(&my_seqlock. Following routines are available to readers: static inline unsigned read seqbegin(const seqlock t *sl). returning non-zero value on success and zero otherwise. seq)). There are two helper routines used to manipulate sequence number (sequence should not be changed directly. static inline void write sequnlock(seqlock t *sl). Acquire the seqlock for writing. Zero return value means that the information processed was consistent. The behavior from reader’s point of view is the same as it is with seqlock t. The difference is in behavior for readers. Check whether the reader processed consitent/correct information. Writers are assumed to use their own locking (probably mutexes. Try to acquire the seqlock. . static inline void write tryseqlock(seqlock t *sl). static inline int read seqretry(const seqlock t *sl. 31 . The second ’locking’ type introduced in this section is not truly a locking primitive: seqcount t does not uses any lock by itself. unsigned seq). because spinlock is implemented in seqlock t). this routines use smp wmb() memory barrier). non-zero value otherwise... only the routines have changed their names to read seqcount begin() and read seqcount retry(). common use is as follows: do { seq=read_seqbegin(&my_seqlock). Synchronization and Workflow Concurrency Behavior of writing routines is identical to spinlock (with addition of sequence increasing each time): static inline void write seqlock(seqlock t *sl). Release the seqlock previously acquired for writing. This check first checks whether there was no writer at the time of acquiring the sequence (odd seq means there was a writer) and if then check whether the seq and sequence equal.
The initialization is implemented by macro ATOMIC INIT: atomic_t my_atomic_counter = ATOMIC_INIT(0)... bh() routines that disable and enable tasklets. Synchronization and Workflow Concurrency static inline void write seqcount begin(seqcount t *s). .. atomic sub and test(i. This routine should be called in the beginning of critical section.h].h>] also include . irqrestore() routines that save/disable and restore IRQs. atomic set(i. their implementation is highly architecture-dependent: [asm/atomic. atomic inc(v) Atomically increase value of v by 1. .. v) Atomically subtract i from v and return true if and only if the result is zero. atomic add(i.9 Atomic Operations Atomic operations are simple operations that are guaranteed to be executed without interruption or being interleaved by other operations. 32 . irq().Chapter 3. Operations are also implemented as macros (at least on x86) for performance reasons: atomic read(v) Atomically read the value of v... v) Atomically add the i to the value of v. v) Atomically set the value of v to i. Since C compiler can’t guarantee us atomicity. atomic sub(i. The file [<seqlock.. These operations are based around structure atomic t. static inline void write seqcount end(seqcount t *s). This routine should be called at the end of critical section. . 3. v) Atomically subtract the i from the value of v.. irqsave().
atomic inc return(v) Atomically increase value of v by 1 and return the result.Chapter 3. From now on a better approach is to use spinlocks with spin lock irqsave(). spinlock exactly shows the critical section. atomic dec return(v) Atomically decrease value of v by 1 and return the result. only on current CPU) can use following macros from <asm/system. spin lock irq() and spin unlock irq().h>: local irq disable(). Synchronization and Workflow Concurrency atomic dec(v) Atomically decrease value of v by 1. v) Atomically add i to v and return true if and only if the result is negative. atomic add negative(i.10 Disabling Local IRQs Previous kernel version contained cli() and sti() macros to disable and enable IRQs. 33 . 3. v) Atomically subtract the i from the value of v and return the result. save cli flags(flags) and restore flags(flags) are now deprecated. v) Atomically add the i to the value of v and return the result. atomic add return(i. atomic dec and test(v) Atomically decrease value of v by 1 and return true if and only if the result is zero. They provide better readability. spin unlock irqrestore(). Drivers that want to disable local IRQs (i. Spinlocks are faster than global IRQ disabling. atomic sub return(i. These macros together with save flags(flags). atomic inc and test(v) Atomically increase value of v by 1 and return true if and only if the result is zero. Disable IRQs on current CPU.e.
3. Splitting the code into two phases allows the removal phase to start immediately. Reader may not block. Following code example declares variable foo var.Chapter 3. }.11 Read-copy Update Read-copy update is a synchronization mechanism optimized for mostly-read access. The removal phase removes reference to old data (possibly by replacing them with new data) and can run concurrently with readers. but acquiring a lock never blocks. local irq restore(flags). who were already active before removal phase should be considered. Restore previously saved IRQ flags... struct foo *foo_var. The old data are freed during reclamation phase. which will be protected by RCU: struct foo { . some ones are using even more bits than one. the reclamation phase could not start until readers no longer hold reference to old data. local save flags(flags). The reclamation phase is deffered. Writer’s behavior is more complicated: update is split into two phases: removal and reclamation. Note that only readers. Because this could disrupt readers. subsequent readers are working with new data. DEFINE_SPINLOCK(foo_spinlock). switch task context or enter idle loop. Save the current IRQ state on local CPU into flags. Enable IRQs on current CPU. local irq save(flags). RCU works under presumption that updates are scarce and reader sometimes retrieves out-dated information. Synchronization and Workflow Concurrency local irq enable(). Reader has to acquire and later to release the lock. On most architecture the state can be on and off. This indicates that preemption is disabled inside the reader’s critical section. 34 . Save the current IRQ state on local CPU into flags and disable IRQs.
new). thus as fast as possible. And writer’s code: struct foo *new. some_var=rcu_dereference(foo_var). Reader’s code: rcu_read_lock(). This macro marks the beginning of RCU protected section. rcu_read_unlock(). rcu_assign_pointer(foo_var. synchronize_rcu(). // ’new’ points to new data spin_lock(&foo_spinlock).h> to gain access to following API: rcu read lock(). *old.Chapter 3. rcu read lock bh(). rcu read unlock (). enables softIRQs and also enables preemption on preemptible kernels. On UP machines without preemption the macros rcu read lock() and rcu read unlock() are evaluated to empty strings. old=foo_var. This macro marks the beginning of RCU protected section and enables preemption on preemptible kernels. This macro marks the beginning of RCU protected section and disables preemption on preemptible kernels. As can be seen. Synchronization and Workflow Concurrency The spinlock is used to prevent race condition of multiple writers. Include <linux/rcupdate. rcu read unlock(). spin_unlock(&foo_spinlock). 35 . disables softIRQs and also preemption on preemptible kernels. This macro marks the beginning of RCU protected section. the reader’s code is very simple. kfree(old).
Wait until all affected readers (i. The idea is to hold array of pointers instead variable of the same type. those working with the old pointer) have left the critical section. The callback will be called when all affected reader (i. This macro must be used in RCU-read critical section. Moreover the per-CPU variable’s single values for 36 . void (*func)(struct rcu head *head)) . The other way is to use callback function to free old pointer when time comes: call rcu() or equivalent. This version assumes that RCU-read critical section ends on completion of a softIRQ handler: therefore RCU-read critical sections may not be interrupted by softIRQs.12 Per-CPU Variables Per-CPU variables (<linux/percpu. This pointer may be dereferenced after rcu read unlock() or equivalent. those that acquired the old pointer) have left the critical section. The callback will be called when all affected reader (i. Memory barrier is used on some architectures. The bad is that that some overhead is needed around critical section for preemptible kernels. void call rcu bh(struct rcu head *head. Fetch a pointer protected by RCU. Queue an RCU reclamation callback.S. those working with the old pointer) have left the critical section. but this implementation is hidden behind a set of macros and functions. value). 3. Synchronization and Workflow Concurrency Note: RCU-read critical section may be nested.h>) are extensively used in 2. because each CPU has its own value. void call rcu(struct rcu head *head.Chapter 3. Note: this mechanism is covered by some patents in U. codevoid synchronize rcu(). void (*func)(struct rcu head *head)) . rcu assign pointer(pointer. Assign new value to pointer in the removal phase.e. Queue an RCU reclamation callback.e.A. and void synchronize sched().e.6 kernel (scheduler being nice example). Memory barrier is used on some architectures. The good is that there is no synchronisation needed. rcu dereference(pointer).
get cpu var(var). put cpu var(var). DEFINE PER CPU(type. This in fact disables preemption on preemptible kernels. Pointer array ptrs holds pointer to each instance of allocated type for each CPU possibly available in the system. }. Free a per-CPU variable previously allocated by alloc percpu(). They’re not allocated as one array. Per-CPU variables can be allocated in the runtime too. ical section. if they were then writing value to one item could invalidate cache on some other CPUs (especially data types with small memory footprint). get per cpu(socket in use)++. cpu) Access per-CPU variable of other cpu. Mark var per-CPU variable accessible to this CPU. 37 This is the beginning of critEvaluates to l-value of the per-CPU variable.Chapter 3. per cpu ptr(ptr. Mark the end of critical section for per-CPU variable var. The essential data structure is as follows: struct percpu_data { void *ptrs[NR_CPUS]. name). Synchronization and Workflow Concurrency each CPU are scattered in memory so that cache on SMP CPUs is not invalidated by other CPUs. EXPORT_PER_CPU_SYMBOL_GPL(variable). void *blkp. One copy is allocated for each CPU. If the variable is to be exported to modules. therefore . use one of the following macros: EXPORT_PER_CPU_SYMBOL(variable). works. this also enables preemption. Allocate per-CPU variable of given type and zero allocated memory. Use with care and choose additional locking. void *free percpu(const void *objp). This macro defines the a per-CPU variable name of given type. void *alloc percpu(type).
smp rmb(). thus no performance loss). The most common one are barrier(). Prevent write and optimalization reordering (SMP only). but CPUs in SMP machines accessing the same data at once could find data incosistent (for example one CPU is writing data out of order and the other is trying to read it in correct order).h>). Prevent write and optimalization reordering (SMP and UP). mb(). Prevent read and optimalization reordering (SMP and UP). Synchronization and Workflow Concurrency 3. Prevent read. Prevent compile-time reordering by inserting optimalization barrier (empty code. so wmb().13 Memory Barriers Designers of modern CPUs try to increase performance by executing instructions out of order they are in memory. rmb(). The reordering is not noticable by single thread. The reason to implement barriers in so much macros is optimalization. 38 . write and optimalization reordering (SMP and UP). Prevent read. Prevent read and optimalization reordering (SMP only). The second part of the problem is compile-time optimization: gcc does the reordering by itself Memory barriers are in Linux implemented as architecture-dependent macros (<asm/system. smp wmb(). accts only as optimalization barrier. for example Intel CPUs does not do write reordering. smp mb(). This includes memory loads and stores.Chapter 3. wmb(). write and optimalization reordering (SMP only).
The list is anchored by one (initial) list head variable. i.h>. macro LIST HEAD INIT(name) is defined as { &name. list is a structure containing pointers to next and previous items in list. &name }. which unrolls itself into struct list head name=LIST HEAD INIT(name).1 tion: List API Following macros/inline functions are defined to ease developer with list manipula- void list add(struct list head *item. Access to the original data structure (which the developer surely wanted to keep in the list) is provided by list entry() macro. right behind the anchoring 39 . The list is double-linked circular. Add the item to the beginning of the list. thus the list is initialized as circle containing one item pointing to itself in both directions.Chapter 4 Linked lists Double-linked lists are provided to kernel developer through <linux/list. List can be also initialized after declaration using INIT LIST HEAD(ptr). which will be part of the list.e. Double-linked circular list is implemented around struct list head structure. The easiest way to define new list is the LIST HEAD() macro.e. but to its member of type list head).h. As we can see in file include/linux/list. not to the structure containing struct list head. which provides the same functionality as described above. This complicated approach provides some flexibility (a structure may contain more members of type list head and also be part of more than one linked list at one time). How is it possible to add other data structures into this list? A structure has to have member of type list head. 4. The next and prev members of struct list head point to next and previous list heads (i. struct list head *head).
It is possible to move the source item from either other list to target list or just move the source item from inside the list to the beginning. See list move(). but also prevents list empty(entry) from returning true. Linked lists list head. void list splice(struct list head *source list. The source list’s members next and prev are not changed. This function is safe only if the only activity that can happen is list del init().Chapter 4. int list empty(const struct list head *head).e. Move the source item from its list to the end of list target list. prev and next are set to LIST POISON1 and LIST POISON2. int list empty careful(const struct list head *head). insert it between head->prev and head. struct list head *target list). struct list head *target list). struct list head *head). struct list head *target list). Move source list to the beginning of target list. If some other CPU is adding items then it’s not safe and some synchronization will be needed. void list del(struct list head *item). so it’s unsafe to use source list after list splice(). See list splice init(). Checks whether a list is empty. Add the item to the end of the list. Test whether the list is empty and check that the list isn’t modified right now. void list move tail(struct list head *source item. Removes the entry from list (the rest of the list is left untouched) and entry is reinitialized as separate list. i. so that the last item of source list will be just before target list’s first item. head is the anchoring list head. void list del init(struct list head *entry). Move the source item from its list to the beginning of list target list. Delete item from list it’s contained in. 40 . void list add tail(struct list head *item. which marks that the item has been deleted. void list move(struct list head *source item.
Chapter 4. Linked lists list splice init(struct list head *source list, struct list head *target list); Move items in source list to the beginning of target list. list again. list entry(pointer, type, member) This macro returns pointer to structure of type, which contains list head as its member variable. The pointer argument points this member inside the structure we want to access. See general description of linked lists in the beginning of this section and example in list for each(). list for each(iterator, list) Iterate over a list using given iterator. Common use of this macro is as follows: struct list_head *iter; list_for_each(iter, init_task) { struct task_struct *task=list_entry(iter, struct task_struct, tasks); /* do something with ’task’ here */ } This code iterates over a task list (init task is the head of list of all process descriptors in Linux) and ’does’ something for each task in the list. struct task struct contains member variable struct list head *tasks, which keeps it in list of tasks. list for each() also does prefetching to speed up list processing. list for each(iterator, list); Iterate over a list using iterator. see list for each() for details, but this macro does not do any prefetching, which makes it suitable only for very short lists. list for each prev(iterator, list); Iterates backwards, see list for each() for details. See list splice for details. In addition the source list is reinitialized to empty
41
Chapter 4. Linked lists list for each safe(iterator, helper, list); Iterate over a list like list for each(), but this implementation adds helper variable and is safe against removal of list entry. list for each entry(type *iterator, list, member); Iterate over a list. struct list head is hidden inside the type as member. This macro can be viewed as union of list for each() and list entry. Example from list for each() can be rewritten: struct task_struct *task; list_for_each_entry(iter, init_task, tasks) { /* do something with ’task’ here */ } list for each entry reverse(type *iterator, list, member); The backward version of list for each entry(). list for each entry safe(type *iterator, type *helper, list, member); Iterate over a list of give type. This version is safe against removal of list entry. list prepare entry(type *position, list, member); Prepare a start point for iteration over list. position should be initialized to null pointer. This macro checks the value of position and it it isn’t false then the position is not initialized to correct pointer for iteration. list for each entry continue(type *position, head, member); Iterate over a list of given type starting (or continuing) from existing position.
4.2
RCU Protected Lists
Following functions are defined to help developer accessing RCU protected macros: void list add rcu(struct list head *item, struct list head *head); Add the item to the beginning of the RCU protected list, i.e. right behind the anchoring list head. Writer synchronization (e.g. using spinlocks or mutexes) is left on developer.
42
Chapter 4. Linked lists void list add tail rcu(struct list head *item, struct list head *head); Add the item to the end of the RCU protected list, i.e. insert it between head->prev and head. Writer synchronization (e.g. using spinlocks or mutexes) is left on developer. void list del rcu(struct list head *item); Delete item from an RCU protected list it’s contained in. prev and next are set to LIST POISON1 and LIST POISON2, which marks that the item has been deleted, but also prevents list empty(entry) from returning true. Deleted item may not be freed immediately, instead use synchronize kernel() or call rcu(). Writer synchronization (e.g. using spinlocks or mutexes) is left on developer. void list replace rcu(struct list head *old, struct list head *new); Replace old entry by a new one. The entry may not be deleted, use synchronize kernel() or call rcu(). Writer synchronization (e.g. using spinlocks or mutexes) is left on developer. list for each rcu(iterator, list); Iterate over an RCU protected list using iterator. Whole iteration must be protected using rcu read lock(), rcu read unlock() or equivalents. list for each safe rcu(iterator, helper, list); Iterate over an RCU protected list like list for each(), but this implementation adds helper variable and is safe against removal of list entry. Whole iteration must be protected using rcu read lock(), rcu read unlock() or equivalents. list for each entry rcu(type *iterator, list, member); Iterate over an RCU protected list. struct list head is hidden inside the type as member. This macro can be viewed as union of list for each() and list entry. Whole iteration must be protected using rcu read lock(), rcu read unlock() or equivalents. list for each continue rcu(position, list); Iterate over an RCU protected list starting (or continuing) from position. Whole iteration must be protected using rcu read lock(), rcu read unlock() or equivalents.
43
Function with this flag may be called from interrupt context.1 Slab Memory Allocation Linux kernel offers to kernel routines two functions similar to user space malloc() and free(). Function may sleep and swap to free memory. Mechanism used to allocate sub-page memory areas is calles slab allocator (SA). Slab allocator takes care of caching freed memory so that future allocations can be faster. Allocate buffer of size.Chapter 5 Memory Allocation 5. Slabs are usually smaller than one page.h>: void *kmalloc(size t size. GFP DMA Allocate memory in lower 16MB of memory. These functions are called kmalloc() and kfree() and they’re based on slabs. This is suitable for device drivers using ISA bus. The meaning of flag is as follows: GFP KERNEL Allocate the physical contignuous memory buffer in kernel space. This API is defined in <linux/slab. This flag is allowed only in user context. GFP ATOMIC This flag forbids the call to sleep. but may fail in case where GFP KERNEL would swap to free memory. The memory is allocated from physical contignuous memory and cannot be swapped out. 44 . therefore suitable only for allocating small buffers. int flags). Return value is the pointer to allocated buffer or NULL if memory allocation failed.
Possible flags are: SLAB POISON Poison the slab with pattern 0xa5 to catch references to uninitialized memory. The power of slab allocator lies in its cache: the slabs of the same size are not freed from memory immediatelly. Create a cache that will allocate. int node). align specifies memory alignment of allocated objects. void kfree(const void *buffer). void (*destructor)(void *. SLAB RED ZONE Insert red zones around allocated memory to check for buffer underruns and overruns. kmem cache t *. but this call also zeroes allocated memory. Allocate a buffer on given node (NUMA-specific call). kmem cache t *kmem cache create(const char *name. The cache is identified by its name (used in /proc/slabinfo). kmem cache t *. int flags). size t align. but they are held in cache. unsigned 45 . Allocate buffer of size using kmalloc(). Free memory buffer previously allocated by kmalloc().Chapter 5. void *kmalloc node(size t size. kmem cache t *cachep. The constructor(void *object. size t size. void ksize(const void *buffer). The arguments are the same. void (*constructor)(void *. unsigned long)). unsigned long flags. gfp t flags. unsigned long flags) and destructor(void *object. Slab cache is therefore suitable only for allocations of small pieces of memory. Return the size of buffer previously allocated by kmalloc. Memory Allocation void *kzalloc(size t size. unsigned long). SLAB HWCACHE ALIGN Align the object in this cache to match hardware cacheline. kmem cache t *cachep. free and hold objects of given size. SLAB NO REAP Don’t shrink memory when the system is looking for more available memory.
Shrink cache. one for DMA memory and the other for normal allocations. void *kmem cache alloc node(struct kmem cache t *cachep. Destroy a cache. kmem cache t *kmem find general cachep(size t size. i. Find suitable cache from array of general caches. The caller must take care that no allocation attempt will be made during kmem cache destroy(). Return pointer to the name of the cache. void kmem cache free(kmem cache t *cache. The constructor must be provided if the de- Both callbacks may be implemented by the same function as the constructor() is called with flag SLAB CTOR CONTRUCTOR. Release an object. Many subsystems use of this cache API and create their own caches.Chapter 5. but the memory is kept in cache. int kmem cache shrink(kmem cache t *cache). Constructors and destructors are very rarely used. Return the size of the objects allocated by this cache. SLAB CTOR VERIFY indicates that this call is a verification call. it only marks object as freed. void *object). const char *kmem cache name(kmem cache t *cache). This does not free memory. The cache must be empty before calling this function. Constructor is called only for newly allocated objects. The SLAB CTOR ATOMIC flag indicates that the callback may not sleep. For description of flags see kmalloc().e. This function returns pointer to created cache or NULL if creation failed. There are in fact two arrays. Allocate an object from cache on given node (NUMA-specific call). Memory Allocation long flags) are optional. the most common ones are: 46 . gfp t flags. int nodeid). structor is also given. unsigned int kmem cache size(kmem cache t *cache). Allocate an object from cache. int kmem cache destroy(kmem cache t *cache). Zero return value indicates that all slabs were released. objects held in the cache and return by allocation call do not gain constructor’s attention. gfp t flags). release as many slabs as possible. gfp t gfpflags). void *kmem cache alloc(kmem cache t *cache.
h>) offer high level API for allocating swappable memory. kmem cache t *sighand cachep. Cache for directory entries (struct dentry). kmem cache t *files cachep. Memory Allocation kmem cache t *vm area cachep. void *vmalloc 32(unsigned long size). Cache for fs struct structures. kmem cache t *fs cachep. The allocated space is rounded up to whole pages. Cache for files struct (table of open files). The allocated space is rounded up to whole pages. kmem cache t *dentry cachep.Chapter 5. Cache for signal handler structures (sighand struct). void *vmalloc exec(unsigned long size). Cache for structures (signal struct). Cache for vm area struct structures. void *vmalloc(unsigned long size). This API works with virtually contignuous memory as opposed to slabs. 47 . Allocate a virtually contignuous executable memory of given size. Cache for struct file objects. which don’t understand paging and virtual memory.2 Virtual Memory Allocation Virtual memory allocation functions (<linux/vmalloc. On the other side memory allocated using vmalloc-like functions is accessed through Translation Look-aside Buffer (TLB) instead of direct access. Allocate a virtually contignuous memory of given size. kmem cache t *signal cachep. 5. The allocated space is rounded up to whole pages. which can result in slight overhead when accessing this memory. There is usually no need to use physically contignuous memory except for hardware devices. kmem cache t *filp cachep. Allocate a virtually contignuous (32bit addressable) memory of given size.
Release memory previously allocated by one of vmalloc functions.h>: struct page *alloc pages(unsigned int gfp mask. void vunmap(void *addr). May not be called in interrupt context. GFP HIGHMEM Highmem allocation. VM ALLOC Pages allocated by one of vmalloc functions. This function may not be called in interrupt context. Allocate virtually contignuous memory buffer. 48 . but it’s sometimes the most suitable when writing a hardware device driver. Map an array of pages into virtually contignuous space. unsigned long flags. 5.3 Page Allocation Page allocation is the most elementar of all allocation methods. unsigned int order). gfp mask is combination of following: GFP USER User allocation. VM IOREMAP Mapped from hardware device. void *vmap(struct page **pages. count is the number of pages to be allocated. pgprot t prot). Memory Allocation void * vmalloc(unsigned long size.h> and <linux/mm. Release mapping obtained by vmap. Allocate pages. pgprot t prot). Possible flags: VM MAP Pages mapped by vmap(). gfp mask contains mask of flags for page level allocator (see <linux/gfp.h>) and prot contains protection mask for allocated pages (see <asm/pgtable/h>).Chapter 5. int gfp mask. unsigned int count. prot contains protection mask. Following interface is defined in <linux/gfp. The allocation takes enough pages to cover whole buffer size. GFP KERNEL Kernel allocation. It’s hardware dependent. void vfree(void *addr).
Allocate one page and return pointer to it’s page structure. order is the power of two of allocation size in pages. get free pages(unsigned int gfp mask. unsigned long get zereod page(unsigned int gfp mask).unsigned int order). Allocate one zeroed page and return it’s logical address. unsigned long get free page(unsigned int gfp mask). unsigned int order). Memory Allocation GFP FS Don’t call back into a file system. Free one page. struct page *alloc page(unsigned int gfp mask). unsigned long order) .Chapter 5. void *page address(struct page *page). Without this option the allocator may swap out some pages to free some more physical memory. 49 . Return the pointer to the first page’s structure or NULL if allocation fails. void free page(unsigned long addr). Free previously allocated pages. void free pages(struct page *pages. void free pages(unsigned long addr. Return the logical address of the page. GFP ATOMIC Don’t sleep. Allocate physical pages (see alloc pages()) and return the logical address of the first of them. unsigned int Allocate one page and return it’s logical address. this also prohibits swapping out pages. Free previously allocated pages.
arrival of packet from network. the meaning of an IRQ is to notice software (the kernel in our case) about some event: tick of timer. The handler won’t be entered by the same interrupt more than once. It’s usual to set a software interrupt and exit the handler. which wrote 0x20 to port 0x20. MSDOS programmers probably remember magic sequence. This handlers are usually invoked with interrupts disabled1 Interrupt handlers need to be fast. CPU knows how to handle each interrupt as it has pointers to interrupt handlers stored in a table. The handler runs with interrupts disabled (this is done automatically by CPU on or IRQ controller on some architectures) so it has to run very fast and may not block. The kernel offers interrupt handlers to handle IRQs. . it is queued or dropped. 1 50 .Chapter 6 Handling Interrupts Interrupts signalize operating system about events that occured in hardware devices. The code is split in linux into two layers. 6. if the same IRQ is generated.1 Hardware Interrupts Hardware devices generate interrupt requests from time to time. and thus allowing PIC to report interrupts to CPU again. Standard PCs have been using Programmable Interrupt Controller for a long time. because we don’t want to lose other pending interrupts. Understanding how to properly handle IRQs is essential for device driver developers. this controller takes care of (un)masking individual interrupts. Taskqueues will be executed later with interrupts enabled2 and this way no interrupt should be lost. 2 But taskqueues can disable interrupt while doing something critical. . the interrupt handler usually just queues needed routines as softIRQs or taskqueues (both will be described later) and quits.
May be called from IRQ context. void synchronize irq(unsigned int irq). If the interrupt line is not used by any other driver then the line is blocked. Allocate an interrupt line irq with a handler. Flags can be: • SA SHIRQ . struct pt regs *). void *. Otherwise the new interrupt handler is added to the end of the interrupt handler chain. Remove interrupt handler from irq for given device. Returns true if called in a hardware IRQ. Interrupt lines may be shared by devices if all interrupt handlers are marked with flag SA SHIRQ. Enables irq.Interrupt is shared.Chapter 6. Include <linux/hardirq. void enable irq(unsigned int irq). Disable irq and wait for any handlers to complete. void *device). void free irq(unsigned int irq. void disable irq nosync(unsigned int irq). irqreturn t (*handler)(int. The function does not wait for completion of any running handlers. const char *devname. May be called from IRQ context. Avoid deadlocks. Enables and disables are nested.h> to access following function and macros: in irq(). Disables and enables are nested. unsigned long irqflags. this request irq() will return with error code -EBUSY. This function may be called with care from IRQ context. Disables and enables are nested. void *device). void disable irq(unsigned int irq). int request irq(unsigned int irq. Disable irq without waiting. If there is already any handler bound to this IRQ without this flag set. Handling Interrupts General rule: don’t call any blocking function waiting for IRQ handle that could block while holding a resource that may be used by IRQ handler. Wait for pending IRQ handler exit for irq. This function may be called from IRQ context. It may not be called from from IRQ context. Caller must ensure that interrupt is disabled on the device prior to calling this function. This function does not guarantee that any running handlers have exited before returning. 51 .
Previous kernel version used bottom halves (BH) to process the deferred which didn’t take advantage in using multiple CPUs and developers decided to switch to softIRQs.Local interrupts are disabled while processing. device must be globally unique (e. address of the device data structure). 6.6. device must be non-NULL. Softirqs are statically created and there are 6 softIRQs defined in kernel 2.2 Softirqs and Tasklets Servicing harware interrupt may not take too much time.Interrupt can be used for random entropy.Chapter 6. so the work is split into two parts: the minimal servicing is done in the hardware IRQ handler and the rest is deffered. The interrupt line is enabled after allocation. They’re also reentrant. If the interrupt is shared. Argument devname is the ASCII name for the claiming device and device is a cookie passed back to handler. Handling Interrupts • SA INTERRUPT . moreover one softirq can be run by multiple CPUs at once. Synchronization is essential. Some macros still contain bh substring as a remainder from the past: local bh enable() and local bh disable(). though they actually disable end enable softirqs. • SA SAMPLE RANDOM .g.16: HI SOFTIRQ high priority tasklets TIMER SOFTIRQ timer interrupts NET TX SOFTIRQ network packet transmission NET RX SOFTIRQ network packet receiving SCSI SOFTIRQ SCSI-related processing TASKLET SOFTIRQ tasklets Softirqs can be run by multiple CPUs at once.h> to access following macros and functions: 52 . Include <linux/interrupt.
Chapter 6. Handling Interrupts in softirq(); Return true if in softIRQ. Warning: this macro returns true even if BH lock is held. in interrupt(); Return true if in hardware IRQ of softIRQ. Warning: this macro returns true even if BH lock is held. Tasklets (as opposed to softirqs) can be creating in runtime, so they’ll be of bigger interest to us. They are executed from softirqs and kernel guarantees not to execute one tasklet more than once on multiple CPUs. Tasklets of the same type are serialized, but tasklets of different type may run concurrently. Tasklets are also preferred way of doing things, they’re sufficient for most operations done by the drivers. The tasklet is built aroung following struct: struct tasklet_struct { struct tasklet_struct *next; unsigned long state; atomic_t count; void (*func)(unsigned long); unsigned long data; }; The next field is pointer to next tasklet in the list. func(data) will be called once the tasklet is to be executed. The state can hold zero (meaning: tasklet not in list) or combination of the following values: TASKLET STATE SCHED Tasklet is scheduled for execution. A tasklet without this flag will not start, even if it’s in the tasklet list. TASKLET STATE RUN Tasklet is running (SMP only). Tasklet can be easily declared using DECLARE TASKLET(name, func, data), which declares struct tasklet struct of given name. Disabled tasklet is provided by DECLARE TASKLET DISABLED(name, func, data). void tasklet init(struct tasklet struct *t, void (*func)(unsigned long), unsigned long data); 53
Chapter 6. Handling Interrupts Initialize a tasklet struct structure. This function is suitable for dynamically allocated or reinitialized tasklets. int tasklet trylock(struct tasklet struct *t); Try to lock the tasklet: try to set TASKLET STATE RUN to t->state using atomic operation. Returns true if the tasklet has been locked before the operation. void tasklet unlock(struct tasklet struct *t); Unlock the tasklet using atomic operation. void tasklet unlock wait(struct tasklet struct *t); Wait for tasklet to become unlocked. Warning: busy-loop implementation, this function does not sleep. void tasklet schedule(struct tasklet struct *t); Activate the tasklet, i.e. put it into the beginning of tasklet list for current CPU. void tasklet hi schedule(struct tasklet struct *t); Activate the tasklet, i.e. put it into the beginning of high priority tasklet list for current CPU. void tasklet disable nosync(struct tasklet struct *t); Disable the tasklet, do not wait for termination of tasklet if it’s currently running. void tasklet disable(struct tasklet struct *t); Disable the tasklet, but wait for termination of tasklet if it’s currently running. void tasklet enable(struct tasklet struct *t); Enable the disabled, but scheduled tasklet. void tasklet kill(struct tasklet struct *t); Kill a tasklet. This is done by clearing the state’s flag TASKLET STATE SCHED. void tasklet kill immediate(struct tasklet struct *t, unsigned int cpu); Kill a tasklet. This is done by clearing the state’s flag TASKLET STATE SCHED. Moreover, the tasklet is immediately removed from the list. The cpu must be in CPU DEAD state.
54
Chapter 6. Handling Interrupts Note that scheduled tasklets are kept in per-CPU arrays (one for normal and the second one for high priority tasklets). Before the tasklet is executed its TASKLET STATE SCHED flag is cleared. If the tasklet wants to be executed in the future, it’s TASKLET STATE SCHED flag must be set.
55
This category contains not only process creation and termination. And everything must be done with maximal efficiency. but also switching between processes. TASK UNINTERRUPTIBLE This task is sleeping. process state management. kernel threads and many other things. but it can’t be woken up by signals or timers. it will run when some CPU has time to run it. The process (or thread or task) itself may be in one of many states: TASK RUNNING The task is able to run. The tasks may be even frozen. depending on power management state. TASK TRACED This task is being traced. in-kernel preemption. 56 . TASK NONINTERACTIVE This task won’t be given any penalty or priority-boost due to average sleep time.Chapter 7 Process Management and Scheduling Good process management is feature needed by every multitasking OS. i. but it’s possible to wake it up using signals or expiration of a timer.e. TASK STOPPED Task is stopped either due to job control or ptrace(). TASK INTERRUPTIBLE This task is sleeping.
and uid. struct files struct. Process Management and Scheduling set task state(task. This structure represents directory entry. pending signals. struct thread struct. it contains pointer to root. set current state(state) This macro sets state to task currently running on local CPU. the load balancing algorithm tries to equally divide load between groups in a single domain. struct sched group. Per-process structure of opened files. struct dentry. struct sched domain. A structure for each user. this function uses memory barrier. Each CPU is represented by its own domain and is a leaf in the domain tree. Scheduling group. struct mm struct. Low level per-architecture defined structure containing copy of some CPU registers and similar non-portable things. Memory management information for a process. 57 . state) This macro sets the state to given task. this may be shared by threads in one process. The state should not be directly assigned. This very complicated structure holds all information concerning one process. inotify watches etc. struct task struct.Chapter 7. pwd (current working directory) directory entries etc. which holds number of files opened. Some structures that are used in many parts of process management are described here for easier reference later. This approach allows to make very complicated load balancing even on NUMA machines. struct fs struct. This structure represents a file system. processes running. struct user struct. Scheduling domain create a tree.
one for active tasks and the other for task with already expired timeslices. A VM area is a part of process virtual memory with a special rule for the page-fault handlers. when all tasks run out of their assigned time they get refilled. it will still roundrobin with other interactive tasks. But even the lowest priority thread gets MIN TIMESLICE worth of execution time. There are two priority arrays. The classic nice-value is converted to user static priority. If a task is interactive. Scheduler also does load balancing on SMP/NUMA architectures. When task runs out of its timeslice. Tasks are executed in timeslices. The higher a thread’s priority. which task will be woken up and how long will it run until next task is woken up. However dynamic priority is used when assigning timeslices to tasks. which is increased by one for each jiffy during sleep and decreased while running. The goal of load balancing is to divide computations equally to the CPU nodes. slightly modified by bonuses/penalties. However it wil not continue to run immediately.Chapter 7. we usually put it to expired array. SCALE PRIO scales dynamic priority values [ -20 . This structure describes one area. PRIO TO NICE(prio) maps static priority back to nice-value and TASK NICE(p) returns nice-value of task p. This function interrupts execution of current task and switches to other one. Dynamic priority is based on static priority. For each task a sleep avg value is stored. Timeslices get refilled after they expire. if it sleeps sometimes) and batch tasks (also called cpu hogs) get penalties. which can be easier to use internally in scheduler routines. Interactive tasks get bonuses (we estimate that task is interactive. Process Management and Scheduling struct vm area struct.1 Scheduler The role of the scheduler in multitasking (and multithreading) operating system is to switch between tasks and to decide when to switch. int task timeslice(task t *p) is the interface that is used by 58 . The minimum timeslice is MIN TIMESLICE (currently 5 msecs or 1 jiffy. There is one function that is mentioned fairly often within following sections: schedule(). which holds lists of tasks being run on this cpu. the bigger timeslices it gets during one round of execution. default timeslice is DEF TIMESLICE (100 msecs). we reinsert it in the active array after its timeslice has expired. maximum timeslice is 800 msecs. 19 ] to time slice values. Each cpu has its own runqueue.. 7. NICE TO PRIO(nice) maps nice-value to static priority for internal use. which one is more)..
pointers to current and idle tasks. This approach is in common better than the one in 2.org/node/view/780). Prior to this the task switching was possible in kernel only when process voluntarily rescheduled. 50ms buffer to soundcard and then sleep. With This approach is often criticised. Following macros are being defined for accessing runqueues: cpu rq(cpu) representes runqueue of given cpu. lock acquire operations must be ordered by ascending &runqueue. timestamp of last tick.6 is preemption.g. number of uninterruptible tasks. so that interactive tasks won’t starve non-interactive). pointer to previously used mm struct (used when switchig kernel threads to find out that sometimes there’s no need to switch address space). nr active is number of active tasks. expired timestamp and the best expired priority priority (used to determine when is the time to return tasks from expired array to active array.4 and older kernels. Priority array contains list queue for each priority. number of context switches. static void double rq lock(runqueue t *rq1.. and if other task gains 100ms timeslice this led to audio dropouts 1 59 . 1 The task uses its timeslice in intervals of max TIMESLICE GRANULARITY msecs and then the scheduler tries to execute other tasks of equal priority from the runqueue2 . Process Management and Scheduling the scheduler. task rq(p) finds runqueue belonging to task p and finally cpu curr(cpu) is currently executed task on given cpu. runqueue t *rq2) and static void double rq lock(runqueue t *rq1. runqueue t *rq2) are provided. whether balancing is active for this runqueue (active balance). Con Kolivas’s patches. number processes waiting for I/O. Too little time for minimal timeslice could cause many context switches and thus decreasing performance as the CPU cache is often reloaded. and the following under the assumption of CONFIG SMP being defined: scheduling domain for this CPU/runqueue. cpu load (only when compiled with CONFIG SMP. Thus the task uses its timeslice in parts (if the timeslice is long enough) before being dropped from the active array). As a locking rule is used the following: those places that want to lock multiple runqueues (such as the load balancing or the thread migration code). The bitmap array keeps in mind which list is empty. To make it simpler. this rq() represents runqueue of this processor. 2 This was added because applications like audio players tend to send e. used when migrating tasks between cpus to determine which cpu is heavily loaded and which one is almost idle). Runqueue (runqueue t data type) is the main per-cpu data structure holding number of running tasks. especially the estimating whether a task is interactive.Chapter 7. push cpu. One of the changes introduced in kernel 2. Dynamic priority can be at most 5 points more or less (depends on interactivity) than static priority. There are attempts to write better scheduler/patch the existing one (e. migration thread and migration queue.g.
thus we use 25% of the full priority range. the priority based on static priority but modified by bonuses/penalties. See ”Locking” chapter for details about preemption. i. int can nice(const task t *p. FPU state: FPU should be used only with preemption disabled (the kernel does not save FPU state except for user tasks. Note: some FPU functions are already preempt-safe.g. void set user nice(task t *p. Set nice value of task p. The more time a task spends sleeping. 7. Externally visible scheduler statistics are in struct kernel stat kstat. based on ->timestamp. The boost works by updating the ’average sleep time’ value here. Recalculates priority of given task. kernel fpu begin() and kernel fpu end() should be used around areas that use FPU. which is defined per cpu. Lock of runqueue the task belongs in is locked during execution. Tasks with low interactive credit are limited to one timeslice worth of sleep avg bonus. This ensures us that the +19 interactive tasks do not preempt 0 nice-value cpu intensive tasks and -20 tasks do not get preempted by 0 nice-value tasks. Next problem is protecting CPU state.Chapter 7. Tasks with credit less or equal than CREDIT LIMIT waking from uninterruptible sleep are limited in their sleep avg rise as they are likely to be cpu hogs waiting on I/O. unsigned long long now). The lower the sleep avg a task has the more rapidly it will rise with sleep time. Process Management and Scheduling preemption it is to switch task at almost any time. Exported symbol.. e. so preemption could change the contents of FPU registers). Exported symbol. Check whether task p can reduce its nice value. This code gives a bonus to interactive tasks. const int nice). 60 .1 Priority static int effective prio(task t *p). long nice).1.e. static void recalc task prio(task t *p. User tasks that sleep a long time are categorised as idle and will get just interactive status to stay active and to prevent them suddenly becoming cpu hogs and starving other processes. Return the effective priority. the higher the average gets . Bonus/penalty range is +-5 points.and the higher the priority boost gets as well. Preemptions uses SMP locking mechanisms to avoid concurrency and reentrancy problems.
Get the realtime priority of a thread and store it to user-space. asmlinkage long sys sched get priority min(int policy). 7. This function locks the runqueue for a given task and disables interrupts. Return the nice value of a given task. asmlinkage long sys sched get priority max(int policy). Realtime tasks are offset by -200. static inline void task rq unlock(runqueue t *rq.1. value goes from -16 to +15. asmlinkage long sys sched setparam(pid t pid. normal tasks are arounf 0. Preemption is not disabled during execution of this function. unsigned long *flags). Exported symbol. Add to the priority of the current process increment value. the same case as with task rq lock(): we need to disable 61 . Lock runqueue. Return maximum realtime priority that can be used by a given scheduling class. Set/change the realtime priority of a thread to the values obtained from userspace.2 Runqueues static runqueue t *task rq lock(task t *p. Return the priority of a given task. int task prio(const task t *p). struct sched param user *param). struct sched param user *param). this is the priority value as seen by users in /proc int task nice(const task t *p). asmlinkage long sys sched getparam(pid t pid. tasklist lock is read-locked during execution. This function unlocks the runqueue (possible locked by task rq lock) static runqueue t *this rq lock(void). unsigned long *flags).Chapter 7. Process Management and Scheduling asmlinkage long sys nice(int increment). Return minimum realtime priority that can be used by a given scheduling class. This function is available only with ARCH WANT SYS NICE defined.
remove it from appropriate list and (if needed) set the bit to indicate that list is empty. prio array t *array). etc. runqueue t *rq). static void dequeue task(struct task struct *p. Adds task to end of appropriate list and sets bit to indicate that the list is surely not empty. prio array t *array). static void resched task(task t *p). static inline void activate task(task t *p. Process Management and Scheduling interrupts first and then lock the spinlock (due to SMP and preemption. 62 . we pull tasks from the head of the remote queue so we want these tasks to show up at the head of the local queue. priority modifiers. on SMP it might also involve a cross-cpu call to triger the scheduler on the target cpu. need resched flag. static void enqueue task(struct task struct *p. static inline void enqueue task head(struct task struct *p. Remove a task from the runqueue. This is used by the migration code (that means migration between cpus).Chapter 7. static void activate task(task t *p. runqueue t *rq. i. prio array t *array). static inline void activate idle task(task t *p.c]) static inline void rq unlock(runqueue t *rq). Only on SMP. runqueue t *rq). int local). static runqueue t *find busiest queue(struct sched group *group). Move idle task to the front of runqueue. runqueue t *rq). Move a task to the runqueue and do priority recalculation. details in [kernel/sched. Unlock the runqueue. Move given task to given runqueue. Find the busiest runqueue among the CPUs in group. Adds task to beginning of appropriate list and sets bit to indicate that the list is surely not empty. update all the scheduling statistics stuff (sleep average calculation.) static void deactivate task(struct task struct *p. SMP version also does preempt disable in the beginning and preempt enable in the end.e. Remove a task from priority array.
7. note that this does not restore interrupts. If 63 . Load balancing happens between groups. During execution it may be unlocked and locked again later (to prevent deadlock). void double lock balance(runqueue t *this rq. runqueue t *busiest). runqueue t *rq2). Only on SMP. load balancing between groups occurs. rebalance tick() is the function that is called by timer tick and checks if there is any need to do load balancing.Chapter 7.1. The other case is setting the scheduling domain sd. This does not disable interrupts like task rq lock. the root domain’s parent is NULL. they are read-only after they’ve been set up. which are organised as one-way circular list. Process Management and Scheduling Following functions are provided to prevent deadlock while locking runqueues’ spinlocks: static void double rq lock(runqueue t *rq1. When the load of a group is out of balance. The union of CPU masks of these groups must be identical to CPU mask of the domain and the intersection of any of these groups must be empty.3 Load Balancing and Migration Following functions are intended for migration tasks between CPUs. therefore are conditionaly compiled only if CONFIG SMP is defined. Scheduling domains are percpu structures as they are locklessly updated. these domains create a tree-like structure. Each cpu has its scheduling domain. task is the task that is being moved to the dest cpu. you need to do so manually before calling. Safely unlock two runqueues. Domain has parent pointer. Groups are (unlike domains) shared between CPUs. which is sum of loads of CPUs that belong into this group. this rq is locked already. Each group has its load. runqueue t *rq2). This function should be used to prevent deadlock when locking two runqueues. Each domain spans over a set of CPUs. Lock the busiest runqueue. Completion mechanism is used for executing migration request. Scheduling domains are new approach to SMT/SMP/NUMA scheduling. There are two possible types of request (request type): REQ MOVE TASK (for migrating between processors) and REQ SET DOMAIN (for setting scheduling domain) Following struct (migration req t) is used to hold migration request details. static void double rq unlock(runqueue t *rq1. registered in cpumask t span. Safely lock two runqueues. these CPUs belong to one or more struct sched group (pointed to by struct sched group *groups. type keeps type of request: REQ MOVE TASK or REQ SET DOMAIN.
SD BALANCE EXEC Balance on exec(). Returns a low guess at the load of a migration-source cpu. Tries to migrate task p to given dest cpu. SD SHARE CPUPOWER Domain members share cpu power. static inline unsigned long source load(int cpu). SD WAKE AFFINE Wake task to waking CPU SD WAKE BALANCE Perform balancing at task wakeup. returns true if you have to wait for migration thread. e. static inline unsigned long target load(int cpu).Chapter 7. SMT architectures. SD WAKE IDLE Wake to idle CPU on task wakeup. balance the domain and then check the parent domain. migration req t *req). this is quite effective.g. int dest cpu. to balance conservatively. 64 . We want to underestimate the load of migration sources. Each scheduling domains can have set the following flags: SD BALANCE NEWIDLE Balance when about to become idle. Process Management and Scheduling is is so. Migration routines: static int migrate task(task t *p. Returns a high guess at the load of a migration-target cpu. without any delay (to get signals handled). since ’execed’ task is not cache hot on any CPU. Causes a process which is running on another CPU to enter kernel-mode. SD BALANCE CLONE Balance on clone(). The task’s runqueue lock must be held. again check for need for balancing and so forth. void kick process(task t *p).
runqueue t *rq. because at this point the task has the smallest effective memory and cachce footprint. static inline int can migrate task(task t *p. static int find idlest cpu(struct task struct *p. struct sched domain *sd. enum idle type idle). int this cpu. int this cpu). Find the highest-level. static void sched migrate task(task t *p. struct task struct *p. Find and return the least busy CPU group within the domain sd. task t *p. execve() is a good opportunity. runqueue t *this rq. Move a task from a remote runqueue to the local runqueue. 65 . enum idle type idle). prio array t *src array. int dest cpu). void sched exec(void). Only on SMP. both runqueues must be locked. least busy runqueue on SMP machine. int this cpu). int this cpu. int sched balance self(int cpu. Find the the idlest CPU i. Only on SMP. If dest cpu is allowed for this process. which will force the cpu onto dest cpu. int flag). static struct sched group *find busiest group(struct sched domain *sd. Find and return the busiest cpu group within the domain.Chapter 7. Preemption must be disabled prior to calling this function. Calculate and return the number of tasks which should be moved to restore balance via the imbalance parameter. unsigned long *imbalance. struct sched domain *sd). Only on SMP machines. Then the cpu allowed mask is restored.e. This is accomplished by forcing the cpu allowed mask to only allow dest cpu. Balance the current task running on given cpu in domains that have flag set. Only on SMP. static inline void pull task(runqueue t *src rq. Target CPU number is returned or this CPU if no balancing is needed. Process Management and Scheduling struct sched group *find idlest group(struct sched domain *sd. int this cpu. migrate the task to it. prio array t *this array. exec-balance-capable domain and try to migrate the task to the least loaded CPU. The least loaded group is selected.
static void active load balance(runqueue t *busiest. struct sched domain *sd. static int load balance newidle(int this cpu. Attempt to move tasks if there is an imbalance. Only on SMP. 66 . Check this cpu to ensure it is balanced within domain. static int move tasks(runqueue t *this rq. Locks of this rq and busiest runqueue in the domains may be locked during executions. enum idle typeidle). Only on SMP. Beware: this rq is being locked and not unlocked upon return. It pushes a running task off the cpu. runqueue t *this rq. enum idle type idle). struct sched domain *sd. struct sched domain *sd). This function is called by schedule() if this cpu is about to become idle. Process Management and Scheduling May the task p from runqueue rq be migrate onto this cpu ? We can’t migrate tasks that are running or tasks that can’t be migrated due to cpus allowed or are cache-hot on their current cpu. runqueue t *this rq). however the lock is a few times relocked to ensure there’ll be no deadlock. unsigned long max nr move. Must be called with busiest locked. runqueue t *this rq.Chapter 7. It can be required to correctly have at least 1 task running on each physical CPU where possible. It attempts to pull tasks from other CPUs on SMP. and not have a physical / logical imbalance. Check this cpu to ensure it is balanced within domain. int this cpu. static int load balance(int this cpu. as part of a balancing operation within domain. no unlocking is being done. Only on SMP. static void rebalance tick(int this cpu. static inline void idle balance(int this cpu. Must be called with this rq unlocked. Must be called with both runqueues locked. on UP does nothing. This function is run by migration threads. runqueue t *this rq. Returns the number of tasks moved. Only on SMP. Attempt to move tasks if there is an imbalance. runqueue t *busiest. but they are finally unlocked. Try to move up to max nr move tasks from busiest to this rq. enum idle type idle). Called from schedule when this rq is about to become idle (NEWLY IDLE). int busiest cpu).
In systems capable of hotplugging. asmlinkage long sys sched getscheduler(pid t pid). int policy. int . Wrapper for do sched setscheduler(). asmlinkage long sys sched setscheduler(pid t pid. static void prio). struct sched param user *param). struct sched param user *param). task t *idle task(int cpu). on every CPU on SMP. Change the scheduling policy and/or realtime priority of a task to the values obtained from user-space. Exported symbol. cpu possible map. asmlinkage long do sched setscheduler(pid t pid. asmlinkage long sys sched setaffinity(pid t pid. Process Management and Scheduling This function will get called every timer tick. This represents all cpus present in the system. int policy. read-locked tasklist lock. During execution are disabled irqs. which is map of all online CPUs (initally CPU MASK ALL). unsigned int len. which 67 user *param). static int setscheduler(pid t pid. this map could dynamically grow as new cpus are detected in the system via any platform specific method. unsigned long user *user mask ptr). On uniprocessors this function does nothing.Chapter 7. On SMP following cpu mask maps (cpumask t) are declared: cpu online map. Check each scheduling domain to see if it is due to be balanced. runqueue lock must be held. int policy. tasklist lock is read-locked during execution. Balancing parameters are set up in arch init sched domains. locked runqueue lock of appropriate task. int policy. Get the policy (scheduling class) of a thread. Set the cpu affinity of a process. struct sched param from usermode. Set/change the scheduler policy and realtime priority to the values obtained setscheduler(struct task struct *p. Change priority. Values are obtained from user-space. Return idle task for given cpu. cpumask t cpu present map. and initiates a balancing operation if so.
data runqueue’s lock is held during execution. static void migrate nr uninterruptible(runqueue t *rq src). which is map of CPUs with switched-off Hz timer (initally and on systems that do not switch off the Hz timer CPU MASK NONE) long sched getaffinity(pid t pid. We’re doing this because either it can’t run here any more (set cpus allowed() away from this cpu. or because we’re attempting to rebalance this task on exec (sched balance exec). unsigned int len. Wrapper for sched getaffinity(). This is a high priority system thread that performs thread migration by bumping thread off cpu then ’pushing’ onto another runqueue. the task must not exit() & deallocate itself prematurely. static void move task off dead cpu(int dead cpu. SMP only. SMP only. Move (not current) task off this cpu. The mask is copied to userspace. Both source and destination CPUs’ runqueue-locks are held. int set cpus allowed(task t *p. cpumask t new mask). int src cpu. The caller must have a valid reference to the task. Adds nr uninterruptible statistics from (rq src) to any online CPU.e. Task’s runqueue lock is being held during execution and irqs are disabled. unsigned long user *user mask ptr). This function moves task tsk from CPU dead cpu that went offline. Migrate the thread to a proper CPU (if needed i. struct task struct *tsk). The call is not atomic. or cpu going down when using hotplug). int Cpu hotplugging is locked and dest cpu). Process Management and Scheduling is map of all possible CPUs (initially CPU MASK ALL) and nohz cpu mask. cpumask t *mask) Get the cpu affinity of a process. Sometimes nr uninterruptible is not updated for performance reasons and this 68 . static int migration thread(void * data). SMP only. Exported symbol. no spinlocks may be held. onto dest cpu. the current task’s cpu is not enabled in the new mask) and schedule it away if the CPU it’s executing on is removed from the allowed bitmask. tasklist lock is read-locked. Change a given task’s CPU affinity. asmlinkage long sys sched getaffinity(pid t pid.Chapter 7. static void migrate task(struct task struct *p.
Process Management and Scheduling way the sum of numbers of TASK UNINTERRUTIBLE tasks on all CPUs is correct. IRQs are blocked and tasklist lock is being held during this operation. That cpu’s rq gets locked for a while. Start one migration thread for boot cpu and register cpu migration notifier. It’s done by boosting its priority to highest possible and adding it to the front of runqueue. unsigned long action. task t *tsk). SMP only. int migration call(struct notifier block *nfb. Used by cpu offline code. This lock is dropped around migration. Run through task list on src cpu CPU and migrate tasks from it. void *hcpu). IRQs are disabled and runqueues’ locks are locked while updating statistics. Current cpu’s runqueue lock is held during execution and interrupts are disabled. Migration thread for this new CPU is started and stopped here and tasks are migrated from dying CPU. Schedule idle task to be the next runnable task on current CPU. SMP only. If cpu’s going up was canceled (this could happen only with cpu hotplugging) stop the migration thread. static int migration call(struct notifier block *nfb. This is a callback that gets triggered when a CPU is added or removed. When a new cpu goes up.Chapter 7. unsigned long action. int init migration init(void). The runqueue lock must be held before calling this function and released afterwards. Ensures that the idle task is using init mm right before its cpu goes offline. migrate all tasks somewhere else and stop migration thread. new migration thread is created and bind to that cpu. When a new cpu goes online. Callback that gets triggered when a CPU is added. Dead cpu’s runqueue gets locked for a while. Migrate exiting task from dead CPU. When cpu dies. 69 . Migrate exiting tasks from dead CPU. static void migrate live tasks(int src cpu). static void migrate dead tasks(unsigned int dead cpu). wake up migration thread. Here we can start up the necessary migration thread for the new CPU. void sched idle next(void). void *hcpu). void idle task exit(void). static void migrate dead(unsigned int dead cpu.
Degenerate domain either contains only one CPU. Process Management and Scheduling This thread has the highest priority so that task migration migrate all tasks happens before everything else. int source. the number of steps (when not implicitly given on command line. static int sd parent degenerate(struct sched domain *sd. this table is boot-time calibrated). Return value is the number of domains on way between CPUs. int cpu). void cpu attach domain(struct sched domain *sd. so that L2 cache will miss and filled with values from this . The migration factor is given in percents and measures the cost of migration.Chapter 7. This function sets up a migration cost table: unsigned long long migration cost[MAX DOMAIN DISTANCE]. i. int target). Dirty a big buffer. static int sd degenerate(struct sched domain *sd). int init migration cost setup(char *str). This table is a function of ’domain distance’. unsigned long domain distance(int cpu1. int cpu2). void touch cache(void * cache. i. Build a circular linked list of the groups covered by the given span. int (*group fn)(int cpu)). unsigned long buffer. 70 size). unsigned long size. retrieve the option given on kernel command line. Estimated distance of two CPUs. Check whether the parent is not degenerated and compare CPU sets of parent and sd and flags to find degeneration.e. Attach the scheduling domain to given cpu as its base domain. Only on SMP. static unsigned long long measure one(void *cache. or if it has set any balacing flag concerning waking processes. This function returns the cache-cost of one task migration in nanoseconds. struct sched domain *parent). or if it supports internal load balancing and has only one group. void init sched build groups(struct sched group groups[].e. cpumask t span. int init setup migration factor(char *str). Return true if scheduling domain is not degenerate. CPU hotplug gets locked during execution. so does given cpu’s runqueue lock and irqs are disabled. Set migration factor.
int find next best node(int node. int cpu2). void *cache. unsigned long long nr context switches(void). unsigned long nr uninterruptible(void).1. 7. cpumask t sched domain node span(int node). Return number of context switches since bootup. static void init arch init sched domains(void). Measure migration cost between two given CPUs. unsigned int size) . Get a CPU mask for a node’s scheduling domain. CONFIG SMP and not ARCH HAS SCHED DOMAIN If ARCH HAS SCHED DOMAIN is not defined then struct sched group sched group cpus[NR CPUS] contains schedule group information for each cpu and for each CPU is declared struct sched domain cpu domains. Measure the cache-cost multiple times for different cache sizes using measure one() between cpu1 and cpu2. they’re copied for each CPU. If CONFIG NUMA defined and ARCH HAS SCHED DOMAIN undefined then struct sched group sched group nodes[MAX NUMNODES] contains schedule groups for each node and the struct sched domain contains schedule domains for each cpu in node domains. Then measure the cost on each CPU itself and the difference is the extra cost that the task migration brings. Process Management and Scheduling unsigned long long measure cost(int cpu1. This function calibrates migration costs for a set of CPUs. Return number of uninterruptible processes. unsigned long *used nodes).4 Task State Management and Switching unsigned long nr running(void). int cpu2. Find the next node to include in a given scheduling domain. unsigned long long measure migration cost(int cpu1. Since these structures are almost never modified but they are fairly often accessed.Chapter 7. 71 . Assumptions: Set up domains for each cpu and groups for each node. void calibrate migration costs(const cpumask t *cpu map). Return number of running processes.
p is forked by current process. Waits for a thread to unschedule. or it may introduce deadlock with smp call function() if an interprocessor interrupt is sent by the same process we are waiting to become inactive. Put it on the run-queue if it’s not already there. one half goes to forked process p. The current thread is always on the run-queue (except when the actual re-schedule is in progress). Performs scheduler related setup for a newly forked process p. Process Timeslice of current proces is split in two. interruptible or uninterruptible processes. The caller must ensure that the task will unschedule sometime soon. This symbol is exported. void wait task inactive(task t * p). static int try to wake up(task t * p. The arguments are: thread to be woken up (p). state mask to be woken allows to wake stopped. Process Management and Scheduling unsigned long nr iowait(void). the mask of task states that can be woken (state) and whether awakening should be synchronous (sync). state. else this function might spin for a long time. unsigned int state). Simple wrapper to call try to wake up(p. Returns failure only if the task is already active. This function can’t be called with interrupts off. This function (conditonally compiled under assumption ARCH HAS SCHED WAKE IDLE being defined) is useful on SMT architectures to wake a task onto an idle sibling if we would otherwise if we would otherwise wake it onto a busy sibling inside a scheduling domain. Just a wrapper to wake up a process using call to try to wake up() without synchronisation.Chapter 7. Returns the cpu we should wake onto. task t *p). Wakes up a process. The remainder of the first timeslice might be recovered by the parent if the child exits early enough. and as such you’re allowed to do the simpler current->state=TASK RUNNING to mark yourself runnable without the overhead of this. int sync). The other version ( ARCH HAS SCHED WAKE IDLE undefined) returns just cpu from argument. 72 . Return number of processes waiting for I/O. unsigned int state. int fastcall wake up process(task t * p). int fastcall wake up state(task t *p. 0). static int wake idle(int cpu. void fastcall sched fork(task t *p).
see schedule() for details. If so. and finish arch switch() (done in this function) will unlock it along with doing any other architecture-specific cleanup actions. This should be called with runqueue lock held and interrupts disabled.) void schedule tail(task t *prev). Process Management and Scheduling Local IRQs are being disabled inside this function and in the end enabled. We enter this with the runqueue still locked. wake it up and do some initial scheduler statistics housekeeping that must be done for every newly created process. task t *prev. Switch to the new MM and the new process’s register state. Note that we may have delayed dropping an mm in context switch(). task t *next). task t *prev). This way the parent does not get penalized for creating too many threads. task t *next). &flags) and unlocks it in the end. This is the first thing a freshly forked thread must call. Calls finish task switch(). the argument prev is the thread we just switched away from. Argument prev is the thread we just switched away from. Prepare to switch tasks from rq runqueue to next: locking and architecture specific things. Does some clean-up after task-switch. finish task switch() must be called. we finish that here outside of the runqueue lock by calling mmdrop() (Doing it with the lock held can cause deadlocks. void fastcall wake up new task(task t *p.Chapter 7. void finish task switch(task t *prev). This function must be called after the context switch with runqueue lock held and interrupts disabled. void prepare task switch(runqueue t *rq. When the switch is finished. Locks task rq lock(current. void fastcall sched exit(task t * p). This function also locks spin lock init(&p->switch lock) but it doesn’t unlock it. static inline task t *context switch(runqueue t *rq. preemption can also be disabled sometimes. Locks locked by prepare task switch() are unlocked and architecure specific things are done. Retrieves timeslices from exiting p’s children back to parent. Disables local irqs and locks runqueue of p’s parent during execution. Return previous task. unsigned long clone flags) Put the p task to runqueue. void finish task switch(runqueue t *rq. 73 .
void account system time(struct task struct *p. runqueue t *rq. void account steal time(struct task struct *p. If a user task with lower static 74 . . unsigned long long now). If an SMT runqueue rq is sleeping due to priority reasons wake it up. Only on SMT architectures. otherwise dummy function. runqueue t *rq. otherwise dummy. when changing the parent’s timeslices. task t *p). static inline int dependent sleeper(int cpu. It also gets called by the fork code. This function gets called by the timer code. e. void wakeup busy runqueue(runqueue t *rq). struct sched domain *sd). The function reschedules idle tasks on cpus within domain of given runqueue. int hardirq offset. unsigned long long current sched time(const task t *tsk). Account system cpu time to a process.g. (SMT CPU’s threads don’t run always at same speed. Account user cpu time to a process. If an SMT sibling task is sleeping due to priority reasons wake it up now. cputime t cputime). cputime t steal). unsigned long smt slice(task t *p. Account for involuntary wait time. void account user time(struct task struct *p. shared FPU. . with HZ frequency. runqueue t *rq).) static inline void wake sleeping dependent(int cpu. cputime t cputime). This CPU’s runqueue lock is locked during execution. If an SMT sibling task has been put to sleep for priority reasons reschedule the idle task to see if it can now run. int sys ticks). void update cpu clock(task t *p. Return number of timeslices lost to process running on multi-thread sibling execution unit.Chapter 7. Process Management and Scheduling static inline int wake priority sleeper(runqueue t *rq). We call it with interrupts disabled. void scheduler tick(int user ticks. Return time since last tick/switched that wasn’t added to p->sched time. Update task’s time since the last tick/switch. Only on SMT architectures.
Note: We must be atomic when calling this function. void fastcall complete all(struct completion *x). This is improved preempt schedule(). Wake up task from x->wait and increase x->done. 75 . which enables local IRQs before calling schedule() and disables them afterwards. void fastcall complete(struct completion *x). asmlinkage void sched preempt schedule irq(void). x->wait. Only with preemptible kernels. Exported symbol. x->wait. asmlinkage void sched schedule(void).lock gets locked (and irqs disabled) before and unlocked (and irqs restored) after waking up a task. Exported symbol. or wake it up if it has been put to sleep for priority reasons. delay it till there is proportionately less timeslice left of the sibling task to prevent a lower priority task from using an unfair proportion of the physical cpu’s resources. unsigned mode. Exported symbol. void *key).) so that high priority tasks will be executed first (that also means interactive tasks have some advantage due to higher dynamic priority). if it is so do balance.lock gets locked (and irqs disabled) before and unlocked (and irqs restored) after waking up a task. Try to wake up current task from curr waitqueue. int sync. preemption is being disabled inside and this CPU runqueue’s lock is held. Exported symbol. Reschedule a lower priority task on the SMT sibling. Jump out if irqs are disabled or preempt count() is non-zero. Exported symbol. This is the main scheduler function. Exported symbol. Wake up task from x->wait and increase x->done by UINT MAX/2 value. This is is the entry point to schedule() from preempt enable() if there is need to reschedule. asmlinkage void sched preempt schedule(void).Chapter 7. then we check if we’ve not run out tasks in our runqueue. int default wake function(wait queue t *curr. If all tasks assigned this CPU are in expired array then switch expired and active array and set best expired priority to hightest (rq->best expired prio = MAX PRIO. Process Management and Scheduling priority than the running task on the SMT sibling is trying to schedule. First we manage here gathering interactive credit of task currently being unscheduled.
Exported symbol. chain with q.lock is held inside but unlocked before each schedule() call and locked upon return. long timeout). call schedule() and remove this new runqueue from q. chain with q. long fastcall sched interruptible sleep on timeout( wait queue head t *q. Exported symbol. chain with q. schedule timeout(). add current task. long fastcall timeout). Improved version of sched wait for completion() that uses interruptible sleep and schedule timeout(). x->wait. void fastcall sched sleep on(wait queue head t *q). Create new waitqueue.Chapter 7. unsigned long fastcall Improved version sched wait for completion timeout(struct of sched wait for completion() that uses completion *x. q’s lock is held while manupulating q. wait for completion interruptible timeout(struct completion *x. unsigned long timeout). Set current task’s state to TASK UNINTERRUPTIBLE and call schedule until we’re done. Exported symbol. mark it as TASK UNINTERRUPTIBLE. q’s lock is held while manupulating q. Process Management and Scheduling void fastcall sched wait for completion(struct completion *x) If completion is not ’done’ then create waitqueue (with WQ FLAG EXCLUSIVE) and chain x->wait to the tail of this new waitqueue. void fastcall sched interruptible sleep on( wait queue head t *q ). unsigned long timeout). mark it as TASK INTERRUPTIBLE. call schedule timeout() and remove this new runqueue from q. unsigned long fastcall sched sched sched wait for completion() that uses interruptible wait for completion interruptible(struct completion *x). Create new waitqueue. add current task. 76 sched sleep on timeout(wait queue head t *q. unsigned long fastcall Improved version of sleep. Create new waitqueue. call schedule() and remove this new runqueue from q. q’s lock is held while manupulating q. long . add current task. Exported symbol. Also unlocked when exiting function.
Exported symbol. Process Management and Scheduling Create new waitqueue. throttling IO wait (this task has set its backing dev info: the queue against which it should throttle). static inline struct task struct *eldest child(struct task struct *p). asmlinkage long sys sched yield(void). struct timespec user *interval). call schedule timeout() and remove this new runqueue from q. Exported symbol. add current task. Sets current task’s state to TASK RUNNIG and calls schedule(). drop the given lock. q’s lock is held while manupulating q. Exported symbol. Realtime tasks will just roundrobin in the active array. void sched cond resched(void). If a reschedule is pending. Exported symbol. Yield the current processor to other threads by moving the calling thread to the expired array. A value of 0 means infinity. If there are no other threads running on this CPU then this function will return. asmlinkage long sys sched rr get interval(pid t pid. tasklist lock is locked during execution. Return the eldest child of a task. Don’t do that if it is a deliberate.Chapter 7. mark it as TASK UNINTERRUPTIBLE. Conditionally reschedule with SoftIRQs enableed. Mark this task as sleeping on I/O. chain with q. This CPU’s runqueue spinlock is locked during execution. Increment rq->nr iowait so that process accounting knows that this is a task in I/O wait state. int sched cond resched softirq(void). Exported symbol. Exported symbol. int cond resched lock(spinlock t *lock). schedule(). void sched io schedule(void). 77 . void sched yield(void). It is done via marking thread runnable and calls sys sched yield(). long sched io schedule timeout(long timeout). Yield the current processor to other threads. and on return reacquire the lock. Return the default timeslice od a process into the user-space buffer. The same as io schedule but limited with timeout.
Process Management and Scheduling static inline struct task struct *older sibling(struct task struct *p). siblings. static void show task(task t * p). Simple timeout is used to prevent message flooding. Then the task si rescheduled. Move idle task to given cpu and make it idle (however the task is still marked TASK RUNNING). task t *curr task(int cpu). void show state(void). . tasklist lock is being held during execution. Return true if addr is in memory range belonging to scheduler functions and false otherwise. Helper funtion that writes warning about call to sleeping function from invalid context and dumps stack if IRQs are disabled and preemption disabled and kernel not locked. static inline struct task struct *younger sibling(struct task struct *p). The boot idle thread does lazy MMU switching as well int in sched functions(unsigned long addr). Both source and destination runqueues are locked and irqs are disabled. Print (via printk) some information about given task: pid.Chapter 7. int line). Exported symbol. Return younger sibling of a task. Calls show task on all threads of all processes. eldest child process. Initialize runqueues and the first thread. Return older sibling of a task. Only when CONFIG DEBUG SPINLOCK SLEEP defined. . int cpu). otherwise dummy function. void init sched init(void). parent’s pid. void init sched init smp(void). Call arch init sched domains() and sched domain debug() on SMP. void devinit init idle(task t *idle. Return the current task for given cpu 78 . void might sleep(char *file.
Process Management and Scheduling void set curr task(int cpu. Is a given cpu idle currently ? Exported symbol. signal handlers.6.16 also unshare() to unshare some parts of process context shared since clone(). Number of threads. Linux also supports clone() syscall and since 2. signal struct. inline int task curr(const task t *p).h>. int max threads. int nr threads. files struct. Child receives zero return value and parental process receives the PID of the child. but some parts are not yet implemented.2 Process Forking Creation of new processes under unix-like operating systems is done by fork() system call. Set the current task for a given cpu. The maximal number of threads. Should be at least 20 (to be safely able to 79 . Almost everything that can be shared using clone() can be later unshared by unshare() syscall. . vm area struct and mm struct to speed up memory allocations. fs struct. Protected by write lock irq(&tasklist lock). Memory for task structures is allocated from slab caches: task struct. int idle cpu(int cpu). sighand struct. signed long timeout) Mark task as TASK UNINTERRUPTIBLE and sleep with timeout. signed long timeout) Mark task as TASK INTERRUPTIBLE and sleep with timeout.Chapter 7. The clone() syscall offers more options: the processes may share memory. the idle ones do not count. task t *p). file descriptors. which forks one process into two processes. complete list is in <linux/sched. Sleep current task until timeout expires. signed long sched schedule timeout(signed long timeout). The simplest operation is fork(). . Is this task currently being executed on a CPU ? sched schedule timeout uninterruptible(signed long sched schedule timeout interruptible(signed long 7.
one for whoever does the release task() (usually parent)). however the default maximum is so big that the thread structures can take up to half of memory. Return NULL if memory allocation fails. unsigned long total forks. Total number of forks done since boot. void *alloc task struct() Allocate memory for task struct. Duplicate task struct and its thread info. Warn when task is dead. void put task struct(struct task struct *t). Defined per CPU. Free memory allocated by task struct and its thread info.Chapter 7. Read-write lock protecting access to task list and nr threads. holds number of processes for each CPU3 . void put task struct cb(struct task struct *tsk). int nr processes(void). unsigned long process counts=0. Return value is pointer to allocated memory or NULL pointer in case of failure. Decrease reference counter and free task if counter has dropped to zero. If needed save FPU state and disable preemption while preparing to copy. rwlock t tasklist lock. but at least 20 threads. Create a slab on which task structs can be allocated and set maximum number of threads so that thread structures can take up to half of memory. for exact numbers look at the runqueues 3 80 . Counts total number of processes (the sum of process counts for each CPU). zombie or current. Process Management and Scheduling boot). Set the resource current and maximal resource limit to max threads/2 static struct task struct *dup task struct(struct task struct *orig). This is the RCU callback to free tsk. void init fork init(unsigned long mempages). Exported symbol. Increase task struct->usage by 2 (one for us. void free task(struct task struct *tsk). As far as I found this is not changed when process migrates from between CPUs.
otherwise return 0. Otherwise copy mem policy. Allocate. and try to allocate page directory. Return zero on success. Note: this function is fully implemented only with CONFIG MMU. do not try to free the anchor of mmlist list. void fastcall mmdrop(struct mm struct *mm). Free page directory structure. static inline int mm alloc pgd(struct mm struct *mm). Allocate a struct mm struct from slab cache mm cachep. static inline void mm free pgd(struct mm struct *mm). otherwise it is an empty macro. Warn when mm is init mm. Process Management and Scheduling static inline int dup mmap(struct mm struct *mm. otherwise return 0. Write-lock oldmm->mmap sem semaphore. i. Note: this function is fully implemented only with CONFIG MMU. Initialize mm struct: set number of users to one.e. duplicate mm struct and initialize some fields and memory region descriptors of a mm struct. fill it with zeroes and if something fails return -ENOMEM otherwise zero. struct mm struct *oldmm). Add it to the mmlist after the parent (mmlist lock spinlock held). Allocate page directory structure. Free the page directory and the mm. unlock locks. Note: this function is fully implemented only with CONFIG MMU. 4 Too complex and too internal to spent more time on this function 81 . Free previously allocated struct mm struct.Chapter 7. If the last fails free mm memory (note: this memory is not allocated in this function) and return NULL otherwise mm. fill with zeros and initialize an mm struct. void free mm(struct mm struct *mm). page table entries etc4 . Locks mm->page table lock and ->vm file->f mapping->i mmap lock. static struct mm struct *mm init(struct mm struct *mm). Return NULL on failure and pointer to mm struct on success. If VM DONTCOPY is set then don’t copy anything. Called when the last reference to the mm is dropped: either by a lazy thread or by mmput. struct mm struct *mm alloc(void). void *allocate mm().
static int copy mm(unsigned long clone flags. If flag CLONE VM is set then just set pointers tsk->mm and tsk->active mm to current->mm and return 0. Allocate a new mm struct and copy from task’s mm. If allocation failed in the beginning then return NULL. Return a struct mm struct for given task. Decrement the use count and release all resources for an mm. This function is called after a mm struct has been removed from the current process. void mm release(struct task struct *tsk. initialize new context and call dup mmap(). This function also increases reference counter for return mm struct. Exported symbol. static inline struct fs struct * copy fs struct(struct fs struct *old) Allocate memory for new struct fs struct. Spinlock mmlist lock is held while mm is removed and mmlist nr decreased. NULL value is returned if flags contain PF BORROWED MM or if the task has no mm. complete tsk->vfork done completion.Chapter 7. Process Management and Scheduling void mmput(struct mm struct *mm). struct mm struct *dup mm(struct task struct *task). then copy it else make it NULL. struct task struct *tsk) Copy mm struct from current task to task tsk. If alternate root mount point is set. The proper way to release a mm struct acquired by this function is mmput(). If anything of these fails. then allocate memory for new mm struct and copy the old one to it. return non-zero value otherwise return zero. Then call mm init() on the new copy. The following is done with lock held for reading: copy info about root mount point and current working directory. struct fs struct *copy fs struct(struct fs struct *old). Notify parent sleeping on vfork() (i. set lock as RW LOCK UNLOCKED and copy umask. struct mm struct *get task mm(struct task struct *task). task->alloc lock is used to ensure mutual exclusion inside this function.e. Just a wrapper to call copy fs struct(). If CLONE VM si not set. Return pointer to newly allocated structure. increase use count. exit all asynchronous I/O operations and release all mmaps. 82 . struct mm struct *mm). this disables IRQs and locks tsk->vfork done->lock while completing).
Spinlock current->files->lock is held inside while copying. struct task struct *tsk). This is helper to call copy files(). static int count open files(struct files struct *files. which isn’t exported. int unshare files(void). If flags contain either CLONE SIGHAND or CLONE THREAD increase usage counter and return. If flags contain CLONE THREAD increase usage counter and return. Otherwise allocate memory. struct files struct *alloc files(). void sighand free(struct sighand struct *sp). otherwise allocate memory for sighand struct. Allocate a new structure files struct. This is callback to free struct sighand struct containing given rcu head. struct files struct *dup fd(struct files struct *oldf. Process Management and Scheduling static inline int copy fs(unsigned long clone flags. Free RCU-protected struct sighand struct. Copy struct fs struct from current task to task->fs. If CLONE FS is given then just increase usage counter in current->fs->count. Also set maximal number of file descriptors. . . struct task struct *tsk). initialize spinlock. Counts the number of open files by files struct. If clone flags contains CLONE FILES then return with zero.Chapter 7. int size). copy relevant data fields and increase usage counter for file descriptors. static inline int copy sighand(unsigned long clone flags. static int copy files(unsigned long clone flags. set usage counter to 1 and copy action from current->sighand->action. and RCU head. int *errorp Allocate a new files struct and copy contents from oldf. static inline int copy signal(unsigned long clone flags. set it’s reference counter to one and initialize some of structure’s members: next file descriptor. struct task struct *tsk). maximal count of FDs. set next file descriptor to 0 and spinlock state to SPIN LOCK UNLOCKED. Exported symbol. otherwise 83 . void sighand free cb(struct rcu head *rhp). struct task struct *tsk).
but does not actually start it yet. This should be called from user space. tty and session. PGID 84 . it is possible here to get SIGKILL from OOM kill). signals. then set p->ptrace to zero to disable ptrace for p. Initialize list of children and list of siblings and reset timers. int user *parent tidptr. In the beginning check corectness of the flags. Clear PF SUPERPRIV and set PF FORKNOEXEC to p->flags. Process Management and Scheduling allocate memory for struct signal struct and fill initial values. also attach TGID. The actual kick-off is left to the caller. files. fs. Then increase appropriate counters.Chapter 7. number of processes. unsigned long stack start.g. If it is ok then copy semaphores. usually set so that task struct take no more than half of memory. memory structs. If CLONE PARENT flag is set then reuse parent’s parent as our parent. unsigned long stack size. Mark the process as yet not executed and copy flags. struct task struct *copy process(unsigned long clone flags. If flag CLONE IDLETASK is not set (note: this is only for kernel only threads) then allocate a pid. If the memory allocation fails return -ENOMEM. If CLONE THREAD flag is set then lock current->sighand->siglock and check for group exit. if needed (flag CLONE PARENT SETTID)set tid in the parent. but never less than 20). Copy thread group ID from parent and also group leader and unlock current->sighand->siglock. and all the appropriate parts of the process environment (as per the clone flags). If CLONE PTRACE is not set. struct task struct *p). Then copy mempolicy and afterwards via security task alloc() and audit alloc() (system call auditing) check the operation.int user *child tidptr). namespace and thread information. Set pointer to thread ID. Attach PID (if the process is a thread group leader. then copy process group. static inline void copy flags(unsigned long clone flags. detached threads can only be started from within group. long sys set tid address(int user *tidptr). This creates a new process as a copy of the old one. Now perform scheduler related setup for our newly forked process. if signal handlers are shared then VM must be implicitly shared too etc. struct pt regs *regs. Lock tasklist lock for writing and check for SIGKILL signal (e. Duplicate task struct and then check whether we’re not going to cross resource limit (max. It copies the registers. otherwise return zero. Set TID and whether clear TID on mm release. such as that thread groups must share signals. Child also inherits execution from parent process.
wait for completion of task and notify the tracer when the task has exited. Finally unsharing a namespace implies unsharing filesystem information. 85 . vm area cachep and mm cachep. Clone the process with zeroed registers and no stack start and set it as an idle process for given cpu. move to cpu we get and put the cpu back (i. but check the pid for quick exit (OOM kill. If task is traced. return pid. notify the tracer. unsharing VM implies unsharing signal handler. long do fork(unsigned long clone flags. enable preempt). unsigned long stack size. Increase number of threads running nr threads and finally release write-locked tasklist lock. int *parent tidptr. files cachep. etc). This function is used only during SMP boot. Check constraints on flags passed to unshare() syscall: unsharing a thread implies unsharing VM. struct pt regs *idle regs(struct pt regs *regs). Unsharing signal handlers from task created using CLONE THREAD implies unsharing a thread. otherwise free what we allocated and return corresponding value. If task is not stopped. If task is traced or stopped. user This is the main fork routine. Initialize signal cachep. If it was not vfork() then set thread flag to reschedule. sighand cachep. void init proc caches init(void). static inline int fork traceflag(unsigned clone flags). In case of stopped task get CPU (this disables preempt) and set its internal state to TASK STOPPED. int user *child tidptr). On success return zero. check whether it is a thread or a task and wake it up using appropriate call. start with immediate SIGSTOP. Zero whole structure and return pointer to it.Chapter 7. Copy the task. Then the process is unhashed from list of processes. Increase number of forks done (for statistical reasons). void check unshare flags(unsigned long *flags ptr). If everything went all right. struct pt regs *regs. If CLONE VFORK is set then initialize completion and set vfork done to this completion for the new task. unsigned long stack start. task t *fork idle(int cpu). If the fork was initiated by the vfork() syscall.e. Check the trace flags modify if needed. fs cachep. Process Management and Scheduling and SID). Extract trace flags from argument.
struct files struct **new fdp). struct fs struct **new fsp). whether to something with allocated memory before releasing it etc. Unsharing of tasks created with CLONE THREAD is not supported yet. Unshare VM if CLONE VM is set. All references to process must be removed from all kernel structures. struct sem undo list **new ulistp). int unshare semundo(unsigned long unshare flags. If CLONE FS flag is set. struct namespace **new nsp. struct fs struct *new fs). Process Management and Scheduling int unshare thread(unsigned long unshare flags). multiple things occur: The kernel must decide what to do with orphaned children processes. long sys unshare(unsigned long unshare flags). unshare file system information (represented by struct fs struct). 7. Return -EINVAL no CLONE THREAD flag and zero otherwise. Unshare file descriptors if CLONE FILES is set. int unshare namespace(unsigned long unshare flags. The flag for this operation is CLONE SYSVSEM. struct sighand struct **new sighp). int unshare fd(unsigned long unshare flags. whom to inform about death. Unshare sighand struct (signal handlers) if CLONE SIGHAND is set. This function will unshare System V semaphore once it will be implemented. This is implementation of the unshare() syscall.Chapter 7. 86 . int unshare vm(unsigned long unshare flags. which allows a process to ’unshare’ part of its context that was originally shared since clone(). This function modifies task struct *current and lock its current->alloc lock. int unshare fs(unsigned long unshare flags.3 Process Termination Whenever a process calls exit() syscall. struct mm struct **new mmp). int unshare sighand(unsigned long unshare flags. Unshare namespace if it’s requested by CLONE NEWNS flag.
87 . copy resource limit from init task. unhashes proc entry and process and locks p->proc lock and tasklist lock (together with disabling IRQs). Only used for SMP init. which should represent init task. SIGTTIN or SIGTTOU. static inline int has stopped jobs(int pgrp). set parent and real parent to child reaper.Chapter 7. void unhash process(struct task struct *p). Process Management and Scheduling static void unhash process(struct task struct *p). Detach PID from given task p and decrease number of threads in system. void reparent to init(void). Newly orphaned process groups are to receive a SIGHUP and a SIGCONT. If this thread is the last non-leader member of a thread group and the leader is zombie. int is orphaned pgrp(int pgrp). task t *ignored task). stop ptracing of this process. then notify the group leader’s parent process if it wants notification. but falls back on the PID if no satisfactory process group is found. Reparent the calling kernel thread to the init task (i. structures for signal handling and unhash process. Locks used: tasklist lock and p->proc lock. Orphaned process groups are not to be affected by terminal-generated stop signals. static int will become orphaned pgrp(int pgrp. Lock tasklist lock. unlock the lock and return appropriate value (gotten from will become orphaned pgrp()). Determine if a process group is orphaned. void release task(struct task struct * p). Stop any ptrace. This function checks the process group. set nice value to 0 (only with SCHED NORMAL). SIGTSTP. switch uid to INIT USER and increase reference count for this structure. Release entry in /proc. tasklist lock should be held before call to this function.e. If this thread was thread group leader then detach PGID and SID. check whether process group will become orphaned. Return non-zero value if there exists any thread in process group that is not TASK STOPPED or it’s being ptraced and its exit code is not one of following: SIGSTOP. int session of pgrp(int pgrp). set the exit signal to SIGCHLD so we signal init on exit. tasklist lock is held for reading.
increase it’s usage counter and close all open file set special pids() 88 . void set special pids(pid t session. Clone fs struct from init. void daemonize(const char *name. Exported symbol. int allow signal(int signal). The various task state such as scheduling policy and priority may have been inherited from a user process.. Allow given signal: the signal is enabled by exluding from set of blocked signals (current->blocked). protecting the body of the function. -EINVAL is reported otherwise. This function does not acquires any locks or tampers with IRQs. int disallow signal(int sig).. tasklist lock locked for writing while reparenting. pid t pgrp). Lock tasklist lock for writing with disabling IRQs. Then block and flush all signals. corectness of the operation is checked with security task reparent to init(). If current task’s process group is not pgrp then detach from the old one and attach to pgrp. This operation is protected with current->sighand->siglock spinlock and IRQs are disabled. Note: the reparent to init() gives the caller full capabili- ties. pid t pgrp). or if it already exits. Return value is zero if the sig is a valid signal number. We don’t need them.). so we reset them to sane values here. Spinlock current->sighand->siglock is held and IRQs are disable. close all of the user space pages. it should generally reparent itself to init so that it is correctly cleaned up on exit. call and restore IRQs. see set special pids(). otherwise -EINVAL is returned. so prevent dropping this signal or converting it to SIGKILL. Kernel threads handle their own signals. Process Management and Scheduling If a kernel thread is launched as a result of a system call. Return value is zero if the sig is a valid signal number. Exported symbol. void set special pids(pid t session. If task process’s SID is not session then detach from the old session and attach to session.Chapter 7. If we were started as result of loading a module. Detach thread from userspace. and if we didn’t close them they would be locked in memory. Disallows a signal by including its number sig into set of blocked signals (current->blocked). .
If the usage counter dropped to zero. we don’t need to lock anything.Chapter 7. put fs struct(struct fs struct *fs). Just a wrapper to call static inline void exit files(task). Wrapper to call static inline void put fs struct(fs). Exported symbol. This function calls put files struct() to decrement reference counter and eventually free memory. Give up using tsk->files and set it to NULL while holding lock task->alloc lock. Decrement reference counter of fs and eventually free memory structures used by it. Process Management and Scheduling descriptors and steal from init. Finally reparent thread to init(). void put fs struct(struct fs struct *fs). Enumerate through all open files in files and close all of them. If we’re the last user and decremented it to zero. With task->alloc lock held increase task->files->count reference counter. an exported symbol. void exit fs(struct task struct *task). Wrapper to call 5 exit fs(tsk). Exported symbol. Give up using files: atomicaly decrease and test files->count. void exit files(struct task struct *task). Set task->fs to NULL value. 89 . decrease reference counter to it and potentially free the memory. struct files struct *get files struct(struct task struct *task). exit fs(struct task struct *task).5 void fastcall put files struct(struct files struct *files). Exported symbol. close all file descriptors. This puts everything required to become a kernel thread without attached user resources in one place where it belongs. task->alloc lock is held while task->fs is being modified. but the following void fastcall This function is not put files struct() is. Locking is done only in calls to subfunctions. static inline void exit files(struct task struct *tsk). static inline void close files(struct files struct * files). Return task->files. free file descriptor arrays and other memory used by this structures.
thread group empty. task t *reaper. and if they have any stopped jobs. Possibly used 90 . Warning: this function may sleep. If p is in other process group than father. then send it a SIGCHLD instead of honoring exit signal.Chapter 7. Wrapper to call exit mm(tsk).) then also notify the new one. task t *child reaper). If something other than our normal parent is ptracing us. void exit mm(struct task struct *tsk). static void exit notify(struct task struct *tsk). static inline void forget original parent(struct task struct *father. Reparent task p to parent child reaper if p is reaper of reaper is zombie. Exported symbol. and it was the only connection outside. mm->mmap sem and task->alloc lock locks are used. modify appropriate structures needed for ptracing and if we’ve notified the old parent about this child’s death (state == TASK ZOMBIE. . Try to give them to another thread in our thread group. give it to the global child reaper process (child reaper i. Reference counter to task->mm is decremented and memory is potentially released if we were the last user. it’s implementation uses semaphores. This function serializes with any possible pending coredump. and if no such member exists. list head *to release). the p’s process group is now orphaned: if there are any stopped jobs. Process Management and Scheduling static inline void exit mm(struct task struct *task). static inline void choose new parent(task t *p. otherwise reparent to reaper. set it to NULL.e. Turn us into a lazy TLB process if we aren’t already. which is called from exit notify() with tasklist lock write-locked. int traced). When we die. Move the child from its dying parent to the new one. we re-parent all our children. static inline void reparent thread(task t *p. . Make init inherit all the child processes and check to see if any process groups have become orphaned as a result of our exiting. which has special meaning only to real parent. send them a SIGHUP and then a SIGCONT. Stop using task->mm. task t *father. init task). send SIGHUP and SIGCONT to the process group Note: this function is called from forget original parent().
Chapter 7. This function is used in sys wait4() to check whether process pid is eligible to wait for if given options. Used locks: tasklist lock. otherwise wait for non-clone children only. Return next thread in group. On NUMA also free memory policy. wait for clone WCLONE is set. This is called by fatal sigThis kills every thread in the Note that any externally wait4()-ing process will get the correct exit code. Exported symbol. NORET TYPE void complete and exit(struct completion *comp. Exported symbol. Take down every thread in the group. Process Management and Scheduling locks: tasklist lock and tsk->sighand->siglock. Wait for all children (clone6 or not) if children only if 6 WALL is set. task t fastcall *next thread(const task t *p). Exported symbol. even if this thread is not the thread group leader. Complete completion comp and exit current task using do exit(). idle task or init. current->sighand->siglock. NORET TYPE void do group exit(int exit code). thread group. Wrapper to call do exit(). release it. Wrapper to call do group exit(). the exit code used is current->signal->group exit code instead of exit code argument. As the last thing call schedule(). 91 . If current->signal->group exit is non-zero. static int eligible child(pid t pid. First check and warn. IRQs get enabled in the end. nals as well as by sys exit group(). if we’re trying to kill interrupt handler. long code). If we’re session leader then dissociate with current tty. We process negative/zero pid according to description of sys wait4(). asmlinkage void sys exit group(int error code). asmlinkage NORET TYPE void do exit(long code). int options. asmlinkage long sys exit(int error code). task t *p). otherwise. Do profiling and process accounting if needed and free resources. This function never returns as its purpose is to exit task. If the task has I/O context. Note: A clone child here is one that reports to its parent using a signal other than SIGCHLD.
wait4() and waitid() syscalls. uid t uid. We hold read lock(&tasklist lock) on entry. struct rusage user *ru). struct rusage user static int wait task zombie(task t *p. If we return nonzero. If this is not detached task. We hold read lock(&tasklist lock) on entry. If we return zero. In this phase we are sure that this task is interesting. We try to move the task’s state to TASK DEAD. we still hold the lock and this task is uninterestingi and we have filled user space structures. This function handles sys wait4() work for one task in state TASK ZOMBIE. if it is so then jump out. int status. static int wait task zombie(task t *p.struct siginfo user *infop. user user *infop. This is useful for wait3(). int delayed group leader. we still hold the lock and this task is uninteresting and the user space structures have been filled with data. pid t pid. If group stop is in progress and p is the group leader return zero. and no other thread can reap it because we set its state to TASK DEAD. struct rusage user *ru). struct siginfo *rusagep).Chapter 7. Return zero on success. Make sure it doesn’t get reaped out from 92 . If we return zero. notify the parent. Fill struct siginfo and struct rusage in user space. struct rusage user *ru). Process Management and Scheduling int wait noreap copyout(task t *p. If we return nonzero. if we fail this task is not interesting to us. If p->real parent != p->parent then write lock tasklist lock. Now we are pretty sure this task is interesting. Then check whether we’re not in a race with ptraced thread dying on another processor. we have released the lock and the system call should return. unlink ptrace for task p and set p’s state to TASK ZOMBIE. unsigned int user *stat addr. And done the releasing potentially we needed after notifying parent before unlocking. int user *stat addr. If it’s still not detached after that. int why. don’t release it now. We can unlock tasklist lock now and check the state of resources. Handle sys wait4() work for one task in state TASK STOPPED. Finally unlock the tasklist lock. we have released the lock and the system call should return. unsigned int *stat addr. int noreap. static int wait task stopped(task t *p.
int options. so let the next iteration catch it in TASK ZOMBIE7 . Relock task from read to write lock and try to update p’s state with TASK STOPPED. int noreap. Zero return value indicates that this task is not interesting and lock is still acquired. decrease p’s usage counter and read-lock tasklist lock and return with return value of zero. long do wait(pid t pid. This function handles do wait() work for one task in a live. go on with next child. Based on the state of this child decide to exit code might already be zero here if it resumed and did exit(0). int user *stat addr. If we failed the task resumed and then died. We don’t want to keep holding onto the tasklist lock while we try to get resource usage and acquire data from user space as this could possibly cause page faults. int my ptrace child(struct task struct *p). or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. This function must be called with read lock(&tasklist lock) acquired. struct rusage user *ru). Process Management and Scheduling under us while we give up the lock and then examine it below. struct rusage user *ru). which is added to current->wait chldexit and change current’s task state to TASK INTERRUPTIBLE. non-stopped state. struct siginfo user *infop. This suspends execution of the current process until a child as specified by the pid argument has exited. Non-zero return value means that the lock has been released and the syscall should return to user space (this non-zero return value is the pid). So unlock tasklist lock. We check during next step whether exit code is zero. static int wait task continued(task t *p. other processors in this function are locked out. For each child of current task check if the child is eligible to wait for.Chapter 7. Implementation of this function declares its own waitqueue. if it is not so. user *infop. so increase its usage using get task struct(p). The task itself is dead and it won’t touch exit code again. As the next step we move to end of parent’s list to avoid starvation and unlock tasklist lock. 7 93 . struct siginfo int user *stat addr. Return true if task p is ptraced by someone and the structures are currently being modified. if it’s sok then other function got it first or it resumed or it resumed and then died.
int options. Developer can It’s true that busyloops are used in kernel. asmlinkage long sys waitid(int which. unsigned int options). See man 2 wait4. pid t pid. sys waitpid() remains for compatibility. do wait() is called after a batch of 7. struct rusage checks. user *ru). If we suceeded then unlock tasklist lock and based on options decide whether we found the child we were looking for or whether we need to restart the whole search. Implementation using busy-loops is not effective8 . asmlinkage long sys wait4(pid t pid. Process Management and Scheduling use either wait task stopped() for TASK STOPPED or wait task zombie() for TASK ZOMBIE. However spinlocks are held only for a short time. do wait() is called after a batch of Implementation of waitid() syscall. If we didn’t find any eligible child. See man 4 wait. e. 8 94 . invalidating cpu cache etc. user *stat addr.4 Waitqueues Sometimes a task gets into state that forbids later execution until some event happens. we try to look for one in list of ptraced children. Return value is the PID of the process we waited for or -ECHILD to indicate that there is no child process we can wait for. int options. return value is non-zero). the tasklist lock is unlocked and we can remove our waitqueue from the current->wait chldexit and return the PID of the child that exited as return value. See man 2 waitid. If the waiting in one of these two functions finished successfully (i. struct rusage checks. asmlinkage long sys waitpid(pid t pid. delaying task using waitqueue can cause bigger overhead: the need for context switching. Implementation of waitid() syscall.e. user *stat addr. Wrapper to call sys waitpid4(). in which case we call schedule() before restarting the search.g see spinlock implementation. -ERESTARTSYS means that this syscall woulb block and WNOHANG option has been set.Chapter 7. waitpid() should be implemented by calling sys wait4() from libc. int user *ru). struct siginfo user *infop. so the task is inserted into structure called wait queue t and delayed for later execution.
WAITQUEUE INITIALIZER(name. Spinlock q->lock is held and IRQs disabled while adding q. static inline int waitqueue active(wait queue head t *q). wait queue t *wait). tsk). Exported symbol. Exported symbol.Chapter 7. wait queue t *wait). Set exclusive flag (WQ FLAG EXCLUSIVE) to wait and add wait to the wait queue q. wait queue func t func). static inline void add wait queue(wait queue head t *head. The exclusive flag means that the process will be woken alone and no other process will be woken up. Spinlock q->lock is held and IRQs disabled while adding to q. void fastcall add wait queue(wait queue head t *q. Check whether task list is empty and if it is so return true. struct task struct *p). in case a variable was declared before assign to that variable macro tion static inline void init waitqueue head(wait queue head t *q). Another option is to initialize using funcwait queue head t tionality is the same. Exported symbol. 95 . The items held in wait queue are represented by structure wait queue head t. Remove wait from wait queue q. will init waitqueue func entry(wait queue t *q. void fastcall add wait queue exclusive(wait queue head t *q. funcwait queue t can be initialized with static inline use void init waitqueue entry(wait queue t *q. void fastcall remove wait queue(wait queue head t *q. this the default wake function – for alternative wake function use static inline void wait queue t *new). otherwise return false. wait queue t *wait). Process Management and Scheduling decide whether to use one of the already declared wait queues or define his own using macro DECLARE WAIT QUEUE(name). which can be declared using macro DECLARE WAIT QUEUE HEAD(name) or initialized using WAIT QUEUE HEAD INITIALIZER(name). Clear exclusive flag (WQ FLAG EXCLUSIVE) from wait and add wait to the wait queue q. This macro also declares variable of name name. q’s lock is held and IRQs disabled while removing.
and we handle it by continuing to scan the queue. Add new to the tail of head. Process Management and Scheduling Add new to the wait queue head head. int sync. Lock q->lock is locked and irqs distabled during execution. int sync.ie. void *key). int default wake function(wait queue t *curr. Wake up threads blocked on a waitqueue. wait queue t *old). Same as wake up() but called with the spinlock in wait queue head t held. unsigned mode. The core wakeup function. wake up locked(wait queue head t *q.Chapter 7. Used for wake-one threads. int nr exclusive. Try to wake up current task from curr wait queue. Exported symbol. int nr exclusive. Remove old from the wait queue head. wait queue t *new). the two threads are synchronized with each other. void *key). static void wake up common(wait queue head t *q. Non-exclusive wakeups (nr exclusive == 0) just wake everything up. static inline void add wait queue tail(wait queue head t *head. The sync wakeup differs that the waker knows that it will schedule away soon. no locks are used or flags changed. it will not be migrated to another CPU . so while the target thread will be woken up. unsigned int void fastcall int nr exclusive). Wake up threads blocked on a waitqueue q. unsigned int mode. try to wake up() returns zero in this rare case. If it’s an exclusive wakeup (nr exclusive == small + ve number) then we wake all the non-exclusive tasks and one exclusive task. static inline void remove wait queue(wait queue head t *head. unsigned int mode. wake up sync(wait queue head t *q. void *key). to compare with add wait queue: this function does not manipulate flags and does not make us of any spinlock. Exported symbol. void fastcall mode). This can prevent needless bouncing between 96 . void fastcall wake up(wait queue head t *q. There are circumstances under which we can try to wake a task which has already started to run but is not in state TASK RUNNING. unsigned int mode.
nr) Wake up nr number of exclusive TASK UNINTERRUPTIBLE or TASK INTERRUPTIBLE tasks. nr) Wake up nr number of exclusive TASK INTERRUPTIBLE tasks. Exported symbol. These are the new interfaces to sleep waiting for an event. wake up interruptible all(x) Wake up all TASK INTERRUPTIBLE tasks. wake up all(x) Wake up all TASK UNINTERRUPTIBLE or TASK INTERRUPTIBLE tasks. wake up locked(x) Wake up one TASK INTERRUPTIBLE or TASK UNINTERRUPTIBLE task with spinlock in x->lock held and IRQs disabled. the older ones are documented later since they’re still in use. On UP it can prevent extra preemption. Some of the following macros are using previous function for waking up: wake up(x) Wake up one exclusive TASK UNINTERRUPTIBLE or TASK INTERRUPTIBLE task. but developers should use these new ones. wake up interruptible nr(x. Lock q->lock is locked during execution. wake up all sync(x) Synchronously wake up all TASK UNINTERRUPTIBLE or TASK INTERRUPTIBLE tasks. wake up interruptible sync(x) Synchronously wake up one TASK INTERRUPTIBLE task. Process Management and Scheduling CPUs. wake up interruptible(x) Wake up one exclusive TASK INTERRUPTIBLE task.Chapter 7. DEFINE WAIT(name) This macro declares a wait queue of given name. wake up nr(x. initializes it and sets its wake function to autoremove wake function(). 97 .
condition. remove task from queue if task was successfully finished) and add wq to wait queue marked as TASK UNINTERRUPTIBLE and wait for finishing wq while condition is not accomplished. wait event interruptible(wq. wait event interruptible timeout(wq. condition). timeout) Declare int ret 98 . ret). condition) Declare int ret = 0. if it is true then jump out else continue with wait event(wq. condition) Declare a wait with autoremove function (i. remove task from queue if task was successfully finished) and add wq to wait queue marked as TASK UNINTERRUPTIBLE and wait for finishing wq while condition is not accomplished. and check condition.e. wait event(wq. ret) Declare a wait with autoremove function (i. condition) First check the condition. Process Management and Scheduling init wait(wait). condition.e. so it should not be -ERESTARTSYS in the beginning. Right after checking the condition check for any pending signals. continue with wait event interruptible(wq. condition.e. remove task from queue if task was successfully finished) and add wq to wait queue marked as TASK UNINTERRUPTIBLE and wait for finishing wq while condition is not accomplished. this misses the possibility of bug -ERESTARTSYS in the beginning mentioned in previous macro. If there are none. Right after checking the condition check for any pending signals. wait event interruptible timeout(wq. Note that if we have successfuly fulfilled the condition we set the ret to timeout value. condition. ret) Declare a wait with autoremove function (i. If there are none try the cycle again otherwise return with -ERESTARTSYS. This macro initializes wait queue t and sets its wake function to autoremove wake function(). check the timeout (if we returned after timeout jump out) and try the cycle again otherwise return with -ERESTARTSYS.e. If the condition is no true. wait event interruptible(wq. wait event(wq. Note that if we have successfuly fulfilled the condition we don’t change the ret value.Chapter 7. i.
It’s rumoured that this interfaces are planned to be removed during 2. q’s lock is held while manupulating q. They can cause race condition. add current task. ret). long fastcall sched interruptible sleep on timeout( wait queue head t *q. If the condition is not true. wait event interruptible exclusive(wq. These are the old interfaces to sleep waiting for an event. remove task from queue if task was successfully finished) and add wq to wait queue marked as TASK UNINTERRUPTIBLE and wait for finishing wq while condition is not accomplished. DO NOT use them. 99 . this misses the possibility of bug -ERESTARTSYS in the beginning mentioned in previous macro (the timeout should be a positive value). static inline void add wait queue exclusive locked(wait queue head t *q. condition. static inline void remove wait queue locked(wait queue head t *q. Create new waitqueue. condition. i. condition) Declare int ret = 0. wait queue t *wait). continue with wait event interruptible exclusive(wq.Chapter 7. If the condition is not true. Right after checking the conditio check for any pending signals. I enlisted them just for simplifying analysis of kernel 2. Note that if we have successfuly fulfilled the condition we don’t change the ret value. i. must be called with the spinlock q->lock held.7: void fastcall sched interruptible sleep on( wait queue head t *q). ret). and check condition. continue with wait event interruptible timeout(wq. this misses the possibility of bug -ERESTARTSYS in the beginning mentioned in previous macro.e. Mark wait as exclusive wake and add wait to the tail of q. use the wait event* interfaces above. so it should not be -ERESTARTSYS in the beginning.6. call schedule() and remove this new runqueue from q. Process Management and Scheduling and initialize it to timeout and check condition. condition.e. long timeout). wait queue t *wait). Remove wait for wait queue q. no locks are used. If there are none try the cycle again otherwise return with -ERESTARTSYS. so must be called with the spinlock q->lock held. Exported symbol. ret) Declare an exclusive wait with autoremove function (i. wait event interruptible exclusive(wq. chain with q.e.
q’s lock is held while manupulating q. call schedule() and remove this new runqueue from q. int state). wait queue t *wait. Create new wait queue. check if list wait->task list is empty and if it is not: lock wait queue spinlock and disable IRQs. everything while holding q lock and IRQs disabled. int sync. sched sleep on timeout(wait queue head t *q. mark it as TASK INTERRUPTIBLE. add current task. Try to wake up wait. Exported symbol. otherwise false. Exported symbol. long fastcall timeout). Exported symbol. Set current task’s state to TASK RUNNING. Exported symbol. wait queue t *wait). void fastcall prepare to wait exclusive(wait queue head t *q. wait queue t *wait. chain with q. Wait queues which are removed from the waitqueue head at wakeup time: void fastcall prepare to wait(wait queue head t *q. Create new wait queue. Set exclusive flag and if list wait->task list is empty add it to q and set current task’s state to state. Clear exclusive flag and if list wait->task list is empty add it to q and set current task’s state to state. void fastcall finish wait(wait queue head t *q. unsigned mode. unlock wait queue spinlock and restore previous IRQ state. everything while holding q->lock and IRQs disabled. mark it as TASK UNINTERRUPTIBLE. long 100 . chain with q. chain with q. int autoremove wake function(wait queue t *wait. void *key). q’s lock is held while manupulating q. Process Management and Scheduling Create new waitqueue. Exported symbol. reinitialize wait as new. void fastcall sched sleep on(wait queue head t *q). call schedule timeout() and remove this new runqueue from q. mark it as TASK UNINTERRUPTIBLE. Exported symbol. delete head. Exported symbol.Chapter 7. add current task. q’s lock is held while manupulating q. add current task. call schedule timeout() and remove this new runqueue from q. if successful then delete head of wait and reinitialize it as new. On success return true. Note: Checking for emptiness is done without any locking using list empty careful(). int state).
static inline int is single threaded(struct workqueue struct *wq). The most basic structure struct work struct represents work to be done with following attributes: pending is non-zero if work is currently pending. which does the same. The contents is protected by its member spinlock lock. f. This list is modified on the fly as the CPUs come and go.h>: WORK INITIALIZER(n. 101 . run depth is used in run workqueue() to check whether recursion is not too deep9 Workqueues are tied together in structure workqueue struct. 4 or 8 kB on i386 Note that this list is empty if the workqueues are single-threaded. Work queues are based on wait queues. which initializes struct work struct n and sets callback function to f with argument d. but they are not as frequently used as wait queues. data).h> and kthread. All the per-CPU workqueues on the system are protected by single spinlock workqueue lock and they’re held in workqueues list. Returns true if workqueue struct is singlethreaded.h. but also declares the variable n. Process Management and Scheduling 7. And the last one is PREPARE WORK( work. There are three functions defined in <linux/workqueue. static void queue work(struct cpu workqueue struct *cwq. func. The next is DECLARE WORK(n.5 Workqueues and Kernel Threads Work queues are generic mechanism for defining kernel helper threads for running arbitrary tasks in process context. f. d). which contains per-CPU cpu workqueue struct cpu wq[NR CPUS]. pointer to cpu workqueue struct this work belongs to and timer to be used with delayed work.10 Reasonable API to these functions and macros is provided by <linux/workqueue. Add work to the tail of queue cwq and save cwq to work->wq data so that we can easily find which cpu workqueue struct we belong to. name of the workqueue and list of all per-CPU workqueues in the system.Chapter 7. struct work struct *work). pointer to function func that will be called with parameter data. which only sets callback function func and its argument data. d). Increase counter of ’works’ in queue (the insert sequence). entry. The worklist keeps list of work that need to be done. Another basic structure is cpu workqueue struct. and try to wake up some work from 9 10 The stack available in kernel is limited.
Queue work on a workqueue wq. Otherwise cycle through cwq->worklist. add work to the first CPU. ((struct work struct Queue work (struct work struct *) data to workqueue belonging to curdata->wq data->cpu wq[smp processor id()]). Then repeat if there is more work to be done. If the workqueue is singlethreaded. Then block and flush all signals and set mark state of current thread as TASK INTERRUPTIBLE. more than 3. add to the first CPU as usual. The work is queued to the CPU it was submitted by (except when wq is singlethreaded). if it is so bug user and dump stack). Preemption should be disabled before calling this function. int fastcall queue work(struct workqueue struct *wq. struct work struct *work). Non-zero return value means success. Set PF NOFREEZE flag to current process and renice it to -10. int fastcall queue delayed work(struct workqueue struct *wq. unsigned long delay). Preemption is disabled during the execution. This way the work will get enqueued in wq as soon as at least delay jiffies pass. Body of this function is executed with IRQs disabled and cwq->lock held. set the callback to be delayed work timer fn and add timer.Chapter 7. If there is no work/timer pending. If wq is singlethreaded. static int worker thread(void * cwq). struct work struct *work. Then set the timer to expire at jiffies+delay time. Increase run depth in cpu workqueue struct and check whether the recursion is not too deep (i. otherwise to current one. 102 . but there is no guarantee that it will be process by that CPU. After completing one increase the remove sequence counter and wake up work done. This is timer callback and shouldn’t be called directly. clear pending bit and call work struct->func on each. static inline void run workqueue(struct cpu workqueue struct *cwq). static void delayed work timer fn(unsigned long rent *) CPU data). Exported symbol. remove work structs one by one. Process Management and Scheduling queue. store in work->wq data the workqueue we want to insert the work into. Return non-zero if it was successfully added. Spinlock cpu workqueue lock is held together with IRQs disabled. the work is added if there is no work pending on wq. Exported symbol.e.
Ensure that any scheduled work has run to completion: if workqueue is singlethreaded then continue with flush cpu workqueue() for CPU 0. struct workqueue struct * create workqueue(const char *name. clear it with zeros 11 see kthread stop() for details 103 . otherwise lock cpu hotplug and for each online CPU call flush cpu workqueue(). we call schedule(). int singlethread).Chapter 7. kthread should stop() is true) mark current process as TASK RUNNING. Create workqueue: allocate memory for workqueue struct. Process Management and Scheduling While kthread should stop()11 is false. current thread is marked as TASK RUNNING.e. void fastcall flush workqueue(struct workqueue struct *wq). When done reinitialize the list (cwq->work done) to be empty. It will sample each workqueue’s current insert sequence number and will sleep until the head sequence is greater than or equal to that. static void flush cpu workqueue(struct cpu workqueue struct *cwq). This means that we sleep until all works which were queued on entry have been handled. Return newly created kthread’s task struct on success (otherwise NULL). If the list is empty. Exported symbols. Prepare cwq->work done to wait and (after unlocking spinlock and restoring IRQs) call schedule() so that waiting task could be waken up. When done unlock CPU hotplug and return. Return value is always zero. If it is so. static struct task struct *create workqueue thread(struct workqueue struct *wq. While we’re doing some work. simply call run workqueue(cwq) to avoid deadlock. Repeat this cwq->insert sequence cwq->remove sequence times to do all work enqueued here. Also set insert sequence and remove sequence to zeros and init more work and work done. In the first place we check whether the keventd is not trying to flush its own queue. In the other case lock cwq->lock and disable irqs. but we are not livelocked by new incoming ones. Create kthread to handle worker thread for given cpu. int cpu). In the end (i. after return from schedule() again lock the spinlock and disable IRQs. we stay inside the cycle and try to perform work enqueued in current CPU’s runqueue. This function forces execution of the workqueue and blocks until completion (typically used in driver shutdown handlers). unlock spinlock and restore IRQs.
Flush workqueues. Queue work to keventd wq with delay jiffies delay.h> defines macro create workqueue(name) as 1).Chapter 7. Keventd’s workqueue. no string copying. 12 create workqueue((name). Unlock cpu hotplug and free memory used by wq. static struct workqueue struct *keventd wq. bind it to CPU and wake it up. unsigned long delay). we can unlock cpu hotplug. int cpu). int fastcall schedule delayed work on(int cpu. Note: <linux/workqueue. int fastcall schedule work(struct work struct *work). When we’re done with all CPUs. hold lock workqueue lock while deleting wq->list12 . Exported symbol. Exported symbol. lock cpu hotplug and clean workqueue thread for each cpu up. Queue a work on given cpu with given delay (in jiffies). Queue work to keventd wq. we don’t need race condition. Stop kthread belonging to workqueue of cpu. 0) and macro create workqueue((name). In case we want single-threaded processing of workqueues we just init list wq->list and call create workqueue thread() and wake up newly created kthread. struct work struct *work. unsigned long delay). In case of multi-thread processing of workqueues we add workqueues to the list and for each online CPU create one kthread. Lock the cpu hotplug. don’t free the string memory too early). Return value on success is the workqueue struct we just created else NULL in the other case. Exported symbol. 104 . Exported symbol. int fastcall schedule delayed work(struct work struct *work. Process Management and Scheduling and set its name (set pointer. Locks that workqueue’s spinlock and disables IRQs while retrieving pointer to task struct (and setting it to NULL) void destroy workqueue(struct workqueue struct *wq). create singlethread workqueue(name) as Remember that for single-threaded processing is this list always empty. static void cleanup workqueue thread(struct workqueue struct *wq. If using multi-threaded processing of workqueues.
Process Management and Scheduling int schedule on each cpu(void (*func)(void *info). Only with CONFIG HOTPLUG CPU void init workqueues(void). Kill work and if it resisted then flush the waitqueue. Prepare workqueue threads for CPUs that are preparing to go up. The function returns whether it has deactivated a pending timer or not. Only with CONFIG HOTPLUG CPU static int devinit workqueue cpu callback(struct notifier block *nfb. Schedule given function on each cpu. Run flush scheduled work() to wait on it. wake thier worker threads when the CPU goes online or when going up was canceled bind the kthread to current CPU and clean its workqueue up. int keventd up(void). Lock of workqueue assigned to incriminated is held and IRQs are disabled protecting the body of function. unsigned long action. Kill work or flush keventd workqueue. unsigned int cpu). static void take over work(struct workqueue struct *wq. struct work struct *work). static inline int cancel delayed work(struct work struct *work). Register callback for cpu hotplug events and create keventd’s waitqueue (keventd wq) with name events. take its work to current CPU. Return true if keventd wq is up. void cancel rearming delayed workqueue(struct work struct *work). void *info). Exported symbol. 105 . Flush keventd wq workqueue. Return non-zero if current process on this CPU is keventd. Take the work from cpu that went down in hotplug. This is callback for handling CPU hotplug events. When a CPU dies. int current is keventd(void). void *hcpu). Kill off a pending schedule delayed work().Chapter 7. Note that the work callback function may still be running on return from cancel delayed work(). void flush scheduled work(void). void cancel rearming delayed workqueue(struct workqueue struct *wq.
Process Management and Scheduling struct task struct *kthread create(int (*threadfn)(void *data). unsigned int cpu). and waits for it to exit. void kthread bind(struct task struct *k. int kthread stop sem(struct task struct *k.. Exported symbol. and the kthread k must be stopped (ie. data. Bind a just-created kthread k to given cpu. Returns the kthread’s task struct. Returns a task struct or ERR PTR(-ENOMEM). . 13 106 . just returned from kthread create(). const char namefmt[]. namefmt. The return value should be zero or a negative error number: it will be passed to kthread stop(). The up operation on semaphore s is used to wake up k. wakes it.). define kthread run(threadfn. threadfn can either call do exit() directly if it is a standalone thread for which noone will call kthread stop(). mutex kthread stop lock serializes multiple kthread stop() calls. int kthread stop(struct task struct *k). The return value is the result of threadfn(). the thread will run threadfn() with data as its argument. int kthread should stop(void). except that cpu doesn’t need to be online. Arguments are identical with those of kthread create().. The namefmt argument contains a printf-style name for the thread. When someone calls kthread stop() on your kthread. The thread will be stopped: use wake up process() to start it. This helper function creates and names a kernel thread.) This macro is wrapper for kthread create() followed by wake up process(). it will be woken and Thread stopping is done by setting struct kthread stop info kthread stop info. . or return when kthread should stop() is true (which means kthread stop() has been called).13 Exported symbol. The threadfn() must not call do exit() itself if you use this function. or ERR PTR(-ENOMEM). void *data.Chapter 7. or -EINTR if wake up process() was never called. Exported symbol... When woken. See also kthread run() and kthread create on cpu(). struct semaphore *s). Stop a thread created by kthread create(). Stop a kthread k created by kthread create(): set kthread should stop() for k to return true. This can also be called after kthread create() instead of calling wake up process(): the thread will exit without calling threadfn(). This function is equivalent to set cpus allowed().
Chapter 7. i. Process groups are used for distribution of signals. 7. processes joined by pipe on a command line will belong to one process group. static void keventd create kthread(void * create). and your return value will be passed through to kthread stop(). If we can guarantee that the set is greater than the biggest possible number of running processes. Exit files. e. On the other side since simple data types are always able to hold exactly one value from a finite set.6 PIDs Processes are identified by PIDs. which are unique numbers. static int kthread(void * create). Then change the state to TASK INTERRUPTIBLE and wait for either stop or wake-up. Create new kernel thread via arch-specific call kernel thread() and following completion. each of six xmms14 threads has it’s own PID. Gives up files struct and fs struct and adopt ones from init task.g.1: it’s the ID of whole group of threads inside one process. No two processes at any moment can share PID. Threads inside one process share this ID. After rescheduling check if someone stopped us. PIDTYPE PGID is the process group PID. Process Management and Scheduling this will return true. or if the thread has exited on its own without kthread stop() and deal with this situation (the return value is zero in this case). block and flush all signals and mark as to be allowed to run on any CPU by default. Exported symbol. uses kthread().e. static void kthread exit files(void). we can use any free pid at any time. 14 Xmms is media player application 107 . There are currently four types of PIDs (from <linux/pid. PIDs need to be reused. Your kthread should then return. it’s different for threads.h>): PIDTYPE TGID is the process PID as defined in POSIX. PIDTYPE PID is the same for standalone processes and for leader threads.
From a minimum of 16 slots up to 4096 slots at one gigabyte or more. enum pid type type). Finally 108 . void switch exec pids(task t *leader. enum pid type type). Exported symbol. pidhash shift and pidhash size. Try to allocate PID from pidmap. task t *thread).c]: fastcall void free pidmap(int pid). Allocate memory for pidmap array->page and set PID 0 as used (so that the first PID used will be 1) and accordingly decrease number of free PIDs. void init pidmap init(void). int fastcall attach pid(task t *task. on failure return -1. This function switches the PIDs if a non-leader thread calls sys execve(). Following functions are defined in [kernel/pid. Always return 0. void fastcall detach pid(task t *task.Chapter 7. Return task that belongs to given PID nr. fastcall struct pid *find pid(enum pid type type. This must be done without releasing the PID. int alloc pidmap(void). which a detach pid() would eventually do. Attach task to PID nr of given type. on success return new PID value. When a tty is lost all processes belonging to affected session receive SIGHUP followed by SIGCONT. static inline int detach pid(task t *task. void init pidhash init(void). Return number of PID. Find struct pid for given type and number nr of pid. int nr). enum pid type type. int nr). Detach task from PID it belongs to. Detach PID via detach pid() and check if there is any type of PID asociated with the number of PID from which we released the task. Process Management and Scheduling PIDTYPE SID is the session ID. If there isn’t any then free pid via free pidmap(). task t *find task by pid(int nr). The pid hash table is scaled according to the amount of memory in the machine. Mark bit as free in pidmap table. Initialize pid hash.
Process accounting is controlled by acct() syscall and by amount of free space. Initially it is suspended whenever there is less then 2% of free space and it is resumed again when the free space crosses 4%.h> contains prototypes for attach pid(). real user/group id. struct acctglbs { spinlock_t lock. AXSIG (killed by signal) and big/little endianness.7 Process Accounting for Linux Process accounting is a way of keeping (recording) accounting information for processes regarding (in version 2) user/group id. PIDTYPE_SID.Chapter 7. system time. task). type) return pointer to struct task struct if elem is pids[type]->pid list inside task struct. control terminal. Moreover later mentioned macros are declared. process creation time. type. user time. type. Process Management and Scheduling associate current task with PID 0 (remember that this is done at boot and the only thread is the one doing all initializations) The API (<linux/pid. task) and while each task pid(who. free pidmap() and switch exec pids(). elapsed time and various flags. Changes between versions consist mainly of new binary format and parent process id was added between version 2 and 3. p) { // do something with whole PID session } while_each_task_pid(tty->session.c]. ACORE (core dumped). Possible flags are AFORK (process forked but didn’t exec). Later the developers added up to 6 possible logging formats. find pid(). Enumeration through all PIDs of some type can be done using these two macros: do each task pid(who. This code was inspired by [drivers/char/tty io. p). detach pid(). because TTY layer is the biggest user of PIDs. Process accounting is somewhat different from BSD. 7. but without any additions to accounted items. 109 . elapsed time. alloc pidmap(). command name. pid task(pids. minor and major pagefaults and number of swaps. characters transfered. exitcode. Arguments to these macros should be the same: do_each_task_pid(tty->session. PIDTYP_SID. blocks read or written. average memory usage. The check is performed every 30 seconds (these values are controllable by acct parm). ASU (superuser privileges).
volatile int needcheck. Close the old accounting file. acct globals. If the name argument is not NULL the file is opened in write and append 110 . If there is a new file open. This function returns either 0 if no error occured or -EACCESS if the permissions do not allow accounting to write to this file or -EIO in case of any other error. If there is an old file open. Finally call acct file reopen() to close old file and use new one. This funcion first checks if free space needs to be checked (see acct timeout) and if it is so it performs accordingly. and open a new one (if file is nonNULL). It’s internal function consists of setting acct globals. which is being checked in following function: static int check free space(struct file *file). }. if any open. struct file *file. which can be changed in runtime). struct timer_list timer.Chapter 7. altough it is unlocked before last accounting to old file. Accounting globals are protected by spinlock acct glbs->lock. it sets it as accounting file in acct globals. void acct file reopen(struct file *file). asmlinkage long sys acct(const char user *name). Open a file filename for appending and check whether it’s ok to write to this file. closing old file and afterwards it is locked again. In the end it does one last accounting and closes old file. This system call starts accounting (or stops in case of NULL parameter). sets the accounting to active state and starts new timer. The accoung information is being written to acct->file. int acct on(char *filename). Process Management and Scheduling volatile int active. This function is being called whenever timer says to check free space.needcheck to 1. static void acct timeout(unsigned unused). Finally it deletes old timer and registers new one using timeout from ACCT TIMEOUT (actually this macro refers to acct param[2].lock must be held on entry and exit. it deletes timer and resets the rest of acct glbs to initial values. accounting is active when acct->active holds nonzero value.
static comp t encode comp t(unsigned long value). void acct update integrals(struct task struct *tsk). If ACCT VERSION is defined as 3 then this function encodes unsigned 64-bit integer into 32-bit IEEE float. Caller holds the reference to file. Handle process accounting for an exiting file. Clear the tsk->mm integral fields. Encodes an unsigned longto comp t. Then the security acct(file) is used to check permission to account. void auto close mnt(struct vfsmount *m). This function is just a wrapper for do acct process() with some checks done first. It starts with checking. struct file *file). fill the structure with the needed values as recorded by the various kernel functions. Then the accounting structure is written to file.Chapter 7. static void do acct process(long exitcode. Update tsk->mm integral fields: RSS and VM usage. void acct auto close(struct super block *sb). static comp2 t encode comp2 t(u64 value). If we don’t have permission to do accounting.lock lock is being held during call to acct file reopen((struct file *)NULL). static u32 encode float(u64 value). If the accounting is turned on for a file in the filesystem pointed to by sb. void acct clear integrals(struct task struct *tsk). If ACCT VERSION is defined as 1 or 2 then this function encodes unsigned 64-bit integer into comp2 t. resource limit limiting filesize (FSIZE) is disabled during this operation. Process Management and Scheduling mode. If it is so. turn accounting off. the file is closed. Turn off accounting if it’s done on m file system.lock is being held. The acct globals. Finallyacct file reopen(file) is being called with acct globals. This function does the real work. void acct process(long exitcode). 111 . whether there’s enough free space to continue the accounting.
TIF SYSCALL EMU Syscall emulation is active. because these macros work as two loops: the outer one iterate through the list of tasks and the inner one iterates through the threads for each task. . This is useful for ptrace.15 15 TIF RESTORE SIGMASK Restore the signal mask in This feature will allow to create inetd-like daemon that would accept connectionis. Useful for ptrace. . close. TIF SINGLESTEP Restore singlestep on return to user mode. TIF SECCOMP Secure computing is active. p) { // do something with ’p’ } while_each_thread(g. p). Then the server itself will be executed to serve the request. thread is allowed to do only some syscalls: read.8 Thread API To enumerate through the all threads use following construction: do_each_thread(g. Thread flags (based on i386 architecture): TIF SYSCALL TRACE Syscall trace is active. TIF NEED RESCHED Rescheduling is necessary.Chapter 7. fork() and then limit abilities to those few allowed in secure computing mode. TIF IRET Return with iret instruction. TIF SYSCALL AUDIT Syscall auditing is active. To exit from forementioned loop use goto and not break. 112 . write. i. TIF NOTIFY RESUME Resumption notification is requested.e. Process Management and Scheduling 7. TIF SIGPENDING A signal is pending.
7. Decrease mm’s reference counter and it it drops to zero then free the memory. Following methods use these flags: void set tsk thread flag(struct task struct *tsk. TIF POLLING NRFLAG True if poll idle() is polling on TIF NEED RESCHED. int flag). int flag). int test and clear tsk thread flag(struct task struct *tsk. Set thread flag (TIF . Return value of a flag. int signal pending(struct task struct *p)..9 Various Other Process Management Functions int on sig stack(unsigned long sp). int flag). void clear tsk need resched(struct task struct *tsk). This is power consuming and should be used carefully.Chapter 7. Set thread flag and return previous value. void set tsk need resched(struct task struct *tsk).. int flag). Process Management and Scheduling do signal(). void clear tsk thread flag(struct task struct *tsk. 113 . Clear thread flag and return previous value... void mmdrop(struct mm struct *mm).) in structure of other task. int flag). Clear TIF NEED RESCHED flag. Return true if we are on alternate signal stack. Set TIF NEED RESCHED flag.) in structure of other task. int need resched(void). int test tsk thread flag(struct task struct *tsk. TIF MEMDIE This thread is freeing some memory so don’t kill other thread in OOM-killer. Return true if TIF NEED RESCHED is set. Clear thread flag (TIF . int test and set tsk thread flag(struct task struct *tsk. Return true if a signal is pending.
files. void task lock(struct task struct *p). see task lock() for details. unsigned long *task stack page(struct task struct *task). for each process(p) Enumerate through list of all processes. comm and cpuset member variables of p. mm. void setup thread stack(struct task struct *p. Return pointer to task’s thread info. void task unlock(struct task struct *p). struct thread info *task thread info(struct task struct *task). 114 . unsigned long *end of stack(struct task struct *p).Chapter 7. Unlock the p->alloc lock. int need lockbreak(spinlock t *lock). Copy struct thread info from original to p. task struct *thread group leader(task struct *p). The struct thread info is on the stack. Process Management and Scheduling next task(p) This macro returns the next task to task p. int thread group empty(task t *p). Return true if p has empty thread group. This lock also synchronizes with wait4(). Lock the p->alloc lock and protect fs. ptrace. struct task struct *original). but maintain correct struct task struct::task. This macro returns true if a critical section we’re currently in needs to be broken because of another task waiting. Return true if p is leader of a thread group. group info. prev task(p) This macro return the previous task to task p. Return pointer to end of stack. Return pointer to thread’s stack page. so the stack is calculated using this structure. The struct thread info is on the stack.
Return true if task p is freezable. Check whether a task is not zombie. int try to freeze(void). Current CPU for given task p. int thaw process(struct task struct *p). Check whether thread p is to be frozen now. int freezeable(struct task struct *p). because frozen thread isn’t running. void set task cpu(struct task struct *p. Process Management and Scheduling int lock need resched(spinlock t *lock). Return true if the process is trying to freeze. int pid alive(struct task struct *p). void frozen process(struct task struct *p). unsigned int task cpu(const struct task struct *p). This means that the task is not current. Return process group of given task. Warning: It’s forbidden on SMP to modify other thread’s flags. Freeze the thread p. This only sets struct task info::cpu. void freeze(struct task struct *p). This should be OK even on SMP. Return zero if process was not frozen before calling this function. Check if a thread has been frozen (due to system suspend). unsigned int cpu).Chapter 7. does not have PF NOFREEZE flag set and may be neither stopped nor traced. pid t process group(struct task struct *task). Return one if critical section needs to be broken either due to another task waiting or preemption is to be performed. int freezing(struct task struct *p). zombie. The process is frozen now. If this test fails then pointers within the task struct are stale and may not be referenced. Assign task p to given cpu. but does not migrate anything. dead. This could be fixed in future versions. int frozen(struct task struct *p). change status from freezing to frozen. 115 . Wake up a frozen thread.
This function with interesting name freezes current task and enters the following cycle: set task’s state to TASK UNINTERRUPTIBLE and call schedule(). Exported symbol. 116 . int freeze processes(void). Process Management and Scheduling void refridgerator(). Return number of processes we could not freeze. Iterate through all processes and their threads and try to freeze them. void thaw processes() Thaw frozen processes.Chapter 7. This is repeated until task is unfrozen by other task (thaw process()).
[devices/]. power management and hot-plugging. with it’s support for plug-and-play. input (mouse). its sensor stops shining and the mouse is without electric power. The third primitive used by driver mode is class. they often support power management. so this two devices share a bus.6 The Linux kernel driver model introduced in 2.6 aims to unite various driver models used in the past. but they all belong to different classes: network. Another exemplary bus is USB. . The common ones were moved from specific bus/device structures to bus type or struct device. This file-system (usually mounted at /sys/) is completely virtual and contains at its root directories like [bus/]. and it acts like object oriented). which contain other items based on the HW structure of the system (or logically sorted in class).Chapter 8 New Driver Model in 2. . The driver model adheres to tradition of displaying hardware in tree-like structure. Most computers have only one PCI bus1 . sound. Let’s explain relations between these three entities: Devices like network card or sound card are usually connected to PCI bus. 1 AGP acts like second logical PCI bus with only device connected to it: the graphics adapter 117 . These devices have something in common. The PCI bus is able to do power management together with compliant devices. The idea behind is that devices have something in common: they’re connected to some type of bus. hot-plug support. This model offers better communication with userspace and management of object lifecycles (the implementation hidden behind does reference counting. When you unload module for your USB optical mouse. Both buses and devices have their common operations and properties: power management. plug and play. This hierarchy of hardware devices is represented by new file-system also introduced during 2. pci bus and usb. [class/].5 development cycle: the sysfs.
A device is controlled by a driver. 118 . its driver in struct device driver and the class is in struct class. drivers..1.h>) is simple: void kref init(struct kref *kref). It’s not used directly. The API is defined in <linux/device. 8. devices.]. the release() callback is used to clean up object. void kref get(struct kref *kref). ksets and subsystems are base on kobject.h>. void (*release)(struct kref *kref)). which is the reference counter itself. int kref put(struct kref *kref. This function returns 1 if the object was released. implemented in struct kref. or they can be embedded into ksets (and further into subsystems).h> is basic object of driver model. This structure has only one member variable: atomic t refcount. This whole hierarchy is represented by directory tree in sysfs and thus exporting the hierarchy to userspace. Decrement reference counter.1 Kref API Whole kobject infrastructure works thanks to reference counting. It uses reference counted life cycle management.Chapter 8.1 From Kobject to Sysfs Kobject is the base type for whole driver model. Initialize reference counter. The device is implemented in struct device.2 Kobject API A struct kobject defined in <linux/kobject. The API to manipulate this data type (defined in <linux/kref. There are symbolic links to the devices deep in the directory [class/]. that knows how to talk to this particular type of hardware. but it will also appear in somewhere [class/pci bus/.1. but it’s embedded in larger objects2 . 8.6 The graphics adapter connected to AGP would be [class/graphics/]. all classes. New Driver Model in 2. The internals of struct kobject are following: 2 Recall container of() macro mentioned in Common routines chapter. 8. Kobjects can create hierarchical structures.. Whne the reference counter drops to zero. Increment reference counter.
struct kset *kset. The parent of kobject.. sysfs directory entry.Chapter 8.. 119 . struct kobject *parent. then the kset is used in sysfs hierarchy. A kobject basic API is as follows: void kobject init(struct kobject *kobj). If there’s no parent for this kobject. struct kobject *kobject get(struct kobject *kobj). const char *fmt.6 const char *k name. . int kobject set name(struct kobject *kobj. struct kobj type *ktype. The kset into which does this kobject belong. Set name for the kobject. Name of kobject if shorter than KOBJ NAME LEN. Add object to the sysfs hierarchy. Get the name of kobject. int kobject add(struct kobject *kobj). const char *kobject name(const struct kobject *kobj). struct dentry *dentry. Reference counter. the arguments are in printf()-like format.). Initialize a kobject (reference is set to 1 and initialize some of its internals). Name of kobject if longer than KOBJ NAME LEN. Increase reference counter. New Driver Model in 2. Free object resources. char name[KOBJ NAME LEN]. struct kref kref. void kobject put(struct kobject *kobj). The type of the kobject. Decrease reference counter and potentially release the object (if the reference counter has falled to 0). void kobject cleanup(struct kobject *kobj).
The type take care of sysfs file operations. A kobject whose parent member variable has NULL value is toplevel object in sysfs hierarchy. struct kset).1. Initialize a kset for use (also the internal spinlock). int kobject rename(struct kobject *kobj. Kset is also a kobject of some and it is able keep kobject of one type. either using parent pointer or ksets. 3 See Memory allocation chapter for gfp t. The ksets are further part of the subsystems. Add a kset k to hierarchy. int kset register(struct kset *k). int kset add(struct kset *k). Remove from hierarchy and decrease reference count. Initialize and add kset. Delete object from the sysfs hierarchy. 120 . gfp t gfp mask). Each kobject has associated type (represented by struct kobj type with it. Change the name of the object. Kobjects are used to simulate hierarchies of objects. as will be explained later). New Driver Model in 2. int kobject register(struct kobject *kobj).6 void kobject del(struct kobject *kobj). Kobject is represented by subdirectory in sysfs. void kobject unregister(struct kobject *kobj). but with a semaphore. char *kobject get path(struct kobject *kobject. destructor (when freeing an kobject) and holds attributes.3 Kset API Kobject can be gathered into sets (named ksets. This directory is a subdirectory of directory that belongs to parent of this kobject. The kset belongs to subsystem (which is also kset. 8. void kset init(struct kset *k). const char *new name). Initialize and add an object. The kset is internally protected by spinlock. The buffer is allocated using gfp mask3 The result must be freed with kfree(). Return path associated with given kobject. All kobjects in kernel are exported to userspace via sysfs.Chapter 8.
8. 121 .1. a kset and rw semaphore rwsen.Chapter 8. Remove from hierarchy and decrease reference counter. This macro sets kset for embedded kset. void kset put(struct kset *k). Declare a subsystem of name subsys name. struct kobj type *get ktype(struct kobject * k). Each subsys attribute contains two callbacks: show() to display and store() to store attribute. New Driver Model in 2. struct kobject *kset find obj(struct kset *k. when name is the only kset’s field to be initialized. but subsystem is not a pointer. Increate reference counter. set kset name(str). type. obj is pointer to kobject.6 void kset unregister(struct kset *k). kobj set kset s(obj. If a kobject is found. Subsystem operations are mostly wrapped kset ones: decl subsys(name. This macro sets kset for embedded kobject obj to be the same as is set in subsystem. kset set kset s(obj. subsystem). increase its reference counter and return pointer to it. The lock is unlocked before return. Find a kobject in kset by its name. Decrease pointer and potentially release kset. subsystem). Subsystem can contain attribute (struct subsys attribute). Otherwiser return kobject’s type. uevent ops). struct kset *to kset(struct kobject *kobjectj) Return pointer to kset in which is the kobject embedded. If the object is in a set and the set has type set. This macro is an initializer. struct kset *kset get(struct kset *k). but subsystem is not a pointer. return this one.4 Subsystem API Subsystem (struct subsystem) contains only two member variables. with given type and uevent ops. Lock internal spinlock and iterate over a list of kobjects. Return the type of the object. obj is pointer to kobject. These attributes are exposed to user space through sysfs. which are controllable from userspace. const char *name).
release subsystem’s kset. enum kobject action action). Remove sysfs attribute file. void subsys remove file(struct subsystem *s. 122 . void subsystem init(struct subsystem *subsys). 8. this makes kset point back to subsystem void subsystem unregister(struct subsystem *subsys). subsysten). Register subsystem.1.6 subsys set kset(obj. struct subsystem *subsys get(struct subsystem *s). void subsys put(struct subsystem *s). The action is one of following: KOBJ ADD An object has been added (usable exclusively by kobject core). KOBJ REMOVE An object has been added (usable exclusively by kobject core). Export sysfs attribute file. This macro sets kset for subsystem. Decrease reference counter and if reference count drops to zero. int subsystem register(struct subsystem *subsys). int subsys create file(struct subsystem *s. but subsystem is not a pointer. obj is pointer to kobject.Chapter 8. struct subsys attribute *a).5 Kobject Kernel to User Space Event Delivery void kobject uevent(struct kobject *kobj. Notify user space by sending an event. Unregister internal kset. KOBJ CHANGE Device state has changed. struct subsys attribute *a). New Driver Model in 2. Increase reference counter. Initialize internal rw semaphore and kset.
the notification is first sent through it.6. Helper for creating environmental variables. cur index is the pointer to index into envp (i. If there is netlink socket opened. This helper return 0 if environmental variable was added successfully or -ENOMEM if there wasn’t enough space available.6. 123 ..g. Comment in 2. Comment in 2. KOBJ UMOUNT Umount event for block devices. KOBJ OFFLINE Device is offline. int *cur index. points to the first free slot in envp. int *cur len.16 source code says it’s broken. buffer points to buffer for environmental variables as passed into uevent() method.h>. format is printf()-like format. This index should be initialized to 0 before first call to add uevent var()).6 KOBJ MOUNT Mount event for block devices. .. char *buffer.2 Bus The bus API is accessible through <linux/device. 8. which contains the name of the bus e.e. New Driver Model in 2. int num envp.). envp is pointer to table of environmental variables. Moreover if uevent helper is set then it’s executed with subsystem as it’s first argument. num envp is the number of slots available. cur len is pointer to current length of space used in buffer. struct device driver *drv).16 source code says it’s broken. int buffer size. but the most interesting are its operations: int (*match)(struct device *dev. This callback is called whenever a new device is added to the bus.Chapter 8. KOBJ ONLINE Device is online. ”pci”. const char *format. The environmental variables are set to describe the event. list of devices and drivers and attributes. The basic type is the bus type structure. int add uevent var(char **envp. It is called multiple times and each time it compares device (dev) with one driver (drv).
Decrement reference counter for bus object. char *buffer. pm message t state).Chapter 8. This functions scans the bus for devices without assigned drivers and tries to match the devices with existing drivers. then enable the device and finally if the device has been bus master before make it bus master again. The API concerning bus management is as follows: int bus register(struct bus type * bus). this callback should return non-zero value. int (*probe)(struct device *dev). device attach() attaches device to driver. Remove device from the bus. This callback is useful for sending events to user space. int (*resume)(struct device * dev). for example to load some module. If any device/driver pair matches. void (*shutdown)(struct device *dev). Probe for a device. int buffer size). int (*suspend)(struct device *dev.6 If they match.e. Unregister the child subsystems and the bus itself. void bus unregister(struct bus type * bus). the driver is able to manage the device. See kobject API. New Driver Model in 2. int num envp. void bus rescan devices(struct bus type * bus). int (*uevent)(struct device *dev. configure the device etc. char **envp. Resume the device. i. struct bus type *get bus(struct bus type * bus). Power management: suspend device. Shutdown the device. int (*remove)(struct device *dev). Increment reference counter for bus object. Register a bus with the system. For example on PCI this first resumes PCI config space. 124 . void put bus(struct bus type *bus).
void *)). int (*fn)(struct device driver *. New Driver Model in 2.6 struct bus type *find bus(char *name). struct device *start. return value is NULL. the return value is 0. non-zero value breaks iteration and this function will return that value. data) callback is called for each device. Remove attribute file from sysfs. store). void bus remove file(struct bus type *bus. data) callback returns non-zero when the device is found and this function exits with return value pointing to struct device of found device. Iterate over a bus’s list of devices starting from start. int (*fn)(struct device *. Find bus by given bus name. void *data.Chapter 8. An attribute is a struct bus attribute. void *)). int bus for each drv(struct bus type *bus. Iterate over a bus’s driver list. int bus for each dev(struct bus type *bus. If no suitable device was found. struct bus attribute *attribute). struct device driver *start. int (*match)(struct device *. The bus attribute supports two operations: show() to show value kept inside and store() to store a new value. which declares struct bus attribute of name bus attr name . If the iteration is successfully finished. Otherwise the return value is zero. return pointer to found bus type or NULL if the bus was not found. mode. struct device * bus find device(struct bus type *bus. void *)). int bus create file(struct bus type bus*. Create an attribute file for given attribute of a bus in codesysfs. it’s a mechanism to provide some interface to user space for setting/getting values. Return value of fn() is checked after each call. If the caller needs to access struct device driver that caused iteration to fail. void * data. 125 . fn(device. void *data. its reference counter must be manually increased in callback. show. Return value of callback fn(driver. data) is checked after each call and if it’s zero the iteration is broken and this return value is also return by bus for each drv(). but it tries to find particular device. Reference counter for device that broke iteration is not incremented. The match(device. This function is similar to bus for each(). struct device *start. New attribute can be declarede using BUS ATTR(name. it must be done in callback if it’s needed. struct bus attribute *attribute).
Find a driver on a bus by its name.3 Drivers Driver (represented in our model by struct device driver) has a name and is connected to some particular bus. extern void put driver(struct device driver *drv). show. Increase reference counter of given driver. Remove driver from the system: the completion will block us until reference count drops to zero. Register a driver with a bus and initialize completion. void (*shutdown)(struct device *dev). extern struct device driver *driver find(const char *name. 126 . struct bus type *bus). int (*suspend)(struct device *dev. int (*resume)(struct device *dev). The driver has its operations and attributes. Driver API is following: extern int driver register(struct device driver *driver). int (*remove)(struct device *dev). pm_message_t state). The driver uses struct completion unloaded to unload itself only if reference count has dropped to zero. New Driver Model in 2. int driver create file(struct device driver *driver. the variable will be named driver attr name . struct driver attribute *attribute). suspending and resuming devices (see bus type operations): int (*probe)(struct device *dev). Driver attributes contain reader and writer routines to show() the value to user space or retrieve a new one using and store() it back to attribute.Chapter 8. extern void driver unregister(struct device driver * drv).6 8. store). extern struct device driver * get driver(struct device driver *driver). The device offers following operations for probing. Decrease reference counter of given driver. Driver attribute can be declared using macro DRIVER ATTR(name. which can be (as in other object in this model) exported to user space. Create a file in sysfs for given attribute. It keeps pointer to module in which it’s implemented. removing. mode.
4 Classes A device class provides higher level view of a device. struct driver attribute *attribute). Remove a file from sysfs for given attribute. void *data. The matching device is returned as the return value of this function (the first match also cancels iteration). struct device *start. The difference is in callback: match(device. void *data. Iterate through devices bound to driver. If driver probe device() returns 0 and device->driver is set. data) returns zero for device that doesn’t match and non-zero for a matching device. Walk through the device list of the bus this driver is attached to and try to match the driver with each device. return NULL. int (*match)(struct device *. 8. Subsystem for this class. Classes allow user space software to work with devices based on ’what they are’ or ’what they do’ rather than ’which bus are they connected to’. struct module *owner. New Driver Model in 2. int driver for each device(struct device driver *driver.Chapter 8. If no device was matched. void *)). a compatible pair was found and the driver will now manage the device.6 void driver remove file(struct device driver *driver. void *)). which contains: const char *name. 127 . Pointer to struct module which owns the class. int (*fn)(struct device *. Basic data type representing class is struct class. struct device * driver find device(struct device driver *driver. data) callback will be called for each device found. struct device *start. void driver attach(struct device driver *drv). fn(device. Each class is also a subsystem. starting from start device. Iterate throiugh devices bound to driver similarly as in driver for each device(). struct subsystem subsys. The name of the class.
void class destroy(struct class *class). The last attribute must have empty name. create attribute files in sysfs and create a subsystem for this class. The API for device class manipulation is following: int class register(struct class *class). int num envp. This callback will be called on class release. New Driver Model in 2. Pointer to array of class attributes. int buffer size). Pointer to array of class device attributes. The last attribute must have empty name. This is used to create a class that can be used in calls to class device create(). Destroy a class previously created with class create() struct class *class get(struct class *class).6 struct semaphore sem. Increment reference counter for given class and return pointer to it. char *buffer. This callback is called when a device is going to be released from this device class. int (*uevent)(struct class device *dev. This structure should be destroyed using class destroy() call. Unregister class and its subsystem and remove corresponding files. The release() and class release() callback are initialized. Semaphore that locks both the children and the interface lists.Chapter 8. The newly created class is also registered. void (*class release)(struct class *class). void class unregister(struct class *class). struct class device attribute *class dev attrs. char *name). struct class attribute *class attrs. void (*release)(struct class device *device). Register a new device class. 128 . struct class *class create(struct module *owner. char **envp. This callback is useful for sending events to user space. Create a struct class with given owner and name.
Each attribute is represented by struct class attribute with show() and store() callbacks to get and set the attribute value: ssize_t (*show)(struct class *. For internal use by the driver core only. store) macro. Each class can have an array of accompanying attributes. void class remove file(struct class *class.Chapter 8. Pointer to the parent class for this class device. mode. Remove file for attribute. 129 . Attribute that represents events for user space. Points to struct device of this device. ssize_t (*store)(struct class*. New Driver Model in 2. const struct class attribute *attribute). struct class device attribute uevent attr. Class attribute can be declared using CLASS ATTR(name.5 Class Devices Class devices are devices belonging to particular class. this is represented by symlink in sysfs hierarchy. Create a file representing given attribute. int class create file(struct class *class. char *). which declares and initializes variable class attr name . struct class device attribute *devt attr.6 void class put(struct class *class). const struct class attribute *attribute). Required in all instances. Decrement reference counter for given class and release it if the counter has dropped to zero. show. const char *buf. struct class device contain following member variables: struct class *class. size_t count). show() and 8. store() are attribute access functions as described before. struct device *device.
int num envp. This callback is used during release of struct class device. driver developer may use this field for anything. void class device initialize(struct class device *dev). char class id[BUS ID SIZE]. int(*uevent)(struct class device *dev. Use class get devdata() and class set devdata() to access this field. void(*release)(struct class device *dev). Class device specific data. char **envp. If NULL then this device will show up at this class’ root in sysfs hierarchy. Return pointer to class specific data. Parent of this device if there is any. New Driver Model in 2. See class device register() for most cases. Create files for attributes. int class device register(struct class device *dev). The API for struct class device manipulation is similar to other kobject APIs: void *class get devdata(struct class device *dev). 130 . release the structure.6 void *class data. (see class device add()). If it’s set. the class-specific uevent() callback will be used.Chapter 8. The developer should use in cases like releasing nested class device structures. it will be called instead of the class specific release() callback. Set pointer to class specific data. Unregister the class device and if the reference counter for this structure has is zero. int buffer size). If this pointer to function is not set. Add device to concerned class and configure user space event notification. This callback is used to send event notifications to user space. At the end an event KOBJ ADD is signalled to user space. void class set devdata(struct class device *dev. char *buffer. int class device add(struct class device *device). void *data). Initialize the class device. Initalize the class device and add it to it’s class. struct class device *parent. void class device unregister(struct class device *dev). Unique ID for this class.
. Remove device from parent class. char *fmt. initialized an registered inside this function. 131 . int class device add(struct class device *device). Class device attribute (struct class device attribute) offers the same functionality as other attributes in this driver model: show() and store() operations. New Driver Model in 2. struct class device *class device create(struct class *cls. int class device create file(struct class device *dev. class id. The attribute can be conveniently declared using CLASS DEVICE ATTR(name. dev t devt. char *name). Create a class device and register it with sysfs hierarchy. device points to struct device associated with this class device. This function can be used by character device classes. Create a file in sysfs hierarchy representing given attribute. void class device destroy(struct class *cls. store) macro.. Rename the class device. void class device put(struct class device *dev). int class device rename(struct class device *dev. const struct class device attribute *attribute).6 void class device del(struct class device *dev). show. struct device *device. remove symlinks and attribute files and issue KOBJ REMOVE event to user space. Increment the reference counter for this structure. cls is the pointer to class that this device should be registered to. parent class device may be NULL pointer. struct class device *class device get(struct class device *dev). mode. cls is the class to which the class device belongs and devt identifies the device. struct class device *parent. which declares class device attr name variable and initializes it’s operations to given callbacks. struct class device will be allocated.Chapter 8. parent class and dev member variables must be set before this call is made. Remove a class device that was created with class device create(). dev t devt is for character device to be added.). . Decrement the reference counter and release the structure when it reaches zero. fmt and following arguments represent printf-like description of this class device’s name. dev t devt).
loff t offset. struct bin attribute *attr. which contains four interesting pointers: struct list head node. kobj is the object to which this attribute belongs. This instance’s entry into list of observers of concerned class. A binary attribute is similar to forementioned attributes. struct bin attribute *attribute). const struct class device attribute *attribute). Remove a file representing an attribute. struct bin attribute *attribute). int class device create bin file(struct class device *dev. kobj is the object to which this attribute belongs. Write size chars from buffer to binary attribute from given offset and size. Remove a file associated with attribute. New Driver Model in 2. Points to class to which is this interface bound and on which we monitor adding and removing of devices. struct vm area struct *vma). Map binary attribute to user space memory. 132 . char *buffer. struct class *class. 8. ssize t (*write)(struct kobject *kobj. vma is the VM area to be used.6 void class device remove file(struct class device *dev. size t size). attribute is the attribute belonging to kobj object.Chapter 8.6 Class Interface The last structure introduced in class section is struct class interface. but it stores binary data and it’s operations are as follows: ssize t (*read)(struct kobject *kobj. char *buffer. size t size). Read size chars from offset of binary attribute to buffer. Create a file in sysfs hierarchy representing given binary attribure void class device remove bin file(struct class device *dev. int (*mmap)(struct kobject *kobj. loff t offset.
dev is the device that will be removed.6 int (*add) (struct class device *dev. void (*remove) (struct class device *device. 8.Chapter 8. The class which will be observed is observer->class. Attribute.7 Devices Let’s describe struct device: struct device *parent. struct bus type *bus. that has store() struct semaphore sem. struct class interface *interface). void class interface unregister(struct class interface *iface). A NULL parent means top-level device. The bus this device is connected on. New Driver Model in 2. struct kobject kobj. This structure represents observer that gets notification about device adding and removal. i. Unique string identifying this device on the bus. int class interface register(struct class interface *observer).e. the device to which is this device attached. usually a bus. 133 . The kobj keeps this device in the sysfs hierarchy. the only API for manipulation with observer are functions for registering an unregistering an interface. This pointer points to function that will be called upon device removal. A semaphore to synchronize calls to driver. Add an observer to chain of observers. add points to function which will be called when some device is added to observed class. This is the parent device. Remove an observer. struct class interface *interface). char bus id[BUS ID SIZE]. dev is the device that is to be added. struct device attribute uevent attr.
which is what device register() exactly does. int device for each child(struct device *parent. void (*release)(struct device *dev). void device unregister(struct device *device). Iteratate over a list of children of parental device and call fn(child device.e. The common driver API is following: int device register(struct device *device). New Driver Model in 2. This function also sets many internal member variables inside struct device.6 struct device driver *driver. int (*fn)(struct device *. void device initialize(struct device *device). Adds the device to sysfs hierarchy (bus etc). to the bus). The driver managing this device. void *)). Remove the device from lists it’s kept in. This should be called manually only if device add() was also called manually. This function is usually preceded by device initialize(). Otherwise the structure will be hanging around in memory until its reference count drops to zero. Register a device with the sysfs hierarchy. when the reference counter drops to zero. If it has dropped to zero. Private driver data. Power state of the device. 134 See . void *data. device register() is the preferred way. Initialize struct device and prepare device to be woken up. int device add(struct device *device). first initialize the device and then add it to system (i.Chapter 8. see device unregister(). device add() and note about device register(). This method releases the device. void *driver data. the device is released by device release(). notify power management and platfom dependent functions about removal. Release the device from all subsystems and then decrement the reference count. void device del(struct device *device). struct dev pm info power.
void dev set drvdata(struct device *dev. . Set driver specific data for this device. . void *dev get drvdata (struct device *dev). This function returns 1 if the driver was bound to this device. This function must be called with dev->sem held for USB drivers. void device shutdown(void). Shut down all devices. int device is registered(struct device *dev). Increase the reference counter. New Driver Model in 2. Walk the list of the drivers attached to bus on which is the device connected and call driver probe device() for each one. Decrease the reference counter. This calls shutdown() operation on each device. struct device *get device(struct device *dev). subsystem. int device attach(struct device *dev). void put device(struct device *dev).6 data) on each one. void device release driver(struct device *dev). Return whether a device is registered.) for importing an exporting values. void device bind driver(struct device *dev). Get driver specific data for this device. Manually attach a driver: dev->driver must be set. This function does not manipulate bus semaphore nor reference count. If a compatible pair is found. break the iteration and return this value. System devices are shut down as the last ones. If the fn() returns non-zero value. Manually release driver from device. Each device also has its set of attributes (just like bus. 0 if no matching device was found or error code otherwise. This function does not manipulate bus semaphore nor reference count. This function must be called with dev->sem held for USB drivers. break iteration and bind the driver to this device.Chapter 8. void *data). Device attribute (struct device attribute) is declared 135 .
struct device attribute *entry). Remove file in sysfs that representing given attribure.h>). struct ide driver s (or ide driver t) and struct eisa driver. int (*probe) (struct usb interface *intf. 8.8 Extended structures Existing buses have their own bus type variables: pci bus type (<linux/pci.6 using DEVICE ATTR(name. void device remove file(struct device *device. int device create file(struct device *device. show. store) macro. it should be unique among USB drivers and it also should be the same as the module name. This callback is called when an interface is no longer available: either the device has been unplugged or the driver is being unloaded. We’ll look more closely on some member variables of struct usb driver: const char *name.h>). mca bus type (<linux/mca.g. If it is so. 136 . zero is returned and dev set drvdata() from the device API to associate driver specific data with the interface. show() and store() operations are available for getting/setting values from user space. mode. struct usb driver. This callback is called to check whether the driver is willing to manage a particular interface on a device.Chapter 8. it must return negative error value. ide bus type (<linux/ide. struct pci driver. struct mca driver.h>) and usb bus type (<linux/usb. A driver is tied tightly to a bus and most of existing buses use extended versions of struct device driver. eisa bus type (<linux/eisa. struct device attribute *attr).h>). which declares and initializes variable named dev attr name . New Driver Model in 2. e.h>). void (*disconnect) (struct usb interface *intf). It the driver is not willing to manage the device. Create a file in sysfs that will represent given attribure. This is the driver name. const struct usb device id *id).
It’s common for <linux/name of a bus. this provides more ways to provide information to user space. int (*suspend) (struct usb interface *intf. unsigned int code.h> files to offer API for that particular type of a bus. Handler for usbfs events. Called when the device is going to be resumed (power management)¿ struct device driver driver. developer should look inside those files as detailed description is behind scope of this work. Wary reader surely noticed struct usb interface. int (*resume) (struct usb interface *intf). This is the device driver’s structure for driver model. Called when the device is going to be suspended (power management). 137 . New Driver Model in 2.Chapter 8. This structure contains both struct device and struct class device and some other internals. void *buf).6 int (*ioctl) (struct usb interface *intf. pm message t message).
KERN WARNING Defined as <4>. 138 . means ”action must be taken immediately”. These priorities are defined also in [kernel. means ”system is unusable”. license).Chapter 9 Common Routines and Helper Macros 9. means ”error conditions”.1 String Manipulation Following routines accessible through <linux/kernel.h]: KERN EMERG Defined as <0>. KERN ERR Defined as <3>. dmesg and syslog daemon.. means ”warning conditions”. The output should contain priority. . KERN ALERT Defined as <1>.\n". Output the message to console. which can be added in the following manner: printf(KERN_WARNING "%s: module license ’%s’ taints kernel. mod->name.). For formatting options see man 3 printf. KERN CRIT Defined as <2>. means ”critical conditions”.h>: int printk(const char* format..
int *ints). KERN DEBUG Defined as <7>. This function internally calls vprintk. int get option(char **string. .). vsprintf(char *buf. Return value is the character in 139 . int *value). const char* format. . vsnprintf(char *buf. size t size.).Chapter 9. 1 if int was found without comma and 2 if comma was found too. va list args). va list args). The kernel mode equivalent of usual user space sscanf(). Parse an integer value from an option string. Common Routines and Helper Macros KERN NOTICE Defined as <5>. means ”debug-level messages”. Parse a string containing comma-separated list of integers into a list of integers. string is the string to be parsed. const char* format. The kernel mode equivalent of usual user space sprintf(). . This is the kernel mode equivalent of vprintf. means ”normal but significant condition”. char *get options(const char *string. A subsequent comma (if any) is skipped and string pointer is modified to point behind the parsed int. The kernel mode equivalent of usual user space snprintf(). The kernel mode equivalent of usual user space vsprintf(). means ”informational”. sprintf(char *buf. KERN INFO Defined as <6>. nints is the size of integer array ints. const char* format. vsscanf(const char *buf. . first see man 3 vprintf and then explanation of printk() above. which uses 1024 byte buffer and does not check for overruns. Return 0 if there’s no integer in string. int nints. The kernel mode equivalent of usual user space vsnprintf(). va list args). int printk(const char *format. . . ints[0] contains the number of integers successfully parsed. The kernel mode equivalent of usual user space vsscanf(). const char *format. sscanf(const char *buf.). Integers parsed are stored into ints from index 1. . . . const char *format. snprintf(char *buf. va list args). const char* format. size t size.
max t(type. Common Routines and Helper Macros the string which caused end of parsing. typecheck(type. both x and y will be type-casted to it. x. This macro can be used to check various conditional branches that shouldn’t be executed. return the pointer to the structure itself. typecheck fn(type. BUG() This macro (with CONFIG BUG defined) prints message about bug and it’s location and then kernel panics.y). It’s intended for debugging purposes to help find out whether the function (which shouldn’t sleep) sleeps. Always evaluates to value 1. might sleep if(condition) First evaluate the condition and if it’s true then evaluate might sleep macro described above. max(x. min(x. x. Prototype is in <linux/string.h> 9. If it’s null then the string was parsed completely char *kstrdup(const char *s. min t(type. irq handler. See list entry() and list implementation for an example.y) Macros that return minimal or maximal value of given pair. type. BUG ON(condition) This macro first checks the condition and if it’s true then calls BUG(). .Chapter 9. gfp is the mask of flags used in kmalloc() call. min t() and max t() allow developer to specify a type. typedef must be used to specify for function type.y). gfp t gfp). min() and max() also does strict type checking. 140 . variable) Check at compile time that variable is of given type.2 Various Helper Macros it prints a stack trace if it’s executed in an atomic context (spinlock.). container of(pointer. . member) If pointer points to member variable inside the structure of given type. might sleep() This macro works as an annotation for function that can sleep. Allocate space to hold duplicate of strin s and copy the string. function) Check at compile time that function is of a certain type or a pointer to that type.y).
unsigned long n). int.) from kernel variable to address at given user space memory with less checking. const void *from. 141 . size) Verify whether the memory area specified by addr and size is accessible for given type of access: VERIFY READ for reading and VERIFY WRITE for writing. addr. int. put user(kernel variable. . . Returns true on success and -EFAULT on error. get user(kernel variable. macros or prototypes: access ok(type.) from user space memory to given kernel variable with less checking. This macro may sleep and it’s valid only in user context.) from kernel variable to address at given user space memory.) from user space memory to given kernel variable. unsigned long copy to user inatomic(void user *to. . likely(condition) and unlikely(condition) These macros advise compiler which branch is prefered. This macro is only valid in user context. <asm/uaccess. umode ptr) Copy a simple variable (char.3 User Space Memory Access The file Kernel code sometimes needs to access data in user space memory.h> provides all necessary inline function. Writing is superset of reading. umode ptr) Copy a simple variable (char. Common Routines and Helper Macros WARN ON(condition) This macro (with CONFIG BUG) prints message about it’s location in file and function on which line it’s been placed. . This macro may sleep and it’s valid only in user context. Returns true on success and -EFAULT on error. 9. so the resulting assembly coded will be optimized for this branch. get user(kernel variable. . int. . Returns true on success and -EFAULT on error. umode ptr) Copy a simple variable (char. This macro may sleep and it’s valid only in user context. put user(kernel variable. Returns true if the memory is valid. int.Chapter 9. umode ptr) Copy a simple variable (char. This macro may sleep and it’s valid only in user context. Returns true on success and -EFAULT on error. . .
zero on success. This function may sleep. Returns the number of bytes that cannot be copied. zero on success. unsigned long n). zero on success. Caller must check the specified block with access ok() before calling this function. If string is too long. Caller must check the specified block with access ok() before calling this function.Chapter 9. Valid in user context only. user *from. i. from is source in kernel space. Returns the number of bytes that cannot be copied. Copy data from kernel space to user space. Copy a NULL terminated string from user space to kernel space. Copy data from user space to kernel space. the return value is n. Common Routines and Helper Macros Copy a block of data into user space. This function is valid only in user context. Return value is the number of bytes that could not be copied. unsigned long copy from user inatomic(void *to. long strnlen user(const char user *s. Get the size of the string s in user space. This function might sleep. If count is too small.e. user *src. long n). n is number of bytes to copy. unsigned long n). from is source in kernel space. unsigned long copy from user(void *to. const void *from. zero on success. user *to. Valid in user context only. long strncpy from user(char *dst. Return value is the lengh of the string or zero in case of error. const void user *from.e. const void unsigned long n). i. This function might sleep. long user *from. This function might sleep. const void copy from user inatomic(). destination dst must be at least count bytes long. Return value is the number of bytes that could not be copied. otherwise -EFAULT. copy count bytes and return count. Wrapper that calls unsigned long copy to user(void unsigned long n). to is the destination in kernel space. to is the destination in user space. 142 . Return value is lenght of the string (NULL omitted). unsigned long copy from user(void *to. This function is valid only in user context. This function may sleep. Copy a block of data from user space. n is the maximum valid length. const char count). n is number of bytes to copy.
Return value is the lengh This is a macro evaluates to Zero a block in user memory.MAXINT). strnlen user(str. unsigned long clear user(void user *mem. Return the number of bytes that could not be cleared. unsigned long len). mem is destination.Chapter 9. len is the length of the block in bytes. Get the size of the string s in user space. zero on success. Common Routines and Helper Macros strlen user(str). of the string or zero in case of error. 143 .
h> static char mpad_init[] __initdata="initialized". Each module goes through three phases while it’s loaded in kernel: initialization. This implies that modules have dependencies between themselves.\n".h> #include <linux/kernel. normal operation and clean-up. These hooks are unhooked during clean-up phase. mpad_init). which will be used during normal operation.ko. 10.o).ko instead of . } static void __exit mousepad_exit() 144 . return 0. which can be dynamically inserted to (or removed from) the kernel. static char mpad_exit[] __exitdata="exiting". which will be driver for mouse pad: #include <linux/module.1 An Exemplary Module Let’s build an exemplary module named mousepad. The module is dynamically linked with the rest of the kernel and other modules at the insertion time. static int __init mousepad_init() { printk(KERN_INFO "Mouse pad %s.Chapter 10 Modules A module is an object file (but with extension . Initialization phase is usually implemented by simple function which sets up some hooks.
therefore exit function is never used. the functions init and variables marked with ory. Once the initialization is completed. A driver that is built-in cannot be unloaded. used only during initialization phase and then the memory is freed. the module is unloaded. MODULE_AUTHOR("Jaroslav Soltys"). if initializing function does not return zero. 145 .data. Drivers which made it to official kernel can be either selected to be compiled as modules or they can be built-in. The other function is used before unloading of module from kernel. mpad_exit). MODULE_SUPPORTED_DEVICE("mousepad"). Our example just prints string "Mouse pad initalized. Modules { printk(KERN_INFO "Mouse pad %s.Chapter 10. This is the cause during kernel initialization. MODULE_LICENSE("Dual BSD/GPL").data section. This exit-function is selected by module exit(). init macro marks functions which decides at compile time whether to include exit function or not. This is accomplished by putting side object file. exitdata puts variables used only from within exit con- You can think of these init and exit functions as constructors and destructors in OOP.\n".1 It simply prints "Mouse pad exiting. 1 init functions to . To save memory Similar memory-saving is done with init functions: for message Freeing unused kernel memory: marked with 4486k freed initdata are freed from memexit puts the functions to exit macro was introduced.text section in- initdata to . . The module init() macro selects which function is called during initialization.exit.init.exit. module_exit(mousepad_exit).init. } module_init(mousepad_init).". This driver contains two functions: mousepad init() is used in the initialization phase. MODULE_DESCRIPTION("Mouse Pad driver").data section and text to . Remember." (probably to [/var/log/messages]).
A tainted kernel is a kernel containing code. Kernel may be tainted by loading proprietary module. using SMP with CPUs not designed for SMP. "Dual BSD/GPL" GNU GPL version 2 or BSD license. 10. MODULE DESCRIPTION describes what a module does. /proc/sys/kernel/tainted returns 1 for tainted kernel. Modules 10. Proprietary modules can either use MODULE LICENSE("Proprietary") or anything other than forementioned GPL strings is considered proprietary. which is neither under GPL license nor under any ’compatible’ free/open software licenses. "GPL and additional rights" GNU GPL version 2 rights and more. machine check experience or bad page. Kernel purity is indicated by following licenses: "GPL" The module is under General Public license version 2 or later. The purity status of a kernel is exported to user space using procfs. forcing loading or unloading of module. The license of a module is specified by MODULE LICENSE() macro. 146 . it remains tainted until reboot. "Dual MPL/GPL" GNU GPL version 2 or Mozilla license code. However developers should use this macro for documentation purposes.2 Kernel Purity Kernel 2. but it might be used in the future to say that this module implements [/dev/device].3 Module Properties Module properties (such as MODULE LICENSE) can be seen using modinfo command.4 introduced tainted kernels. MODULE SUPPORTED DEVICE("device") is not yet implemented. "GPL v2" The module is under GPL version 2 license. Once a kernel becomes tainted.Chapter 10. MODULE AUTHOR declares module’s author.
static int __init mousepad_init() { int i. S_IRUSR|S_IWUSR).\n". &ver_len. S_IRUSR|S_IWUSR). static int ver_len=VER_LEN. color. COLOR_STR_LEN. -1}.h> static char mpad_init[] __initdata="initialized".h> #include <linux/kernel. port. module_param_array(version. module_param(height. int. Modules 10.h> #include <linux/init. 147 . S_IRUSR|S_IWUSR).4 Module Parameters Modules used to take parameters since time of ISA bus. Modern hardware is usually able to operate without any parameters. DMA channel and IRQ for a sound card driver.Chapter 10. -1. #define VER_LEN 3 static int version[VER_LEN]={-1. int. module_param(width. static char mpad_exit[] __exitdata="exiting". It was necessary to specify e. Let’s augment our existing code: #include <linux/module. static int height=15. int.h> #include <linux/stat.h> #include <linux/moduleparam.g. #define COLOR_STR_LEN 80 static char color[COLOR_STR_LEN]="deep blue". but these interface still provides the possibility to send parameters to a module. static int width=20. because earlier versions of this bus did not support plug and play operation. printk(KERN_INFO "Mouse pad %s. module_param_string(color.mpad_init). S_IRUSR|S_IWUSR).
width.".Chapter 10. "Mouse pad width"). color). We introduced parameters height and width to hold size of a mouse pad. MODULE_SUPPORTED_DEVICE("mousepad"). MODULE_DESCRIPTION("Mouse Pad driver"). version[i]). printk(KERN_INFO "Mouse pad colour: %s\n". color). version[i]). color of the pad and version number that consists of up to three dot-separated numbers. MODULE_PARM_DESC(height. module_exit(mousepad_exit). MODULE_PARM_DESC(color. "Mouse pad color"). printk(KERN_INFO "The mouse pad is version "). i<ver_len. width. MODULE_LICENSE("Dual BSD/GPL"). } module_init(mousepad_init). MODULE_PARM_DESC(version. "Version of a mouse pad"). mpad_exit). for(i=0. i<ver_len.\n". printk(KERN_INFO "Mouse pad %s. height). height). Each parameter can be set at command line: 148 . "Mouse pad height"). } static void __exit mousepad_exit() { int i. i++) printk("%i. i++) printk("%i.\n". for(i=0. return 0. Modules printk(KERN_INFO "The mouse pad is version "). printk(KERN_INFO "Mouse pad colour: %s\n". MODULE_AUTHOR("Jaroslav Soltys"). printk("\n" KERN_INFO "It’s size is %ix%i.\n".". printk("\n" KERN_INFO "It’s size is %ix%i. MODULE_PARM_DESC(width.
int height is declared as ordinary variable. ulong (unsigned long). use module param array() macro with four parameters: name. says what’s the meaning of a parameter. the module will fail to load. int. The last type described is string color.3 mousepad init() writes values of these variables to /var/log/messages. while echo 4. Use 149 . charp (char *). The strings are exported using module param string().ko height=15 width=20 color=red version=1. type of a single item inside an array. long. ushort (unsigned short). Similarly color is string with limited length. Sysfs has a directory called /sys/module/mousepad/parameters for our mousepad. then var len is modified accordingly. which can be one of simple types like byte. Let’s describe the simplest type firstr. Module with parameter version more than three numbers can’t be loaded into kernel.2 parameter. Each parameter has a description assigned to it. it’s the name of the variable to be used as module parameter and it’s also the name of the parameter. if you try to load module with longer string. uint (unsigned int). array length (this must be pointer to int variable. string. To export an array of simple types as module parameter. which uses four parameters: name. more complex types will be described later. This macro takes three arguments: name is the first one. kernel won’t allow you to load module with longer parameter or write to belonging file more bytes than this limit allows) and finally file permissions. "Version of a mouse pad"). as this value can be decreased when shorter array is sent from user space) and again file permissions. MODULE PARM DESC(version.Chapter 10. The third argument describes file permission in sysfs. short. These parameter may be read or written. bool and invbool (inverted boolean). If there are only two numbers in version=1.ko module. For example echo red > color starts internal kernel mechanism that stores zero-terminated string "red" into color buffer. buffer size (to prevent buffer overrun. but it’s made accessible as module parameter thanks to module param(name) macro. which offers virtual file for each parameter. Modules insmod mousepad. /sbin/modinfo to display this information.2. cat version prints version. The second one is type.5 > version sets first and second numbers of version array and also sets ver len to 2. and you can’t skip any number. all of our parameters are RW for owner (root). You must always set at least one number in array.
6 makes building modules using makefiles easier then ever: obj-m+=mousepad. which take following variables (only those interesting are listed): obj-m List of modules you want to build ([mousepad. If this variable is not set then [extra/] is used as default. INSTALL MOD DIR The relative path inside the kernel’s module collection and selects where will be the module located. obj-y List of modules that will be built-in in the kernel.Chapter 10.o] in our case). Kbuild offers ready-to-use makefiles. (this is not interesting for external modules). change KDIR variable to point it to relevant kernel source. The most important make targets are: 150 . Modules 10. Kbuild in 2. if the module is split into multiple files.o KDIR=/lib/modules/$(shell uname -r)/build all: make -C $(KDIR) clean: make -C $(KDIR) install: make -C $(KDIR) M=$(PWD) modules_install M=$(PWD) clean M=$(PWD) modules If you’re not building module for current kernel.5 Building Modules It’s convenient to include a Makefile with your module’s source code. obj-n List of modules that won’t be built. modulename -y List of object files that will be linked to create the module.
modules install Install the module into [/lib/modules/`name -r` u /extra/]. These symbols can be exported using one of following macros: EXPORT SYMBOL(name) This macro exports symbol of given name. 151 . See [Documentation/kbuild/] for more in-depth information. See INSTALL MOD DIR to place module somewhere else than into [extra/] directory.6 Exporting Symbols When a module is loaded into kernel it needs to resolve references to some kernel functions. This symbol can be used by any module. Modules under proprietary licenses cannot access this module. Modules modules Build modules.Chapter 10. This macro also for documentation purposes marks the symbol as external. EXPORT SYMBOL GPL(name) This macro exports symbol of given name to GPL-complatibly licensed modules.ko and temporary files. 10. This symbol is internal for documentation purposes. clean Clean target .
6 at the time I started working on this thesis. there are plenty of opportunities for deeper studies: networking infrastructure. Studying Linux kernel is a hard nut to crack in the beginning. Some other interfaces became deprecated in favor of other ones. The assignment proved to be too general. Inner working of scheduler can be of great interest for people studying optimization of parallel algorithms. the view of changes. This thesis however does not drain every possible information from Linux kernel. yet I have describe task scheduler and process management deeper than just the API.6 internals. I learned many things while I was studying the kernel and I hope that this thesis will help me to share this knowledge with others. Writing about software under heavy development is like shooting at the moving target. other ones evolved in some way. virtual file system or memory management internals would make a theses by themselves. Description of other subsystems should be sufficient to understand basics of how the subsystem works and the API needed for module developers to use the functionality provided by particular subsystem. There were no books available and only a few resources describing 2. new features and performance improvements introduced to kernel 152 . Interesting and comprehensive is the description of driver infrastructure. Some of the internal interfaces mentioned here were changed after I described them for the first time. I put strong emphasis on locking issues and therefore I delved deeper into various techniques provided. Time spent with kernel source.6 released.Chapter 11 Conclusion My goal was to describe Linux kernel 2. There was even no stable kernel 2. and this thesis aims to fill some of the gaps between theoretical knowledge of operating systems’ inner working and practical expertise of Linux kernel.
Chapter 11. Conclusion have convicted me that Linux has very bright future.
153
Bibliography
[1] Daniel P. Bovet and Marco Cesati. Understanding Linux Kernel. O’Reilly Media, Inc., 2nd edition edition, December 2002. This book covers kernel 2.4. [2] Daniel P. Bovet and Marco Cesati. Understanding Linux Kernel. O’Reilly Media, Inc., 3rd edition edition, November 2005. This book covers kernel 2.6. [3] Ladislav Lhotka. Server v Internetu. Kopp, 1st edition edition, 2006. Published in czech language. [4] Dirk Louis, Petr Mejzlík, and Miroslav Virius. Jazyk C a C++ podle normy ANSI/ISO. Grada, 1st edition edition, 1999. Published in czech language. [5] Michael Lucas. Síťový operační systém FreeBSD. Computer Press, 1st edition edition, 2003. Published in czech language. [6] Linux Kernel Mailing List <linux-kernel@vger.kernel.org>, archive is accessible on. [7] Linux Mailing List <linux@lists.linux.sk>, Slovak Linux mailing list, archive accessible on. [8]. [9]. [10]. [11]. [12]. [13]. [14]. [15]. 154
Bibliography [16]. [17]. [18]. [19]file.sf.net/. [20]. [21]. [22]. [23]. [24]. [25]∼mel/projects/vm/guide/. [26] corvi/games/lkpe/index.htm. [27]. [28]. [29]. [30]. [31]. [32]. [33]∼davej/docs/post-halloween-2.6.txt. [34]∼frey/linux/. [35]. [36]∼mel/projects/vm/guide/html/understand/. [37]. [38].
155
org/.wikipedia. [47] IRC channel #kernelnewbies on server irc. [43] 2005 driver model/index.net. [46]. [42]. [48] IRC channel #slackware on server irc.org/linux-patches/nio-improve.umn.Bibliography [39]. [40]. [41]∼bentlema/unix/advipc/ipc.kroah.html.net.org/.html.3/1647.cs.indiana. [45]. [44]. 156 .com/log/.html.oftc.
Installable File System. • ACL .File Transfer Protocol • GDT . this abbreviation refers either to one of many BSD derivates of Unix or to BSD license.IP in IP tunneling 157 . not through the server).Central Processing Unit • DCC .Internet Control Message Protocol • IFS .e.Input/Output • IP . • CPU .Global Descriptor Table. i386-specific table used to access segments of memory • HAL .Asynchronous Input/Output • API .Internet Protocol • IPIP .Hardware Emulation Layer • ICMP .File Descriptor • FTP .Processor architecture compatible with Intel 80386 processor.Direct Client-to-Client connection used on IRC network either to transfer files or to chat directly (i. an IFS-kit enables developer to write a new filesystem for Windows family of operating systems.Originally Berkeley Software Distribution. • I/O .Application Program Interface • BSD . • FD .Hardware Abstraction Layer • HEL .Access Control List • AIO .Glossary • i386 .
Non-Uniformed Memory Access .Memory Management Unit. but the memory is closer to some processors than to other and thus more optimization in scheduler is needed. the first of three levels of table structures used in memory pagination. The X signifies the Unix heritage of the API.Page Middle Directory • POSIX .Glossary • IPX .Keep It Simple. • PIC . others simply crash. While some OSes prefer to stop all processes and panic.e. • PPTP .rather specific set of multiprocessing machines that has shared memory.Queueing discipline for Linux network traffic shaping 158 .Ineternet Service Provider • KISS . • OS .Network Address Translation • NFS .Local Descriptor Table • MMU . • NAT .Operating System • PF .Packet Filter. Small • LDT .Programmable Interrupt Controller • PMD . a part of processor that takes care of pagination and segmentation of memory.4. • PGD . i.Interrupt ReQuest • ISP . Linux kills processes using OOM-killer since 2. an engine that evaluates set of rules on each packet it receives and choses either to pass the packet further or to drop or reject it.Out-Of-Memory killer kills a process if OS runs out of memory. • OOM .Page Global Directory.Portable Operating System Interface.Network File System • NUMA .Point-to-Point-Tunneling-Protocol used for creating VPNs • qdisc .Internet Relay Chat • IRQ . access right etc.Internetwork Packet eXchange • IRC .
substitute for rcp implemented in OpenSSH • SFTP .Secure Copy Protocol.Glossary • RAM .Real Time Operating System • RW . an extended HTTP protocol that allows users to collaboratively edit and manage files.Read/Write • SCP . not swapped out.Thread ID • UDP .Web-based Distributed Authoring and Versioning.Virtual File System • VM .Resident Set Size .Processor architecure/family compatible with Intel 8086 processor 159 . multi-processing in which no memory is closer to one processor that to other as in NUMA. • RT .Virtual Memory • VPN . type of physical memory that can be read from and written to.Real Time.A way to call certain function implemented in kernel. • SSH . • TCP .e.e. architecture or machine with only one processor (one processor core) • VFS .Virtual Private Network • WebDAV .User Datagram Protocol • UP . • x86 . i.Transmission Control Protocol • TID .Random Access Memory.The part of the process’ virtual memory that is currently in RAM. • RSS .Uniprocessing. i. computing with dead-line constraints to response • RTOS .Symmetric Multi-Processing. substitute for ftp implemented in OpenSSH • SMP .Secure SHell • syscall .
rôzne zámky. obsluha prerušení. atomické operácie. semafory a iné synchronizačné mechanizmy. rozhranie novej architektúry ovládačov zariadení a alokácia pamäte.Abstract in Slovak Language Práca sa zaoberá vnútorným fungovaním jadra operačného systému Linux verzie 2. 160 . Jadro práce uzatvára popis tvorby jadrových modulov aj s ukážkovým modulom. Veľmi podrobne preskúmaná je aj správa procesov a nový plánovač s dobrou podporou viacprocesorových a NUMA architektúr a preemptívneho prepínania procesov. Snaží sa zdôrazniť rozdiely oproti jadru 2.6.4 a uviesť do problematiky aj človeka znalého iba všeobecných princípov operačných systémov. hlbšie rozobraté sú dôležité stavebné kamene jadra ako napr. Popísaný je prehľad subsystémov jadra. vhodné dátové štruktúry.
This action might not be possible to undo. Are you sure you want to continue? | https://www.scribd.com/doc/61429544/Linux-Kernel-2-6 | CC-MAIN-2015-48 | refinedweb | 48,470 | 70.5 |
Subject: Re: [boost] [config/multiprecision/units/general] Do we have a policy for user-defined-literals?
From: Peter Sommerlad (peter.sommerlad_at_[hidden])
Date: 2013-05-06 06:06:55
Hi,
Vicente made me aware of that post. Since I am guilty, I'd like to answer.
First of all, John Maddock is right in almost everything... my fault.
However, let me defend what's there and confess what shouldn't be there.
As John wrote:
> I've been experimenting with the new C++11 feature "user-defined-literals", and they're pretty impressive ;-)
that's how I started as well....
1. using the parsing version for chrono literals is bullshit, John is right. The standard proposal I submitted does only define the regular numeric literal operators: operator"" h(unsigned long long) and operator"" h(long double), etc.
2. one can use the template version of operator"" for two things:
* parsing integer values in non-standard bases, i.e., ternary
* determining the best fitting type for integral values like the compiler does for integers, this can not be done through the cooked version, because it requires a template parameter for the meta function.
2.a the latter is a reason where it can make sense for a concrete chrono implementation to use the parsing version for the suffixes, since it depends on the implementation which integral range is useful/used for representing the duration (at least in the standard version), where it is open which integral type is used for the representation (i.e. at least 23 bits for hours). But that is really only interesting when you actually use that many hours.
3. the parsing can be "simplified" with using a more complex expression like John proposes, instead of the monstrous template dispatching I implemented. I haven't tested which is faster for which compiler yet and unfortunately doesn't have the time to do so soon. John's version is definitely shorter than the many overloads but requires an additional template parameter, so it is not a direct replacement to my coded version. However, this way it avoids the pow multiplications.
(see also inline below).
So thank you for teaching me something.
Regards
Peter.
On 28.04.2013, at 10:12, John Maddock <john_at_[hidden]> wrote:
>>.
>
> I hadn't seen that before, thanks for the heads up.
>
> If we have UDL utilities in boost then I agree they should have their own top-level namespace in Boost, whether it makes sense to group all literals in there is another matter. My gut feeling is that users will find boost::mylib::literals or boost::mylib::suffixes easier, but I can see how it would make sense for the std to go your way.
>
> BTW, I believe your implementation of parse_int is unnessarily complex, looks like that whole file can be reduced to just:
>
> template <unsigned base, unsigned long long val, char... Digits>
> struct parse_int
> {
> // The default specialization is also the termination condition:
> // it gets invoked only when sizeof...Digits == 0.
> static_assert(base<=16u,"only support up to hexadecimal");
> static constexpr unsigned long long value{ val };
> };
>
> template <unsigned base, unsigned long long val, char c, char... Digits>
> struct parse_int<base, val, c, Digits...>
> {
> static constexpr unsigned long long char_value = (c >= '0' && c <= '9')
> ? c - '0'
> : (c >= 'a' && c <= 'f')
> ? c - 'a'
> : (c >= 'A' && c <= 'F')
> ? c - 'A'
> : 400u;
> static_assert(char_value < base, "Encountered a digit out of range");
> static constexpr unsigned long long value{ parse_int<base, val * base + char_value, Digits...>::value };
> };
>
> Typical usage is:
>
> template <char...PACK>
> constexpr unsigned long long operator "" _b()
> {
> return parse_int<2, 0, PACK...>::value;
> }
>
> constexpr unsigned bt = 1001_b;
>
> static_assert(bt == 9, "");
>
> More than that though: I can't help but feel that base 8, 10 and 16 parsing is much better (faster) handled by the compiler, so parse_int could be reduced to base-2 parsing only which would simplify it still further.
The latter will be standardized to be 0b101010 in C++14. So not many useful things remain, unless you want ternary literals :-)
> What's the rationale for the chrono integer literals parsing the ints themselves rather than using cooked literals?
none. It was a ridiculous experiment by me and I forgot to adapt it back again to the cooked version.
>
> Cheers, John.
>
> _______________________________________________
> Unsubscribe & other changes:
-- Prof. Peter Sommerlad Institut für Software: Bessere Software - Einfach, Schneller! HSR Hochschule für Technik Rapperswil Oberseestr 10, Postfach 1475, CH-8640 Rapperswil tel:+41 55 222 49 84 == mobile:+41 79 432 23 32 fax:+41 55 222 46 29 == mailto:peter.sommerlad_at_[hidden]
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/2013/05/203446.php | CC-MAIN-2021-43 | refinedweb | 777 | 55.54 |
I made standalone executables for Linux and Windows of my Python programs Microbe, Replicator Machine, Neural Construct and Biomorph Entity. These executables were built using cx_Freeze, and have Python and all dependent libraries included, no installation needed.
Some details of the cx_Freeze build follows:
The cx_Freeze utility is similar to py2exe, but can build both Linux and Windows executables. To build the executable from the Python script using cx_Freeze, build options can be entered in a setup.py script, a basic one being:
#setup.py
from cx_Freeze import setup, Executable
setup( name = "Microbe",
version = "1.21",
description = "Microbial Simulation",
executables = [Executable("microbe.py")] )
Then from the command line run:
python setup.py build
There were a few glitches in the build. This was mainly because my Python scripts use the Pygame and NumPy modules. I used Ubuntu Linux 9.10 to build, and tested executables on an Arch Linux virtual machine (VM) installed in VirtualBox with no external Python modules. The build system has Python 2.64(Linux)/2.54(Windows), Pygame 1.81, NumPy 1.30, and used cx_Freeze 4.11 (4.01 appeared to give the same results; latest version had an import error, solved by renaming /cx_Freeze/util to util.so (Linux) or util.pyd (Windows)). I will describe the process with the Microbe build, which requires both Pygame and NumPy. The described process yielded successful builds, and is meant as advice but not necessary the most appropriate solutions for other situations. I first started a build with the basic setup.py script. This should create a build folder with the Python script, Python and all dependencies included, and in this example, the program can be launched on Linux by the command './microbe'. The build ran properly, except there were hidden dependencies still on the build machine that may not be available on another Linux machine. A good way on Linux to check what files are opened when the program is launched is to use from the command line:
top
lsop | grep ID
The top utility shows the ID of running programs, so get the ID of the executable and put it on the lsop line to list all files opened by the executable. Doing this, you can see which are being open through the build package, and those that are being obtained from the system.
To get back to the build, attempt at running the build on the VM got:
File "/usr/lib/python2.6/dist-packages/numpy/lib/polynomial.py", line 11, in
AttributeError: 'module' object has no attribute 'core'
This concerned missing NumPy dependencies libblas.so.3gf/liblapack.so.3gf that were not packaged by cx_Freeze and can be fixed by adding to cx_Freeze setup.py:
includeDependencies =
[("/usr/lib/libblas.so.3gf.0","libblas.so.3gf"),
("/usr/lib/liblapack.so.3gf.0","liblapack.so.3gf")]
These dependencies comprise a Linear Algebra Package (lapack), and are quite a large addition. If NumPy is built from source, without the lapack library installed, it will compile a lite version that would be better to package. On Ubuntu Linux, NumPy depends on the full version of lapack. I do not have a requirement for the full lapack version, and decided to removed NumPy/libatlas3gf-base/libblas3gf; if you do have another program requiring lapack then do not do this or reinstall later. With the removal of NumPy, several other programs dependent on this module may be removed and need to be reinstalled after NumPy is reinstalled. I then compiled NumPy 1.4.0rc1 from source:
sudo apt-get install python-dev
python setup.py build --fcompiler=gnu95
sudo checkinstall python setup.py install
This compilation requires the Python Headers (python-dev) and the gfortran compiler. The install should be to /usr/local/lib/; Ubuntu should have the path in /etc/ld.so.conf, if missing add it then run 'sudo ldconfig'. Checkinstall makes a deb package while installing (during install info is requested - update name: pygame-numpy and version: 1:1.4.0), and inserts it in the package manager, which updates dependencies to the installed version. Since Pygame was removed when I removed NumPy before, I reinstalled that. This allowed a cx_Freeze build of Microbe with NumPy/lapack-lite added using the basic setup.py. The build ran on the system after a required change to my program. Though it was due to an unrelated issue concerning a computer-intensive amoeba animate function that I compiled with Cython, a Python-like to C compiler. The program terminated immediately with 'ValueError: numpy.dtype does not appear to be the correct type object'. It seems that the new version of NumPy had changed numpy.dtype and broke the Cython compiled code. Needed to recompile the animate code to have a separate version that works with the installed NumPy module.
When the new build was run on the VM, the previous error was gone, but another appeared:
File "microbe.py", line 75, in __init__
pygame.error: File is not a Windows BMP file
This concerned the inability to find Pygame dependencies, libjpeg.so.62/libpng12.so.0, due to discrepancies with names between Ubuntu and Arch Linux. I decided to include these in the build using the buildOptions includeDependencies. This can be seen below in the final setup.py used for the cx_Freeze build. I used this to build in Linux and Windows. However, upon exit of the program in Windows, there was an error that the program 'encountered a problem and needs to be close - ModName: python25.dll', and I found that the build did not like the code 'sys.exit', fixed by changing the program to exit by main loop termination. One final note, for some of my other programs such as Biomorph Entity that do not import NumPy, NumPy is still packaged in the build. I believe this is because Pygame is dependent on NumPy for its surfarray module. Since I do not use this module in those programs, I was able to cx_Freeze build with the buildOptions 'excludes = ["numpy"]', and possibly excludes of other unnecessary Python modules can make a lighter executable.
The executables for the Microbe program was built on both Linux and Windows with cx_Freeze by issuing the command 'python setup.py build' from the program folder with the following setup.py:
#setup.py:
from cx_Freeze import setup, Executable
import sys
if sys.platform == "win32":
base = "Win32GUI"
includeDependencies = []
else:
base = None
includeDependencies =
[ ("/usr/lib/libjpeg.so.62.0.0","libjpeg.so.62"),
("/usr/lib/libpng12.so.0.37.0","libpng.so.0") ]
includePersonalFiles =
[ ("data","data"), ("readme.txt","readme.txt") ]
includeFiles = includeDependencies + includePersonalFiles
buildOptions =
dict( include_files = includeFiles,
icon = "microbe.ico",
optimize = 2,
compressed = True )
setup( name = "Microbe",
version = "1.21",
description = "Microbial Simulation",
options = dict(build_exe = buildOptions),
executables = [Executable("microbe.py", base = base)] )
Submitted by Jim on December 23, 2009 at 11:00 pm | https://gatc.ca/2009/12/23/python-program-executables/ | CC-MAIN-2020-24 | refinedweb | 1,139 | 57.47 |
Currently, SPM performs checks to ensure no overlapping source paths exist among all targets in a package. Otherwise, the following error is shown:
error: target 'Foo' has sources overlapping sources:
This makes complete sense, because otherwise it would be very easy to have issues such as duplicated symbols. However, there are some scenarios where having multiple targets with overlapping paths can be desirable, and even required, to support different configurations of the same package:
- a product that has multiple compilation "paths", e.g. same code, compiled with or without a particular flag
- a product made available as variable module configurations: e.g. a single module (
import Foo) vs multiple submodules (
import FooBar,
import FooBaz, ...)
Point 1 as something that can be quite frequent and a legitimate use case. This limitation is mentioned in this discussion, and was partly what sparked the idea for this pitch:
While the above problem is related to conditionally compiling a target to use in a test target, it's easy to see this being an issue for targets exposed to products (e.g. to conditionally compile a feature).
Point 2 can arguably be seen as a bit of an anti-pattern, but it can still make sense on some cases, like libraries that are transitioning from single module to multi-module and want to provide backwards compatibility, or when you simply want to allow multiple setups.
Current workaround
On the above discussion we can find a workaround for this (thanks @NeoNacho
), which is to use a symlink to the overlapped source path, and use that in the target that requires it. While this works perfectly in practice (essentially by tricking SPM to see a different path
), it's a bit "sneaky" and allows for duplicate symbols to happen, precisely what the path exclusivity validations try to prevent.
Proposal
That led me to think that this perhaps deserves a better, more explicit solution. In practice, we could have the best of both worlds and be able to create product/target groups that would be mutually exclusive between themselves (group scope), instead of globally (package scope). Something like:
let package = Package( name: "Foo", products: [ .library( name: "FooSingle", targets: ["Foo"], group: "Single" // <-- group tag ), .library( name: "Foo", targets: ["Bar", "Baz"], group: "Multi" // <-- group tag ), .library( name: "FooSingleFlag", targets: ["FooFlag"], group: "Flag" // <-- group tag ), ], targets: [ .target( name: "Foo", dependencies: [], path: ["Sources"], group: "Single" // <-- group tag ), .target( name: "Bar", dependencies: [], path: ["Sources/Foo"], group: "Multi" // <-- group tag ), .target( name: "Baz", dependencies: [], path: ["Sources/Baz"], group: "Multi" // <-- group tag ), .target( name: "FooFlag", dependencies: [], path: ["Sources"], group: "FooFlag", // <-- group tag swiftSettings: [.define("FLAG")] ), ] )
This new
group key/tag would allow SPM to perform the exact same checks on path exclusivity (now scoped per group), while allowing multiple groups with overlapping paths to co-exist. Users would still be prevented from possibly problematic/invalid configurations by forbidding products/targets imports from different groups simultaneously (e.g. I can't import both
Foo and
FooSingle into another package
Potato). Products from a particular group can only reference targets from the same group, enforcing the same restriction.
Finally it would be a purely additive change, because if we added a new
group: String? parameter as mentioned in the example, the default value could simply be
nil which would be equivalent to the "global" group, while being completely backwards compatible.
Hope this made sense! Thoughts?
| https://forums.swift.org/t/pitch-mutually-exclusive-groups-of-targets/47518 | CC-MAIN-2021-31 | refinedweb | 559 | 51.78 |
API to highlight search results in editor? That will not help you but this line prints the search text
print(v.searchController().searchText())
Have you tried using on_main_thread?
Thanks for the on_main_thread idea - I gave it a go, but the search term didn't change and it just cycled through the old search results.
I'll keep playing with it.
@emkay_online and @JonB Perhaps is it the same limitation as in my topic
@cvp that issue is due to the sandbox security limitations of the uidocumentpicker -- in this case the search bar is hosted by pythonista.
import editor, objc_util @objc_util.on_main_thread def setSearchTerm(txt): t=editor._get_editor_tab() v=t.editorView() v.searchController().searchView().searchBar().text=txt v.searchController().searchBar_textDidChange_(v.searchController().searchView().searchBar(),txt) def highlighNext(): t=editor._get_editor_tab() v=t.editorView() v.highlightNextSearchResult() setSearchTerm('tab')
Setting the searchbar text seems necessary.
@emkay_online @jonb just found this
import editor from objc_util import * t = editor._get_editor_tab() v = t.editorView() v.searchController().searchView().subviews()[0].setText_('test')
My example above used
v.searchController().searchView().searchBar().text=txt
Which is probably more robust than using subviews. Sorry I wasnt clear -- the above example is fully functional. (You need to also call the delegate method for the little arrows to show up)
@JonB That is fantastic. It took a second to realise I needed to open the search bar first, but now it works perfectly.
Thank you
ps. Sorry to only just reply, I wasn't getting alerts on your posts | https://forum.omz-software.com/topic/5236/api-to-highlight-search-results-in-editor/12 | CC-MAIN-2020-29 | refinedweb | 247 | 52.15 |
Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search Coderanch
Advance search
Google search
Register / Login
Pallavi Roy
Ranch Hand
37
15
Threads
0
Cows
since Jun 01, (37/100)
Number Threads Started (37/10)
Number Threads Started (15/10)
Number Likes Received (0/3)
Number Likes Granted (0/3)
Set bumper stickers in profile (0/1)
Set signature in profile
Set a watch on a thread
Save thread as a bookmark
Create a post with an image (0/1)
Recent posts by Pallavi Roy
829 with 100%
Hi,
This is pallavi roy Thanking Senthilkumar Panneer Selvam.
I cleared the exam today and without the link to tkhis post it wouldnt have been possible.
I would also like to thank my husband for coaxing me constantly for the exam and all his support and encouragement.[He even searched topics :-)].
[Passed IBM 829]
I have been working for 3 years on Portals now.Worked mainly on Faces Portlet development and Portal and WSRP framework and Portal Server administration.
The questions i found a few additional topics of interest.
Architecting a Portal Solution
� Develop themes, skins and screens
IBM WebSphere Portal V6 Information Center (Concentrate on custom themes)
Designing and Transforming Content(wp_dev_pdf.pdf).
Their favorites are Theme.policy.
�
Identify portal dependencies on existing software
� Search the IBM Workplace Solutions catalog
What is the purpose of catalog in IBM.
� Size the custom portlets that have to be written
� Use out-of-the-box portlets
Install, Set up and Configure the Development Environment
� Debug a portlet on a local server - sg247501.pdf
I would recommend to go to RAD help contents and read each line on local and remote portlet debugging.I got all my questions from there.
� Diagnose problems with development environment installation
� Identify Software Requirements
If you had done installation of RAD, you would be able to answer. These are pretty simple.
� Optimize development environment
� Understand software prerequisites (including compatibility questions)
Write a portlet
� Ajax basics
[URL=]
� Compile and package a WAR file
� Describe the portlet life cycle
� Develop Portlet applications utilizing Portlet JSR 168 API core objects
� Effectively use JSPs to supply portlet rendering markup
� Effectively utilize portlet configuration and state objects to control portlet behavior
� Effectively utilize portlet modes and states
� Embed references to resources within a portlet
� Implement action processing
� Make effective use of portlet application wizards
� Support multiple locales, clients and devices within a portlet application
� Support multiple markup
� Use APIs to forward and redirect URLs
� Wiring cooperative portlets
� Work with portlet deployment descriptors (caching)
portlet-1_0-fr-spec.pdf � JSR 168 Spec.
I wouldnt like to add more to this.Their favorites are Portlet Context,Portlet Preferences.
Backend Portlet Services Just want to add They love this topic]
I covered each type of Portlet Service all from wp_dev_pdf.pdf.
Trust me the coverage is exhaustive.
1) Content Access Service
2) Credential Vault service.
3) Property Broker Service
4) PUMA Service.
� Configure and access application-specific data sources
� Create a portlet service
IBM WebSphere Portal V6 Information Center
Developing Portlets (wp_dev_pdf.pdf)�
� Implement cooperative portlets
� Use a portlet service
IBM WebSphere Portal V6 Information Center
Developing Portlets (wp_dev_pdf.pdf)
� Use Service Data Objects (SDO) tooling to enable access to remote systems
� Use the credential vault service
IBM WebSphere Portal V6 Information Center
Developing Portlets (wp_dev_pdf.pdf)
Testing and Debugging a Portal Solution
� Debug a portlet on a local server
� Debug a portlet using WebSphere Portal remote - sg247501.pdf
� Set up portlet parameters
� Troubleshoot portlet applications
Go to RAD Help contents and search for error conditions table.And others is how you have been exposed to working with RAD and WPS.
Additional Portlet Concepts
� Implement personalization within portlet application
� Use struts concepts within the portal framework and JavaServer Faces
Though it talks about RAD6, I referred this for struts portlets.
The content provided in wp_dev_pdf is also very good.
� Use the business process engine (bpe) API
IBM WebSphere Portal V6 Information Center
Integrating business processes (wp_admin_pdf.pdf).
Same applies here the better you know process of creating a business proces application.
� Using Content Manager APIs
IBM WebSphere Portal V6 Information Center
Managing Web Content (wp_wcm_pdf.pdf)
� Work with composite applications/templates
Lots of questions on these know how to implement a composite application and its API.
Apart from this:
1) Know the type of portlet preferences provided at portlet mode level.
2) Packaging your components into war file.
3) Accessing your Portlet Service,Credential Vault Service.
4) Try doing an installation of RAD and Portal Server.
5) Know where your log files are updated.
6) JSR-168 specification is required more than 60%
Best of luck to everybody.
Best Regards,
Pallavi
show more
13 years ago
Product and Other Certifications
Good Portal Tutorials from the scratch
Hi Cameron Wallace McKenzie
Why are all the links to portal tutorials down.
Night is the only time i get to study.
My portal certification is knocking at the door.
Please get the site functional.
Your site is the only site with good insight into Portal development.
Best Regards,
Pallavi
show more
13 years ago
Portals and Portlets
Insert Table in JSP page
Hi,
I need ti insert a table in jsp page.
Which does not display data from a database.
It has some controls in the table like radio buttons and command buttons.
Could anybody suggest the best approach.
Best Regards,
Pallavi
show more
14 years ago
HTML Pages with CSS and JavaScript
Has anybody forund an answer-Browser window closing
Hi All,
I have a form where i want this functionality:
A)If the user clicks the browser closing button(X) then he should get a pop up stating that "Do you want to save the changes before closing the window"
B)If the user clicks "yes" on the confirmation Dialog then the window should not get closed but allow him to do some other functionality on the current page.
C)The pop up Diaolg should not appear when the user is navigating to some other page from the current page.
For the above scenario A) and B) using window.onbeforeunload = function(e) is ideal.But the problem is it also pops up when the user is navigating to another page.so scenario C) fails.
I applied another solution for preventing scenario C) taking the IE properties but sceanrio B) fails here the window will definitely get closed :
function unLoadFnc()
{
if(window.screenLeft < 10004)
{
alert("Refresh Coordinate: "+window.screenLeft);
}
else
{
alert("Closing Coordinate: "+window.screenLeft);
dispConfirm();
}
I know it is asking to much in a nut shell.But please respond to this mail if you know any alternative.I would really appreciate any help.
Best Regards,
Pallavi
show more
14 years ago
HTML Pages with CSS and JavaScript
How to access request parameters in Faces Portlets
Hi All,
i have a portlet and i have created a URL mapping.
I am using Websphere Portal Server 5.1 and RAD 6.0.
Where i intend to pass a request parameter as :
And in my Faces Portlet code i want to use the paramter to display the name in scriptlet code.In this way :
<% String userValue = request.getParameter("name"); %>
Hi !! <%= userValue %>
But this doesn't seem to work.
i only get the message :
Hi !! null
What is the reason for the request parameter for not being visible.
Best Regards,
Pallavi
show more
14 years ago
Portals and Portlets
portelt namespace encoding
Hi Geetu,
I hope this caters to your requirement.
But if i have the following components in my portal page then i use the following to retrieve the id.
view<portlet:namespace/>:" + formID+ ":rowValueId"
Best Regards,
Pallavi
show more
14 years ago
Portals and Portlets
How to handle pagination?
Hi ,
Could you tell me your environment.(portal server and technology)
If you are using tomahawk components.Then you could use <t
ataScroller>.
It works wonderfully.
I could help you then.
Best Regards,
Pallavi
show more
14 years ago
Portals and Portlets
PASS SCWCD 85 % today !
Congrats!!!
Harkwork pays.
Best Regards,
Pallavi
show more
14 years ago
Web Component Certification (OCEJWCD)
Cracked SCWCD - score 91%
Congratulations.
You deserve it.
I am sure people are waiting to offer you the new job.
Best Regards,
Pallavi
show more
14 years ago
Web Component Certification (OCEJWCD)
Help needed for SCWCD preparation...
Hello ,
Its not required to have elaborate work experience before you start for SCWCD.What is required is the right material and dedication.
You can do it in 2 months also.Go through the success stories of fellow ranchers on Wall of Fame.
Refer to the SCWCD FAQ you will lots of answers there like mock exam specification etc.
Read Head First properly and make your own notes.This is very much required in remembering all the important points.
And you can get all your unanswered technical queries answered on this forum.
Best of luck.
Best Regards,
Pallavi
show more
14 years ago
Web Component Certification (OCEJWCD)
Coding SuccessServlet
Hello Everybody,
Its good to do things differently.I want to thank you for your wishes.
I am really happy with the innovative response from Satou kurinosuke,
Sayak Banerjee(thanks for the 550/- offer) , Rohitt Vermaa and Sreeraj G H.
Thank you Marc Peabody for giving me a chance to be on the wall of fame.
Best Regards,
Pallavi
show more
14 years ago
Web Component Certification (OCEJWCD)
Coding SuccessServlet
Hi All,
I have written a servlet which tell my journey to SCWCD1.4.
I scored 89%.I have two years of experience in core java development.
But advanced java always fascinated me but my lack of experience hindered
people from offering me j2ee projects.
So i finally decided to crack SCWCD.
import hardwork;
import balanceWorkWithStudies;
(java package imports are mandatory don't skip them)
public class
SuccessServlet
extends HttpServlet {
public void
init()
throws ServletException {
Buy HeadFirst and Hanumanth Deshmukh SCWCD study guide;
Install Tomcat on your system;
Download the jstl,jsp,servlet specification;
Download the j2ee api;
Get a good copy to take down your notes;
Set a target for your self(int time(2-3 hours in a day,7-8 hours on weekends));
}
public void
doPost
(HttpServletResquest req,HttpServletResponse res) throws
ServletException,IOException {
A)Read Head First once and execute the code snippets to understand the code flow and take down you notes properly (Best narrative book ever written)
Now read Hanumanth Deshmukh it gives a right view into specification related details.
B)Give importance to these topics apart from all the objectives on :
(Things lited below are the favourite topics of exam authors)
dynamic attributes,filter mapping,return types of methods(rem getResource()),log and sendError methods,jstl optional attributes(rem scope of attributes),EL expressions,JSP document(rem jsp:root),
'/' plays a vital role when it comes to requestDispatcher,<taglib-location>,welcome-file.
tag files tag,variable,attribute directive and jsp:invoke,jsp
oBody.
<body-content> values usage,
war files,empty operator in EL,<jsp:include> and <%@include%>,how exceptions are handled.
Follow java ranch forum closely you get very important information.
C)20 days before the exam read HeadFirst and SCWCD study kit again.
This time drill all the points in your mind.
Now start the mock exam go for a chapter wise assessment first
(preferable for this are Marcus Green,j2eeCertificate).
Enthuware mock exams or Jdiscuss are from same authors.
Whizlabs questions are also amazing.
(For all those confused which one to buy both get 100% score so you can buy either).Try to score minimum of 80-85% in these exams if its more even better.
}
Download Miklai Zaikin's notes and read it in the last week (what's registered once in your mind is done).
2 days before the exam take up the Head First exam.
Trust me it has the most beautiful questions to tickle your mind.
I scored 68% in this exam. (68+20+1% god's grace=89%).
Your Preparations done now go for it.
}
public void
destroy()
{
Clear the exam and get the score.
Thank god , pat your back.
Thank the authors of HeadFirst and encourage fellow ranchers to go for the exam.
}
}
God Bless you all.
Best Regards,
Pallavi
show more
14 years ago
Web Component Certification (OCEJWCD)
Order of xml elements in the DD
Hi All,
Please let me know if the order of xml elements is fixed in the deployment descriptor.
Best Regards,
Pallavi
show more
14 years ago
Web Component Certification (OCEJWCD)
help me in purchasing online exam
Thank you all of you.
I shall buy Whizlabs.
Sayank would it be a relaible source to buy JWebPlus.
Best Regards,
Pallavi
show more
14 years ago
Web Component Certification (OCEJWCD)
help me in purchasing online exam
Hi All,
This is a question to the people who have answered their exam and have purchased online mock exam.I wanted to know which exam help you better in tackling the real exam.The questions were of the same difficulty level as the real exam.
Whizlabs : 345 questions+150 quiz questions.
Enthuware: 483 questions.
Your suggestions would be really helpful.
Best Regards,
Pallavi
show more
14 years ago
Web Component Certification (OCEJWCD) | https://www.coderanch.com/u/125936/Pallavi-Roy | CC-MAIN-2021-31 | refinedweb | 2,187 | 55.95 |
02 February 2011 06:03 [Source: ICIS news]
SINGAPORE (ICIS)--Nalco’s fourth-quarter net profit jumped 44% year on year to $55.4m (€40m) as sales improved across its three businesses, the ?xml:namespace>
Net sales rose 11% to $1.12bn, led by double-digit sales growths recorded in North America and increase in
“Global upstream markets drove strong energy services sales growth, while in water services, heavy markets grew at twice the global rate of light markets,” it said.
“Paper services sales growth was led by greater than 20% growth in Asia Pacific, followed by high single-digit growth in both Latin and
The company’s full-year 2010 net profit more than tripled to $196.2m, from $60.5m in 2009, while net sales rose 13% to $4.25bn.
"Our strong 2010 sales were driven by a recovery of the global economy and our differential investment in BRIC+ (Brazil, Russia, India and China) growth regions," said Erik Fyrwald, Nalco chairman and CEO.
Nalco said it hopes to deliver a 6-8% growth in organic sales this year, Fyrwald said.
The company said it had an 11% growth in organic sales | http://www.icis.com/Articles/2011/02/02/9431468/us-nalco-q4-net-profit-jumps-44-on-higher-sales.html | CC-MAIN-2014-52 | refinedweb | 193 | 70.33 |
The hotel provides you with big and clean rooms based on which I would have given them a 4 star but the basic facilities are lacking. The WiFi is on an open network with pathetic connectivity... in fact non of my devices were able to connect. The breakfast was ok but below par compared to most other hotels in Wels.. but the biggest issue was the availability of a cloth iron box... the just have one for the entire hotel and you will be lucky to get it.. the hotel staff is helpful though, especially Ricardo who helped track down the only iron box.. such a waste of their time.. hotel is close to wels station and 10 minutes walk to city center.. hope the hotel improves the availability of basic facilities
I stayed her in March 2017 for a business trip. Not my first to Austria, and I know the area well. The hotel is clean and comfortable. A few English TV channels which was great for background noise whilst getting ready and keep up with the news back home. Free wifi which is good and reliable. The breakfast was ok, not as good as some of the others I have had in other hotels though as has less variety. Helpful staff. I didn't eat in the restaurant in the evenings, but heard it was a bit more expensive than going into town. Overall a good experience.
This hotel is attached to the Bayrischer Hof and we have stayed here a number of times when en route to and from our house in Greece. General areas in the hotel are a little tired round the edges and quality of rooms vary, we have stayed in several different ones - some completely refurbished with new bathrooms and some in need of tlc but beds are comfy and rooms always spotlessly clean. Hotel is pet friendly. Be aware the bar and restaurant in the hotel are closed at weekends. Despite our previous visits where we have enjoyed good food and a lovely atmosphere in the bar (which by chance have always been midweek) we were oblivious to this and having driven for some 8 hours were really disappointed to find them closed. There is no room service and the only 'refreshments' we were aware of was a small coffee machine on the reception desk. In need of food and liquid refreshment on recommendation from the reception we found a lovely restaurant about 10 min walk away at the end of the town centre called Gosserbrau - well worth a visit. Quite frustrating when checking out the following morning we discovered there were vending machines in the hotel where we could have got a cold drink, even beer and wine but there had been no mention made of these when we arrived the previous evening. Shame as this last visit has tainted my view on the hotel but despite this we are likely to return (only Monday to Friday tho !!!!) …
Alexandra hotel is a family run small hotel. In my opinion the hotel rooms are very clean. The service is nice and friendly. The one disadventage is that the breakfast is every day the same with a samll range of products. Every time I am in Wels I am the Alexandra guest. Free WiFi.
My wife has just checked in today 27/04/14 and was informed that the restaurant is not open. HOW IS THAT POSSIBLE IN A 4* rated hotel!! The hotel is in a residential area so not really convenient for alternatives. Star ratings are based upon facilities, surely this hotel cannot be rated as such. OH and the prices are very much 4*. Quite frankly not worth it if you wan't basic facilities like FOOD!!
Own or manage this property? Claim your listing for free to respond to reviews, update your profile and much more.Claim Your Listing | https://www.tripadvisor.com/Hotel_Review-g190430-d621014-Reviews-Hotel_Alexandra-Wels_Upper_Austria.html | CC-MAIN-2020-24 | refinedweb | 650 | 72.05 |
NAME
HTML::Mason::Utils - Publicly available functions useful outside of Mason
DESCRIPTION
The functions in this module are useful when you need to interface code you have written with Mason.
FUNCTIONS
- data_cache_namespace ($comp_id)
Given a component id, this method returns its default
Cache::Cachenamespace. This can be useful if you want to access the cached data outside of Mason.
With a single component root, the component id is just the component path. With multiple component roots, the component id is
key/
path, where
keyis the key corresponding to the root that the component falls under.
- cgi_request_args ($cgi, $method)
This function expects to receive a
CGI.pmobject and the request method (GET, POST,. | https://metacpan.org/pod/HTML::Mason::Utils | CC-MAIN-2016-50 | refinedweb | 112 | 55.84 |
If you've ever had to show the density of point features on a map, you may already be familiar with the concept of a heat map, which allows you to generalize the display of points according to their density. A heat map provides an excellent tool for discovering patterns in your data. In addition to looking at density of point location, you can also provide a field in your dataset with which to weight the density. This allows you to look at the density of things like sales (dollars, for example) instead of just the density of customers over an area.
Heat maps are displayed with a color ramp that usually shows dense areas with a darker color (red, for example) and sparse areas with a light color (such as yellow). You may have used a heat map renderer to display your point data in the ArcGIS Online map viewer or ArcGIS Pro. The heat map below shows the density of earthquakes weighted with a field that contains the magnitude.
"Sounds great". You might be saying. "I'm excited to try it in my ArcGIS Runtime for .NET app"!
"Um, yeah. About that." I would say, sheepishly looking at my shoes.
While there is support in ArcGIS Runtime for reading things like a heat map renderer from a web map, there's no API exposed (as of v100.2.1) that allows you to construct one and apply it to a point layer without crafting the raw JSON definition. Fortunately, with a little effort, there's a way to make it much easier to work with.
In a previous blog, I described how to create a serializable class to define labeling properties to apply to a layer. I'll describe the same technique here to define a heat map renderer class that can be serialized to JSON and applied to your point layer. If you don't really care about the details and just want to start using it, you can download the completed class and sample project and give it a try.
- Start Visual Studio and create a new ArcGIS Runtime SDK for .NET app.
- Use the NuGet Package Manager to add the Newtonsoft.Json package to the project.
- Add a new class to the project. Let's name it HeatMapRenderer.cs. Add the following using statements at the top of the class.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Windows.Media;
- Create properties for everything expected in the JSON definition of the heat map renderer class. This information is defined under heatmapRenderer in the Web map specification. The specification defines a "blurRadius" value, for example. This could be implemented with the following simple long property. Note that the name of the property in the class does not need to match the name in the specification.
Based on the specification, here are the properties (and corresponding data type) needed for the heat map renderer class:
public long BlurRadius { get; set; }
- blurRadius (long)
- colorStops (list of objects)
- field (string)
- maxPixelIntensity (double)
- minPixelIntensity (double)
- type (string).
- OK, the list above looks pretty straightforward, except for the property that returns a list of objects. Go ahead and create properties for everything except colorStops (we'll circle back to that one).
- The Type property needs to be set with "heatmap" as the default, as shown here.
public string Type { get; set; } = "heatmap";
- After you've defined the properties, in order to make them serializable you'll need to decorate them with the JsonProperty attribute. The string you supply will be used in the output JSON and must match the name used in the Web map specification. Add the appropriate JsonProperty attribute to all properties, as shown below for the BlurRadius property.
[JsonProperty("blurRadius")]
public long BlurRadius { get; set; }
- The colorStops value is defined with a list of objects. What kind of object do we need here? In the specification, the JSON describes a colorStop class with two properties: color and ratio. You'll therefore need to create a new class with those properties. Let's call the class ColorStop.
public partial class ColorStop
{
[JsonProperty("ratio")]
public double Ratio { get; set; }
[JsonProperty("color")]
public int[] Color { get; set; }
}
- The ratio property is a double. Color is a four value array (R, G, B, A). The constructor for ColorStop will accept a ratio (double) and a Color. The color values are used to set the array.
public ColorStop(double ratio, Color color)
{
Ratio = ratio;
Color = new int[] { color.R, color.G, color.B, color.A };
}
- Return to the HeatMapRenderer class and add a property to hold the color stops. Initialize the property with an empty list of color stops.
[JsonProperty("colorStops")]
public List<ColorStop> ColorStops { get; set; } = new List<ColorStop>();
- Add some helper methods to add or clear color stops in the collection.
public void AddColorStop(double ratio, Color color)
{
if (ratio > 1.0 || ratio < 0.0) { throw new Exception("Argument 'ratio' must be a value between 0 and 1."); };
ColorStop stop = new ColorStop(ratio, color);
ColorStops.Add(stop);
}
public void ClearColorStops()
{
ColorStops.Clear();
}
- Finally, add a ToJson method that returns the JSON representation of the class.
public string ToJson()
{
return JsonConvert.SerializeObject(this);
}
- You should now be able to use the new HeatMapRenderer class to write code like the following to apply a heat map renderer to a point feature layer!
// Create a new HeatMapRenderer with info provided by the user.
HeatMapRenderer heatMapRendererInfo = new HeatMapRenderer
{
BlurRadius = blurRadius,
MinPixelIntensity = minIntensity,
MaxPixelIntensity = maxIntensity
};
// Use a selected field to weight the point density if the user chooses to do so.
if (UseFieldCheckBox.IsChecked == true)
{
heatMapRendererInfo.Field = (FieldComboBox.SelectedValue as Field).Name;
}
// Add the chosen color stops (plus transparent for empty areas).
heatMapRendererInfo.AddColorStop(0.0, Colors.Transparent);
heatMapRendererInfo.AddColorStop(0.10, (Color)StartColorComboBox.SelectedValue);
heatMapRendererInfo.AddColorStop(1.0, (Color)EndColorComboBox.SelectedValue);
// Get the JSON representation of the renderer class.
string heatMapJson = heatMapRendererInfo.ToJson();
// Use the static Renderer.FromJson method to create a new renderer from the JSON string.
var heatMapRenderer = Renderer.FromJson(heatMapJson);
// Apply the renderer to a point layer in the map.
_quakesLayer.Renderer = heatMapRenderer;
I'd agree with you if you think this is a lot of code to write to implement a heat map renderer. But remember, this class can be used in all your ArcGIS Runtime for .NET apps when you want to apply heat map rendering.
Apologies if you were unable to successfully follow the steps above. Fortunately, the attached project contains the HeatMapRenderer class, as well as a WPF app for testing the heat map renderer. | https://community.esri.com/community/developers/native-app-developers/arcgis-runtime-sdk-for-net/blog/2018/03/29/heat-map-renderer-map-it-like-its-hot | CC-MAIN-2019-26 | refinedweb | 1,090 | 57.27 |
I got an email in which the simple concepts of "data manipulation" and "persistence" had become entangled with SQL DML to a degree that the conversation failed to make sense to me.
They had been studying Pandas and had started to realize that the RDBMS and SQL were not an essential feature of all data processing software.
I'll repeat that with some emphasis to show what I found alarming.
They had started to realize that the RDBMS and SQL were not an essential feature of all data processing.Started to realize.
They were so entrenched in RDBMS thinking that the very idea of persistent data outside the RDBMS was novel to them.
They asked me about extending their growing realization to encompass other SQL DML operations: INSERT, UPDATE and DELETE. Clearly, these four verbs were all the data manipulation they could conceive of.
This request meant several things, all of which are unnerving.
- They were sure—absolutely sure—that SQL DML was essential for all persistent data. They couldn't consider read-only data? After all, a tool like Pandas is clearly focused on read-only processing. What part of that was confusing to them?
- They couldn't discuss persistence outside the narrow framework of SQL DML. It appears that they had forgotten about the file system entirely.
- They conflated data manipulation and persistence, seeing them as one thing.
After some back-and-forth it appeared that they were looking for something so strange that I was unable to proceed. We'll turn to this, below.
Persistence and Manipulation
We have lots of persistent data and lots of manipulation. Lots. So many that it's hard to understand what they were asking for.
Here's some places to start looking for hints on persistence.
This list might provide some utterly random hints as to how persistent data is processed outside of the narrow confines of the RDBMS.
For manipulation... Well... Almost the entire Python library is about data manipulation. Everything except itertools is about stateful objects and how to change state ("manipulate the data.")
Since the above lists are random, I asked them for any hint as to what their proper use cases might be. It's very difficult to provide generic hand-waving answers to questions about concepts as fundamental as state and persistence. State and persistence pervade all of data processing. Failure to grasp the idea of persistence outside the database almost seems like a failure to grasp persistence in the first place.
The Crazy Request
Their original request was—to me—incomprehensible. As fair as I can tell, they appeared to want the following.
I'm guessing they were hoping for some kind of matrix showing how DML or CRUD mapped to other non-RDBMS persistence libraries.
So, it would be something like this.
The point here is that data manipulation, state and persistence is intimately tied to the application's requirements and processing.
All of which presumes you are persisting stateful objects. It is entirely possible that you're persisting immutable objects, and state change comes from appending new relationships, not changing any objects.
The SQL reductionist view isn't really all that helpful. Indeed, it appears to have been deeply misleading.
The Log File
Here's an example that seems to completely violate the spirit of their request. This is ordinary processing that doesn't fit the SQL DML mold very well at all.
Let's look at log file processing.
- Logs can be persisted as simple files in simple directories. Compressed archives are even better than simple files.
- For DML, a log file is append-only. There is no insert, update or delete.
- For retrieval, a query-like algorithm can be elegantly simple.
Interestingly, we would probably loose considerable performance if we tried to load a log file into an RDBMS table. Why? The RDBMS file for a table that represents a given log file is much, much larger than the original file. Reading a log file directly involves far fewer physical I/O operations than the table.
Here's something that I can't answer for them without digging into their requirements.
A "filter" could be considered as a DELETE. Or a DELETE can be used to implement a filter. Indeed, the SQL DELETE may work by changing a row's status, meaning the the SQL DELETE operation is actually a filter that rejects deleted records from future queries.
Which is it? Filter or Delete? This little conundrum seems to violate the spirit of their request, also.
Python Code
Here's an example of using persistence to filter the "raw" log files. We keep the relevant events and write these in a more regular, easier-to-parse format. Or, perhaps, we delete the irrelevant records. In this case, we'll use CSV file (with quotes and commas) to speed up future parsing.
We might have something like this:
log_row_pat= re.compile( r'(\d+\.\d+\.\d+\.\d+) (\S+?) (\S+?) (\[[^\]]+?]) ("[^"]*?") (\S+?) (\S+?) ("[^"]*?") ("[^"]*?")' )
def log_reader( row_source ):
for row in row_source:
m= log_row_pat.match( row )
if m is not None:
yield m.groups()
def some_filter( source ):
for row in source:
if some_condition(row):
yield row
with open( subset_file, "w" ) as target:
with open( source_file ) as source:
rdr= log_reader( source )
wtr= csv.writer( target )
wtr.writerows( some_filter( rdr ) )
This is a amazingly fast and very simple. It uses minimal memory and results in a subset file that can be used for further analysis.
Is the filter operation really a DELETE?
This should not be new; it should not even be interesting.
As far as I can tell, they were asking me to show them how is data processing can be done outside a relational database. This seems obvious beyond repeating. Obvious to the point where it's hard to imagine what knowledge gap needs to be filled.
Conclusion
Persistence is not a thing you haphazardly laminate onto an application as an afterthought.
Data Manipulation is not a reductionist thing that has exactly four verbs and no more.
Persistence—like security, auditability, testability, maintainability—and all the quality attributes—is not a checklist item that you install or decline.
Without tangible, specific use cases, it's impossible to engage in general hand-waving about data manipulation and persistence. The answers don't generalize well and depend in a very specific way on the nature of the problem and the use cases. | http://slott-softwarearchitect.blogspot.com/2013/07/nosql-befuddlement-dml-and-persistence.html | CC-MAIN-2017-43 | refinedweb | 1,063 | 57.98 |
PatternNetTransform allows you to create transforms using a simple interface. More...
#include <pattern_net_transform.h>
PatternNetTransform allows you to create transforms using a simple interface.
Simply provide a Pattern NetDef and a Replace NetDef, and this Transform will find subgraphs which fit the pattern net, and replace it with the replace net.
Definition at line 18 of file pattern_net_transform.h.
We want to the final result of subgraph to match the PatternNet in the order of ordered_ops, operator by operator.
[[[ ie. g.node(subgraph[i]) should match p.node(ordered_ops[i]) ]]]
PatternRule for PatternNetTransform does the following:
When trying to insert node idx into subgraph[p_idx], we need to see if the edges between index and the subgraph match the edges between p[ordered_ops[idx]] and p[ordered_ops[0]...ordered_ops[p_idx-1]].
Reimplemented from caffe2::Transform.
Definition at line 91 of file pattern_net_transform.cc.
ReplaceRule for PatternNet Transform does the following:
1) Figure out edge renamings for edges going into/out of the subgraph. That is, for each blob in the pattern graph, what is it called in the matched subgraph?
2) Remove the matched subgraph.
3) Append the replace graph's operators to the graph's operators, and use the renamings to rename the blob names.
4) Create all the children/parent relationships within the replaced graph, and stitch together the inputs and outputs into the rest of the graph, matching the removed subgraph.
Reimplemented from caffe2::Transform.
Definition at line 140 of file pattern_net_transform.cc.
ValidatorRule for PatternNetTransform does the following:
Checks if the size of subgraph and p.size() are the same. That's it!
Reimplemented from caffe2::Transform.
Definition at line 133 of file pattern_net_transform.cc. | https://caffe2.ai/doxygen-c/html/classcaffe2_1_1_pattern_net_transform.html | CC-MAIN-2022-40 | refinedweb | 279 | 50.23 |
While the 2.0 release of the JSF specification will do something about it, the 1.x implementations of JavaServer Faces only offer request, session and application scope. Many JSF implementations have added additional scopes, such as the processScope in ADF Faces and the conversation scope in SEAM. Another frequently desired scope, also somewhere requestScope and sessionScope, could be called pageScope or viewScope. In this article I will describe a very simple implementation of such a scope that I needed for one of the JSF projects I am working on.
The simplified use case is the following: when I navigate to a JSF page (from another page), some fields should be reset. However, any values entered by the user in those fields should be retained as long as the user is staying within the page. As soon as she navigates out of the page, the values should be discarded.
In the situation I had to deal with, the page has a search area. When the page is accessed from somewhere else, the search items should be empty. However, once the user enters search criteria and executes the query, the page returns with the search area and the search results. The search criteria entered earlier and responsible for the search results should be visible, also to allow the user to further refine them.
The items in the search area are bound to a managed bean, obviously. But what should be the scope of this bean? If the bean were requestScope, it would be reset for each request and the search criteria would disappear when the search is performed. On the other hand, with sessionScope, the search criteria would still be there when the user navigates out of the page and sometime later returns to it. So we need a mechanism that would reset the bean as soon as the user navigates out of the page, but not before. For that, I wanted the viewScope (or pageScope).
Implementing ViewScope
The implementation is surprisingly simple – and may not be enough for all situations – yet does what I needed from it.
1. I set up a managed bean called viewScope and configure it to be in sessionScope:
<managed-bean>
<managed-bean-name>viewScope</managed-bean-name>
<managed-bean-class>java.util.HashMap</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
As you can tell from this configuration snippet from the faces-config.xml, the bean is a Map – that will hold any object I put into it.
2. Create page items bound to the viewScope bean
I create a page with the following content:
<h:form>
<h:outputText
<h:panelGrid
<h:outputText
<h:inputText
<h:commandButton
<h:commandButton
</h:panelGrid>
</h:form>
I also create another page with almost identical content:
<h:form>
<h:outputText
<h:panelGrid
<h:outputText
<h:inputText
<h:commandButton
<h:commandButton
</h:panelGrid>
</h:form>
Well, the main difference is the action on the second command button. Basically these two pages both contain a single inputText item, bound to the expression #{viewScope.searchItem}. Two navigation cases have been defined: from the first page to the second (action is other) and from the second to the first (action is search).
When we run the first page,
enter a value in the search item
and press the search button, the page will redisplay and the value entered is still there.
However, when we press the Go Away button, the Other Page is displayed
and we see the value entered on the first page – not good, as we wanted this value to be reset as soon as we navigate out of the page. When we navigate back to the search page, the value is still there, again not the functionality we intended. But of course exactly what we should have expected, given the fact that even though we called the bean viewScope, it is nothing but a session scoped thing.
What we need is a piece of logic that will reset the viewScope bean as soon as we navigate from one page to another. And that is a requirement we can easily address with a PhaseListener.
3. Create class ViewScopeManagerPhaseListener
This class kicks in before RenderResponse is performed. It looks at an entry in the viewScope with key VIEW_BASE. That value indicates the viewId (in other words: the page) for which the current edition of the viewScope was set up. If the viewId that is about to be rendered is a different one, we should reset the viewScope bean and set the VIEW_BASE entry to the viewId of this new page.
package nl.amis.jsf;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
public class ViewScopeManagerPhaseListener implements PhaseListener {
private final static String VIEW_BASE_KEY = "VIEW_BASE";
public ViewScopeManagerPhaseListener() {
}
public PhaseId getPhaseId() {
return PhaseId.RENDER_RESPONSE;
}
public void beforePhase(PhaseEvent e) {
Map viewScope =
(Map)FacesContext.getCurrentInstance().getApplication().createValueBinding("#{viewScope}").getValue(FacesContext.getCurrentInstance());
String currentViewId =
FacesContext.getCurrentInstance().getViewRoot().getViewId();
if (!currentViewId.equals(viewScope.get(VIEW_BASE_KEY))) {
viewScope.clear();
viewScope.put(VIEW_BASE_KEY, currentViewId);
}
}
public void afterPhase(PhaseEvent e) {
}
}
4. Configure class as PhaseListener
In order to ensure that this ViewScopeManagerPhaseListener class will actually be invoked during the JSF life cycle, we have to configure it in the faces-config.xml file as a phaseListener (in JSF 2.0 we would be able to simply use an annotation in the class definition):
<lifecycle>
<phase-listener>nl.amis.jsf.ViewScopeManagerPhaseListener</phase-listener>
</lifecycle>
With this in place, when we next run the application, we get the behavior we want:
< /p>
When we run the first page,
enter a value in the search item
and press the search button, the page will redisplay and the value entered is still there.
Now, when we press the Go Away button, the Other Page is displayed
and
the field has no value. When we press the Go away button to return to the search page, no value is displayed, as is intended.
This implementation is fairly simplistic and I am quite sure there are many situations where it is not good enough. For example, in ADF Faces, opening a dialog window – perhaps an LOV – will reset the viewScope, what is probably not what you would want. So more logic is needed in the ViewScopeManagerPhaseListener class. | https://technology.amis.nl/it/easy-implementation-of-viewscope-or-pagescope-in-javaserver-faces-jsf-1x/ | CC-MAIN-2022-27 | refinedweb | 1,049 | 53.51 |
Hancitor Loader
Hancitor in a Nutshell
Hancitor is a famous malware loader that has been in use for years since first being observed in 2015. A malware loader is the software which drops the actual malicious content on the system then executes the first stage of the attack. Hancitor has been the attacker’s loader of choice to deliver malwares like: FickerStealer, Sendsafe, and Cobalt Strike if the victim characteristics are met. In recent months, more threat intelligence has been gathered to confirm the selection of Hancitor by Cuba Ransomware gangs as well [1]. The popularity of Hancitor among threat actors is considered to last for a while. Therefore, it’s crucial to assure your organization’s safety from this emerging threat.
Hancitor Infection Vector
Hancitor DLL is embedded within malicious documents delivered by phishing e-mails . The method that the malicious document uses to achieve execution is usually a VBA macro that is executed when the document is opened. Being dropped by the doc file, the initial packed DLL is an intermediate stage responsible for unpacking and exposing the true functionality of Hancitor. Based on the collected information about the victim host, it will decide which malware to deploy. Hancitor will then proceed to perform the loading functionality in order to infect the system with the actual malicious content.
Technical Summary
- Configuration Extraction: Hancitor comes with embedded RC4 encrypted configuration with hard-coded key. It uses the Microsoft Windows
CryptoAPIto do the decryption. These configuration contains the C2 which it will communicate with for further commands.
- Host Profiling: Hancitor will gather information about the host in order to decide which malicious payload will be downloaded as well as to generate a unique victim ID. For instance, if the host is connected to an active directory domain, Cobalt Strike conditions are met. Collected information contains: OS version, IP address, Domains trusts, Computer name & username.
- C2 Communication: The victim profile will be forwarded to the C2 to decide further orders. The returned C2 command is base64 encoded with additional layer of single-byte XOR encryption. The command defines a set of 5 available loading techniques to be performed + a new URL to download the additional malware to be loaded and executed.
- Payload Download: There are a lot of options to be selected. For example, Hancitor can download fully grown malicious EXE or DLL files, or even tightly crafted shellcodes. There is high degree of flexibility here that can serve a lot of threat actors which makes Hancitor a great choice.
- Malicious Code Execution: Whether it’s process injection or simply to drop on disk and execute the malware, Hancitor is capable of performing the complex operation to ensure running that the malicious code on the victim’s machine.
Technical Analysis
First look & Unpacking
Catching the initial dropped DLL by the malicious document and inspecting it, it is first seen at 2021-08-26 14:38:31 UTC according to VirusTotal. At the given date, the file sample was flagged as malicious by only 6 security vendors.
To unpack the dropped DLL, we use X64dbg to set a breakpoint on
VirtualAlloc API. After writing new data into the allocated memory space, we set a hardware breakpoint on execution there. We continue single stepping into the rest of the unpacking stub to assure the building of the import table. Then, we can spot a successfully unpacked PE header as well as many resolved strings in the newly allocated memory space. Finally, we dump the memory section into disk.
Host Profiling
Using IDA Pro we can see that unpacked Hancitor DLL has two exports which lead to the same function. From there our static code analysis will begin. The malware functionality begins with host profiling. Collected information contains: OS version, Victim’s IP address, Domains names & DNS names, Computer name, username, and whether the machine is x64 or x86.
It creates a unique ID for the victim using its MAC addresses of all the connected adapters XORed with the Windows directory volume serial number.
Then, it concatenates the final string which will hold the collected host information to be sent to the C&C server. The call to
mw_wrap_config_decryption routine will be discussed in details in a few lines. It’s used to extract the embedded configuration which will also be used in the final host profile. Something that can be very useful while YARA rules is the format string
{"GUID=%I64u&BUILD=%s&INFO=%s&EXT=%s&IP=%s&TYPE=1&WIN=%d.%d"} which makes a good indicator for Hancitor . These collected characteristics about the infected host will decide which malware will be deployed. For instance, if the host is connected to an active directory domain, Cobalt Strike malware will be downloaded and executed.
Configuration Extraction
But before finishing the host profile, the malware decrypts the embedded configuration in order to send a copy to the C&C server. The decryption routine references two global data variables very close the beginning of the .data section. From the way the parameters are arranged for the decryption routine, I’ve concluded that the 8 bytes beginning at
0x5A5010 are the decryption key followed by the encrypted configuration.
Hancitor comes with embedded RC4 encrypted configuration with hard-coded key. It uses the Microsoft Windows
CryptoAPIto do the decryption. First, the key will be SHA-1 hashed before attempting the decryption. Then only the first 5 bytes of the hashed key will be used to decrypt the encrypted data.
The upper 16 bits of the 4th parameter denotes the size of the RC4 decryption key. Here it’s
0x280011 = 0000000000101000 -- 0000000000010001
in which
101000 = 40 bits or 5 bytes.
We can use CyberChef to simulate the decryption process statically. First, the 8 bytes key
{f0da08fe225d0a8f} will be
SHA-1 hashed = {67f6c6259f8f4ef06797bbd25edc128fd64e6ad7}. Then, the first 5 bytes of the key will be used as the final RC4 decryption key for decrypting the configuration data. These configuration contains the C2 which it will communicate with for further commands based on the collected host profile. Here at the bottom right corner, we can see that the malware comes with 3 C&C servers to try to connect with. At the end of this report, we will use another way to automatically extract the embedded configuration using Python.
C&C Communication
Hancitor extracts the C2 URLs and initializes the connection with the remote end using the high level
Wininet.dll library APIs. It uses the following hard-coded User-Agent
{"Mozilla/5.0 (Windows NT 6.1; Win64; x64; Trident/7.0; rv:11.0) like Gecko"} which is very common.
First, the collected host profile is sent using HTTP POST request. Secondly, it accepts the matched C2 command based on the gathered information about the victim. The received C2 command is base64 encoded and XOR encrypted with a single-byte key
0x7A. The malware performs the necessary decoding before interpreting the command.
The command consists of 4 parts:
- A character from the set
{'b','e','l','n','r'}to specify what action to be performed.
- The colon character
:as delimiter.
- URL of the malicious content to be downloaded.
- The bar character
|as delimiter.
# i.e decoded command X:
Executing C2 Commands
After retrieving the C2 command and performing the appropriate decoding, the command is validated and then passed to the routing in which it will download and execute the malicious content. The malicious content will be downloaded using the URL at offset 3 from the beginning of the C2 string. Then, based on the first character of the C2 command, one of the switch case branches will be executed.
There are 5 available options or executions paths. Excluding the
n command because it simply acts as a
NOP operation, so we have 4 valid options.
The ‘b’ Command
This execution branch will perform a process injection in a newly created
svchost.exeprocess with
CREATE_SUSPENDED flag. The injected malicious code is first checked to be a valid PE file -DLL or EXE- in order to be injected. For the new suspended
svchost.exe process, the injection is done in a classic way using the APIs:
VirtualAllocEx and
WriteProcessMemory. What is more interesting here is the way the malware sets the new Entry point for the malicious code.
It changes the value of the
EAX register and sets the new thread context overwriting the old one. The
EAX register in a newly created thread will always point to the OEP. This effectively transfers the entry point of the newly created
svchost.exe process to the start of the injected malicious binary.
The ‘e’ Command
The difference between this execution branch and the previous one is that this performs execution of the malicious binary inside the currently running process without touching
svchost.exe. First, Hancitor will perform PE header parsing to find the
ImageBase and
AddressOfEntryPoint fields.
Then, it will proceed to build the import table which will be used by the injected binary. It uses
LoadLibraryAand
GetProcAddress to do the job. That’s because the newly created thread will crash if it’s found to have dependencies problems. At last, based on function flags, the malware will decide to launch the newly downloaded malicious in a new separate thread or simply just to call it as a function.
The ‘l’ Command
Here the malware doesn’t check for valid PE file because it’s supposed to inject a shellcode. Based on the function’s flags, Hancitor will decide which to inject a newly created
svchost.exe or to call the malicious shellcode as a function in the currently running process.
The malware doesn’t need to resume the suspended process because its only suspends the main thread. The malware is creating another thread within
svchost.exe to execute the malicious shellcode.
The ‘r’ Command
This execution path is the only one that actually drops files on the disk. Hancitor will drop the newly downloaded malicious binary in the
%TEMP% directory with a random name beginning with the “BN” prefix. Then, if it’s an EXE file, it will simply execute it in a new process. If it’s a DLL file, it will use
run32dll.exeto execute the malicious DLL.
Conclusion
Hancitor is considered a straightforward loader but very efficient at the same time. So far, Hancitor has targeted companies of all sizes and in a wide variety of industries and countries to deploy very serious malwares like FickerStealer, Sendsafe, and Cobalt Strike or even Cuba Ransomware. It’s a must to take the appropriate countermeasures to defend your organization from such dreadful threat. We can’t be sure which threat actors will also use Hancitor as their loader in the future. Yet, one thing is sure: as effective as it has been to date, the threat posed by Hancitor will not fade away in the coming future.
IoCs
YARA Rule
rule hancitor : loader { meta: description = "This is a noob rule for detecting unpacked Hancitor DLL" author = "Nidal Fikri @cyber_anubis" strings: $mz = {4D 5A} //PE File $s1 = "" ascii fullword $s2 = /GUID=%I64u&BUILD=%s&INFO=%s(&EXT=%s)?&IP=%s&TYPE=1&WIN=%d\.%d\(x64\)/ ascii fullword $s3 = /GUID=%I64u&BUILD=%s&INFO=%s(&EXT=%s)?&IP=%s&TYPE=1&WIN=%d\.%d\(x32\)/ ascii fullword $s4 = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; Trident/7.0; rv:11.0) like Gecko" ascii fullword condition: (filesize < 500KB) and ($mz at 0) and (3 of ($s*)) }
Python Automated Configuration Extraction
This python script is used to automatically extract the configuration of the Hancitor malware. Steps required are as follows:
- Open the binary file.
- Get the .data section.
- Extract the the key and the encrypted configuration data at offset 16.
- SHA-1 hash the extracted key to get the final key.
- Use the key to decrypt the configurations.
import pefile #To manipulate PE files import hashlib #To perform the SHA-1 hashing import binascii #To perfrom unhexing import arc4 #To perform the RC4 decryption #This functions creates a PE object. Then iterates over the sections to locate #the .data section in order to return its content def Get_Date_Section(file): pe_file = pefile.PE(file) for section in pe_file.sections: if b".data" in section.Name: return section.get_data() def rc4_decryption(key, encrypted_data): cipher = arc4.ARC4(key) decrypted_content = cipher.decrypt(encrypted_data) extracted_config = decrypted_content[:200] print(extracted_config.decode('utf-8')) #Prints in Unicode def main(): file_path = input("Pls enter the file path: ") data_section = Get_Date_Section(file_path) #The config data begins at offset 16 inside the .data section full_configuration = data_section[16:] #The key is the first 8 bytes while the encrypted data is the rest key = full_configuration[0:8] data = full_configuration[8:] #The RC4 key is only the first 5 bytes = 10 hex digits hashed_key = hashlib.sha1(key).hexdigest() rc4_key = hashed_key[0:10] rc4_decryption(binascii.unhexlify(rc4_key),data) if __name__ == '__main__': main() | https://cyber-anubis.github.io/malware%20analysis/hancitor/ | CC-MAIN-2022-05 | refinedweb | 2,137 | 56.25 |
- Interfaces
- Object Cloning
- Inner Classes
- Proxies
Object Cloning
When you make a copy of a variable, the original and the copy are references to the same object. (See Figure 61.) This means a change to either variable also affects the other.
Figure
61: Copying and cloning
Employee original = new Employee("John Public", 50000); Employee copy = original; copy.raiseSalary(10); // oops--also changed original
If you would like copy to be a new object that begins its life being identical to original but whose state can diverge over time, then you use the clone() method.
Employee copy = (Employee)original.clone(); // must castclone returns an Object copy.raiseSalary(10); // OK-original unchanged
But it isn't quite so simple. The clone method is a protected method of Object, which means that your code cannot simply call it. Only the Employee class can clone Employee objects. There is a reason for this restriction. Think about the way in which the Object class can implement clone. It knows nothing about the object at all, so it can make only a field-by-field copy..
To visualize that phenomenon, let's consider the Employee class that was introduced in Chapter 4. Figure 62 shows what happens when you use the clone method of the Object class to clone such an Employee object. As you can see, the default cloning operation is "shallow"it doesn't clone objects that are referenced inside other objects.
Figure
62: A shallow copy
Does it matter if the copy is shallow? It depends. If the subobject that is shared between the original and the shallow clone is immutable, then the sharing is safe. This happens in two situations. The subobject may belong to an immutable class, such as String. Alternatively, the subobject may simply remain constant throughout the lifetime of the object, with no mutators touching it and no methods yielding a reference to it.
Quite frequently, however, subobjects are mutable, and you must redefine the clone method to make a deep copy that clones the subobjects as well. In our example, the hireDay field is a Date, which is mutable.
For every class, you need to decide whether or not
The default clone method is good enough;
The default clone method can be patched up by calling clone on the mutable subobjects;
clone should not be attempted.
The third option is actually the default. To choose either the first or the second option, a class must
Implement the Cloneable interface, and
Redefine the clone method with the public access modifier.
NOTE
The clone method is declared protected in the Object class so that your code can't simply call anObject.clone(). But aren't protected methods accessible from any subclass, and isn't every class a subclass of Object? Fortunately, the rules for protected access are more subtle (see Chapter 5). A subclass can call a protected clone method only to clone its own objects. You must redefine clone to be public to allow objects to be cloned by any method.
In this case, the appearance of the Cloneable interface has nothing to do with the normal use of interfaces. In particular, it does not specify the clone methodthat method is inherited from the Object class. The interface merely serves as a tag, indicating that the class designer understands the cloning process. Objects are so paranoid about cloning that they generate a checked exception if an object requests cloning but does not implement that interface.
NOTE
The Cloneable interface is one of a handful of tagging interfaces that Java provides. Recall that the usual purpose of an interface such as Comparable is to ensure that a class implements a particular method or set of methods. A tagging interface has no methods; its only purpose is to allow the use of instanceof in a type inquiry:
if (obj instanceof Cloneable) . . .
Even if the default (shallow copy) implementation of clone is adequate, you still need to implement the Cloneable interface, redefine clone to be public, call super.clone() and catch the CloneNotSupportedException. Here is an example:
class Employee implements Cloneable { public Object clone() // raise visibility level to public { try { return super.clone(); } catch (CloneNotSupportedException e) { return null; } // this won't happen, since we are Cloneable } . . . }
The clone method of the Object class threatens to throw a CloneNotSupportedExceptionit does that whenever clone is invoked on an object whose class does not implement the Cloneable interface. Of course, the Employee class implements the Cloneable interface, so the exception won't be thrown. However, the compiler does not know that. Therefore, you still need to catch the exception and return a dummy value.
The clone method that you just saw adds no functionality to the shallow copy provided by Object.clone. It merely makes the method public. To make a deep copy, you have to work harder and clone the mutable instance fields.
Here is an example of a clone method that creates a deep copy:
class Employee implements Cloneable { . . . public Object clone() { try { // call Object.clone() Employee cloned = (Employee)super.clone(); // clone mutable fields cloned.hireDay = (Date)hireDay.clone() return cloned; } catch (CloneNotSupportedException e) { return null; } } }
NOTE
Users of your clone method still have to cast the result. The clone method always has return type Object.
As you can see, cloning is a subtle business, and it makes sense that it is defined as protected in the Object class. (See Chapter 12 for an elegant method for cloning objects, using the object serialization feature of Java.)
NOTE
When you define a public clone method, you have lost a safety mechanism. Your clone method is inherited by the subclasses, whether or not it makes sense for them. For example, once you have defined the clone method for the Employee class, anyone can also clone Manager objects. Can the Employee clone method do the job? It depends on the fields of the Manager class. In our case, there is no problem because the bonus field has primitive type. But in general, you need to make sure to check the clone method of any class that you extend.
The program in Example 63 clones an Employee object, then invokes two mutators. The raiseSalary method changes the value of the salary field, while the setHireDay method changes the state of the hireDay field. Neither mutation affects the original object because clone has been defined to make a deep copy.
Example 63: CloneTest.java
1. import java.util.*; 2. 3. public class CloneTest 4. { 5. public static void main(String[] args) 6. { 7. Employee original = new Employee("John Q. Public", 50000); 8. original.setHireDay(2000, 1, 1); 9. Employee copy = (Employee)original.clone(); 10. copy.raiseSalary(10); 11. copy.setHireDay(2002, 12, 31); 12. System.out.println("original=" + original); 13. System.out.println("copy=" + copy); 14. } 15. } 16. 17. class Employee implements Cloneable 18. { 19. public Employee(String n, double s) 20. { 21. name = n; 22. salary = s; 23. } 24. 25. public Object clone() 26. { 27. try 28. { 29. // call Object.clone() 30. Employee cloned = (Employee)super.clone(); 31. 32. // clone mutable fields 33. cloned.hireDay = (Date)hireDay.clone(); 34. 35. return cloned; 36. } 37. catch (CloneNotSupportedException e) { return null; } 38. } 39. 40. /** 41. Set the pay day to a given date 42. @param year the year of the pay day 43. @param month the month of the pay day 44. @param day the day of the pay day 45. */ 46. public void setHireDay(int year, int month, int day) 47. { 48. hireDay = new GregorianCalendar(year, 49. month - 1, day).getTime(); 50. } 51. 52. public void raiseSalary(double byPercent) 53. { 54. double raise = salary * byPercent / 100; 55. salary += raise; 56. } 57. 58. public String toString() 59. { 60. return "Employee[name=" + name 61. + ",salary=" + salary 62. + ",hireDay=" + hireDay 63. + "]"; 64. } 65. 66. private String name; 67. private double salary; 68. private Date hireDay; 69. } | http://www.informit.com/articles/article.aspx?p=31110&seqNum=2 | CC-MAIN-2017-43 | refinedweb | 1,305 | 67.65 |
20 February 2012 11:10 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The company had originally planned to increase its plant operating rates to 100% at the end of last week but this changed when the production team recalculated the plant’s margins, the source added.
The producer restarted the unit on 11 February after shutting it on 24 January to control rising inventory, the source said.
Nan Ya Plastics took its 40,000 tonne/year No 1 BDO plant, which is located at the same site, off line on 20 January for the same reason. The producer plans to keep this plant shut for an indefinite period, | http://www.icis.com/Articles/2012/02/20/9533727/taiwans-nan-ya-plastics-to-run-no-2-bdo-at-50-indefinitely.html | CC-MAIN-2014-41 | refinedweb | 108 | 59.23 |
Facebook Graph API & OAuth 2.0 & Flash (update)
As previously mentioned, facebook released a new Graph API. It is based on OAuth 2.0 protocol (old authorization token also works). While it is fresh thing, there is no much ActionScript stuff around, so I came with FacebookOAuthGraph class. This class is meant to be used as an abstract class, while it contains just the basic authentication algorithm and call method to request data. It stores access token in SharedObject, so next time you came into app, you get connected on background without noticing (no popup etc.). Your token should expire in 24 hours.
Here is the code for the following flex app, to make it work, get latest FacebookOAuthGraph and FacebookOAuthGraphEvent classes.
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns: <mx:Script> <![CDATA[ import sk.yoz.events.FacebookOAuthGraphEvent; import sk.yoz.net.FacebookOAuthGraph; // facebook Application ID private var clientId: <mx:Text </mx:HBox> <mx:HBox <mx:Text <mx:TextInput <mx:Button </mx:HBox> <mx:HBox> <mx:TextInput <mx:Button <mx:Spacer <mx:TextInput <mx:Button </mx:HBox> <mx:HBox> <mx:TextInput <mx:Button </mx:HBox> <mx:HDividedBox <mx:TextArea <mx:TextArea <mx:Image </mx:HDividedBox> </mx:Application>
Make sure your html wrapper defines correct allowScriptAccess and both id and name for <object> tag. This enables ExternalInterface.objectID. With swfobject use:
var params = { allowScriptAccess: "sameDomain" }; var attributes = { id: "FacebookOAuthGraphTest", name: "FacebookOAuthGraphTest" }; swfobject.embedSWF("FacebookOAuthGraphTest.swf", "alternative", "100%", "100%", "10.0.0", "expressInstall.swf", flashvars, params, attributes);
callback.html pushes url hash into flash app. When running this application from desktop (creating/debugging), your callback.html located on public domain has no access to its opener (different domain – XSS), so you need to pass access_token manualy into <TextInput id=”hash”>, but once your flash application is on the same domain with callback, it works automaticaly.
callback.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ""> <html xmlns="" xml: <head> <script type="text/javascript"> <!-- if(window.opener && window.opener.confirmFacebookConnection) { window.opener.confirmFacebookConnection(window.location.hash); self.close(); } //--> </script> </head> <body> <p>You may now close this window.</p> </body> </html>
Click connect and allow facebook application. Facebook redirects to callback.html that pastes hash into flash and closes popup. Now you are authenticated. Next time you visit this flash application (refresh this page) you will get authenticated in background (if your access token is still valid). Notice, some graph api calls returns JSON objects (me), other may return binary data (me/picture). For now it may take some time to finish calls (5 second or more), but I hope facebook will soon make it fast.
You get your JSON decoded data via event.data. Just make sure you do not try to decode ByteArray (eg. me/picture)
// call("me") private function callComplete(event:FacebookOAuthGraphEvent):void { trace(event.data.name); }
Some calls to test:
Friends: me/friends News feed: me/home Profile feed (Wall): me/feed Likes: me/likes Movies: me/movies Books: me/books Notes: me/notes Photos: me/photos Videos: me/videos Events: me/events Groups: me/groups
Additional information about my facebook app (see all settings):
Application ID: 268718683475 App Domain: yoz.sk Website / Site URL: App on FB / Canvas URL: Page Tab / Page Tab URL:? Canvas type: iframe Developer Mode: Off App Type: Native/Desktop Sandbox Mode: Disabled Remove Deprecated APIs: Enabled signed_request for Canvas: Enabled Timezone-less events: Enabled Encrypted Access Token: Enabled ...other Migrations: Disabled
Based on facebook access token, it should be valid approximately for 24 hours. Notice the bold part, works as expiration time (unix time format). Use FacebookOAuthGraph.tokenToExpiration() to parse Date:
access_token=268718683475%7C2.w3fjqz80Xi1CdBXt7Ygh6A__.86400.1273158000-1215645368%7CDGv2l2HtTymd6cM6Fy_8k6P_8CQ.
Important update: May 19, 2010: Application is working again. Due to massive support in bug tracker (thanks all for your votes), facebook devs changed secured crossdomain.xml, so it allows unsecured requests. changeStatus() method added into example and some minor changes in FacebookOAuthGraph class (please update).
Here is what happend and why this app was not working for a while:
- May 11, 2010: facebook changed rules, so requests on unsecured graph service (via…) were limited to just those without access_token parameter. Requets to secured service () resulted in security violation due to missing secure=”false” parameter in crossdomain.xml
- May 12, 2010: bug submitted
- May 12, 2010 – May 14, 2010: massive bug voting
- May 14, 2010: Bug confirmed by facebook dev team
- May 19, 2010: Bug fixed, crossdomain file changed
I am glad that facebook devs listens and care.
Is there a .fla version available?
Yes, there is a simple working Flash CS4 archive available for download (.fla + all sources). The demo connects the facebook application and once connected, it uploads generated picture into photo album.
How can I use this class in my iframe canvas page?
Please read article Authorizing Iframe Facebook Applications For Graph API
How can I make this class do more advanced things and what are the best practices?
Please read article Extending FacebookOAuthGraph Class, where all the most comon extendings are described.
When I connect with this app in one browser (firefox), and I run another browser (chrome) I get automatically connected. Why?
Your authorization token is stored in SharedObject, that is OS-user persistent (eg. windows user). No matter what browser you run, all of those reads data from one SharedObject. If you need cookie or session persistent authorization, please extend my class and override methods that use SharedObject.
How to add request parameters into my call?
Pass URLVariables object as a second parameter to call() method:
// eg. in order to make this call "me/picture?type=large", do the following: var data:URLVariables = new URLVariables(); data.type = "large" call("me/picture", data);
Why I can not access me/photos?
Facebook has changed rules again. You also need “user_photo_video_tags” permission within your app. I have already added it into my app, so please remove your browser cache, refresh and click connect button again (even if you are connected already). Now it should work.
How to upload photo with graph api?
This is a piece of working code from Sean, thnx Sean:
//("message", message); mpLoader.addFile(ba, "image.jpg", "image"); loaderAddListeners(mpLoader.loader); mpLoader.load(apiSecuredPath + "/me/photos?access_token="+ token); return mpLoader; }
Can I make fql calls with this class?
However graph api does not implement fql calls, you can make fql calls using this class. The resulted data are not JSON but XML:
var data:URLVariables = new URLVariables(); data.query = "SELECT uid, name FROM user WHERE uid = XXX"; // insert your uid var loader:URLLoader = facebook.call("method/fql.query", data, URLRequestMethod.POST, null, ""); loader.addEventListener(FacebookOAuthGraphEvent.DATA, fqlComplete); private function fqlComplete(event:FacebookOAuthGraphEvent):void{ var xml:XML = new XML(event.rawData);
For fqlComplete method, please read Parsing FQL result article.
Can I post feeds with attachments?
Graph API has not documented attachment functionality for feeds, anyway, you can publish streams with attachments with this class as simple as:
var media:Object = {}; media.type = "flash"; media.swfsrc = ""; media.imgsrc = ""; media.width = "80"; media.height = "80"; media.expanded_width = "120"; media.expanded_height = "120"; var attachment:Object = {}; attachment.name = "test name"; attachment.href = "" attachment.description = "test description"; attachment.caption = "test caption"; attachment.media = [media]; var data:URLVariables = new URLVariables(); data.message = "test message"; data.attachment = JSON.encode(attachment); facebook.call("method/stream.publish", data, URLRequestMethod.POST, null, "");
How can I develop my app locally when callback only works on the domain?
While callback is not able to push access_token into your app on runtime, I just copy access_token value into my code and publish again:
if(!parameters.session) parameters.session = JSON.encode({ access_token:String("123864964303507%7C2._pSS7WlemeGB9M0RV8Vnuw__.3600.1276246800-1215645368%7C-kYjWPx4MR6DXc5Clcnv5kXX3t4.") .replace(/\%7C/g, "|") }); facebook.autoConnect(parameters);
Hi Is there a way to implement a “i Like” button with your class?
Sorry,.
This example app works with Internet Explorer, but my one results in Error #2032
Please complie your app to Flash Player 10 (or later). It should fix this issue. Credits goes to Garcimore :-), thnx. The issue has been identified as header Content-Type: application/json, that is returned from facebook. Suggested workaround (by facebook dev team) is to use POST variables with your requests, however it is reported as not working solution.
I can not make it run in my Mac-Safari sonfiguration
It seems there is a bug in Safari on Mac that does not let you open popup via ExternalInterface. You should use navigateToURL() in that case. Credits goes to Beans, thank you. More instructions here.
var js:String = "return window.navigator.userAgent.indexOf('Safari') > -1);" if(ExternalInterface.call("function(){" + js + "}")){ // safari specific code
[...] (May 5, 2010): I have created Facebook Graph API & OAuth 2.0 & Flash – FacebookOAuthGraph ActionScript 3 class to use with OAuth 2.0 and [...]
When I tried the demo app on this page…
Error #2044: Unhandled IOErrorEvent:. text=Error #2124: Loaded file is an unknown type.
I got this when I tried a ‘me/feed’, ‘me/friends’ etc.
Is this normal? Am I doing something wrong?
Hi Kevin,
it should work ok, I have just tested it on 2 accounts. It may be required to grant more extended permissions (via scope = “publish_stream,user_photos,…”), but in this case it should work without change. Interesting, every URLLoader from FacebookOAuthGraph.call() method handles its IOErrorEvent, so I guess the error message is not from this application, and it may have been caused by drawing application on the top of this blog.
please try again and let me know
hi,
really thank you for the source!!
but i got an issue that i can resolve:
whan facebook call my callback.html (that is the same as your), i receive an error from firebug “flash.confirmFacebookConnection is not a function”. but “externalinterface.addcallback” is in your class…
i use the same technique as your to embed flash in html. and i’ve added Security.allowDomain(“…mydomain…”); to ensure privacy policy…
<!–
NO FLASH PLUGIN
<!–
i don’t know…
argh it didin’t wrote my embed code, but i don’t think is so useful
Hi Maz,
make sure you set both “id” and “name” for flash object in html, that enables your ExternalInterface access objectID.
var attributes = {
id: “FacebookOAuthGraphTest”,
name: “FacebookOAuthGraphTest”
};
swfobject.embedSWF(“FacebookOAuthGraphTest.swf”, “alternative” , “100%”, “100%”, “10.0.0″,
“expressInstall.swf”, flashvars, params, attributes);
hi jozef!
yes, i did it…
“……..
…….”
testing on latest firefox on osx.
however you’re test app doesen’t work on my safari and chrome! could be a popup blockin’ problem?
yes it could be popup blocker, I am unable to handle blockers
… thinking about something like:
Kevin here again…
Thank you sooooooo much for making these classes available. I converted your Flex app into regular ol’ Flash and it worked without a hitch. The authentication is totally smooth and the code was concise and easy to understand. I was a little out of my depth there, trying to figure OAuth2.0 out myself, so you saved my ass. Big thanks!
thanks Kevin, glad to hear that
ok it works, thank you
the problem was a strange bug between externalinterface.callback and firefox on mac!
i resolved this bug making a callback to flash functions after a timetout!
now i got a new question, do you ever tried to publish something to the feed of the user with your classFacebookOAuthGraph ? i’m triyng without results…
thank you again !!
I’m facing the same problem as Kevin. I’m able to connect but when I enter ‘me/photos’ I get the following error…
Error #2044: Unhandled IOErrorEvent:. text=Error #2124: Loaded file is an unknown type.
I want to display a list of logged in user’s albums and corresponding photos. Plz help how shall I go about it.
Hi gurpreet,
finally I managed to reproduce your error. I put me/photos request into right text input that expects image bytes on return… FAIL
I created two text inputs there in my example. One is to return JSON string data the other to return binary data. The most of the calls return JSON (me, me/photos), but there are also some that returns binary data – e.g. bytes of profile picture (me/picture). In your case (me/photos) you expect JSON data (some list of urls and other stuff), please insert your request into left input field and click left call button.
In order to get logged users you have to use fql like:
SELECT uid, name, pic_small FROM user WHERE online_presence IN (‘active’, ‘idle’) AND uid IN (SELECT uid2 FROM friend WHERE uid1 = $MYUSERID)
Maz, I did not have tried that myself, but it should work. You have to:
- make POST request on /PROFILE_ID/feed
- add message variable parameter
more here
Thanks!!!!!
Jozef,
I was wondering, if you had a Flex project I could download. I’m having a issue with some of the browser-AS communication, and it would be great to see the entire project.
Thanks,
JT
Interactive Evangelist
Dell Inc.
I put together an example app at git hub for those struggling with facebook and air:
Hi John,
the entire project (flex framework v3.5) consists of:
- app.mxml (source in the article)
- FacebookOAuthGraph.as (linked in the article)
- FacebookOAuthGraphEvent.as (linked in the article)
- html wrapper file view-source:
- swfobject.js view-source:
- callback.html (source in the article)
thats it thats all, there is nothing else
if you have issues with JS to AS communication please follow this comment:
Hi Jozef,
Thanks for this great class. Like Kevin I tried to convert your Flex example into a fully working Flash example.
However, I experience some problem with the call function where the callComplete() is never fired.
It seems that the request is endless.
[i]“Transfering data from graph.facebook.com”[/i]
My Flash demo page :
My As file :
Thanks in advance for your feedback.
Jk_
hi Jk,
facebook service may be down or may timeout, however, my best recommendetaion is to use proxy software to watch all your requests/responds, that helps you with debugging a lot. Brilliant one is .
hello.
This my sound a stupid question but … how do i do to get the data from the byteArray. Example : how do i get the “name” of the logged user.
Thans
josep, you do not need binary call for that, try:
facebook.call(“me”).addEventListener(FacebookOAuthGraphEvent.DATA, callComplete);
function callComplete(event:FacebookOAuthGraphEvent):void
{
trace(event.data.name);
}
Hi Jozef,
Thanks for the Charles Proxy link. It looks like something very useful indeed.
It works properly now.
Greetings from Belgium.
Hi Jozef,
Me again. I wonder how I could publish to user wall using me/feed/.
Where should I specify the content of the message, link and description?
Cheers,
jk:
Hi Jozef,
Thanks for putting the work into this – it’s really useful in trying to unravel the mess FB drop on us.
Seems that me/feed and me/home etc won’t work due to permissions – you’d need to add in read_stream as well most of the time, as the posts won’t be public. Facebook probably saw that you had this working so added that in to keep the fun going…
Thanks
@Jozef Chúťka
Thanks… i haven’t thought that well..
Cheers.
Josep
hello again.
I was trying to publish something in my wall with this code:
public function post(id:String, msg:String):void
{
var loader:URLLoader = new URLLoader ();
var request:URLRequest = new URLRequest (apiPath + ‘/’ +id+ ‘/feed’);
request.method= URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.message=msg;
request.data=variables;
loader.load(request);
loader.addEventListener(Event.COMPLETE, on_complete);
}
But something is not woking.
Any help?
Thanks, Jozef, I appreciate the quick response.
Cheers!
JT
@josep, do not forget to include
variables.access_token = token;
all other code seems to be ok, use charles proxy to debug request and let us know
Hello Jozef, great stuff with the code and thanks for sharing it. I have tried to implement a flash version of it.
The thing is i get this error when i check my response to any calls made to me/whatever
{
“error”: {
“type”: “OAuthException”,
“message”: “You must use https:// when passing an access token”
}
}
My current scenario is facebook application running on facebook itself. so its not a desktop mode but website and developer mode on. I have also left out the hash portion of the mxml as confirmconnection seems to be running anyway.
Can you tell me what i may be doing wrong?
Thanks!
MT
hello Murtuza,
I have noticed today morning, facebook changing rules on the fly again. Please read “update” part of this article I have just added
Hi Jozef,
Thanks for the update!
It’s a sad news.
anyone, please support this bug with your vote, on official facebook bugzilla, it may help:
Thanks for the update mate. I find that there is one other method to connect other than the sever side script proxy method which is to use the Facebook Javascript api to proxy the calls. This would reduce any load on your own server and just pass queries and results to and fro the swf to facebook. I guess it is heading back to the old days.
Hi Murtuza,
I created a small demo page where I use the JS api with As3 using ExternalInterface.
If you are curious of the JS api, you should definitely read this awesome tutorial by Mahmud Ahsan.
Hope it helps.
Jk_
Link to the article
Sorry, it seems that i forgot to close a tag in my previous post.
Hello jk_
Can you please give more information on how you mix the as3 and js API.
Doing the connection on facebook throught as3 connect, and then doing call on open graph methods through js s?
Thanks a lot
Please support this bug with your vote, on official facebook bugzilla, it may help:
reply from facebook devs to the bugged issue:
Jeff Bowen 2010-05-14 11:32:12
Thanks for the report. We are looking into this.
thanks for voting folks
I hope things get solved soon
Hi daweed,
In fact, I only use the JS Facebook SDK.
The connection between as3 and js is done with ExternalInterface.
I would prefer use only as3 but with the recent changes in the facebook crossdomain policy, I had to figure out something else.
Cheers.
Jk
@Jk
How do you fire the FB.login function with ExternalInterface? When I try to do it, the popup with the fb connect doesn’t show up because it doesn’t get fired by a clickEvent in js, how did you get around it?
grts
@Brmm
You should definitely read this article of Mahmud Ahsan. So far it’s the best tutorial on the JS Facebook SDK.
Just browser my JS code and you will find what you need.
-
- (check the source)
Let me know if it helps.
I’m weeks away from launching my app on Facebook and this info is very helpful. It’s a shame it all has to be so hacky. I’d love to see someone publish a straightforward tutorial or best practices doc. Seems like the JS api and external interface are still the way to go.
——- Comment #12 From Jeff Bowen 2010-05-17 13:56:45 ——-
This should be fixed with Tuesday’s push. Stay tuned.
:O
They’ve said it should be fixed by Tuesday. At least I didn’t spend the past week writing a version to handle it all through JS. Oh wait, yes I did…
atleast I didnt
…
@Chris
We all did!
Yay! It’s done!
Now we can rewrite everything and wait for the excitement of finding out what they’ll change next!
anyone tried out – … and how the hell (noob question proberbly) do i get my domain to run SSL … or https ?
good news everyone – secure is false
and application is working again!
I’m not sure if it’s a load balancing issue or what, but it has now gone back to secure=”true” for me on all of the connections I’m trying. Seems they’re having some problems with Tuesday’s release so it it may take a little while to cement this fix.
Chris,
try clear from your browser cache
for now it contains <allow-access-from domain=”*” secure=”false”/> for me … but it may be that there is an old version of .xml somewhere in network heaven
Yeah, it’s not a caching issue – from work it’s now updated to “false”, but from my home it’s still “true”. I think the only sensible solution might be to have a version that can switch between JS and AS calls, just for future proofing as far as possible. Which is annoying!
For some reason the javascript function doesn’t seem to be calling the confirmConnection function (getting a null token value when I trace it out from inside the class). I did everything exactly as you did up there w/ swf object…any ideas?
Hi Nick,
- first please clear browser cache and let me know if this example works for you, if not tell me what browser you use
- download latest class and copy latest application code (change clientId and redirectURI), define all the necessary settings for your facebook app
- upload your app so callback.html and .swf file and wrapper file are on the same domain
(as defined in facebook settings) now tell me what works and what do not, does the popup open? does it close itself after success auth?
Hey JC … I got a question, I use your classes in Flash (thx for sharing btw).
If I do a call like{uid}/feed the result come back are in JSON, do I need to decode them with JSON, or ? Because I don’t see you doing that
I’m asking because I’m a bit confused the Flash vs Flex
Hi Dan,
well ok,
am I JC?
anyway good question, I am glad you noticed that because I forgot to mention this in the article. well this may not be obvious but you can get decoded data via event.data
example call(“me”), returns:
private function callComplete(event:FacebookOAuthGraphEvent):void
{
trace(event.data.name);
}
just make sure you dont try to decode ByteArray (eg. me/picture)
Hehe ye your JC … got a bit lazy with the typing (sorry)
I got another question, what would be easiest:
I’m trying to load alot of profiles pictures for a Flash Facebook game, do I reference all thru individual calls to /{uid}/picture and load them with ByteArray, or … can i load them like I would load external pictures normally
var image:URLRequest = new URLRequest (“{uid}/picture”);
because i think i saw somewhere that its possible to batch load multiple profile pictures thru one api call, i just cant find it anymore.
And now im a bit confused what way to do it
Hi Jozef,
I am new to flash/as3/xml.i am trying to understand the code.i am trying to create a button when user clicks on it message will goto their feed.can you please tell me in steps like how to run this code from flash cs4.
@Dan, that reminds me C.J. from BayWatch
I would use Loader class with normal URLrequest, no need to go through secured nor authorized requests for this as long as profile picture is public
@greeshma you should follow the actionscript code used in the example, it is more less the shortest possible way to achieve what you need.
1. create facebook instance and check for saved token
2. use user interaction (mouse click) to dispatch popup via facebook.connect() – user interaction needed so blocker will allow your popup to open
3. prepare a listener for FacebookOAuthGraphEvent.AUTHORIZED that is dispatched after callback
4. now you are connected (access token defined)
5. use facebook.call() function to do whatever you want
Hi! You definitely did an awesome work here! I was totally clueless on how to implement the new changes until I read this article.
I have this situation, I have a canvas application, so I’m looking for a way the users don’t have to click on a “Connect” button like you do on a website outside facebook.
I tried modifying the checkSavedToken() function on FacebookOAuthGraph to this:
public function checkSavedToken():Boolean
{
if(!savedSession.data.token){
return false;
}else{
var token:String = savedSession.data.token;
var loader:URLLoader = call(“me”, null, “”, token);
var type:String = FacebookOAuthGraphEvent.DATA;
loader.addEventListener(type, checkSavedTokenComplete);
return true;
}
}
And then init() to this:
private function init():void
{
facebook.clientId = clientId;
facebook.redirectURI = redirectURI;
facebook.scope = scope;
facebook.useSecuredPath = true;
facebook.addEventListener(FacebookOAuthGraphEvent.AUTHORIZED, authorized);
var iftoken:Boolean = facebook.checkSavedToken();
if (iftoken == false){
connect();
}
log.text += “checkSavedToken()\n”;
}
But then Firefox blocks the popup!
The app can’t connect to facebook unless I allow the popup, so I can’t use this.
Any ideas? I really don’t want to have a “connect” button on a canvas app
@greeshma you are messing the whole thing up
… are you trying to use official ActionScript Facebook classes with my one? that will just not work
@Jessica There is no need to change the code of FacebookOAuthGraph class, if you need changes, please extend it with your custom class, I made all methods in public or protected namespace so there should not be problem with it. PopUp blocker does exactly what you have described, it block popups that are not invoked by user interaction, you will not make this work but you dont even need it!!!
when using canvas page (i suggest iframe):
- before generating flash, redirect from your html (via javascript or php) to authorization url
- when it returns to your html it contains access_token (same as our callback.html)
- now it is time to generate flash and pass this token into your flash via eg. flashvars.token
- in actionscript handle flashvar params and pass token into facebook.confirmConnection(“#access_token=” + token)
- now you should get connected
It works like a charm!
Thanks Jozef for the updates.
Greetings from Belgium.
You’re genius! Just let me try it and I’ll tell you how it worked out, thanx a million
thanks, works just great! anyway due to all that changes i’m a little bit confused now
actually i’m missing a complete application setup incl. app settings and stuff. like checking for
“is logged in”, “has app”, redirect, login, check token, check if extended permissions granted and stuff. somekind of “framework”-basic-setup-tutorial would be handy.
in my case i totally dropped the as3 api and just use this handy class for the new extended permissions, what i’m missing now is the initial setup (verify login, redirect to login, check permission). also i would love to integrate the js sdk into this, because i still prefer having popups when posting stuff to a user’s wall instead of automatically doing so (even if the user granted his permission to do so).
anyone sucessfully this class and the js sdk via external interface already? if the user is logged in via opengraph, do i need to re-login him via the js sdk? is it the bad facebook documentation or is it me that’s causing this confusion?
thanks: lars
just noticed i do not get any permission popup on safari (windows) or chrome (windows). ie and firefox do work…
hi lars,
thanks for your feedback
- what exactly do you mean by “i do not get permission popup”? is your popup blocked? or does it close itself in a second? I use chrome as my main browser and do not have any problems with it. once you grant permissions to the app, you are not asked to regrant them with next login (facebook behaviour)
- I know there are some things missing in the class, that is why its meant to be abstract. It contains just the minimal working code by purpose. I have left a lot of room for extending there, eg. to verify login override confirmConnection() method, add some simple call (me) and handle the result (or error)… there is a lot of things everyone needs to handle differently so why making this code any longer?
- I would also like to hear someone mount this class with js. if so please let me know. I guess the js makes the same api calls (with access_token), so to push token from flash to js (or vice versa) should be enough to make them work both
hi jozef,
no popup blocker on chrome or safari. it seems there’s an js error on the ext interface call. actually i’m logged in on firefox and try chrome and safari while the logged-on-session in firefox is running.
safari error console reports: Unsafe JavaScript attempt to access frame with URL (my facebook app url) from frame with URL (my own server with url pars passed). Domains, protocols and ports must match.
safari on windows and safari on osx report this error…
thanks: lars
lars, does my example work for you? if so, please follow all the steps one by one so your app will get also working. I do not have safari but this seems like xss, you may have bad callback url defined or something like that.
Wow.. now it seems that facebook is changing the crossdomain.xml file at random.
I am developing a login function for a site using your code (great stuff, btw – thanks!), but suddenly it got unstable.
When I checked the file, is’s changing at random for a very short time (1-2 seconds), removing the ‘secure=”false”/’ part, so that https would be needed.
I REALLY hope Facebook will stabilize this.
Just thought i would post this comment to help explain the problem to anyone experiencing the same thing.
Can you help me figure out a way to log the user out with a function in flash?
I can’t figure out how to call the javascript (FB.logout) needed to do this. So when I try to use the login a second time, there is no way of changing the user, without logging out of facebook in another window, or deleting the application permittoin in facebook.
It would be great if you could give me a hint fro this!
@Morten, if this issue persist even after clearing your browser cache, pleas report it as a bug
@Morten to log-out user, it is enough to clear the SharedObject (contains access_token)
Hi, thanks for the quick response!
I tried clearing the SharedObject allready, but it did not seem to work. I’ve not worked with this before, so I might be doing something wrong.. Here is my code, I have tried a bunch of different stuff, to see if any of it works, but no luck:
public function logOut(){
var name:String = “FacebookOauthGraph” + clientId;
var _savedSession = SharedObject.getLocal(name);
trace(“before loging out: ” + _savedSession.data.token);
_savedSession.clear();
trace(“after loging out: ” + savedSession.data.token);
}
I put the code inside your class (sorry for the mess). But it seems like the reference to the token is still there, as it logs me back in automatically when calling the connect method again. The before/after trace tells me that the tokens are gone after clearing.
Any ideas?
@Morten
now I see what you are trying to do. There is no logout method in graph api (as far as I know), you can logout user from facebook using javascript api:
FB.Connect.logoutAndRedirect(“”);
or logout in another window (as you have mentioned)
If you want to just disconnect – clear token data from my class you can use:
public function disconnect():void
{
savedSession.clear();
protected::token = “”;
protected::authorized = false;
}
Tks for this post, very usefull.
However, how can we get large picture ?
Because we have to write something like that :me/picture?type=large
Is there a solution ?
tks
@Jey you should do it this way:
var data:URLVariables = new URLVariables();
data.type = “large”
call(“me/picture”, data);
Tks for the update !
Hey Jozef, these classes are invaluable – great work! I’m having difficulties posting an image bytearray to a FB album,
What should I post in the URLVariables?
Hi Sean,
I do not have much time to test it but it should be possible on “/ALBUM_ID/photos” + supplying image file and message params section “Publishing to Facebook”
Thank you posting that forum post, made it alot easier figuring it out.
This is how we did it, implemented in to your class.
Maybe there is a way of using normal urlloader for this aswell.
/**
*(‘message’, message);
mpLoader.addFile(ba, “image.jpg”, “image”);
loaderAddListeners(mpLoader.loader);
mpLoader.load(apiSecuredPath + ‘/’+ path + “&access_token=”+ _token);
return mpLoader;
}
Thanks alot for pushing us in the right direction.
very strange things… all worked, but me/photos return:
{“data”: [ ]}
but full string like. returned normal fulled data.
WHY?
@Sean thnx for posting working solution
Is not permission problem because me/albums worked ok.
@ancle because api does not know who you are without sending access_token, even if it would, your photos may be private, that is why you need access_token
and i can update my status message whitout access_token?
i try connect to fb with different way… now i see my acess_token inside my swf (with iframe cavnas).
i see “authorized” message too, but me/photos still empty…
i need to get call() with my token manualy or it’s automatic?
me/albums work
me/feed work
changeStatus work
but me/photos – empty… i don’t fking understand
same here, me/photos not working. Tried the left box for me/photos but it returns empty result. I don’t think privacy is an issue because I set all my albums to “everyone can see” mode.
Can you please explain what I need to do to see the photo data? Actually maybe updating the article or writing a new one about photos (simple photo gallery app) would be so awesome!
Thanks for the article anyways, it helped a lot.
look, about same problem talking here
and here
look like bug…
@znt, @ancle now I see what is the problem, facebook changed rules again. I have removed and readded my app and I also see empty arrays for me/photos. Now, it is time to introduce “user_photo_video_tags” permission. I have already added it into my app, so please remove your browser cache, refresh app and click connect button (even if you are connected) and grant the permission, results should be ok again
yes, it look like solution, but… still not working
maybe cache or something… i try it from another pc…
Thanks for quick reply jozef, here’s what happened.
I cleared browser cache (firefox), refreshed the page, connected to facebook, application asked for new permissions, granted. => “me/photos” not working.
Fired up google chrome, came to this page, connected to facebook. => not working.
Sat on a different pc, came to this page, connected to facebook => not working.
Logged out, logged in with another facebook account (sister’s), came to this page, connected to facebook, granted all permissions to the application. => “me/photos” working for sister’s account.
So what may be the problem? Is there an option to regrant/refresh all the permissions to application? maybe the application is still prohibited from accessing my photos?
Hey I just tried something and it worked.
From facebook dev forum:
“In all my attempts searching I couldn’t figure out what the issue was. ahdang you may have missed that any photos that you aren’t tagged in won’t show still.
In order to successfully do this you must retrieve the albums, then the pictures from that object. For example:
then call…”
Read this on facebook, then tagged myself in my photos. The photos I was tagged was returned when “me/photos” was called.
Then I copy pasted an album id from “me/albums” and used “album_id/photos” command in the left box. Voila, all photos in that album returned as a result.
I think you should update your article about this.
Thanks for great work anyways.
From another pc, after new autorization me/photos worked.
Jozef thanks, i’ll go to create AMAZING application.
Hey thanks for the props, though I have to clarify that it was
“barryels” from who came up with the solution I just implemented it with your OAuthGraph class.
I can only confirm it working with users own albums.
Haven’t figured out how to – 1, send image bytearray via “/feed”, only the string gets passed to your feed.
2 – you will get a “stream error” when trying to upload images to a fanpage’s public gallery.
why am I getting a strange window within a window when doing a iFrame canvas app :(?
i ofc mean iFrame with a iFrame inside
nvm .. stumbled upon this
I would like to know why i can’t have the same informations about my profil when i call : “me” with this flash application and when i click on this link : in the selection part of: (this method allow to get full information)
@Jey its due to permissions, I guess the app behind call from developers.facebook.com has granted all permissions from you (fb made it so). this app just a few of them.
Damn it !
But thx
May be there is a solution to get all permissions?
I have searched in parameters of my application but there is nothing about that…
@Jey here you can find list of all possible permissions
put all you need into scope:
private var scope:String = “publish_stream,user_photos,user_photo_video_tags”;
Thks a lot, i have already founded and i was back to post these informations about authorization.
Some of authorizatios about profil
user_location ,email ,user_relationships, user_religion_politics, user_birthday, user_photos ,read_stream ,user_status, user_about_me”…….
Thanks for the feedback !
Hello, well I’m back to tell you how things are working out for me trying to make my iframe app work.
I tried to implement the steps of “How can I use this class in my iframe canvas page?” but I’m afraid that I had the same problem described here
The good news is that someone posted a working solution to this(answers #13 from jasek2)that consists on having an index.php which only function is to make a redirect and having the rest of the application in another folder, the redirect uri MUST be to that folder, e.g. .Then you can retrieve a var called ‘code’ and ask for ‘acess_token’ using your ‘code’,'client_id’, ‘redirect_uri’ and ‘client_secret’. Once you get your ‘acess_token’ you can send it via flashvars to the flex app. This is how I did it, it’s a mix of Jozef’s exellent app and the solution of facebook forum:
Index.php on:
<?
echo "”;
echo “window.open(‘’, ‘_parent’, ”)”;
echo ” “;
?>
Index.php on:
<?php
$code = $_GET["code"];
$token = file_get_contents(''.$code.'');
echo 'var flashVars = {access_token:”‘.$token.’”};var params = {wmode:”opaque”,allowScriptAccess: “sameDomain”};var attributes = {id: “FacebookOAuthGraphTest”,name: “FacebookOAuthGraphTest”};swfobject.embedSWF(“myswf.swf”, “flashDiv”, “600″, “400″, “10.0.0″, “expressInstall.swf”, flashVars, params, attributes);’;
?>
On Flex app:
public var myToken:String;
private function initfb():void
{
facebook.clientId = clientId;
facebook.redirectURI = redirectURI;
facebook.scope = scope;
facebook.useSecuredPath = true;
facebook.addEventListener(FacebookOAuthGraphEvent.AUTHORIZED, authorized);
facebook.checkSavedToken();
myToken=this.loaderInfo.parameters.access_token;
facebook.confirmConnection(myToken);
}
—–
This is working for me BUT on the same thread on facebook forum (answer #21) someone is asking about how safe is to pass the client_secret on the url. I have the same doubt but I see no other way to get the acess_token. Even facebook suggest passing the client_secret on the url here :
* After the user authorizes your application, we redirect the user back to the redirect URI you specified with a verification string in the argument code, which can be exchanged for an oauth access token. Exchange it for an access token by fetching. Pass the exact same redirect_uri as in the previous step:?
client_id=…&
redirect_uri=
client_secret=…&
code=…
I’m really concerned about safety, so even if this is working, I don’t know how risky is to pass the client_secret on the url. What do you think? What do you recommend? :S
Hello Jozef,
This is a very helpful class and much better than the old way of doing things. It seems I have a problem, however. I get the following error AFTER the authentication goes through:
Invalid redirect_uri: The Facebook Connect cross-domain receiver URL () must have the application’s Connect URL () as a prefix. You can configure the Connect URL in the Application Settings Editor.
Here is what I am doing. My directory on my server () looks like this:
- callback.html
- Project1.swf
- index.html
- expressinstall.swf
- js/swfobject.js
and in my application settings, under Authentication, my Post-Authorize Callback URL is “” and when I call the connect method of your class I set redirectURI = “”.
I don’t know what is going on…
@Randall make sure to read whole article, especialy the facebook settings part. You do not need Post-Authorize Callback URL, just setup other correctly (Connect URL…).
I extended your class and override the ‘call’ function and added this line:
path = path.indexOf(“?”) > -1 ? path + “&” : path;
it allows you to call methods like: /me?metadata=1 and /?ids=me,cocacola,eastpak
might be helpful.
@Pieter ok, or you can do it with URLVariables … read FAQ / “How to add request parameters into my call?”
Found an error or maybe its just me. Click Connect -> when the facebook login pop up appears click cancel..
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
at Error$/throwError()
at flash.net::URLVariables/decode()
at flash.net::URLVariables()
at sk.yoz.net::FacebookOAuthGraph/hashToToken()
at sk.yoz.net::FacebookOAuthGraph/confirmConnection()
at Function/
at flash.external::ExternalInterface$/_callIn()
at ()
[...] graph api integration into your flash app. Before continue reading, make sure you understand the previous article. Due to huge interest, I am adding codes that makes your flash app working with graph api within [...]
Just FYI, I don’t know if anyone figured this out yet (didn’t read through all the posts). I noticed that some people seemed to be having an issue with the events. From what I can tell, the event may be getting fired before it is listened for.
@James ok I will take a look at it
@Marc I have been doing some minor changes lately… anyway can you replicate the issues?
@Jozef I added a quick fix for the issue in my version of the code.
all that i needed to do was add a couple extra (optional) params to the call function so that the listener can be added to it prior to the event firing. There are a couple ways to do it, this was just the quickest for me to get going with.
public function call(path:String, data:URLVariables=null, method:String=”", token:String=null, ARG_type:String = “”, ARG_callback:Function = null):URLLoader {
if(!data)
data = new URLVariables();
data.access_token = token || public::token;
var request:URLRequest = new URLRequest(apiPath + ‘/’ + path);
request.data = data;
request.method = method || URLRequestMethod.GET;
var loader:URLLoader = new URLLoader();
loaderAddListeners(loader);
if (ARG_callback != null) loader.addEventListener(ARG_type, ARG_callback);
loader.load(request);
return loader;
}
so then my call looks as follows:
public function checkSavedToken():void
{
if(!savedSession.data.token)
return;
var token:String = savedSession.data.token;
var type:String = FacebookOAuthGraphEvent.DATA;
var loader:URLLoader = call(“me”, null, “”, token, type, checkSavedTokenComplete);
}
@Marc nice workaround, anyway I would recomend to extend FacebookOAuthGraph class instead of rewriting it, I have also made some changes in this class, so please update
@James ok mate, I have just fixed the error issue. please update
Thank you very much. I will give it a try!
Hi folks. I’m seeing some issues regarding the public and protected namespaces for the token and authorized vars. I’m assuming this is set up for FLEX only? Also, I know this has seen quite a bit of activity (for obvious reasons) over the course of the couple weeks, and if anyone has an AS3 only based example using these awesome classes that would rock!
Hi Donovan, I will take a look at it
Thanks Jozef! Feel free to shoot me an email if you have any suggestions. I’ll be playing around with this this week and let you know if I find anything worth sharing. Cheers
@Donovan, updated, please download latest FacebookOAuthGraph, its compatible with flash authoring tool compiler.
Hi !
I have one question about the new class, what is exactly :
” parameters ”
in —> facebook.autoConnect(parameters);
I have check it s an object who can have : parameters.session
But to start i have to declare this object “parameter”
Hi Jey, parameters are flashvars:
- in flex project you can use application.parameters
- in as project it is something like stage.root.loaderInfo.parameters
…when using facebook iframe ( ) , you receive valid session as GET parameter
Hi,
Thanks for your tutorial. Great !
One thing : You need compile in Flash 10, in Flash 9, it doesn’t work on Internet Explorer.
Enjoy !
Hey Jozef!
Thank’s alot for these great classes, really helps alot.
I have one problem though, I’m trying to detect if a user declines(presses cancel/don’t allow) in the facebook-allow-popup. I noticed there is an UNAUTHORIZED-event in your eventclass but is is never dispatched. I tried to deduce where to dispatch it myself but I couldn’t figure it out.
Any idéas?
/Carl
Hi Carl,
1. when user clicks cancel confirmConnection() method is called with empty argument – catch it there
2. you are right, I did not implemented UNAUTHORIZED dispatch. I think graph API does not support logout method, but you can use “auth.logout” method from REST API. try something like:
facebook.call(“method/auth.logout”, null, URLRequestMethod.GET, null, “”);
Hi again. Thanks for taking the time to help. Although, this doesn’t seem to work. I do it like this;
public function confirmConnection(hash:String):void
{
if(hash && hash != “”)
verifyToken(hashToToken(hash));
else {
var type:String = FacebookOAuthGraphEvent.UNAUTHORIZED;
dispatchEvent(new FacebookOAuthGraphEvent(type));
}
}
facebook = new FacebookOAuthGraph(); facebook.addEventListener(FacebookOAuthGraphEvent.AUTHORIZED, authorized);
facebook.addEventListener(FacebookOAuthGraphEvent.UNAUTHORIZED, unAuthorized);
But the UNAUTHORIZED-event never seem to be dispatched, at least my listener doesn’t pick it up. The AUTHORIZED-event works just fine though..
you are almost there Carl, now all you have to do is to debug what comes in hash variable when cancel is clicked
Bah, the only problem was my darn computer being somewhat retarded. Worked as a charm as soon as I rebooted. Sorry about that and thanks again.
Hello guys.
Does any one ever tried to implement a button the button with this example. I getting desperate with this issue because i trying to render some xfbml on my html page, but nothing is being showed.
The code i trying is …
thanks
@josep again pls, what should your button do?
sorry the code is ,
but i´m almost sure that it is the wrong way to go
The button should add my application to a tab on the user profile.
@josep how does this relate to the actionscript class?
@Jozef Chúťka
On line 031 of your example, you are referring to a variable called parameters in your autoConnect function, but this is undefined. What should I put here? I hacked it to work but I’m getting a popup after the user has connected, trying to avoid this. Thank you.
@Nick parameters are flashvars: stage.root.loaderInfo.parameters
Hi Josef,
I’ve being trying to load a profile picture using your class but i’m not able to do that.
i’m using like this:
loader = facebook.call(“me/picture”);
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(FBGraphEvents.DATA, callComplete);
the connecting part is working fine.
but on the “callComplete(event:FBGraphEvents)” i try to trace this values:
trace(event.rawData) //this traces weirds chars (should be ok)
trace(event.rawData is ByteArray) //this traces false
trace(event.rawData as ByteArray) //this traces null
then if i try to use the loadBytes here, it won’t work.
Do you know what could be happening? Am I doing something worng?
Thank you for your time. =)
@Paulo, please use callComplete() from my example. It works. Maybe the FBGraphEvents class you use is problematic. FacebookOAuthGraphEvent works fine…
@Jozef, thanks a lot for your feedback. it’s weird because i just renamed the classes. All other method are still working fine just the binary one is having problem. But anyway i downloaded it again and used the default name and it worked. Later i will try to figure out what could’ve happened with my code =)
Thanks again.
Hi Jozef:
Is it possible to use the Graph API to “like” a page via AS3? The issue I’m encountering is that my site is completely Flash based while the only utilities provided by Facebook are HTML/Javascript (e.g. their “Like” Button).
Thanks in advance,
jaglavek
When you have no picture it will FAIL!
Error #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation: cannot load data from.
at sk.yoz.net::FacebookOAuthGraph/call()
at FacebookOAuthGraphTest/call()
at FacebookOAuthGraphTest/___FacebookOAuthGraphTest_Button4_click()
@jag,
@markval override loaderAddListeners() and loaderRemoveListeners() and add security error handler like so:
type = SecurityErrorEvent.SECURITY_ERROR;
loader.addEventListener(type, loaderSecurityError);
[...] The Facebook Graph API article becomes pretty popular and a lot of developers keep asking me to publish some practices I use, I [...]
Hi Josef. Thank you for taking the time to respond to my (and the many other) questions. Your help is greatly appreciated.
Sincerely,
Jaglavek
Thanks for this.
Anyone know a way to use this to popup a feed dialog so the stream publish message is editable by the user. Like this example?
Hi John, the dialog you are refering to, is a part of facebook javascript sdk. I do not use js sdk in my class, its pure actionscript. If you want dialog box, you are free to create one inside your flash app, with your graphics, your text input etc.
hi,
When I am running your app I am getting this error from Facebook: “An error occurred. Please try again later.”
Any ideas?
@Ilya I guess it is one of the facebook’s api common error, please try again later.
Yeah defiantly, the question is there any thing I can do to fix it?
Oh nvm, I forgot the init() when moving to flash builder…
Hi again,
Now I got some other error, I can log in this time, and it even redirect to the redirectURI, but then nothing, the authorized function is not executed.
Thanks for posting on this, I found your examples useful and have managed to get Graph API auth & calls working now. Thanks again.
That’s what I figured. Thanks Jozef.
@Ilya, is your callback url on the same domain as original app? if not use advanced callback
Hey Jozef,
Evewn though you explained it I cannot develop my app locally because the callback only works on the domain.
Where do you get the access_token value and where do you copy it into the code to publish again?
thnx a lot BB
Hi Jozef,
I got it to work after I inserted this little function and button:
protected function showToken():void {
Alert.show(facebook.token);
}
And then inserte your code snippet from the FAQ into the init() of the main.mxml file.
As this however implies that I have to copy and paste the token String all the time, I tried your Advanced Crossdomain Working Authorization from your other article here:
But somehow I cannot get this to work properly. I am not so sure if I generated the correct Callback.swf. Could you possibly post yours or tell me how to create it the right way, please?
I will keep you posted on my progress.
Anyways, thanks for your seriously great effort here!
BB
Hi Jozef,
The callback URL are the same as domain, the only difference is that I am using flex 4, I have no idea what may cost this problem. What information should I provide you so you can help me?
Hi Ben Bee, to make it work locally, please read and advanced callback part. I have fixed link to Callbkac.swf, thanx for noticing that. Now I read your next post, do you have problems with LocalConnection? What OS / flash player you use? In mac + 10.0 is LocalConnection somehow broken, fixed in 10.1…
Ilya, does it work with my app? if so, make sure you use latest class versions + check your facebook app settings
Hi
Really cool classes =) Though I have wierd problem using the MultipartURLLoader to upload a image to an album. I get Sandbox violations #2048 error. I don’t know what is missing because the FacebookOAuthGraph loads both the and the. I don’t get the error trying to get autorization or when I want to use the FacebookOAuthGraph::call function to get and set user data in facebook. I don’t know if it has something to with sending a bytearray and new retrictions from the flash player itself? I am currently using Flash debugger version 10,1,53,64.
//Per Borin
Hi per, what are your call() parameters? Is your request domain/path really… or is it… ?
Yeah man, I load both and. When I am authorised with the FacebookOAuthGraph.as I set a button visible and only then you’re able to save an image through a mouse click. To save the image I use the example code:
var theAlbumID:String = “”;
var theJpegEncoder:JPGEncoder = new JPGEncoder(60);Some image text!’);
this._theMultipartLoader.addFile(theUserImageByteArray, “image.jpg”, “image”);
this._theMultipartLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onSecurityError );
this._theMultipartLoader.load(“”+ theAlbumID +”/photos?access_token=”+ this._theFacebook.token );
I noticed it is working on the Internet Explorer where I am not using a debugger version, I don’t know, I am just little bit confused. If you want to you can see the example at
I did not used MultipartLoader myself yet, but i guess it does make POST request, so isnt the missing album id the case? Does your app request correct permissions?…
… try contacting Sean for correct solution
Thanks for the fast replies, if you leave the album empty it will create a new photoalbum, at least it does it in flash player in Internet Explorer. Okey I try to contact him. =)
Hi guys. That method seems to be promising. However from time I’ve got Flash 10.1 installed. Very often I see Security Sandbox errors when I am dealing with .NET services and I’ve noticed here as well.
In the example provided above Authentication is okay,
Call me works
But call binary giving me Sandbox security Error.
On the example above(next me my post) same issue.
> onSecurityError:: [SecurityErrorEvent type="securityError" bubbles=false cancelable=false eventPhase=2 text="Error #2048: Security Sandbox Violation: can't read data from.."]
Hi Is there a way to implement a “i Like” button with your class, by the way u are my hero! thanks for this class!
Hi Francsico, sorry, but impossible for now… please read updated faq
Hi devu,
I use latest release FP 10,1,53,64 / debug version / Mozilla / win xp, and no errors for me with binary calls. what is your version / type / os?
I solved the problem when I got a message from Sean. The problem is that I did not set the url correct and got an “unvalid path string” error, as you said yesterday Jozef =) I was trying to set up a new album to anything with the API. But when I changed the URL to me/photos instead of just blank everything worked in both IE Flash player and the debugger player Firefox. Why it did worked in IE player before I can’t explaine. Here is the code that worked for me.
var theJpegEncoder:JPGEncoder = new JPGEncoder(90);This is a message!’);
this._theMultipartLoader.addFile(theUserImageByteArray, “image.jpg”, “image”);
this._theMultipartLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onSecurityError );
this._theMultipartLoader.load( “”+ this._theFacebook.token );
Thank you for the great help and fast replies =)
//Per
Hi there,
I wonder if anyone else have trouble to make the FacebookOAuthGraph works with IE6.
I know IE6 (and all IE versions) is a pain in the ass but…
Let me know if it works for you.
Thanks in advance.
Jk_
@Jk_
Yes, I can’t get it to work on IE, any version.
There’s a bug filed on the issue, see if it is related to your problem and if it is, please vote so we can have Facebook check the issue:
Hi Jozef, thanks for your response, was hoping for a solution.
Anyways i have another question, regarding the implementation of autoconnect, where did u declared the variable parameters? or what values should this variable have, thanks in advance.
Im using the flash IDE for my project, and i dont see where in your flex code its declared, i would like to be able to autoconnect if you already have a access token.
Regards,
Francisco Chong
@Carol X
Hi Carol,
It’s weird because everything works fine for me on IE7 & IE8.
However, your test app doesn’t work on my IE8 either…
Could you please try this app with your version :
Let me know.
Cheers,
Jk_
Jk_, Carol X funny, my app works for me in IE8… I have FP 10,1,53,64 debug / ActiveX / IE8 / win xp
Hi francisco Chong,
parameters are flashvars (stage.root.loaderInfo.parameters) , you can use parametrs variable in flex Application element
@Jozef > It works in IE8 for me too! The problem for me it’s IE6… I will just advice my client to download Google Chrome
In fact I got a status 304 for the callback.html instead of a 200
HTTP/1.1 304 Not Modified
Date:Wed, 30 Jun 2010 11:45:07 GMT
Server:Apache
ETag:”2ac5ef9-1ea-485d92083311e”
Vary:Accept-Encoding
Hi again Jozef thank you for your replies, i noticed that u added that to your flex code, but im still having trouble making it autoConnect, is there a way for me to retrieve the parameters.session object variable with your class, maybe a method?
i noticed when i open your app, in a new window you have flashvars = { }, since there is nothing there flash just throws an error saying its undefined or null, and locks.
Thank you very much for this class, i hope there is some kind of solution, oh btw im kinda looking for a way to force a “like” within flash hehe, when i have it ready ill share the method.
Thanks in advance,
Fch
@Francisco, parameters (flashvars) are only utilizable with facebook iframe app, because facebook pushes GET parameter session to your iframe that you can use for connect, please read
when you pass parameters without session, the class tries to connect with stored (SharedObject) session.
Has anyone had issues with the callback not firing on Safari Mac/Win? No matter what I do the FacebookOAuthGraphEvent.AUTHORIZED callback never comes back.
@John, Maz kind of has on mac/ff:
are you able to debug javascript and actionscript? where does your scripts fails? Is ExternalInterface called from the callback.html javascript?
Hi Jozef!
Thanks not only by the great library, but also to explain how auth works with the new Facebook API.
I’m using your library now, to build a feature where users can download a wallpaper composed with profile pictures of friends.
But when I try to draw the bitmapData I got the error:
“SecurityError: Error #2122: Security sandbox violation: BitmapData.draw”
All the images where loaded like:
var thumbURL:String = ‘’;
var loader:Loader = new Loader();
var context:LoaderContext = new LoaderContext(true, ApplicationDomain.currentDomain);
loader.load(new URLRequest(thumbURL), context);
Any idea?
Thanks in advance!
Best regards
Hi Rapha,
I guess this is due to the fact that your request is redirected to a different domain. check this out:
request:
response:
HTTP/1.1 302 Found
Location
the actual photo exist on profile.ak.fbcdn.net domain, you should try to parse targeting domain and request crossdomain from
[...] it all good, this guy, Jozef Chúťka, figured it all up. His code is pretty good and the example gives you everything you need to get [...]
Hi Jozef,
Thanks for your quickly reply!
I’ve tried to request the crossdomain.xml file, but it doesn’t work.
But then, I’ve created a proxy php file to load the image from that address and works.
It’s not a good solution, but I’ve no more time left to research more about this subject right now.
Later I’ll check this out and post the result here.
Thanks!
hi Jozef
thanks for this – you continue to do amazing work
Cheers
@Rapha, yes it shuould work just fine with proxy
@Daniel, thank you
hi Josef
To get the access-token to work I had to unescape the string rather than just do the regex replace : i.e.
JSON.encode({ access_token:String(unescape(String(“139972822682…
cheers
Thank-you so much for your tutorial and scripts. They have been so useful for a project I have just completed! Just wondering if you have every taken the code 1 step further and made the popup a modal, rather than a new window (Facebook Connect style)? Thanks again!
@Jason, unable to make it modal, facebook does not let you open its content in iframe anymore (clickjacking)
Hi Jozef
I can’t get posting to feeds working.
I tried your example from the FAQ but nothing happens.
I had it working using the old AS3 API from Adobe.
Any ideas ?
I tried your example and i receive this error…
{
“error”: {
“type”: “OAuthException”,
“message”: “Invalid redirect_uri: The Facebook Connect cross-domain receiver URL () must have the application’s Connect URL () as a prefix. You can configure the Connect URL in the Application Settings Editor.”
}
}
Any idea?
Thanks in advance!
Best regards
Hi Torben,
could you please try change your status from my app? if this works for you, make sure you grant correct permission with your app and try using code from my app
@Sa, I think you have used your own app ( is not defined in my one), facebook is trying to tell you that you have to setup facebook connect url correctly, please read “Additional information about my facebook app” section, if you try to debug your own app from desktop, read section “Advanced Crossdomain Working Authorization”
I am able to change status with your app on this page.
I’m pretty sure I grant the correct permission.
I’m also able to post to my Wall with your app here:
My popup looks excactly the same.
For posting on the wall don’t I just need to ask for “publish_stream” in the scope ?
This is my code for publishing:
———
var fbAttachment : Object = {};
fbAttachment.media = [{"name":"", "type":"image", "src":src, "href":""}];
fbAttachment.caption = “my caption”;
fbAttachment.description = “my description”;
var data:URLVariables = new URLVariables();
data.message = message;
//// data.attachment = fbAttachment;
data.attachment = JSON.encode(fbAttachment);
facebook.post(“method/stream.publish”, data);
…and the src in the media is a valid url to an image BTW :o)
Torben, yes publish_stream is enough. But, are you sure you are using my library? Coz I am somehow unfamiliar with your facebook.post() function…
Sorry, that should have been facebook.call(“method/stream.publish”, data);
Don’t know what the problem is then. How do I debug those calls to facebook ?
ok than, I see few problems there:
1. you should use post method
2. as 5th parameter for call
anyway… you can use the working example from: , section Publishing Feeds / Publish feed with image
I’m closing in on something here.
After calling connect() the callback funtion confirmConnection is fired.
But as far as I can see that should call verifyToken() which in turn should call verifyTokenSuccess() which should dispatch the FacebookOAuthGraphEvent.AUTHORIZED event.
But I’m not getting that event.
verifyTokenSuccess() doesn’t get called ?
When is it actually authorized ?
Torben does your browser open new popup window when clicking on connect? this popup opens facebook and after successful verification calls your callback.html where is the javascript that calls verifyToken(). does this happen to you? does it happen for you in my app? if no what is your os and browser. If this works for you in my app and does not in your one, please makse sure to read whole article again, there must be something you are doing wrong. There are many questions answered in faq and other in comments. Please go through the stuff and you will get your issues resolved sooner
But callback.html calls:
window.opener.confirmFacebookConnection(window.location.hash);
…isn’t that a javascript function in my index.html it’s trying to call ?….I don’t have that and I can’t see that you do either.
js function confirmFacebookConnection() is injected from actionscript when connecting
OK, good. I don’t get any errors there and verifyToken() does get called. I know that but the problem is that verifyTokenSuccess() never does.
Getting closer.
verifyToken() calls the call() method which tries to load with the token as a parameter.
But I get an IOError on that which is weird beacuse if I paste that url with the token I got traced back directly in a new browser window I do get the info on me back with no errors.
Torben, search IOError in this page and you may find your answer…, even in FAQ:
This example app works with Internet Explorer, but my one results in Error #2032
Please complie your app to Flash Player 10 (or later). It should fix this issue. Credits goes to Garcimore , thnx
I am compiling to v10.
Thanks for all your help – I’m kinda lost now.
This example:
Do I understand correctly that it only uses JS via ExternalInterface and not the FacebookOAuthGraph at all ?
If yes, is all the JS I need in the js file ?
Thank you
Compiling the app to flash 10 didn’t work for me.
I’ve been checking this page regularly in the hope that someone has stumbled upon the same issue and found a solution, since the bug filed in facebook is kinda abandoned
@Torben, @Carol X.,
I confirm that I can reproduce the error from the bug post, but while the requests from my app works for me in IE, the same requests () from e.g. this app results in some connection problem. It seems like it must be some kind of facebook issue / facebook app settings that is causing it. there is not much i can do about it, just make sure your app settings looks something like this
first thanks for sharing this! Real good work! I already extended your Class and Implemented several Facebook graph features. Everything works quite fine as far as Facebook let you interact. But there is one thing that works different in every App I created to your Demo: My Access Token expires after I log out of Facebook and your Token keeps on working. My Tokens worked for 30 minutes after log out when I switch the App mode from Web to Desktop and certainly longer when I add the offline_access scope. But you don’t ask for offline access and It keeps on working for hours.
What do I miss?
Thanks Jozef, this is great work. Being a bit old school, I’m not much of a Flex developer and I was able to convert most of your example so it would work using the Flash IDE. However, I can’t seem to figure out how to retrieve the hash confirmation string back from the callback.html popup. Would you have an example that works just through the Flash IDE? Appreciate any help you can offer.
ps. I think it’s time for me to learn to program in Flex.
@Dionysiusm thnx, I guess facebook does not unvalidate access_token that fast after logging out, in this class the token is persistently stored in sharedobject, and while facebook api responds with a valid result (for this token) your app may not notice your logout
@Jason Redhawkm thank you, please download latest FacebookOAuthGraph, its compatible with flash authoring tool compiler. … in general, when clicking on “connect” button, actionscript injects javascript into wrapping html. callback holds reference for its opener (wrapping html) and is able to call the javascript function that pushes hash back into the main flash, make sure to have allowScriptAccess and name + id attributes for flash.
Thanks for your reply. Thats how I proceed actually because I’m extending your class. For testing purpose I created a button wich always do the same call with the sharedObject Token. As long as I’m logged in everything works fine, but as far as I log out I’m getting a “400 Bad Request” response. The same call keeps on working in your Demo App above.
I really have no Idea why this is happening. Maybe its some app setting thing.
@Dionysius yes it may be some app settings, see
Hi
My application suddenly started to work on IE after no change from my part, and I almost threw a party… but it didn’t take long to find out it only worked for my own user.
Then I came back here and saw you shared your application settings, thanks! But I tried them out and they did not help.
Now I noticed it has nothing to do with broser version or flash player version. The application works on the same machine for user 1, but it doesn’t work for user 2.
The only differences between the two accounts are:
- id for account 1 (working) has 9 digits, while for account 2 (not working) it is longer, 15 digits
- account 1 (working) is the application developer, account 2 (not working) is not, but the app is not in sandbox mode (I’ll try adding someone to the developer list to see if it works)
Seems more likely that the problem is in the id length, what do you think?
Hi again Jozef thanks to your class i have solved so much on this FB graph project im working on, but now i got some kind of an issue with Macs, seems the authorization popup window never loads for ppl on a mac and probably behind a firewall, do you have any idea why this could happen?
Works perfectly on any PC, but when its loaded on MAC, it seems to try to connect for a long period of time ending in not being able to connect at all.
@Francisco, do i get it right – the popup is opened and the request to secured facebook page blocked?
@Carol do you have issues with the app also with other browsers than ie? Long (64bit bigint) ID could be problem while actionscript uses 32bit integers, but IDs are handled (e.g. returned from /me) as strings so it should not do any harm
Hey Thanks for this just what i was looking for.
Popup blocking from some browsers setup was a bit of a pain but did a hacky fix around. that worked for my purposes
Might be interesting to some, basically I create a temporary html text link to do the same window open command, if its blocked automatically
Modified within your connect() method of facebookOAuthGraph
+ ‘var success = window.open(“‘ + url + ‘”, “‘ + name + ‘”, “‘ + props + ‘”);’
+ ‘if(!success){‘
// create a new div element position on page above/near around the flash
//set innerhtml to have a text link – which does the window.open method
etc etc
@Steve very nice solution, thank you for sharing
I have tried your example application from here:. The login works, but the label near the connect button will remain “not connected” even if i copy paste the access token in the hash textbox. The verifyTokenSuccess function will be NOT called. I am new in Actionscpript. The application runs in adobe flex bulider. I have debugged it, after clicking the “add hash” button, the acces token is good, this function: function(event:FacebookOAuthGraphEvent):void
{
EventDispatcher(event.currentTarget)
.removeEventListener(event.type, arguments.callee);
verifyTokenSuccess(event, token);
});
never runs.
I didnt change the application id (private var clientId:String = “268718683475″;), I think this isnt a problem.
@eva I am somehow unable to reproduce this issue, I am using xp/ie8 and authorization process is smooth (eva is win7/ie?). Did you click allow button on the opened facebook popup? Could you test it on another facebook account?
hi Jozef, thank u for your impressions.
now, i still have some problem with working in IE8 (Error #2032)
Firefox and Chrome work fine
many people say publish to flash 10.0.0 will be fine..
but it doesnt work..
Here is my file
i write the code in fla file and use Flash CS4
@John, Hi, this is definitely a facebook bug, please vote for … I have all my 100 votes on it right now
Thank you for help~~^^
so this bug didnt fixed yet…..ok.
anyway, your example work so perfect, its work in IE6 to IE8.
and i saw other example, some example can run, some example fail
what happend to it??
use Flex make flash is more better?
@John you are welcome. make sure you have correct settings , if the issue remains it is facebook/ie8 related and I am unable to handle that from flash player, some apps works, some do not, some works for some users only… Flex vs. Flash does not behave different in this context.
After I tried this setting, it doesnt work again.
anyway…i just hope facebook quick fix it now.
thank you for your help.^^
Thank you for the great source!
I have a swf that publishes a game score to the user’s facebook wall.
In Safari, it behaves perfectly. I’ve already added a javascript timeout for the confirmFacebookConnection(), which made it work in Firefox, but Internet Explorer still gets stalled on the callback.html.
Has anyone had this issue and resolved it?
Would there be an issue with loading the swf from a Content Delivery Network, instead of having it sit in the same directory as the callback.html?
Could this also be related to the IE facebook bug you mentioned? I put 100 votes on it.
Hi @Tryg, if your original html wrapper for main.swf exists on the same domain as callback.html, the javascript should be executed without security issues. I did not tried it within different directories:browsers, but I believe it does not violate crossdomain. Does my example work for your IE? .. If issues persist, try advanced callback from . If you tell me where the flow collapses (javascript/actionscript line?), I can tell you wheter it is related to the facebook IE bug or not. Even if it were not related, your votes are very useful
thank you
Hey Jozef
Yes, I only experienced the problem in IE and long ids…
A Facebook employee sent me a proposed fix (where I sould use POST instead of GET for all requests). I thought it would work, but I still get the error with long IDs. =(
Hi Carol, thank you for reporting, I have updated the article. it seems like ie issue with content-type:application/json header. I hope it soon get resolved by fb devs:
Not sure if this will help anyone else, but I was facing a huge problem with IE 6-8. My flash iframe app just wouldn’t connect to retrieve the access token. After hours of trying, I just tried changing my app settings. Under migrations > OAuth 2.0 for Canvas (beta) > disabled. Amazingly that fixed everything.
hi, i am in big trouble. i need help with session .logout() it is not working. how do i make this work
facebook.call(“method/auth.logout”, null, URLRequestMethod.GET, null, “”); it is not a website it is an air application. i want users to be able to logout to other can login. i use desktopsessionhelper and is there a work around using the clear() flash cookie. i want when i user logout he needs to loginagain. but here it justs login without asking for username and password.
Hi, tkx for all those precious informations. I have a question though:
do you have any idea of how to get that same application that you have here in a tab ? (profile tab or fan page tab)
The facebook documentation explicitly says that they need the user to make an action on the tab to actually allow us to get user id for example. When loading a flash movie in a tab, the user has to activate it in order to use it (needed action from user), but I can’t find a way to use the facebook api the same way you are doing here in an application tab.
If you have any idea or clue, plz feel free to drop a line. I might be totally “wrong” or blind but I just can’t get it to work.
tkx!
hi shammi, what exactly is desktopsessionhelper? you can not make user login on your site, there is no such api method “method/auth.logout” in rest api. however you can subscribe with javascript sdk to FB.Event.subscribe (auth.logout) but my class does not use javascript sdk
hi tom, I have not worked with tabs yet, but I guess you have to use FBML for tab content:
by using FBML fb:swf, all fb_sig_ params should be passed into your flash (I guess also access_token based on your app settings):
Jozef, tkx for your quick answer, I found the “problem”, I got a session_key instead of a token, just had to activate the “Canvas Session Parameter” in the migration tab of the application parameters form.
tkx again for your support.
hi, i dont have to wory about logout anymore i am using ur api now. i had to delete all the code of reset API . which stoped working two days ago.
now my only problem is i want users to upload picture to a specific album.
the MultipartURLLoader i am using an air application and i get stream error.
albumid = 214446590807
when using
hey thanks for ur quick response earlier.
i tried using this
and using multipathurlloader
i get some error like this
Error #2044: Unhandled ioError:. text=Error #2032:
i dont have links to seans blogs. i am making a desktop air application in as3. so do u think that i have to load something else too?
ok i seems to have fixed this. it works now i was posting it with two ?? so the error. it’s amazing how this works.
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL:
yea everything good now. i am able to post it to a specific album“+ 312707920807+”/photos”. every one use the graph API it will solve all ur problems relating to empty album data and logout.
@shammi, Im glad you did it
Hi Jozef,
Excellent tutorial – I have a strange problem when calling:
call([my id]/photos)
It used to work in that it returned all the photos I have most recently been tagged in, but for some reason now just returns an empty “data” array…
I think it may have something to do with my access token or something. The call works when I enter it into your flex app. Here is the call my flash is making:
Any help would be very much appreciated!
Cheers
Adam
Hi Adam, i guess its due to missing permissions, try “user_photos,user_photo_video_tags”
Thanks for that Jozef – I had ‘user_photos’ but not user_photo_video_tags’ added – this seems to have made the difference.
Cheers
Adam
Is it possible to get the person e-mail?
@PVieira yes, extended permission “email”, more here
[...] Facebook Graph API & OAuth 2.0 & Flash (update) [...]
Jk_ .. could you send me your example.. i am trying to do what you did exacly but i am having a ton of issues
[...] It does not provide login authentication as there are many other libraries available for this purpose and really…why re-invent the wheel? Some great examples are from Big Spaceship and Jozef Chúťka. [...]
Hi,
First, congrats for your work! It´s amazing =)
I´m trying to solve a connection problem with IE6. It seems that facebook doesn´t pass the token to it. I´m putting an “alert(hash)” on callback.html and just on IE6 it´s empty.
What should I do? I´m trying to sniffer my network with wireshark to see the difference between browsers, but I failed =)
Cheers,
André Vendramini
Hi Jozef,
Thanks for this class, anyway I have add a disconnect method and logoutURI variabel to this class. logoutURI is just a blank html file you can name it logout.html or something else.
public function disconnect():void
{
var urlReq:URLRequest = new URLRequest(“”+logoutURI+”&access_token=”+savedSession.data.token);
navigateToURL (urlReq, “_logout”);
savedSession.clear();
protected::_token = “”;
protected::_authorized = false;
}
rather than opening the logout in a new window I’m opening the logout url in an iframe named _logout, this iframe size is just 1×1 pixel.
So once you call this method a token in shared object will be clear and Facebook login session will be clear too.
I hope this helps.
Cheers.
[...] Facebook Graph API & OAuth 2.0 & Flash (update) [...]
Hi Jozef,
Thanks for your useful example. Works fine for me.
I have a question. I want the users to have a cool navigation inside my flex project, so for that, your cool flex iframe is fine, non popup.
But when i try your example on your website, here:
The login page doesn’t appear.
Is it normal? I try for me on a simple example and same problem.
Is it possible to add flex iframe with FacebookOAuthGraph class ?
Thanks by advance
Hi @André,
how does callback url looks like in ie6? all you need is to grab the token part from it. does javascript execution goes inside the IF statement? Would advanced callback ( ) help you?
Hi @Herdiansah, thanx for your logout method, briliant idea!
Hi @Vincent, I am sorry to tell you that whole facebook does not work in an iframes anymore. It is a security thing for avoiding clickjacking (my best guess)
Hi Josef, another question for you. From your example i was able to load profile image from the current user directly from a loader:
if (event.rawData is ByteArray) {
var loader:Loader = new Loader();
loader.loadBytes(event.rawData as ByteArray);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,
function():void {
image.addChild(loader);
…
How can i save the picture url?
@PVieira picture url is static “me/picture” for current user, “{user}/picture” for any other user. I suppose you want to save picture bytes (image)… hm… I guess it will not be possible directly (you do not have crossdomain.xml access) and you will need to use server side proxy to download the image
Hi @Jozef,
Now I´m getting the token. But IE6 bring me a surprise: when I call it return a JSON, all right? I´ve this code to test it:
var urlLoader : URLLoader = new URLLoader(new URLRequest(“”));
urlLoader.addEventListener(Event.COMPLETE, test);
function test(e : Event) : void
{
_txt.text = urlLoader.data;
trace(urlLoader.data);
}
IE6 give me this error:
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL
All browsers are working this test. It´s very simple, uh? Do you know what´s happening?
Thanks,
André Vendramini
Hi Andre, please go through the article again read section “This example app works with Internet Explorer, but my one results in Error #2032″ + comments here containing string “2032″
Hi again Josef.
I’m trying to load the picture from uid but i’m allways receiving this error:
Error opening URL ‘{uid}/picture?access%5Ftoken=null’
The call:
call({uid} + “/picture”, true);
Any ideia what the problem is?
Only works with “me/picture” call, with “{uid}/picture” gives me an error..
Hi Jozef,
Did you manage to get worked this beautiful class and your great stuff with flex iframe?
Regards
Hello!
Thank you for making this class.
I am having troubles implementing it.
It works most of the time, but sometime it does not, for no reason at all.
Is there any limit, how many posts you can make?
@PVieira it surely works, even without access_token:
Hi Vincent, facebook managed to block its content within iframe, if you try to load facebook inside any frame/iframe, the content will be hidden or “disabled”, its because of clickjacking attacks (my best guess)
Hi Sandi, in case of fails, what is the server response content? Or does it throw flash player exception? Facebook API has limits but it raises with your fan base (user count), I personaly never hit one… If you are not about to crawl the whole facebook database I believe you can not hit limits.
Josef, i have a little problem with swfobject parameters. The parameter id is being used by another api.
What do i need to change in your code to change this line:
id: “FacebookOAuthGraphTest”
to something like:
{other name}: “FacebookOAuthGraphTest”
I solved the problem with picture, but only with access_token, i can’t test this localy. Well, it works.
PVieira, you can change “FacebookOAuthGraphTest” to anything… both id and name are required keys for flash attributes (used with ExternalInterface)
I will try to change the parameters, thanks.
Now i have found another problem. I can’t connect with IE.
facebook.autoConnect(stage.root.loaderInfo.parameters);
private function facebookConnected(e:FacebookOAuthGraphEvent) {
// doesn’t reach this
}
I think the problem is this line that i don’t understand:
var session:Object = JSON.decode(parameters.session);
Any ideia what might be?
IE working thanks to a comment tip from @tom:
Josef, you said to me:
“PVieira, you can change “FacebookOAuthGraphTest” to anything… both id and name are required keys for flash attributes (used with ExternalInterface)”
I don’t want to change FacebookOAuthGraphTest, i just don’t want to use id for that. That required key is being used from other api. My question is, this id is being used by your code where exactly?
id/name is used in FacebookOAuthGraph class in connect() method … this method injects javascript method into html that later calls flash based on your id/name
Hi Jozef,
I have a few question:
- if the user close the facebook login / cancel login, can we detect using FacebookOAuthGraphEvent.UNAUTHORIZED ?
- and if fail to load picture can we detect using FacebookOAuthGraphEvent.ERROR ?
Thanks,
Herd
Thanks, i will try to change that.
Herd,
if user clicks “dont allow” button, the facebook makes following request:
GET /examples/FacebookOAuthGraph/callback.html?error%5Btype%5D=OAuthException&error%5Bmessage%5D=The+user+denied+your+request. HTTP/1.1
Host: blog.yoz.sk
… means following arguments are sent via GET:
error[type] OAuthException
error[message] The user denied your request.
you can update callback javascript to pass the error into flash and handle it from there
I am not sure now, how would graph api request fail response look like, but generaly yes, debuging fail response may help you to be able to catch it and handle it (via extending my class) to work correct way for you
[...] API. You have some choice to execute the call to Facebook via Actionscript (BigSpaceship Package or FacebookOAuthGraph). It’s not an official list, maybe there is other ressource for this [...]
Any ideas on oauth via a desktop AIR application? For the purposes of a kiosk I cannot use pop-up which are standard on with the Facebook_library_with_AIRConnect_v3.4_flex.swc. I’ve been trying to connect to a facebook users page to post to their wall. Inside my air application I’m using an htmlloader making call to the facebook api and I’m having a problem with accomplishing this:
var html:HTMLLoader= new HTMLLoader();
var permURL:URLRequest = new URLRequest(“”);
html.load(permURL);
I get to login, I get to the basic permissions page… and after that I try for extended permissions but fail miserably. Any help would be great, and I have scoured the net to find help and most roads point back to you.
vErGo_O
Hi @verg, please read here
[...] lack of GraphAPI support in the “officialist” Facebook AS3 API. I’ve found a number of solutions out there and see that quite a few people have gotten some work-arounds and even some [...]
Hi again,
Not sure what I’m doing wrong so, I decided to start at the beginning and try the example above. So I:
1. set up a FlashBuilder Project (easy switch from Flex),
2. grabbed the classes, created a new application copy/pasting the code above
3. set up a facebook application
4. swapped out the clientId
and redirectURI(“”) to the app and callback on my server
5. upload everything to my server, ran it and I get the following error in a pop-up.
here’s the url:
here’s the error:
{
“error”: {
“type”: “OAuthException”,
“message”: “redirect_uri isn’t an absolute URI. Check RFC 3986.”
}
}
Not sure what’s up? Any Ideas? Is it because my site does not have a domain name or something?
Hi @verg,
you see, there is a lot of null parameters in your url, you have to fix that first
wow… noobed-it on that one!! Had all those nulls in my url cuz I didn’t init() on creationComplete which sets all the facebook vars… duh! sorry.
can someone compare vs
does anybody now of an example Flash (.fla) file?
i would love to let people post a created painting from a Flash site to their Facebook feed or photo album.
thanks!
Hey
I cant seem to get the JS bridge to work. It looks like Facebook is passing back the # parameters to the callback html, but then flash never gets notified. Do you have a zip of all these source files somewhere for download?
Many thanks,
Eric
@tom sory I have no .fla file, but library will work for flash cs compilator
@Eric, Hi all files necessary are in the article, do you mean that your callback.html does not work for you? what is your browser/os? can you debug javascript or actionscript and see where the process fails? try read some comments for this post, there are some issues mentioned…
Jozef – In regards to the flash IDE side of things, and pop up blockers – i have some information that might be of use to you, and others.
Safari on Mac (wrongly) ignored the ExternalInterface call to open a new window. Its a well documented bug, and avoidable by using the navigateToURL function. The only problem is you need to know if you are using safari or not, or else just open the window with the external interface (blank) and then target it with the navigateToURL(urlRequestVar, ‘myWinName’).
You could have some js in your page to be called with an externalInterface.call , but keeping with the closed style of you facebook class – i suggest you add in the following (not foolproof but its better than nothing)
var safariJS:String = ”
+ “var browser = window.navigator.userAgent;”
+ “if (browser.indexOf(‘Safari’) > -1){”
+ ‘ return true;’
+ ‘}else{‘
+ ‘ return false;’
+ ‘};’
+ ‘window.open(“‘ + url + ‘”, “‘ + name + ‘”, “‘ + props + ‘”);’
var id:String = ExternalInterface.objectID;
var url:String = authorizationURL;
var name:String = jsWindowName;
var props:String = “width=670,height=370″;
var urlRequest:URLRequest = new URLRequest(url);
if(ExternalInterface.call(“function(){” + safariJS + “}”)){
navigateToURL(urlRequest, “_blank”);
}else{ + “}”);
}
As a side note to this, its worth noting that these have to be triggered by a method that captures a mouse event.If for example, the function is triggered on the result of a data call – think zendAMF or a an image load (basically something that requires time to process) the external interface call will fail silently. In this case you would need a prompt to continue.
The second problem that you face with Safari on OSX deals with the problem of callbacks from another window. It seems that safari does not keep the relationship of parent/child – and window.opener will always == null. I have tried in vain to fix this with js, but im not very experienced that way. I tackled the problem a little differently (to save space i will describe it here, if anyone wants the code just comment back)
basically i rig up a callback.swf that has a list of all the callbacks i want to use on my site. I embed this on the callback.html page. When the swf loads, it uses the external interface to check a dummy js function to make sure javascript is ready. If it is false, a timer is set up to ping the js. Once javascript ready condition == true, i external interface call another js function that returns the method name i want to use as my callback.
In flash i have a localConnection set up with the main flash app, and my callback swf. The callback.swf has the method name, and then performs the method (with any arguments) across the local connection.
So far it has been a rather nice solution to a frustrating problem that only safari osx seems to suffer from. And finally – thank you for the great code. It has helped me flesh out my flash app very n icely.
[...] the GraphAPI. Hopefully we’ll be able to integrate ideas. As well as the steps that Josef has taken to getting the OpenGraph into the AS3 world and Toby’s return to the JavaScript bridge. [...]
Hi @Beans, thank you for your instructions and solution. I have added it into FAQ section, I think this is really useful to know, I never used this class on mac-safari config by myself.
Did you tried my advanced callback “Advanced Crossdomain Working Authorization” on:
Hi Jozef,
Is there anyway to opening the facebook login in an iframe rather than opening in a popup window?
Thanks,
Herdiansah
Hi @Herdiansah,
it is not possible, facebook blocks its content within iframe, you can make simple test… I guess due to clickjacking it is
THANK YOU!
Excellent class. Very nice work.
I’m using it in one of my projects now and it works like a charm.
I was thinking about making a popup-confirmation when posting to wall like the one you get from the fb javascript sdk. So i’m trying to do this in the same way you did the authorization window, but haven’t quite gotten it to work.
Have you done this or do you have any thought if its possible?
hi! i would like to use the FLEX example from above in FLASH.
what do i need to change? please help!
Hi @Cechise,
1. you are using flash, you have free hands to do any UI you want with your custom graphics etc. or
2. you can use javascript sdk or
3. you can sharer.php in popup –
@Siret,
all you have to do is change the main class in terms of to use your own custom UI (maybe ), all libriaries should work for CS compiler
i don’t get it to work in FLASH. are there any code or file downloads available please?
thanks
Hi,
I am using your class on my site and it works great.
Now I am sending flash post to my users wall, and I want to add there a share button, just like in my site, that will register them to the application and make a post on they wall.
But I can’t do it now, because I have no control on Facebook html file where my swf file is loaded.
Is there any way to this?
@Siret, I have uploaded working .fla, please read FAQ … download link there.
Hi @Ilya, graph api does not contain like function, you have to generate it via facebook iframe widget… after user likes your application, he can publish feeds into your application/page feed stream
something seems to be wrong with your HTML part.
the .swf don’t show up!!
CODE:
it’s always just the alternative content that gets displayed.
what’s wrong it?
@Porter, it seems like you are having issue with javascript, is your swfobject.js file located correctly?
yes it’s in the same folder. (swfobject 2.2)
anybody experienced the same problem? WindowsXP with IE / Firefox / Chrome / Opera
@Porter, its definitely a javascript issue, make sure your javascript is correct… I can see undefined variable flashvars etc… use firebug to debug javascript
what a great tutorial,, :cheers:
Hi,,,
noob here,, n i got the same problem with Ilya,,
can u make an example about it?? or you have some?
thanx a lot
Donny I am not sure if I am getting this correctly, are you trying to be able to connect to facebook via flash feed post? like when running youtube video from feed and somewhere inside this flash a button to connect? yes it is possible, however, you can not use javascript popup but navigateToURL() into new window, than use advances callback, so user gets access_token via NetConnection (advanced callback )
hello Jozef
If i’m already logged-in facebook, and i trigger the connect method, i have the fb_callback popup that pop and then auto close.
i there a way to avoid this window to pop when i’m already connected ?
Thank you
Hi david,
why do you let your script call connect when you are connected already? use FacebookOAuthGraph.authorized to show/hide connect button etc.
hummm FacebookOAuthGraph.authorized return false if i don’t connect before.
Do i need to use the autoConnect ? (but with what parameters ? )
verifyToken? ( same, don’t know my token)
i’m a bit confused.
@david, yes you should use autoConnect() inside init() (see line 33), it works with 2 sources:
1. stage.root.loaderInfo.parameters (if you pass access_token via flashvars, used with iframed facebook app )
2. ShaderObject data – previous working token is autmaticaly stored and used by autoConnect()
… you may want to require “offline_access” extended permissions so your stored tokens are valid for a long time
ok, it was the shared object that was missing me…
i’ll test it..
thank you
Any way to make this retrieve the contents of a fan page’s photo album? I mean the user posted images to the fan page, not the official fan page photos. A lot of people would use this if you could make it happen.
Great work!
Hi Jozef,
Hey, I just found out (the hard way) that session parameters are now coming in escaped on an app I built. It was a simple fix:
public function autoConnect(parameters:Object=null):URLLoader
{
if(parameters && parameters.hasOwnProperty(“session”))
{
var session:Object = JSON.decode(unescape(parameters.session));
if(session.access_token)
return verifyToken(session.access_token);
}
return verifySavedToken();
}
but I wasn’t sure if this was something FaceBook changed or in my client’s environment.
What do you think?
WL
Hi Bill,
thanks for your code, I suggest you do it using the “override” way ( ), I am just checking my session parameter and it seems like it is encoded correctly as it should be – once, when value passed into flashvars (via javascript), the variable parameters should containt decoded – raw value… but if that was an issue in your case I am glad that you made it work…
Anyway I recommend to use charles proxy – great tool for debugging this kind of things (requests/responses/data etc.)
@Kirk, you can post images directly into page album, and you can also grap photos from this album or from an album of any user if correct permission granted (user_photos) … later it is no problem to get album content via
I have the same problem like : markval (on June 22, 2010 | 01:11)
and can’t seem to be able to override it, although I use a SecurityError Listener. I push all the rawData (of the user’s friends) in an array and then load them serially.
If an avatar picture is missing none of the avatars is loaded – got a clue why?
call(id+”/picture”)
private function call (path : String, binary : Boolean ) : void
{
friendLoader = new URLLoader();
friendLoader = facebook.call(path);
friendLoader.dataFormat = binary ? URLLoaderDataFormat.BINARY : URLLoaderDataFormat.TEXT;
friendLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
friendLoader.addEventListener(FacebookOAuthGraphEvent.DATA, onCallComplete);
}
private function securityErrorHandler ( e : SecurityErrorEvent ) : void
{
trace(“ERROR ERROR SECURITY BREACH OUWAOWA: ” + e);
}
private function onCallComplete ( e : FacebookOAuthGraphEvent ) : void
{
if(e.rawData is ByteArray){
rawDataURL.push(e.rawData);
counter++
}
else{
for (var i : int = 0; i < e.data.data.length; i++ ){
friendId.push(e.data.data[i].id);
friendName.push(e.data.data[i].name);
}
}
}
THANKS!
@jiannis, do you use debug player? what is the Exception being thrown?
@jozef, i get the following error in the firebug flash tracer:
rRror: Request for resource at by requestor from is denied due to lack of policy file permissions.
The debugger doesn’t throw any error.
I also get a trace from the SecurityErrorEvent:
Error #2048: Security sandbox violation: cannot load data from.”
any clues?
thanks in advance!
Hi Jozef,
Ive tested your flash CS4 source files and cant seem to connect? After you click the app freezes on “connecting…”? Any ideas why?
Thanks
C
Nevermind got it working now
Thanks for posting this article, really helped me out!
C
@jiannis, in order to access raw data (bytes) from , you need to download crossdomain.xml from b.static.ak.fbcdn.net domain
@Ciaran, cool, maybe you could send info what was the issue (I guess just some mistake in process), it may help some other developers too
@jozef, thanks I tried that but I think b.static.ak.fbcdn.net/crossdomain.xml doesn’t allow access from just any domain.
Is there a way to check the URL of the request before it tries to load the image? Then I could replace the images coming from b.static.ak.fbcdn.net with an image saved locally.
thanks a lot!!
@jiannis, if there is not suitable crossdomain, in general you should/can:
1. do not access raw data, use Loader.load() in order to just display image
2. use proxy to access data
@jozef, got it! thanks a million!
I’ve developed an apps in facebook.
Three weeks ago, it worked perfectly but since 2 days ago, it goes wrong. It is always loading and refreshing over and over again.
Here is my code to connect to facebook:
public function loginToFacebook():void
{
_flexVar = Application.application.loaderInfo.parameters;
facebookSession=new FacebookSessionUtil(_flexVar.fb_sig_api_key, null, Application.application.loaderInfo);
…
And these are the errors that I got, actually it’s not error message but address of web the facebook loading and refreshing over and over again.
Please help me.
Soleh Ayubi, it seems like you are not using FacebookOAuthGraph library but the official Adobe one, please ask the question on their discussion forum
How can i get wall photos?
@PVieira me/feed to get feeds on wall, then iterate and get those with image attachments
Guys, did any one tried to use this API after facebook changed its security protocols in 10/12 ?
I’m getting this response to my post wall (function publishPost):
“Failed to load source” for:
I might screwed something (always possible) but after some digging, I haven’t found anything about this, and since this security changes is recent, I’m wandering…
@Renan, stream.publish (part of old REST API ) works just fine … could you paste here the full exception text+code? do you use secured or unsecured path? do you host your app on secured or unsecured domain?
[...] Facebook AS3 Graph API 的作法,請參照 Jozef Chúťka 前輩所寫的 Facebook Graph API & OAuth 2.0 & Flash (update) [...]
Hi Jozef,
after a while during which I did not touch my app, I today tried to publish to a user’s stream. Therefore I integrated your Code from the FAQ Section
var media:Object = {};
[...]
facebook.call(“method/stream.publish”, data, URLRequestMethod.POST, null, “”);
Unfortunately this doesn’t do the trick inside my app / my configuration.
Background:
- My App is generally able to connect with facebook and execute calls like the following
facebook.call(“method/fql.query”, data, URLRequestMethod.POST, null, “”);
- But, my config is incomplete aka faulty, that is why I have to fetch a access-Token by hand, when I want to run the app outside of facebook. And, what baffles my most: When I add permissions (like create_event, manage_pages) the app aka facebook still does not asks me for allowance.
Any help would be great,
Thx, Robson
Hi robrob,
I guess does not for you is what are you asking me to help you with? Can you debug/trace the response from facebook on your call. Than we can move forward to investigate this
Hi Jozef,
thanks for your response. The error message confirmed the assumption, that the problem results out of insufficient permissons. So I’ve got some more study to do.
I appreciate all your quality stuff. Big thx,
robrob
robrob, you are welcome
Hi Jozef,
I am making progress, but still have some questions.
1. Is it correct, that opening the pop-up inside Facebook can only be executed, if it is triggered by the user clicking. Because right now it does work local, but not on FB. I thought I read something similar on here, but can’t find it anymore.
2. Is it correct, that the External Interface call isn’t handled by safari browsers.
Can’t thank you enough.
On that note: Where is your donate button?
robrob
Hi again,
as there is a clear statement to the second question of my previous comment, I would like to restate my post as follows
————————————
Hi Jozef,
I am making progress, but still have some rookie questions.
1. Am I assuming correct, that if everything is setup correctly, the user has to give permission only once and afterwards permission will be given automatically, without any need of user-action?
2. Is it correct, that opening the pop-up inside Facebook can only be executed, if it is triggered by the user clicking? I am asking, because I added an event-listener for FacebookOAuthGraphEvent.Error and tried to launch the External-Interface automatically if the user hasn’t authorized the app yet. This works local, but not on FB. (I thought I read something similar on here, but can’t find it anymore).
Still can’t thank you enough.
And again: Where is your donate button?
robrob
Hi jozef!
Do you know what other values that these can be sent with a photo upload? For instance, I don’t want to publish this photo in my feed, how do I go about it?
var values:Object = {
message:’My Caption’,
fileName:’FILE_NAME’,
image:img
};
Facebook.api(‘/me/photos’, handleUploadComplete, values, ‘POST’);
Hi robrob,
thank you for the donation button suggestion, I have added a donation button into section “Donations”
You may want to open popup without user interaction, there is no restriction within my library. What restricts your pop-up to be open is popup blocker (browser plugin or browser native behaviour), you may try to open new window via navigateToURL but based on browser blocker this action may also be prohibited from being called without user interaction.
If your user connects with your application, he receives token valid like 30 minutes (I guess), this token is saved into SharedObject that persists on his pc. Next time he comes into your app, the lib first try to use the stored token if it succeed you are connected else he have to click connect again. In order to make the token valid for long period of time (unlimited) request “offline_access” permission with scope parameter.
There are more safari users complaining about some javascript behaviour, please go through the blog comments here to find the solution. If you dont find any, try asking again, I am not sure I understood the issue
Hi Sven,
check out this article about uploading a photo vs. publishing post with image: … sections “Uploading Photo” and “Publishing Feeds”
Hi Jozef,
sure thing, I am happy to give something back.
So, do I get it right, that
1. The user has to click a button every once in a while, to let the app establish a connection to Facebook?
Except if I ask for offline access permission, which itself gives not 100% guarantee, because the shared object can get lost if a user shout his Pc?
2. If a user logs in, logs out and logs in with a different account, he will be treated as the first user, unless I implement some logout logic, which flushes the shared object?
3. Would any of this be different, if I would follow your authorizing with IFrame-Article? ()
Many Thanks,
robrob
@robrob,
paypal notification already received, thanks again
1. exactly. But if user keeps communication with his token on graph api he will not get unconnected anyway. I guess offline_access gives you good guarantee, I did not tried it any longer but it lasts more than a month for sure. Docs says:
“offline_access Enables your application.”
2. right. he is identified by stored token. you can make logout function as easy as described here
it should be able to compare these users by /me vs. /me?token
3. everything mentioned here remains the same for iframe version, its more less the same in all aspects
var js:String = ”
+ ‘if(!window.’ + jsConfirm + ‘){‘
+ ‘ window.’ + jsConfirm + ‘ = function(hash){‘
+ ‘ var flash = document.getElementById(“‘ + id + ‘”);’
hi i am unable to know what i need to put in place of id. also i am not able to get the access_token. i don’t know why. i do not see any code in java script which will call jsConfirm inside flash do i need to provide the id for flash object in your FacebookOAuthGraph.as class?
i am making in in flash Professional and html page has javascript.
if u can explain it would be great. after i log on to facebook what happens how does your code get the access_token after i see the message ” You may now close this window.” thanks for you help
hi shammi,
yes you need to specify id and name for your flash object in html:
var attributes = {id: “flash”, name: “flash”}; // or “whatever”, need same values for id and name
swfobject.embedSWF(“…swf”, “alternative”, “100%”, “100%”, “10.0.0″,
“flash/expressInstall.swf”, flashvars, params, attributes);
than, there is no need for changing the code in .as file, ExternalInterface.objectID contains the value of whatever you put inside swfobject attributes.id (.name) …
read the part of article starting with sentence “Make sure your html wrapper defines correct allowScriptAccess”.
Popup window should close itself when it is able to find your main flash and it also passes token into it via javascript/ExternalInterface
Hi Jozef,
Thanks for the article.
I am using the GraphAPI and a canvas based application.
I would like to get a list of my friends who are using ‘this app’. is there a way to do this with the GraphAPI?
thanks
When I call me/feed it doesnt return anything?
hello jozef
if the window “You may now close this window” does not close on it’s own. is it a cross domain issue. actually instead of adding the callback.html file to a domain i called for redirect url. and also i use your client id. i wanted to check if your code can be converted to a flash application. i am still unable to understand what this line of code does.
var js:String = ”
+ ‘if(!window.’ + jsConfirm + ‘){‘
+ ‘ window.’ + jsConfirm + ‘
——
jsConfirm =”confirmFacebookConnection”
callback.html page does not close on it’s own so i do not what to do?
Hi magicDamo, you have to use rest api call with FQL: see section “Application Friends”
@Don, it is a standard http request, it must return something even if it was an error code. please debug and trace the response
hi shammi, yes, it keeps opened if it is a crossdomain issue or it can not find confirmFacebookConnection() function in wrapping html javascript. this is the javascript function being injected by actionscript in the time when your popup is opened… those are exactl the lines you are asking about. you can not connect with my callback due to XSS. Read about “Advanced Crossdomain Working Authorization” here
Sorry Jozef it returns blank data
{
“data”: [
]
}
Don, go to and click me/feed link there. does that contain your data? if so you are missing some permissions with application, if not you somehow blocked your wall content in facebook settings for your account
hi all,
first of all, thanks jozef for a fantastic couple of classes, they’re going to really save my bacon!
but… I’m having problems getting the AUTHORIZED callback to function at all. Code is set up virtually identical to yours and the app knows whether its connect or not (the facebook.authorized var is set to true when you would expect it) but the callback just does not seem to be called at all. I’m utterly mystified!
Hi Matt,
go through article on up to the section “Auto Execution After Authorization”… does this attemp fix your issue?
hi Jozef
really thank you for the source!!^_^
but i have a question
can i get the (UserLoginState) before (publish.stream) methods?
prevent from the situation when user logout manually
thank you very much
hi Ellis, you can call “/me” to get info about logged user
Thanks Jozef, very cool what you have done here!
Sorted my problem with the me/feed with read_stream permission.
Hi Jozef i am a Flex 3 Developer i found this api to connect to facebook and looks great! xD
But… i’ve 2 days trying to make this api works in IE8 and… nothing…
I saw your app in and test it in IE8 and works perfectly then try my app and doesnt works in IE8…
My app is
Please if you now how to fix this.. help me..
thank you very much.
Hi Carlos,
your app works for my IE8. make sure to clear your cache and try it again…
what exactly means “doesnt works in IE8″ does it fall in endless redirect loop?
Hi Jozef thanks for your answer…
My app dont falls in endless redirect loop, i try to clear cache and temporary files and still dont work.
The problem occurs when i try to login… in the left panel shows checkSavedToken(), then shows connect() and never shows the label “authorized”… i try my app in IE7 and IE8 and never shows this label in FF,Chrome, and Safari works great!
I’ve debugin the class FacebookOAuthGraph.as and I found the function called “verifyToken”.. in this function never execute the code:
loader.addEventListener(FacebookOAuthGraphEvent.DATA,
function(event:FacebookOAuthGraphEvent):void
{
EventDispatcher(event.currentTarget)
.removeEventListener(event.type, arguments.callee);
verifyTokenSuccess(event, token);
});
then… the verifyTokenSuccess never called…
I put a Alert.show(token); at begining and now in the application shows the “178299352184385|2.7rMLm_8DQxDlCd8oyRApwA__.86400.1290700800-737101097|Z2uIg0gi8-Uk2ljvXmscFmEHRVI” …
But… still doesnt work and the token is not null…
Thank you very much for the help…
Carlos, may this be your issue?
follow a few comments below to see… if not than try searching verifyToken in this page
[...] Facebook AS3 Connect 方法在此一樣不提,請自行參考教學連結。 [...]
Hi Jozef, thank you for the help…. I’m still working in this problem, now i debug the application again and found in the FacebookOAuthGraphEvent.as class the variable _rawData and this var get the value “Error #2032″ only in W7 with IE7 and IE8, i was searching this issue about 3 days and i can’t fix this… i tried the headers solution putting application/json, building the application for flash 10, and… nothing, if you know something about this error please help me..
Thanks for the help…
Hi, Thanks for this great class. It helped me alot!
I’ve spent days trying to make this work across all browsers and I’m having a weird problem now.
Here’s the error:
Error: Permission denied for to get property Window.confirmFacebookConnection from .
This error only comes up in firefox and everything works in IE/Chrome/Safari on both Mac and PC.
Another problem I’m having is getting it to open in a small window instead of a big window. i.e. to say, using super.connect() instead of navigateToURL doesn’t work.
I would really appreciate if I can get some help! Thanks!
Turns out that in the end, the prefix www is the problem after all!
If you’re loading the website without a prefix of www, and your redirect URI is one with a prefix of www, it will throw you an error.
After spending HOURS trying to figure out what went wrong, this WAS IT! Hopefully someone will benefit from this.
Btw, here’s a snippet to detect the domain of where the swf is loaded so that you can load the correct redirect URI.
var urlPattern:RegExp = new RegExp(“.*?\.(com|org|net)”,”i”);
var found:Object = urlPattern.exec(root.loaderInfo.url);
var redirectURI:String = found[0]+”/advancedcallback.html”;
found[0] will basically return you something like “” or “”
Carlos, the bug is reported on facebook bugzilla fir more than 6 month now, no solution / feedback from dev team
Hi Edwin, yes, be careful with crossdomains… read more about flash security on
I did not got your issue with openning small window … it is bone by default
@Jozef, thanks for your reply. The small window problem was a mistake on my part.
Thanks for sharing this great solution too!
Hi, great stuff! I am currently using your classes in creating a simple app. One question though, how do i trigger the pop-up dialog that asks users to post a message to their walls when a button is clicked inside the flash app? Thanks!
Hi kalel,
this class is not javascript api based, thus there is no popup window to be opened… you can call the publish method from inside the flash, no evil popup required. make your own graphics and form inside your flash app in order to publish comments.
Hi,
Just a small question ?
it possible to have to use this class for a flash application dropped in fbml canvas in a fan page tab, I think we can but just a confirmation from an expert will save some time.
anyway great work, it helps me a lot.
Hi gilles,
you can use this lib anywhere. If you are able to pass token into flashvars you will get connected
great thanks, I’ll try. so it’s the only way left to make interactive app in a fan tab.
thanks again
Hi,
I made fbml app with a flash inside and I have a really weird behaviour, which i think is not because of your class, I have a sandbox violation error, it doesn’t want to addCallBack to js function when i call the connect function. I have the same probleme with the official api. Thanks for helping.
gilles, can you debug the exception? on what line does it throw this exception?
hi, it comes from the connect function, but actually now facebook doesn’t allow script access to flash on fbml canvas. that’s why the sandbox doesn’t allow me to have js callback.
I found a solution by ask for autorisation which go to my callback with the token dans then do what i want do with facebook by calling php script from flash which curl the facebook graph. Maybe there is a simpler way but the sandbox also block me when i call the graph url directly from flash. thanks for your help.
gilles thankx for the response gilles, I did never worked with fbml embeding flash much. I guess it is easier to use iframe while it gives you more freedom about how do you want to embed flash and things…
Does anyone managed to publish a swf on a facebook application fan page?
something like
FacebookDesktop.api(‘/app/feed’, callback, attachment,’POST’);
Basically I try to figure out how adidas managed to do it on their fan page
here
??
charles-j, you can simply do that with FacebookOAuthGraph. read section “Publish feed with flash” and comment for targreting feed into fan page
fantastic job you’ve done here
i can run your cs4 flash only version fine using your parameters supplied for callbackurl and app id, when i try to use my app id and callback html on my webserver it doesnt authenticate – i think i’ve missed something.
can you tell me “redirectURI” is this meant to be the same value the same as the Bookmark URL in the Edit Settings section for the app on facebook config page? I got the popup and permissions request fine first time app loads but doesnt seem to go anywhere. was there anything special in facebook settings ?
many thanks
@mike,
here are all the fb settings for my demo app
- Bookmark URL is not important for you at all
- Define Site URL and Site Domain correctly for your domain in Web Site tab
- Define redirectURI within Site Domain you defined in fb settings
that should be all the necessary. There were some comments reporting issues with connection, we were able to fix them all. go through the comments posts here using “connect” fulltext search and I believe you will find a solution.
I Jozef,
Thanks for your code, works great!
I have only one question…
There’s a way in the application to recognize te current user?
I mean, if I load this page, click connect and “log me in” in facebook as “USER A”, all works fine.
If i go to facebook and log out USER A, and then log in with “USER B”, then reload this page, all info is fetched from USER A (Not USER B who is currently logged in)
There’s a way to do this?
Thanks a lot!
Hi Pipe,
you can use FacebookOAuthGraph.me to read info about current api user. This value is filled once you are logged in. There is a separated authorization system in facebook for classic facebook.com vs. api. Api is token based, once you have valid tokens you can make api requests as any user not just the one that is logged on facebook.com. The token for FacebookOAuthGraph is saved in SharedObject (something like flash cookie) and is used with autoConnect(). You can logout api user as easy as remove the token from sharedobject, feel free to extend my lib with disconnect method() – search for “disconnect” in comments e.g. here:
hey jozef,
i try to implement your tuts about “change facebook Status” part n i’ve made it, but when i try “publishing feeds with image” part i got a problem,
i wanna ask bout these lines
var data:URLVariables = new URLVariables();
data.message = message;
data.attachment = JSON.encode(attachment);
n i got an error = 1120: Access of undefined property JSON.
what should i do? coz i noob here,,
thx before :cheers:
Hi Donny,
JSON is not a property but a class. you can import one from original adobe package
import com.adobe.serialization.json.JSON
Jozef,
how can I upload and post an image into user’s wall? As I learned from the documentation POST to /me/feed could only publish an image by URL. But I need to upload an image from user’s desktop.
Someone said that all I need is uploading by using /me/photos. But uploaded photo just saves into app’s album, with no sight in the feed.
Is there workaround for this?
Thanks
fltz,
I am sorry to tell you that only possible upload with graph api is to an album. What makes perfect sense because, there is also a “Wall Photos” album for your wall uploads. So to make your upload appear within your feed do:
1. upload photo (one album will be created as default for your facebook app)
2. publish feed linking to your upload
Really useful package. But!
You need to override the clone method in your FacebookOAuthGraphEvent class, otherwise you can’t redispatch the event (I lost some time trying to terack this down
)
public override function clone():Event
{
return new FacebookOAuthGraphEvent(type, bubbles, cancelable, _rawData);
}
—–
from
.”
Hi Paul,
thank you for your feedback, one really should override clone method when extending Event… I have updated the FacebookOAuthGraphEvent file.
Hi Jozef,
Thanks for your great code!
I just download your .fla version from () and build my own on local, I has been copy the access_token value into my code and publish. but Output error:
“Error opening URL ‘’”
I wonder are your .fla source is uptodate? or have any change on facebook make it not work?
Thanks a lot!
Nim, there are changes everyday… but, if you are trying to access data with a token, make sure its secured request – https://… !
Hi Jozef,
I have face one problem, bellow mentioned function is not call,if you have any solution can u share with me
loader.addEventListener(FacebookOAuthGraphEvent.DATA,
function(event:FacebookOAuthGraphEvent):void
{
EventDispatcher(event.currentTarget)
.removeEventListener(event.type, arguments.callee);
verifyTokenSuccess(event, token);
});
Thanks a lot.
Hi kaniskar, may this be your issue?
follow a few comments below to see… if not than try searching verifyToken in this page
Hi jozef. I m having a problem with authentification, is making an infinitive loop. When the app is trying to open. Its must be something that facebook api change because it was working until last week.
The url is
ill wait your answer.
thanks!
marc
p.s. sorry for my english, im from Argentina
Marco check out latests updates on
Hi, I have a problem with Facebook flex.
My apps is working fine but when I put a chart (any chart, either native from flex or from outside flex) on my apps, it doesn’t show up.
Anyone can help?
Thanks.
for those of you still having problems with the https/ssl of facebook, there is a solution:
the fql api of facebook has the following parameter: return_ssl_resources
So when you do an fql query for photos, etc try this:
//get thumbnails from ‘uid’ album
var data:URLVariables = new URLVariables();
data.query = “SELECT src_small” + “FROM photo ” + “WHERE aid IN ( SELECT aid FROM album WHERE owner=’”+uid+”‘ AND type=’profile’ )”;
data.return_ssl_resources = 0;
albumLoader = facebook.call(“method/fql.query”, data, URLRequestMethod.POST, null, “”);
albumLoader.addEventListener(FacebookOAuthGraphEvent.DATA, onGetAllphotos);
regards!
Hi,
Thank you so much for your hard work.
I’m testing out your flash example. But I seems to be getting erratic results after logging in and out. Sometimes it only say ‘connecting’, sometimes ‘connecting, authorizing’, sometimes ‘connecting, authorizing and uploading’. The image only successfully uploaded onto my fb ones.
I tried looking through the comments just in case you’ve already answered it, but I didn’t seem to see anyone else with the same problem?
Please help.
Maggie
hi muudles,
I am not able to reproduce any issues, it seems like example is working correctly for me. maybe you could debug request being called to see if there are any issues with connection – response by facebook
Hello,
Will this work on a mobile device, especially if I’m making a Flash app for ios?
Many thanks.
Hi Eulochi,
if ios supports StageWebView you should be able to use this source
[...] It does not provide login authentication as there are many other libraries available for this purpose and really…why re-invent the wheel? Some great examples are from Big Spaceship and Jozef Chúťka. [...]
Nice one good for flash people
Hi man,
Thanks for this source !here the issue is
i implemented expectantly in flex but i will get the same will get the same window which is visible on the top . when am clicking that button it gos to the Facebook login page other button are enabled how to share videos and images in Facebook
and how to create the like button and share button in my Flex ui
hi Rana,
for like button read this article again there is a section “Hi Is there a way to implement a “i Like” button with your class?”
for uploading images to facebook:
Great post! I will try to add this inside to my flash game.
[...] [...]
Hi,
Great post!how to get the current user session?
hi aravindakumar,
you mean FacebookOAuthGraph.token?
or you could just use this method… with the new 1.7 api ()
here’s a snippet from a game i’m building on facebook that requires permissions at a certain point in the game.. it works well
private function facebookInit():void // START THE SESSION…
{
Cc.add (‘facebookInit — v 8.0′);
Facebook.init(APP_ID, facebookInitHandler,{
appId: APP_ID,
status: true,
cookie: true,
xfmbl: true,
channelUrl: ‘’,
oauth: true,
perms: “publish_stream,email”});
}
private function facebookInitHandler(response:Object, fail:Object):void
{
if (response.accessToken)
{
userAccessToken = JSON.encode(response.accessToken);
facebookLoggedInWithToken = true;
loadProfileData();
} else {
facebookLoggedInWithToken = false;
}
}
private function loadProfileData():void
{
var request:String = ‘/me’;
var requestType:String = ‘GET’;
var params:Object = null;
Facebook.api(request, loadProfileDataHandler, params, requestType);
}
private function loadProfileDataHandler(response:Object, fail:Object):void
{
if (response) {
userID = response.id;
fullName = response.name;
firstName = response.first_name;
lastName = response.last_name;
userEmail = response.email;
userPicURL = ‘’ + userID + ‘/picture’;
}
}
enjoy!
Hi Jeff! I was seeing some new stuff from facebook and I saw this article:
I’ve tried to do a feed with that code: attachment.description = “Friend: @[{uid}:1:{name}]”
Didn’t work. I wonder if you already tried this successfully?
hi PVieira,
I have not tryed it yet myself… however
“I’ve tried to do a feed with that code: attachment.description = “Friend: @[{uid}:1:{name}]”” … I believe it works only on message feeds, not attachments
Thanks for the answer Josef. I tried also in data.message so it seems it really doesn’t work.
Is there a way to send a message to a user friend? Some notification that my app is using his data?
notifications are depricated, see
Yes, I saw that information in other forum. So there is no alternative? That sucks but I understand facebook position.
can anybody guide me how to invite friends for events using graph api ( post method ) in c# example.
All seems to work great! I can post photo’s from my flash App to facebook
Although my Facebook permission window is opened in a new tab, not a nice small popup. What can this problem be? Thanks in advance people.
hi Sam, if this also happens for you with the flash example in this blog post than it is related to your webbrowser. else make sure the window in your code is opened via javascript:window.open
I using the the code above and so far all is great (Many thanks) How would I go about having the post to an image where by the pop up to add additiona text to your wall is present.
Thanks
hi Gil, please read and comments under, there is a lot of useful stuff and tips
is there an updated facebook app settings configuration now that facebook has changed it?
Henry, I have updated those in article, I hope it helps you
Hi,
Once again I am using it, and once again great job!
I translated your sample to flash builder 4.6 style, tell me if you need the code.
*mail me
i got the flash c4 source code and when i run in flash ide i got the follow message:
Error #1065: A variável com.adobe.serialization.json::JSON não foi definida.
at sk.yoz.events::FacebookOAuthGraphEvent/get data()[C:\facebook_11\cs4\src\sk\yoz\events\FacebookOAuthGraphEvent.as:36]
at sk.yoz.net::FacebookOAuthGraph/verifyTokenSuccess()[C:\facebook_11\cs4\src\sk\yoz\net\FacebookOAuthGraph.as:108]
at Function/()[C:\facebook_11\cs4\src\sk\yoz\net\FacebookOAuthGraph.as:100]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at sk.yoz.net::FacebookOAuthGraph/loaderComplete()[C:\facebook_11\cs4\src\sk\yoz\net\FacebookOAuthGraph.as:186]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
help me please
norberto, I think you are missing JSON library. try downloading it from
hi jozef
I am using your code for facebook authantication and it perfactly run but i am faceing problem regarding facebook access token url,when we run our app on facebook we get a authantication popup .my question is you without opening the popup can we get access token.
i am using this code in flash and in flash side we call “advancedcallback.html” .can we use php side code for access token handling?if yes,please guide me how we write that
hi aarti, you should be able to access token on php, there is an php api documentation on , sending access token from php to flash can be done via flashvars … see “add hash” button functionality in my example
hi jozef
Once again i am here with my problem.actually jozef i had tried to solve the access token according to your suggestion but our team want to solve this problem in flash side completely,can you please suggest me how we get access token without open the popup.
when we run our app on crome and if my popup setting is blocked ,in this case authantication popup does’nt open and my app is autherized completely and i get my all friends information,but when i run my app on mozzila and ie browser and we blocked our popup setting, in this case our app does not autherized and we do not get any friends information,so in this case my functionality do not work and its a big issue ,that’s why i want to try to get access token without opening any popup.
if you have any solution please suggest me .
aarti, in order to get access token you must visit facebook page with authorization for your app. you can do it in popup or redirecting whole page (I would expect frames to not to work to avoid clickjacking). offline access seems to be depricated so user will have to reauthenticate with every new session – popup or redirect
Hi,
Thanks for your project ! I got same problem about open a small popup window. It just open up a new tab or window. I looked into the Class, it looks ok !
Wonder if there’s other MUST HAVE js code in html ?
public function connect():void
{
if(!tokenCallbackDefined)
{
tokenCallbackDefined = true;
ExternalInterface.addCallback(jsConfirm, confirmConnection);
}
var id:String = ExternalInterface.objectID;
var url:String = authorizationURL;
var name:String = jsWindowName;
var props:String = “width=670,height=370″; + “}”);
}
Hi Ttcat,
you do not need to have any additional code in javascript, you can define all needed via ExternalInterface, just make “Make sure your html wrapper defines correct allowScriptAccess and both id and name for
will you please resolve my query i have implemented your code it is connected with the application but not authrized…this function not call and add hash is also not called..
so please resolve my query..
My flash code is not connected with my Facebook application. I can not resolve the error and not getting the error that what and where is the problem..
on click the connect button the window show my application on logging into the account it appears the message
“You may now close this window.”
not connected with the application..
I can’t debug ma flash application..
please give me some solution how to resolve it..
Hi Vaishali,
I have no idea what might went wrong based on your description. I suggest you debug flash callback method as well as javascript part.
I used your above code my application perfectly run and update the status, now i want to add the additional feature for uploading the photo using the above code…
Can u send me the code to upload the photo on Facebook just like to update the status on the above code..
Thanx in advance….
hi Vaishali, have a look at | http://blog.yoz.sk/2010/05/facebook-graph-api-and-oauth-2-and-flash/ | CC-MAIN-2014-10 | refinedweb | 22,676 | 65.12 |
hack to allow react-native projects to use node core modules, and npm modules that use them.
However, with bigger projects that don't reimplement every wheel from scratch, somewhere in your dependency tree, something uses a core node module. I found myself building this because in my React Native app, I wanted to use bitcoinjs-lib, levelup, bittorrent-dht, and lots of fun crypto. If that sounds like you, keep reading.
rn-nodeify --installinstalls shims for core node modules, see './shims.js' for the current mappings. It recurses down
node_modulesand modifies all the
package.json's in there to add/update the
browserand
react-nativefields. It sounds scary because it is. However, it does work.
rn-nodeify --hackNow that you're scared, I should also mention that there are some package-specific hacks (see './pkg-hacks.js'), for when the React Native packager choked on something that Webpack and Browserify swallowed.
If you're looking for a saner approach, check out ReactNativify. I haven't tested it myself, but I think philikon will be happy to help.
rn-nodeify
--install install node core shims (default: install all), fix the "browser" and "react-native" fields in the package.json's of dependencies --hack hack individual packages that are known to make the React Native packager choke --yarn use yarn instead of npm
# install all shims and run package-specific hacks rn-nodeify --install --hack
# install specific shims rn-nodeify --install "fs,dgram,process,path,console"
# install specific shims and hack rn-nodeify --install "fs,dgram,process,path,console" --hack
It is recommended to add this command to the "postinstall" script in your project's package.json
"scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "postinstall": "rn-nodeify --install fs,dgram,process,path,console --hack" }
rn-nodeify will create a
shim.jsfile in your project root directory. The first line in index.ios.js / index.android.js should be to
importit (NOT
requireit!)
import './shim'
If you are using the crypto shim, you will need to manually uncomment the line to
require('crypto')in
shim.js, this is because as of react-native 0.49, dynamically requiring a library is no longer allowed.
Some shims may require linking libraries, be sure to run
react-native linkafter installing new shims if you run into problems.
copied from react-native-crypto
Install and shim ```sh npm i --save react-native-crypto
npm i --save react-native-randombytes react-native link react-native-randombytes
npm i --save-dev [email protected]
./node_modules/.bin/rn-nodeify --hack --install ```
rn-nodeifywill create a
shim.jsin the project root directory
js // index.ios.js or index.android.js // make sure you use `import` and not `require`! import './shim.js' // ...the rest of your code import crypto from 'crypto' // use crypto console.log(crypto.randomBytes(32).toString('hex'))
npm link.
rm node_modules/*/.babelrc)
npm run postinstall)
rm -fr $TMPDIR/react-*)
node_modulesto disappear. See: | https://xscode.com/tradle/rn-nodeify | CC-MAIN-2022-05 | refinedweb | 487 | 50.63 |
Your mongoid.yml has an error "hosts:" key should be inside of "default:"
because it is a required configuration for sessions
Please check
First, you can create a new rails project without triggering bundler:
rails new foo --skip-bundle
Next, you'll have to edit the Gemfile and manually set the gem versions to
those that you have installed on your machine. Using pessimistic operator
~> is fine. Example:
gem 'rails', '~> 4.0.0'
Then install the gems on your local machine with bundler:
bundle install --local
Pointers inherited from a block are considered "read-only". In order to
modify the value you need to prefix it with __block. In your case you
cannot prefix value with __block because it's an argument. Even if you
could, your GCD block is asynchronous, and would return before your CGD
block was called.
For what you're trying to do, you need to do something like this:
- (void)doSomethingIntensive:(NSNumber *)value complete:(void (^)(NSNumber
*result))complete
{
dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(queue, ^{
if (complete) complete(@(value.integerValue + 1));
});
}
You would call such a function like this:
[doSomethingIntensive:@(1) complete^(NSNumber *result) {
NSLog(@"%@", result);
});
The general
Solved.
Aash Dhariya helped to solve this in the mongoid google groups.
I did change reviews_controller.rb:
class ReviewsController < ApplicationController
def index
@product = Product.find(params[:product_id])
@reviews = @product.reviews
end
end
and app/views/reviews/index.html.erb:
<h1>Reviews</h1>
<% @product = Product.find(params[:product_id]) %>
<table>
<tr>
<th>Content</th>
</tr>
<% @reviews.each do |review| %>
<tr>
<td><%= review.content %></td>
</tr>
<% end %>
</table>
<br />
Now it's showing the reviews on a separate page! :)
you have to pass params you can use update_attributes or update_attributes!
@user = User.find(params[:id])
if @user.update_attributes!(params[:user])
...
Well, instead of making a workaround, why dont we migrate the old ones?
First, change both models to embed by replacing has_one with embeds_one and
replacing belongs_to with embedded_in. Save the code.
Then use your rails console (>> rails console)
Then
Output.each do |o|
if !o.task_id.nil?
#change to embedded format
t=Task.find(o.task_id)
t.output=o
t.output.task_id=nil
t.save
end
end
Try changing like this
Easyblog::Application.routes.draw do
resources :posts do
resources :comments do
match :vote
end
member do
post :mark_archived
end
end
end
You're looking in the wrong places. The error is saying there's something
wrong with your config/routes.rb file. Rails is not being able to figure
out what URL matches the show method in your controller.
Apparently rails generate scaffold_controller does not edit the routes.rb,
so you'll have to do it by hand and add the following code to it:
resources :tipocontenidos
There's a great tool to debug Rails routing here:
More about routing:
Ok, I have found the problem.
First of all, I assume you are using Rails 4. The reason you are getting
this error is that attr_protected and attr_accessible have been removed
from Rails 4 and placed in their own gem. Rails is now encouraging a new
protection model. You can read about this in the README. If you would like
to continue using the old behavior, you must include the
protected_attributes gem. Hope that helps.
EDIT: I've added clarification below since this is likely to be a common
problem with users to upgrading to rails 4.
If you would like to continue using attr_accessible, i.e. the Rails 3 way,
simply add gem protected_attributes to your Gemfile.
If you would like to start doing things the Rails 4 way, you must no longer
use attr_accessible. Instead, you must move the at
usually the log files should be at /var/log/mongodb.log or try find / -name
mongodb.log.
usually it keeps data at /data/db.
To know more about where does it store data please visit How is the data in
a MongoDB database stored on disk?
You're missing a semi-colon at the end of your cursor:
CURSOR employees_in_10_cur
IS
FROM ad_week_table;
The error message will always give you the line number of the error
occurring. Please always check this and look in that area.
For instance; if I change the table so I can run this I get the following:
SQL> declare
2
3 cursor employees_in_10_cur is
4 select *
5 from user_tables
6
7 begin
8 for employee_rec in employees_in_10_cur loop
9 dbms_output.put_line (
10 employee_rec.ad_no || ',' || employee_rec.week_no );
11 end loop;
12 end;
13 /
for employee_rec in employees_in_10_cur loop
*
ERROR at line 8:
ORA-06550: line 8, column 8:
PL/SQL: ORA-00905: missing keyword
ORA-06550: line
There is a tutorial about how to create a messaging system. The url is not
longer available. But you can give this a try:
The book isn't Rails/Ruby/Mongoid specific but the concepts should
translate fairly easy for you. Rick is an avid Python guy and strong member
of the MongoDB community. In his book there's actually a whole chapter in
there dedicated to creating a social follower/following style model.
Hope that helps.
Edit: This presentation on "Advanced Schema Design" may be of use to you
also. I'm going to be doing a blog post on this topic in the near future,
but you can get most of the content here form Jared's talk.
The collection methods seem to be a common gotcha in rails, I wrote a blog
Although it's about collection_select, it applies to checkboxes too. This
should be a step in the right direction
= form.collection_check_boxes :neighborhoods, Neighborhood, :id, :name
Hope this helps.
Cursors in mongodb are latent by default. This means that if further writes
come in while you are processing the cursor then you may or may not see the
results of these updates.
Baiscally as more data is added or existing data is modified the object may
move around the collection which may causes them to appear in the cursor
multiple times(the actual behaviour is unspecified).
You can use pass mongoid the snapshot option in your query to fix this
problem.
(You could also use the hint option specifying the '_id' index.)
Based on your question i have created a sample. Please try this will some
times helps you. Please share your code. So that we can help more
private void Form1_Load(object sender, EventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 10; // Maximum should be based on your value
}
private void button1_Click(object sender, EventArgs e)
{
if (progressBar1.Value < progressBar1.Maximum)
{
progressBar1.Value += 1;
}
}
The problem was in the form, it should be user_form.fields_for :cards
instead of :health_cards
Below is the corrected version
= form_for @user do |user_form|
= user_form.fields_for :cards, @health_card do |hc_form|
= hc_form.text_field :number
= user_form.submit 'Next'
The userAdminAnyDatabase role doesn't quite do what you might think it
does. Here's what the MongoDB docs say about it:
Important: Because users with userAdminAnyDatabase and userAdmin have the
ability to create and modify permissions in addition to their own level of
access, this role is effectively the MongoDB system superuser. However,
userAdminAnyDatabase and userAdmin do not explicitly authorize a user for
any privileges beyond user administration.
Giving the user you created the userAdminAnyDatabase role, actually only
allows them to administer the database (create new users, remove users,
access system.* collections) but it doesn't actually authorize them to read
or write any data.
If you want to create a super user who has all admin privileges and can
also read and write in
You can write:
def self.search(search)
if search
any_of({name: /#{search}/i}, {hobby: /#{search}/i})
end
end
That will give you all objects that include this value, with ignoring
case-sensitive.
About adding search by date range.
Send to your controller an additional value - for example ~ search_to.
def index
@parents = if params[:search]
Parent.search(params[:search], params[:search_to]) # when searching
name/hobby, params[:search_to] will be nil
else
Parent.all
end
end
Your search function:
def self.search(search, search_to)
if search && search_to
where(:born => {'$gte' => Date.parse(search),'$lt' =>
Date.parse(search_to)})
elsif search
any_of({name: /#{search}/i}, {hobby: /#{search}/i})
end
end
Question 3 - I don
This is not a good/safe way to maintain profile views. If there are many
people viewing you could have race conditions.
There is a highly sophisticated gem called 'impressionist'.
(). Use it. You will have
access to lot of features like getting unique profile views based on User,
or IP, or session hash etc.
in this code you are creating a parent item per child:
$.each(data, function(index, item){
results.push({
text: item.parent,
children: [{id: item._id, text:item.title}]
});
});
instead, you should group by parent:
var hashtable={};
var results=[];
$.each(data, function(index, item){
if (hashtable[item.parent]===undefined) {
hashtable[item.parent]={text:item.parent, children:[]};
results.push(hashtable[item.parent]);
}
hashtable[item.parent].children.push({id:item._id,text:item.title});
});
It may not be very elegant, but a counter in the parent view should do it:
view:
<% index = 1 %>
<%= f.fields_for :levels do |builder| %>
<%= render 'level_fields', {f: builder, index: index} %>
<% index = index + 1 %>
<% end %>
partial:
<%= f.label :title, "Level #{index}"%>
desc is a rake method. you can either require 'rake', or remove:
remove:
require "dotenv/tasks"
There doesn't appear to be any reason to do that.
Check it once
if params[:vote][:type] == "up"
answer = Answer.find_by_id(params[:vote][:id])
answer.to_i.increment(:ups)
render text: answer.ups
elsif params[:vote][:type] == "down"
answer = Answer.find_by_id(params[:vote][:id])
answer.to_i.increment(:downs)
render text: answer.downs
end
It seems rmongodb cannot really handle operators embedded in other operator
when aggregating. I faced the same issue when using $substr in $group.
Try only one operator in a stage. If it is not possible, I can recommend
RMongo package as an alternative.
dbAggregate(
mongo, "db", '{
$project : {
y : 1,
x : {$cond : [{ $ne : ['$x', NaN] }, '$x', 0]}
}
}')
Actually, all queries have a timeout by default. You can set a no_timeout
option to tell the query to never timeout.Take a look here
You can configure the timeout period using a initializer, like this
Mongoid.configure do |config|
config.master = Mongo::Connection.new(
"localhost", 27017, :op_timeout => 3, :connect_timeout => 3
).db("mongoid_database")
end
It looks like you started Diaspora two times.
First make sure to you have Diaspora and your other projects alongside each
other, not nested.
~/Diaspora
~/Projects
Then change into your projects folder, get the latest version of Rails and
create a new project:
cd ~/Projects
gem install rails
rails new project2
cd project2
bundle install
There start your other project first:
cd ~/Projects/project2
bundle exec rails server -p 3002
Now in a second shell start Diaspora:
cd ~/Diaspora
bundle exec rails server -p 3001
Make sure to use bundle exec to avoid any version conflicts between the
gems Diaspora uses and the gems your new application uses.
Your parenthesis are not in the correct places. A parenthesis, unless
quoted, are the start of a function application.
It begins with a variable cond that is not bound. It's not the special form
(cond (predicate consequent) (predicate2 consequent2)) since it doesn't
start with an open parenthesis.
From indentation alone I guess you meant to write:
(DEFUN testAL (x)
(COND ((ATOM x) 'this-is-an-atom)
((LISTP x) 'this-is-a-list)
(T 'this-is-neither)))
(testal 'test) ; ==> THIS-IS-AN-ATOM
(testal '(a b c)) ; ==> THIS-IS-A-LIST
I have removed the extra parenthesis around x since (x) means apply the
function x while x means the variable x. With x in a different position
like (+ x 3) then + is the function to be applied and x is one of its
operands.
I chan
First, I must say this is not a good practice, but I will only focus on a
solution for your problem:
You can always get the organisation's posts count by doing on your
PostsController:
def create
post = Post.new(...)
...
post.post_id = Organization.find(organization_id).posts.count + 1
post.save
...
end
You should not alter the database yourself. Let ActiveRecord take care of
it.
Depending on your terminal you can use File->new tab, or maj+ctrl+t to pen
a new tab.
Personally i have one tab for the server, one for the tests using guard,
one for the console and one to have an actual shell.
This one seems to work fine for me, give it a try:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}s([^.]+).(html|phtml) [NC]
RewriteRule ^ %1 [R=301,L]
# To internally forward /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^/]*)/?$ $1.html [L]
# To internally forward /dir/foo to /dir/foo.phtml
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.phtml -f
RewriteRule ^([^/]*)/?$ $1.phtml [L]
It looks like you need to include the module in each model and set the
observers.
class ORM
include ActiveModel::Observing
end
# Calls PersonObserver.instance
ORM.observers = :person_observer
# Calls Cacher.instance and GarbageCollector.instance
ORM.observers = :cacher, :garbage_collector
# Same as above, just using explicit class references
ORM.observers = Cacher, GarbageCollector
This is because, in your system there is rails 2 also installed and rails 2
is your default rails. The syntax for creating project in rails 2 is simply
"rails project_name" that's why every time you are running **rails** either
for generating controller, model or anything...the project is creating
uninstall ruby and rails completely and follow this link to install rails
in your system:
How to install Ruby on Rails on linux OR
Oh! I forgot to tell, you can install Ruby Version Manager (RVM) instead.
may be this can help
Perhaps you defined the block in a .h file, so that it is defined in every
.m file
that imports this .h file?
You have to declare it in a .h file:
typedef NSComparisonResult(^UITagCompareBlock)(UIView*, UIView*);
extern UITagCompareBlock uiTagCompareBlock;
and define it in exactly one .m file:
UITagCompareBlock uiTagCompareBlock = ^NSComparisonResult(UIView* a,
UIView* b){
if (a.tag < b.tag) return NSOrderedAscending;
else if (a.tag > b.tag) return NSOrderedDescending;
else return NSOrderedSame;
};
You need to add the Microsoft.Bcl.Async NuGet package.
These packages were previously unavailable on non-Microsoft platforms, but
as part of the Xamarin collaboration Microsoft relicensed them to be usable
under all platforms.
Like the comment says, it's internal state the macros use to remember where
they are and what they're doing. Nothing you need to worry about unless you
are reimplementing the code, in which case the complete lack of
documentation apart from that comment and the general coding style suggest
you might have a problem.
As it's static it is only accessible from that file (God help you if that
code is from a header) and it has a lifetime the same as the executing
program.
But basically, you should not touch _O in your code.
Roughly:
def needs_clearance(level, &block)
if current_user.clearance >= level
capture(&block)
end
end
Block helpers generally look like the following, e.g., to wrap something in
a div:
def box(&block)
"<div class='box'>" + capture(&block) + "</div>"
end
From:
I'd consider reading that, too, as it discusses an interesting consequence
of block helpers.
You can use the indexOf method on the String, and then do substring for the
characters after.
int start = yourString.indexOf(searchString);
System.out.println(yourString.subString(start + 1, start + 6);
I just solved the problem .
Query query = Query.parse(searchQuery, conf);
QueryParams queryParams = new QueryParams();
queryParams.setMaxHitsPerDup(100);
queryParams.setNumHits(100);
query.setParams(queryParams);
Hits hits = bean.search(query);
long allResultsCount =**hits.getTotal());**
I changed this into
long allResultsCount =**hits.getLength());**
I ended up just going to the index action of my pages controller and adding
a raise ActionController::RoutingError.new('Not Found'). Goes one level
deeper but the result is the same nonetheless. | http://www.w3hello.com/questions/how-to-increment-the-conuter-in-project-block-in-mongoid-using-cond-keyword-in-rails | CC-MAIN-2018-17 | refinedweb | 2,642 | 58.08 |
This is for an original object, not something imported…
You make an object, you mirror it to make the reverse object (great for hair)...
now you need to mirror the morphs. this works, just tested it. The problem is placement. When I exported the objects to OBJ, the placement of the mirrored object moves in DS… hmmm… not good.
Anyone know how to make sure your morph target, when you mirror it, does not move the object?
My DeviantArt Galleries
My ShareCG Gallery
OPENSUBDIV Testing and Discussion
3Delight Surface and Lighting Thread
Need a lot more info on your workflow:)
As I understand your explanation, you made an object in Hex, did a symmetry mirror copy, saved as .obj and imported to D/S?
Did you then send it to Hex via the bridge to make morphs and on sending back to D/S something moved from the original position?
When you made the original, did you center it at all XYZ = 0?
When you made the morph/s, did you move the position of anything?
Some screencaps would help:)
My ShareCG freebies
okay. Create a plane. Mirror it. Export the mirrored object
edit the plane’s shape. Mirror that. The mirrored object will change shape.
Export the mirrored object again.
import the first OBJ into DS, then apply the second as a morph target.
You will see what I mean…
I’m not sure what centering will accomplish, because if you change the shape of an object in HEX, the center of that object changes.
OK - I did that - the morph imported perfectly into Studio, no changing of position.
The questions I asked were to try and get a handle on what may be the problem.
another double post.
Cheers, Fanners.
I’m not sure what centering will accomplish, because if you change the shape of an object in HEX, the center of that object changes.
Oh no, it doesn’t/shouldn’t. What Roy was saying is that the edge that denotes the interface of the half that is to be mirrored, must lay along either the X Y or Z axis ( = 0) depending which way you are mirroring it.
Changing the shape/size of the object should not change the position of the interface between the two half’s. If it does, YOU must ensure all the verts line up to either the x y or z before you mirror/weld/transfer/export it.
Yes, I never suggested that centering - which refers to the position of the mesh where X, Y, Z =0 and does not change when you change the shape of the mesh - would fix the problem. I merely asked whether you had, in fact, done this:)
The only way I could get the position of the mesh to change when applying the morph was to change the X, Y, Z position of the target mesh in Hex.
What is it you want to do using Hexagon? | http://www.daz3d.com/forums/viewthread/18802/ | CC-MAIN-2015-14 | refinedweb | 492 | 80.11 |
Overview of if Statement
An if statement consists of a boolean expression followed by one or more statements. C.
Syntax of if statement:
if (condition/boolean expression) { //Block of C statements here //These statements will only execute if the condition is true }
In this statement, if condition is true then statement are execute and if is false, then statement are not execute.
As a general rule, we express a condition using C's relational operators. The relational operator allow us to compare two values to see whether they are equal to each other, unequal, or whether one is greater thanthe other.
Flow Diagram
Fig- Flow Diagram of if statement
Example:-
#include <stdio.h> int main() { int number; printf("Enter an integer: "); scanf("%d", &number); // Test expression is true if number is less than 0 if (number < 0) { printf("You entered %d. ", number); } printf("The if statement is easy."); return 0; }
Output:
Enter an integer: -2 You entered -2. The if statement is easy. | http://www.cseworldonline.com/tutorial/c_if_statement.php | CC-MAIN-2019-18 | refinedweb | 163 | 53.92 |
excuse my caps…
Today is August 21st — the Summer of Code deadline.
It’s been a pretty fun ride. I’ve been getting up close and personal with the gnome-panel code in ways that I wouldn’t previously have imagined to be possible.
I’ve been working on an API for applets. In addition to this API, I’ve written an implementation of a client-side library for this API and in-panel code for this library to communicate with.
The communication is done by way of DBUS and XEmbed. The API has been constructed in such a way, however, that other than GTK itself, all underlying implementation detail is invisible. If DBUS should fall out of fashion, it will be possible to replace the back-end implementation without an API shift. This is not the case for the current applet system which is very much tied to Bonobo.
Note: the API is UNSTABLE. It will change. I promise.
From the standpoint of the user (applet writer) a class is provided named GnomeApplet. You subclass this class to create your own types of applets. To give a feel for this API, I will present an example of a very simple applet.
The applet in question is a simple clock. An icon has been added for demonstration purposes.
I’ll assume for the sake of simplicity that the following function has been provided:
const char *format_current_time (gboolean seconds, gboolean _24hour);
This function returns a string representing the current time either in 24 or 12 hour format and with or without seconds.
The code of the applet is included here:
#include <libgnome-applet.h>
GNOME_APPLET_DEFINE (ClockApplet, clock_applet,
gboolean _24hour;
gboolean show_seconds;
);
static gboolean
update_time (ClockApplet *clock)
{
gnome_applet_set_text (GNOME_APPLET (clock),
format_current_time (clock->show_seconds, clock->_24hour));
return TRUE;
}
static void
update_boolean (GnomeApplet *applet, const char *key,
gboolean value, gpointer user_data)
{
*(gboolean *) user_data = value;
update_time ((ClockApplet *) applet);
}
static void
clock_applet_initialise (ClockApplet *clock)
{
GnomeApplet *applet = GNOME_APPLET (clock);
gnome_applet_set_name (applet, "Clock Applet");
gnome_applet_set_persist (applet, TRUE);
gnome_applet_add_dropdown_widget (applet, gtk_calendar_new ());
gnome_applet_set_image_from_stock (applet, GTK_STOCK_YES);
gtk_timeout_add (1000, (GtkFunction) update_time, clock);
gnome_applet_config_watch_boolean (applet, "24hour", update_boolean,
&clock->_24hour, NULL);
gnome_applet_config_watch_boolean (applet, "24hour", update_boolean,
&clock->show_seconds, NULL);
}
The first thing to notice is the GNOME_APPLET_DEFINE line. In its simple form, this line is like a G_DEFINE_TYPE instantiation minus the parent class (since the parent class is always GnomeApplet).
For example:
GNOME_APPLET_DEFINE (ClockApplet, clock_applet);
However, this macro aims to reduce your typing for you. As such, you do not need to define structures for your class. If you want additional items in these structures (other than the parent class) then you give them using the syntax seen in the example code.
The update_time function is uninteresting. It shows that the fields defined in the extended syntax of
GNOME_APPLET_DEFINE are accessed as you’d expect them to be. It also shows use of the
gnome_applet_set_text function.
The new applet API is a hybrid API. As a subclass of
GtkContainer, you can
gtk_container_add a widget to the applet and it will be displayed on the panel. You are much more likely, however, to want to use the set_text and set_image functions.
The first time you use a set_text or set_image function the applet will internally create a
GnomeAppletLayoutBox and add it to itself. It will then request the creation of the image or label inside of this box.
The
GnomeAppletLayoutBox system allows you to easily create applets that feature 0 or 1 icons and 0 or 1 text labels. In addition, it gracefully handles horizontal and vertical panels and drawers of varying thickness.
The label that is created is not a
GtkLabel, but rather a
GnomeAppletLabel.
GnomeAppletLabel has some functions that make it easier to use than a simple
GtkLabel for purposes of putting in a
GnomeAppletLayoutBox. The most noticeable feature of a
GnomeAppletLabel, however, is that when placed on a coloured, pixmap or transparent panel, it shows a drop shadow like Nautilus shows on its desktop contents.
update_boolean is not a very interesting function either. It simply updates a boolean value pointed at by the
user_data parameter and calls
update_clock. The need for functions like this may disappear as the API becomes more developed.
clock_applet_initialise is the most important function here. When you use
GNOME_APPLET_DEFINE the 2nd parameter has
_initialise added to it and this is the name of the only function that you must implement.
This function is NOT a normal
GObject init function. It would be called
clock_applet_init if that were the case. This function is, rather, called after the object has been entirely constructed and connected to the panel. This means that you can perform function calls from it which query the state of the panel.
We perform a number of calls here:
gnome_applet_set_name tells the panel the name of the applet. This is used in UI that the user sees concerning the applet. For example, of the applet were to unexpectedly exit, the message dialog shown would be customised with the applet’s name.
gnome_applet_set_persist registers the applet as a persistent applet. When an applet is first created it is non-persistent. This means that the applet can come and go as it pleases. The panel will make no attempt to start the applet on login and won’t complain if the applet just vanishes. This behaviour is useful for programs like Gossip or Muine, where the life of the applet is tied to the life of the application, rather than the life of the session. It is also useful for applets that wish to come and go as hardware is added or removed.
If an applet is marked persistent then its current path is noted down in the panel’s GConf tree. On login the applet will be invoked and asked to join the panel at its previous location.
gnome_applet_add_dropdown_widget is a new feature. When passed a
GtkWidget, this function will add the widget to a dropdown display. Many applets would or currently do benefit from this functionality. For the clock, it makes sense to have a dropdown calendar. For the weather applet you could have a dropdown detailed forecast. For the mixer, a dropdown slider. If a dropdown is registered then it is displayed when the left mouse button is clicked. If the user moves their mouse from applet to applet while a dropdown is displayed then the dropdowns of the different applets are displayed.
gnome_applet_set_image_from_stock sets the image shown with an applet. There are functions for setting from stock, from file, from icon theme, from pixmaps and from pixbufs. See the discussion above about GnomeAppletLayoutBox.
gtk_timeout_add is
gtk_timeout_add.
gnome_applet_config_watch_boolean is showing a very small part of the configuration system that exists. It was decided, for a number of reasons, that applets would not link against GConf. It is still possible to do this for yourself and use GConf functions with your applet, but this behaviour is not recommended. All configuration requests are, instead, sent to the panel via DBUS.
There are a number of reasons for this:
- The configuration information associated with an applet should be tied to the panel (as it is now). The panel might be using a different configuration system then the applet. (think: mixing KDE, xfce, GNOME).
- If GNOME itself shifts configuration systems, the GConf API is completely hidden. (think: you won’t need to rewrite your applet).
- There is a memory savings associated with not linking to GConf in every applet, not firing up the machinery in every applet and not having a server-side connection for every applet.
- There is an additional benefit interms of load time. Since the panel can preload all of the information for all of the applets in a single roundtrip to the GConf daemon, the number of roundtrips is reduced. This means less contention for a heavily contended resource.
There are a few unfortunate effects:
- You can not store pairs or lists. Only values which fit in a GValue are supported. I could add more API, but the point is to not expose GConf-specifics.
- I had to do a lot more typing. More typing introduces the possibility of more bugs and certainly, the interface won’t share the exact semantics of GConf.
In general, there are 5 flavours of each function. One for each of GValue, string, int, boolean, double. I’ll introduce the integer variants:
gnome_applet_config_get_int- gets a key of a given name and returns it in a pass-by-reference variable. This function returns TRUE if the key existed or FALSE if it did not.
gnome_applet_config_get_int_default- gets a key of a given name and returns it. If the key did not exist then a user-provided default value is returned.
gnome_applet_config_set_int- sets a key of a given name to a given value. Returns TRUE if successful.
gnome_applet_config_watch_int- registers a watch function on a given key. A user_data (with corresponding destroy notify) field is also given. When this function is first called, a synthetic notify event is immediately generated. You can, therefore, use this function to initialise variables without having to manually call one of the ‘get’ functions.
There is more API than shown here, but this should give a good overview of the general flavour. This project is not yet done! The following features are planned to be completed before GNOME 2.18 when, if all goes well, this code will ship as part of gnome-panel.
Immediate TODOs:
- gtk-doc for the client-side API with the documentation posted on developer.gnome.org
- integration of Vytautas’ work to make multiple instances of the same applet use the same process
- support for dynamic loading of applets into the panel to further reduce memory use
- improved support for finding and loading persistent applets (the path for invoking applets on startup is currently hard-coded to my working directory)
Other TODOs:
- gather feedback from early adopters of the API. What needs to change? Can there be some more convenience functions?
- look into language bindings (python and C# are likely early candidates)
- bug fixes! I can’t even imagine how many bugs are in the code. It will take time to reveal them all and get the code to be stable enough for general use.
A recent version of the code is usually available at. I’m going to wait until after the GNOME CVS branches 2.16 stable until I commit the code to CVS HEAD.
6 Comments
if this is adopted in 2.16, since already in 2.14 gnome-vfs uses D-Bus and not bonobo anymore, what will be left in GNOME which uses bonobo/CORBA? (this is not meant to be aggressive, just being curious).
make my 2.16 a 2.18 and 2.14 a 2.16 from in previous comment.
gnome-panel will use bonobo. the two APIs will co-exist for some time. (at least until 2.20). you can’t quite ditch bonobo just yet :)
Ryan, this looks good. From a gnome-power-manager perspective, can an application add itself as an applet to the panel using your framework, or do we still have to do this manually?I’m thinking average user: 1. installs gnome-power-manager
2. logs out. Logs back in.
3. gnome-power-manager automatically starts
4. applet/notification icon appears in panel. rather than:
3a. user is asked to manually add an applet
4. applet appears.
yes. this is absolutely how it works. the gnome-panel exports an interface called AppletServer where remote clients can request that an applet is created on their behalf. this means that applets can come and go as they please.there is still some debate about what happens for non-persistent applets that want to come and go as they please (ie: not be auto-loaded by the panel). currently i explicitly include code to remove these applets on panel-startup (ie: their info is deleted from gconf). removing this code to allow, for example, gnome-power-manager to remember its previous location on the panel would be trivial but i’m not sure how i should go about doing this. suggestions are welcome.
What about notification area items? Their usecase seems to overlap about 1000% with the “non-persistent” applets. | http://blogs.gnome.org/desrt/2006/08/21/your-domain-lowercaseca-is-expiring/ | crawl-002 | refinedweb | 2,023 | 65.93 |
The idea is that when rotating the array, there must be one half of the array that is still in sorted order.
For example, 6 7 1 2 3 4 5, the order is disrupted from the point between 7 and 1. So when doing binary search, we can make a judgement that which part is ordered and whether the target is in that range, if yes, continue the search in that half, if not continue in the other half.
public class Solution { public int search(int[] nums, int target) { int start = 0; int end = nums.length - 1; while (start <= end){ int mid = (start + end) / 2; if (nums[mid] == target) return mid; if (nums[start] <= nums[mid]){ if (target < nums[mid] && target >= nums[start]) end = mid - 1; else start = mid + 1; } if (nums[mid] <= nums[end]){ if (target > nums[mid] && target <= nums[end]) start = mid + 1; else end = mid - 1; } } return -1; } }
I have one question:
Why don't consider the case "nums[start] > nums[mid]" and "nums[mid] > nums[end]"?
You want to zero in onto a sorted region without confusing yourself by having 1 pointer in 1 sorted region and the other pointer in the other. The array can be seen as 2 separate sorted regions. Both the cases described above handle each of these regions: i.e. either target will be between start and mid or between mid and end. The cases that you have cited are covered in these 2 cases. For example, nums[start] > nums[mid] when start is in the 1st sorted region and mid is in the 2nd sorted region. When this happens, nums[mid] < nums[end].
Not until reading your code that I realized when leetcode says an array is sorted,it means non-descending order...Thanks anyway and well done with your excellent work ! But I think it's better to use "else" than "if (nums[mid] <= nums[end])" , just personal opinion ; )
Hi @tjbstuff, here is my simple technique (actually it is quite common!!). when performing search:
while (left < right-1) { ... if (target < nums[mid]) { right = mid; } if (target > nums[mid]) { left = mid; } ...}
after that, you just need to do some simple post-processing:
if (nums[left] == target) { return left; } if (nums[right] == target) { return right; } return -1;
Except for the most standard binary search, when coming to first/last occurance etc., this simple trick will make your life a lot easier.
C++ version of the solution.
class Solution { public: int search(vector<int>& nums, int target) { int i = 0, j = nums.size()-1; while(i < j){ int mid = i + (j-i)/2; if(nums[mid] < target){ if(target > nums[j] && nums[mid] <= nums[j])j = mid; else i = mid+1; } else if(nums[mid] > target){ if(target < nums[i] && nums[mid] >= nums[i])i = mid+1; else j = mid; } else return mid; } return nums[i] == target?i:-1; } };
The solution has two if's inside the loop which modifies the start and end variable I think it could be if and else, because it seems as if both the if statements would be executed but actually only one of the both gets executed at any iteration.
it's told that the array is sorted, but not mention whether it's sorted by desc. Give one test case, [3,2,1,5,4], target=2. Your solution return -1...
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/16580/java-ac-solution-using-once-binary-search | CC-MAIN-2018-05 | refinedweb | 574 | 69.41 |
1. Download Nafees Nastaleeq Urdu font from CRULP.
2. Copy the font in C:\WINDOWS\Fonts folder
3. Create following java program. It should display "Usman" in Urdu.
import java.awt.*;
import javax.swing.*;
public class BasicDraw {
public static void main(String[] args) {
new BasicDraw();
}
BasicDraw() {
// Create a frame
JFrame frame = new JFrame();
// Add a component with a custom paint method
frame.getContentPane().add(new MyComponent());
// Display the frame
int frameWidth = 200;
int frameHeight = 200;
frame.setSize(frameWidth, frameHeight);
frame.setVisible(true);
}
class MyComponent extends JComponent {
// This method is called whenever the contents needs to be painted
public void paint(Graphics g) {
int style = Font.PLAIN;
int size = 24;
Font font = null;
font = new Font("Nafees Nastaleeq", style, size);
String text = "\u0639\u062b\u0645\u0627\u0646";
g.setFont(font);
// Draw a string such that its base line is at x, y
int x = 80;
int y = 40;
g.drawString(text, x, y);
}
}
}
4. The resulting image should look like:
45 comments:
[url=][img][/img][/url]
Related keywords:
Tramadol and sheep
next day air ups Tramadol Tramadol
overnight delivery on Tramadol
Tramadol cod overnight delivery
drug interaction between amiodarone and Tramadol
buy cheap Tramadol free fedex shipping
Tramadol overnight delivery no prescription
Tramadol drug
[url=]Tramadol 500mg information [/url]
[url=][/url]
Tramadol without presciption
Tramadol with suboxone
Tramadol without prescription shipped overnight
cheap Tramadol 300ct 50mg
Tramadol use in canines
order Tramadol tamoxifen online
pharmacy tech job buy Tramadol
clomid 100mg days 5-9 | buy clomid without prescription - clomid prices, clomid days 3-7 when will i ovulate
clomid wiki | - buy clomid online no prescription usa, can clomid delay your period
ovulate early on clomid | [url=]clomid buy no prescription[/url] - how to buy clomid online, eliu clomid success stories first round
clomid ingredients | clomid 50mg et grossesse - clomid online cheap, clomid and nolva p to relating pdf [url=]dating directory jewish web[/url] adventist programs on dating
dating black book picking up women [url=]amy rose dating[/url] dating vintage jbl d130f speaker
fun free sim dating games [url=]how reliable is carbon dating[/url] free dating service single dating service
[url=][img][/img][/url]
how to dating a married woman [url=]free top adult dating site[/url] dating gratis video
how do dating sites work [url=]ezine online dating[/url] free sex dating and swingers personals
who is alexis bledel dating [url=]harmful teen dating relationships[/url] hawaii dating service
ebook bela liptak ebook bookshelf [url=]forex ebook 2008[/url] into the wild ebook
gen x software get free windows software with torrent [url=]what are footprint software[/url] merit 2000 software download
[url=]Multimedias y entretenimiento - Cheap Legal OEM Software, Software Sale, Download OEM[/url] grammar remediation software
[url=][img][/img][/url]
you need a budget software reviews gif animation free software [url=]optimizer software[/url] government contractors project management software
[url=]Roxio Toast Ti Pro 10 [Mac] - Cheap Legal OEM Software, Software Sale, Download OEM[/url] orion controlworks 4.0 software
[url=][img][/img][/url]
Rather than borrowing money from family or friends, think about a quick online money advance loan choosing wisely - there are many pay day
loan lenders out there.
Also see my webpage ::
You must also do not forget that you will find few others expenses which come which has a car
like fuel, insurance and maintenance from the car fax payday loan what happens to
the people who use payday cash advances is because keep getting less and fewer with their paycheck because with the interest and charges, virtually kiting them into bankruptcy.
This limitation means that you might have a very narrow cause of comparison Pay Day Loans they
could possibly be outright scams or they could possibly be come-ons for several
sorts of loan products, usually payday or advance
loan loans which aren't exactly bad credit loans.
So, need to never look towards others when it is possible to't delay your urgent expenses not having sufficient funds with your bank account personal loan in bangalore by developing a more confident, an even more come up with self, you start to make positive changes to attitude about yourself with the same time - not merely your clothes.
Feel free to visit my blog post; homepage
The differences a wide range of among the technique of
bank loans and internet based payday cash advances payday loan this enables borrowers to assimilate the necessary documentation and apply for
the bad credit loan in a structured and organized
manner.
The report which was released this week included an email from -
Bank of Americadiscussing Burk with his fantastic activities
laons this is the reason most financiers have strict rules and policies that
you need to comply.
This is to ensure the lending company that his money
wouldn't normally lead to unrecoverable debt payday loan direct lenders only before you begin writing the letter, you will need to perform some important homework.
Also visit my blog post; web site
my blog; webpage
Feel free to visit my web page: homepage
Feel free to visit my page - webpage
A no fax payday loans might be borrowed for a time period of 14 to 31 days signature loans if you select you should
work with a cash advance, borrow only the maximum amount of because you are able to afford to pay for
along with your next paycheck and have enough to generate it for
the next payday.
But, this cancelled amount had for ages been considered taxable
No teletrack payday loan companies moreover, you should have to acquire a company form which matches your company to have the advantages of tax treatments.
In fact, in case you find Podium and Greenbelt a little classy since several with the stores are top with the
line then NRW will be the same, maybe a lot more payday loans bad credit if she says this happened with the airport with ticket
and visa at hand, it likely is really a scam.
As a very first time payday advance customer, you're eligible to gain access to approximately $1500 payday loans columbus ohio lo doc with no doc loans simply need that you can be which you offer an income coming in, and never every one of the mounds of tax statements that banking institutions require.
Hi mates, its wonderful article regarding tutoringand completely defined, keep it
up all the time.
Here is my blog post ... breast uplift
Excellent article. Keep posting such kind of information on your site.
Im really impressed by your site.
Hey there, You've done a great job. I will definitely digg it and personally suggest to my friends. I'm confident they'll be benefited from this website.
Also visit my blog post: semenax price
Wow, fantastic blog layout! How long have you been
blogging for? you make blogging look easy. The overall look of your site is excellent, as well as the content!
Feel free to surf to my page: does semenex work
You are so awesome! I don't believe I've read through a single thing like that before.
So wonderful to find someone with some original thoughts on this topic.
Really.. thank you for starting this up.
This web site is something that's needed on the web, someone with a little originality!
Here is my blog: longer lasting erections
Hey there, I think your site might be having browser compatibility issues.
When I look at your website in Safari, it looks fine
but when opening in Internet Explorer, it has some overlapping.
I just wanted to give you a quick heads up! Other then that, wonderful
Feel free to surf to my web page - hhgh
I am curious to find out what blog system you
have been utilizing? I'm having some minor security issues with my latest site and I'd like to find something more safe.
Do you have any solutions?
Visit my website; whitening teeth fast
Do you have a spam problem on this blog; I
also am a blogger, and I was wanting to know your situation; many of us have developed some nice methods and we are looking to trade
solutions with others, why not shoot me an email if
interested.
My web-site ... eazol review
This site really has all of the information and facts I needed about this subject and didn't know who to ask.
Here is my web blog ... human body
I was able to find good advice from your blog articles.
Feel free to surf to my blog: gethairatlanta.com
You are so cool! I do not think I have read through anything
like that before. So great to discover somebody with a few original thoughts on this topic.
Really.. thanks for starting this up. This site is one thing that
is required on the web, someone with some originality!
my web blog; beep.com
Hi there it's me, I am also visiting this site on a regular basis, this web page is really nice and the users are really sharing pleasant thoughts.
My weblog: hoodia works
I got this web page from my buddy who told me on the topic of this web
site and now this time I am browsing this website and reading very
informative content at this place.
My page
100 free nsa dating no more dating djs mp3
halifax speed dating [url=]dating sties katie[/url] complete free online dating
love hina sim dating cheats [url=]united states dating service personals classifieds[/url] speed dating in nashville tn [url=]veronikaqqt7[/url] search names online dating scams
Thank you for another wonderful post. The place else could anybody get
that kind of information in such an ideal manner of writing?
I have a presentation subsequent week, and I'm on the search for such information.
my homepage
profile dating transexual dating to girls
novels on interracial dating [url=]free dating christian sites[/url] meet international dating
dating larger women [url=]professional lesbian dating service[/url] kelley earnhardt dating [url=]vovafr[/url] lexington kentucky speed dating
I was wanting to know your situation; many of us have developed some nice methods.
Title Loans Utah
Are you fantasized about interracial dating? Do you want to have a partner from another race or ethnic group? If yes, then you have come to the right place. MixedRelationship.com | http://vajahatalee.blogspot.com/2009/06/using-urdu-in-java.html | CC-MAIN-2017-51 | refinedweb | 1,721 | 54.97 |
#include <hallo.h> * Thomas Bushnell BSG [Sat, Mar 26 2005, 11:49:37PM]: > This is like saying that people will use star office whether it's DFSG > free or not, so there is no reason to say "we won't distribute this > until it's DFSG free". In fact, people can and do make things free. > > > Please explain why you disagree with this. > > We should tell users: we are unable to support this hardware, because > we don't have the source. Among other things, we are unable to fix > security bugs in it. (And yes, device drivers certainly can have > security bugs! I've even seen firmware bugs with security > implications.)" > > I suspect you'll say that we simply must have the source, without > > compromise. Freedom for freedom's sake, etc. > > No. Why do you think we insist on the source for programs in general? Because we want to modify it where we need it and this modification is a feasible thing. If your BIOS is crappy and your hardware manufacturers does not provide updates, do you burn the bits with a soldering gun or open flames in order to fix that? You don't? Why do you insist on modifying hardware parts (firmware is one) then? >. Regards, Eduard. -- Ambassador Londo Mollari: Mr. Garibaldi,j ust now, would you really have killed me? Michael Garibaldi: Yes. Yes, I would've, but I'm just as glad I didn't have to. The paperwork's a pain in the butt. -- Quotes from Babylon 5 -- | https://lists.debian.org/debian-devel/2005/03/msg02842.html | CC-MAIN-2017-22 | refinedweb | 253 | 75.71 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.