Search Results

Search found 521 results on 21 pages for 'calculator'.

Page 5/21 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Help with PHP and associative arrays

    - by errata
    Hello. I have to do a simple calculator in php based on user's input and choice from select field, something like this: <?php $a = $_GET['a']; $b = $_GET['b']; $array = array( "option1" => 0.1, "option2" => 0.15, "option3" => 0.3, "option4" => 3, "option5" => 3, "option6" => 16, "option7" => 16, "option8" => 16 ); echo "<form action='calc.php' method='get'>"; echo "<input type='text' name='a' value='".$a."'> of "; echo "<select name='b'>"; foreach ($array as $k => $v) { echo "<option value='".$v."'>".$k."</option>"; } echo "</select> "; echo "<input type='submit' value='='> "; $total_volume = $a * $b; echo $total_volume; echo "</form>"; ?> Well, for now everything works fine, but the idea is that after user submits form, the page reloads with sent amount in input field and selected option which user actually selected... First thing is easy: I just put value="a" in my input field, but I'm not sure how to make a selected option in <select> field??? I started with this: foreach ($array as $k => $v) { echo "<option value='".$v."'"; if ($b == $v) { echo " selected "; } echo ">".$k."</option>"; } ...but this is obviously not working as expected... Please help me with this easy one :) Thanks!

    Read the article

  • Java Grade Calculator program for class kepp geting the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException." [migrated]

    - by user2880621
    this is my first question I've posted. I've used this site to look at other questions to help with similar problems I've had. After some cursory looking I couldn't find quite the answer I was looking for so I decided to finally succumb and create an account. I am fairly new to java, only a few weeks into my first class. Anyway, my project is to create a program which takes any amount of students and their grades, and then assign them a letter grade. The catch is, however, that it is on a sort of curve and the other grades' letter are dependent on the the highest. Anything equal to or 10 points below the best grade is an a, anything 11-20 points below is a b, and so on. I am to use an array, but I get this error when ran "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException." I will go ahead and post my code down below. Thanks for any advice you may be able to give. package grade.calculator; import java.util.Scanner; /** * * @author nichol57 */ public class GradeCalculator { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter the number of students"); int number = input.nextInt(); double[]grades = new double [number]; for (int J = number; J >=0; J--) { System.out.println("Enter the students' grades"); grades[J] = input.nextDouble(); } double best = grades[0]; for (int J = 1; J < number; J++) { if (grades[J] >= best){ best = grades[J]; } } for (int J = 0;J < number; J++){ if (grades[J] >= best - 10){ System.out.println("Student " + J + " score is " + grades[J] + " and grade is " + "A"); } else if (grades[J] >= best - 20){ System.out.println("Student " + J + " score is " + grades[J] + " and grade is " + "B"); } else if (grades[J] >= best - 30) { System.out.println("Student " + J + " score is " + grades[J] + " and grade is " + "C"); } else if (grades[J] >= best - 40) { System.out.println("Student " + J + " score is " + grades[J] + " and grade is " + "D"); } else { System.out.println("Student " + J + " score is " + grades[J] + " and grade is " + "F"); } } // end for loop for output }// end main method }

    Read the article

  • android program crashing (new to platform)

    - by mutio
    So it is my first real Android program (!hello world), but i do have java experience.The program compiles fine, but on running it crashes as soon as it opens (tried debugging, but it crashes before it hits my breakpoint). Was looking for any advice from anyone who is more experienced with android. package org.me.tipcalculator; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.text.NumberFormat; import android.util.Log; public class TipCalculator extends Activity { public static final String tag = "TipCalculator"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final EditText mealpricefield = (EditText) findViewById(R.id.mealprice); final TextView answerfield = (TextView) findViewById(R.id.answer); final Button button = (Button) findViewById(R.id.calculate); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { try { Log.i(tag, "onClick invoked."); String mealprice = mealpricefield.getText().toString(); Log.i(tag, "mealprice is [" + mealprice + "]"); String answer = ""; if (mealprice.indexOf("$") == -1) { mealprice = "$" + mealprice; } float fmp = 0.0F; NumberFormat nf = java.text.NumberFormat.getCurrencyInstance(); fmp = nf.parse(mealprice).floatValue(); fmp *= 1.2; Log.i(tag, "Total Meal Price (unformatted) is [" + fmp + "]"); answer = "Full Price, including 20% Tip: " + nf.format(fmp); answerfield.setText(answer); Log.i(tag, "onClick Complete"); } catch(java.text.ParseException pe){ Log.i (tag ,"Parse exception caught"); answerfield.setText("Failed to parse amount?"); } catch(Exception e){ Log.e (tag ,"Failed to Calculate Tip:" + e.getMessage()); e.printStackTrace(); answerfield.setText(e.getMessage()); } } } ); } Just in case it helps heres the xml <?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Android Tip Calculator"/> <EditText android:id="@+id/mealprice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:autoText="true"/> <Button android:id="@+id/calculate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Calculate Tip"/> <TextView android:id= "@+id/answer" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text=""/> </LinearLayout>

    Read the article

  • FLEX/BISON : Why my rule is not regonized ?

    - by Natim
    Hi, I am trying to do a little exercice in FLEX and BISON. Here is the code I wrote : calc_pol.y %{ #define YYSTYPE double #include "calc_pol.tab.h" #include <math.h> #include <stdlib.h> %} %start line %token NOMBRE %token FIN %% line: exp '\n' { printf("\t%.2lf\n", $1); }; exp: exp exp '+' { $$ = $1 + $2 ;} | exp exp '-' { $$ = $1 - $2 ;} | exp exp '*' { $$ = $1 * $2 ;} | exp exp '/' { $$ = $1 / $2 ;} | exp exp '^' { $$ = pow($1, $2) ;} | NOMBRE; %% calc_pol.l %{ #include "calc_pol.tab.h" #include <stdlib.h> #include <stdio.h> extern YYSTYPE yylval; %} blancs [ \t]+ chiffre [0-9] entier [+-]?[1-9][0-9]* | 0 reel {entier}('.'{entier})? %% {blancs} {reel} { yylval = atof(yytext); return NOMBRE; } \n { return FIN; } . { return yytext[0]; } %% Makefile all: calc_pol.tab.c lex.yy.c gcc -o calc_pol $< -ly -lfl -lm calc_pol.tab.c: calc_pol.y bison -d calc_pol.y lex.yy.c: calc_pol.l flex calc_pol.l Do you have any idea of what's wrong ? Thanks Edited: The error message is flex calc_pol.l: calc_pol.l:18: règle non reconnue Line 18 is the line beginning with {reel}, and the error message translates to English as "unrecognized rule".

    Read the article

  • How do calculators work with precision?

    - by zoul
    Hello! I wonder how calculators work with precision. For example the value of sin(M_PI) is not exactly zero when computed in double precision: #include <math.h> #include <stdio.h> int main() { double x = sin(M_PI); printf("%.20f\n", x); // 0.00000000000000012246 return 0; } Now I would certainly want to print zero when user enters sin(p). I can easily round somewhere on 1e–15 to make this particular case work, but that’s a hack, not a solution. When I start to round like this and the user enters something like 1e–20, they get a zero back (because of the rounding). The same thing happens when the user enters 1/10 and hits the = key repeatedly — when he reaches the rounding treshold, he gets zero. And yet some calculators return plain zero for sin(p) and at the same time they can work with expressions such as (1e–20)/10 comfortably. Where’s the trick?

    Read the article

  • Calculators and C#

    - by Alon
    Does those calculators have some type of a processor like a computer? Is it possible to program to them? And finally, is it somehow possible to run the .NET Micro Framework on it? Thank you.

    Read the article

  • Display calculating result in the same page

    - by garcon1986
    Hello, I have a table in my php code. In the second column of the table, normally it displays "---", and after i click the submit button, it will display the calculating result in the same page. For example, <table> <tr><td>1</td><td>---</td></tr> <tr><td>2</td><td>---</td></tr> <tr><td>3</td><td>---</td></tr> </table> And in the same page, it should receive the variables $var1 = $_POST['variable1']; I'm not sure which way to use, ajax or javascript or just css? Do you have any ideas? Thanks

    Read the article

  • float addition 2.5 + 2.5 = 4.0? RPN

    - by AJ Clou
    The code below is my subprogram to do reverse polish notation calculations... basically +, -, *, and /. Everything works in the program except when I try to add 2.5 and 2.5 the program gives me 4.0... I think I have an idea why, but I'm not sure how to fix it... Right now I am reading all the numbers and operators in from command line as required by this assignment, then taking that string and using sscanf to get the numbers out of it... I am thinking that somehow the array that contains the three characters '2', '.', and '5', is not being totally converted to a float... instead i think just the '2' is. Could someone please take a look at my code and either confirm or deny this, and possibly tell me how to fix it so that i get the proper answer? Thank you in advance for any help! float fsm (char mystring[]) { int i = -1, j, k = 0, state = 0; float num1, num2, ans; char temp[10]; c_stack top; c_init_stack (&top); while (1) { switch (state) { case 0: i++; if ((mystring[i]) == ' ') { state = 0; } else if ((isdigit (mystring[i])) || (mystring[i] == '.')) { state = 1; } else if ((mystring[i]) == '\0') { state = 3; } else { state = 4; } break; case 1: temp[k] = mystring[i]; k++; i++; if ((isdigit (mystring[i])) || (mystring[i] == '.')) { state = 1; } else { state = 2; } break; case 2: temp[k] = '\0'; sscanf (temp, "%f", &num1); c_push (&top, num1); i--; k = 0; state = 0; break; case 3: ans = c_pop (&top); if (c_is_empty (top)) return ans; else { printf ("There are still items on the stack\n"); exit (0); case 4: num2 = c_pop (&top); num1 = c_pop (&top); if (mystring[i] == '+'){ ans = num1 + num2; return ans; } else if (mystring[i] == '-'){ ans = num1 - num2; return ans; } else if (mystring[i] == '*'){ ans = num1 * num2; return ans; } else if (mystring[i] == '/'){ if (num2){ ans = num1 / num2; return ans; } else{ printf ("Error: cannot divide by 0\n"); exit (0); } } c_push (&top, ans); state = 0; break; } } } } Here is my main program: #include <stdio.h> #include <stdlib.h> #include "boolean.h" #include "c_stack.h" #include <string.h> int main(int argc, char *argv[]) { char mystring[100]; int i; sscanf("", "%s", mystring); for (i=1; i<argc; i++){ strcat(mystring, argv[i]); strcat(mystring, " "); } printf("%.2f\n", fsm(mystring)); } and here is the header file with prototypes and the definition for c_stack: #include "boolean.h" #ifndef CSTACK_H #define CSTACK_H typedef struct c_stacknode{ char data; struct c_stacknode *next; } *c_stack; #endif void c_init_stack(c_stack *); boolean c_is_full(void); boolean c_is_empty(c_stack); void c_push(c_stack *,char); char c_pop(c_stack *); void print_c_stack(c_stack); boolean is_open(char); boolean is_brother(char, char); float fsm(char[]);

    Read the article

  • Mocking objects with complex Lambda Expressions as parameters

    - by iCe
    Hi there, I´m encountering this problem trying to mock some objects that receive complex lambda expressions in my projects. Mostly with with proxy objects that receive this type of delegate: Func<Tobj, Fun<TParam1, TParam2, TResult>> I have tried to use Moq as well as RhinoMocks to acomplish mocking those types of objects, however both fail. (Moq fails with NotSupportedException, and in RhinoMocks simpy does not satisgy expectation). This is simplified example of what I´m trying to do: I have a Calculator object that does calculations: public class Calculator { public Calculator() { } public int Add(int x, int y) { var result = x + y; return result; } public int Substract(int x, int y) { var result = x - y; return result; } } I need to validate parameters on every method in the Calculator class, so to keep with the Single Responsability principle, I create a validator class. I wire everything up using a Proxy class, that prevents having duplicate code: public class CalculatorProxy : CalculatorExample.ICalculatorProxy { private ILimitsValidator _validator; public CalculatorProxy(Calculator _calc, ILimitsValidator _validator) { this.Calculator = _calc; this._validator = _validator; } public int Operation(Func&lt;Calculator, Func&lt;int, int, int&gt;&gt; operation, int x, int y) { _validator.ValidateArgs(x, y); var calcMethod = operation(this.Calculator); var result = calcMethod(x, y); _validator.ValidateResult(result); return result; } public Calculator Calculator { get; private set; } } Now, I´m testing a component that does use the CalculatorProxy, so I want to mock it, for example using Rhino Mocks: [TestMethod] public void ParserWorksWithCalcultaroProxy() { var calculatorProxyMock = MockRepository.GenerateMock&lt;ICalculatorProxy&gt;(); calculatorProxyMock.Expect(x =&gt; x.Calculator).Return(_calculator); calculatorProxyMock.Expect(x =&gt; x.Operation(c =&gt; c.Add, 2, 2)).Return(4); var mathParser = new MathParser(calculatorProxyMock); mathParser.ProcessExpression("2 + 2"); calculatorProxyMock.VerifyAllExpectations(); } However I cannot get it to work! Any ideas about how this can be done? Thanks a lot!

    Read the article

  • Simple calculator app crashes when a third number key is punched.

    - by Justin
    Hi , I am a newbie to the iphone app world. So I thought I try my luck with a calculator app. Unfortunately I am running into an issue where if I press a third key in the calculator the app crashes. Sometimes I get this error EXC_BAD_ACCESS. Here is a code in my CalculatorViewController.m file. #import "CalculatorViewController.h" @implementation CalculatorViewController @synthesize screenText; - (IBAction)buttonPressed:(id)sender { NSString *title = [sender titleForState:UIControlStateNormal]; [self collect:title]; } - (void)collect:(NSString *)digitz { NSString * newText = nil; if ([digitz isEqualToString:@"+"]) { [self add:result]; big_digit = nil; } else if ([digitz isEqualToString:@"+"]) { [self sub:result]; } else if ([digitz isEqualToString:@"x"]) { [self multiply:result]; } else if ([digitz isEqualToString:@"="]) { [self equate:result]; } else { if (big_digit != nil && [big_digit isEqualToString:@"0"] == FALSE) big_digit = [big_digit stringByAppendingFormat:@"%@",digitz]; else big_digit = (NSMutableString *) digitz; result = (int) big_digit; newText = [[NSString alloc] initWithFormat: @"%@",big_digit]; } screenText.text = newText; [newText release]; } - (void)add:(int)res { NSString * newText = nil; ans = ans + res; newText = [[NSString alloc] initWithFormat: @"%@",ans]; screenText.text = newText; [newText release]; } Can anyone spot an obvious issue here. Here is the respective header file too. #import <UIKit/UIKit.h> @interface CalculatorViewController : UIViewController { UILabel *screenText; int number; int result; int ans; //NSString *big_digit; NSMutableString * big_digit ; } @property (nonatomic, retain) IBOutlet UILabel *screenText; - (IBAction)buttonPressed:(id)sender; - (void)collect:(NSString *)digitz; - (void)add:(int)num; - (void)sub:(int)num; - (void)multiply:(int)num; - (void)equate:(int)num; @end

    Read the article

  • Using PHP SoapClient with Java JAX-WS RI (Webservice)

    - by Kau-Boy
    For a new project, we want to build a web service in JAVA using JAX-WS RI and for the web service client, we want to use PHP. In a small tutorial about JAX-WS RI I found this example web service: package webservice; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.Style; @WebService @SOAPBinding(style = Style.RPC) public class Calculator { public long addValues(int val1, int val2) { return val1 + val2; } } and for the web server: package webservice; import javax.xml.ws.Endpoint; import webservice.Calculator; public class CalculatorServer { public static void main(String args[]) { Calculator server = new Calculator(); Endpoint endpoint = Endpoint.publish("http://localhost:8080/calculator", server); } } Starting the Server and browsing the WDSL with the URL "http://localhost:8080/calculator?wsdl" works perfectly. But calling the web service from PHP fails My very simple PHP call looks like this: $client = new SoapClient('http://localhost:8080/calculator?wsdl', array('trace' => 1)); echo 'Sum: '.$client->addValues(4, 5); But than I either get a "Fatal error: Maximum execution time of 60 seconds exceeded..." or a "Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://localhost:8080/calculator?wsdl' ..." exception. I have tested the PHP SoapClient() with other web services and they work without any issues. Is there a known issue with JAX-WS RI in comibation with PHP, or is there an error in my web service I didn't see? I have found this bug report, but even updating to PHP 5.3.2 doesn't solved the problem. Can anyone tell me what to do? And by the way, my java version running on Windows 7 x64 is the following: java version "1.6.0_17" Java(TM) SE Runtime Environment (build 1.6.0_17-b04) Java HotSpot(TM) 64-Bit Server VM (build 14.3-b01, mixed mode)

    Read the article

  • Making Separate Assemblies For Different Types Of Tests For The Same Component?

    - by sooprise
    I was told by a few members here that splitting up my unit tests into different assemblies for different components is the best way to structure unit tests. Now, I have a few questions about that idea. What are the advantages of this? Organization, and isolation of errors? Let's say I have a component named "calculator", and I create an assembly for the unit tests on "calculator". Would I create a separate assembly for the integration tests I want to run on "calculator"? Or is the definition of an integration test a test across multiple components, like "calculator" and whatever else, which would require a separate assembly to test both of them together? In that case, would I have one assembly to do all of the integration testing for every component combination?

    Read the article

  • Unity The parameter host could not be resolved when attempting to call constructor

    - by Terrance
    When I attempt to instantiate my instance of the base class I get the error: a ResolutionFailedException with roughly the following error "The parameter host could not be resolved when attempting to call constructor" I'm currently not using an Interface for the base type and my instance of the class is inheriting the base type class. I'm new to Unity and DI so I'm thinking its something I forgot possibly. ExeConfigurationFileMap map = new ExeConfigurationFileMap(); map.ExeConfigFilename = "Unity.Config"; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); UnityConfigurationSection section = (UnityConfigurationSection)config.GetSection("unity"); IUnityContainer container = new UnityContainer(); section.Containers.Default.Configure(container); //Throws exception here on this BaseCalculatorServer server = container.Resolve<BaseCalculatorServer>(); and the Unity.Config file <container> <types> <type name ="CalculatorServer" type="Calculator.Logic.BaseCalculatorServer, Calculator.Logic" mapTo="Calculator.Logic.CalculateApi, Calculator.Logic"/> </types> </container> </containers> The Base class using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Transactions; using Microsoft.Practices.Unity; using Calculator.Logic; namespace Calculator.Logic { public class BaseCalculatorServer : IDisposable { public BaseCalculatorServer(){} public CalculateDelegate Calculate { get; set; } public CalculationHistoryDelegate CalculationHistory { get; set; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.Dispose(); } } } The Implementation using System; using System.Collections.Generic; using System.Linq; using System.Text; using Calculator.Logic; using System.ServiceModel; using System.ServiceModel.Configuration; using Microsoft.Practices.Unity; namespace Calculator.Logic { public class CalculateApi:BaseCalculatorServer { public CalculateApi(ServiceHost host) { host.Open(); Console.WriteLine("Press Enter To Exit"); Console.ReadLine(); host.Close(); } public CalculateDelegate Calculate { get; set; } public CalculationHistoryDelegate CalculationHistory { get; set; } } } Yes both base class and implementation are in the same Namespace and thats something design wise that will change once I get this working. Oh and a more detailed error Resolution of the dependency failed, type = "Calculator.Logic.BaseCalculatorServer", name = "". Exception message is: The current build operation (build key Build Key[Calculator.Logic.BaseCalculatorServer, null]) failed: The value for the property "Calculate" could not be resolved. (Strategy type BuildPlanStrategy, index 3)

    Read the article

  • Where do I learn about IP blocks and subnets? Or is there just a calculator that does it all for me?

    - by cwd
    Amazon's elastic compute tool (among others) requires the ip block format for their command: ec2-authorize websrv -P tcp -p 80 -s 205.192.0.0/16 I may be doing this wrong, but as far as I can tell I need to use the block format even for a single IP address. 1) So, how would I do that for this IP? 71.75.232.132 Several years ago I took a CCNA class, and I remember going over IPs and subnets, masks, broadcast addresses, class a/b/c networks, etc. However a lot seems to have changed since then - for example I don't think you can tell what "class" a network is in just by looking at it anymore - sometimes they could be multiple classes. 2) Anyhow, my second question is where do I go to get a refresher on all these things? 3) Or should I just be using ipcalc or an online calculator to do it all for me - and if so, which one?

    Read the article

  • Communicating between classes set up in nib, in code?

    - by cannyboy
    A beginner's question: If, in your nib, you have the File's Owner linked to the ViewController class, and you also have a NSObject-derived class, how do you communicate between the ViewController class and the NSObject class within code? For instance, suppose ScientificCalculatorView.xib looks like this File's Owner (class: ScientificCalculatorViewController) FirstResponder View Calculator (an object that has been linked to the Calculator class) Obviously, I'd want Calculator to be reusable, so it could be used with a NormalCalculatorViewController or something like that. So that UI and the calculator code are separate. Does Calculator even need to be in the nib? It's a beginners question, but I'm just trying to get my head around it.

    Read the article

  • How to write simple code using TDD [migrated]

    - by adeel41
    Me and my colleagues do a small TDD-Kata practice everyday for 30 minutes. For reference this is the link for the excercise http://osherove.com/tdd-kata-1/ The objective is to write better code using TDD. This is my code which I've written public class Calculator { public int Add( string numbers ) { const string commaSeparator = ","; int result = 0; if ( !String.IsNullOrEmpty( numbers ) ) result = numbers.Contains( commaSeparator ) ? AddMultipleNumbers( GetNumbers( commaSeparator, numbers ) ) : ConvertToNumber( numbers ); return result; } private int AddMultipleNumbers( IEnumerable getNumbers ) { return getNumbers.Sum(); } private IEnumerable GetNumbers( string separator, string numbers ) { var allNumbers = numbers .Replace( "\n", separator ) .Split( new string[] { separator }, StringSplitOptions.RemoveEmptyEntries ); return allNumbers.Select( ConvertToNumber ); } private int ConvertToNumber( string number ) { return Convert.ToInt32( number ); } } and the tests for this class are [TestFixture] public class CalculatorTests { private int ArrangeAct( string numbers ) { var calculator = new Calculator(); return calculator.Add( numbers ); } [Test] public void Add_WhenEmptyString_Returns0() { Assert.AreEqual( 0, ArrangeAct( String.Empty ) ); } [Test] [Sequential] public void Add_When1Number_ReturnNumber( [Values( "1", "56" )] string number, [Values( 1, 56 )] int expected ) { Assert.AreEqual( expected, ArrangeAct( number ) ); } [Test] public void Add_When2Numbers_AddThem() { Assert.AreEqual( 3, ArrangeAct( "1,2" ) ); } [Test] public void Add_WhenMoreThan2Numbers_AddThemAll() { Assert.AreEqual( 6, ArrangeAct( "1,2,3" ) ); } [Test] public void Add_SeparatorIsNewLine_AddThem() { Assert.AreEqual( 6, ArrangeAct( @"1 2,3" ) ); } } Now I'll paste code which they have written public class StringCalculator { private const char Separator = ','; public int Add( string numbers ) { const int defaultValue = 0; if ( ShouldReturnDefaultValue( numbers ) ) return defaultValue; return ConvertNumbers( numbers ); } private int ConvertNumbers( string numbers ) { var numberParts = GetNumberParts( numbers ); return numberParts.Select( ConvertSingleNumber ).Sum(); } private string[] GetNumberParts( string numbers ) { return numbers.Split( Separator ); } private int ConvertSingleNumber( string numbers ) { return Convert.ToInt32( numbers ); } private bool ShouldReturnDefaultValue( string numbers ) { return String.IsNullOrEmpty( numbers ); } } and the tests [TestFixture] public class StringCalculatorTests { [Test] public void Add_EmptyString_Returns0() { ArrangeActAndAssert( String.Empty, 0 ); } [Test] [TestCase( "1", 1 )] [TestCase( "2", 2 )] public void Add_WithOneNumber_ReturnsThatNumber( string numberText, int expected ) { ArrangeActAndAssert( numberText, expected ); } [Test] [TestCase( "1,2", 3 )] [TestCase( "3,4", 7 )] public void Add_WithTwoNumbers_ReturnsSum( string numbers, int expected ) { ArrangeActAndAssert( numbers, expected ); } [Test] public void Add_WithThreeNumbers_ReturnsSum() { ArrangeActAndAssert( "1,2,3", 6 ); } private void ArrangeActAndAssert( string numbers, int expected ) { var calculator = new StringCalculator(); var result = calculator.Add( numbers ); Assert.AreEqual( expected, result ); } } Now the question is which one is better? My point here is that we do not need so many small methods initially because StringCalculator has no sub classes and secondly the code itself is so simple that we don't need to break it up too much that it gets confusing after having so many small methods. Their point is that code should read like english and also its better if they can break it up earlier than doing refactoring later and third when they will do refactoring it would be much easier to move these methods quite easily into separate classes. My point of view against is that we never made a decision that code is difficult to understand so why we are breaking it up so early. So I need a third person's opinion to understand which option is much better.

    Read the article

  • why assign null value or another default value firstly?

    - by Phsika
    i try to generate some codes. i face to face delegates. Everythings is ok.(Look below) But appearing a warning: you shold assing value why? but second code below is ok. namespace Delegates { class Program { static void Main(string[] args) { HesapMak hesapla = new HesapMak(); hesapla.Calculator = new HesapMak.Hesap(hesapla.Sum); double sonuc = hesapla.Calculator(34, 2); Console.WriteLine("Toplama Sonucu:{0}",sonuc.ToString()); Console.ReadKey(); } } class HesapMak { public double Sum(double s1, double s2) { return s1 + s2; } public double Cikarma(double s1, double s2) { return s1 - s2; } public double Multiply(double s1, double s2) { return s1 * s2; } public double Divide(double s1, double s2) { return s1 / s2; } public delegate double Hesap(double s1, double s2); public Hesap Calculator; ----&#60; they want me assingn value } } namespace Delegates { class Program { static void Main(string[] args) { HesapMak hesapla = new HesapMak(); hesapla.Calculator = new HesapMak.Hesap(hesapla.Sum); double sonuc = hesapla.Calculator(34, 2); Console.WriteLine("Toplama Sonucu:{0}",sonuc.ToString()); Console.ReadKey(); } } class HesapMak { public double Sum(double s1, double s2) { return s1 + s2; } public double Cikarma(double s1, double s2) { return s1 - s2; } public double Multiply(double s1, double s2) { return s1 * s2; } public double Divide(double s1, double s2) { return s1 / s2; } public delegate double Hesap(double s1, double s2); public Hesap Calculator=null; } }

    Read the article

  • How to achieve interaction between GUI class with logic class

    - by volting
    Im new to GUI programming, and haven't done much OOP. Im working on a basic calculator app to help me learn GUI design and to brush up on OOP. I understand that anything GUI related should be kept seperate from the logic, but Im unsure how to implement interaction between logic an GUI classes when needed i.e. basically passing variables back and forth... Im using TKinter and when I pass a tkinter variable to my logic it only seems to hold the string PY_VAR0. def on_equal_btn_click(self): self.entryVariable.set(self.entryVariable.get() + "=") calculator = Calc(self.entryVariable) self.entryVariable.set(calculator.calculate()) Im sure that im probably doing something fundamentally wrong and probabaly really stupid, I spent a considerable amount of time experimenting (and searching for answers online) but Im getting no where. Any help would be appreciated. Thanks, V The Full Program (well just enough to show the structure..) import Tkinter class Gui(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() self.create_widgets() """ grid config """ #self.grid_columnconfigure(0,weight=1,pad=0) self.resizable(False, False) def create_widgets(self): """row 0 of grid""" """Create Text Entry Box""" self.entryVariable = Tkinter.StringVar() self.entry = Tkinter.Entry(self,width=30,textvariable=self.entryVariable) self.entry.grid(column=0,row=0, columnspan = 3 ) self.entry.bind("<Return>", self.on_press_enter) """create equal button""" equal_btn = Tkinter.Button(self,text="=",width=4,command=self.on_equal_btn_click) equal_btn.grid(column=3, row=0) """row 1 of grid""" """create number 1 button""" number1_btn = Tkinter.Button(self,text="1",width=8,command=self.on_number1_btn_click) number1_btn.grid(column=0, row=1) . . . def on_equal_btn_click(self): self.entryVariable.set(self.entryVariable.get() + "=") calculator = Calc(self.entryVariable) self.entryVariable.set(calculator.calculate()) class Calc(): def __init__(self, equation): self.equation = equation def calculate(self): #TODO: parse string and calculate... return self.equation if __name__ == "__main__": app = Gui(None) app.title('Calculator') app.mainloop()

    Read the article

  • Google Currency Convertor JSON API

    - by Gopinath
    There are many live currency conversion services available on the web and the popular one’s among them are – Google, Yahoo, MSN & XE. Among all these four Google is the developer’s darling and it provides a simple JSON API that can be integrated in your applications.  http://www.google.com/ig/calculator?hl=en&q=1USD=?INR Using the API is very simple and it takes two parameters as input. The first parameter “hl” is the language code in which you want output. The second parameter “q” is the conversion query in the format <number><from currency code>=?<to currency code>. In the URL give above the query requests for conversion of 1 USD in INR. JSON output for the above query would be  similar to {lhs: "1 U.S. dollar",rhs: "54.4602984 Indian rupees",error: "",icc: true} Examples: 100 USD in INR  http://www.google.com/ig/calculator?hl=en&q=100USD=?INR Example 2: 1 GBP in INR http://www.google.com/ig/calculator?hl=en&q=1GBP=?INR Example 3: 1 USD in INR, output the data in French language http://www.google.com/ig/calculator?hl=fr&q=1USD=?INR   This is an undocumented service and expect changes at any time. But as long as it works, you got a programmatic way to convert currencies.

    Read the article

  • JSF2 - use view scope managed bean to pass value between navigation

    - by Fekete Kamosh
    Hi all, I am solving how to pass values from one page to another without making use of session scope managed bean. For most managed beans I would like to have only Request scope. I created a very, very simple calculator example which passes Result object resulting from actions on request bean (CalculatorRequestBean) from 5th phase as initializing value for new instance of request bean initialized in next phase lifecycle. In fact - in production environment we need to pass much more complicated data object which is not as primitive as Result defined below. What is your opinion on this solution which considers both possibilities - we stay on the same view or we navigate to the new one. But in both cases I can get to previous value stored passed using view scoped managed bean. Calculator page: <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:head> <title>Calculator</title> </h:head> <h:body> <h:form> <h:panelGrid columns="2"> <h:outputText value="Value to use:"/> <h:inputText value="#{calculatorBeanRequest.valueToAdd}"/> <h:outputText value="Navigate to new view:"/> <h:selectBooleanCheckbox value="#{calculatorBeanRequest.navigateToNewView}"/> <h:commandButton value="Add" action="#{calculatorBeanRequest.add}"/> <h:commandButton value="Subtract" action="#{calculatorBeanRequest.subtract}"/> <h:outputText value="Result:"/> <h:outputText value="#{calculatorBeanRequest.result.value}"/> <h:outputText value="DUMMY" rendered="#{resultBeanView.dummy}"/> </h:panelGrid> </h:form> </h:body> Object to be passed through lifecycle: package cz.test.calculator; import java.io.Serializable; /** * Data object passed among pages. * Lets imagine it holds something much more complicated than primitive int */ public class Result implements Serializable { private int value; public void setValue(int value) { this.value = value; } public int getValue() { return value; } } Request scoped managed bean used on view "calculator.xhtml" package cz.test.calculator; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; @ManagedBean @RequestScoped public class CalculatorBeanRequest { @ManagedProperty(value="#{resultBeanView}") ResultBeanView resultBeanView; private Result result; private int valueToAdd; /** * Should perform navigation to */ private boolean navigateToNewView; /** Creates a new instance of CalculatorBeanRequest */ public CalculatorBeanRequest() { } @PostConstruct public void init() { // Remember already saved result from view scoped bean result = resultBeanView.getResult(); } // Dependency injections public void setResultBeanView(ResultBeanView resultBeanView) { this.resultBeanView = resultBeanView; } public ResultBeanView getResultBeanView() { return resultBeanView; } // Getters, setter public void setValueToAdd(int valueToAdd) { this.valueToAdd = valueToAdd; } public int getValueToAdd() { return valueToAdd; } public boolean isNavigateToNewView() { return navigateToNewView; } public void setNavigateToNewView(boolean navigateToNewView) { this.navigateToNewView = navigateToNewView; } public Result getResult() { return result; } // Actions public String add() { result.setValue(result.getValue() + valueToAdd); return isNavigateToNewView() ? "calculator" : null; } public String subtract() { result.setValue(result.getValue() - valueToAdd); return isNavigateToNewView() ? "calculator" : null; } } and finally view scoped managed bean to pass Result variable to new page: package cz.test.calculator; import java.io.Serializable; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; @ManagedBean @ViewScoped public class ResultBeanView implements Serializable { private Result result = new Result(); /** Creates a new instance of ResultBeanView */ public ResultBeanView() { } @PostConstruct public void init() { // Try to find request bean ManagedBeanRequest and reset result value CalculatorBeanRequest calculatorBeanRequest = (CalculatorBeanRequest)FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("calculatorBeanRequest"); if(calculatorBeanRequest != null) { setResult(calculatorBeanRequest.getResult()); } } /** No need to have public modifier as not used on view * but only in managed bean within the same package */ void setResult(Result result) { this.result = result; } /** No need to have public modifier as not used on view * but only in managed bean within the same package */ Result getResult() { return result; } /** * To be called on page to instantiate ResultBeanView in Render view phase */ public boolean isDummy() { return false; } }

    Read the article

  • what is itunes result sorted by ?

    - by NemesisII
    This is my App on Itunes: http://itunes.apple.com/us/app/buddy-calculator/id445261163?mt=8 My app Key word is : "calculator scientific calc equation math mathematics unit converter conversion statistic algebra" But when I search "Calculator" on Itunes, my app is not appeared (in first two pages). So I want to ask a question that how to improve the rank of my app , and what is the searched result sorted by (new first, vote or downloaded or ...) ? If I want to improve the rank, how can I do, does it cost fee or something ? Thanks you very much ^^ !

    Read the article

  • iPhone/Obj-C: Accessing a UIScrollView from a View displayed within it.

    - by Daniel I-S
    I'm writing a simple iPhone app which lets a user access a series of calculators. It consists of the following: UITableViewController (RootViewController), with the list of calculators. UIViewController + UIScrollView (UniversalScroller), which represents an empty scroll view - and has a 'displayedViewController' property. UIViewController (Calculators 1-9), each of which contains a view with controls that represents a particular calculator. Each calculator takes 3-5 values via UITextFields and UISliders, and has a 'calculate' button. They can potentially be taller than 460px(iPhone screen height). The idea is: User taps on a particular menu item in the RootViewController. This loads and inits UniversalScroller, ALSO loads and inits the UIViewcontroller for the particular calculator that was selected, sets the displayedViewController property of UniversalScroller to the newly loaded calculator UIViewcontroller, and pushes the UniversalScroller to the front. When the UniversalScroller hits its 'viewDidLoad' event, it sets its contentSize to the view frame size of its 'displayedViewController' object. It then adds the displayedViewController's view as a subview to itself, and sets its own title to equal that of the displayedViewController. It now displays the calculator, along with the correct title, in a scrollable form. Conceptually (and currently; this stuff has all been implemented already), this works great - I can design the calculators how I see fit, as tall as they end up being, and they will automatically be accommodated and displayed in an appropriately configured UIScrollView. However, there is one problem: The main reason I wanted to display things in a UIScrollView was so that, when the on-screen-keyboard appeared, I could shift the view up to focus on the control that is currently being edited. To do this, I need access to the UniversalScroller object that is holding the current calculator's view. On the beganEditing: event of each control, I intended to use the [UniversalScroller.view scrollRectToVisible: animated:] method to move focus to the correct control. However, I am having trouble accessing the UniversalScroller. I tried assigning a reference to it as a property of each calculator UIViewController, but did't seem to have much luck. I've read about using Delegates but have had trouble working out exactly how they work. I'm looking for one of three things: Some explanation of how I can access the methods of a UIScrollView from a UIViewController whose view is contained within it. or Confirmation of my suspicions that making users scroll on a data entry form is bad, and I should just abandon scrollviews altogether and move the view up and down to the relevant position when the keyboard appears, then back when it disappears. or Some pointers on how I could go about redesigning the calculators (which are basically simple data entry forms using labels, sliders and textfields) to be contained within UITableViewCells (presumably in a UITableView, which I understand is a scrollview deep down) - I read a post on SO saying that that's a more pleasing way to make a data entry form, but I couldn't find any examples of that online. Screenshots would be nice. Anything to make my app more usable and naturally 'iPhone-like', since shuffling labels and textboxes around makes me feel like I am building a winforms app! I've only recently started with this platform and language, and despite being largely an Apple skeptic I definitely see the beauty in the way that it works. Help me solve this problem and I might fall in love completely. Dan

    Read the article

  • Unknown Exception on trying to initialize the web service stub created by Axis C++

    - by Harsha Reddy
    Hi, I am trying out the sample calculator program given in the folder of axis c++. I am mainly interested in the client side. So I used the wsdl to create the stubs and my main is pretty much the same as given in the sample. However on executing the call Calculator ws (endpoint) I get an unknown exception "First-chance exception at 0x7c0024b9 in CalculatorClient.exe: 0xC0000005: Access violation reading location 0x00000000. First-chance exception at 0x7c812afb in CalculatorClient.exe: Microsoft C++ exception: [rethrow] at memory location 0x00000000.. Unhandled exception at 0x7c0024b9 in CalculatorClient.exe: 0xC0000005: Access violation reading location 0x00000000." and the exception causing code is Calculator::Calculator(const char* pchEndpointUri, AXIS_PROTOCOL_TYPE eProtocol) :Stub(pchEndpointUri, eProtocol) { } I had earlier tried to run a a webservice using Axis C++ but had received the same error. At that time my web service was a java ws on WAS. Then I later tried the calculator client (but this time I did not have any server hosting the ws as I just wanted to check if the Client could initialize). Is the problem caused due to the web service not being hosted on Apache in C++ (though I highly doubt it). Any help would be appreciated. Thanks, Harsha

    Read the article

  • What can be done to speed up synchronous WCF calls?

    - by Dimitri C.
    My performance measurements of synchronous WCF calls from within a Silverlight application showed I can make 7 calls/s on a localhost connection, which is very slow. Can this be speeded up, or is this normal? This is my test code: const UInt32 nrCalls = 100; ICalculator calculator = new CalculatorClient(); // took over from the MSDN calculator example for (double i = 0; i < nrCalls; ++i) { var call = calculator.BeginSubtract(i + 1, 1, null, null); call.AsyncWaitHandle.WaitOne(); double result = calculator.EndSubtract(call); } Remarks: CPU load is almost 0%. Apparently, the WCF module is waiting for something. I tested this both on Firefox 3.6 and Internet Explorer 7. I'm using Silverlight v3.0

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >