Search Results

Search found 3076 results on 124 pages for 'beginner'.

Page 17/124 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • Java: How to have an ArrayList as instance variable of an object?

    - by JDelage
    All, I'm working on a class project to build a little Connect4 game in Java. My current thinking is to have a class of Columns that have as instance variable a few integers (index, max. length, isFull?) and one ArrayList to receive both the integers above and the plays of each players (e.g., 1's and 0's standing for X's and O's). This is probably going to be split between 2 classes but the question remains the same. My current attempt looks like this: import java.util.ArrayList; public class Conn4Col { public int hMax; public int index; public final int initialSize = 0; public final int fullCol = 0; public ArrayList<Integer>; (...)} Unfortunately, this doesn't compile. The compiler says an is missing where my ArrayList declaration stands. We're just starting objects and we haven't really looked into other instance variables than the basic types. Can someone tell me where my error is and how to correct it? Many thanks, JDelage

    Read the article

  • How to make Python Extensions for Windows for absolute beginners

    - by JR
    Hello: I've been looking around the internet trying to find a good step by step guide to extend Python in Windows, and I haven't been able to find something for my skill level. let's say you have some c code that looks like this: #include <stdio.h> #include <math.h> double valuex(float value, double rate, double timex) { float value; double rate, timex; return value / double pow ((1 + rate), (timex)); } and you want to turn that into a Python 3 module for use on a windows (64bit if that makes a difference) system. How would you go about doing that? I've looked up SWIG and Pyrex and in both circumstances they seem geared towards the unix user. With Pyrex I am not sure if it works with Python 3. I'm just trying to learn the basics of programing, using some practical examples. Lastly, if there is a good book that someone can recommend for learning to extend, I would greatly appreciate it. Thank you.

    Read the article

  • Rails Message This User Button

    - by bob
    Hello, I am using this http://github.com/professionalnerd/simple-private-messages plugin in rails and I am on a user page show.html.erb - User and I want to put a button there that, when clicked, goes to the current user's inbox and populates the field call "send to" with the "user" name. How do I send that data along when the button is clicked? <%= link_to image_tag('send_message_button.jpg', :title => 'send #{user} a message', :alt => 'send #{user} a message'), new_user_message_path(current_user), :class=>'messageuser' %> This goes to the current_user's inbox. I want to send the "params[:user_id]" variable along with it so that I can then fill out the "send to" textbox in the inbox page with it. How do I send that params variable along with this button?

    Read the article

  • tableView:didSelectRowAtIndexPath: calls TTNavigator openURLAction:applyAnimated: — UITabBar and na

    - by vikingosegundo
    I have an existing iphone project with a UITabBar. Now I need styled text and in-text links to other ViewControllers in my app. I am trying to integrate TTStyledTextLabel. I have a FirstViewController:UITabelViewController with this tableView:didSelectRowAtIndexPath: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSString *url; if ([self.filteredQuestions count]>0) { url = [NSString stringWithFormat:@"%@%d", @"tt://question/", [[self.filteredQuestions objectAtIndex:indexPath.row] id]]; [[TTNavigator navigator] openURLAction:[[TTURLAction actionWithURLPath: url] applyAnimated:YES]]; } else { Question * q = [self.questions objectAtIndex:indexPath.row] ; url = [NSString stringWithFormat:@"%@%d", @"tt://question/", [q.id intValue]]; } TTDPRINT(@"%@", url); TTNavigator *navigator = [TTNavigator navigator]; [navigator openURLAction:[[TTURLAction actionWithURLPath: url] applyAnimated:YES]]; } My mapping looks like this: TTNavigator* navigator = [TTNavigator navigator]; navigator.window = window; navigator.supportsShakeToReload = YES; TTURLMap* map = navigator.URLMap; [map from:@"*" toViewController:[TTWebController class]]; [map from:@"tt://question/(initWithQID:)" toViewController:[QuestionDetailViewController class]]; and my QuestionDetailViewController: @interface QuestionDetailViewController : UIViewController <UIScrollViewDelegate , QuestionDetailViewProtocol> { Question *question; } @property(nonatomic,retain) Question *question; -(id) initWithQID:(NSString *)qid; -(void) goBack:(id)sender; @end When I hit a cell, q QuestionDetailViewController will be called — but the navigationBar wont @implementation QuestionDetailViewController @synthesize question; -(id) initWithQID:(NSString *)qid { if (self = [super initWithNibName:@"QuestionDetailViewController" bundle:nil]) { //; TTDPRINT(@"%@", qid); NSManagedObjectContext *managedObjectContext = [(domainAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext]; NSPredicate *predicate =[NSPredicate predicateWithFormat:@"id == %@", qid]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Question" inManagedObjectContext:managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entity]; [request setPredicate:predicate]; NSError *error = nil; NSArray *array = [managedObjectContext executeFetchRequest:request error:&error]; if (error==nil && [array count]>0 ) { self.question = [array objectAtIndex:0]; } else { TTDPRINT(@"error: %@", array); } } return self; } - (void)viewDidLoad { [super viewDidLoad]; [TTStyleSheet setGlobalStyleSheet:[[[TextTestStyleSheet alloc] init] autorelease]]; [self.navigationController.navigationBar setTranslucent:YES]; NSArray *includedLinks = [self.question.answer.text vs_extractExternalLinks]; NSMutableDictionary *linksToTT = [[NSMutableDictionary alloc] init]; for (NSArray *a in includedLinks) { NSString *s = [a objectAtIndex:3]; if ([s hasPrefix:@"/answer/"] || [s hasPrefix:@"http://domain.com/answer/"] || [s hasPrefix:@"http://www.domain.com/answer/"]) { NSString *ttAdress = @"tt://question/"; NSArray *adressComps = [s pathComponents]; for (NSString *s in adressComps) { if ([s isEqualToString:@"qid"]) { ttAdress = [ttAdress stringByAppendingString:[adressComps objectAtIndex:[adressComps indexOfObject:s]+1]]; } } [linksToTT setObject:ttAdress forKey:s]; } } for (NSString *k in [linksToTT allKeys]) { self.question.answer.text = [self.question.answer.text stringByReplacingOccurrencesOfString:k withString: [linksToTT objectForKey:k]]; } TTStyledTextLabel *answerText = [[[TTStyledTextLabel alloc] initWithFrame:CGRectMake(0, 0, 320, 700)] autorelease]; if (![[self.question.answer.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] hasPrefix:@"<div"]) { self.question.answer.text = [NSString stringWithFormat:@"%<div>%@</div>", self.question.answer.text]; } NSString * s = [NSString stringWithFormat:@"<div class=\"header\">%@</div>\n%@",self.question.title ,self.question.answer.text]; answerText.text = [TTStyledText textFromXHTML:s lineBreaks:YES URLs:YES]; answerText.contentInset = UIEdgeInsetsMake(20, 15, 20, 15); [answerText sizeToFit]; [self.navigationController setNavigationBarHidden:NO animated:YES]; [self.view addSubview:answerText]; [(UIScrollView *)self.view setContentSize:answerText.frame.size]; self.view.backgroundColor = [UIColor whiteColor]; [linksToTT release]; } ....... @end This works quite nice, as soon as a cell is touched, a QuestionDetailViewController is called and pushed — but the tabBar will disappear, and the navigationItem — I set it like this: self.navigationItem.title =@"back to first screen"; — won't be shown. And it just appears without animation. But if I press a link inside the TTStyledTextLabel the animation works, the navigationItem will be shown. How can I make the animation, the navigationItem and the tabBar be shown?

    Read the article

  • Objective C for beginners

    - by Golfgod130
    I was just asked to talk about Objective C to a bunch of High School student for 20 minutes. They have no experience with programming at all. What topics should I cover? Should I define vocab such as Method, Class, Variable? Or should I do something else? Any comments are helpful!

    Read the article

  • append set to another set

    - by mr.bio
    Hi Is there a better way of appending a set to another set than iterating through each element ? i have : set<string> foo ; set<string> bar ; ..... for (set<string>::const_iterator p = foo.begin( );p != foo.end( ); ++p) bar.insert(*p); Is there a more efficient way to do this ?

    Read the article

  • Python dictionary: add or increment entry

    - by cursa
    Hi everyone, I'm currently re-engaging with Python after a long absence and loving it. However, I find myself coming across a pattern over and over. I keep thinking that there must be a better way to express what I want and that I'm probably doing it the wrong way. The code that I'm writing is in the following form: # foo is a dictionary if foo.has_key(bar): foo[bar] += 1 else: foo[bar] = 1 I'm writing this a lot in my programs. My first reaction is to push it out to a helper function, but so often the python libraries supply things like this already. Is there some simple little syntax trick that I'm missing? Or is this the way that it should be done?

    Read the article

  • beginning oop php question: do constructors take the place of getter?

    - by Joel
    I'm working through this tutorial: http://www.killerphp.com/tutorials/object-oriented-php/php-objects-page-3.php At first he has you create a setter and getter method in the class: <?php class person{ var $name; function set_name($new_name){ $this->name=$new_name; } function get_name(){ return $this->name; } } php?> And then you create the object and echo the results: <?php $stefan = new person(); $jimmy = new person(); $stefan ->set_name("Stefan Mischook"); $jimmy ->set_name("Nick Waddles"); echo "The first Object name is: ".$stefan->get_name(); echo "The second Object name is: ".$jimmy->get_name(); ?> Works as expected, and I understand. Then he introduces constructors: class person{ var $name; function __construct($persons_name) { $this->name = $persons_name; } function set_name($new_name){ $this->name=$new_name; } function get_name(){ return $this->name; } } And returns like so: <?php $joel = new person("Joel"); echo "The third Object name is: ".$joel->get_name(); ?> This is all fine and makes sense. Then I tried to combine the two and got an error, so I'm curious-is a constructor always taking the place of a "get" function? If you have a constructor, do you always need to include an argument when creating an object? Gives errors: <?php $stefan = new person(); $jimmy = new person(); $joel = new person("Joel Laviolette"); $stefan ->set_name("Stefan Mischook"); $jimmy ->set_name("Nick Waddles"); echo "The first Object name is: ".$stefan->get_name(); echo "The second Object name is: ".$jimmy->get_name(); echo "The third Object name is: ".$joel->get_name(); ?>

    Read the article

  • Append an object to a list in R?

    - by Nick
    If I have some R list mylist, you can append an item obj to it like so: mylist[[length(mylist)+1]] <- obj But surely there is some more compact way. When I was new at R, I tried writing append() like so: append <- function(lst, obj) { lst[[length(list)+1]] <- obj return(lst) } but of course that doesn't work due to R's call-by-name semantics (lst is effectively copied upon call, so changes to lst are not visible outside the scope of append(). I know you can do environment hacking in an R function to reach outside the scope of your function and mutate the calling environment, but that seems like a large hammer to write a simple append function. Can anyone suggest a more beautiful way of doing this? Bonus points if it works for both vectors and lists.

    Read the article

  • POI dynamic templates

    - by gabriela
    Hello, Can anyone tell me where do I find some useful documentation on handling copying rows, cells, columns from one excel file to another, using POI? I need to insert in one blank excel file, 2 or more templates from other files, dynamic. I also need to keep all the styles made for the group of cells that I copy. How can I do that? Nothing found on apache poi tutorial on this point. I am using POI 3.0.1. Thank you!

    Read the article

  • Beginning Java (Working with Arrays; Class Assignment)

    - by Jason
    I am to the point where I feel as if I correctly wrote the code for this homework assignment. We were given a skeleton and 2 classes that we had to import (FileIOHelper and Student). /* * Created: *** put the date here *** * * Author: *** put your name here *** * * The program will read information about students and their * scores from a file, and output the name of each student with * all his/her scores and the total score, plus the average score * of the class, and the name and total score of the students with * the highest and lowest total score. */ // import java.util.Scanner; import java.io.*; // C:\Users\Adam\info.txt public class Lab6 { public static void main(String[] args) throws IOException { // Fill in the body according to the following comments Scanner key boardFile = new Scanner(System.in); // Input file name String filename = getFileName(keyboardFile); //Open the file // Input number of students int numStudents = FileIOHelper.getNumberOfStudents(filename); Student students[] = new Student[numStudents]; // Input all student records and create Student array and // integer array for total scores int totalScore[] = new int[students.length]; for (int i = 0; i < students.length; i++){ for(int j = 1; j < 4; j++){ totalScore[i] = totalScore[i] + students[i].getScore(j); } } // Compute total scores and find students with lowest and // highest total score int maxScore = 0; int minScore = 0; for(int i = 0; i < students.length; i++){ if(totalScore[i] >= totalScore[maxScore]){ maxScore = i; } else if(totalScore[i] <= totalScore[minScore]){ minScore = i; } } // Compute average total score int allScores = 0; int average = 0; for (int i = 0; i < totalScore.length; i++){ allScores = allScores + totalScore[i]; } average = allScores / totalScore.length; // Output results outputResults(students, totalScore, maxScore, minScore, average); } // Given a Scanner in, this method prompts the user to enter // a file name, inputs it, and returns it. private static String getFileName(Scanner in) { // Fill in the body System.out.print("Enter the name of a file: "); String filename = in.next(); return filename; // Do not declare the Scanner variable in this method. // You must use the value this method receives in the // argument (in). } // Given the number of students records n to input, this // method creates an array of Student of the appropriate size, // reads n student records using the FileIOHelper, and stores // them in the array, and finally returns the Student array. private static Student[] getStudents(int n) { Student[] myStudents = new Student[n]; for(int i = 0; i <= n; i++){ myStudents[i] = FileIOHelper.getNextStudent(); } return myStudents; } // Given an array of Student records, an array with the total scores, // the indices in the arrays of the students with the highest and // lowest total scores, and the average total score for the class, // this method outputs a table of all the students appropriately // formatted, plus the total number of students, the average score // of the class, and the name and total score of the students with // the highest and lowest total score. private static void outputResults( Student[] students, int[] totalScores, int maxIndex, int minIndex, int average ) { // Fill in the body System.out.println("\nName \t\tScore1 \tScore2 \tScore3 \tTotal"); System.out.println("--------------------------------------------------------"); for(int i = 0; i < students.length; i++){ outputStudent(students[i], totalScores[i], average); System.out.println(); } System.out.println("--------------------------------------------------------"); outputNumberOfStudents(students.length); outputAverage(average); outputMaxStudent(students[maxIndex], totalScores[maxIndex]); outputMinStudent(students[minIndex], totalScores[minIndex]); System.out.println("--------------------------------------------------------"); } // Given a Student record, the total score for the student, // and the average total score for all the students, this method // outputs one line in the result table appropriately formatted. private static void outputStudent(Student s, int total, int avg) { System.out.print(s.getName() + "\t"); for(int i = 1; i < 4; i++){ System.out.print(s.getScore(i) + "\t"); } System.out.print(total + "\t"); if(total < avg){ System.out.print("-"); }else if(total > avg){ System.out.print("+"); }else{ System.out.print("="); } } // Given the number of students, this method outputs a message // stating what the total number of students in the class is. private static void outputNumberOfStudents(int n) { System.out.println("The total number of students in this class is: \t" + n); } // Given the average total score of all students, this method // outputs a message stating what the average total score of // the class is. private static void outputAverage(int average) { System.out.println("The average total score of the class is: \t" + average); } // Given the Student with highest total score and the student's // total score, this method outputs a message stating the name // of the student and the highest score. private static void outputMaxStudent( Student student, int score ) { System.out.println(student.getName() + " got the maximum total score of: \t" + score); } // Given the Student with lowest total score and the student's // total score, this method outputs a message stating the name // of the student and the lowest score. private static void outputMinStudent( Student student, int score ) { System.out.println(student.getName() + " got the minimum total score of: \t" + score); } } But now I get an error at the line totalScore[i] = totalScore[i] + students[i].getScore(j); Exception in thread "main" java.lang.NullPointerException at Lab6.main(Lab6.java:42)

    Read the article

  • Python 3.1.1 Class Question

    - by Protean
    I'm a new Python programmer who is having a little trouble using 'self' in classes. For example: class data: def __init__(self): self.table = [] def add(self, file): self.table.append(file) data.add('yes') In this function I want to have table be a variable stored in the class data and use add to modify it. However, when I run this script it gives me the error: Traceback (most recent call last): File "/Projects/Python/sfdfs.py", line 7, in <module> data.add('yes') TypeError: add() takes exactly 2 positional arguments (1 given) I assume that I am trying to call the function the wrong way in this instance, as this syntax is very similar to an example in the python documentation: http://docs.python.org/3.1/tutorial/classes.html

    Read the article

  • Python - calculate multinomial probability density functions on large dataset?

    - by Seafoid
    Hi, I originally intended to use MATLAB to tackle this problem but the inbuilt functions has limitations that do not suit my goal. The same limitation occurs in NumPy. I have two tab-delimited files. The first is a file showing amino acid residue, frequency and count for an in-house database of protein structures, i.e. A 0.25 1 S 0.25 1 T 0.25 1 P 0.25 1 The second file consists of quadruplets of amino acids and the number of times they occur, i.e. ASTP 1 Note, there are 8,000 such quadruplets. Based on the background frequency of occurence of each amino acid and the count of quadruplets, I aim to calculate the multinomial probability density function for each quadruplet and subsequently use it as the expected value in a maximum likelihood calculation. The multinomial distribution is as follows: f(x|n, p) = n!/(x1!*x2!*...*xk!)*((p1^x1)*(p2^x2)*...*(pk^xk)) where x is the number of each of k outcomes in n trials with fixed probabilities p. n is 4 four in all cases in my calculation. I have created three functions to calculate this distribution. # functions for multinomial distribution def expected_quadruplets(x, y): expected = x*y return expected # calculates the probabilities of occurence raised to the number of occurrences def prod_prob(p1, a, p2, b, p3, c, p4, d): prob_prod = (pow(p1, a))*(pow(p2, b))*(pow(p3, c))*(pow(p4, d)) return prob_prod # factorial() and multinomial_coefficient() work in tandem to calculate C, the multinomial coefficient def factorial(n): if n <= 1: return 1 return n*factorial(n-1) def multinomial_coefficient(a, b, c, d): n = 24.0 multi_coeff = (n/(factorial(a) * factorial(b) * factorial(c) * factorial(d))) return multi_coeff The problem is how best to structure the data in order to tackle the calculation most efficiently, in a manner that I can read (you guys write some cryptic code :-)) and that will not create an overflow or runtime error. To data my data is represented as nested lists. amino_acids = [['A', '0.25', '1'], ['S', '0.25', '1'], ['T', '0.25', '1'], ['P', '0.25', '1']] quadruplets = [['ASTP', '1']] I initially intended calling these functions within a nested for loop but this resulted in runtime errors or overfloe errors. I know that I can reset the recursion limit but I would rather do this more elegantly. I had the following: for i in quadruplets: quad = i[0].split(' ') for j in amino_acids: for k in quadruplets: for v in k: if j[0] == v: multinomial_coefficient(int(j[2]), int(j[2]), int(j[2]), int(j[2])) I haven'te really gotten to how to incorporate the other functions yet. I think that my current nested list arrangement is sub optimal. I wish to compare the each letter within the string 'ASTP' with the first component of each sub list in amino_acids. Where a match exists, I wish to pass the appropriate numeric values to the functions using indices. Is their a better way? Can I append the appropriate numbers for each amino acid and quadruplet to a temporary data structure within a loop, pass this to the functions and clear it for the next iteration? Thanks, S :-)

    Read the article

  • F#: Advantages of converting top-level functions to member methods?

    - by J Cooper
    Earlier I requested some feedback on my first F# project. Before closing the question because the scope was too large, someone was kind enough to look it over and leave some feedback. One of the things they mentioned was pointing out that I had a number of regular functions that could be converted to be methods on my datatypes. Dutifully I went through changing things like let getDecisions hand = let (/=/) card1 card2 = matchValue card1 = matchValue card2 let canSplit() = let isPair() = match hand.Cards with | card1 :: card2 :: [] when card1 /=/ card2 -> true | _ -> false not (hasState Splitting hand) && isPair() let decisions = [Hit; Stand] let split = if canSplit() then [Split] else [] let doubleDown = if hasState Initial hand then [DoubleDown] else [] decisions @ split @ doubleDown to this: type Hand // ...stuff... member hand.GetDecisions = let (/=/) (c1 : Card) (c2 : Card) = c1.MatchValue = c2.MatchValue let canSplit() = let isPair() = match hand.Cards with | card1 :: card2 :: [] when card1 /=/ card2 -> true | _ -> false not (hand.HasState Splitting) && isPair() let decisions = [Hit; Stand] let split = if canSplit() then [Split] else [] let doubleDown = if hand.HasState Initial then [DoubleDown] else [] decisions @ split @ doubleDown Now, I don't doubt I'm an idiot, but other than (I'm guessing) making C# interop easier, what did that gain me? Specifically, I found a couple *dis*advantages, not counting the extra work of conversion (which I won't count, since I could have done it this way in the first place, I suppose, although that would have made using F# Interactive more of a pain). For one thing, I'm now no longer able to work with function "pipelining" easily. I had to go and change some |> chained |> calls to (some |> chained).Calls etc. Also, it seemed to make my type system dumber--whereas with my original version, my program needed no type annotations, after converting largely to member methods, I got a bunch of errors about lookups being indeterminate at that point, and I had to go and add type annotations (an example of this is in the (/=/) above). I hope I haven't come off too dubious, as I appreciate the advice I received, and writing idiomatic code is important to me. I'm just curious why the idiom is the way it is :) Thanks!

    Read the article

  • How do I stop inheritance in xaml?

    - by cfouche
    Hi Let's say I have some Control that has been disabled. It contains a bunch of elements, but I want one of those child elements to remain enabled. Something like this: <ContentControl IsEnabled="False"> <Border> <Button Content="Button" IsEnabled="True"/> </Border> </ContentControl> So in this example, the Button's IsEnabled="True" setting gets overridden by its parent. Is there a way of stopping this from happening? This seems like a strange thing to be doing, but I have a situation where, when a Control is disabled and a user mouses down on it, I still want an event to be triggered. I read in WPF Unleashed that wrapping something in a Frame control, "..isolates the content from the rest of the UI [and] properties that would normally be inherited down the element tree stop when they reach the Frame", but wrapping the Button in the example above in a Frame doesn't work. Am I on the wrong track here?

    Read the article

  • jQuery calculation plugin: show total in form field rather than text

    - by Katherine
    I'm embarrassed by the 'basicness' of this question, but after wasted hours, here goes. In an effort to do something with the jQuery Calculation plugin, I am playing with the basic example of the order form on the plugin site. I want to have the grand total as a form field,rather than text, so I can use the value. The function that calculates and shows the grand total is: function ($this){ // sum the total of the $("[id^=total_item]") selector var sum = $this.sum(); $("#grandTotal").text( // round the results to 2 digits sum.toFixed(2) ); } the total updates on keyup in: <span id="grandTotal"></span> But this does not work with: <input type="text" id="grandTotal" value=""/> Can anyone point me to what I need to add/change to make that work? To call my javascript basic would be a compliment, so please talk to me like I know nothing!

    Read the article

  • Difference of HTTP Components, Restlet, Apache Mina and Netty

    - by dexter
    I used HTTPComponents to implement a custom web server that access SQLite database. Requests are sent via TCP/IP and I am using REST concepts. By the way my frontend is HTML/jQuery. I know it will be a lot easier if I'll just create a servlet but I am restricted to just using apache http server. I really don't get good performance in using HTTP Components. Any suggestions please. Thanks in advance.

    Read the article

  • How do I use try...catch to catch floating point errors?

    - by Peter Stewart
    I'm using c++ in visual studio express to generate random expression trees for use in a genetic algorithm type of program. Because they are random, the trees often generate: divide by zero, overflow, underflow as well as returning "inf" and other strings. I can write handlers for the strings, but the literature left me baffled about the others. If I understand it correctly, I have to set some flags first? Advice and/or a pointer to some literature would be appreciated.

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >