Daily Archives

Articles indexed Tuesday October 30 2012

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

  • C++ Linked List - Reading data from a file with a sentinel

    - by Nick
    So I've done quite a bit of research on this and can't get my output to work correctly. I need to read in data from a file and have it stored into a Linked List. The while loop used should stop once it hits the $$$$$ sentinel. Then I am to display the data (by searching by ID Number[user input]) I am not that far yet I just want to properly display the data and get it read in for right now. My problem is when it displays the data is isn't stopping at the $$$$$ (even if I do "inFile.peek() != EOF and omit the $$$$$) I am still getting an extra garbage record. I know it has something to do with my while loop and how I am creating a new Node but I can't get it to work any other way. Any help would be appreciated. students.txt Nick J Cooley 324123 60 70 80 90 Jay M Hill 412254 70 80 90 100 $$$$$ assign6.h file #pragma once #include <iostream> #include <string> using namespace std; class assign6 { public: assign6(); // constructor void displayStudents(); private: struct Node { string firstName; string midIni; string lastName; int idNum; int sco1; //Test score 1 int sco2; //Test score 2 int sco3; //Test score 3 int sco4; //Test score 4 Node *next; }; Node *head; Node *headPtr; }; assign6Imp.cpp // Implementation File #include "assign6.h" #include <fstream> #include <iostream> #include <string> using namespace std; assign6::assign6() //constructor { ifstream inFile; inFile.open("students.txt"); head = NULL; head = new Node; headPtr = head; while (inFile.peek() != EOF) //reading in from file and storing in linked list { inFile >> head->firstName >> head->midIni >> head->lastName; inFile >> head->idNum; inFile >> head->sco1; inFile >> head->sco2; inFile >> head->sco3; inFile >> head->sco4; if (inFile != "$$$$$") { head->next = NULL; head->next = new Node; head = head->next; } } head->next = NULL; inFile.close(); } void assign6::displayStudents() { int average = 0; for (Node *cur = headPtr; cur != NULL; cur = cur->next) { cout << cur->firstName << " " << cur->midIni << " " << cur->lastName << endl; cout << cur->idNum << endl; average = (cur->sco1 + cur->sco2 + cur->sco3 + cur->sco4)/4; cout << cur->sco1 << " " << cur->sco2 << " " << cur->sco3 << " " << cur->sco4 << " " << "average: " << average << endl; } }

    Read the article

  • chrome extension script is loading twice even more on some pages

    - by Youhan
    this is my background.js file chrome.tabs.onUpdated.addListener(function(tabId,info, tab) { var sites =new Array('site2','site1'); var url=tab.url; var siteFlag=0; for(var i in sites) { var regexp = new RegExp('.*' + sites[i] + '.*','i'); if (regexp.test(url)) {siteFlag=1;} }; if(siteFlag==1){ chrome.tabs.executeScript(tabId, {file:"contentscript.js"}); chrome.tabs.executeScript(tabId, {file:"jquery.js"}); chrome.tabs.insertCSS(tabId,{file:"box.css"}); } }); In the contentscript.js I simply run a popup box. $(document).ready(function () { function popup() {...} if (window.addEventListener) { window.addEventListener('load', popup(), false); } else if (window.attachEvent) { window.attachEvent('onload', popup()); } }); There are some pages that there are one popup-box and there are pages that two or even more what is the problem?

    Read the article

  • ASP.NET MVC 3 NOT showing appropriate view, action called using jquery

    - by TunAntun
    I have a small problem. My action is : public ViewResult SearchForRooms(int HotelDDL) { List<Room> roomsInHotel = bl.ReturnRoomsPerHotel(HotelDDL); return View(roomsInHotel); } Here is the jquery that is calling the action: <script type="text/javascript" language="javascript"> $(document).ready(function () { $("#HotelDDL").change(function () { var text = $("#HotelDDL option:selected").text(); var value = $("#HotelDDL option:selected").val(); alert("Selected text=" + text + " Selected value= " + value); $.post("/Home/SearchForRooms", { HotelDDL: $("#HotelDDL option:selected").val() }); }); }); </script> And finally, here is the View that should be called: @model IEnumerable<RoomReservation.Entities.Entities.Room> @{ ViewBag.Title = "Search"; } <h2>Result</h2> <table> <tr> <th> City </th> <th> Hotel </th> <th> Room label </th> <th> Number of beds </th> <th> Price per night </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelitem=>item.Hotel.City.Name) </td> <td> @Html.DisplayFor(modelItem => item.Hotel.Name) </td> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.NumberOfBeds) </td> <td> @Html.DisplayFor(modelItem => item.PricePerNight) </td> </tr> } </table> Everthing is working ok (databse return all rooms correctly) except final view rendering. I have tried Phil's tool but it doesn't give me any suspicious hints: RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); So, why is it not showing after jscript send it's post method to SearchForRooms()? Thank you P.S. If you need any other piece of code please just say so.

    Read the article

  • Upload Image with Django Model Form

    - by jmitchel3
    I'm having difficulty uploading the following model with model form. I can upload fine in the admin but that's not all that useful for a project that limits admin access. #Models.py class Profile(models.Model): name = models.CharField(max_length=128) user = models.ForeignKey(User) profile_pic = models.ImageField(upload_to='img/profile/%Y/%m/') #views.py def create_profile(request): try: profile = Profile.objects.get(user=request.user) except: pass form = CreateProfileForm(request.POST or None, instance=profile) if form.is_valid(): new = form.save(commit=False) new.user = request.user new.save() return render_to_response('profile.html', locals(), context_instance=RequestContext(request)) #Profile.html <form enctype="multipart/form-data" method="post">{% csrf_token %} <tr><td>{{ form.as_p }}</td></tr> <tr><td><button type="submit" class="btn">Submit</button></td></tr> </form> Note: All the other data in the form saves perfectly well, the photo does not upload at all. Thank you for your help!

    Read the article

  • WCF operationcontract with List type unavailable in (Silverlight) client

    - by Dave
    This is the first time I have tried returning a List of data to a Silverlight client, so I'm having trouble getting the client to recognize this operationcontract. All others are fine. I have a method on the server called ReadOwFileData that needs to return a List. ReadOwFileDataCompletedEventArgs shows up in the Object Browser in the client, but not ReadOwFileDataAsync. What I want is similar to the tutorial here. The Dictionary collection type on the client is set to System.Collections.Generic.List. I tried deleting and recreating the service reference. Web.Config on the server is using basicHttpBinding. Here is the operationcontract on the server: [OperationContract] public List<OwFileData> ReadOwFileData(string OrderID) { DataClasses1DataContext db = new DataClasses1DataContext(); var dFileData = (from p in db.OwFileDatas where p.OrderID == OrderID select p).ToList(); List<OwFileData> x = new List<OwFileData>(dFileData); return x; } Incidently, this works fine: [OperationContract] public Customer GetShippingAndContactInfo(string login, string ordernum) { DataClasses1DataContext db = new DataClasses1DataContext(); Customer dInfo = (from p in db.Customers where p.Login == login select p).Single(); return dInfo; } I would like to read this data in the client and place it into an object I created called ObservableCollection. But that obviously can't happen until the client can see the method on the server. I do not know if this is an acceptable start, but this is what is on the client so far. The ReadOwFileDataAsync object is null: void populatefilesReceivedDataSource(string OrderID) { ArtUpload.ServiceReference1.UploadServiceClient client = new ArtUpload.ServiceReference1.UploadServiceClient(); var myList = client.ReadOwFileDataAsync(OrderID); // can I just itterate thru the list instead of 'binding' }

    Read the article

  • best way to add and delete text lines with jquery product configurator

    - by Daniel White
    I am creating a product configurator with Jquery. My users can add custom text lines to their product. So you could create say... 4 text lines with custom text. I need to know what the best way to add and delete these lines would be. Currently I have the following code for adding lines... //Add Text Button $('a#addText').live('click', function(event) { event.preventDefault(); //Scroll up the text editor $('.textOptions').slideUp(); $('#customText').val(''); //count how many items are in the ul textList var textItems = $('ul#textList li').size(); var nextNumber = textItems + 1; if(textItems <= 5) { //Change input to reflect current text being changed $('input#currentTextNumber').val(nextNumber); //Append a UL Item to the textList $('ul#textList').append('<li id="textItem'+nextNumber+'">Text Line. +$5.00 <a class="deleteTextItem" href="'+nextNumber+'">Delete</a></li>'); //Scroll down the text editor $('.textOptions').slideDown(); }else { alert('you can have a maximum of 6 textual inputs!'); } }); I'm probably not doing this the best way, but basically i have an empty UL list to start with. So when they click "Add Text Line" it finds out how many list elements are in the unordered list, adds a value of 1 to that and places a new list element with the id TextItem1 or TextItem2 or whatever number we're on. The problem i'm running into is that when you click delete item, it screws everything up because when you add an item again all the numbers aren't correct. I thought about writing some kind of logic that says all the numbers above the one you want deleted get 1 subtracted from their value and all the numbers below stay the same. But I think i'm just going about this the wrong way. Any suggestions on the easiest way to add and delete these text lines is appreciated.

    Read the article

  • Android ksoap nested soap objects in request gives error in response

    - by Smalesy
    I'm trying to do the following soap request on Android using KSOAP. It contains a list of nested soap objects. However, I must be doing something wrong as I get an error back. The request I am trying to generate is as follows: <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> <SetAttendanceMarks xmlns="http://hostname.net/"> <strSessionToken>string</strSessionToken> <LessonMarks> <Count>int</Count> <LessonMarks> <LessonMark> <StudentId>int</StudentId> <EventInstanceId>int</EventInstanceId> <Mark>string</Mark> </LessonMark> <LessonMark> <StudentId>int</StudentId> <EventInstanceId>int</EventInstanceId> <Mark>string</Mark> </LessonMark> </LessonMarks> </LessonMarks> </SetAttendanceMarks> </soap12:Body> </soap12:Envelope> My code is as follows: public boolean setAttendanceMarks(List<Mark> list) throws Exception { boolean result = false; String methodName = "SetAttendanceMarks"; String soapAction = getHost() + "SetAttendanceMarks"; SoapObject lessMarksN = new SoapObject(getHost(), "LessonMarks"); for (Mark m : list) { PropertyInfo smProp =new PropertyInfo(); smProp.setName("LessonMark"); smProp.setValue(m); smProp.setType(Mark.class); lessMarksN.addProperty(smProp); } PropertyInfo cProp =new PropertyInfo(); cProp.setName("Count"); cProp.setValue(list.size()); cProp.setType(Integer.class); SoapObject lessMarks = new SoapObject(getHost(), "LessonMarks"); lessMarks.addProperty(cProp); lessMarks.addSoapObject(lessMarksN); PropertyInfo sProp =new PropertyInfo(); sProp.setName("strSessionToken"); sProp.setValue(mSession); sProp.setType(String.class); SoapObject request = new SoapObject(getHost(), methodName); request.addProperty(sProp); request.addSoapObject(lessMarks); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(getURL()); androidHttpTransport.debug = true; androidHttpTransport.call(soapAction, envelope); String a = androidHttpTransport.requestDump; String b = androidHttpTransport.responseDump; SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn; SoapObject res = (SoapObject) resultsRequestSOAP.getProperty(0); String resultStr = res.getPropertyAsString("Result"); if (resultStr.contentEquals("OK")) { result = true; } return result; } The error I get is as follows: <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <soap:Fault> <soap:Code> <soap:Value>soap:Sender</soap:Value> </soap:Code> <soap:Reason> <soap:Text xml:lang="en">Server was unable to read request. ---&gt; There is an error in XML document (1, 383). ---&gt; The specified type was not recognized: name='LessonMarks', namespace='http://gsdregapp.net/', at &lt;LessonMarks xmlns='http://gsdregapp.net/'&gt;.</soap:Text> </soap:Reason> <soap:Detail /> </soap:Fault> </soap:Body> </soap:Envelope> Can anybody tell me what I am doing wrong? I will be most grateful for any assistance!

    Read the article

  • Optimizing memory usage and changing file contents with PHP

    - by errata
    In a function like this function download($file_source, $file_target) { $rh = fopen($file_source, 'rb'); $wh = fopen($file_target, 'wb'); if (!$rh || !$wh) { return false; } while (!feof($rh)) { if (fwrite($wh, fread($rh, 1024)) === FALSE) { return false; } } fclose($rh); fclose($wh); return true; } what is the best way to rewrite last few bytes of a file with my custom string? Thanks!

    Read the article

  • Region or ItemsSource for large data set in ListBox

    - by Ryan
    I'm having trouble figuring out what the best solution is given the following situation. I'm using Prism 4.1, MEF, and .Net 4.0. I have an object Project that could have a large number (~1000) of Line objects. I'm deciding whether it is better to expose an ObservableCollection<LineViewModel> from my ProjectViewModel and manually create the Line viewmodels there OR set the ListBox as it's own region and activate views that way. I'd still want my LineViewModel to have Prism's shared services (IEventAggregator, etc.) injected, but I don't know how to do that when I manually create the LineViewModel. Any suggestions or thoughts?

    Read the article

  • Returning and printing string array index in C

    - by user1781966
    I've got a function that searches through a list of names and I'm trying to get the search function to return the index of the array back to the main function and print out the starting location of the name found. Everything I've tried up to this point either crashes the program or results in strange output. Here is my search function: #include<stdio.h> #include<conio.h> #include<string.h> #define MAX_NAMELENGTH 10 #define MAX_NAMES 5 void initialize(char names[MAX_NAMES][MAX_NAMELENGTH], int Number_entrys, int i); int search(char names[MAX_NAMES][MAX_NAMELENGTH], int Number_entrys); int main() { char names[MAX_NAMES][MAX_NAMELENGTH]; int i, Number_entrys,search_result,x; printf("How many names would you like to enter to the list?\n"); scanf("%d",&Number_entrys); initialize(names,Number_entrys,i); search_result= search(names,Number_entrys); if (search_result==-1){ printf("Found no names.\n"); }else { printf("%s",search_result); } getch(); return 0; } void initialize(char names[MAX_NAMES][MAX_NAMELENGTH],int Number_entrys,int i) { if(Number_entrys>MAX_NAMES){ printf("Please choose a smaller entry\n"); }else{ for (i=0; i<Number_entrys;i++){ scanf("%s",names[i]); } } } int search(char names[MAX_NAMES][MAX_NAMELENGTH],int Number_entrys) { int x; char new_name[MAX_NAMELENGTH]; printf("Now enter a name in which you would like to search the list for\n"); scanf("%s",new_name); for(x = 0; x < Number_entrys; x++) { if ( strcmp( new_name, names[x] ) == 0 ) { return x; } } return -1; } Like I mentioned before I have tried a lot of different ways to try and fix this issue, but I cant seem to get them to work. Printing X like what I have above is just the last thing I tried, and therefor know that it doesn't work. Any suggestions on the simplest way to do this?

    Read the article

  • Why does `Array.length`, `Function.length`, `String.length`, etc return 1?

    - by zealoushacker
    While teaching my JavaScript class yesterday, my students and I came across some interesting functionality that I thought might be worth capturing in a question and the answer I've come to. Typing Array.length in the JS console in chrome returns 1. Likewise, Function.length returns 1. This is important because: Every function in JavaScript is actually a Function object. (MDN JS Ref: Function) Thus, Object.length and likely all other native objects will and should return 1 as the value of the length property. So, finally why is this behavior occurring?

    Read the article

  • Create macro to move data in a column UP?

    - by user1786695
    I have an excel sheet of which the data was jumbled: for example, the data that should have been in Columns AB and AC were instead in Columns B and C, but on the row after. I have the following written which moved the data from B and C to AB and AC respectively: Dim rCell As Range Dim rRng As Range Set rRng = Sheet1.Range("A:A") i = 1 lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row For Each rCell In rRng.Cells If rCell.Value = "" Then Range("AB" & i) = rCell.Offset(0, 1).Value rCell.Offset(0, 1).ClearContents End If i = i + 1 If i = lastRow + 1 Then Exit Sub End If Next rCell End Sub However, it doesn't fix the problem of the data being on the row BELOW the appropriate row now that they are in the right columns. I am new to VBA Macros so I would appreciate any help to make the data now align. I tried toggling the Offset parameter (-1,0) but it's not working.

    Read the article

  • Strange output produced by program

    - by Boom_mooB
    I think that my code works. However, it outputs 01111E5, or 17B879DD, or something like that. Can someone please tell me why. I am aware that I set the limit of P instead of 10,001. My code is like that because I start with 3, skipping the prime number 2. #include <iostream> bool prime (int i) { bool result = true; int isitprime = i; for(int j = 2; j < isitprime; j++) ///prime number tester { if(isitprime%j == 0) result = false; } return result; } int main (void) { using namespace std; int PrimeNumbers = 1; int x = 0; for (int i = 3 ; PrimeNumbers <=10000; i++) { if(prime(i)) { int prime = i; PrimeNumbers +=1; } } cout<<prime<<endl; system ("pause"); return 0; }

    Read the article

  • How can I display the clicked products by user on a list in another view?

    - by Avar
    I am using MVC3 Viewmodel pattern with Entity Framework on my webbapplication. My Index View is list of products with image, price and description and etc. Products with the information I mentioned above is in div boxes with a button that says "buy". I will be working with 2 views one that is the Index View that will display all the products and the other view that will display the products that got clicked by the buy button. What I am trying to achieve is when a user click on buy button the products should get stored in the other view that is cart view and be displayed. I have problems on how to begin the coding for that part. The index View with products is done and now its the buy button function left to do but I have no idea how to start. This is my IndexController: private readonly HomeRepository repository = new HomeRepository(); public ActionResult Index() { var Productlist = repository.GetAllProducts(); var model = new HomeIndexViewModel() { Productlist = new List<ProductsViewModel>() }; foreach (var Product in Productlist) { FillProductToModel(model, Product); } return View(model); } private void FillProductToModel(HomeIndexViewModel model, ProductImages productimage) { var productViewModel = new ProductsViewModel { Description = productimage.Products.Description, ProductId = productimage.Products.Id, price = productimage.Products.Price, Name = productimage.Products.Name, Image = productimage.ImageUrl, }; model.Productlist.Add(productViewModel); } In my ActionResult Index I am using my repository to get the products and then I am binding the data from the products to my ViewModel so I can use the ViewModel inside my view. Thats how I am displaying all the products in my View. This is my Index View: @model Avan.ViewModels.HomeIndexViewModel @foreach (var item in Model.Productlist) { <div id="productholder@(item.ProductId)" class="productholder"> <img src="@Html.DisplayFor(modelItem => item.Image)" alt="" /> <div class="productinfo"> <h2>@Html.DisplayFor(modelItem => item.Name)</h2> <p>@Html.DisplayFor(modelItem => item.Description)</p> @Html.Hidden("ProductId", item.ProductId, new { @id = "ProductId" }) </div> <div class="productprice"> <h2>@Html.DisplayFor(modelItem => item.price)</h2> <input type="button" value="Läs mer" class="button" id="button@(item.ProductId)"> @Html.ActionLink("x", "Cart", new { id = item.ProductId }) // <- temp its going to be a button </div> </div> } Since I can get the product ID per product I can use the ID in my controller to get the data from the database. But I still I have no idea how I can do that so when somebody click on the buy button I store the ID where? and how do I use it so I can achieve what I want to do? Right now I have been trying to do following thing in my IndexController: public ActionResult cart(int id) { var SelectedProducts = repository.GetProductByID(id); return View(); } What I did here is that I get the product by the id. So when someone press on the temp "x" Actionlink I will recieve the product. All I know is that something like that is needed to achieve what im trying to do but after that I have no idea what to do and in what kind of structure I should do it. Any kind of help is appreciated alot! Short Scenario: looking at the Index I see 5 products, I choose to buy 3 products so I click on three "Buy" buttons. Now I click on the "Cart" that is located on the nav menu. New View pops up and I see the three products that I clicked to buy.

    Read the article

  • Excel, VBA Vlookup, multiple returns into rows

    - by Sean Mc
    Very new to VBA, so please excuse my ignorance. How would you alter the code below to return the result into rows as opposed to a string? Thanks in advance.... data Acct No CropType ------- --------- 0001 Grain 0001 OilSeed 0001 Hay 0002 Grain function =vlookupall("0001", A:A, 1, " ") Here is the code: Function VLookupAll(ByVal lookup_value As String, _ ByVal lookup_column As range, _ ByVal return_value_column As Long, _ Optional seperator As String = ", ") As String Application.ScreenUpdating = False Dim i As Long Dim result As String For i = 1 To lookup_column.Rows.count If Len(lookup_column(i, 1).text) <> 0 Then If lookup_column(i, 1).text = lookup_value Then result = result & (lookup_column(i).offset(0, return_value_column).text & seperator) End If End If Next If Len(result) <> 0 Then result = Left(result, Len(result) - Len(seperator)) End If VLookupAll = result Application.ScreenUpdating = True End FunctionNotes:

    Read the article

  • PCI function number for SATA AHCI controller

    - by Look Alterno
    I'm debugging a second stage boot loader for a PC with SATA AHCI controller. I'm able to enumerate the PCI bus and find the hard disk. So far, so good. Now, lspci in my notebook (Dell Inspiron 1525) show me: -[0000:00]-+-1f.0 Intel Corporation 82801HEM (ICH8M) LPC Interface Controller +-1f.1 Intel Corporation 82801HBM/HEM (ICH8M/ICH8M-E) IDE Controller +-1f.2 Intel Corporation 82801HBM/HEM (ICH8M/ICH8M-E) SATA AHCI Controller \-1f.3 Intel Corporation 82801H (ICH8 Family) SMBus Controller My question: Is SATA AHCI Controller always function 2 in any PC? If not, how I found? I don't pretend to be general; booting my notebook will be good enough, without compromise further refinements.

    Read the article

  • Rails validation count limit on has_many :through

    - by Jeremy
    I've got the following models: Team, Member, Assignment, Role The Team model has_many Members. Each Member has_many roles through assignments. Role assignments are Captain and Runner. I have also installed devise and CanCan using the Member model. What I need to do is limit each Team to have a max of 1 captain and 5 runners. I found this example, and it seemed to work after some customization, but on update ('teams/1/members/4/edit'). It doesn't work on create ('teams/1/members/new'). But my other validation (validates :role_ids, :presence = true ) does work on both update and create. Any help would be appreciated. Update: I've found this example that would seem to be similar to my problem but I can't seem to make it work for my app. It seems that the root of the problem lies with how the count (or size) is performed before and during validation. For Example: When updating a record... It checks to see how many runners there are on a team and returns a count. (i.e. 5) Then when I select a role(s) to add to the member it takes the known count from the database (i.e. 5) and adds the proposed changes (i.e. 1), and then runs the validation check. (Team.find(self.team_id).members.runner.count 5) This works fine because it returns a value of 6 and 6 5 so the proposed update fails without saving and an error is given. But when I try to create a new member on the team... It checks to see how many runners there are on a team and returns a count. (i.e. 5) Then when I select a role(s) to add to the member it takes the known count from the database (i.e. 5) and then runs the validation check WITHOUT factoring in the proposed changes. This doesn't work because it returns a value of 5 known runner and 5 = 5 so the proposed update passes and the new member and role is saved to the database with no error. Member Model: class Member < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :password, :password_confirmation, :remember_me attr_accessible :age, :email, :first_name, :last_name, :sex, :shirt_size, :team_id, :assignments_attributes, :role_ids belongs_to :team has_many :assignments, :dependent => :destroy has_many :roles, through: :assignments accepts_nested_attributes_for :assignments scope :runner, joins(:roles).where('roles.title = ?', "Runner") scope :captain, joins(:roles).where('roles.title = ?', "Captain") validate :validate_runner_count validate :validate_captain_count validates :role_ids, :presence => true def validate_runner_count if Team.find(self.team_id).members.runner.count > 5 errors.add(:role_id, 'Error - Max runner limit reached') end end def validate_captain_count if Team.find(self.team_id).members.captain.count > 1 errors.add(:role_id, 'Error - Max captain limit reached') end end def has_role?(role_sym) roles.any? { |r| r.title.underscore.to_sym == role_sym } end end Member Controller: class MembersController < ApplicationController load_and_authorize_resource :team load_and_authorize_resource :member, :through => :team before_filter :get_team before_filter :initialize_check_boxes, :only => [:create, :update] def get_team @team = Team.find(params[:team_id]) end def index respond_to do |format| format.html # index.html.erb format.json { render json: @members } end end def show respond_to do |format| format.html # show.html.erb format.json { render json: @member } end end def new respond_to do |format| format.html # new.html.erb format.json { render json: @member } end end def edit end def create respond_to do |format| if @member.save format.html { redirect_to [@team, @member], notice: 'Member was successfully created.' } format.json { render json: [@team, @member], status: :created, location: [@team, @member] } else format.html { render action: "new" } format.json { render json: @member.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @member.update_attributes(params[:member]) format.html { redirect_to [@team, @member], notice: 'Member was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @member.errors, status: :unprocessable_entity } end end end def destroy @member.destroy respond_to do |format| format.html { redirect_to team_members_url } format.json { head :no_content } end end # Allow empty checkboxes # http://railscasts.com/episodes/17-habtm-checkboxes def initialize_check_boxes params[:member][:role_ids] ||= [] end end _Form Partial <%= form_for [@team, @member], :html => { :class => 'form-horizontal' } do |f| %> #... # testing the count... <ul> <li>Captain - <%= Team.find(@member.team_id).members.captain.size %></li> <li>Runner - <%= Team.find(@member.team_id).members.runner.size %></li> <li>Driver - <%= Team.find(@member.team_id).members.driver.size %></li> </ul> <div class="control-group"> <div class="controls"> <%= f.fields_for :roles do %> <%= hidden_field_tag "member[role_ids][]", nil %> <% Role.all.each do |role| %> <%= check_box_tag "member[role_ids][]", role.id, @member.role_ids.include?(role.id), id: dom_id(role) %> <%= label_tag dom_id(role), role.title %> <% end %> <% end %> </div> </div> #... <% end %>

    Read the article

  • c++ "interface"-like classes similar to Java?

    - by William the Coderer
    In Java, you can define an interface as a class with no actual code implementation, but only to define the methods that a class must implement. Those types can be passed as parameters to methods and returned from methods. In C++, a pure virtual class can't be used as a parameter or return type, from what I can tell. Any way to mimic Java's interface classes? I have a string class in C++, and several subclasses for different encodings (like UTFxxx, ISOxxx, etc) that derive from the base string class. However, since there are so many different encodings, the base class has no meaningful implementation. But it would serve well as an interface if I could handle it as its own object and calls to that object would call on the correct subclass it was inherited to.

    Read the article

  • Selecting a column that is also a keyword in MySQL

    - by randall123
    For some reason, the developers at a new company I'm working for decided to name their columns "ignore" and "exists". Now when I run MySQL queries with those words in the where clause, I get a syntax error; however, I can't seem to figure out how to reference those columns without running into an error. I tried setting them as strings, but that doesn't make any sense. Help? Also, is there a term for this kind of mismatch?

    Read the article

  • Microsoft Build 1st Day

    - by Dave Noderer
    Great keynote and I don’t like keynotes.. Seeing the great breadth of large and small devices and the number of manufacturers along with the software vision for Windows 8 and Windows Phone 8 was inspiring. Jordan Rudess demonstrates Tachyon on Windows 8 Then he played for a while too..   I especially liked Steve Balmers 82” slate!! Can I have one!   And best of all, they finally released the Windows Phone 8 SDK. http://www.microsoft.com/en-us/download/details.aspx?id=35471 Off to sessions…   Stay tuned for more!

    Read the article

  • Book Review: Getting Started With Window 8 Apps By Ben Dewey

    - by Tim Murphy
    When O’Reilly gave me an opportunity to review this book I was excited.  It gave me a reason to finally put some time into this new platform and what developers will need to learn in order to be successful. This book by Ben Dewey is only 92 pages long, so if you were looking for an in-depth treatment of Windows 8 development you will need supplemental materials.  It is also due for an update from the perspective of recent changes made by Microsoft prior to the final release of the OS and tools.  This causes a few issues if you try to run the code samples because of namespace changes. I was encouraged by the fact that the author didn’t do the typical “hello world” app.  He uses a lot of pattern based development techniques and hits many of the main topics including: Application lifecycle Charms integration Tiles Sensors The lifecycle is critical for anyone who hasn’t done mobile development before.  Limited resources on these devices mean that the OS can suspend or kill your app altogether if it decides it needs to.  He covers tombstoning which is the key to Windows 8 and Windows Phone lifecycle management. He also dedicates a chapter to marketing and distributing the application you build.  From my experience with Windows Phone development this is crucial information.  You need to know how to test your application so that it is going to pass certification and present your app so that it is going to get noticed amongst thousands of other apps. The main things that I wish had been in the book explanations of more of the common controls and more complete explanation of patterns that were implemented. In the end this book is a good foundation getting exposure to the concepts that underlie this new version of the Windows platform and how it effects developers.  It isn’t a book that I would suggest for someone just getting into development with no understanding of pattern based development. del.icio.us Tags: Windows 8,O'Reilly,Ben Dewey,Book Review,Review

    Read the article

  • Microsoft Build 2012 Day 1 Keynote Summary

    - by Tim Murphy
    So I have finally dried the tears after watching the Keynote for Build 2012.  This wasn’t because it was an emotional presentation, but because for the second year I missed the goodies.  Each on site attendee got a Surface RT, a Lumia 920 and a voucher for 100GB of SkyDrive storage. The event was opened with the announcement that in the three days since the launch of Windows 8 over 4 million upgrades have been sold.  I don’t care who you are that is an impressive stat.  Ballmer then spent a fair amount of time remaking the case for the Windows and Windows Phone platforms similar to what we have heard over the last to launch events. There were some cool, but non-essential demos.  The one that was the most fun was the Perceptive Pixel 82” slate device.  At first glance I wondered why I would ever want such a device, but then Ballmer explained it’s possible use for schools and boardrooms.  The actually made sense. Then things got strange.  Steve started explaining features that developers could leverage.  Usually this type of information is left to the product leads.  He focused on the integration with the Charms features such as Search and Share. Steve “Guggs” Guggenheim showed off an app that would appeal to my kids from Disney called “Agent P” which is base on Phineas and Ferb.  Then he got to the meat of the presentation.  We found out that you could add a tile that can be used to sell ad space.  In the same vein we also found out that you could use Microsoft’s, Paypal’s or any commerce engine of your own creation or choosing. For those who are interested in sports and especially developing sports apps you would have found the small presentation from Michael Bayle of ESPN.  He introduced the ESPN app which has tons of features.  For the developers in the crowd he also mentioned that ESPN has an API available at developer.espn.com. During the launch events we were told apps were coming.  In this presentation we were actually shown a scrolling list of logos and told about a couple of them.  Ballmer mentioned specifically Twitter, SAP and DropBox.  These are impressive names that were just a couple of the list impressive names. Steve Ballmer addressed the question of why you should develop for the Windows 8 platform.  He feels that Microsoft has the best commercial terms for developers, a better way to build apps than other platforms and a variety of form factors.  His key point though was the available volume of customers given the current Windows install base and assuming even a flat growth of the platform.  This he backed with a promise that Microsoft is going to do better at marketing and you won’t be able to avoid the ads that they are bringing out. The last section of the key note was present by Kevin Gallo from the Windows Phone team.  This was the real reason I tuned into the webcast.  He impressed upon those watching that the strength of developing for the Microsoft platform is the common programming model that now exist.  While there are difference between form factor implementations you can leverage code across them. He claimed that 90% of developer requests for Windows Phone 8 had been implemented.  These include: More controls with better performance Better live tiles including lock screen integration Speech support in custom apps Easier submission to the market place App camera integration VOIP and chat support Bluetooth and NFC support Native C++ development Direct 3D development   The quote from Kevin that stood out for me was that “Take your Dramamine and buckle your seatbelt type of games are coming to Windows Phone 8”.  He back this up by displaying a list of game development frameworks and then having Unity come out and do a demo. Ok, almost done … The last two things of note for me were the announcement that the SDK is immediately available at dev.windowsphone.com and that they were reducing the cost of an individual developer account to $8 for the next 8 days. Let the development commence. del.icio.us Tags: Build 2012,Windows 8,Windows Phone 8,Windows Phone

    Read the article

  • MVVM Light V4.1 with support for Windows Phone 8

    - by Laurent Bugnion
    Today is a very exciting day: After the official release of Windows 8 (and Microsoft Surface!) on Friday, and the official release of Windows Phone 8 on Monday, the Build conference is starting! This is the conference in which we will learn all about the developer experience for Windows 8 and Windows Phone 8. As a partner of Microsoft, I had the privilege of trying out some of the new things early, and this gave me the opportunity to port MVVM Light to Windows Phone 8 (it was already running for Windows 8), and today I am officially publishing this new version. Before you go and update, please not the following: V4.1 (4.1.24.0) only supports Visual Studio 2012 (and Express). If for some reason you are still using Visual Studio 2010, don’t despair! In the next few days I will publish an update supporting these versions as well. But for now, please only upgrade if you are on VS12! That being said, here we go: The download page is available on Codeplex and you can download the updated MSI and install it. Please make sure to read the Readme HTML page that automatically opens in your web browser after the MSI completes! It contains important information on how to install selected Project and Item templates for the frameworks of your choice. This version also support the following versions of Visual Studio: Visual Studio 2012 Pro, Premium, Ultimate Visual Studio 2012 Express for Windows 8 Visual Studio 2012 Express for Windows Phone 8 Visual Studio 2012 Express for Web (Silverlight 4, Silverlight 5) Visual Studio 2012 Express for Windows Desktop (WPF3.5, WPF4, WPF4.5) We also support Expression Blend of course. Windows Phone 8 and Windows 8 are very very exciting opportunities for developers in the whole world. There are already a number of apps running on top of MVVM Light in the Windows Store and of course a large range of apps for Windows Phone too. With this release, we hope to support the developers and speed up application development. It is a pleasure to serve such an innovative and creative community! Happy coding Laurent   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

  • Windows Phone 8 SDK

    - by Nikita Polyakov
    Yesterday, the new Windows Phone 8 was announced! Find out more about the cool new OS and the new devices supporting it at www.WindowsPhone.com Today at BUILD conference in Redmond, WA – Microsoft has announced general availability of the Developer SDK for Windows Phone 8! Get the SDK and more info in the dev center: http://dev.WindowsPhone.com Also watch the Windows Phone Developer blog. Also this is the best time to join the Windows Phone Store for just for $8 for next 8 days.

    Read the article

  • Office 365 domain federation conversion failed

    - by Matt Bear
    We're doing things backwards, we have an established o365 domain, with 400+ users, and are just now deploying local AD, and ADFS for SSO. Last night, after configuring my servers, I ran the powershell command convert-MSOLdomaintofederated to convert the xxx.com vanity domain to federated, it errored out with an unspecified error(Microsoft ADFS support said the error has to do with the default password settings being changed.) And when I run convert-MSOLdomaintostandard, it comes back with the domain is already standard. Also in the o365 portal it shows the domain as standard, however it is trying to process login attempts as if it were a federated domain. I've spent 5 hours total on the phone with Microsoft, and it has been escalated to their engineering department for resolution, sometime within the next few days... I need it yesterday. From what we can gather, the conversion process started, error out, changed some of the internal configurations to federated, but left the description as standard.(if that makes since). So its in a weird limbo, where its in both modes but neither at the same time. Currently, the only way to fix it is to remove the vanity domain, and re-add it. I need a way to dissociate the user accounts from xxx.com domain to allow its removal. Removal of all the users themselves is not an option.

    Read the article

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