Jump to content

The under 100 line challenge!

fletch to 99

Awww man I had a program that made my room's light turn on and off from my phone or any browser, it was barely 50 lines of code, and it was using a custom http server... Guess what? Python!

 

I had a gpu monitor app for Linux too. It just showed temp and clock graph, nothing fancy. that was made out of need, not for fun xD (although it was...)
 

It doesn't really count buy I had attached a led strip to my pc and made a code that tells my arduino what to do based on what app I have open :c it was a lot like razer's case!

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

First post here. A little program I made, that converts a number written in decimals in words. Hope someone considers this useful.

 


 

#include <iostream>
#include <string>
#include <vector>

using namespace std;

string digit[1000] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fouteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"},
expo [] = {"", "thousand,", "million,", "billion", "trillion,", "quadrillion,"};

vector <string> engNum;

int st, niv;

void Set (int st, int niv) {
    if (!st)
        return;
    engNum.push_back (" " + expo[niv]);
    if (st % 100 <= 20 ) {
        engNum.push_back (" " + digit[st % 100]);
    }
    else {
        if (st % 10 != 0)
            engNum.push_back (" " + digit[st % 10]);
        if ((st / 10) % 10 != 0)
            engNum.push_back (" " + digit[st % 100 - st % 10]);
    }
    if (st / 100 != 0)
        engNum.push_back (" " + digit[st / 100] + " " + digit[100] + " and");
}

int main()
{
    string x;
    digit[30] = "thirty"; digit[40] = "fourty"; digit[50] = "fifty"; digit[60] = "sixty"; digit[70] = "seventy"; digit[80] = "eighty"; digit[90] = "ninety", digit[100] = "hundred";

    for (;;) {
        cin >> x;
        if (x == "0")
            cout << " zero\n";
        else {
            for (int i = x.size () - 1, niv = 0; i >= 0; i = i - 3) {
                if (i >= 2) {
                    st = (x.at (i) - 48) + (x.at (i - 1) - 48) * 10 + (x.at (i - 2) - 48) * 100;
                    Set (st, niv);
                    niv++;
                }
                else {
                    if (i == 1) {
                        st = (x.at (i) - 48) + (x.at (i - 1) - 48) * 10;
                        Set (st, niv);
                    }
                    else {
                        st = (x.at (i) - 48);
                        Set (st, niv);
                    }
                }
            }


            for (int i = engNum.size () - 1; i >= 0; i--) {
                if (i == 0) {
                    x = engNum [0];
                    if (x.at (x.size () - 1) == ',')
                        x.at (x.size () - 1) = ' ';
                    cout << x;
                    break;
                }
                cout << engNum; 

            }
            cout << "\n";
            engNum.clear();
        }
    } 

    return 0;
}
  

Link to comment
Share on other sites

Link to post
Share on other sites

A JS module for editing point array data, I just finally got it to work properly after realizing I've been writing the equations that calculate the new positions of points has been wrong this entire time.

 

99 lines of code and some comments.

var object = function (color) {
	
	// Define our matrices
	this.x = [];
	this.y = [];
	this.s = [];
	
	// Set out color
	this.color = color;
	
	// Set our scale factor.
	this.scale = 0.5
	
	// Set our range of detection.
	this.range = 10
	
	// Set the offset of our vertex
	this.offset = [GetScreenWidth() / 2,  GetScreenHeight() / 2];
	
	// Create our pen.
	this.pen = new pen(this.color,this.offset);
}

object.prototype = {};

// Adds new points to the array.
object.prototype.addPoint = function(x, y, s)
{
	this.x.push(x);this.y.push(y);this.s.push(s);
	Print("Added point " + x + "," + y);
}

// Resets the offset
object.prototype.resetOffset = function()
{
	this.offset = [GetScreenWidth() / 2, GetScreenHeight() / 2];
}
	
	
// Renders our object.
object.prototype.render = function (ox, oy)
{
	// Resets our clock
	f = 0
	while(f < this.x.length)
	{
		// Grab the current position of the mouse.
		mouseData = [GetMouseX(), GetMouseY()];
		
		// Set our cache to I forget
		cache = [(this.x[f] * this.scale) + this.offset[0], (this.y[f] * this.scale * -1) + this.offset[1]];
		mCache = null
		
		// If the point exists, draw it.
		if (f == this.x.length)
		{
			this.pen.draw(cache[0], cache[1], this.s[0]);
		}
		else
		{
			this.pen.draw(cache[0], cache[1], this.s[f]);
		}
		
		// If the mouse is on a point, allow interaction.
		if (mouseData[0] < cache[0] + this.range)
		{
			if (mouseData[0] > cache[0] - this.range)
			{
				if (mouseData[1] < cache[1] + this.range)
				{
					if (mouseData[1] > cache[1] - this.range)
					{
						// Draw an indicator over the point we want to modify.
						Rectangle(cache[0] - 4.5, cache[1] - 4.5, 9,9, CreateColor(0,255,255,255));
						
						// If the mouse is clicked and held begin operations on point.
						if (IsMouseButtonPressed(MOUSE_LEFT))
						{
							if (mCache == null)
							{
								mCache = f;
							}
							this.x[mCache] = (mouseData[0] - this.offset[0]) / this.scale
							this.y[mCache] = (mouseData[1] - this.offset[1]) / this.scale * -1
						}
						else
						{
							if (mCache !== null)
							{
								mCache = null
							}
						}
					}
				}
			}
		}
		f = f + 1
	}
}

I'm not too happy with how bulky my collision code is but eh, it works.

My procrastination is the bane of my existence.

I make games and stuff in my spare time.

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

This thread immediately made me think of a little gem I whipped up in a few hours trying to teach basic AI concepts to a few college kids. I build a travelling salesman genetic solver in JavaScript (and Python) and it works surprisingly well. When you add all the DOM crap it's something like 400 lines, full code (with demo) is on JSBin [edit link], feel free to fork it and do whatever, I'm all for it. Just ping me if you create something cool. I also took an image of a reasonably solved state (below) and the results aren't that unreasonable. Then, I bundled the basics into a Python class and put it on GitHub - the actual framework for the genetic solver is only 80 lines, including comments:

import math
import random

class Organism:
    fitness = None
    data = None
    def __init__(self, data):
        self.data = data
    def mutate(self, mutate_func):
        self.data = mutate_func(self.data)
    def reproduce(self, reproduce_func, other):
        return Organism(reproduce_func(self.data, other.data))
    def score(self, fitness_func):
        self.fitness = fitness_func(self.data)

class GenerationStats:
    raw = []
    def __init__(self, population):
        self.raw = map(lambda o: o.fitness, population.organisms)
    
    def percentile(self, p):
        return self.raw[int((len(self.raw)-1)/100*p)]

class Population:
    generate_func = None
    mutate_func = None
    reproduce_func = None
    fitness_func = None
    organisms = []
    state = None
    generation_data = []

    def __init__(self, generate_func, mutate_func, reproduce_func, fitness_func, size):
        self.generate_func = generate_func
        self.mutate_func = mutate_func
        self.reproduce_func = reproduce_func
        self.fitness_func = fitness_func
        for i in range(0, size):
            self.organisms += [Organism(generate_func())]

    def step(self):
        # Score all organisms.
        for org in self.organisms:
            org.score(self.fitness_func)

        # Sort by fitness.
        self.organisms.sort(key=lambda o: o.fitness)
        
        # Record generation info.
        self.generation_data.append(GenerationStats(self))
        
        # Kill with gradient.
        population_size = len(self.organisms)
        for i, org in enumerate(self.organisms):
            if random.randrange(population_size) < i:
                self.organisms[i] = None
        
        # Replace missing in population with new.
        org_copy = self.organisms[:]
        for i, org in enumerate(self.organisms):
            if org is None:
                mom = None
                dad = None
                while True:
                    mom = self.organisms[random.randrange(population_size)]
                    if mom is not None:
                        break;
                while True:
                    dad = self.organisms[random.randrange(population_size)]
                    if dad is not None:
                        break;
                org_copy[i] = dad.reproduce(self.reproduce_func, mom)
                org_copy[i].mutate(self.mutate_func)
        self.organisms = org_copy[:]
    
    def has_converged(self):
        top = self.generation_data[-1].percentile(0)
        median = self.generation_data[-1].percentile(50)
        # < 1% difference between top and median in population
        return abs((top-median)/top) < 0.01

You can use it by just telling it how to generate a random solution for your problem, what a success metric, how to mutate things and how to reproduce things and voila, it can solve any problem. Travelling salesman example is, again, in the repo but doesn't have that nice visual part JS version does. My favorite thing I did with this was to evolve the best convoluted neural network for a kinda specific image recognition task I had by training randomly structured networks and evaluating their accuracy as my "success" metric, then merging the successful ones based on a structural similarity function. Took a few days to run but I was super happy with the resulting network. I might still have the code somewhere if anyone cares to see it.

travelling salesman.png

Link to comment
Share on other sites

Link to post
Share on other sites

On 12.1.2017 at 2:03 AM, sgzUk74r3T3BCGmRJ said:
  Reveal hidden contents

 

I came across this post while reading people bike-shed about what language a beginner should use:

The author stated they'd want a program that…

So they wanted a simple substitution cipher. Fair enough, but generating the mapping is probably already built into your shell. What if we took that idea and made it a web service instead of just a crumby desktop application? We could call it "TerribleEncryption.io", now with more Web 2.0! What would it take to make a minimum viable API that we could start building on? Maybe we could pitch it to VCs and become the next Snapchat!

 

We'd want to define a minimal API:

 

Given that spec, what's the shortest complete solution we can provide that:

  1. Only uses code within the language's standard library
  2. Doesn't use ";"—or similar—to cram everything onto a single line.
  3. Sticks to something readable like 80 characters per line.
  4. No compiler errors/warnings, but ungraceful handling of things off the happy-path are okay.
  5. Let's allow for cheats like short variable names, unidiomatic solutions, trimming whitespace, etc.

I propose something like the code at the top does the job. Assuming you've tossed that into a file called "server.rb" then you can run it with:



ruby server.rb

It seems to work as advertised:



> http post :8000 msg="twinkle twinkle little star"
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 72
Content-Type: text/json
Date: Thu, 12 Jan 2017 00:01:01 GMT
Server: WEBrick/1.3.1 (Ruby/2.3.3/2016-11-21)

{
    "key": "sxwmvfyuztdriajghbcenlqokp",
    "msg": "eqzadrv eqzadrv rzeerv cesb"
}


> http get :8000 msg="eqzadrv eqzadrv rzeerv cesb" key="sxwmvfyuztdriajghbcenlqokp"
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 37
Content-Type: text/json
Date: Thu, 12 Jan 2017 00:01:05 GMT
Server: WEBrick/1.3.1 (Ruby/2.3.3/2016-11-21)

{
    "msg": "twinkle twinkle little star"
}

 

 

 

I think this topic would be a lot more interesting if it were "what can you do in 1000 bytes?" We can get a pretty long way with about 400 bytes and half an hour worth of code-golf.

True, especially since there are languages which require more, but shorter LoC (ASM, Python, Ruby, ...).

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

here you go.
working web browser built in vb, 64 lines of code

 

 

   

public class form1

Private Sub btn_close_Click(sender As Object, e As EventArgs) Handles btn_close.Click
        Me.Close()
    End Sub

    Private Sub btn_properties_Click(sender As Object, e As EventArgs) Handles btn_properties.Click
        Process.Start("inetcpl.cpl")
    End Sub

    Private Sub btn_forward_Click(sender As Object, e As EventArgs) Handles btn_forward.Click
        If WebBrowser1.CanGoForward Then
            WebBrowser1.GoForward()
        End If
    End Sub

    Private Sub btn_back_Click(sender As Object, e As EventArgs) Handles btn_back.Click
        If WebBrowser1.CanGoBack Then
            WebBrowser1.GoBack()

        End If
    End Sub

    Private Sub btn_home_Click(sender As Object, e As EventArgs) Handles btn_home.Click
        WebBrowser1.GoHome()
    End Sub

    Private Sub btn_go_Click(sender As Object, e As EventArgs) Handles btn_go.Click
        WebBrowser1.Navigate(txtbx_url.Text)
    End Sub

    Private Sub btn_stop_Click(sender As Object, e As EventArgs) Handles btn_stop.Click
        WebBrowser1.Stop()
    End Sub

    Private Sub btn_refresh_Click(sender As Object, e As EventArgs) Handles btn_refresh.Click
        WebBrowser1.Refresh()
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs)
        txtbx_url.Text = WebBrowser1.Url.ToString

    End Sub

    Private Sub txtbx_url_KeyDown(sender As Object, e As KeyEventArgs) Handles txtbx_url.KeyDown
        If e.KeyCode = Keys.Enter Then
            WebBrowser1.Navigate(txtbx_url.Text)
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        WebBrowser1.Navigate("http://www.google.co.nz")
        WebBrowser1.ScriptErrorsSuppressed = True
    End Sub

    Private Sub WebBrowser1_DocumentCompleted_1(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        txtbx_url.Text = WebBrowser1.Url.ToString()
    End Sub

    Private Sub btn_newbrowserwindow_Click(sender As Object, e As EventArgs)

    End Sub
End Class[ /code]

Link to comment
Share on other sites

Link to post
Share on other sites

I made an entire Neural Network in just 75 lines....ok, maybe not a network, but it does train a single sigmoid neuron.

package theGhastModding.oneHundred.main;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Random;

public class SigmoidNeuron {
	
	public static void main(String[] args){
			try {
			List<String> lines = Files.readAllLines(Paths.get(args[0]));
			double[][] inSequence = new double[lines.size()][];
			for(int i = 0; i < inSequence.length; i++){
				String[] a = lines.get(i).split("#");
				inSequence[i] = new double[a.length];
				for(int j = 0; j < a.length; j++) inSequence[i][j] = Double.parseDouble(a[j]);
			}
			String[] expectedStrings = Files.readAllLines(Paths.get(args[1])).get(0).split("#");
			double[] expectedSequence = new double[expectedStrings.length];
			for(int i = 0; i < expectedSequence.length; i++) expectedSequence[i] = Double.parseDouble(expectedStrings[i]);
			int iterations = Integer.parseInt(args[2]);
			double trainingRate = Double.parseDouble(args[3]);
			double[] weights = new double[inSequence[0].length];
			double bias = 1;
			double loss = loss(expectedSequence, pass(inSequence, bias, weights));
			double[] prevWeights = copy(weights);
			Random random = new Random();
			for(int i = 0; i < iterations; i++){
				if(i % (iterations / 100 * 10) == 0) System.out.println("Iteration: " + Integer.toString(i) + "/" + Integer.toString(iterations));
				for(int j = 0; j < weights.length; j++) if(random.nextBoolean()) weights[j] += (random.nextDouble() - 0.5d) * trainingRate;
				if(random.nextBoolean()) bias += (random.nextDouble() - 0.5d) * trainingRate;
				double newLoss = loss(expectedSequence, pass(inSequence, bias, weights));
				if(newLoss < loss){
					prevWeights = copy(weights);
					loss = newLoss;
				}else{
					weights = copy(prevWeights);
				}
			}
			System.out.println("Done.\nGenerating outputs...");
			double[] outputs = pass(inSequence, bias, weights);
			for(int i = 0; i < outputs.length; i++)System.out.println(Double.toString(outputs[i]) + ",");
			System.out.println();
		} catch(Exception e) {e.printStackTrace();}
	}
	private static double loss(double[] expected, double[] output){
		double tmse = 0;
		for(int i = 0; i < expected.length; i++){
			tmse += Math.pow(expected[i] - output[i], 2D);
		}
		return tmse * (1d / ((double)expected.length * 2d));
	}
	private static double[] copy(double[] original){
		double[] copy = new double[original.length];
		for(int i = 0; i < copy.length; i++){
			copy[i] = original[i];
		}
		return copy;
	}
	private static double[] pass(double[][] inputs, double bias, double[] weights){
		double[] outputs = new double[inputs.length];
		for(int j = 0; j < inputs.length; j++){
			double v = 0;
			for(int i = 0; i < inputs[j].length; i++){
				v += weights[i] * inputs[j][i] - bias;
			}
			outputs[j] = sigmoid(v);
		}
		return outputs;
	}
	private static double sigmoid(double z){
		return 1 / (1 + Math.pow(Math.E, -z));
	}
}

You use it as follows:

1: Type your training inputs into a text document. Seperate inputs with new lines and numbers with #. Save it.

2. Type the outputs you want the neuron to give your for the inputs in the previous step. Seperate the numbers with # and write it all in one line

3. Start the program with the arguments like this: java -jar [whatever you named the .jar file after exporting] [path to file containing training inputs] [path to file containing wanted outputs] [number of training iterations you want it to do] [training rate]

4. Wait for it to finish.

5. At the end, it gives you the final outputs of the neuron for the given training inputs

At the moment it doesn't save the neuron, so you can really only train it. But i have like 25 free lines, so i'll definitely update it.

Example:

I trained a neuron using this as training input:

0#0
0#1
1#0
1#1

And this as the outputs i wanted:

1#1#1#0

So we want the output to be 1 for the inputs of 0 and 0, 0 and 1, 1 and 0. And want it to be 0 for the inputs of 1,1.

Which is basically a NAND gate. I trained it with a training rate of 1 over 100 iterations and got these outputs:

0.9998635526179154,
0.9431409876976167,
0.949081101268096,
0.04048354437353434,

which is very close to what i wanted. So it DOES work. Kinda useless until you can save and load the weights and the bias, but i'm working on it.

Note: i know this uses what is probably the most slow and most ineficient training algorithm. But did you really expect me to program gradient descent in the 25 lines that were left?

Link to comment
Share on other sites

Link to post
Share on other sites

very simple: a direct download link converter for google drive. needed a direct download link for a website I built with a friend. these few lines in python saved me so much time copying and pasting xD you simply enter the shareing link and it spews out the download link. it is simple as all hell but so usefull to me.

 

 

reflink= "https://drive.google.com/uc?export=download&id="
vlink= input()
dlink = vlink.split("=")
print(dlink)
d2link = dlink[1].split("/view")
print(reflink + d2link[0])
print("do you want to exit? y/n")
awns= input()
if "y" in awns:
    print("oke")
else:
    print("shutting down anyway")

 

 

 ______     ______     ______     ______     __  __     __   __     ______     __   __     ______     ______  
/\  __ \   /\  == \   /\  __ \   /\  ___\   /\ \_\ \   /\ "-.\ \   /\  ___\   /\ "-.\ \   /\  ___\   /\__  _\ 
\ \  __ \  \ \  __<   \ \  __ \  \ \ \____  \ \  __ \  \ \ \-.  \  \ \  __\   \ \ \-.  \  \ \  __\   \/_/\ \/ 
 \ \_\ \_\  \ \_\ \_\  \ \_\ \_\  \ \_____\  \ \_\ \_\  \ \_\\"\_\  \ \_____\  \ \_\\"\_\  \ \_____\    \ \_\ 
  \/_/\/_/   \/_/ /_/   \/_/\/_/   \/_____/   \/_/\/_/   \/_/ \/_/   \/_____/   \/_/ \/_/   \/_____/     \/_/ 
Link to comment
Share on other sites

Link to post
Share on other sites

I made a (very poor) lisp interpreter in Python: https://gist.github.com/jmikkola/b7c6c644dff1c07891c698f0a527a890

 

It's just powerful enough to let you define functions like map:

(def map
     (fn (f lst)
         (if (eq lst ())
             ()
           (cons (f (head lst)) (map f (tail lst))))))

(def times-10 (fn (n) (* 10 n)))

(print (map times-10 (list 1 2 3 4 5)))

 

R7 1700x @ 3.9Ghz, MSI GTX 1070, 16 GB ram, too many drives to count, P400s case, H100i cooler

HD6xx Headphones, LG UM95 34UM95 34" ultrawide, Corsair K70 keyboard with red switches

 

lstdgtfp = consonants from "last digit of pi"

I never claimed it was a good username.

Link to comment
Share on other sites

Link to post
Share on other sites

Here's a little program that calculates pi using the probability of picking two random coprime integers.

#include <bits/stdc++.h>
using namespace std;
int n=1000000,k=0;
double prob,pi,realPi=atan(1)*4;
int main()
{
    mt19937_64 rng;
    rng.seed(chrono::system_clock::now().time_since_epoch().count());
    uniform_int_distribution<uint64_t> r;
    for(int i=1;i<=n;++i)
    {
        uint64_t a=r(rng),b=r(rng);
        if(__gcd(a,b)==1)
            k++;
    }
    prob=(double)k/n;
    pi=sqrt(6.0/prob);
    cout<<setprecision(64)<<"Generated value : "<<pi<<endl<<"Actual value of pi : "<<realPi<<endl<<"Error : "<<pi-realPi<<endl<<"Precision : "<<100-abs(pi-realPi)/realPi*100<<" %";
    return 0;
}

 

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

32 minutes ago, Nineshadow said:

Here's a little program that calculates pi using the probability of picking two random integers which are coprime.

I too saw that video and here's a Python version written in the worst way possible.

print(f'Pi = {__import__("math").sqrt(6/(lambda gcd, randint: (lambda x: x.count(1) / len(x))([gcd(randint(0,1000000), randint(0,1000000)) for _ in range(1000000)]))(__import__("math").gcd, __import__("random").randint))}')

 

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

I made this screensaver thing a little while ago in JavaScript using PixiJS, you can see it in action here: http://opl.io/bg/add_orbs/

it's only 87 lines but you can tell in one look that it's not optimized for minimum linelyness.

var stage = new PIXI.Container();

var renderer = new PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, {backgroundColor : 0x000000});

PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST;
renderer.autoResize = true;


document.body.appendChild(renderer.view);


PIXI.loader
  .add("images/grey_blured_circle.png")
  .load(setup);

var things = [];

function r(min,max) {
  return Math.floor(Math.random()*(max-min))+min;
}

function addThing (number = things.length, create = false) {
  if (!create) {
    thing = new PIXI.Sprite(
      PIXI.loader.resources["images/stone_tile.png"].texture
    );
    thing.x = r(0,window.innerWidth);
    thing.y = r(0,window.innerHeight);
    thing.scale.x = r(0,100)/50+0.25;
    thing.scale.y = thing.scale.x;
    thing.tint = Math.random() * 0xFFFFFF;
    thing.blendMode = PIXI.BLEND_MODES.ADD;
    things[number] = {
      sprite: thing,
      offset: {
        x:r(10,100)/100,
        y:r(0,50)/100-0.5
      }
    }
    stage.addChild(thing);
  }
  else {
    things[number].sprite.scale.x = r(0,100)/50+0.25;
    things[number].sprite.scale.y = things[number].sprite.scale.x;
    things[number].sprite.x=-things[number].sprite.width;
    things[number].sprite.y=r(0,window.innerHeight);
    things[number].offset.x=r(10,100)/100;
    things[number].offset.y=r(0,50)/100-0.5;
    things[number].tint = Math.random() * 0xFFFFFF;
  }
}

function removeThing (thing) {
  things[thing];

  addThing(thing, true);
}

function setup() {
  for (var i = 0; i < window.innerWidth/50*window.innerHeight/300; i++) {
    addThing();
  }
};

var start = Date.now();

var cam = {x:0,y:0};


window.addEventListener("resize", function () {
  renderer.resize(window.innerWidth, window.innerHeight);
});


function tic() {
  for (var i = things.length - 1; i >= 0; i--) {
    things[i].sprite.x += things[i].offset.x*5;
    things[i].sprite.y += things[i].offset.y;
    if (things[i].sprite.y > window.innerHeight || things[i].sprite.x > window.innerWidth || things[i].sprite.y < -things[i].sprite.height) {
      removeThing(i);
    }
  }
	renderer.render(stage);
	window.requestAnimationFrame(tic);
}
tic();

 

Link to comment
Share on other sites

Link to post
Share on other sites

Just spent about 45 minutes writing this, I dunno why I didn't think to write it sooner.

 

It's basically a tool for logging events in situations where you don't have an actual console to log to. It probably won't work outside of anything compatible with the Sphere v1.5 API specification; at least not without modifications to the code.

 

Maybe one day I'll learn how to properly develop within a web environment and make an HTML5 implementation of the sphere engine.

 

/*
Waifu.js - a tool for seeing events realtime within the Sphere RPG engine.

Feel free to use this code in whatever, alhough it will probably need
to be adapted to function within a browser.
*/

// Create our console constructor, now you can have multiple consoles!
var runtimeConsole = function (lines)
{
  this.log = [];
  this.font = GetSystemFont();
  this.lines = lines;
  this.bg = CreateSurface(system.screen.width, 11 + (this.lines * 10), CreateColor(100, 100, 100, 100));
  this.bg.line(0, this.bg.height - 1, system.screen.width, this.bg.height - 1, CreateColor(255,255,255));
  
  this.log.push(" Software Version - " + system.version + " [" + system.state + "]");
  this.log.push("----   ----   ----");
};

runtimeConsole.prototype = {};

//Displays our console if the display parameter returns true.
runtimeConsole.prototype.display = function (display)
{
  if (display == true)
  {
    this.bg.blit(0,0);
		if (this.log.length <= this.lines)
		{
			a = 0;
			b = 0;
			while (a < this.lines - this.log.length)
			{
				this.font.drawText(5, 5 + (10 * a), "[No event]");
				a = a + 1;
			};
			displayOffset = a - 1;
			while (a <= this.log.length + displayOffset)
			{
				this.font.drawText(5, 5 + (10 * a), this.log[b]);
				a = a + 1;
				b = b + 1;
			};
		} else {
			a = 0;
			while (a < this.lines)
			{
				this.font.drawText(5, 5 + (10 * (this.lines - 1)) - (10 * a), this.log[this.log.length - a - 1]);
				a = a + 1;
			};
		}
	};
};

// Pushes a new event to the log array, self explanatory.
runtimeConsole.prototype.pushEvent = function (event) 
{
  this.log.push("- " + event);
};

 

My procrastination is the bane of my existence.

I make games and stuff in my spare time.

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, YoungProgrammer said:

waifu.js - thank you for the idea of a waifu search engine for all anime\manga. or is that MAL?

MAL? I dunno what that acronym stands for

 

Waifu.js is litterally a name I came up with for the script on the spot

 

EDIT: I googled MAL, I'm assuming that means Macro Assembly Language. If that's the case, then no, this is Core JavaScript written to run on the Sphere RPG Engine.

My procrastination is the bane of my existence.

I make games and stuff in my spare time.

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

On 3/24/2017 at 7:50 PM, YoungProgrammer said:

waifu.js - thank you for the idea of a waifu search engine for all anime\manga. or is that MAL?

Well, I mean it shouldn't be that hard... 

Hold on, imma do that right now.

 

In ~30 lines of code and all coding conventions followed, I bring you.... THE WAIFU SEARCHER!

What is does is it asks for your waifu's name, then opens up a tab with "$waifuName + waifu" to ensure relevant results!

 

TBH it probably isn't really useful but still... 

package ltt.under100;
import java.awt.Desktop;
import java.io.IOException;
import java.net.*;
import java.util.*;
public class LTTUnder100 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your waifu's name: ");
        final String waifuName = input.nextLine();
        String searchTerm = waifuName;
        for(int i = 0; i < waifuName.length(); i++){
            if(!Character.isLetterOrDigit(waifuName.charAt(i))){//checks to see if not an alphabet/digit
                searchTerm = searchTerm.replaceFirst( String.valueOf(waifuName.charAt(i)), "%" + Integer.toHexString((int) waifuName.charAt(i)));
            }    
        }
        try {
            if (Desktop.isDesktopSupported()) {
                // Windows
                Desktop.getDesktop().browse(new URI("https://www.bing.com/images/search?q=" + searchTerm + "%20waifu"));
             } else {
            // Ubuntu
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("/usr/bin/firefox -new-window " + "https://www.bing.com/images/search?q=" + searchTerm + "%20waifu");
            }
        } catch (IOException | URISyntaxException ex){  
            System.out.println("RIP");
        }  
    }
}

 

Want to know which mobo to get?

Spoiler

Choose whatever you need. Any more, you're wasting your money. Any less, and you don't get the features you need.

 

Only you know what you need to do with your computer, so nobody's really qualified to answer this question except for you.

 

chEcK iNsidE sPoilEr fOr a tREat!

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

This program implements a form of Euclid's Algorithm to calculate the greatest common divisor of two numbers in TI BASIC. It works flawlessly on my TI-84+. 

 


1→G
1→P
Prompt A,B
While G>0
G→P
If A>B
Then
remainder(A,B)→A
A→G
Else
remainder(B,A)→B
B→G
End
Disp G
End
Disp "Found P"
Disp P

Link to comment
Share on other sites

Link to post
Share on other sites

Nothing fancy, but here's an old shell script to monitor my RAID health (the script I currently use is more fancy, but this is under 100 lines):

 

#!/bin/bash

#Formatted hostname
server=`hostname | awk 'sub(".................$", "")' | awk '{print substr($0,0)}'`

#Set today's date (mmddyyyy)
DATE=`date +%m%d%G`

#Check RAID
/opt/MegaRAID/MegaCli/MegaCli64 -AdpAllInfo -aAll | grep Degraded > /var/log/raidmon.log
/opt/MegaRAID/MegaCli/MegaCli64 -AdpAllInfo -aAll | grep "Critical Disks" >> /var/log/raidmon.log
/opt/MegaRAID/MegaCli/MegaCli64 -AdpAllInfo -aAll | grep "Failed Disks" >> /var/log/raidmon.log
/opt/MegaRAID/MegaCli/MegaCli64 -PDList -aALL | awk -f /opt/MegaRAID/MegaCli/analysis.awk >> /var/log/raidmon.log

nail -s "Daily RAID Report for $server" email@example.com < /var/log/raidmon.log

 

-KuJoe

Link to comment
Share on other sites

Link to post
Share on other sites

My program is especially useful if you like to troll colleagues or (in my case) classmates by changing their wallpapers.

So basically what it does, it changes the wallpaper to a random picture from a specified folder after a certain amount of time.

It also checks that not the same image gets set as wallpaper twice in a row.

 

The time waited between the change of the wallpaper is random, but the limits are specified via a json settings file.

 

Here is the code for it: 

https://gist.github.com/anonymous/b70767bf62007e5b549e47513b540399
i have also included an example of the settings.json 

 

If you are interested, i also wrote an installer which creates a scheduled task to start the application at startup for extra fun

Link to comment
Share on other sites

Link to post
Share on other sites

Hey, its very simple and rather inaccurate but I just did this to simplify my maths assignments on numerical methodologies. It estimates the value of a definite integral with 2 methods. Very simple but my mathematics peers think I'm some kind of wizard because I know basic python :D. Anyway let me know what you think. 

import math
n = math.pow(10,3)		#The number of "slices", increas for higher precision, decrease for faster compute
a = 0					#Inital value of the defined integral 
b = math.pi				#final value of the defined integral
method = 0				#0 for medium-point, 1 for trapezoids

def function(x):
	return math.sin(x)		#write your function in terms of X here, use the "return" command instead of "y="

sumation = 0				
run = 0
dif = (b-a)/n


if method == 0:
	while run < n:
		run += 1
		sumation += dif*function(run*dif)		
		#print ("n:"+str(run) + "\tX=" + str(run*dif) + "\tf(x)=" + str(function(run*dif)) + "\tvalue sum=" + str(sumation))

if method == 1:
	sumation += (dif)*(function(run*dif)/2)
	sumation += (dif)*(function(n*dif)/2)
	run = 1
	while run < n:
		run += 1
		sumation += (dif)*function(run*dif)	
		#print ("n:"+str(run) + "\tX=" + str(run*dif) + "\tf(x)=" + str(function(run*dif)) + "\tvalue sum=" + str(sumation))

print("Value of the definite integral of f(x): " + str(sumation))

Cheers!

Quote or tag if you want me to answer! PM me if you are in a real hurry!

Why do Java developers wear glasses? Because they can't C#!

 

My Machines:

The Gaming Rig:

Spoiler

-Processor: i5 6600k @4.6GHz

-Graphics: GTX1060 6GB G1 Gaming

-RAM: 2x8GB HyperX DDR4 2133MHz

-Motherboard: Asus Z170-A

-Cooler: Corsair H100i

-PSU: EVGA 650W 80+bronze

-AOC 1080p ultrawide

My good old laptop:

Spoiler

Lenovo T430

-Processor: i7 3520M

-4GB DDR3 1600MHz

-Graphics: intel iGPU :(

-Not even 1080p

 

Link to comment
Share on other sites

Link to post
Share on other sites

On 4/22/2017 at 6:11 AM, sgzUk74r3T3BCGmRJ said:

Here's a project I banged out yesterday afternoon as a bit of a joke project when we were discussing the IOCCC and who among the people on our team would be the best at it. I was hoping to get the main runtime preamble (lines 1-4) compact enough to fit in the file name but I'm still about 60 bytes too long.

 

There's a bit of redundancy in the jump calculators and I could use a couple more golf tricks but probably not enough to shed the bytes I need without a new design for the memory layout.

 

Care to guess at its functionality?


#!/usr/bin/env ruby -w -rbase64 -rzlib
i,d,t,z,p=-1,0,[0]*3e4,{?[=>1,?]=>-1},Zlib::Inflate.inflate(Base64.decode64 DATA
.read);{?+=>->{t[d]+=1},?-=>->{t[d]-=1},?<=>->{d-=1},?>=>->{d+=1},?.=>->{
print t[d].chr},?[=>->{(j=1;j+=z[p[i+=1]].to_i while j>0)if t[d]==0},?]=>->{(j=1
j-=z[p[i-=1]].to_i while j>0)if t[d]>0}}[p[i]][]while p[i+=1]
__END__
eJztWgmu4yAMPZDFPwHiIhH3v8Z8Fm9gE5hpO/3TQarUJo53nl+SAoh1hQSQUqo/yleIdeWU8CikEEKi
BXpdF53JcEVcmY6G78P4/Qo5ZZIxpL8FugOxu3exaTC04zdI/uLrbMsXu4ieFkeXnrKjJ26KS86vct2v
zmrvu52upl8VSF3RCGxoWZIkqheVXrqOwiDVe7q3FUp3Vv1X63bzWcZaO4F66S4vgYMAkm++A8VRzkM9
V35BP5W5YbNhxMi+9CbZjRP5qydhxVazomK5vn+OPVSQokWfMUpoKs3cnCURWwHEJT0CEC1RpUC58JB0
3uazeOzJvCylSeyY5VqBIce/UZ3FXiPpsNQQsu0MOPIXBlmSUSG2piUst5njwIXGhdsl4e1oU1i1NChv
GkM0msw3QjaUkTodcsWjaORsDY54JNQ9FJYVEWuBRBX1Sgdjf5QYgU/meulokI328CSQut6nlIZ55Ffu
ZASJzhd7fevqd5sYe2A3zo2KDO84Nfp+EQAn5jlBHMaxhLfb1Bx0zCtq8iGzPL188NAYeKTJVwy7M7Jc
zx/y8IaurmidOYy4KZMn1M4ArHho+zICsD30RcIXgsTlHEWfy/nQzpUzwSJxsqA78xWHuMUU4rBJXdU2
P/ij0c35mMZdNwScEAbESScwLChqopbsfLGFO1wshDNjikjbQjxL/WJhFrlYU2Wxdq0tFfSsIr7xSZC/
3HQuxTPR961ssspmYYyYmipvFNzolx9R2k7zJN+79M8tuHoA+Xs3+nZ6w/8BxO2Vo7q338Om9YffbaYb
2JYJkh66EM4ExKg67Y1GSzyxHPsTl4jz0hXMYr+JtQPNR7N47Uj1tM0NTyRzslcp6kpAx9Mfx+t69q2n
bspX9+QCx6kYwvz8mHjzSe5MORkQdkmnghl1Yb1si2k+gw72DfwMEvvUbbvLtjAg6fzEtNp+zxadsFiW
wzwshjXyDgHxJy8HnkC874NI1K9t/PqCzMru0k2MDOLEx5Li2m64x8njeKTDKP/O6UCvt1jpjICPeTDJ
mryHR7uvw34+1f2Q52H/3239A48Y/7/b+iu0JSxQBd9TYeO5YdT11etMffMlLHsgWWLxz+090VgQbdlQ
W//uAEPEcWBjprfZPxclHlB+x3YGpZBxZ8MtwkxZUFV53TfkRzcwz/8d2tJBSruIUNWiUfTYToYFWKHJ
ZfVkh4ygVfonEyUicA8x/3y+0yft6NRfU6buY2YikMTGXrZCHNYRrG1mOcbbiWubf859WidmB1UIoxbC
pi8S3HkddApGPhrZ/9XDQzNLYGsVk1aQdNI1zj8GbWDadZAInW5uKTbcKYntRVWwMOoIpJS7fcfDtN/9
5JjMqnfSAFXCFFnPHBIdC2kI72Xu/17TzgsJtl8RdDvoNKDlsN1GcVyn0LZdFcK3mzFuO/IuIJdYZl5h
slF77xdaffmi
  Hide contents

First it we implemented a a minimal Brainfuck 'virtual machine' (without the "," instruction because that isn't needed) and then use it to run a compressed BF program that calculates the Mandelbrot fractal mapped to a range that makes it possible to display it on an ASCII terminal:

58fb39044cd1e_ScreenShot2017-04-22at7_05_18AM.thumb.png.6b3a46571ee2b5e6ddd2cfb0602193e9.png

Offered in the spirit of "Real programmers don't use PASCAL". A neat novelty and a fun way to kill half an hour at the end of a week.

My jaw dropped seeing this code. 

 

Are those loops nested inside one another? What is the purpose of having these?

My procrastination is the bane of my existence.

I make games and stuff in my spare time.

 

 

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


×