Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

18 April 2012

Quadractic equation

This equation I like more than the "beatiful" equation () mainly becaus it's not that mysterious. There is certain propoties of the quadractic equation that can be looked at and tested.
1st one is what shape will the equation be:

x^2x
Is the shape of:



And The second property you can get is directly from the quadractic equation, whether a equation has 2 roots, 1 root or it has imaginary roots

x^2x
b^2-4ac=
How many roots has this equation got?



Okay that was fun hope you enjoy.

18 March 2012

CodeEval FizzBuzz

CodeEval is a site where programmers can compete for jobs or in my case hopefully learn something more. I have small experience in Java and Visual Basic. I have slightly more experience in HTML, JavaScript and PHP. So I use this site for practise.
The 1st problem they put on there is FizzBuzz, the problem is below:

Description

Players generally sit in a circle. The player designated to go first says the number "1", and each player thenceforth counts one number in turn. However, any number divisible by 'A' e.g. three is replaced by the word fizz and any divisible by 'B' e.g. five by the word buzz. Numbers divisible by both become fizz buzz. A player who hesitates or makes a mistake is either eliminated.

Write a program that prints out the the pattern generated by such a scenario given the values of 'A'/'B' and 'N' which are read from an input text file. The input text file contains three space delimited numbers i.e. A, B, N. The program should then print out the final series of numbers using 'F' for fizz, 'B' for 'buzz' and 'FB' for fizz buzz.

Input sample:

Your program should read an input file (provided on the command line) which contains multiple newline separated lines. Each line will contain 3 numbers which are space delimited. The first number is first number to divide by ('A' in this example), the second number is the second number to divide by ('B' in this example) and the third number is where you should count till ('N' in this example). You may assume that the input file is formatted correctly and is the numbers are valid positive integers.e.g.

3 5 10
2 7 15

Output sample:

Print out the series 1 through N replacing numbers divisible by 'A' by F, numbers divisible by 'B' by B and numbers divisible by both as 'FB'. Since the input file contains multiple sets of values, your output will print out one line per set. Ensure that there are no trailing empty spaces on each line you print.e.g.

1 2 F 4 B F 7 8 F B
1 F 3 F 5 F B F 9 F 11 F 13 FB 15

Unfortunately when I did the Java solution I couldn't do it, so I searched for the solution online. DO NOT CLICK LOOK UNLESS YOU HAVE TRIED IT FIRST
/*Sample code to read in test cases:
public class fizzbuzz {
    public static void main (String[] args) {
    ...
    File file = new File(args[0]);
    BufferedReader in = new BufferedReader(new FileReader(file));
    String line;
    while ((line = in.readLine()) != null) {
        String[] lineArray = line.split("\s");
        if (lineArray.length > 0) {
            //Process line of input Here
        }
    }
  }
}
*/
import java.io.*;

import java.util.*;

public class fizzbuzz {

    public static void main(String[] args) throws IOException{

        Scanner console = new Scanner(new FileReader(args[0]));
        while(console.hasNext()){
            int first=console.nextInt();
            int second =console.nextInt();
            int third =console.nextInt();

            for(int i=1;i<=third;i++){
                if(i%first==0 && i%second==0 ){
                    System.out.printf("FB ");
                }
                else if(i%first==0)
                    System.out.printf("F ");
                else if(i%second==0)
                    System.out.printf("B " );
                else
                    System.out.printf("%d ",i);
            }
            System.out.println();
        }
        console.close();
    }
}
The last bit of the code I can do, it's just I couldn't read a file.
I also decided to see if I could do it in PHP as well
<?php
 /*Sample code to read in test cases:
 $fh = fopen($argv[1], "r");
 while (true) {
 $test = fgets($fh);
 # break loop if $test is an empty line
 # $test represents the test case, do something with it
 }
 */
    $file_get_contents=fopen($argv[1],"r");
     while ( ($line = fgets($file_get_contents)) !== false) {
     $k=0;
           foreach(preg_split("/[\s]/", $line) as $space){
              if($k==0){
                  $f=$space;
               }
                if($k==1){
                  $b=$space;
                }
               if($k==2){
                   $n=$space;
                }
                $k=$k+1;
            }
           for($i=1;$i<=$n;$i++){
                if(($i % $f==0)&&($i % $b==0)){
                 echo "FB ";
                }
                elseif($i % $f==0){
              echo "F ";
             }
                elseif($i % $b==0){
                 echo "B ";
                }
                else{
                 echo $i." ";
                }
            }
            echo "\n";
        }
 ?>
Good tip they do provide comments to help you through it, which is rather handy. Anyway I also tried to do it in JavaScript:
/*Sample code to read in test cases:
function codeEvalExecute(line) 
{ //your code goes here. line is your test case 
//return 
}*/
function codeEvalExecute(line){
 //an array with 3 values
 var Byline=line.split(" ");
 //fizz
 var f=Byline[0];
 //buzz
 var b=Byline[1];
 //number run to
 var n=Byline[2];
 var string="";
 
 for(var i=1;i<=n;i++){
  if((i % f==0)&&(i % b==0)){
          string=string+"FB ";
        }
        else if(i % f==0){
           string=string+"F ";
       }
        else if(i % b==0){
            string=string+"B ";
        }
        else{
           string=string+i+" ";
       }
 }
 return string;
}
Update 18/03/2012 11.59am
I should point out if you want to learn JavaScript or PHP I suggest w3 school as for Java I don't know any sites so put some in the comments if you have a suggestion

7 September 2011

php open, write and download a file

I have spend today and yesterday trying to make html write into a file and then download that file. The first objective was to open a file.

<?php
$filename="LinkTestText.txt";
$file=fopen($filename,'w+');
?>

Seems straight forward but i got an error

fopen(LinkTestText.txt) [function.fopen]: failed to open stream: Permission denied.

Okay okay calm down all I have to do is change permission of the file. <long time doing a google search> (many frustrating clicking and shouting at the computer (glad it doesn't have emotions)). On all <exaggeration> the forums no one mentioned a php function called "chmod"!!! Why this is what i'm looking for, okay so lets code it.

<?php
$filename="LinkTestText.txt";
chmod($filename, 0777);
$file=fopen($filename,'w+');
?>

Error appears:

chmod(): Operation not permitted in /file/path/to/that/ruddy/file.php

Rubbish, lets look on php.net to see if they have an answer <Quick look> ooh they have an answer. What one person says is use File Transfer Protocol (ftp) to change the permission, Huzzah an answer finally.

<?php
$filename="LinkTestText.txt";
$row['username']="Joe Bloggs";
$row['password']="passw0rd";
$ftp_details['ftp_user_name'] = $row['username'];
$ftp_details['ftp_user_pass'] = $row['password'];
$ftp_details['ftp_root'] = '/file/path/to/that/ruddy/';
//website address
$ftp_details['ftp_server'] = '10.0.1.200';
function chmod_11oo10($path, $mod, $ftp_details){
// extract ftp details (array keys as variable names)
extract ($ftp_details);
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// try to chmod $path directory
if (ftp_site($conn_id, 'CHMOD '.$mod.' '.$ftp_root.$path) !== false){
$success=TRUE;
}
else {
$success=FALSE;
}
// close the connection
ftp_close($conn_id);
return $success;
}
chmod_11oo10($filename, "0777", $ftp_details);
$file=fopen($filename,'w+');
fwrite($file,"Writing a lovely string to a file");
fclose($file);
$file=fopen($filename,'w+');
?>

Good so all we need to do now is activate ftp and then work out a way to force a download. Here is a link i found earlier

<?php
//http://php.net/manual/en/function.readfile.php
header('Content-Description: File Transfer');
header('Content-Type: application/download');
//it will be called
header('Content-Disposition: attachment; filename="Link test test.txt"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_clean();
flush();
readfile($filename);
exit;
?>

Done. One last thing the whole of it HAS to appear before "any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.". The only thing that is missing is why i put 0777 as the permission, to be honest i have no idea, just saw the number keep on popping up on a couple of forums.

1 August 2011

MSc Project website

I did originally set the website up as being just one big huge html file. It became too big especially when i started doing Material Properties Module (at the moment Material Properties Modules is still very big and is a bit slow on loading). This also meant it was slow as well. Now being a student (still) I get to have some free webspace and hosting, I know amazing. So all my pages i've done so far are up on the website. Just to let you know don't click on any links between and including 'General Equation Module' and 'User Module' you will get a error message saying page not found. Any suggestion to improve the site please leave a comment.

1 July 2011

Html show hide button

I've set up a new blog where i can post my MSc project user entry system on there. At the moment i have a long way to go. Any way at the moment i have a couple of buttons that are meant to display information on line of code but you can't hide it so i remembered xkcd had the spoiler hide show code but it looked a bit complicated so i searched elsewhere and found this website and it looked amazing and from these two i developed my own version of hide and show tailored to my specs.

<!--my code for info button-->
<button type="button" onclick="if (document.getElementById('PartitionSource Info').style.display !=''){
document.getElementById('PartitionSource Info').style.display='';
document.getElementById('PartitionSource Info').innerHTML='infomation based on button';
}
else{
document.getElementById('PartitionSource Info').style.display='none';
}">
Info
</button>
<p id="PartitionSource Info" style="display: none">
text</p>

And here is the actual button


22 June 2011

Lists using HTML and JavaScript

After browsing the web for ages on trying to work out how to do expansions of lines for excel, I gave up. It seems it is easy to expand rows but to do automatically is not. So I moved on to html. Someone directed me to W3schools as a recommendation, I do recommend it. Anyway lists, I am going to use the same example as last time.


<h2>Physica Module </h2>
<!--Runtime-->
Should the processes be timed and printed at the end of the run?
<form>
<select name="Runtime" id="Physica.Runtime">
<!--default is off-->
<option value="OFF">OFF
<option value="ON">ON
</select>
</form>
<button type="button" onclick="PhysicaModule()">
Submit
</button>
<p id="Runtime Output"> </p>

<script type="text/javascript">
function PhysicaModule()
{
txt=document.getElementById("Physica.Runtime").name+" "+ document.getElementById("Physica.Runtime").value;
document.getElementById("Runtime Output").innerHTML=txt;
}
</script>


the idea is there is dropdown list with two options "ON" and "OFF" and a button underneath called submit. underneath that is a paragraph where we put the results from clicking the button into (at the moment i haven't worked out how to get it into a txt file). Then a bit of javascript that determines what happens when the button is pressed. which hopefully we say "Runtime ON" or "Runtime OFF" depending on what option you choose.


Physica Module


Should the processes be timed and printed at the end of the run?




If the above bit of code doesn't work do it for yourself just remember to put <HTML> at the beginning and </HTML> at the end.

20 June 2011

MSc project

My main goal for my Project was to design a user interface to help create the 'inform' file that can be used for PHYSICA. For this I am deciding whether to use HTML and JavaScript or create it using Excel. So to test it out I am going to create a test case for each that will cover the following critea:
1. Lists. Some lines of code of physica have different options
2. Expansion. This is for if the user wants to specify for example Materials properties and they had multiple materials, space would be required.
3. Write to file. In each case I need to know how easy it is to write to file
4. Read from file. this is for if the user need to change something. this is more tricky.

Now the hard part my knowledge of both is not extensive so hopefully when I learn something new I'll post it on here (I hope).

Starting on Excel 1st.
Lists. From my research from today there are two ways of creating lists.
No Visual basic required

1st thing 1st you need to specify options for your list. My list is commands for a bit of code called 'Runtime' the options are "ON" or "OFF" this I put in column E. For the user I have put a prompt in Cell A2 simply called 'Runtime'


Now select the cell B2 then go to data tab and click Validate.


Although this is a mac version of Excel the options are similar for Windows users. In the drop down option select "list" and then specify what the options are and then your done.


Visual Basic form of a list.
Actually there are multiple ways of creating lists. One option is using a "Combo Box" but since I want it in the cell I'm not going to cover this.

Sub test()
Dim sList As String
Dim N As Integer
Dim dv As Validation

sList = "On,Off"
Set dv = Range("C2").Validation
dv.Delete
'.delete i think will clear the range it has been assigned
dv.Add xlValidateList, xlValidAlertStop, xlBetween, sList
'expression.Modify(Type, AlertStyle, Operator, Formula1, Formula2)
'below is what may have to use for intergers problem
'i tested the word thing if you enter something than not on the list it give a warning box
'website=http://msdn.microsoft.com/en-us/library/bb210323%28v=office.12%29.aspx
End Sub

if you see ' line its a comment.
To be honest I did adapt it from this website

There is another way which is good to use for constraints on variables(from this website).

With Range("e5").Validation
.Add Type:=xlValidateWholeNumber, _
AlertStyle:= xlValidAlertStop, _
Operator:=xlBetween, Formula1:="5", Formula2:="10"
.InputTitle = "Integers"
.ErrorTitle = "Integers"
.InputMessage = "Enter an integer from five to ten"
.ErrorMessage = "You must enter a number from five to ten"
End With


Hope you learned something I know I did.

UPDATE 21/6/2011 09.49AM
Just found out he second bit of code crashes if you run it more than one so it should be:

sub test()
Set dv = Range("B4").Validation
With dv
dv.Delete
.Add Type:=xlValidateDecimal, _
AlertStyle:=xlValidAlertInformation, _
Operator:=xlBetween, Formula1:="0", Formula2:="10"
.InputTitle = "Real"
.ErrorTitle = "Must be Real"
.InputMessage = "Enter an Real from zero to ten"
.ErrorMessage = "You must enter a number from zero to ten"
End With
End Sub

15 February 2011

Unstructured Meshes

Last term for me I was studying meshes and the physics of what goes on when the radiator is on. The most common mesh is structured meshes, like calendars, all squares all evenly distributed. i.e.

This was taken from my iCal on my mac. (note sure who I ask permission to use this image, if you know can you reply in the comments)

Structured meshes are good for rectangle type of shapes but what if they are not rectangle? For this type of problem we can triangles and view this as an unstructured mesh.
An example would be a rectangle split into triangles (because i can claim its my own work and its easy to draw)

This image was made by the software Paintbrush
Now before we get into the how a computer works with unstructured meshes we first need to know each triangles neighbour.
1: has neighbours 2 & 3.
2: has neighbours 1 & 4.
3: has neighbours 1 & 6.
4: has neighbours 2 & 5.
5: has neighbours 4, 6 & 7.
6: has neighbours 3 & 5.
7: has neighbours 5 & 8.
8: has neighbour 7.

Now we create three vectors, one will be the neighbours so something like
Neigh=[2,3,1,4,1,6,2,5,4,6,7,3,5,5,8,7]
The second will be to determine how many where the neighbours finish for that triangle i.e. for triangle 3 it would be 6, the vector will look like:
NeighPos=[2,4,6,8,11,13,15,16]
The last matrix will be the coefficients for those triangles so something like:
Coeff=[15,16,16,17,18,17,19,19]

Then you can use Successive over relation or Gauss Seidel or even the Jacobi method. Other iterative methods are available.

One last bit of advice do not use my triangle arrangement to solve problems mainly because it is not evenly spread out and so any results you get will be wrong or at least not very accurate.

This should be pre dated to 30th January 2011