Search Results

Search found 6764 results on 271 pages for 'bryan head'.

Page 10/271 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Creating an adjacency List for DFS

    - by user200081
    I'm having trouble creating a Depth First Search for my program. So far I have a class of edges and a class of regions. I want to store all the connected edges inside one node of my region. I can tell if something is connected by the getKey() function I have already implemented. If two edges have the same key, then they are connected. For the next region, I want to store another set of connected edges inside that region, etc etc. However, I am not fully understanding DFS and I'm having some trouble implementing it. I'm not sure when/where to call DFS again. Any help would be appreciated! class edge { private: int source, destination, length; int key; edge *next; public: getKey(){ return key; } } class region { edge *data; edge *next; region() { data = new edge(); next = NULL; } }; void runDFS(int i, edge **edge, int a) { region *head = new region(); aa[i]->visited == true;//mark the first vertex as true for(int v = 0; v < a; v++) { if(tem->edge[i].getKey() == tem->edge[v].getKey()) //if the edges of the vertex have the same root { if(head->data == NULL) { head->data = aa[i]; head->data->next == NULL; } //create an edge if(head->data) { head->data->next = aa[i]; head->data->next->next == NULL; }//if there is already a node connected to ti } if(aa[v]->visited == false) runDFS(v, edge, a); //call the DFS again } //for loop }

    Read the article

  • I'm new to C++. Please Help me with the Linked List (What functions to add)?

    - by Igal
    DEAR All; Hi, I'm just beginner to C++; Please help me to understand: What functions should be in the Linked list class ? I think there should be overloaded operators << and ; Please help me to improve the code (style, errors, etc,) Thanks for advance. Igal. Please review the small code for the integer List (enclosed MyNODE.h and ListDriver1.cpp); MyNODE.h // This is my first attempt to write linked list. Igal Spector, June 2010. #include <iostream.h> #include <assert.h> //Forward Declaration of the classes: class ListNode; class TheLinkedlist; // Definition of the node (WITH IMPLEMENTATION !!!, without test drive): class ListNode{ friend class TheLinkedlist; public: // constructor: ListNode(const int& value, ListNode *next= 0); // note: no destructor, as this handled by TheLinkedList class. // accessor: return data in the node. // int Show() const {return theData;} private: int theData; //the Data ListNode* theNext; //points to the next node in the list. }; //Implementations: //constructor: inline ListNode::ListNode(const int &value,ListNode *next) :theData(value),theNext(next){} //end of ListNode class, now for the LL class: class TheLinkedlist { public: //constructors: TheLinkedlist(); virtual ~TheLinkedlist(); // Accessors: void InsertAtFront(const &); void AppendAtBack(const &); // void InOrderInsert(const &); bool IsEmpty()const;//predicate function void Print() const; private: ListNode * Head; //pointer to first node ListNode * Tail; //pointer to last node. }; //Implementation: //Default constructor inline TheLinkedlist::TheLinkedlist():Head(0),Tail(0) {} //Destructor inline TheLinkedlist::~TheLinkedlist(){ if(!IsEmpty()){ //list is not empty cout<<"\n\tDestroying Nodes"<<endl; ListNode *currentPointer=Head, *tempPtr; while(currentPointer != 0){ //Delete remaining Nodes. tempPtr=currentPointer; cout<<"The node: "<<tempPtr->theData <<" is Destroyed."<<endl<<endl; currentPointer=currentPointer->theNext; delete tempPtr; } Head=Tail = 0; //don't forget this, as it may be checked one day. } } //Insert the Node to the beginning of the list: void TheLinkedlist::InsertAtFront(const int& value){ ListNode *newPtr = new ListNode(value,Head); assert(newPtr!=0); if(IsEmpty()) //list is empty Head = Tail = newPtr; else { //list is NOT empty newPtr->theNext = Head; Head = newPtr; } } //Insert the Node to the beginning of the list: void TheLinkedlist::AppendAtBack(const int& value){ ListNode *newPtr = new ListNode(value, NULL); assert(newPtr!=0); if(IsEmpty()) //list is empty Head = Tail = newPtr; else { //list is NOT empty Tail->theNext = newPtr; Tail = newPtr; } } //is the list empty? inline bool TheLinkedlist::IsEmpty() const { return (Head == 0); } // Display the contents of the list void TheLinkedlist::Print()const{ if ( IsEmpty() ){ cout << "\n\t The list is empty!!"<<endl; return; } ListNode *tempPTR = Head; cout<<"\n\t The List is: "; while ( tempPTR != 0 ){ cout<< tempPTR->theData <<" "; tempPTR = tempPTR->theNext; } cout<<endl<<endl; } ////////////////////////////////////// The test Driver: //Driver test for integer Linked List. #include <iostream.h> #include "MyNODE.h" // main Driver int main(){ cout<< "\n\t This is the test for integer LinkedList."<<endl; const int arraySize=11, ARRAY[arraySize]={44,77,88,99,11,2,22,204,50,58,12}; cout << "\n\tThe array is: "; //print the numbers. for (int i=0;i<arraySize; i++) cout<<ARRAY[i]<<", "; TheLinkedlist list; //declare the list for(int index=0;index<arraySize;index++) list.AppendAtBack( ARRAY[index] );//create the list cout<<endl<<endl; list.Print(); //print the list return 0; //end of the program. }

    Read the article

  • Is this (Lock-Free) Queue Implementation Thread-Safe?

    - by Hosam Aly
    I am trying to create a lock-free queue implementation in Java, mainly for personal learning. The queue should be a general one, allowing any number of readers and/or writers concurrently. Would you please review it, and suggest any improvements/issues you find? Thank you. import java.util.concurrent.atomic.AtomicReference; public class LockFreeQueue<T> { private static class Node<E> { E value; volatile Node<E> next; Node(E value) { this.value = value; } } private AtomicReference<Node<T>> head, tail; public LockFreeQueue() { // have both head and tail point to a dummy node Node<T> dummyNode = new Node<T>(null); head = new AtomicReference<Node<T>>(dummyNode); tail = new AtomicReference<Node<T>>(dummyNode); } /** * Puts an object at the end of the queue. */ public void putObject(T value) { Node<T> newNode = new Node<T>(value); Node<T> prevTailNode = tail.getAndSet(newNode); prevTailNode.next = newNode; } /** * Gets an object from the beginning of the queue. The object is removed * from the queue. If there are no objects in the queue, returns null. */ public T getObject() { Node<T> headNode, valueNode; // move head node to the next node using atomic semantics // as long as next node is not null do { headNode = head.get(); valueNode = headNode.next; // try until the whole loop executes pseudo-atomically // (i.e. unaffected by modifications done by other threads) } while (valueNode != null && !head.compareAndSet(headNode, valueNode)); T value = (valueNode != null ? valueNode.value : null); // release the value pointed to by head, keeping the head node dummy if (valueNode != null) valueNode.value = null; return value; }

    Read the article

  • Adding Polynomials (Linked Lists)......Bug Help

    - by Brian
    I have written a program that creates nodes that in this class are parts of polynomials and then the two polynomials get added together to become one polynomial (list of nodes). All my code compiles so the only problem I am having is that the nodes are not inserting into the polynomial via the insert method I have in polynomial.java and when running the program it does create nodes and displays them in the 2x^2 format but when it comes to add the polynomials together it displays o as the polynomials, so if anyone can figure out whats wrong and what I can do to fix it it would be much appreciated. Here is the code: import java.util.Scanner; class Polynomial{ public termNode head; public Polynomial() { head = null; } public boolean isEmpty() { return (head == null); } public void display() { if (head == null) System.out.print("0"); else for(termNode cur = head; cur != null; cur = cur.getNext()) { System.out.println(cur); } } public void insert(termNode newNode) { termNode prev = null; termNode cur = head; while (cur!=null && (newNode.compareTo(cur)<0)) { prev = null; cur = cur.getNext(); } if (prev == null) { newNode.setNext(head); head = newNode; } else { newNode.setNext(cur); prev.setNext(newNode); } } public void readPolynomial(Scanner kb) { boolean done = false; double coefficient; int exponent; termNode term; head = null; //UNLINK ANY PREVIOUS POLYNOMIAL System.out.println("Enter 0 and 0 to end."); System.out.print("coefficient: "); coefficient = kb.nextDouble(); System.out.println(coefficient); System.out.print("exponent: "); exponent = kb.nextInt(); System.out.println(exponent); done = (coefficient == 0 && exponent == 0); while(!done) { Polynomial poly = new Polynomial(); term = new termNode(coefficient,exponent); System.out.println(term); poly.insert(term); System.out.println("Enter 0 and 0 to end."); System.out.print("coefficient: "); coefficient = kb.nextDouble(); System.out.println(coefficient); System.out.print("exponent: "); exponent = kb.nextInt(); System.out.println(exponent); done = (coefficient==0 && exponent==0); } } public static Polynomial add(Polynomial p, Polynomial q) { Polynomial r = new Polynomial(); double coefficient; int exponent; termNode first = p.head; termNode second = q.head; termNode sum = r.head; termNode term; while (first != null && second != null) { if (first.getExp() == second.getExp()) { if (first.getCoeff() != 0 && second.getCoeff() != 0); { double addCoeff = first.getCoeff() + second.getCoeff(); term = new termNode(addCoeff,first.getExp()); sum.setNext(term); first.getNext(); second.getNext(); } } else if (first.getExp() < second.getExp()) { sum.setNext(second); term = new termNode(second.getCoeff(),second.getExp()); sum.setNext(term); second.getNext(); } else { sum.setNext(first); term = new termNode(first.getNext()); sum.setNext(term); first.getNext(); } } while (first != null) { sum.setNext(first); } while (second != null) { sum.setNext(second); } return r; } } Here is my Node class: class termNode implements Comparable { private int exp; private double coeff; private termNode next; public termNode(double coefficient, int exponent) { coeff = coefficient; exp = exponent; next = null; } public termNode(termNode inTermNode) { coeff = inTermNode.coeff; exp = inTermNode.exp; } public void setData(double coefficient, int exponent) { coefficient = coeff; exponent = exp; } public double getCoeff() { return coeff; } public int getExp() { return exp; } public void setNext(termNode link) { next = link; } public termNode getNext() { return next; } public String toString() { if (exp == 0) { return(coeff + " "); } else if (exp == 1) { return(coeff + "x"); } else { return(coeff + "x^" + exp); } } public int compareTo(Object other) { if(exp ==((termNode) other).exp) return 0; else if(exp < ((termNode) other).exp) return -1; else return 1; } } And here is my Test class to run the program. import java.util.Scanner; class PolyTest{ public static void main(String [] args) { Scanner kb = new Scanner(System.in); Polynomial r; Polynomial p = new Polynomial(); System.out.println("Enter first polynomial."); p.readPolynomial(kb); Polynomial q = new Polynomial(); System.out.println(); System.out.println("Enter second polynomial."); q.readPolynomial(kb); r = Polynomial.add(p,q); System.out.println(); System.out.print("The sum of "); p.display(); System.out.print(" and "); q.display(); System.out.print(" is "); r.display(); } }

    Read the article

  • Prolog: Sentence Parser Problem

    - by Devon
    Hey guys, Been sat here for hours now just staring at this code and have no idea what I'm doing wrong. I know what's happening from tracing the code through (it is going on an eternal loop when it hits verbPhrase). Any tips are more then welcome. Thank you. % Knowledge-base det(the). det(a). adjective(quick). adjective(brown). adjective(orange). adjective(sweet). noun(cat). noun(mat). noun(fox). noun(cucumber). noun(saw). noun(mother). noun(father). noun(family). noun(depression). prep(on). prep(with). verb(sat). verb(nibbled). verb(ran). verb(looked). verb(is). verb(has). % Sentece Structures sentence(Phrase) :- append(NounPhrase, VerbPhrase, Phrase), nounPhrase(NounPhrase), verbPhrase(VerbPhrase). sentence(Phrase) :- verbPhrase(Phrase). nounPhrase([]). nounPhrase([Head | Tail]) :- det(Head), nounPhrase2(Tail). nounPhrase(Phrase) :- nounPhrase2(Phrase). nounPhrase(Phrase) :- append(NP, PP, Phrase), nounPhrase(NP), prepPhrase(PP). nounPhrase2([]). nounPhrase2(Word) :- noun(Word). nounPhrase2([Head | Tail]) :- adjective(Head), nounPhrase2(Tail). prepPhrase([]). prepPhrase([Head | Tail]) :- prep(Head), nounPhrase(Tail). verbPhrase([]). verbPhrase(Word) :- verb(Word). verbPhrase([Head | Tail]) :- verb(Head), nounPhrase(Tail). verbPhrase(Phrase) :- append(VP, PP, Phrase), verbPhrase(VP), prepPhrase(PP).

    Read the article

  • Introduction to the ASP.NET Web API

    - by Stephen.Walther
    I am a huge fan of Ajax. If you want to create a great experience for the users of your website – regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site — then you need to use Ajax. Otherwise, you are just being cruel to your customers. We use Ajax extensively in several of the ASP.NET applications that my company, Superexpert.com, builds. We expose data from the server as JSON and use jQuery to retrieve and update that data from the browser. One challenge, when building an ASP.NET website, is deciding on which technology to use to expose JSON data from the server. For example, how do you expose a list of products from the server as JSON so you can retrieve the list of products with jQuery? You have a number of options (too many options) including ASMX Web services, WCF Web Services, ASHX Generic Handlers, WCF Data Services, and MVC controller actions. Fortunately, the world has just been simplified. With the release of ASP.NET 4 Beta, Microsoft has introduced a new technology for exposing JSON from the server named the ASP.NET Web API. You can use the ASP.NET Web API with both ASP.NET MVC and ASP.NET Web Forms applications. The goal of this blog post is to provide you with a brief overview of the features of the new ASP.NET Web API. You learn how to use the ASP.NET Web API to retrieve, insert, update, and delete database records with jQuery. We also discuss how you can perform form validation when using the Web API and use OData when using the Web API. Creating an ASP.NET Web API Controller The ASP.NET Web API exposes JSON data through a new type of controller called an API controller. You can add an API controller to an existing ASP.NET MVC 4 project through the standard Add Controller dialog box. Right-click your Controllers folder and select Add, Controller. In the dialog box, name your controller MovieController and select the Empty API controller template: A brand new API controller looks like this: using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { } } An API controller, unlike a standard MVC controller, derives from the base ApiController class instead of the base Controller class. Using jQuery to Retrieve, Insert, Update, and Delete Data Let’s create an Ajaxified Movie Database application. We’ll retrieve, insert, update, and delete movies using jQuery with the MovieController which we just created. Our Movie model class looks like this: namespace MyWebAPIApp.Models { public class Movie { public int Id { get; set; } public string Title { get; set; } public string Director { get; set; } } } Our application will consist of a single HTML page named Movies.html. We’ll place all of our jQuery code in the Movies.html page. Getting a Single Record with the ASP.NET Web API To support retrieving a single movie from the server, we need to add a Get method to our API controller: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using MyWebAPIApp.Models; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { public Movie GetMovie(int id) { // Return movie by id if (id == 1) { return new Movie { Id = 1, Title = "Star Wars", Director = "Lucas" }; } // Otherwise, movie was not found throw new HttpResponseException(HttpStatusCode.NotFound); } } } In the code above, the GetMovie() method accepts the Id of a movie. If the Id has the value 1 then the method returns the movie Star Wars. Otherwise, the method throws an exception and returns 404 Not Found HTTP status code. After building your project, you can invoke the MovieController.GetMovie() method by entering the following URL in your web browser address bar: http://localhost:[port]/api/movie/1 (You’ll need to enter the correct randomly generated port). In the URL api/movie/1, the first “api” segment indicates that this is a Web API route. The “movie” segment indicates that the MovieController should be invoked. You do not specify the name of the action. Instead, the HTTP method used to make the request – GET, POST, PUT, DELETE — is used to identify the action to invoke. The ASP.NET Web API uses different routing conventions than normal ASP.NET MVC controllers. When you make an HTTP GET request then any API controller method with a name that starts with “GET” is invoked. So, we could have called our API controller action GetPopcorn() instead of GetMovie() and it would still be invoked by the URL api/movie/1. The default route for the Web API is defined in the Global.asax file and it looks like this: routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); We can invoke our GetMovie() controller action with the jQuery code in the following HTML page: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Get Movie</title> </head> <body> <div> Title: <span id="title"></span> </div> <div> Director: <span id="director"></span> </div> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> getMovie(1, function (movie) { $("#title").html(movie.Title); $("#director").html(movie.Director); }); function getMovie(id, callback) { $.ajax({ url: "/api/Movie", data: { id: id }, type: "GET", contentType: "application/json;charset=utf-8", statusCode: { 200: function (movie) { callback(movie); }, 404: function () { alert("Not Found!"); } } }); } </script> </body> </html> In the code above, the jQuery $.ajax() method is used to invoke the GetMovie() method. Notice that the Ajax call handles two HTTP response codes. When the GetMove() method successfully returns a movie, the method returns a 200 status code. In that case, the details of the movie are displayed in the HTML page. Otherwise, if the movie is not found, the GetMovie() method returns a 404 status code. In that case, the page simply displays an alert box indicating that the movie was not found (hopefully, you would implement something more graceful in an actual application). You can use your browser’s Developer Tools to see what is going on in the background when you open the HTML page (hit F12 in the most recent version of most browsers). For example, you can use the Network tab in Google Chrome to see the Ajax request which invokes the GetMovie() method: Getting a Set of Records with the ASP.NET Web API Let’s modify our Movie API controller so that it returns a collection of movies. The following Movie controller has a new ListMovies() method which returns a (hard-coded) collection of movies: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using MyWebAPIApp.Models; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { public IEnumerable<Movie> ListMovies() { return new List<Movie> { new Movie {Id=1, Title="Star Wars", Director="Lucas"}, new Movie {Id=1, Title="King Kong", Director="Jackson"}, new Movie {Id=1, Title="Memento", Director="Nolan"} }; } } } Because we named our action ListMovies(), the default Web API route will never match it. Therefore, we need to add the following custom route to our Global.asax file (at the top of the RegisterRoutes() method): routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); This route enables us to invoke the ListMovies() method with the URL /api/movie/listmovies. Now that we have exposed our collection of movies from the server, we can retrieve and display the list of movies using jQuery in our HTML page: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>List Movies</title> </head> <body> <div id="movies"></div> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> listMovies(function (movies) { var strMovies=""; $.each(movies, function (index, movie) { strMovies += "<div>" + movie.Title + "</div>"; }); $("#movies").html(strMovies); }); function listMovies(callback) { $.ajax({ url: "/api/Movie/ListMovies", data: {}, type: "GET", contentType: "application/json;charset=utf-8", }).then(function(movies){ callback(movies); }); } </script> </body> </html>     Inserting a Record with the ASP.NET Web API Now let’s modify our Movie API controller so it supports creating new records: public HttpResponseMessage<Movie> PostMovie(Movie movieToCreate) { // Add movieToCreate to the database and update primary key movieToCreate.Id = 23; // Build a response that contains the location of the new movie var response = new HttpResponseMessage<Movie>(movieToCreate, HttpStatusCode.Created); var relativePath = "/api/movie/" + movieToCreate.Id; response.Headers.Location = new Uri(Request.RequestUri, relativePath); return response; } The PostMovie() method in the code above accepts a movieToCreate parameter. We don’t actually store the new movie anywhere. In real life, you will want to call a service method to store the new movie in a database. When you create a new resource, such as a new movie, you should return the location of the new resource. In the code above, the URL where the new movie can be retrieved is assigned to the Location header returned in the PostMovie() response. Because the name of our method starts with “Post”, we don’t need to create a custom route. The PostMovie() method can be invoked with the URL /Movie/PostMovie – just as long as the method is invoked within the context of a HTTP POST request. The following HTML page invokes the PostMovie() method. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Create Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToCreate = { title: "The Hobbit", director: "Jackson" }; createMovie(movieToCreate, function (newMovie) { alert("New movie created with an Id of " + newMovie.Id); }); function createMovie(movieToCreate, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify( movieToCreate ), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { callback(newMovie); } } }); } </script> </body> </html> This page creates a new movie (the Hobbit) by calling the createMovie() method. The page simply displays the Id of the new movie: The HTTP Post operation is performed with the following call to the jQuery $.ajax() method: $.ajax({ url: "/api/Movie", data: JSON.stringify( movieToCreate ), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { callback(newMovie); } } }); Notice that the type of Ajax request is a POST request. This is required to match the PostMovie() method. Notice, furthermore, that the new movie is converted into JSON using JSON.stringify(). The JSON.stringify() method takes a JavaScript object and converts it into a JSON string. Finally, notice that success is represented with a 201 status code. The HttpStatusCode.Created value returned from the PostMovie() method returns a 201 status code. Updating a Record with the ASP.NET Web API Here’s how we can modify the Movie API controller to support updating an existing record. In this case, we need to create a PUT method to handle an HTTP PUT request: public void PutMovie(Movie movieToUpdate) { if (movieToUpdate.Id == 1) { // Update the movie in the database return; } // If you can't find the movie to update throw new HttpResponseException(HttpStatusCode.NotFound); } Unlike our PostMovie() method, the PutMovie() method does not return a result. The action either updates the database or, if the movie cannot be found, returns an HTTP Status code of 404. The following HTML page illustrates how you can invoke the PutMovie() method: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Put Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToUpdate = { id: 1, title: "The Hobbit", director: "Jackson" }; updateMovie(movieToUpdate, function () { alert("Movie updated!"); }); function updateMovie(movieToUpdate, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify(movieToUpdate), type: "PUT", contentType: "application/json;charset=utf-8", statusCode: { 200: function () { callback(); }, 404: function () { alert("Movie not found!"); } } }); } </script> </body> </html> Deleting a Record with the ASP.NET Web API Here’s the code for deleting a movie: public HttpResponseMessage DeleteMovie(int id) { // Delete the movie from the database // Return status code return new HttpResponseMessage(HttpStatusCode.NoContent); } This method simply deletes the movie (well, not really, but pretend that it does) and returns a No Content status code (204). The following page illustrates how you can invoke the DeleteMovie() action: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Delete Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> deleteMovie(1, function () { alert("Movie deleted!"); }); function deleteMovie(id, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify({id:id}), type: "DELETE", contentType: "application/json;charset=utf-8", statusCode: { 204: function () { callback(); } } }); } </script> </body> </html> Performing Validation How do you perform form validation when using the ASP.NET Web API? Because validation in ASP.NET MVC is driven by the Default Model Binder, and because the Web API uses the Default Model Binder, you get validation for free. Let’s modify our Movie class so it includes some of the standard validation attributes: using System.ComponentModel.DataAnnotations; namespace MyWebAPIApp.Models { public class Movie { public int Id { get; set; } [Required(ErrorMessage="Title is required!")] [StringLength(5, ErrorMessage="Title cannot be more than 5 characters!")] public string Title { get; set; } [Required(ErrorMessage="Director is required!")] public string Director { get; set; } } } In the code above, the Required validation attribute is used to make both the Title and Director properties required. The StringLength attribute is used to require the length of the movie title to be no more than 5 characters. Now let’s modify our PostMovie() action to validate a movie before adding the movie to the database: public HttpResponseMessage PostMovie(Movie movieToCreate) { // Validate movie if (!ModelState.IsValid) { var errors = new JsonArray(); foreach (var prop in ModelState.Values) { if (prop.Errors.Any()) { errors.Add(prop.Errors.First().ErrorMessage); } } return new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest); } // Add movieToCreate to the database and update primary key movieToCreate.Id = 23; // Build a response that contains the location of the new movie var response = new HttpResponseMessage<Movie>(movieToCreate, HttpStatusCode.Created); var relativePath = "/api/movie/" + movieToCreate.Id; response.Headers.Location = new Uri(Request.RequestUri, relativePath); return response; } If ModelState.IsValid has the value false then the errors in model state are copied to a new JSON array. Each property – such as the Title and Director property — can have multiple errors. In the code above, only the first error message is copied over. The JSON array is returned with a Bad Request status code (400 status code). The following HTML page illustrates how you can invoke our modified PostMovie() action and display any error messages: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Create Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToCreate = { title: "The Hobbit", director: "" }; createMovie(movieToCreate, function (newMovie) { alert("New movie created with an Id of " + newMovie.Id); }, function (errors) { var strErrors = ""; $.each(errors, function(index, err) { strErrors += "*" + err + "\n"; }); alert(strErrors); } ); function createMovie(movieToCreate, success, fail) { $.ajax({ url: "/api/Movie", data: JSON.stringify(movieToCreate), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { success(newMovie); }, 400: function (xhr) { var errors = JSON.parse(xhr.responseText); fail(errors); } } }); } </script> </body> </html> The createMovie() function performs an Ajax request and handles either a 201 or a 400 status code from the response. If a 201 status code is returned then there were no validation errors and the new movie was created. If, on the other hand, a 400 status code is returned then there was a validation error. The validation errors are retrieved from the XmlHttpRequest responseText property. The error messages are displayed in an alert: (Please don’t use JavaScript alert dialogs to display validation errors, I just did it this way out of pure laziness) This validation code in our PostMovie() method is pretty generic. There is nothing specific about this code to the PostMovie() method. In the following video, Jon Galloway demonstrates how to create a global Validation filter which can be used with any API controller action: http://www.asp.net/web-api/overview/web-api-routing-and-actions/video-custom-validation His validation filter looks like this: using System.Json; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace MyWebAPIApp.Filters { public class ValidationActionFilter:ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { var modelState = actionContext.ModelState; if (!modelState.IsValid) { dynamic errors = new JsonObject(); foreach (var key in modelState.Keys) { var state = modelState[key]; if (state.Errors.Any()) { errors[key] = state.Errors.First().ErrorMessage; } } actionContext.Response = new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest); } } } } And you can register the validation filter in the Application_Start() method in the Global.asax file like this: GlobalConfiguration.Configuration.Filters.Add(new ValidationActionFilter()); After you register the Validation filter, validation error messages are returned from any API controller action method automatically when validation fails. You don’t need to add any special logic to any of your API controller actions to take advantage of the filter. Querying using OData The OData protocol is an open protocol created by Microsoft which enables you to perform queries over the web. The official website for OData is located here: http://odata.org For example, here are some of the query options which you can use with OData: · $orderby – Enables you to retrieve results in a certain order. · $top – Enables you to retrieve a certain number of results. · $skip – Enables you to skip over a certain number of results (use with $top for paging). · $filter – Enables you to filter the results returned. The ASP.NET Web API supports a subset of the OData protocol. You can use all of the query options listed above when interacting with an API controller. The only requirement is that the API controller action returns its data as IQueryable. For example, the following Movie controller has an action named GetMovies() which returns an IQueryable of movies: public IQueryable<Movie> GetMovies() { return new List<Movie> { new Movie {Id=1, Title="Star Wars", Director="Lucas"}, new Movie {Id=2, Title="King Kong", Director="Jackson"}, new Movie {Id=3, Title="Willow", Director="Lucas"}, new Movie {Id=4, Title="Shrek", Director="Smith"}, new Movie {Id=5, Title="Memento", Director="Nolan"} }.AsQueryable(); } If you enter the following URL in your browser: /api/movie?$top=2&$orderby=Title Then you will limit the movies returned to the top 2 in order of the movie Title. You will get the following results: By using the $top option in combination with the $skip option, you can enable client-side paging. For example, you can use $top and $skip to page through thousands of products, 10 products at a time. The $filter query option is very powerful. You can use this option to filter the results from a query. Here are some examples: Return every movie directed by Lucas: /api/movie?$filter=Director eq ‘Lucas’ Return every movie which has a title which starts with ‘S’: /api/movie?$filter=startswith(Title,’S') Return every movie which has an Id greater than 2: /api/movie?$filter=Id gt 2 The complete documentation for the $filter option is located here: http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption Summary The goal of this blog entry was to provide you with an overview of the new ASP.NET Web API introduced with the Beta release of ASP.NET 4. In this post, I discussed how you can retrieve, insert, update, and delete data by using jQuery with the Web API. I also discussed how you can use the standard validation attributes with the Web API. You learned how to return validation error messages to the client and display the error messages using jQuery. Finally, we briefly discussed how the ASP.NET Web API supports the OData protocol. For example, you learned how to filter records returned from an API controller action by using the $filter query option. I’m excited about the new Web API. This is a feature which I expect to use with almost every ASP.NET application which I build in the future.

    Read the article

  • Introduction to the ASP.NET Web API

    - by Stephen.Walther
    I am a huge fan of Ajax. If you want to create a great experience for the users of your website – regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site — then you need to use Ajax. Otherwise, you are just being cruel to your customers. We use Ajax extensively in several of the ASP.NET applications that my company, Superexpert.com, builds. We expose data from the server as JSON and use jQuery to retrieve and update that data from the browser. One challenge, when building an ASP.NET website, is deciding on which technology to use to expose JSON data from the server. For example, how do you expose a list of products from the server as JSON so you can retrieve the list of products with jQuery? You have a number of options (too many options) including ASMX Web services, WCF Web Services, ASHX Generic Handlers, WCF Data Services, and MVC controller actions. Fortunately, the world has just been simplified. With the release of ASP.NET 4 Beta, Microsoft has introduced a new technology for exposing JSON from the server named the ASP.NET Web API. You can use the ASP.NET Web API with both ASP.NET MVC and ASP.NET Web Forms applications. The goal of this blog post is to provide you with a brief overview of the features of the new ASP.NET Web API. You learn how to use the ASP.NET Web API to retrieve, insert, update, and delete database records with jQuery. We also discuss how you can perform form validation when using the Web API and use OData when using the Web API. Creating an ASP.NET Web API Controller The ASP.NET Web API exposes JSON data through a new type of controller called an API controller. You can add an API controller to an existing ASP.NET MVC 4 project through the standard Add Controller dialog box. Right-click your Controllers folder and select Add, Controller. In the dialog box, name your controller MovieController and select the Empty API controller template: A brand new API controller looks like this: using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web.Http; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { } } An API controller, unlike a standard MVC controller, derives from the base ApiController class instead of the base Controller class. Using jQuery to Retrieve, Insert, Update, and Delete Data Let’s create an Ajaxified Movie Database application. We’ll retrieve, insert, update, and delete movies using jQuery with the MovieController which we just created. Our Movie model class looks like this: namespace MyWebAPIApp.Models { public class Movie { public int Id { get; set; } public string Title { get; set; } public string Director { get; set; } } } Our application will consist of a single HTML page named Movies.html. We’ll place all of our jQuery code in the Movies.html page. Getting a Single Record with the ASP.NET Web API To support retrieving a single movie from the server, we need to add a Get method to our API controller: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using MyWebAPIApp.Models; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { public Movie GetMovie(int id) { // Return movie by id if (id == 1) { return new Movie { Id = 1, Title = "Star Wars", Director = "Lucas" }; } // Otherwise, movie was not found throw new HttpResponseException(HttpStatusCode.NotFound); } } } In the code above, the GetMovie() method accepts the Id of a movie. If the Id has the value 1 then the method returns the movie Star Wars. Otherwise, the method throws an exception and returns 404 Not Found HTTP status code. After building your project, you can invoke the MovieController.GetMovie() method by entering the following URL in your web browser address bar: http://localhost:[port]/api/movie/1 (You’ll need to enter the correct randomly generated port). In the URL api/movie/1, the first “api” segment indicates that this is a Web API route. The “movie” segment indicates that the MovieController should be invoked. You do not specify the name of the action. Instead, the HTTP method used to make the request – GET, POST, PUT, DELETE — is used to identify the action to invoke. The ASP.NET Web API uses different routing conventions than normal ASP.NET MVC controllers. When you make an HTTP GET request then any API controller method with a name that starts with “GET” is invoked. So, we could have called our API controller action GetPopcorn() instead of GetMovie() and it would still be invoked by the URL api/movie/1. The default route for the Web API is defined in the Global.asax file and it looks like this: routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); We can invoke our GetMovie() controller action with the jQuery code in the following HTML page: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Get Movie</title> </head> <body> <div> Title: <span id="title"></span> </div> <div> Director: <span id="director"></span> </div> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> getMovie(1, function (movie) { $("#title").html(movie.Title); $("#director").html(movie.Director); }); function getMovie(id, callback) { $.ajax({ url: "/api/Movie", data: { id: id }, type: "GET", contentType: "application/json;charset=utf-8", statusCode: { 200: function (movie) { callback(movie); }, 404: function () { alert("Not Found!"); } } }); } </script> </body> </html> In the code above, the jQuery $.ajax() method is used to invoke the GetMovie() method. Notice that the Ajax call handles two HTTP response codes. When the GetMove() method successfully returns a movie, the method returns a 200 status code. In that case, the details of the movie are displayed in the HTML page. Otherwise, if the movie is not found, the GetMovie() method returns a 404 status code. In that case, the page simply displays an alert box indicating that the movie was not found (hopefully, you would implement something more graceful in an actual application). You can use your browser’s Developer Tools to see what is going on in the background when you open the HTML page (hit F12 in the most recent version of most browsers). For example, you can use the Network tab in Google Chrome to see the Ajax request which invokes the GetMovie() method: Getting a Set of Records with the ASP.NET Web API Let’s modify our Movie API controller so that it returns a collection of movies. The following Movie controller has a new ListMovies() method which returns a (hard-coded) collection of movies: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using MyWebAPIApp.Models; namespace MyWebAPIApp.Controllers { public class MovieController : ApiController { public IEnumerable<Movie> ListMovies() { return new List<Movie> { new Movie {Id=1, Title="Star Wars", Director="Lucas"}, new Movie {Id=1, Title="King Kong", Director="Jackson"}, new Movie {Id=1, Title="Memento", Director="Nolan"} }; } } } Because we named our action ListMovies(), the default Web API route will never match it. Therefore, we need to add the following custom route to our Global.asax file (at the top of the RegisterRoutes() method): routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); This route enables us to invoke the ListMovies() method with the URL /api/movie/listmovies. Now that we have exposed our collection of movies from the server, we can retrieve and display the list of movies using jQuery in our HTML page: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>List Movies</title> </head> <body> <div id="movies"></div> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> listMovies(function (movies) { var strMovies=""; $.each(movies, function (index, movie) { strMovies += "<div>" + movie.Title + "</div>"; }); $("#movies").html(strMovies); }); function listMovies(callback) { $.ajax({ url: "/api/Movie/ListMovies", data: {}, type: "GET", contentType: "application/json;charset=utf-8", }).then(function(movies){ callback(movies); }); } </script> </body> </html>     Inserting a Record with the ASP.NET Web API Now let’s modify our Movie API controller so it supports creating new records: public HttpResponseMessage<Movie> PostMovie(Movie movieToCreate) { // Add movieToCreate to the database and update primary key movieToCreate.Id = 23; // Build a response that contains the location of the new movie var response = new HttpResponseMessage<Movie>(movieToCreate, HttpStatusCode.Created); var relativePath = "/api/movie/" + movieToCreate.Id; response.Headers.Location = new Uri(Request.RequestUri, relativePath); return response; } The PostMovie() method in the code above accepts a movieToCreate parameter. We don’t actually store the new movie anywhere. In real life, you will want to call a service method to store the new movie in a database. When you create a new resource, such as a new movie, you should return the location of the new resource. In the code above, the URL where the new movie can be retrieved is assigned to the Location header returned in the PostMovie() response. Because the name of our method starts with “Post”, we don’t need to create a custom route. The PostMovie() method can be invoked with the URL /Movie/PostMovie – just as long as the method is invoked within the context of a HTTP POST request. The following HTML page invokes the PostMovie() method. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Create Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToCreate = { title: "The Hobbit", director: "Jackson" }; createMovie(movieToCreate, function (newMovie) { alert("New movie created with an Id of " + newMovie.Id); }); function createMovie(movieToCreate, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify( movieToCreate ), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { callback(newMovie); } } }); } </script> </body> </html> This page creates a new movie (the Hobbit) by calling the createMovie() method. The page simply displays the Id of the new movie: The HTTP Post operation is performed with the following call to the jQuery $.ajax() method: $.ajax({ url: "/api/Movie", data: JSON.stringify( movieToCreate ), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { callback(newMovie); } } }); Notice that the type of Ajax request is a POST request. This is required to match the PostMovie() method. Notice, furthermore, that the new movie is converted into JSON using JSON.stringify(). The JSON.stringify() method takes a JavaScript object and converts it into a JSON string. Finally, notice that success is represented with a 201 status code. The HttpStatusCode.Created value returned from the PostMovie() method returns a 201 status code. Updating a Record with the ASP.NET Web API Here’s how we can modify the Movie API controller to support updating an existing record. In this case, we need to create a PUT method to handle an HTTP PUT request: public void PutMovie(Movie movieToUpdate) { if (movieToUpdate.Id == 1) { // Update the movie in the database return; } // If you can't find the movie to update throw new HttpResponseException(HttpStatusCode.NotFound); } Unlike our PostMovie() method, the PutMovie() method does not return a result. The action either updates the database or, if the movie cannot be found, returns an HTTP Status code of 404. The following HTML page illustrates how you can invoke the PutMovie() method: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Put Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToUpdate = { id: 1, title: "The Hobbit", director: "Jackson" }; updateMovie(movieToUpdate, function () { alert("Movie updated!"); }); function updateMovie(movieToUpdate, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify(movieToUpdate), type: "PUT", contentType: "application/json;charset=utf-8", statusCode: { 200: function () { callback(); }, 404: function () { alert("Movie not found!"); } } }); } </script> </body> </html> Deleting a Record with the ASP.NET Web API Here’s the code for deleting a movie: public HttpResponseMessage DeleteMovie(int id) { // Delete the movie from the database // Return status code return new HttpResponseMessage(HttpStatusCode.NoContent); } This method simply deletes the movie (well, not really, but pretend that it does) and returns a No Content status code (204). The following page illustrates how you can invoke the DeleteMovie() action: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Delete Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> deleteMovie(1, function () { alert("Movie deleted!"); }); function deleteMovie(id, callback) { $.ajax({ url: "/api/Movie", data: JSON.stringify({id:id}), type: "DELETE", contentType: "application/json;charset=utf-8", statusCode: { 204: function () { callback(); } } }); } </script> </body> </html> Performing Validation How do you perform form validation when using the ASP.NET Web API? Because validation in ASP.NET MVC is driven by the Default Model Binder, and because the Web API uses the Default Model Binder, you get validation for free. Let’s modify our Movie class so it includes some of the standard validation attributes: using System.ComponentModel.DataAnnotations; namespace MyWebAPIApp.Models { public class Movie { public int Id { get; set; } [Required(ErrorMessage="Title is required!")] [StringLength(5, ErrorMessage="Title cannot be more than 5 characters!")] public string Title { get; set; } [Required(ErrorMessage="Director is required!")] public string Director { get; set; } } } In the code above, the Required validation attribute is used to make both the Title and Director properties required. The StringLength attribute is used to require the length of the movie title to be no more than 5 characters. Now let’s modify our PostMovie() action to validate a movie before adding the movie to the database: public HttpResponseMessage PostMovie(Movie movieToCreate) { // Validate movie if (!ModelState.IsValid) { var errors = new JsonArray(); foreach (var prop in ModelState.Values) { if (prop.Errors.Any()) { errors.Add(prop.Errors.First().ErrorMessage); } } return new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest); } // Add movieToCreate to the database and update primary key movieToCreate.Id = 23; // Build a response that contains the location of the new movie var response = new HttpResponseMessage<Movie>(movieToCreate, HttpStatusCode.Created); var relativePath = "/api/movie/" + movieToCreate.Id; response.Headers.Location = new Uri(Request.RequestUri, relativePath); return response; } If ModelState.IsValid has the value false then the errors in model state are copied to a new JSON array. Each property – such as the Title and Director property — can have multiple errors. In the code above, only the first error message is copied over. The JSON array is returned with a Bad Request status code (400 status code). The following HTML page illustrates how you can invoke our modified PostMovie() action and display any error messages: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Create Movie</title> </head> <body> <script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script> <script type="text/javascript"> var movieToCreate = { title: "The Hobbit", director: "" }; createMovie(movieToCreate, function (newMovie) { alert("New movie created with an Id of " + newMovie.Id); }, function (errors) { var strErrors = ""; $.each(errors, function(index, err) { strErrors += "*" + err + "n"; }); alert(strErrors); } ); function createMovie(movieToCreate, success, fail) { $.ajax({ url: "/api/Movie", data: JSON.stringify(movieToCreate), type: "POST", contentType: "application/json;charset=utf-8", statusCode: { 201: function (newMovie) { success(newMovie); }, 400: function (xhr) { var errors = JSON.parse(xhr.responseText); fail(errors); } } }); } </script> </body> </html> The createMovie() function performs an Ajax request and handles either a 201 or a 400 status code from the response. If a 201 status code is returned then there were no validation errors and the new movie was created. If, on the other hand, a 400 status code is returned then there was a validation error. The validation errors are retrieved from the XmlHttpRequest responseText property. The error messages are displayed in an alert: (Please don’t use JavaScript alert dialogs to display validation errors, I just did it this way out of pure laziness) This validation code in our PostMovie() method is pretty generic. There is nothing specific about this code to the PostMovie() method. In the following video, Jon Galloway demonstrates how to create a global Validation filter which can be used with any API controller action: http://www.asp.net/web-api/overview/web-api-routing-and-actions/video-custom-validation His validation filter looks like this: using System.Json; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace MyWebAPIApp.Filters { public class ValidationActionFilter:ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { var modelState = actionContext.ModelState; if (!modelState.IsValid) { dynamic errors = new JsonObject(); foreach (var key in modelState.Keys) { var state = modelState[key]; if (state.Errors.Any()) { errors[key] = state.Errors.First().ErrorMessage; } } actionContext.Response = new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest); } } } } And you can register the validation filter in the Application_Start() method in the Global.asax file like this: GlobalConfiguration.Configuration.Filters.Add(new ValidationActionFilter()); After you register the Validation filter, validation error messages are returned from any API controller action method automatically when validation fails. You don’t need to add any special logic to any of your API controller actions to take advantage of the filter. Querying using OData The OData protocol is an open protocol created by Microsoft which enables you to perform queries over the web. The official website for OData is located here: http://odata.org For example, here are some of the query options which you can use with OData: · $orderby – Enables you to retrieve results in a certain order. · $top – Enables you to retrieve a certain number of results. · $skip – Enables you to skip over a certain number of results (use with $top for paging). · $filter – Enables you to filter the results returned. The ASP.NET Web API supports a subset of the OData protocol. You can use all of the query options listed above when interacting with an API controller. The only requirement is that the API controller action returns its data as IQueryable. For example, the following Movie controller has an action named GetMovies() which returns an IQueryable of movies: public IQueryable<Movie> GetMovies() { return new List<Movie> { new Movie {Id=1, Title="Star Wars", Director="Lucas"}, new Movie {Id=2, Title="King Kong", Director="Jackson"}, new Movie {Id=3, Title="Willow", Director="Lucas"}, new Movie {Id=4, Title="Shrek", Director="Smith"}, new Movie {Id=5, Title="Memento", Director="Nolan"} }.AsQueryable(); } If you enter the following URL in your browser: /api/movie?$top=2&$orderby=Title Then you will limit the movies returned to the top 2 in order of the movie Title. You will get the following results: By using the $top option in combination with the $skip option, you can enable client-side paging. For example, you can use $top and $skip to page through thousands of products, 10 products at a time. The $filter query option is very powerful. You can use this option to filter the results from a query. Here are some examples: Return every movie directed by Lucas: /api/movie?$filter=Director eq ‘Lucas’ Return every movie which has a title which starts with ‘S’: /api/movie?$filter=startswith(Title,’S') Return every movie which has an Id greater than 2: /api/movie?$filter=Id gt 2 The complete documentation for the $filter option is located here: http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption Summary The goal of this blog entry was to provide you with an overview of the new ASP.NET Web API introduced with the Beta release of ASP.NET 4. In this post, I discussed how you can retrieve, insert, update, and delete data by using jQuery with the Web API. I also discussed how you can use the standard validation attributes with the Web API. You learned how to return validation error messages to the client and display the error messages using jQuery. Finally, we briefly discussed how the ASP.NET Web API supports the OData protocol. For example, you learned how to filter records returned from an API controller action by using the $filter query option. I’m excited about the new Web API. This is a feature which I expect to use with almost every ASP.NET application which I build in the future.

    Read the article

  • Why is CDATA needed and not working everywhere the same way?

    - by baptx
    In Firefox's and Chrome's consoles, this works (alerts script content): var script = document.createElement("script"); script.textContent = ( function test() { var a = 1; } ); document.getElementsByTagName("head")[0].appendChild(script); alert(document.getElementsByTagName("head")[0].lastChild.textContent); Using this code as a Greasemonkey script for Firefox works too. Now, if want to add a "private method" do() to test() It is not working anymore, in neither Firefox/Chrome console nor in a Greasemonkey script: var script = document.createElement("script"); script.textContent = ( function test() { var a = 1; var do = function () { var b = 2; }; } ); document.getElementsByTagName("head")[0].appendChild(script); alert(document.getElementsByTagName("head")[0].lastChild.textContent); To make this work in a Greasemonkey script, I have to put all the code in a CDATA tag block: var script = document.createElement("script"); script.textContent = (<![CDATA[ function test() { var a = 1; var do = function() { var b = 2; }; } ]]>); document.getElementsByTagName("head")[0].appendChild(script); alert(document.getElementsByTagName("head")[0].lastChild.textContent); This is only works in a Greasemonkey script; it throws an error from the Firefox/Chrome console. I don't understand why I should use a CDATA tag, I have no XML rules to respect here because I'm not using XHTML. To make it work in Firefox console (or Firebug), I need to do put CDATA into tags like <> and </>: var script = document.createElement("script"); script.textContent = (<><![CDATA[ function test() { var a = 1; var do = function() { var b = 2; }; } ]]></>); document.getElementsByTagName("head")[0].appendChild(script); alert(document.getElementsByTagName("head")[0].lastChild.textContent); This doesn't working from the Chrome console. I've tried adding .toString() at the end like many people are doing (]]></>).toString();), but it's useless. I tried to replace <> and </> with a tag name <foo> </foo> but that didn't work either. Why doesn't my first code snippet work if I define var do = function(){} inside another function? Why should I use CDATA as a workaround even if I'm not using XHTML? And why should I add <> </> for Firefox console if it's working without in a Greasemonkey script? Finally, what is the solution for Chrome and other browsers? EDIT: My bad, I've never used do-while in JS and I've created this example in a simple text editor, so I didn't see "do" was a reserved keyword :p But problem is still here, I've not initialized the Javascript class in my examples. With this new example, CDATA is needed for Greasemonkey, Firefox need CDATA between E4X <> </> and Chrome fails: var script = document.createElement("script"); script.textContent = ( <><![CDATA[var aClass = new aClass(); function aClass() { var a = 1; var aPrivateMethod = function() { var b = 2; alert(b); }; this.aPublicMethod = function() { var c = 3; alert(c); }; } aClass.aPublicMethod();]]></> ); document.getElementsByTagName("head")[0].appendChild(script); Question: why?

    Read the article

  • Azure Grid Computing - Worker Roles as HPC Compute Nodes

    - by JoshReuben
    Overview ·        With HPC 2008 R2 SP1 You can add Azure worker roles as compute nodes in a local Windows HPC Server cluster. ·        The subscription for Windows Azure like any other Azure Service - charged for the time that the role instances are available, as well as for the compute and storage services that are used on the nodes. ·        Win-Win ? - Azure charges the computer hour cost (according to vm size) amortized over a month – so you save on purchasing compute node hardware. Microsoft wins because you need to purchase HPC to have a local head node for managing this compute cluster grid distributed in the cloud. ·        Blob storage is used to hold input & output files of each job. I can see how Parametric Sweep HPC jobs can be supported (where the same job is run multiple times on each node against different input units), but not MPI.NET (where different HPC Job instances function as coordinated agents and conduct master-slave inter-process communication), unless Azure is somehow tunneling MPI communication through inter-WorkerRole Azure Queues. ·        this is not the end of the story for Azure Grid Computing. If MS requires you to purchase a local HPC license (and administrate it), what's to stop a 3rd party from doing this and encapsulating exposing HPC WCF Broker Service to you for managing compute nodes? If MS doesn’t  provide head node as a service, someone else will! Process ·        requires creation of a worker node template that specifies a connection to an existing subscription for Windows Azure + an availability policy for the worker nodes. ·        After worker nodes are added to the cluster, you can start them, which provisions the Windows Azure role instances, and then bring them online to run HPC cluster jobs. ·        A Windows Azure worker role instance runs a HPC compatible Azure guest operating system which runs on the VMs that host your service. The guest operating system is updated monthly. You can choose to upgrade the guest OS for your service automatically each time an update is released - All role instances defined by your service will run on the guest operating system version that you specify. see Windows Azure Guest OS Releases and SDK Compatibility Matrix (http://go.microsoft.com/fwlink/?LinkId=190549). ·        use the hpcpack command to upload file packages and install files to run on the worker nodes. see hpcpack (http://go.microsoft.com/fwlink/?LinkID=205514). Requirements ·        assuming you have an azure subscription account and the HPC head node installed and configured. ·        Install HPC Pack 2008 R2 SP 1 -  see Microsoft HPC Pack 2008 R2 Service Pack 1 Release Notes (http://go.microsoft.com/fwlink/?LinkID=202812). ·        Configure the head node to connect to the Internet - connectivity is provided by the connection of the head node to the enterprise network. You may need to configure a proxy client on the head node. Any cluster network topology (1-5) is supported). ·        Configure the firewall - allow outbound TCP traffic on the following ports: 80,       443, 5901, 5902, 7998, 7999 ·        Note: HPC Server  uses Admin Mode (Elevated Privileges) in Windows Azure to give the service administrator of the subscription the necessary privileges to initialize HPC cluster services on the worker nodes. ·        Obtain a Windows Azure subscription certificate - the Windows Azure subscription must be configured with a public subscription (API) certificate -a valid X.509 certificate with a key size of at least 2048 bits. Generate a self-sign certificate & upload a .cer file to the Windows Azure Portal Account page > Manage my API Certificates link. see Using the Windows Azure Service Management API (http://go.microsoft.com/fwlink/?LinkId=205526). ·        import the certificate with an associated private key on the HPC cluster head node - into the trusted root store of the local computer account. Obtain Windows Azure Connection Information for HPC Server ·        required for each worker node template ·        copy from azure portal - Get from: navigation pane > Hosted Services > Storage Accounts & CDN ·        Subscription ID - a 32-char hex string in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. In Properties pane. ·        Subscription certificate thumbprint - a 40-char hex string (you need to remove spaces). In Management Certificates > Properties pane. ·        Service name - the value of <ServiceName> configured in the public URL of the service (http://<ServiceName>.cloudapp.net). In Hosted Services > Properties pane. ·        Blob Storage account name - the value of <StorageAccountName> configured in the public URL of the account (http://<StorageAccountName>.blob.core.windows.net). In Storage Accounts > Properties pane. Import the Azure Subscription Certificate on the HPC Head Node ·        enable the services for Windows HPC Server  to authenticate properly with the Windows Azure subscription. ·        use the Certificates MMC snap-in to import the certificate to the Trusted Root Certification Authorities store of the local computer account. The certificate must be in PFX format (.pfx or .p12 file) with a private key that is protected by a password. ·        see Certificates (http://go.microsoft.com/fwlink/?LinkId=163918). ·        To open the certificates snapin: Run > mmc. File > Add/Remove Snap-in > certificates > Computer account > Local Computer ·        To import the certificate via wizard - Certificates > Trusted Root Certification Authorities > Certificates > All Tasks > Import ·        After the certificate is imported, it appears in the details pane in the Certificates snap-in. You can open the certificate to check its status. Configure a Proxy Client on the HPC Head Node ·        the following Windows HPC Server services must be able to communicate over the Internet (through the firewall) with the services for Windows Azure: HPCManagement, HPCScheduler, HPCBrokerWorker. ·        Create a Windows Azure Worker Node Template ·        Edit HPC node templates in HPC Node Template Editor. ·        Specify: 1) Windows Azure subscription connection info (unique service name) for adding a set of worker nodes to the cluster + 2)worker node availability policy – rules for deploying / removing worker role instances in Windows Azure o   HPC Cluster Manager > Configuration > Navigation Pane > Node Templates > Actions pane > New à Create Node Template Wizard or Edit à Node Template Editor o   Choose Node Template Type page - Windows Azure worker node template o   Specify Template Name page – template name & description o   Provide Connection Information page – Azure Subscription ID (text) & Subscription certificate (browse) o   Provide Service Information page - Azure service name + blob storage account name (optionally click Retrieve Connection Information to get list of available from azure – possible LRT). o   Configure Azure Availability Policy page - how Windows Azure worker nodes start / stop (online / offline the worker role instance -  add / remove) – manual / automatic o   for automatic - In the Configure Windows Azure Worker Availability Policy dialog -select days and hours for worker nodes to start / stop. ·        To validate the Windows Azure connection information, on the template's Connection Information tab > Validate connection information. ·        You can upload a file package to the storage account that is specified in the template - eg upload application or service files that will run on the worker nodes. see hpcpack (http://go.microsoft.com/fwlink/?LinkID=205514). Add Azure Worker Nodes to the HPC Cluster ·        Use the Add Node Wizard – specify: 1) the worker node template, 2) The number of worker nodes   (within the quota of role instances in the azure subscription), and 3)           The VM size of the worker nodes : ExtraSmall, Small, Medium, Large, or ExtraLarge.  ·        to add worker nodes of different sizes, must run the Add Node Wizard separately for each size. ·        All worker nodes that are added to the cluster by using a specific worker node template define a set of worker nodes that will be deployed and managed together in Windows Azure when you start the nodes. This includes worker nodes that you add later by using the worker node template and, if you choose, worker nodes of different sizes. You cannot start, stop, or delete individual worker nodes. ·        To add Windows Azure worker nodes o   In HPC Cluster Manager: Node Management > Actions pane > Add Node à Add Node Wizard o   Select Deployment Method page - Add Azure Worker nodes o   Specify New Nodes page - select a worker node template, specify the number and size of the worker nodes ·        After you add worker nodes to the cluster, they are in the Not-Deployed state, and they have a health state of Unapproved. Before you can use the worker nodes to run jobs, you must start them and then bring them online. ·        Worker nodes are numbered consecutively in a naming series that begins with the root name AzureCN – this is non-configurable. Deploying Windows Azure Worker Nodes ·        To deploy the role instances in Windows Azure - start the worker nodes added to the HPC cluster and bring the nodes online so that they are available to run cluster jobs. This can be configured in the HPC Azure Worker Node Template – Azure Availability Policy -  to be automatic or manual. ·        The Start, Stop, and Delete actions take place on the set of worker nodes that are configured by a specific worker node template. You cannot perform one of these actions on a single worker node in a set. You also cannot perform a single action on two sets of worker nodes (specified by two different worker node templates). ·        ·          Starting a set of worker nodes deploys a set of worker role instances in Windows Azure, which can take some time to complete, depending on the number of worker nodes and the performance of Windows Azure. ·        To start worker nodes manually and bring them online o   In HPC Node Management > Navigation Pane > Nodes > List / Heat Map view - select one or more worker nodes. o   Actions pane > Start – in the Start Azure Worker Nodes dialog, select a node template. o   the state of the worker nodes changes from Not Deployed to track the provisioning progress – worker node Details Pane > Provisioning Log tab. o   If there were errors during the provisioning of one or more worker nodes, the state of those nodes is set to Unknown and the node health is set to Unapproved. To determine the reason for the failure, review the provisioning logs for the nodes. o   After a worker node starts successfully, the node state changes to Offline. To bring the nodes online, select the nodes that are in the Offline state > Bring Online. ·        Troubleshooting o   check node template. o   use telnet to test connectivity: telnet <ServiceName>.cloudapp.net 7999 o   check node status - Deployment status information appears in the service account information in the Windows Azure Portal - HPC queries this -  see  node status information for any failed nodes in HPC Node Management. ·        When role instances are deployed, file packages that were previously uploaded to the storage account using the hpcpack command are automatically installed. You can also upload file packages to storage after the worker nodes are started, and then manually install them on the worker nodes. see hpcpack (http://go.microsoft.com/fwlink/?LinkID=205514). ·        to remove a set of role instances in Windows Azure - stop the nodes by using HPC Cluster Manager (apply the Stop action). This deletes the role instances from the service and changes the state of the worker nodes in the HPC cluster to Not Deployed. ·        Each time that you start a set of worker nodes, two proxy role instances (size Small) are configured in Windows Azure to facilitate communication between HPC Cluster Manager and the worker nodes. The proxy role instances are not listed in HPC Cluster Manager after the worker nodes are added. However, the instances appear in the Windows Azure Portal. The proxy role instances incur charges in Windows Azure along with the worker node instances, and they count toward the quota of role instances in the subscription.

    Read the article

  • Javascript || or operator with a undefinded variable

    - by bryan sammon
    I have been doing some reading lately one article I read was from Opera. http://dev.opera.com/articles/view/javascript-best-practices/ In that article they write this: Another common situation in JavaScript is providing a preset value for a variable if it is not defined, like so: if(v){ var x = v; } else { var x = 10; } The shortcut notation for this is the double pipe character: var x = v || 10; For some reason I cant get this to work for me. Is it really possible to check to see if v is defined, if not x = 10? --Thanks. Bryan

    Read the article

  • Exposing a pointer in Boost.Python

    - by Goose Bumper
    I have this very simple C++ class: class Tree { public: Node *head; }; BOOST_PYTHON_MODULE(myModule) { class_<Tree>("Tree") .def_readwrite("head",&Tree::head) ; } I want to access the head variable from Python, but the message I see is: No to_python (by-value) converter found for C++ type: Node* From what I understand, this happens because Python is freaking out because it has no concept of pointers. How can I access the head variable from Python? I understand I should use encapsulation, but I'm currently stuck with needing a non-encapsulation solution.

    Read the article

  • is it wasteful/bad design to use a vector/list where in most instances it will only have one element

    - by lucid
    is it wasteful/bad design to use a vector/list where in most instances it will only have one element? example: class dragon { ArrayList<head> = new ArrayList<head> Heads; tail Tail = new tail(); body Body = new body(); dragon() { theHead=new head(); Heads.add(theHead); } void nod() { for (int i=0;i<Heads.size();i++) { heads.get(i).GoUpAndDown(); } } } class firedragon extends dragon { } class icedragon extends dragon { } class lightningdragon extends dragon { } // 10 other one-headed dragon declarations here class hydra extends dragon { hydra() { anotherHead=new head(); for (int i=0;i<2;i++) { Heads.add(anotherHead); } } } class superhydra extends dragon { superhydra() { anotherHead=new head(); for (int i=0;i<4;i++) { Heads.add(anotherHead); } } }

    Read the article

  • typedef of a template with a template type as its parameter

    - by bryan sammon
    Im having a problem with a typedef below, I can seem to get it right: template <typename T> struct myclass1 { static const int member1 = T::GetSomeInt(); }; template <int I> struct myclass2 { typedef myclass1< myclass2<I> > anotherclass; static int GetSomeInt(); }; anotherclass MyObj1; // ERROR here not instantiating the class When I try and initialize a anotherclass object, it gives me an error. Any idea what I am doing wrong? There seems to be a problem with my typedef. Any help is appreciated, Thanks Bryan

    Read the article

  • How to get the changes on a branch in git

    - by Greg Hewgill
    What is the best way to get a log of commits on a branch since the time it was branched from the current branch? My solution so far is: git log $(git merge-base HEAD branch)..branch The documentation for git-diff indicates that "git diff A...B" is equivalent to "git diff $(git-merge-base A B) B". On the other hand, the documentation for git-rev-parse indicates that "r1...r2" is defined as "r1 r2 --not $(git merge-base --all r1 r2)". Why are these different? Note that "git diff HEAD...branch" gives me the diffs I want, but the corresponding git log command gives me more than what I want. In pictures, suppose this: x---y---z---branch / ---a---b---c---d---e---HEAD I would like to get a log containing commits x, y, z. "git diff HEAD...branch" gives these commits. However, "git log HEAD...branch" gives x, y, z, c, d, e.

    Read the article

  • How to ignore CDATA tags?

    - by Petre
    I'm trying to make an html parser, but when I load the html I get warnings like this Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: Invalid char in CDATA 0x1C in Entity, line: 1302 Here is the code I use class Parser { public $url=null; public $html=null; public $tidy=null; public $head=null; public $head_xpath=null; function __construct($url){ $this->url=$url; $this->html=file_get_contents($this->url); $this->tidy=tidy_parse_string($this->html); $this->head=new DOMDocument(); $this->head->loadHTML($this->tidy->head()); $this->head_xpath= new DOMXPath($this->head); } } $x=new Parser("http://www.guardian.co.uk/politics/2012/mar/24/vince-cable-coalition-banking-row"); I searched around and found the LIBXML_NOCDATA constant, but I don't know how to set it. So how could i completely ignore CDATA?

    Read the article

  • Undefined reference to ...

    - by Patrick LaChance
    I keep getting this error message every time I try to compile, and I cannot find out what the problem is. any help would be greatly appreciated: C:\DOCUME~1\Patrick\LOCALS~1\Temp/ccL92mj9.o:main.cpp:(.txt+0x184): undefined reference to 'List::List()' C:\DOCUME~1\Patrick\LOCALS~1\Temp/ccL92mj9.o:main.cpp:(.txt+0x184): undefined reference to 'List::add(int)' collect2: ld returned 1 exit status code: //List.h #ifndef LIST_H #define LIST_H #include <exception> //brief Definition of linked list class class List { public: /** \brief Exception for operating on empty list */ class Empty : public std::exception { public: virtual const char* what() const throw(); }; /** \brief Exception for invalid operations other than operating on an empty list */ class InvalidOperation : public std::exception { public: virtual const char* what() const throw(); }; /** \brief Node within List */ class Node { public: /** data element stored in this node */ int element; /** next node in list */ Node* next; /** previous node in list */ Node* previous; Node (int element); ~Node(); void print() const; void printDebug() const; }; List(); ~List(); void add(int element); void remove(int element); int first()const; int last()const; int removeFirst(); int removeLast(); bool isEmpty()const; int size()const; void printForward() const; void printReverse() const; void printDebug() const; /** enables extra output for debugging purposes */ static bool traceOn; private: /** head of list */ Node* head; /** tail of list */ Node* tail; /** count of number of nodes */ int count; }; #endif //List.cpp I only included the parts of List.cpp that might be the issue #include "List.h" #include <iostream> #include <iomanip> using namespace std; List::List() { //List::size = NULL; head = NULL; tail = NULL; } List::~List() { Node* current; while(head != NULL) { current = head-> next; delete current->previous; if (current->next!=NULL) { head = current; } else { delete current; } } } void List::add(int element) { Node* newNode; Node* current; newNode->element = element; if(newNode->element > head->element) { current = head->next; } else { head->previous = newNode; newNode->next = head; newNode->previous = NULL; return; } while(newNode->element > current->element) { current = current->next; } if(newNode->element <= current->element) { newNode->previous = current->previous; newNode->next = current; } } //main.cpp #include "List.h" #include <iostream> #include <string> using namespace std; //void add(int element); int main (char** argv, int argc) { List* MyList = new List(); bool quit = false; string value; int element; while(quit==false) { cin>>value; if(value == "add") { cin>>element; MyList->add(element); } if(value=="quit") { quit = true; } } return 0; } I'm doing everything I think I'm suppose to be doing. main.cpp isn't complete yet, just trying to get the add function to work first. Any help will be greatly appreciated.

    Read the article

  • Zend Framework: how to remove rendered views in the controller?

    - by takpar
    i want to render one of these sets of views: head body-$id1 foot OR head body-$id2 foot which set exsists. i do it like this: try { $this->render("head"); $this->render("body-$id1"); $this->render("foot"); } catch (Exception $e) { $this->render("head"); $this->render("body-$id2"); $this->render("foot"); } but it causes the head view be rendered twice if body-$id1 does not exists. do you have a better solution? in another saying, may i check the existance of body-$id1 before rendering it?

    Read the article

  • Javascript recursive data structure definition

    - by Matt Bierner
    I need to define a data structure recursively in Javascript. Here is a simple example of a circular linked list: // List a very simplified example of what the actual (non list) code does. function List(f, r) { return function(){ return [f, r]; }; } var head = List('a', List('b', List('c', head))); When this is executed, head in List 'c' is resolved to undefined, not List 'a' as I need. List is an example function that returns a function (It is not an Javascript list that I can append to). I tried to wrap the definition of head is a self executing named function, but that blew the stack when head was resolved. What is the Javascript style solution that I am overlooking?

    Read the article

  • Last element not getting insert in Tree

    - by rdk1992
    So I was asked to make a Binary Tree in Haskell taking as input a list of Integers. Below is my code. My problem is that the last element of the list is not getting inserted in the Tree. For example [1,2,3,4] it only inserts to the tree until "3" and 4 is not inserted in the Tree. data ArbolBinario a = Node a (ArbolBinario a) (ArbolBinario a) | EmptyNode deriving(Show) insert(x) EmptyNode= insert(tail x) (Node (head x) EmptyNode EmptyNode) insert(x) (Node e izq der) |x == [] = EmptyNode --I added this line to fix the Prelude.Head Empty List error, after I added this line the last element started to be ignored and not inserted in the tree |head x == e = (Node e izq der) |head x < e = (Node e (insert x izq) der) |head x > e = (Node e izq (insert x der)) Any ideas on whats going on here? Help is much appreciated

    Read the article

  • Hard drive failed, suspected filesystem corruption, still cannot salvage any data from harddrive

    - by Hippy-Head
    Firstly, I am terribly sorry if this is a duplicate, but I couldn't find a similar issue to mine, so here goes. I have a 1TB hdd bought around 8 months ago used as backup hard drive. I have not used the drive for a period of time whatsoever, and when I was trying to get back to some files on it, it was completely wiped just like that. At first it would not boot I tried everything from command line chkdsk and filesystem recovery software to rebuilt it. After a few attempts I managed to initialize it, at that time it was an achievement. The problems started when I tried to recover the data inside, I have used A LOT of software free and commercial software on both Mac and Windows, with the help of cmd or Terminal commands, however no data of any kind was recovered, even after leaving it thoroughly scan for around 9-10 hours all night sometimes longer, with no results at all. I am somewhat desperate, I am usually good at retrieving data from corrupt hard drives, but this is not the case. Call me paranoid, but I do not want to give it to someone to fix it for me, as I have a lot of photos and personal stuff that I do not want anyone to see.

    Read the article

  • Ragdoll continuous movement

    - by Siddharth
    I have created a ragdoll for my game but the problem I found was that the ragdoll joints are not perfectly implemented so they are continuously moving. Ragdoll does not stand at fix place. I here paste my work for that and suggest some guidance about that so that it can stand on fix place. chest = new Chest(pX, pY, gameObject.getmChestTextureRegion(), gameObject); head = new Head(pX, pY - 16, gameObject.getmHeadTextureRegion(), gameObject); leftHand = new Hand(pX - 6, pY + 6, gameObject.getmHandTextureRegion() .clone(), gameObject); rightHand = new Hand(pX + 12, pY + 6, gameObject .getmHandTextureRegion().clone(), gameObject); rightHand.setFlippedHorizontal(true); leftLeg = new Leg(pX, pY + 18, gameObject.getmLegTextureRegion() .clone(), gameObject); rightLeg = new Leg(pX + 7, pY + 18, gameObject.getmLegTextureRegion() .clone(), gameObject); rightLeg.setFlippedHorizontal(true); gameObject.getmScene().registerTouchArea(chest); gameObject.getmScene().attachChild(chest); gameObject.getmScene().registerTouchArea(head); gameObject.getmScene().attachChild(head); gameObject.getmScene().registerTouchArea(leftHand); gameObject.getmScene().attachChild(leftHand); gameObject.getmScene().registerTouchArea(rightHand); gameObject.getmScene().attachChild(rightHand); gameObject.getmScene().registerTouchArea(leftLeg); gameObject.getmScene().attachChild(leftLeg); gameObject.getmScene().registerTouchArea(rightLeg); gameObject.getmScene().attachChild(rightLeg); // head revolute joint revoluteJointDef = new RevoluteJointDef(); revoluteJointDef.enableLimit = true; revoluteJointDef.initialize(head.getHeadBody(), chest.getChestBody(), chest.getChestBody().getWorldCenter()); revoluteJointDef.localAnchorA.set(0f, 0f); revoluteJointDef.localAnchorB.set(0f, -0.5f); revoluteJointDef.lowerAngle = (float) (0f / (180 / Math.PI)); revoluteJointDef.upperAngle = (float) (0f / (180 / Math.PI)); headRevoluteJoint = (RevoluteJoint) gameObject.getmPhysicsWorld() .createJoint(revoluteJointDef); // // left leg revolute joint revoluteJointDef.initialize(leftLeg.getLegBody(), chest.getChestBody(), chest.getChestBody().getWorldCenter()); revoluteJointDef.localAnchorA.set(0f, 0f); revoluteJointDef.localAnchorB.set(-0.15f, 0.75f); revoluteJointDef.lowerAngle = (float) (0f / (180 / Math.PI)); revoluteJointDef.upperAngle = (float) (0f / (180 / Math.PI)); leftLegRevoluteJoint = (RevoluteJoint) gameObject.getmPhysicsWorld() .createJoint(revoluteJointDef); // right leg revolute joint revoluteJointDef.initialize(rightLeg.getLegBody(), chest.getChestBody(), chest.getChestBody().getWorldCenter()); revoluteJointDef.localAnchorA.set(0f, 0f); revoluteJointDef.localAnchorB.set(0.15f, 0.75f); revoluteJointDef.lowerAngle = (float) (0f / (180 / Math.PI)); revoluteJointDef.upperAngle = (float) (0f / (180 / Math.PI)); rightLegRevoluteJoint = (RevoluteJoint) gameObject.getmPhysicsWorld() .createJoint(revoluteJointDef); // left hand revolute joint revoluteJointDef.initialize(leftHand.getHandBody(), chest.getChestBody(), chest.getChestBody().getWorldCenter()); revoluteJointDef.localAnchorA.set(0f, 0f); revoluteJointDef.localAnchorB.set(-0.25f, 0.1f); revoluteJointDef.lowerAngle = (float) (0f / (180 / Math.PI)); revoluteJointDef.upperAngle = (float) (0f / (180 / Math.PI)); leftHandRevoluteJoint = (RevoluteJoint) gameObject.getmPhysicsWorld() .createJoint(revoluteJointDef); // right hand revolute joint revoluteJointDef.initialize(rightHand.getHandBody(), chest.getChestBody(), chest.getChestBody().getWorldCenter()); revoluteJointDef.localAnchorA.set(0f, 0f); revoluteJointDef.localAnchorB.set(0.25f, 0.1f); revoluteJointDef.lowerAngle = (float) (0f / (180 / Math.PI)); revoluteJointDef.upperAngle = (float) (0f / (180 / Math.PI)); rightHandRevoluteJoint = (RevoluteJoint) gameObject.getmPhysicsWorld() .createJoint(revoluteJointDef);

    Read the article

  • What affects video encoding speeds?

    - by Pig Head
    FRAPs doesn't compress its videos when you record, so the files are enormous. In a long recording you can get up to a few hundred gigabytes. Obviously, usually you would need to convert/compress them. What affects the speed of this? I don't think the RAM does, as when I converted 600 gb my RAM usage only went to 6 gig, but the processor was at 100%, which is surprising as I have a 6 core processor @ 3.46 ghz. Would clock speed or cores help the most?

    Read the article

  • Is there a way to snip part of the screen with a hotkey?

    - by Head of Catering
    I'm able to launch the snipping tool, select an option and then copy based on my selection. Is there a way to launch a default snipping option so that I can create partial screen screenshots without using a third-party tool? Essentially, I'm looking for winkey+S without having to use OneNote. Both OneNote and SnagIt implement this perfectly. If OneNote is running, pressing winkey+S allows me to click and drag any portion of the screen, including pop-out menus with selections that are active. SnagIt does almost the exact same thing, invoked by the prt screen key.

    Read the article

  • Excel Subtotal if adjacent column is not blank

    - by Head of Catering
    I'm trying to create a subtotal for a range that excludes rows that don't have a wholesale price. I have a range of products, prices and units that have subtotals by brand, although the brand subtotal is a sum and not a subtotal because the total needs to be displayed regardless of what the user chooses to filter. These subtotal rows do not have wholesale prices. Here is the sumif formula I'm using to calculate totals in the summary area above the range: =SUMIF(B5:B12, "", D5:D12) I need to have a subtotal formula that works the same way. Is there an equivalent to the sumif formula for subtotals? Or maybe a worksheet function I can use? I need to be able to do this without using VBA.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >