Jump to content

The under 100 line challenge!

fletch to 99

Tree Calculator in HTML and JS in 65 Lines:

http://www.adakac11.bplaced.com/turmrechner.htm

<script type="text/javascript">		function calculate()		{				var x = document.getElementById("textfield").value;				var i = 0;				var output = "<table align='center'>";				var color1="FFFFCC";				var color2="99CCFF";				<!-- Multiplikationsberechnung -->				for(i = 2; i <= 9; i++){					if(i%2==0){						output += "<tr bgcolor='#"+color1+"'><td align='right'>"+x+"</td><td align='center'> * "+i+" = </td><td>"+(i*x)+"</td></tr>";						x*=i; }					else{						output += "<tr bgcolor='#"+color2+"'><td align='right'>"+x+"</td><td align='center'> * "+i+" = </td><td>"+(i*x)+"</td></tr>";						x*=i;}				}  				<!-- Divisionsberechnung -->				for(i = 2; i <= 9; i++)				{					if(i%2==0){						output += "<tr bgcolor='#"+color1+"'><td align='right'>"+x+"</td><td align='center'> / "+i+" = </td><td>"+(x/i)+"</td></tr>";						x/=i;} 					else{						output += "<tr bgcolor='#"+color2+"'><td align='right'>"+x+"</td><td align='center'> / "+i+" = </td><td>"+(x/i)+"</td></tr>";						x/=i;}				}				output+="</table>";				<!-- Ausgabe -->				document.getElementById("output").innerHTML=output;		}		</script>	</head>	<body>	<div align="left" style="font-size:12px">			Website of adakac11@2013			<br>			<button type="button" onclick="window.location.href='aufgaben.htm'">Back to the menu</button>			<hr></hr>			<br>	</div>			<center>		<p style="font-family:'Courier New'; font-size:15px;">Bitte Zahl eingeben: </p>		<input type="text" id="textfield" onKeyUp="calculate()" value="">				<p id="output" style="font-family:'Courier New'"></p>				</center>	</body>

Of course, it is completly normal to have a GPU at 90°c all the time <_< 

 

Java, Sysadmin, Network Engineer, Project Management

 

 

Love you all - thanks for helping me! ^_^

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

It was the first (and only one actually) python code that i have written, it changes my desktop background every 5 seconds, "rebuild" the file that has the wallapapers' path with every file that have in a certain directory and change the wallpaper according to my mood (there is 3 options SFW, kinda SFW and totally NSFW).

 

I did removed the file paths to post it here.

from subprocess import callimport timeimport sysimport globimport shutildef rebuild():    myFile = dict()    thelist = dict()    filename= dict()    for x in range(0, 3):        filename[x] = '/path/list' + str(x) +'.list'        myFile[x] = open(filename[x], 'w')        thelist[0] = glob.glob("/path/*")        thelist[1] = glob.glob("/path/*")        thelist[2] = glob.glob("/path/*")        myFile[x].write("%s\n" % "# xfce backdrop list")        for item in thelist[x]:            myFile[x].write("%s\n" % item)        myFile[x].close()    print("Done rebuilding")if ((len(sys.argv)) >=2):    if (sys.argv[1] == "--rebuild"):        rebuild()    else:        print("To rebuild the wallpaper database use the parameter : --rebuild")while (True):    with open('/path/parameter') as f:        parameter = f.readline().rstrip()        print(parameter)        if (parameter == "0"):            shutil.copyfile("/path/list0.list", "/path/backdrop.list")            call(["/usr/bin/xfdesktop", "--reload"])        elif (parameter == "1"):            shutil.copyfile("/path/list1.list", "/path/backdrop.list")            call(["/usr/bin/xfdesktop", "--reload"])        elif (parameter == "2"):            shutil.copyfile("/path/list2.list", "/path/backdrop.list")            call(["/usr/bin/xfdesktop", "--reload"])        else:            shutil.copyfile("/path/error.list", "/path/backdrop.list")            call(["/usr/bin/xfdesktop", "--reload"])            print("Calling the error list, no parameter found")    time.sleep(5)

Signatures are stupid.

Link to comment
Share on other sites

Link to post
Share on other sites

So I got bored and wrote an encryption program using the one-time-pad algorithm in under 100 lines.

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.security.SecureRandom;import java.util.Arrays;public class Leonardo {    public static void main(String args[]){        FileInputStream in = null;        FileOutputStream out = null;        FileOutputStream keyfile = null;        try {            String filename = ""; //Enter file to encrypt here            in = new FileInputStream(filename);            out = new FileOutputStream(filename.split("\\.")[0] + "_encrypted." + filename.split("\\.")[1]);            keyfile = new FileOutputStream(filename.split("\\.")[0] + "_key.txt");            int b;            int index = 0;            byte[] binaryContents = new byte[1024];            while((b=in.read())!=-1){                if(index >= binaryContents.length) {                    binaryContents = Arrays.copyOf(binaryContents, (binaryContents.length + binaryContents.length/4));                }                binaryContents[index] = (byte)b;                index++;            }            if(binaryContents.length > index) {                binaryContents = Arrays.copyOf(binaryContents, index);            }            in.close();            SecureRandom random = new SecureRandom();            byte[] key = new byte[binaryContents.length];            random.nextBytes(key);            for(int i=0; i<binaryContents.length; i++) {                binaryContents[i] = (byte)(binaryContents[i] ^ key[i]);            }            out.write(binaryContents);            keyfile.write(key);            out.close();            keyfile.close();        } catch(FileNotFoundException fnfe) {            System.err.println(fnfe.getMessage());        } catch(IOException ie) {            System.err.println(ie.getMessage());        } finally {            try {                if(in != null)                    in.close();                if(out != null)                    out.close();                if(keyfile != null)                    keyfile.close();            } catch(IOException ie) {                System.err.println(ie.getMessage());            }        }    }}

Also, I wrote a decryption program in under 100 lines to go along with it.

import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Arrays;public class Michelangelo {    public static void main(String args[]){        FileInputStream in = null;        FileOutputStream out = null;        FileInputStream key = null;        try{            String filename = ""; //Enter file to be decrypted here            in = new FileInputStream(filename);;            out = new FileOutputStream(filename.replaceAll("_encrypted", ""));            key = new FileInputStream(filename.replaceAll("_encrypted", "_key"));            int b;            int index = 0;            byte[] binaryContents = new byte[1024];            while((b=in.read())!=-1){                if(index >= binaryContents.length) {                    binaryContents = Arrays.copyOf(binaryContents, (binaryContents.length + binaryContents.length / 4));                }                binaryContents[index] = (byte)b;                index++;            }            if(binaryContents.length > index) {                binaryContents = Arrays.copyOf(binaryContents, index);            }            in.close();            byte[] keyContents = new byte[binaryContents.length];            key.read(keyContents);            key.close();            for(int i=0; i<binaryContents.length; i++) {                out.write((int)(binaryContents[i] ^ keyContents[i]));            }            out.close();        } catch(FileNotFoundException fnfe) {            System.err.println(fnfe.getMessage());        } catch(IOException ie) {            System.err.println(ie.getMessage());        } finally {            try {                if(in != null)                    in.close();                if(key != null)                    key.close();                if(out != null)                    out.close();            } catch(IOException ie) {                System.err.println(ie.getMessage());            }        }    }}

Enjoy! :D

Link to comment
Share on other sites

Link to post
Share on other sites

a web page running the conway's game of life

(demo at http://chuk.altervista.org/stronzate/under100linesGOL.html)

<!DOCTYPE html><head>	<meta charset="UTF-8" />	<title>Conway's Game Of Life</title>	<style>html, body{	margin: 0px;	background: black;	overflow: hidden;}.square{	transition: all 150ms ease;	-moz-transition: all 150ms ease;	-webkit-transition: all 150ms ease;	-o-transition: all 150ms ease;	position: absolute;	opacity: 0;}	</style>	<script>var field, turn, l=15, t=100;// report the gosper glider gun from wikipedia's GOL articlevar gosperGliderGun=[[0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 0]];function init(){	var wX=window.innerWidth;	var wY=window.innerHeight;	var nCols=parseInt(wX/l);	var nRows=parseInt(wY/l);	var paddingLeft=(wX-l*nCols)/2;	var paddingTop=(wY-l*nRows)/2;	// data structure	turn=0;	field=new Array(nCols);	var i, j, tmp;	for(i=0; i<nCols; i++){		field[i]=new Array(nRows);		for(j=0; j<nRows; j++){			field[i][j]=new Array(3);			field[i][j][0]=field[i][j][1]=0;		}	}	var w=gosperGliderGun.length, h=gosperGliderGun[0].length;	for(i=0; i<w; i++)		for(j=0; j<h; j++)			field[10+i][10+j][turn]=gosperGliderGun[i][j];	// creating the squares	for(i=0; i<nCols; i++)		for(j=0; j<nRows; j++){			tmp=document.createElement("div");			tmp.style.left=(paddingLeft+i*l)+"px";			tmp.style.top=(paddingTop+j*l)+"px";			tmp.style.width=tmp.style.height=l+"px";			tmp.style.background="rgba(255, 255, 63, "+(.3+Math.random()*.7)+")";			tmp.className="square";			document.body.appendChild(tmp);			field[i][j][2]=tmp;		}	update();}function update(){	var i, j, nAliveNeighbours, nCols=field.length, nRows=field[0].length;	for(i=1; i<nCols-1; i++)		for(j=1; j<nRows-1; j++){			nAliveNeighbours=	field[i]	[j-1]	[turn]+						field[i]	[j+1]	[turn]+						field[i+1]	[j]	[turn]+						field[i+1]	[j-1]	[turn]+						field[i+1]	[j+1]	[turn]+						field[i-1]	[j+1]	[turn]+						field[i-1]	[j]	[turn]+						field[i-1]	[j-1]	[turn];			field[i][j][1-turn] = nAliveNeighbours==2 && field[i][j][turn] || nAliveNeighbours==3 ? 1 : 0;			field[i][j][2].style.opacity=field[i][j][1-turn] ? "1" : "0";		}	turn=1-turn;	setTimeout(update, t);}window.onload=init;	</script></head>

the stupidly long line is just a reported image from http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life

it can be done with proper formatting under 100 line using, say, the lightweight spaceship instead of the gospel glider gun, but it would look worse :)  so yeah, take that line and deal with it

i also just found out that if you google "conways game of life" there is another google easter egg

 

edit: how the hell do i show line numbers?

Link to comment
Share on other sites

Link to post
Share on other sites

Not really an app, but hey I use it every now and then since working with web.

In an editor which supports search replace using regex (like sublimbe text, notepad++ etc):

Search for: [\r\n]{2,}Replace with: \n

This will replace 2+ repeating "new lines" with a single newline.

Link to comment
Share on other sites

Link to post
Share on other sites

Not really an app, but hey I use it every now and then since working with web.

In an editor which supports search replace using regex (like sublimbe text, notepad++ etc):

Search for: [\r\n]{2,}Replace with: \n

This will replace 2+ repeating "new lines" with a single newline.

 

This made me remember an assignment for our Natural Language course earlier this semester.

 

Here's an excerpt:

sed -r -n 's/[^0-9]*([0-9]+[.[0-9]+]?)[^0-9]*/\1\n/pg' $INPUT | sed -r '/^$/d' > $OUTPUT1sed -r "s/[[:alpha:]\'-]{6,}|[^[:alpha:]]/\n/g" $INPUT | sed -r '/^$/d' | sort | uniq -c > $OUTPUT5

Useful when you are working with natural language processing systems. Or, in this case, if you just want to find the numbers and big words in a text!

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
package ch6.graphicsLab03;import expo.Expo.*;import java.applet.Applet;import java.awt.Graphics;/** * * @author Aaditya */public class Ch6GraphicsLab03 extends Applet {    public void paint(Graphics g) {        // Draw Grid        Expo.drawLine(g, 250, 0, 250, 650);        Expo.drawLine(g, 500, 0, 500, 650);        Expo.drawLine(g, 750, 0, 750, 650);        Expo.drawLine(g, 0, 325, 1000, 325);        // Draw 10,000 Random Points        for (int count = 1; count <= 10000; count++) {            Expo.setRandomColor(g);            int x = Expo.random(5, 245);            int y = Expo.random(5, 320);            Expo.drawPoint(g, x, y);        }        // Draw 1000 Random Lines        for (int count = 1; count <= 1000; count++) {            Expo.setRandomColor(g);            int x1 = Expo.random(255, 495);            int x2 = Expo.random(255, 495);            int y1 = Expo.random(5, 320);            int y2 = Expo.random(5, 320);            Expo.drawLine(g, x1, y1, x2, y2);        }        // Draw 1000 Random Rectangles        for (int count = 1; count <= 1000; count++) {            Expo.setRandomColor(g);            int x1 = Expo.random(505, 745);            int x2 = Expo.random(505, 745);            int y1 = Expo.random(5, 320);            int y2 = Expo.random(5, 320);            Expo.fillRectangle(g, x1, y1, x2, y2);        }        // Draw 500 Random Triangles        for (int count = 1; count <= 500; count++) {            Expo.setRandomColor(g);            int x1 = Expo.random(755, 995);            int x2 = Expo.random(755, 995);            int x3 = Expo.random(755, 995);            int y1 = Expo.random(5, 320);            int y2 = Expo.random(5, 320);            int y3 = Expo.random(5, 320);            Expo.fillPolygon(g, x1, y1, x2, y2, x3, y3);        }        // Draw 100 Random Initials        for (int count = 1; count <= 100; count++) {            Expo.setRandomColor(g);            int x = Expo.random(5, 235);            int y = Expo.random(340, 640);            Expo.drawString(g, "AM", x, y);        }        // Draw 500 Random Stars with a constant radius of 30 and a random # of points        for (int count = 1; count <= 500; count++) {            Expo.setRandomColor(g);            int points = Expo.random(5, 10);            final int radius = 30;            int x = Expo.random(255, 495);            int y = Expo.random(330, 645);            if (255 <= x - radius && x + radius <= 495 && y + radius <= 645 && y - radius >= 330)                Expo.fillStar(g, x, y, radius, points);            else                count--;        }        // Draw 1000 Random Circles with random radii        for (int count = 1; count <= 1000; count++) {            Expo.setRandomColor(g);            int x = Expo.random(505, 745);            int y = Expo.random(330, 645);            int radius = Expo.random(0, 75);            if (505 <= x - radius && x + radius <= 745 && y + radius <= 645 && y - radius >= 330)                Expo.fillCircle(g, x, y, radius);            else                count--;        }        // Draw a 3-D Box (Nothing random in this last part)        Expo.setColor(g, Expo.red);        Expo.fillRectangle(g, 770, 450, 900, 580);        Expo.setColor(g, Expo.lightGreen);        Expo.fillPolygon(g, 900, 580, 900, 450, 1000, 350, 1000, 480);        Expo.setColor(g, Expo.blue);        Expo.fillPolygon(g, 900, 450, 1000, 350, 870, 350, 870, 450);        Expo.setColor(g, Expo.yellow);        Expo.fillPolygon(g, 770, 450, 870, 350, 870, 450);    }}

Here is a Graphics Lab that I had to do as an assignment in my programming class. Needless to say, we were given an Expo class file, and we had to use its graphics methods to come up with a bunch of Random graphics!

 

The best way to predict the future is to invent it

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Here is my entry:

 

Its a calculator I made using loops and common sense.Its about 150 lines.

 

EDIT-

I forgot to mention that it is coded in C++.Btw it supports all Operating systems(Windows,Linux,Mac or any other os out there)

 #include <iostream>using namespace std;int factorialfinder(int x){    if(x==1){        return 1;    }else{        return x*factorialfinder(x-1);    }}int main(){    int answer,num3;    double num2;    char ans;    float pans = 0;    do{    float num2total = 0,num3total = 1;    int countt = 0;    cout << "CalculatorxPro by <TheUnknown>               Previous result: "<< pans << endl;    cout<< "Main menu:" << endl;    cout << endl;    cout << "Insert:"<< endl;    cout << "1. for [+]"<< endl;    cout << "2. for [-]"<< endl;    cout << "3. for [*]"<<endl;    cout << "4. for [/]"<<endl;    cout << "5. for [Average]"<<endl;    cout <<"6. for [Factorial Finder]"<<endl;    cout <<"7. for [odd,even Checker]" << endl;    cout << endl;    cout <<"Answer: ";    cin >> answer;    cout << string (100,'\n');    switch(answer){    case 1:        cout<<"CalculatorxPro by <Unknown>               Previous result: "<< pans << endl;        pans = 0;        cout <<"Operation [+]" << endl;        cout << endl;        cout << "Insert integers seperated with 'enter' (0 to exit)" << endl;        while((cin >> num2) && num2!=0){            num2total = num2 + num2total;        }        pans = pans + num2total;        cout << "Result: " << num2total << endl;        break;    case 2:                cout<<"CalculatorxPro by <Unknown>               Previous result: "<< pans << endl;        cout <<"Operation [-]" << endl;        pans = 0;        cout << endl;        cout << "Insert integers seperated with 'enter' (0 to exit)" <<endl;        cin >> num2;        if(num2 == 0){            cout << "Result: 0" << endl;            break;        }        num2total = num2 + num2total;        while( (cin >> num2) && num2!=0){                num2total = num2total - num2;        }        pans = pans + num2total;        cout << "Result: " << num2total << endl;        break;    case 3:                cout<<"CalculatorxPro by <Unknown>               Previous result: "<< pans << endl;        cout <<"Operation [*]" << endl;        pans = 0;        cout << endl;        cout << "Insert integers seperated with 'enter' (0 to exit)" << endl;        while( (cin >> num2) && num2!=0){            num3total = num2 * num3total;        }        pans = pans+num3total;        cout << "Result: " << num3total <<endl;        break;    case 4:                cout<<"CalculatorxPro by <Unknown>               Previous result: "<< pans << endl;        cout <<"Operation [/]" << endl;        pans = 0;        cout << endl;        cout << "Insert integers seperated with 'enter' (0 to exit)" << endl;        cin >> num2;        if(num2 == 0){            cout << "Result: 0" << endl;            break;        }        num3total = num2 / num3total;        while( (cin >> num2) && num2!=0){        num3total = num3total / num2;  }        pans = pans+num3total;        cout << "Result: " << num3total <<endl;        break;    case 5:                cout<<"CalculatorxPro by <Unknown>               Previous result: "<< pans << endl;        cout <<"Operation [average]" << endl;        pans = 0;        cout << endl;        cout << "Insert integers seperated with 'enter' (0 to exit)" << endl;        while((cin >> num2) && num2!=0){            num2total = num2total + num2;            countt++;        }        cout << "Numbers entered " << countt << endl;        pans = pans+(num2total/countt);        cout << "Average of the numbers entered " << num2total/countt << endl;        cout <<endl;        break;    case 6:        cout<<"CalculatorxPro by <Unknown>               Previous result: "<< pans << endl;        cout <<"Operation [Factorial Finder]" << endl;        pans = 0;        cout << endl;        cout << "Insert a number [maximum number 16]" << endl;        cin >> num2;        if(16>=num2){            cout << "!" << factorialfinder(num2) << endl;            pans = pans + factorialfinder(num2);            }else{            cout << "Smaller than 16!" << endl;            }        break;    case 7:        cout<<"You selected 7 for [odd,even Checker]" << endl;        cout << endl;        cout << "Enter a number: (0 to exit)" << endl;        while(cin >> num3 && num3!=0){            if((num3%2)==0){                    cout << "Number is even!" << endl;                    cout << "Enter a number: (0 to exit)" << endl;            }else{                cout << "Number is odd!" << endl;                cout << "Enter a number: (0 to exit)" << endl;            }        }        break;     default:        cout <<"Wrong answer!" << endl;    }    cout << "Do you want to continue (y/n)?" <<endl;    cin >> ans;    cout << string(100,'\n');    }    while(ans=='y');    return 0;}

 C++,Assembly,Reverse Engineering,Penetration testing,Malware analysis


 


Do you have a question?Are you interested in programming?Do you like solving complex problems?Hit me up with a pm.

Link to comment
Share on other sites

Link to post
Share on other sites

Just started learning to code, pig latin translator (in python)

pyg = 'ay'original = raw_input('Enter a word:')if len(original) > 0 and original.isalpha():    word = original.lower()    first = word[0]    if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":        new_word = word + pyg        print new_word    else:        new_word =  word[1:100] + first + pyg        print new_word    else:    print 'empty'

Stuff I have I like: Moto G - Superlux HD681 Evo - Monoprice 9927

90% of what I say is sarcasm.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

It computes Pi and tells you how far it got and outputs the results of computed pi in realtime in a file so when your computer crashes you can have the latest computed pi stored locally
 

import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.math.BigInteger; public class ComputePi {	final static BigInteger two = BigInteger.valueOf(2);	final static BigInteger three = BigInteger.valueOf(3);	final static BigInteger four = BigInteger.valueOf(4);	final static BigInteger seven = BigInteger.valueOf(7); 	static BigInteger q = BigInteger.ONE;	static BigInteger r = BigInteger.ZERO;	static BigInteger t = BigInteger.ONE;	static BigInteger k = BigInteger.ONE;	static BigInteger n = BigInteger.valueOf(3);	static BigInteger l = BigInteger.valueOf(3);	static PrintWriter out; 	public static void main(String[] args) {		BigInteger nn, nr;		boolean first = true;		File outpi = new File(System.getProperty("user.home")+"/out.pi");				try {			out = new PrintWriter(outpi);						while(true){				if(four.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){					out.print(n);					if(first){out.print("."); first = false;}					nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t)));					n = BigInteger.TEN.multiply(three.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n));					q = q.multiply(BigInteger.TEN);					r = nr;					out.flush();					System.out.println((outpi.length()-2)+", Decimals Computed");				}else{					nr = two.multiply(q).add(r).multiply(l);					nn = q.multiply((seven.multiply(k))).add(two).add(r.multiply(l)).divide(t.multiply(l));					q = q.multiply(k);					t = t.multiply(l);					l = l.add(two);					k = k.add(BigInteger.ONE);					n = nn;					r = nr;				}			}		}catch (IOException e) {			e.printStackTrace();		}finally{			out.close();		}	}	}
Link to comment
Share on other sites

Link to post
Share on other sites

It computes Pi and tells you how far it got and outputs the results of computed pi in realtime in a file so when your computer crashes you can have the latest computed pi stored locally

 

- code -
it might be nice naming the source, if this is the case?

http://rosettacode.org/wiki/Pi#Java

Link to comment
Share on other sites

Link to post
Share on other sites

that just computes pi though and doesn't save it within a file and tells you the decimals

sure, it's not a mere copypaste, but as it gave you some... inspiration, the source deserves a little link, just for reference

Link to comment
Share on other sites

Link to post
Share on other sites

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Diagnostics;namespace awesome{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            if (textBox1.Text == "AWESOME")            {                Process.Start("http://www.linustechtips.com");            }            else            {                MessageBox.Show("You are lacking awesomeness");            }        }    }}

Where is my reward?  B)

Link to comment
Share on other sites

Link to post
Share on other sites

made this in python(2.7.6), it calculates all prime numbers till 999

for n in range(1, 1001):    for x in range(2, n):        if n % x == 0:            print n, 'equals', x, '*', n/x            break    else:        # loop fell through without finding a factor        print n, 'is a prime number'

edit(s):

cleared a typo.

at the moment looking to how far i can push it up with this code.

Link to comment
Share on other sites

Link to post
Share on other sites

https://gist.github.com/migueldferreira/9485468

 

Just a simple python 3 script with some functions to create, populate and query a database of transactions.

Helps me keep track of mah monay!

 

The goal of this script was to create a stepping stone to move from excel (libre office calc, actually) to mysql and php and be able to log my transactions from the web without having to store the files in dropbox or having to ssh.

But that's probably going to take a looooooong time! I'm still trying to figure out some functionality to be able to categorize the transactions (that's why there is an extra 'type' column in there) to make searching and "data mining" easier.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Skyrim Save Converter for Xbox 360 to PC and back again:

Language: Visual Basic

Imports System.IO Public Class Form1     Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load        PCSaveDirectory.Text = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)    End Sub     Private Sub SelectX360_Click(sender As System.Object, e As System.EventArgs) Handles SelectX360.Click        Dim OFD As New OpenFileDialog        OFD.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)        OFD.Filter = "Xbox 360 Gamesave (*.dat)|*.dat"        If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then            X360GamesaveDirectory.Text = OFD.FileName        End If    End Sub     Private Sub X360GamesaveDirectory_TextChanged(sender As System.Object, e As System.EventArgs) Handles X360GamesaveDirectory.TextChanged        If Not X360GamesaveDirectory.Text = "" Then            ConvertToPC.Enabled = True        Else            ConvertToPC.Enabled = False        End If    End Sub     Private Sub Convert_Click(sender As System.Object, e As System.EventArgs) Handles ConvertToPC.Click        Try            If File.Exists(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\my games\skyrim\saves\" & "Savegame.ess") Then                If MessageBox.Show("This File Already Exsists!" & Environment.NewLine & "Do you want to Overwrite it?", "File Already Exists", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) = Windows.Forms.DialogResult.Yes Then                    File.Delete(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\my games\skyrim\saves\" & "Savegame.ess")                    File.Copy(X360GamesaveDirectory.Text, System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\my games\skyrim\saves\" & "Savegame.ess")                End If            Else                File.Copy(X360GamesaveDirectory.Text, System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\my games\skyrim\saves\" & "Savegame.ess")            End If            MessageBox.Show("File has Succefully been Converted to PC." & Environment.NewLine & Environment.NewLine & "Now you can Start Skyrim to Load this Game Save.", "Succefully Converted", MessageBoxButtons.OK, MessageBoxIcon.Information)        Catch ex As Exception            MessageBox.Show(ErrorToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)        End Try    End Sub     Private Sub ResetX360_Click(sender As System.Object, e As System.EventArgs) Handles ResetX360.Click        X360GamesaveDirectory.Text = ""    End Sub     Private Sub SelectPC_Click(sender As System.Object, e As System.EventArgs) Handles SelectPC.Click        Dim OFD As New OpenFileDialog        OFD.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\my games\skyrim\saves"        OFD.Filter = "PC Gamesave (*.ess)|*.ess"        If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then            PCGamesaveDirectory.Text = OFD.FileName        End If    End Sub     Private Sub SelectPCSave_Click(sender As System.Object, e As System.EventArgs) Handles SelectPCSave.Click        Dim FBD As New FolderBrowserDialog        With FBD            .RootFolder = Environment.SpecialFolder.Desktop            .SelectedPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)            .Description = "Select a folder"            If .ShowDialog = DialogResult.OK Then                PCSaveDirectory.Text = .SelectedPath            End If        End With    End Sub     Private Sub ConvertToX360_Click(sender As System.Object, e As System.EventArgs) Handles ConvertToX360.Click        Try            If File.Exists(PCSaveDirectory.Text & "\Savegame.dat") Then                If MessageBox.Show("This File Already Exsists!" & Environment.NewLine & "Do you want to Overwrite it?", "File Already Exists", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) = Windows.Forms.DialogResult.Yes Then                    File.Delete(PCSaveDirectory.Text & "\Savegame.dat")                    File.Copy(PCGamesaveDirectory.Text, PCSaveDirectory.Text & "\Savegame.dat")                End If            Else                File.Copy(PCGamesaveDirectory.Text, PCSaveDirectory.Text & "\Savegame.dat")            End If            MessageBox.Show("File has Succefully been Converted to Xbox 360." & Environment.NewLine & Environment.NewLine & "Please use a program like Modio or Horizon to Inject the 'savegame.dat' into a Xbox 360 '.CON' File.", "Succefully Converted", MessageBoxButtons.OK, MessageBoxIcon.Information)        Catch ex As Exception            MessageBox.Show(ErrorToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)        End Try    End Sub     Private Sub ResetPC_Click(sender As System.Object, e As System.EventArgs) Handles ResetPC.Click        PCGamesaveDirectory.Text = ""        PCSaveDirectory.Text = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)    End Sub     Private Sub PCGameSaveDirectory_TextChanged(sender As System.Object, e As System.EventArgs) Handles PCGamesaveDirectory.TextChanged, PCSaveDirectory.TextChanged        If Not PCGamesaveDirectory.Text = "" And Not PCSaveDirectory.Text = "" Then            ConvertToX360.Enabled = True        Else            ConvertToX360.Enabled = False        End If    End SubEnd Class
AMD FX 6350 @4.3GHz | Gigabyte 990XA-UD3 Rev. 3.0 | 8GB Dual Channel @1600MHz Corsair Vengeance LP | 2GB MSI GTX 660 Ti Power Edition

CiT Vengeance x11 | 500GB Segate, 2TB WD Green, 2TB WD Red | OCZ ZT 650W | Akasa Venom Voodoo | Ozone 5.1 Strato Evolution

Link to comment
Share on other sites

Link to post
Share on other sites

Siince I saw some Prime Seives I thought I post some of my prime related code:

My seive:

http://tizzyt-archive.blogspot.com/2014/02/prime-sieve.html

''' Prime Sieve '''    Private Function Sieve(ByVal limit As Integer) As List(Of Integer)        Dim sqrt As Integer, CrntNbr = 11        Sieve = {2, 3, 5, 7}.ToList        While CrntNbr < limit            sqrt = Math.Sqrt(CrntNbr)            For Each prime In Sieve                If prime <= sqrt Then                    If CrntNbr Mod prime = 0 Then Exit For                Else                    Sieve.Add(CrntNbr) : Exit For                End If            Next            CrntNbr += 2        End While    End Function

http://pastebin.com/y89dX3LH

 

My Large Prime Number Generator:
http://tizzyt-archive.blogspot.com/2014/02/large-prime-number-generator.html

''' Large Prime Generator '''    Public Function PrimeGen(ByVal length As Integer, ByRef Rand As Random, _                             Optional ByVal iteration As Integer = 0) As BigInteger        If length < 2 Then length = 2        If iteration = 0 Then iteration = Math.Sqrt(length)        Dim temp, r, y, a(iteration - 1) As BigInteger        PrimeGen = RandBigInt(length, Rand)        While True            If PrimeGen.IsEven Then PrimeGen -= 1            If PrimeGen Mod 5 = 0 Then PrimeGen -= 2            If PrimeGen <= 3 Then Return Rand.Next(2, 4)            For i = 0 To a.Length - 1                While a(i) <= 2 Or a(i) >= PrimeGen - 2 : a(i) = RandBigInt(length, Rand) : End While            Next            r = New BigInteger((PrimeGen - 1).ToByteArray())            While r Mod 2 = 0 : r = r / 2 : End While            For i = 0 To iteration - 1                temp = r                y = BigInteger.ModPow(a(i), r, PrimeGen)                While temp <> PrimeGen - 1 AndAlso y <> 1 AndAlso y <> PrimeGen - 1                    y = BigInteger.ModPow(y, 2, PrimeGen)                    temp = BigInteger.Multiply(temp, 2)                End While                If y <> PrimeGen - 1 AndAlso BigInteger.ModPow(temp, 1, 2) = 0 Then : Exit For                ElseIf i = iteration - 1 Then : Return PrimeGen : End If            Next            PrimeGen -= 2        End While    End Function    Private Function RandBigInt(ByVal BitLength As BigInteger, ByRef Rnd As Random) As BigInteger        Dim Rmdr, numParts(BigInteger.DivRem(BitLength, 8, Rmdr)) As Byte        For i = 0 To numParts.Length - 2 : numParts(i) = Rnd.Next(0, 256) : Next        numParts(numParts.Length - 1) = If(Rmdr = 0, 0, Rnd.Next(0, 2 ^ Rmdr - 1))        RandBigInt = New BigInteger(numParts)    End Function

http://pastebin.com/RV3kyuqu

 

Prime Number test (Miller Rabin):
http://tizzyt-archive.blogspot.com/2014/02/miller-rabin-vbnet.html

''' Miller Rabin Primality Test '''    Public Function MRtest(N As BigInteger, iterations As Integer) As Boolean        Dim a, y, t As BigInteger, r As New BigInteger((N - 1).ToByteArray())        If N = 2 OrElse N = 3 Then Return True        If N Mod 2 = 0 Then Return False        While r Mod 2 = 0 : r = r / 2 : End While        For i = 0 To iterations - 1            t = r            Do : a = RandBigInt(BitLen(N), New Random) : Loop While a < 2 OrElse a > N - 2            y = BigInteger.ModPow(a, r, N)            While t <> N - 1 AndAlso y <> 1 AndAlso y <> N - 1                y = BigInteger.ModPow(y, 2, N)                t = BigInteger.Multiply(t, 2)            End While            If y <> N - 1 AndAlso BigInteger.ModPow(t, 1, 2) = 0 Then Return False        Next        Return True    End Function    Private Function RandBigInt(ByVal BitLength As BigInteger, ByRef Rnd As Random) As BigInteger        Dim Rmdr, numParts(BigInteger.DivRem(BitLength, 8, Rmdr)) As Byte        For i = 0 To numParts.Length - 2 : numParts(i) = Rnd.Next(0, 256) : Next        numParts(numParts.Length - 1) = If(Rmdr = 0, 0, Rnd.Next(0, 2 ^ Rmdr - 1))        RandBigInt = New BigInteger(numParts)    End Function    Private Function BitLen(ByVal TestingNbr As BigInteger) As BigInteger        Dim Nbr As String = TestingNbr.ToString("X")        BitLen = Convert.ToString(Convert.ToInt32(Nbr(0), 16), 2).TrimStart("0").Length        BitLen = BigInteger.Add(BitLen, BigInteger.Multiply(New BigInteger(4), New BigInteger(Nbr.Length - 1)))    End Function

http://pastebin.com/PXCZ5p7x

Link to comment
Share on other sites

Link to post
Share on other sites

fixed code isn't 100 lines...

Link to comment
Share on other sites

Link to post
Share on other sites

Dunno if this works? Its a game of battleship I made in Python - currently learning it using codeacademy and I just finished this little game 

from random import randintboard = []for x in range(5):    board.append(["O"] * 5)def print_board(board):    for row in board:        print " ".join(row)print "Let's play Battleship!"print_board(board)def random_row(board):    return randint(0, len(board) - 1)def random_col(board):    return randint(0, len(board[0]) - 1)ship_row = random_row(board)ship_col = random_col(board)for turn in range(4):    guess_row = int(raw_input("Guess Row:"))    guess_col = int(raw_input("Guess Col:"))    if guess_row == ship_row and guess_col == ship_col:        print "Congratulations! You sunk my battleship!"        break    else:        if turn == 3:            print "Game Over"        else:            if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):                print "Oops, that's not even in the ocean."            elif(board[guess_row][guess_col] == "X"):                print "You guessed that one already."            else:                print "You missed my battleship!"            board[guess_row][guess_col] = "X"        print (turn + 1)        print_board(board)

Desktop - Corsair 300r i7 4770k H100i MSI 780ti 16GB Vengeance Pro 2400mhz Crucial MX100 512gb Samsung Evo 250gb 2 TB WD Green, AOC Q2770PQU 1440p 27" monitor Laptop Clevo W110er - 11.6" 768p, i5 3230m, 650m GT 2gb, OCZ vertex 4 256gb,  4gb ram, Server: Fractal Define Mini, MSI Z78-G43, Intel G3220, 8GB Corsair Vengeance, 4x 3tb WD Reds in Raid 10, Phone Oppo Reno 10x 256gb , Camera Sony A7iii

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

dam. made a program and before i realized i was a 1000 lines ( dam gui )

:(

Needs Update

Link to comment
Share on other sites

Link to post
Share on other sites

You know, with Java, I could just very tediously write all my code in one huge line,

so technically i would only use 1 line xD

i love you

Link to comment
Share on other sites

Link to post
Share on other sites

dam. made a program and before i realized i was a 1000 lines ( dam gui )

:(

who cares, put up a download i wanna see it

i love you

Link to comment
Share on other sites

Link to post
Share on other sites

You know, with Java, I could just very tediously write all my code in one huge line,

so technically i would only use 1 line xD

This would be a good way to make people work for your source code :P or even write a script to do it for them

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×