Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
fletch to 99

The under 100 line challenge!

Recommended Posts

On 23.5.2017 at 2:29 AM, CannonContraption said:

Wrote a shell script for doing a dropbox-style SSH-based RSync on a specific directory. Manual invocation, but when it runs it does an incremental diff on the files on both sides and moves the ones that were created/modified.


#!/bin/bash
#Server parameters
server="10.0.0.1" #Change this to your server's IP address
username="jim"
portnumber="20" #Your SSH server's port number.


#Excluded files
#I added an example excludes file based on files I've had problems with in the past.
path_to_excludes="...../rsyncexcludes.txt" #Change this to the path to the excludes file

#source and destination
#Please note that due to the nature of rsync, these MUST be absolute paths. They also
#must match on the source and destination, so if you mirror /home/joey/SyncMe on one
#machine, you'll get /home/joey/SyncMe on the other.
source_path="/..../SyncMe" #Path to what you're syncing plus the folder name itself
dest_path="/..../" #Path to what you're syncing without the folder itself

#Tools
excludes="--exclude-from $path_to_excludes" #if you prefer to hard-code exludes, use this variable instead of the excludes file
sshcommand="ssh -p $portnumber" #This is the SSH command. If you need extra params to login, place them here

#From here down is the code to sync stuff itself. Most of the params should be above.
rsync -avucr $excludes -e "$sshcommand" $username@$server:$source_path $dest_path
if [ $? == 0 ]; then
	echo -e "\e[1;32mPull complete. Beginning push...\e[m"
else
	echo -e "\033[1;31mFailed to fetch updates. Please diagnose and rerun the script.\033[m"
	exit;
fi
rsync -avucr $excludes -e "$sshcommand" $source_path $username@$server:$dest_path
if [ $? == 0 ]; then
	echo -e "\e[1;32mPush complete. Script is successful.\e[m"
else
	echo -e "\e[1;31mPush failed. Please diagnose and rerun the script.\e[m"
	exit;
fi

It is written in Bash, and relies on RSync being installed on both systems. If this counts, then including the readme and excludes example file, the entire project comes in at under 100 lines.

 

https://github.com/CannonContraption/rsynccstation

for the other files.

 

I do wish that there was BASH syntax highlighting support, but Perl isn't so far off so if something looks out of place in the highlighting, that's why.

Now you just need to tie it down with some inotify goodness, right? :) Or just "cheat" and use incron to trigger it when folder contents change.

Link to post
Share on other sites
<?php

       if (isDomainAvailible('http://google.com'))
       {
               echo "<div class='alert alert-success'>No Problem!</div>";
       }
       else
       {
               echo "<div class='alert alert-danger'><strong>Problem Detected! GET TO DA CHOPPER</strong></div>";
       }
       function isDomainAvailible($domain)
       {
               if(!filter_var($domain, FILTER_VALIDATE_URL))
               {
                       return false;
               }
               $curlInit = curl_init($domain);
               curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
               curl_setopt($curlInit,CURLOPT_HEADER,true);
               curl_setopt($curlInit,CURLOPT_NOBODY,true);
               curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);
               $response = curl_exec($curlInit);
               curl_close($curlInit);
               if ($response) return true;
               return false;
       		}
?>

A PHP script that checks if it is able to connect to domain :)


 

Q: How many prolog programmers does it take to change a lightbulb?

A: Yes.

Link to post
Share on other sites

If I understood the theory correctly, I made a basic Huffman codec in Python

def bucketize_string(input):
    buckets = {}
    for idx in xrange(0, len(input), 1):
        char = input[idx]
        if char not in buckets:
            buckets[char] = 1
        else:
            buckets[char] += 1
    return buckets

def create_nodes(leaves, freq_idx = 1):
    nodes = []
    if len(leaves) > 1:
        for idx in xrange(0, len(leaves)-1, 2):
            if type(leaves[idx+1]) is tuple:
                nodes.append([leaves[idx], leaves[idx+1], leaves[idx][freq_idx] + leaves[idx+1][1]])
            else:
                nodes.append([leaves[idx], leaves[idx+1], leaves[idx][freq_idx] + leaves[idx+1][freq_idx]])
        if idx < len(leaves) - 2:
            nodes.append(leaves[idx+2])
    else:
        nodes.append(leaves[0])
    return nodes

def build_sym_table(tree):
    sym_table = {}
    map_node(tree, sym_table, '')
    return sym_table

def map_node(node, sym_table, code):
    for x in xrange(0, len(node), 1):
        if type(node[x]) is list:
            map_node(node[x], sym_table, code + str(x))
        elif type(node[x]) is tuple:
            sym_table[node[x][0]] = code + str(x)

def huffman_encode(in_string):
    import operator
    buckets = bucketize_string(foobar)
    tree = create_nodes(sorted(buckets.items(), key=operator.itemgetter(1)))

    while len(tree) > 2:
        tree = create_nodes(tree, 2)
    sym_table = build_sym_table(tree)

    code = ''
    for x in xrange(0, len(in_string), 1):
        code += sym_table[in_string[x]]
    return code, tree
    
def huffman_decode(in_stream, tree):
    message = ''
    node = tree
    for x in xrange(0, len(in_stream), 1):
        symbol = int(in_stream[x])
        node = node[symbol]
        if type(node) is tuple:
            message += node[0]
            node = tree

    return message

This has no practical purpose (for one it expands rather than compresses), but I was bored.

 

EDIT again: I think I finally got it down. It now theoretically compresses :3

Edited by M.Yurizaki
Link to post
Share on other sites
On 15/06/2013 at 7:27 AM, fletch to 99 said:

Here's a HTML clock I made in 10 minutes


<script>
function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};
    return i;
}
</script>
</head>

<body onload="startTime()">

<div id="txt"></div>

 

 


<script type="text/javascript" src="http://100widgets.com/js_data.php?id=264"></script>

Link to post
Share on other sites

This is a .bat script that temporally sets the APPDATA folder to a different folder to allow minecraft to be run off a flash drive.  It also has a built in version switcher. I used this to play minecraft at school. More to showoff than to actually play. Its value is probably less since minecraft does those things now. However this works with hacked clients that allow you to play offline multiplayer with any username. These hacked clients only work up to release 1.5.2 but it can be fun to go back in time sometimes. It also has an ASCII grass block. I thought it was a nice touch.

@echo off
color 0a
title Minecraft
If Not Exist .\Minecraft\.minecraft\bin\ (
color 07
Echo.
Echo   Minecraft has yet to be installed in this folder. 
Echo   Please hit enter and run it for the first time.
Echo   After this, you will be able to run the version selector
Pause >Nul
Set AppData=.\
.\Minecraft\MinecraftH.exe
Exit
)
Del .\Minecraft\.minecraft\bin\minecraft.jar
cls
Echo.
Echo                                +#++           
Echo                              +####+#+         
Echo                            +#+#++++###+       
Echo                          #++++###+++#+++#     
Echo                        #+##+###++#####++:+#   
Echo      Minecraft        ##:##+#+##+++++#+#+##+  
Echo ===================   ''#++#+#++#++##++##+;+  
Echo                       '''''+#++##+#++#+;+;++  
Echo  A. 1.2.6 (Alpha)     '''+'####+++###+;;;+++  
Echo  B. 1.7.3 (Beta)      '''+'';''##++++;+;+++;  
Echo  C. 1.5.2 (Release)   ''''+';';';;;;+;+++++;  
Echo                       '''''++'+'''+++++++++;  
Echo ===================   ';;''++'''++++;+++;+++  
Echo                       ''''''+;'''+;++++'+''+  
Echo                       '''''';';''++++;;+++;;  
Echo                        ,'+'''''''+++''+'+;:   
Echo                          :;;;'';'+'+++;;:     
Echo                            ,''';;++'+;:       
Echo                              :'''++;:         
Echo                                '++:            
Echo.
Choice /C ABC /N /M "Choose"
Pause >Nul
cls
If %ErrorLevel% EQU 3 (
Copy /B .\Jars\1.5.2\minecraft.jar .\Minecraft\.minecraft\bin\ 
cls
Set AppData=.\
.\Minecraft\Minecraft.exe 
Exit
)
If %ErrorLevel% EQU 2 (
Copy /B .\Jars\1.7.3\minecraft.jar .\Minecraft\.minecraft\bin\ 
cls
Set AppData=.\
.\Minecraft\MinecraftH.exe
Exit
)
If %ErrorLevel% EQU 1 (
Copy /B .\Jars\1.2.6\minecraft.jar .\Minecraft\.minecraft\bin\
cls
Set AppData=.\
.\Minecraft\MinecraftH.exe
Exit
)

 

Link to post
Share on other sites

i call this program "SHAForce1".

 

Not quite 100 lines, little bit over but i already had made this a while back and thought it could be kinda cool. 

 

You supply 2 files, a file full of SHA1 hashes and a dictionary, All the hashes will then be testing and if there are any matches then they will be displayed.

 

total: 144 lines (had around 160 on the full project with annotations)

 

no comments: https://gist.github.com/h3adshotzz/cf37e94e7621cee1a46bf5327f785a4b

Full project: https://github.com/h3adshotzz/SHAForce1

Link to post
Share on other sites

So I needed to come up with a way to clean up some whitespaces in CSV's that I was reading in.  I needed to both trim the ends of the strings, as well as convert multiple whitespaces into a single white space.  Took a stab at doing it with Regular Expressions and came up with

 

^\s*+([^\s])|(\s)\s*+|([^\s])\s*+$

And you would replace it with

\1\2\3

 

So it would take something like this:

Quote

<     Smith,    John                 H                  >

The <> brackets just signify where the string begins and end

 

And it would convert it into

Quote

<Smith, John H>

Yes, that many extra white spaces is unrealistic, but all it takes is one extra space to throw off my parser.

 

Sadly, as beautiful as it is, it does have some slight performance problems, and I ended up instead just first trimming the string, then using the regex:

\s+

And Replaced it with a single space.

 

 

 

Link to post
Share on other sites

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 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-5820k @ 4.2Ghz // MOBO: Asus X99 Sabertooth // RAM: 32GB Corsair Dominator Platinum 2400MHz 

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

STORAGE: Samsung Evo 850 500GB + 250GB // COOLING: Full custom loop // DISPLAY: LG 34UC89G-B

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 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 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 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 post
Share on other sites

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 post
Share on other sites

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 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 post
Share on other sites

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 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.

|Build Your Own Case Project|

 

 

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 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 post
Share on other sites

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 post
Share on other sites

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 post
Share on other sites

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 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

Buy VPN

×