Really...? And I can't even get ioquake3 to compile properly. :smallfrown:
Thanks for sharing.
Printable View
You may find the relevant Wikipedia article to be of interest.
Loop unrolling isn't specific to FOR loops. It also applies to other types of loops. Consider the following bit of Assembly (pseudocode x86 -- I'm a bit foggy on the exact syntax).
This is essentially what a typical loop might look like in handwritten Assembly. You've got an operation to do some work on, and a comparison value that you're checking against to continue the loop based on some exit condition. However, since I know the contents and number of iterations in advance, I could instead write the following:Code:# Set the Registers
lea ebx, [0] # Index Value
lea eax, [5] # Upper Bound
# Step Through the Loop
label:
add ebx, 1
cmpl ebx, eax
JLE label
# Jump to 'label' if Less Than or Equal
In this simple case, you pretty much only save on the fact that only one register was used (ebx) instead of two (eax & ebx). However, you could imagine the benefits once you start involving memory addresses. For example, since you know the memory address of your next array value (via the offset) ahead of time, you no longer need to compute the next address in memory after each loop iteration (think "Pointer Arithmetic" here), thereby saving an instruction on each pass.Code:lea ebx, [0] # Index Value
add ebx, 1
add ebx, 1
add ebx, 1
add ebx, 1
add ebx, 1
If your TA said loop unrolling isn't really taught much, then my institution is probably among the exception, heh. We spent two lectures covering loop unrolling. Just because you have a ton of memory and processing power doesn't mean optimization is irrelevant.
Also, Relevant SO Answer. For what it's worth, if you read the gcc man pages, the compiler does actively optimize your loops, though compiling with -o2 and above will disable loop unrolling.
For those that are more experienced in Assembly, feel free to point out the glaring flaws in my explanation. I probably made a mistake somewhere--haven't slept in about 30 hours now. :smallbiggrin:
Welcome to the club (of Game Dev Majors)!
Have you looked at any of the source code yet? Some of the comments are genuinely quite amusing, though some phrasings are perhaps inappropriate for this forum. :smallredface:
How do I write a Javascript program to generate all the content for a webpage?
Context– Found a neat perpetual calendar; want to make a Chrome extension to find the date on it. And unfortunately, Chrome seems to allow neither Java nor PHP in their extensions (the two languages I know)
If you want to do it in Javascript, you might want to look at http://nodejs.org/
Well, if you want to do it as a Chrome extension, you'll have to use Javascript and other client side (in-browser) technology. You can generate/change page content with Javascript using the Document Object Model API. Javascript is more than sufficient for what you want to do, especially in Chrome: if you're writing a Chrome extension and not worrying about compatibility with other browsers, you can use all sorts of fancy new APIs.
PHP is used by servers to generate content; you can't use it in a Chrome extension, which runs in a browser. Java is also used by servers to generate content. Java could theoretically be embedded in an extension page as an applet, but that would require a Java installation and a separate plugin to run the applet, and it would be an unusual choice for a Chrome extension.
Edit: node.js is server-side, which would not be applicable for an extension, unless you made an extension that communicated with a server.
Edit 2:
An explanation of Chrome extensions:
There are different parts of Chrome extensions, but all of them use web technologies like JavaScript, HTML, and CSS, and behave essentially like normal webpages. There are browser actions, which are extension buttons (little icons) displayed next to the main dropdown menu, which when clicked usually display a webpage related to the extension. There are also page actions, which are icons shown in the address bar for pages that match a certain URL pattern. Finally, there are content scripts, which are basically JavaScript files that are injected into pages that match a certain URL pattern. Content scripts are not allowed to directly communicate with existing JavaScript on the pages they are injected into, for security reasons.
As I mentioned earlier, Chrome extensions behave essentially like normal webpages, with access to normal web APIs. They also get access to special Chrome APIs, which can be found here.
Content scripts are useful for modifying/adding to existing webpages, while browser actions and page actions are good for option menus and user interfaces.
Hey all. I'm not much of a programmer really, at least not now. But as a kid in the 80ies I did program a whole lot, mostly in BASIC on my Commodore 64 and by extension also some 6510 assembly code stuff. However, as I got older this interest kind of faded away, even though I'm a physics major (and math minor). Sure, I've programmed a bit of other stuff like Pascal and even SML and C++ in the course of my education, but nothing that I actively use today (and I would probably had to start over if I ever needed any of those laguages for anything serious).
So why am I writing? Well, the thing is that I currently teach math and physics (10th-12th grad level equivalent, assuming this is comparable to Danish standards). Specifically, I've been tinkering with the idea of incorporating some programming into the teaching of math. The pedagogical reasoning for this is essentially, that programming teaches you to think logically and structured in a pretty practical way - exactly what math is actually about (as opposed to calculations). Also, I'm suspecting working with flowcharts could really help students structure mathematical proofs.
So, I've been looking for a programming language that is simple to get into, and after some casual investigation/asking around friends, it's my impression that Python is a good choice.
The thing is, that I only have so much time to teach a given math class, and on the surface, programming isn't part of the mandatory part of the curriculum. And we still have a lot of other stuff to teach. But I don't want the students to be master programmers. I want to introduce them to a certain way to think, you could say.
So, I'm basically asking if people have some good math-related ideas for simple programming exercises that would be easy to do in Python? And ways in which to tie them to more logical structures and problematics. Not very specific, I know, but I'm basically on the brain-storming level of this, and I'd love to hear any input on this.
Python is indeed a good language for beginners; people like to say that if you can write programs in English (or I suppose in your case in Danish), you can write programs in Python. :smallwink: The college where I used to TA required math and physics majors to take the introductory CS course, which they hated, but since the course has switched from C++ to Python the class dropout rates for non-CS majors have gone way down.
As for specific examples, Euclid has some good ones. His algorithm for finding the greatest common divisor, for instance, can be expressed as the following in English:
- Start out with two positive integers m and n.
- If the value of m is less than the value of n, switch the values of m and n.
- Find a number r equal to the remainder of m divided by n.
- Let m have the same value as n.
- Let n have the same value as r.
- If n does not have the value of 0, go to step 1.
- The GCD value is in m.
And that translates almost word-for-word (or word-for-symbol) to Python, with some added output statements to show the process as it goes along:
Code:def GCD(m, n):
if m < n:
(m, n) = (n, m)
while n != 0:
r = m % n
print "r = ", r, "m = ", m, "n = ", n
m = n
n = r
print "GCD = ",m
Basically, any algorithm that you can express as a set of simple, logical operations like that can be implemented in Python, from iterated integration and derivation, to matrix multiplication and finding eigenvalues, to probabilities and statistics, to plenty of other topics appropriate to 10th-12th graders, and as long as you're sticking with straightforward math and not trying to do anything fancy the syntax is fairly intuitive as you saw above.Code:Output of GCD(4,3)
r = 1, m = 4, n = 3
r = 0, m = 3, n = 1
GCD = 1
Output of GCD(12,8)
r = 4, m = 12, n = 8
r = 0, m = 8, n = 4
GCD = 4
Output of GCD(8246,1406)
r = 1216, m = 8246, n = 1406
r = 190, m = 1406, n = 1216
r = 76, m = 1216, n = 190
r = 38, m = 190, n = 76
r = 0, m = 76, n = 38
GCD = 38
Anyone here knows Free Pascal?
I have learned the basics there and would like to try making some simple games. Can you suggest any good tutorials about creating basic software (windowed/full screen and all that stuff) and doing 2d graphics?
Does anyone here know JPA? I'm trying to map some classes to a database, but one class has FIVE tables associated with it. (The data's normalized in the database, but not my existing Java code)
I can make more classes if I have to, but I'd prefer not to. Also, it is NOT an option to use anything besides JPA connecting to my existing MySQL database because it's homework
Thanks for the input. Euclid's algorithm for finding GCD was indeed one of the things I've considered using. Especially since I know a lot of my students (who, btw are adults, so for many of them it's been a while since they last dealt with math) are really bad at handling fractions. Making them write simple programs that do fraction arithmetic seems like an excellent idea here. Specifically, the GCD is needed when one wishes to truncate fractions. If two minds think alike, I consder it a sign that I'm on the right track here :smallsmile: (Any further ideas are still very much welcome, of course).
I've found this site very useful in learning python. Dunno if it'd work as a good base for you, or as somewhere to send people who want to learn more programming, either way its a rather accessable approach.
So here is an interesting problem I'm stuck on...
As part of my website development, I've implemented a user authentication system (in python). As part of registration, individuals enter their usernames, passwords, and so on, and the backend compares the usernames to unique records already in the database, before creating a new entry in the users table.
At this point, the user is considered "created" in the database. Attempting to authenticate the user via function call immediately following a successful user creation throws an unhandled exception relating to the authentication parameter (i.e. username). Through some tentative analysis, I've determined that the primary fault with the login code lies in the fact that when using the Google High Replication Datastore, records created in the database require some significant (0.25ms+) period of time to achieve consistency. As the login code is executed server side nearly instantaneously following a successful datastore put, the login code will fail as the datastore has yet to reach consistency, inhibiting an automatic login flow.
Short of 'import time' and calling 'time.sleep()' -- what are possible ways to get around this problem? Assume that the time-delay between datastore put and login flow (i.e. time necessary to achieve datastore consistency) is variable.
Isn´t there some response code from the Datastore when the data has been successfully added?
So just execute the serverside login once the response from datastore is there.
As I said previously I don´t know python but there has to be something like Async task or similar ^^
The time thing could seriously go wrong due to high load or similar so I wouldn´t use that :smallbiggrin:
Yes, there is a response, which I tuple-unpack. The success state is a simple True/False flag for user creation.
As I noted above, attempting to authenticate immediately following a successful user creation throws the error. I'm doing exactly as you're describing. The problem is a race condition in which the datastore returns "yes, I've made the entry!' and "hey wait, the entry hasn't propagated across all datastores!"
Obviously, the time.sleep() approach is a bit of a hackjob approach, given server load, and increasing datastore size.
I'm not entirely convinced async is the solution, since I'm receiving a success==True for user creation, which would still enter my race condition problem.
I'd just use a proper SQL database where you can guarantee that, when you put the data in there, it's actually *there* myself... :smalltongue:
My target platform is Google App Engine running the High Replication Datastore. :smalltongue:
I've verified that the data is most certainly there. It just has a non-zero lag time between user creation and user authentication within the lifespan of the request handler.
I'm programming in java and trying to get a program to write information to a text file, and then pull it up later to read it. However, I keep getting end of file errors when I try to read it.
(The println stuff is so I can tell what executes and what doesn't)HTML Code:
//Here's the code for reading:
public double GetBalance(String Name) throws IOException
{
FileName1 = Name + "Accnt.txt"; //This references a text file created in another method
double Output;
//Creates an inputstream from the file name.
//Then reads the only double that should be in the file.
//If a file is not found, it creates a file using its own constructor.
//Then the balance is assigned to the Output variable, which is returned.
try
{
FileInputStream accntIn = new FileInputStream(FileName1);
ObjectInputStream objectInputFile1 = new ObjectInputStream(accntIn);
Output = objectInputFile1.readDouble();
System.out.println("Should be working.");
objectInputFile1.close();
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
Output = Customer.Balance;
}
catch(EOFException e)
{
System.out.println("End of file. - Balance");
Output = 0;
}
return Output;
}
Yes it won´t do you any good in that case, I did not realize you where already doing all this.
That is quite a problem hmm...
Two possible ways I can think of which would """fix""" that (they are quite ugly)
1)you could let the user login again when the account has been created (popup user created please login)
2)you could make a login loop in an async task that is resolved when the data is found.(or closed if x seconds have gone by or after xy tries)
Both not really awesome :-/
It should be =/ It writes to the file earlier in the program. Upon rereading it again, it might just be rewriting the file every time... And when I check the file afterward there IS information in it.
... heck with it, here's the whole WriteToFile class.
HTML Code:import java.io.*;
import java.util.Scanner;
import java.io.FileReader;
import java.io.BufferedReader;
public class WriteToFile
{
String FileName1;
String FileName2;
double[] WaD = new double[2]; //Holds the number of Withdraws and deposits
double Balance; //This is there for the ease of the GetBalance method since it calls the WriteToFile class if the file asked for doesn't exist yet
SavingAccount Customer;
WriteToFile Records;
FileInputStream accntIn; //FileInputStream accntIn = new FileInputStream(FileName1);
ObjectInputStream objectInputFile1; //ObjectInputStream objectInputFile1 = new ObjectInputStream(accntIn);
FileOutputStream WaDout;
ObjectOutputStream objectOutputFile2;
FileOutputStream accntOut;
ObjectOutputStream objectOutputFile1;
//Make this our new constructor. WriteToFile will be called at the end of the program, but for now we need
//a way to call a SavingsAccount from name alone.
public WriteToFile(String Name) throws IOException
{
//This method takes the name of the account holder, then adds an end to the name, which becomes a text file for the account.
//Ouput and input objects are created for it, and then the WriteToFile method (the other one) is run.
FileName1 = Name + "Accnt.txt";
FileName2 = Name + "WaD.txt";
System.out.println("FileName assignment");
accntOut = new FileOutputStream(FileName1);
System.out.println("accntOut assignment");
objectOutputFile1 = new ObjectOutputStream(accntOut);
System.out.println("objectOutputFile1 assignment");
WaDout = new FileOutputStream(FileName2);
objectOutputFile2 = new ObjectOutputStream(WaDout);
System.out.println("objectOutputFile2 assignment");
accntIn = new FileInputStream(FileName1);
objectInputFile1 = new ObjectInputStream(accntIn);
System.out.println("Almost there");
WriteToFile(Name, GetBalance(Name), getDeposits(Name), getWithdraws(Name));
System.out.println("ENDOFCONSTRUCTORENDOFCONSTRUCTORENDOFCONSTRUCTORENDOFCONSTRUCTORENDOFCONSTRUCTORENDOFCONSTRUCTOR");
}
public void WriteToFile(String Name, double Accnt, double DepositInput, double WithdrawInput) throws IOException
{
//This writes the information to the file.
FileName1 = Name + "Accnt.txt";
FileName2 = Name + "WaD.txt";
Balance = Accnt;
//Create the stream objects (pg.775), using the FileName fields
accntOut = new FileOutputStream(FileName1);
objectOutputFile1 = new ObjectOutputStream(accntOut);
WaDout = new FileOutputStream(FileName2);
objectOutputFile2 = new ObjectOutputStream(WaDout);
//Populate the WaD array
WaD[1] = DepositInput;
WaD[0] = WithdrawInput;
//Now, put the info from each accntOut and WaDout into their respective files.
objectOutputFile1.writeObject(Accnt);
for (int i = 0; i < WaD.length; i++)
{
objectOutputFile2.writeObject(WaD[i]);
}
//Close the files.
objectOutputFile1.close();
objectOutputFile2.close();
}
//Use this to get the balance at the start of a session.
public double GetBalance(String Name) throws IOException
{
FileName1 = Name + "Accnt.txt";
double Output;
//Creates an inputstream from the file name.
//Then reads the only double that should be in the file.
//If a file is not found, it creates a file using its own constructor.
//Then the balance is assigned to the Output variable, which is returned.
accntIn = new FileInputStream(FileName1);
objectInputFile1 = new ObjectInputStream(accntIn);
try
{
Output = objectInputFile1.readDouble();
System.out.println("Should be working.");
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
Output = Customer.Balance;
}
catch(EOFException e)
{
System.out.println("End of file. - Balance");
Output = 0;
}
finally
{
objectInputFile1.close();
}
return Output;
}
//Create an array and store the two values in it
public double getDeposits(String Name) throws IOException
{
FileName2 = Name + "WaD.txt";
double Output;
//Create an array
try
{
for (int i = 0; i < WaD.length; i++)
{
WaD[i] = objectInputFile1.readDouble();
}
Output = WaD[1];
System.out.println("Deposits should be working");
objectInputFile1.close();
}
catch(FileNotFoundException e)
{
System.out.println("Deposits not found");
Output = 0;
}
catch(EOFException e)
{
System.out.println("End of file. - Deposits");
Output = 0;
}
return Output;
}
public double getWithdraws(String Name) throws IOException
{
FileName2 = Name + "WaD.txt";
double Output;
try
{
//FileInputStream accntIn = new FileInputStream(FileName2);
//ObjectInputStream objectInputFile1 = new ObjectInputStream(accntIn);
for (int i = 0; i < WaD.length; i++)
{
WaD[i] = objectInputFile1.readDouble();
}
Output = WaD[0];
System.out.println("Withdraws should be working");
objectInputFile1.close();
}
catch(FileNotFoundException e)
{
//WriteToFile Records = new WriteToFile(Name);
//Records.WriteToFile(Name, 0, 0, 0);
System.out.println("Withdraws not found");
Output = 0;
}
catch(EOFException e)
{
System.out.println("End of file. - Withdraws");
Output = 0;
}
return Output;
}
}
Outside of this class (Interface2): WriteToFile(String) is called at the start of the program. WriteToFile(String, double, double, double) is called right before the interface closes.
... I'm a student, sorry about the mess.
I've already implemented the first one as part of the standard login flow. I could see the second becoming increasingly costly in terms of CPU cycles, so not an ideal solution.
It would be really handy if there was some sort of database query I could perform to check for eventual consistency while the authentication flow is paused until the appropriate amount of time has passed.
I have a test in half an hour, so I can't look over this now. Can you either post here or PM me a list of methods and fields (public AND private) in SavingAccount? It would help make sense of what's going on in the program.
No offense, but I see issues even in the logic of the code, not just the file I/O. But hey, that's what this thread is for– programming chat and advice.
None taken - this definitely isn't my best/cleanest work. I got pretty desperate/lazy there at the end trying to make it work.
Here's SavingAccount and BankAccount (which SavingAccount extends)
SpoilerSavingAccount
Bank AccountHTML Code:import javax.swing.*; //Needed for Swing class
import java.awt.event.*; //Needed for ActionListener Interface
import java.io.*;
import javax.swing.JOptionPane;
public class SavingAccount extends BankAccount
{
boolean Inactive = false;
double Service = 0; //Will hold how many dollars in monthly service charges are made.
public SavingAccount(double Accnt, double IRate)
{
super(Accnt, IRate); //Passes the initial account amount and interest rate (this will later be stored in a pair of text files)
}
public void Deposit(String Input)
{
if (Balance >= 25)
Inactive = false;
if (Balance < 25)
{
Inactive = true;
double Newbal = Balance + Double.parseDouble(Input);
if (Newbal >= 25)
Inactive = false;
if (Newbal < 25)
Inactive = true;
}
Deposit(Double.parseDouble(Input));
}
public void Withdraw(String Input)
{
if(Balance >= 25)
Inactive = false;
if (Balance < 25)
Inactive = true;
if(Inactive)
{
JOptionPane.showMessageDialog(null, "This account is inactive at " + Balance + " dollars. An inactive account cannot make withdraws."
+ "Please maintain a balance of $25 or more to reactivate it.");
}
if(!Inactive)
{
Withdraw(Double.parseDouble(Input));
}
}
public void MonthlyProcess()
{
//This method is run to simulate the passage of a month.
Service = 0; //This resets the service charge so it's not applied more than once.
if(Withdrawals >= 4)
{
Service = Withdrawals - 4;
}
//
//With the cost of service determined, it is applied to the balance at the end of the month like so.
MonthlyProcess(Service);
if(Balance >= 25)
Inactive = false;
if (Balance < 25)
Inactive = true;
}
}
HTML Code:import javax.swing.*; //Needed for Swing class
import java.awt.event.*; //Needed for ActionListener Interface
import java.io.*;
import javax.swing.JOptionPane;
public abstract class BankAccount
{
double Balance; //Holds the account's balance
int Deposits = 0; //Holds the number of withdrawals
int Withdrawals = 0; //Holds the number of withdrawals
double Rate; //Holds monthly interest rate
public BankAccount(double Input1, double Input2)
{
//This sets the BankAccount's particular
Balance = Input1;
Rate = Input2;
}
public void Deposit(double Deposit)
{
//Deposits money
Balance += Deposit;
Deposits++;
}
public void Withdraw(double Withdraw)
{
//Withdraws money
Balance -= Withdraw;
Withdrawals++;
}
public void CalcInterest()
{
double MonthR = Rate / 12; //MonthR will hold the monthly interest rate
double MonthI = MonthR * Balance; //MonthI holds the interest earned in a month,
Balance += MonthI; //Which is then added to balance
}
public void MonthlyProcess(double Service)
{
//This method runs to simulate a month's passage.
Balance -= Service; //Deduction of service charge
Deposits = 0; //Resets deposits and withdrawals to 0 because of
Withdrawals = 0; //the start of a new month.
Service = 0;
CalcInterest(); //This applies interest. It's applied after service charges because the bank likes to screw you.
}
}
I'll review this one first. (Man, I feel like I'm in the homebrew forums PEACH'ing)
1) Typical code convention is to capitalize the first words of classes and not for methods are variables. Just a nit-picky thing.
2) I would make calcInterest() private, or even eschew it completely. Just multiply balance by 1+rate or 1+(rate/12) depending on if it's monthly effective or monthly nominative. I would store it as an effective rate (already divided by 12) for simplicity of coding
3) This is just my experience with interest theory shining through, but I would make a factory class. It would have public Factory setBalance(double d), public Factory setNominalRate(double d), public Factory setEffectiveRate(double d) and public BankAccount getAccount(). Unfortunately, both versions of the rate are doubles, so it's not as simple as overloading the constructor.
4) Finally, unless this has some other code attached you didn't post, you can (and maybe should) remove all the imports. You aren't using any
EDIT: Here's a conveniently pre-edited copy of the class :smallsmile:
SpoilerCode:public abstract class BankAccount
{
private double balance = 0; //Holds the account's balance
private int deposits = 0; //Holds the number of withdrawals
private int withdrawals = 0; //Holds the number of withdrawals
private double rate = 0; //Holds monthly interest rate
protected BankAccount(double balance, double rate) {
this.balance = balance;
this.rate = rate;
}
//Deposits money
public void deposit(double deposit) {
balance += deposit;
deposits++;
}
//Withdraws money
public void withdraw(double withdraw) {
balance -= withdraw;
withdrawals++;
}
//This method runs to simulate a month's passage.
public void advanceMonth(double service) {
balance -= service; //Deduction of service charge
deposits = 0; //Resets deposits and withdrawals to 0 because of
withdrawals = 0; //the start of a new month.
balance *= 1 + rate;
}
}
EDIT: Umm... Let's pretend I DIDN'T try instantiating an abstract class. Nothing to see here (the code's been fixed)
EDIT: Eeek! Big no-no I just noticed. You want instance variables to be private
Actually, HalfTangible, what exactly are you trying to do? It seems you're managing customers at a bank and need to write customers to files and retrieve them from files. If I'm to help clean up this code, it's kinda important to know
No, I'm still in school, not working at a bank :smalltongue: The project was to create a program that would simulate a bank account, though as far as I could tell it didn't require you to save customer data to files - I wanted to try adding something extra to the project.
Short version: You could deposit, withdraw, make a month pass, or display your current balance.
At this point, it's too late to fix it and turn it in. I just took out the WriteToFile class and any references to it were commented out or changed. It looks messy but it still works.
You're welcome to 'clean it up' still if you want, mind :smalltongue:
*mouth hanging open* Uhhhh... wow.
First off, I knew you weren't actually working at a bank; being metaphorical like that was just the easiest way to describe the project :smalltongue:
As for saving customer data, it would have been easiest to use JDBC or JPA, but that would require having a database to work with. Given, though, that it wasn't necessary and there's only one type of account, I'd just have made a single SavingAccount class. BankAccount as a superclass would only be strictly necessary if you had multiple types of accounts to manage.
All that being said, however, I don't feel like studying right now, so I think I'll make a touched up version of this class anyway. I'll just PM it to you when I'm done. This should be nice because it'd give me experience with factory classes and queues, as well as inadvertently helping me study for interest theory.
*bows*Quote:
*mouth hanging open* Uhhhh... wow.
There is a mistake nobody else seemed to notice - your use of the double primitive type.
The double and float primitive types can not accuratly represent many values, including 0.1 If I remmember correctly, a double value can only represent a value of int multiplied by a power of 2.
To accuratly calculate values for decimal fractions, eithar write your own class, or use this one: http://docs.oracle.com/javase/7/docs...igDecimal.html