Jump to content

The under 100 line challenge!

fletch to 99

This was something I didn't think I needed it until I started building computers for my friends. I wanted something easy for me to create junctions on fresh windows installations that had a boot drive (usually an ssd) and a storage drive (usually an hdd). I wanted to do it only for the Documents, Music, Pictures, Videos, and Downloads folders. So I created a batch file to have the user input the drive letter and the program creates the directories in the secondary hard drive and copies all the files from the boot drive to the storage drive. Then it deletes the folders from %UserProfile% and makes a junction to link the storage drive folders to the %UserProfile%.

 

@echo off
color 0a
:start
echo Type the drive letter of the storage drive.
SET /P Drive=
md %Drive%:\%UserName%
md %Drive%:\%UserName%\Documents
md %Drive%:\%UserName%\Music
md %Drive%:\%UserName%\Pictures
md %Drive%:\%UserName%\Videos
md %Drive%:\%UserName%\Downloads

copy %UserProfile%\Documents\*.* %Drive%:\%UserName%\Documents
copy %UserProfile%\Music\*.* %Drive%:\%UserName%\Music
copy %UserProfile%\Pictures\*.* %Drive%:\%UserName%\Pictures
copy %UserProfile%\Videos\*.* %Drive%:\%UserName%\Videos
copy %UserProfile%\Downloads\*.* %Drive%:\%UserName%\Downloads

rmdir /s /q %UserProfile%\Documents
rmdir /s /q %UserProfile%\Music
rmdir /s /q %UserProfile%\Pictures
rmdir /s /q %UserProfile%\Videos
rmdir /s /q %UserProfile%\Downloads

mklink /j "%UserProfile%\Documents" "%Drive%:\%UserName%\Documents"
mklink /j "%UserProfile%\Music" "%Drive%:\%UserName%\Music"
mklink /j "%UserProfile%\Pictures" "%Drive%:\%UserName%\Pictures"
mklink /j "%UserProfile%\Videos" "%Drive%:\%UserName%\Videos"
mklink /j "%UserProfile%\Downloads" "%Drive%:\%UserName%\Downloads


ECHO ALL DONE!

pause

Current Build

Successful Builds

Spoiler
Spoiler

 

Link to comment
Share on other sites

Link to post
Share on other sites

Currently working on an Internet of Things home project to control a 5 channel ledstrip controller connected to a raspberry pi through websockets.

For this I'm using crossbar.io which is a WAMP-router. WAMP (Web Application Messaging Protocol) is an open standard WebSocket subprotocol that provides two messaging patterns on top of raw websocket messaging namely: Remote Procedure Calls and Publish & Subscribe.

 

My goal is to be able to control and/or monitor several aspects of my fishtank over WAN and/or LAN. Like:

  • Setting up lighting schema's which control the brightness of the ledstrips during the day and simulate sunrise and sundown.
  • Controlling of how much carbon dioxide is added (can be done through Ph value)
  • Monitoring temperature and Ph values.
  • Controlling an automated feeding device and pumps for adding fertilisers such as iron for example.   

Currently I have a prototype working and wrote a very basic webpage with some javascript to connect to my crossbar server and calling procedures that my Raspberry Pi, which is also connected to my crossbar server through a node.js script, has registered on the server.

//Requires:
//jquery.min.js
//bootstrap.min.js
//bootstrap-slider.min.js
//autobahn.min.js

var user = "*****";
var key = "*****";

// this callback is fired during WAMP-CRA authentication
function onchallenge(session, method, extra) {
    console.log("onchallenge", method, extra);
    if (method === "wampcra") {
        console.log("authenticating via '" + method + "' and challenge '" + extra.challenge + "'");
        return autobahn.auth_cra.sign(key, extra.challenge);
    } else {
        throw "don't know how to authenticate using '" + method + "'";
    }
}

var connection = new autobahn.Connection({
    url: 'ws://hoogstraaten.eu/ws',
    realm: 'fishtank',
    // the following attributes must be set for WAMP-CRA authentication
    authmethods: ["wampcra"],
    authid: user,
    onchallenge: onchallenge
});

connection.onopen = function(session, details) {
    var RGBChange = function() {
        $('#RGB').css('background', 'rgb('+r.getValue()+','+g.getValue()+','+b.getValue()+')');

        var red = Math.round((r.getValue() / 255) * 100);
        var green = Math.round((g.getValue() / 255) * 100);
        var blue = Math.round((b.getValue() / 255) * 100);

        session.call('com.fishtank.ledcontrol.setcolors', [red, green, blue, 0, 0]);
    };

    var r = $('#R').slider().on('slide', RGBChange).data('slider');
    var g = $('#G').slider().on('slide', RGBChange).data('slider');
    var b = $('#B').slider().on('slide', RGBChange).data('slider');

    $("#cycle").on('click', function () {
        session.call('com.fishtank.ledcontrol.cyclecolors', [30]); //30ms passed as argument for setInterval() on Raspberry Pi
        console.log('Cycling RGB Colors');
    });

    $("#blink").on('click', function () {
        session.call('com.fishtank.ledcontrol.blinkleds', [500]); //500ms passed as argument for setInterval() on Raspberry Pi
        console.log('Blink LEDs');
    });
};

connection.onclose = function (reason, details) {
    console.log("disconnected", reason, details.reason, details);
};

connection.open();

 

CPU: i7-12700KF Grill Plate Edition // MOBO: Asus Z690-PLUS WIFI D4 // RAM: 16GB G.Skill Trident Z 3200MHz CL14 

GPU: MSI GTX 1080 FE // PSU: Corsair RM750i // CASE: Thermaltake Core X71 // BOOT: Samsung Evo 960 500GB

STORAGE: WD PC SN530 512GB + Samsung Evo 860 500GB // COOLING: Full custom loop // DISPLAY: LG 34UC89G-B

Link to comment
Share on other sites

Link to post
Share on other sites


;-----------------------------------------------------------
; Script Name: Jabbers Static Magery trainer.
; Author: Jabber
; Version: 2.2
; Client Tested with: 7.0.58.12
; EUO version tested with: 1.5 (Updated on: 2017-04-28)
; Shard OSI / Only tested on RUNUO DEMISE server
; Revision Date: 11th July 2017
; Public Release: 11th July 2017
; Purpose: Trains Magery to GM. Stanging still. Without damaging LRC suit.
;          Has a secondary effect of raising: Meditation/Focus/Eval Int/Magic Resist
;-------------------------------------------------------------
set %shutdown #FALSE ; #TRUE:  Computer will shutdown when %skillcap reached.
                     ; #FALSE: Script will halt. Computer will not shutdown.

set %skillcap 760 ; Script will halt, or shutdown when this skill level is reached
                   ; 1000 = Magery 100.0 , 1100 = Magery 110.0 , 1200 = Magery 120.0

set %system_messages #TRUE ; set to #TRUE to see Wait times adapting.
; ------------------------Dont edit below unless you know what you're doing---------
set %curse 480
set %reflect_magic 620
set %invisability 760
set %mana_vampire 900
set %earthquake 1200
set %jaw 10 ; start duration for wait
set %jaw_speedup 30 ; number of spells to cast before speeding up wait
set %jaw_counter 0  ; counter used for %jaw_speedup
;-----------------------------------------------------------------------------------
set %jrnl #jindex
while #TRUE ; main program loop
      {
      gosub check_skill ; is it time to halt, or shutdown?
      gosub jabbers_adaptive_wait ; wait time that tunes itself
      if %magery_skill <= %curse
         gosub cast_spell 11 26 1 ; mana needed, curse, 1=target self
      if %magery_skill > %curse && %magery_skill <= %reflect_magic
         gosub cast_spell 14 35 0 ; mana needed, reflect_magic
      if %magery_skill > %reflect_magic && %magery_skill <= %invisability
         gosub cast_spell 20 43 1 ; mana needed, invisability, 1=target self
      if %magery_skill > %invisability && %magery_skill <= %mana_vampire
         gosub cast_spell 40 52 1 ; mana needed, mana_vampire, 1=target self
      if %magery_skill > %mana_vampire && %magery_skill <= %earthquake
         gosub cast_spell 50 56 0 ; mana needed, earthquake
      } ; end of main program loop
sub cast_spell ; -------------------------------------------------------------------
    set %mana_needed %1
    set %spell_to_cast %2
    set %target_self %3
    gosub mana_check
    event macro 15 %spell_to_cast
    if %target_self = 1
       {
       target 5s
       set #ltargetkind 1
       event macro 23
       }
    return
sub jabbers_adaptive_wait ; --------------------------------------------------------
    wait %jaw
    ; this section slows down cast time if "recovered" or "already" found in journal
    while #jindex > %jrnl
          {
          scanjournal %jrnl
          if recovered in #journal || already in #journal
             {
             set %jaw %jaw + 2
             if %system_messages #TRUE
                event sysmessage JAW increased to %jaw
             }
          set %jrnl %jrnl + 1
          }
    ; this section uses a counter to occasionally speed up cast times
    set %jaw_counter %jaw_counter + 1
    if %jaw_counter = %jaw_speedup
       {
       set %jaw_counter 0
       set %jaw %jaw - 1
       if %system_messages #TRUE
          event sysmessage JAW decreased to %jaw
       }
    set %jrnl #jindex
    return
sub mana_check ; -------------------------------------------------------------------
    if #mana > %mana_needed ; Enough mana to cast spell?
       return
    wait 4s
    event macro 13 46 ; use skill meditate
    while #mana < #maxmana
          wait 1
    return
sub check_skill ; ------------------------------------------------------------------
    chooseskill mage
    set %magery_skill #skill
    if %magery_skill < %skillcap
       return
    if %shutdown #FALSE
       halt
    shutdown
    return

 

'Bot' to raise your magery skill in the old game 'Ultima Online', using the script language Easyuo.

Link to comment
Share on other sites

Link to post
Share on other sites

Spoiler

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]){

	printf("\n&&&&&&&&&&&&&&&&&&&&&&&&\n");
	printf("&                      &\n");
	printf("&      Welcome to:     &\n");
	printf("&      ===========     &\n");
	printf("&      &AMPERSAND&     &\n");
	printf("&                      &\n");
	printf("&&&&&&&&&&&&&&&&&&&&&&&&\n\n");

	int helpMenuLvl = 0;

	if(argc != 2){
		printf("= Usage ::: ./ampersand <argument>\n");
		return 2;
	} else if(strcmp(argv[1], "ampersand") != 0){
		printf("= Try ampersand\n");
		return 2;
	} else if(strcmp(argv[0], "./ampersand") != 0){
		printf("= Name me 'ampersand'!\n");
	} else {
		while(1 == 1){
			char command[] = "placeholder";
			printf("& ");
			scanf("%s", &command);
			if(strcmp(command, "help") == 0){
				if(helpMenuLvl == 0){
					printf("\n= help      :::           Show this message\n");
					printf("= ampersand :::           Display stuff\n");
					printf("= exit      :::           Exit Ampersand\n");
					printf("= password  :::           Submit a password\n\n");
				} else if(helpMenuLvl == 1){
					printf("\n= help      :::           Show this message\n");
					printf("= ampersand :::           Display stuff\n");
					printf("= exit      :::           Exit Ampersand\n");
					printf("= message   :::           Read a mysterious message\n");
					printf("= password  :::           Submit passphrase\n\n");
				} else {
					printf("\n= help      :::           Show this message\n");
					printf("= ampersand :::           Display stuff\n");
				 	printf("= exit      :::           Exit Ampersand\n");
					printf("= message   :::           Read a mysterious message\n");
					printf("= message2  :::           Read another mysterious message\n");
					printf("= password  :::           Submit a password\n\n");
				}
			} else if(strcmp(command,"ampersand") == 0){
				printf("\n= PleASe Say the magic WORD. IT IS IMPERATIVE!\n\n");
			} else if(strcmp(command, "password") == 0){
				char PASSWORD[] = "IMPERATIVE";
				char password[] = "placeholder";
				printf("\n= Enter your password: ");
				scanf("%s", &password);
				printf("\n");
				if(strcmp(PASSWORD, password) == 0){
					helpMenuLvl += 1;
				} else if(strcmp("passphrase", password) == 0){
					helpMenuLvl += 1;
				}
			} else if(strcmp(command, "exit") == 0){
				printf("\nHehe...\n\n");
				break;
			} else if(strcmp(command, "message") == 0){
				printf("\n= Hello there... I just made it in here with a heap buffer over flow exploit I found before they patched it... not sure how much longer it'll be till their automation finds this connection. Don't have enough time for a backdoor. I'm trying to get you out of here; but I can only really you instructions. I think they reused some of their code, too lazy to come up with other ways of stopping you from getting out of here. If it weren't for the other workers, they wouldn't even need to put in ways to escalate... The password program you used to find this probably has an alternative password. It's probably around there somewhere, see if anything has changed---No! I see a cron job starting up, I may not last on here much longer--.......\n\n");
			} else if(strcmp(command, "message2") == 0){
				printf("\n= Exploit-db is going to fail me, we need to get you out of here fast! Run this command to connect back to me, see you there!: ncat_127.0.0.1:443\n\n");
			} else if(strcmp(command, "ncat_127.0.0.1:443") == 0){
				printf("\n= I can't believe that worked! hahaha! How did I do it? I've seen hacking movies, duh! That's how everyone learns to social engineer right? I'm in your company now, I've got your databases, your workstations, everything! Good luck getting rid of me!\n");
				printf("\nSYSTEM MESSAGE ::: I'm sorry Sir/Ma'am; but as the kernel of this computer I can't help but notice that you seem to have a problem of being hacked... May I suggest something? There's a command that I think will recover everything for you and remove this script kiddie from your computers: sudo_rm_-rf_/\nSYSTEM MESSAGE :::: No, I'm not kidding, it always works! I've seen it done a thousand times! Try it out!\n\n");
			} else if(strcmp(command, "sudo_rm_-rf_/") == 0){
				printf("\nSYSTEM MESSAGE ::: LOL I love being a troll kernel, I'm sorry. Here, I'll remove him for you, thanks for amusing me! It gets so boring down here with all the mov's xor's and lea's...\n= Running AV scan...\n= Removing the bad stuff...\n= Deleting script kiddie...\n= Done.\nSYSTEM MESSAGE ::: Catch you later buddy! Try 123456 to get out!\n\n");
			} else if(strcmp(command, "123456") == 0){
				printf("\n= Root access granted, have a nice day.\n");
				break;
			} else if(strcmp(command, "") == 0){
				printf("\n= Try 'help'\n\n");
			} else {
				printf("\n= Try 'help'\n\n");
			}
		}
	}

	return 0;

}

 

Source code above and attached. It is just a goofy little game I made in a couple hours for the fun of it while staying up late... So it's probably best to get the source code attachment and compile that so as to avoid spoiling it by seeing the source code. It's not designed to be anti-reverse engineering or intended for the player to see the source code.

ampersand.c

Join the Appleitionist cause! See spoiler below for answers to common questions that shouldn't be common!

Spoiler

Q: Do I have a virus?!
A: If you didn't click a sketchy email, haven't left your computer physically open to attack, haven't downloaded anything sketchy/free, know that your software hasn't been exploited in a new hack, then the answer is: probably not.

 

Q: What email/VPN should I use?
A: Proton mail and VPN are the best for email and VPNs respectively. (They're free in a good way)

 

Q: How can I stay anonymous on the (deep/dark) webzz???....

A: By learning how to de-anonymize everyone else; if you can do that, then you know what to do for yourself.

 

Q: What Linux distro is best for x y z?

A: Lubuntu for things with little processing power, Ubuntu for normal PCs, and if you need to do anything else then it's best if you do the research yourself.

 

Q: Why is my Linux giving me x y z error?

A: Have you not googled it? Are you sure StackOverflow doesn't have an answer? Does the error tell you what's wrong? If the answer is no to all of those, message me.

 

Link to comment
Share on other sites

Link to post
Share on other sites

#script made by notverynerdykid. Originally built for SL4A. It was supposed to vibrate the a phone three times every 90 seconds. Now it makes noise.
#Also,this script can be modfied to fit any use as a displaying timer. Do whatever you want with it (Except for setting off bombs, of course.)
import time

def timerstart():
    sec = 0
    while True:
        if sec == 0:
            #insert function here
            print("\a")
            #end function
            sec = 90 #sets time
            print("\n" * 100, sec, "sec")
        else:
            while True:
                time.sleep(1)
                sec -= 1
                print(sec, "sec")
                if sec == 0:
                    break

try:
    timerstart()
except(KeyboardInterrupt):
    print("timer stopped")
    pass

Little Python Timer.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Decided to go a little overboard here for my first post on the LTT forums, so here's a fully functional Login AND Register script in PHP, complete with input validation and exit codes + messages, all in only 88 lines of code!

<?php
if (isset($_POST['login']) && $_POST['login']) {
	if (!isset['username'] && !isset['email']) {
		echo 'No username or email provided!';
		exit(1);
	}
	if (!isset['passwd']) {
		echo 'No password provided!';
		exit(1);
	}
	if (!($con = new mysqli('localhost', 'mysql_user', 'mysql_pass', 'users'))) {
		echo 'Could not connect to database!';
		exit(2);
	}
	$qry = $con->prepare('SELECT * FROM accounts WHERE ' . ((isset($_POST['username'])) ? 'user' : 'email') . ' = ?';
	if (!$qry->bind_param('s', ((isset($_POST['username'])) ? $_POST['username'] : $_POST['email']))) {
		echo 'Could not query database!';
		exit(2);
	}
	if (!$qry->execute()) {
		echo 'Could not query database!';
		exit(2);
	}
	$qry->bind_result($account);
	if (($res = $qry->fetch()) === null) {
		echo 'User does not exist!';
		exit(3);
	}
	if (!$res) {
		echo 'Could not query database!';
		exit(2);
	}
	if (hash("sha256", $_POST['passwd'] . $account['salt']) != $account['passwd']) {
		echo 'Incorrect password!';
		exit(3);
	}
	$qry = $con->prepare('UPDATE accounts SET last_login = NOW() WHERE ' . ((isset($_POST['username'])) ? 'user' : 'email') . ' = ?')
	if (!$qry->bind_param('s', ((isset($_POST['username'])) ? $_POST['username'] : $_POST['email']))) {
		echo 'Could not update database!';
		exit(2);
	}
	if (!$qry->execute()) {
		echo 'Could not query database!';
		exit(2);
	}
	if (!$qry->affected_rows()) {
		echo 'Could not query database!';
		exit(2);
	}
	session_start();
	$_SESSION['uuid'] = $account['uuid'];
	$_SESSION['name'] = $account['user'];
	echo 'Logged in successfully!';
	exit(0);
} else {
	if (!isset($_POST['username']) || !isset($_POST['email'])) {
		echo 'No username or email provided!';
		exit(1);
	}
	if (!isset($_POST['passwd'])) {
		echo 'No password provided!';
		exit(1);
	}
	if (!($con = new mysqli('localhost', 'mysql_user', 'mysql_pass', 'users'))) {
		echo 'Could not connect to database!';
		exit(2);
	}
	$saltStr = '';
	$len = random_int(16, 32);
	for($i = 0; $i < $len; $i++) $saltStr .= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'[random_int(0, 63)];
	$saltStr = hash("sha256", $saltStr);
	$passwd = hash("sha256", ($_POST['passwd'] . $saltStr));
	$qry = $con->prepare("INSERT INTO accounts (user, email, passwd, salt) VALUES (?, ?, ?, ?)");
	if (!$qry->bind_param('ssss', $_POST['username'], $_POST['email'], $passwd, $saltStr)) {
		echo 'Could not query database!';
		exit(2);
	}
	if (!$qry->execute()) {
		echo 'Could not query database!';
		exit(2);
	}
	if (!$qry->affected_rows()) {
		echo 'Could not query database!';
		exit(2);
	}
	echo 'Account created successfully!';
	exit(0);
}

 
Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

A password-manager, cause I had some trouble with gpg2 (used by most password managers). Could be optimized and be even smaller, but temporary fix till I switch to Arch, instead of my messed-up UbuntuServer setup.

#! /bin/bash

id=$( cat ~/.pass/.id )

if [ "$1" = "add" ]; then
    read -s -p "Password:" pass
    [ ! -z $2 ] && $(cd ~/.pass/store; mkdir -p `dirname $2`; touch $2)
    rm ~/.pass/store/$2
    echo $2 >> ~/.pass/.index
    exec echo $pass | gpg -e -r $id --output ~/.pass/store/$2.gpg
    echo ""
    echo "Password for $2 added to store"
    echo "Password: $pass"
    exit
fi

if [ "$1" = "gen" ]; then
    [ ! -z $2 ] && $(cd ~/.pass/store; mkdir -p `dirname $2`; touch $2)
    rm ~/.pass/store/$2
    pass=$(exec pwgen -ys 16 1)
    exec echo $pass | gpg -e -r $id --output ~/.pass/store/$2.gpg
    echo $2 >> ~/.pass/.index
    echo "Password for $2 added to store"
    echo "Password: $pass"
    exit
fi

if [ "$1" = "copy" ]; then
    pass=$(exec gpg -q -d ~/.pass/store/$2.gpg)
    exec echo $pass | xclip -sel c
    echo "You have 30 seconds to paste"
    sleep 30
    exec echo "You are too late!" | xclip -sel c
    exit
fi

if [ "$1" = "rm" ]; then
    read -p "Are you sure you want to delete store/$2 ? (yes/no) [no]:" del
    if [ "$del" = "yes" ]; then
        rm ~/.pass/store/$2.gpg
        exec grep -v $2 ~/.pass/.index > ~/.pass/.tmp
        exec cat ~/.pass/.tmp > ~/.pass/.index &
        rm  ~/.pass/.tmp
        echo "key deleted"
    else
        echo "key not deleted"
        exit
    fi
    exit
fi

if [ -z $1 ]; then
    exec tree ~/.pass/store/
    exit
fi

if [ -f ~/.pass/store/$1.gpg ]; then
    exec gpg -q -d ~/.pass/store/$1.gpg
    exit
fi

exec tree ~/.pass/store/$1
exit

# vim:ft=sh

 

Be safe, don't drink and sudo

 

Laptop: ASUS K541UA (i5-6198DU, 8GB RAM, 250GB 850 EVO) OS: Debian Buster (KDE)

Desktop: i7-7700, ASUS Strix H270F, 16GB RAM, 128GB SSD from laptop, some HDD's, iGPU, some NIC's, OS: Debian Buster (KDE)

 

Link to comment
Share on other sites

Link to post
Share on other sites

You wanted a useful program for the masses. Do not fear, corporate America is here to bring you the extremely low budget and poorly optimized Turbulent's Time Waster for only $99.99. Or you could just get it off of GitHub from the programmer they stole most of the code from but who am I kidding no one's gonna do that. It's version 1 of 1 because it's issues will never be fixed as the game will be abandoned after a few weeks when Turbulent's Time Waster 2 comes out and blows the consumers mind with 10% less bugs. WOW! Of course the older version will not be fixed because the bugs are need to drive the consumer to the next product in hope of less bugs and EXTRA LIFE WASTING CAPIBILITIES! Again, who am I kidding, it will be a reskin with minor tweaks done by some intern. Heck, I don't even know if it works but people will by it anyway, because not working is a step up over how much fun you would have if it actually did something. In either case you'll waste so much time trying to get it to work right that you will have been playing Turbulent's Time Waster even before you started it up. From the unmotivated interns here at some Chinese knockoff toy company I hope you waste just as much time as we did creating this; about 5 minutes give or take.

 

https://github.com/TurbulentWinds/TurbulentsTimeWaster

ORANGE SCREEN WINDOWS 10 VALUE OVER TIME - PC VS MAC

Spoiler

i5 7600k @ 5.0 GHz xD

Corsair H60 with Noctua NF-F12 iPPC-3000 PWM

MSI Z270-A Pro Motherboard

EVGA 1050 Ti SC

16 GB Corsair DDR4 @ 2400 MHz

500 GB Sandisk 950 PRO - Windows 10, Elementary OS, Zorin OS

500 GB Sandisk 850 PRO

1 TB WD Blue

Corsair CX750

1 x Corsair AF120 Quiet Red Led

Rosewell Tyrfing Case

Spoiler

EliteBook 8570w
i7 3720QM @ 2.6 GHz
Quadro K1000M
24 GB DDR3 @ 1600 MHz
250 GB SanDisk 850 EVO - Elementary OS, Windows 10, Debian

Spoiler

i5 3470 @ 3.2 GHz
EVGA 750 Ti SC
8 GB DDR3 @ 1333 MHz
240 GB SanDisk - Windows 10, Linux Mint

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

OH! OH! I wrote a python script to retrieve all XKCD comics from the website! It's hosted on GitHub.

 

EBEvans xkcd pool pull

 

It pulls a pool of xkcd comics, as I like to say.

It's written with Python 3, and it's not, like, compiled or anything (do you compile python?). But, yeah. I like it. I'm proud of it.

 

One thing I've noticed is that It'll always have comic #404 in the failed comics list, because FKIN Randall thinks he's sooo funny (he is)!

Link to comment
Share on other sites

Link to post
Share on other sites

On 9/19/2017 at 12:11 AM, EthanBE said:

OH! OH! I wrote a python script to retrieve all XKCD comics from the website! It's hosted on GitHub.

 

EBEvans xkcd pool pull

 

It pulls a pool of xkcd comics, as I like to say.

It's written with Python 3, and it's not, like, compiled or anything (do you compile python?). But, yeah. I like it. I'm proud of it.

 

One thing I've noticed is that It'll always have comic #404 in the failed comics list, because FKIN Randall thinks he's sooo funny (he is)!

Neat, I wrote a similar program years ago that pulled manga from scanlation sites. I might have to revisit that idea.

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

If you remove the whitespaces, my Python script is sub-100 lines. It finds backup files on a given website...

 

Spoiler

import requests
import time
from progressbar import ProgressBar

things = ['conf', 'bak', 'swp', 'txt', 'old', 'tar', 'tar.gz', 'tar.bz2', 'zip', 'inc',
        'asa', 'tgz', 'gz', 'rar', 'java', 'py', 'js', 'pdf', 'doc', 'docx', 'rtf',
        'pl', 'o', 'obj', 'jar', 'inf', 'exe', 'c', 'bat', 'asm', 'awk', 's', 'sh',
        'src', 'log', 'lock', 'jsp', 'aspx', 'dev', 'orig', 'copy', 'tmp', '~', 'backup',
        'copyof', 'copy of', 'snapshot']

print
print "============="
print "[i] Beginning..."
print "============="

http = raw_input("[>] Enter the HTTP host >>> ")
link = raw_input("[>] Enter the directory >>> ")
file = raw_input("[>] Enter the file      >>> ")
fiex = raw_input("[>] Enter the extension >>> ")
things.append(fiex)

session = requests.head(http)
if session.status_code == 200:
    print "[i] Connection is working."
else:
    print "[!] Connection does not work!"
    print "============="
    exit(1)

urls = []
codes = []
direct = []

def store(request, code, directlink):
    urls.append(request)
    codes.append(code)
    direct.append(directlink)

def checkreq(request):
    if request in direct:
        return False
    else:
        return True

print "============="
print "=== Appending ==="
pbar = ProgressBar()
for ext in pbar(things):
    req = http + link + file + "." + fiex + "." + ext
    if checkreq(req):
        connection = requests.head(req)
        store(req, connection.status_code, req)
        time.sleep(0.05)
    else:
        continue

print "=== Replacing ==="
pbar = ProgressBar()
for repl in pbar(things):
    req = http + link + file + "." + repl
    if checkreq(req):
        connection = requests.head(req)
        store(req, connection.status_code, req)
        time.sleep(0.05)
    else:
        continue

print "=== Prepending ==="
pbar = ProgressBar()
for pre in pbar(things):
    req = http + link + pre + file + "." + fiex
    if checkreq(req):
        connection = requests.head(req)
        store(req, connection.status_code, req)
        time.sleep(0.05)
    else:
        continue

print "=== Mixing ==="
pbar = ProgressBar()
for exten in pbar(range(0, len(things))):
    for main in things:
        req = http + link + main + file + fiex + "." + things[exten]
        if checkreq(req):
            connection = requests.head(req)
            store(req, connection.status_code, req)
            time.sleep(0.05)
        else:
            continue

c200s = 0
for search in range(0, len(codes)):
    if codes[search] != 404:
        c200s += 1
        print "============="
        print "[" + str(c200s) + "] URL ::: " + urls[search].replace("\n", "").replace("\r", "")
        print "|__ COD ::: " + str(codes[search])

print "============="
print "[i] " + str(c200s) + " URLs found."
print "[i] " + str(len(codes)) + " URLs attempted."
print "============="
print "[*] Done."
print "============="
print
exit(0)

 

 

https://pastebin.com/hFMTzRVC

 

https://www.reddit.com/r/LiveOverflow/comments/71szt1/python_backup_file_bruteforcer/

 

https://github.com/larkwiot/backupfinder

Join the Appleitionist cause! See spoiler below for answers to common questions that shouldn't be common!

Spoiler

Q: Do I have a virus?!
A: If you didn't click a sketchy email, haven't left your computer physically open to attack, haven't downloaded anything sketchy/free, know that your software hasn't been exploited in a new hack, then the answer is: probably not.

 

Q: What email/VPN should I use?
A: Proton mail and VPN are the best for email and VPNs respectively. (They're free in a good way)

 

Q: How can I stay anonymous on the (deep/dark) webzz???....

A: By learning how to de-anonymize everyone else; if you can do that, then you know what to do for yourself.

 

Q: What Linux distro is best for x y z?

A: Lubuntu for things with little processing power, Ubuntu for normal PCs, and if you need to do anything else then it's best if you do the research yourself.

 

Q: Why is my Linux giving me x y z error?

A: Have you not googled it? Are you sure StackOverflow doesn't have an answer? Does the error tell you what's wrong? If the answer is no to all of those, message me.

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

For batch files, add this to the very beginning (right after @ECHO OFF)

cd "%~dp0"

This command sets the current working directory to whatever directory that batch file is currently stored in.

 

For normal batch files this does pretty much nothing, but it's very useful if you're running batch files with scheduled tasks.  One of the irritating things about scheduled tasks is the optional "Start In" option, where you can specify what the working directory is that the batch file starts in.  For the vast majority of cases, you're going to want the starting directory to be whatever directory the batch file is stored in.  This is especially irritating since it in no way defaults to the batch file's directory.  It is a genuine problem in cases where you create the scheduled task via the command line with "schtasks" which in no way, shape, or form, gives you the option to set the "Start In" directory.

 

The %0 refers to the very first argument to the batch file, which is always the full path name of the batch file.  %d refers to the drive name, while %p refers to the full path without the filename or drive name.  

 

String it together and you get the full pathname of the batch file's folder.  We then pass that to the cd command, to ensure that we are currently running in a known folder.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 1 month later...

I was just digging around in some old folders, when I came over a file I had lying around from a functional programming course. Thought the function was a little cool.

QuickSort (kind of) over 2 lines, in Haskell: 

qs [] = []
qs (x:xs) = qs [y|y<-xs,y<=x] ++[x]++ qs [y|y<-xs,y>x]

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

My little Decimal to Binary coded in Java (I just started learning Java and I'm in the first year of Computer Science).

 

[code]
package decimaltobinary;

import java.util.Scanner;
/**
 *
 * @author juanp
 */
public class DecimalToBinary {
 
    public static void main(String[] args) {
       
        System.out.println("Please, write a number and then press Enter.\n");
           
            Scanner input = new Scanner(System.in);
            int number = input.nextInt();
            int result;
            int remainder[];
            remainder = new int[16];
            remainder[0] = number % 2;
            result = number / 2;
 
            if(number <= 255) {
                for(int i = 1; i < 8; i++) {
                    remainder[i] = result % 2;
                    result = result / 2;
                }
                System.out.println("You chose the number: "+number);
                System.out.println("Which in binary is: " +remainder[7] +remainder[6] +remainder[5] +remainder[4] +remainder[3] +remainder[2] +remainder[1] +remainder[0]);
 
            }
 
            else if(number >= 256) {
                System.out.println("ERROR: The max number possible in this type is 256.");
            }
        }
}
[/code]
Link to comment
Share on other sites

Link to post
Share on other sites

4 hours ago, penia said:

+remainder[7] +remainder[6] +remainder[5] +remainder[4] +remainder[3] +remainder[2] +remainder[1] +remainder[0])

you could put this in another for loop:

for (count = remainder.length; count < 0; count--) {
  System.out.println(remainder[count])
}

(don't know how to get the length of an array, but I hope you get it)

 "Aeneas troianus est."

I'm allergic to social interaction in real life, don't talk to me in real life please.

don't forget to quote or tag (@marten.aap2.0) me when you reply!

Link to comment
Share on other sites

Link to post
Share on other sites

  • 5 weeks later...

Is arduino code allowed? I have some code lying around.

Your resident osu! player, destroyer of keyboards.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
  • 1 month later...
class Fibonacci
    {
        public int a = 1;
        public int b = 1;
        public int c = 0;

        public IEnumerator<int> GetEnumerator()
        {
            while (true)
            {
                this.c = this.a + this.b;
                this.a = this.b;
                this.b = this.c;

                yield return this.a;
            }
        }

A Fibonacci iterator in C#. Should probably be modified to allow for only producing fibonacci numbers up to n, or only producing n fibonacci numbers.

EDIT:: Here's the updated version (Please note some backing fields can be removed):
 

    public class Fibonacci
    {
        // Backing fields
        private ulong _a;
        private ulong _b;
        private bool _mode; // True for up to n, false for maximum of n
        private ulong _num;
        private ulong _count;

        // Properties
        public bool Mode { get { return _mode; } set { _mode = value; } }
        public ulong A { get { return _a; } set { _a = value; } }
        public ulong B { get { return _b; } set { _b = value; } }
        public ulong Number { get { return _num; } set { _num = value; } }
        public ulong Count { get { return _count; } }

        // Constructors
        public Fibonacci()
        {
            _a = 0;
            _b = 1;
            _mode = true;
            _num = ulong.MaxValue;
        }

        public Fibonacci(ulong a, ulong b, ulong num, bool mode)
        {
            _a = a;
            _b = b;
            _mode = mode;
            _num = num;
        }

        public Fibonacci(ulong num)
        {
            _a = 0;
            _b = 1;
            _mode = true;
            _num = num;
        }

        // Iterators
        public IEnumerator<ulong> GetEnumerator()
        {
            if (_mode)
                return UpTo();

            else
                return LessThan();
        }

        // Methods
        public IEnumerator<ulong> UpTo()
        {
            ulong c = 0;
            _count = 2;

            while ((_a < _num) && (_b < _num))
            {
                c = _a + _b;
                _a = _b;
                _b = c;

                yield return _a;
                _count++;
            }

        }

        public IEnumerator<ulong> LessThan()
        {
            ulong c = 0;
            _count = 2;

            while (_count < _num)
            {
                c = _a + _b;
                _a = _b;
                _b = c;

                yield return _a;
                _count++;
            }
        }
    }


Fits in 93 lines.

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

Using AHK, simple script that let you alternate between the last 2 windows (visible) using the key [ESC] (as alt tab but faster since it require only 1 key)

Esc::
hwnd := WinActive("A")
Loop
{
	hwnd := DllCall("GetWindow",uint,hwnd,int,2) ; 2 = GW_HWNDNEXT
	SetFormat,integer,hex
	hwnd += 0
	SetFormat,integer,d
	if (DllCall("IsWindowVisible",uint,hwnd) = 1)
		break
}
WinActivate,ahk_id %hwnd%
return

 


 

Link to comment
Share on other sites

Link to post
Share on other sites

This is the final form of my first ever Windows exe 

 

 

^!NumpadEnter::
  Run CMD
  Winactivate, C:\Windows\System32\CMD.exe
  WinWaitActive, C:\Windows\System32\CMD.exe
  Sendinput shutdown /r /fw /t 0 {enter}
 Return

^!NumpadSub::
  Run CMD
  Winactivate, C:\Windows\System32\CMD.exe
  WinWaitActive, C:\Windows\System32\CMD.exe
  Sendinput bcdedit /set {current} safeboot minimal {enter}
  Sendinput shutdown /r /t 0 {enter}
 Return

^!NumpadAdd::
  Run CMD
  Winactivate, C:\Windows\System32\CMD.exe
  WinWaitActive, C:\Windows\System32\CMD.exe
  Sendinput bcdedit /deletevalue safeboot {enter}
  Sendinput shutdown /r /t 0 {enter}
 Return

^+`::
  Run c:\\windows\system32\control.exe
 Return

^SPACE::  
  Winset, Alwaysontop, , A
 Return

I run it with Task Scheduler from the System32 folder 

 With all the Trolls, Try Hards, Noobs and Weirdos around here you'd think i'd find SOMEWHERE to fit in!

Link to comment
Share on other sites

Link to post
Share on other sites

Probably pointless, but could useful depending on the individual who is interested in IL programming and this snippet is about 140 lines of code. I created it on a whim.

 

The purpose of this snippet is basically to emit Brainf*ck programming language into IL during runtime in C#:

 

using System;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.IO;

namespace BFJIT
{
    public unsafe class BFJIT
    {
        public static void ZeroOutMemory(byte* ptr, int size)
        {
            for (int I = 0; I < size; I++)
                ptr[I] = 0;
        }
        public delegate IntPtr BrainFkCompile();
        public BrainFkCompile Compile(string code)
        {
            var WhileBeginMarkStack = new Stack<Label>();
            var WhileEndMarkStack = new Stack<Label>();
            var reader = new StringReader(code);

            var method = new DynamicMethod($"BrainFk{Guid.NewGuid().ToString().Replace("-", "_")}", typeof(IntPtr), null);
            var il = method.GetILGenerator();
            // Set the locals
            il.DeclareLocal(typeof(byte*));
            il.DeclareLocal(typeof(IntPtr));
            // Allocate pointer
            il.Emit(OpCodes.Ldc_I4, 1048576); // 1 MB Memory
            il.EmitCall(OpCodes.Call, typeof(Marshal).GetMethod("AllocHGlobal", new Type[] { typeof(int) }), null);
            il.Emit(OpCodes.Stloc_1);
            il.Emit(OpCodes.Ldloca_S, 1);
            il.EmitCall(OpCodes.Call, typeof(IntPtr).GetMethod("ToPointer"), null);
            il.Emit(OpCodes.Stloc_0);
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ldc_I4, 1048576); // 1 MB Memory
            il.EmitCall(OpCodes.Call, typeof(BFJIT).GetMethod("ZeroOutMemory"), null);
            int currentCharacter = -1;
            do
            {
                currentCharacter = reader.Read();
                switch ((char)currentCharacter)
                {
                    case '>':
                        {
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Ldc_I4_1);
                            il.Emit(OpCodes.Add);
                            il.Emit(OpCodes.Stloc_0);
                            break;
                        }
                    case '<':
                        {
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Ldc_I4_1);
                            il.Emit(OpCodes.Sub);
                            il.Emit(OpCodes.Stloc_0);
                            break;
                        }
                    case '+':
                        {
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Dup);
                            il.Emit(OpCodes.Ldind_U1);
                            int increment = 1;
                            while (reader.Peek() == '+')
                            {
                                ++increment;
                                reader.Read();
                            }
                            il.Emit(OpCodes.Ldc_I4, increment);
                            il.Emit(OpCodes.Add);
                            il.Emit(OpCodes.Conv_U1);
                            il.Emit(OpCodes.Stind_I1);
                            break;
                        }
                    case '-':
                        {
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Dup);
                            il.Emit(OpCodes.Ldind_U1);
                            int decrement = 1;
                            while (reader.Peek() == '-')
                            {
                                ++decrement;
                                reader.Read();
                            }
                            il.Emit(OpCodes.Ldc_I4, decrement);
                            il.Emit(OpCodes.Sub);
                            il.Emit(OpCodes.Conv_U1);
                            il.Emit(OpCodes.Stind_I1);
                            break;
                        }
                    case '.':
                        {
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Ldind_U1);
                            il.EmitCall(OpCodes.Call, typeof(Console).GetMethod("Write", new[] { typeof(byte) }), null);
                            break;
                        }
                    case '[':
                        {
                            Label begin = il.DefineLabel();
                            Label end = il.DefineLabel();
                            il.Emit(OpCodes.Br, end);
                            il.MarkLabel(begin);
                            WhileBeginMarkStack.Push(begin);
                            WhileEndMarkStack.Push(end);
                            break;
                        }
                    case ']':
                        {
                            il.MarkLabel(WhileEndMarkStack.Pop());
                            il.Emit(OpCodes.Ldloc_0);
                            il.Emit(OpCodes.Ldind_U1);
                            il.Emit(OpCodes.Brtrue, WhileBeginMarkStack.Pop());
                            break;
                        }
                    default:
                        continue;
                }
            } while (currentCharacter > -1);
            il.Emit(OpCodes.Ldloc_1);
            il.Emit(OpCodes.Ret);
            return (BrainFkCompile)method.CreateDelegate(typeof(BrainFkCompile));
        }

        static unsafe void Main(string[] args)
        {
            var jitter = new BFJIT();
            var func = jitter.Compile("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.");
            Console.WriteLine("Brainfk Compiled");
            var ptr = func();
            Console.WriteLine();
            Console.WriteLine("Program Terminated.");
            Marshal.FreeHGlobal(ptr);
            Console.ReadLine();
        }
    }
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

45 minutes ago, FreeDev said:

Probably pointless, but could useful depending on the individual who is interested in IL programming and this snippet is about 140 lines of code. I created it on a whim.

That's interesting. My implementation is a little different. I do a a two pass compilation that spits out an AST, then I walk the AST. Yours is probably faster (maybe, it's hard to tell with reflection), but mine includes a WPF "IDE" which shows the state of memory and allows breakpoint debugging. 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

That would work pretty well, I am actually curious on how much faster it would be to try and have Brainf*ck emitted as native assembly with the help of LLVM JIT, guess that would be the next challenge for me.

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, FreeDev said:

That would work pretty well, I am actually curious on how much faster it would be to try and have Brainf*ck emitted as native assembly with the help of LLVM JIT, guess that would be the next challenge for me.

I'm more interested in adding features to BF than making it faster, so for me the AST is the way to go. Adding subroutines is a big one that I'm thinking about now. I can't decide if I want to do it with a stack (functions calls with arguments), a stack (manually push arguments to stack), or to change the AST into a weird combined AST/CALL graph structure.

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

You could do it similarly to how IL does it, you basically can load the parameters/fields/variables onto the stack and call the function which would pop the stack for each parameter and then return the value (if it's non-void) onto the stack. I think it's fairly sensible approach.

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


×