Jump to content

The under 100 line challenge!

fletch to 99
import matplotlib.pyplot as plt
import numpy as np
import psutil as ps
import time
import sys

while True:
    battStat = ps.sensors_battery()
    battPerc = np.zeros(2880)
    i = 0
    while battStat[2] != True:
        battStat = ps.sensors_battery()
        battPerc[i] = battStat[0]
        time.sleep(10)
        i += 1
        if battStat[2] == True:
            t = np.zeros(2880)
            plt.plot(t, battPerc)
            plt.show()
            sys.exit()

I think this is my first half successful Python project. It's a simple lil guy that monitors your laptop battery percentage while the power is disconnected, then plots it once power is reconnected. I wish I wrote more comments, I can't remember why I made two arrays that are 2880 indices large, but I mostly just took on this project at 3am to see how hard it was to replace Matlab with Python. Answer: not that hard, but not really worth it for classes.

ASU

Link to comment
Share on other sites

Link to post
Share on other sites

I made a program that helps you calculate the surface area and volume of some 3d shapes

  (Cylinder, Rectangular Prism, Pyramid, Cone, and Sphere)

link

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Quick solution for something at work yesterday

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                if (!File.Exists("[REMOVED].sqlite"))
                {
                    SQLiteConnection.CreateFile("[REMOVED].sqlite");

                    using SQLiteConnection conn = new SQLiteConnection("Data Source=[REMOVED].sqlite;Version=3;");
                    conn.Open();

                    using SQLiteCommand comm = conn.CreateCommand();
                    comm.CommandText = @"
                        CREATE TABLE '[REMOVED]' (
                            '[REMOVED]'	[REMOVED],
                            '[REMOVED]' [REMOVED],
                            '[REMOVED]'	[REMOVED],
                            '[REMOVED]'	[REMOVED],
                            '[REMOVED]'	[REMOVED],
                            '[REMOVED]'  [REMOVED]
                        );";
                    comm.ExecuteNonQuery();
                }

                DataTable dt = new DataTable();

                using (SqlConnection conn = new SqlConnection("[REMOVED]"))
                {
                    conn.Open();
                    using SqlCommand comm = new SqlCommand("[REMOVED]", conn);
                    using SqlDataAdapter da = new SqlDataAdapter(comm);
                    da.Fill(dt);
                }

                ParallelOptions parallelOptions = new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount };

                Parallel.ForEach(dt.AsEnumerable(), parallelOptions, dtRow =>
                {
                    LogThis(dtRow);
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        static void LogThis(DataRow dr)
        {
            try
            {
                List<SQLiteParameter> SqlParams = new List<SQLiteParameter> 
                {
                    new SQLiteParameter("$[REMOVED]", dr["[REMOVED]"]),
                    new SQLiteParameter("$[REMOVED]", dr["[REMOVED]"]),
                    new SQLiteParameter("$[REMOVED]", dr["[REMOVED]"]),
                    new SQLiteParameter("$[REMOVED]", dr["[REMOVED]"]),
                };

                using SQLiteConnection conn = new SQLiteConnection("Data Source=[REMOVED].sqlite;Version=3;");
                conn.Open();

                using SQLiteCommand comm = conn.CreateCommand();
                comm.CommandText = @"[REMOVED]";

                foreach (SQLiteParameter param in SqlParams)
                {
                    comm.Parameters.Add(param);
                }

                comm.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }

 

EZ BAKE OVEN 3.5

AMD Ryzen 7 1700 @3.85Ghz, 1.46v
16GB DDR4 @3400Mhz, 1.35v

MSI GTX 1060 3GB

x2 Corsair 500GB SSD

x2 Seagate 6TB HDD RAID 1 @7200RPM

Ubuntu 20.04

 

Link to comment
Share on other sites

Link to post
Share on other sites

A cuckoo clock in Rust:

 

[dependencies]
chrono = "0.4"
use chrono::prelude::*;

fn main() {
	let (_, hour) = Local::now().hour12();
	let hour_usize = hour as usize;
	println!("{}", "Cuckoo! ".repeat(hour_usize));
}

 

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 weeks later...

A VBScript file that very lazily converts Brainfuck to C.

Dim p, j, f, c, b, o
p = WScript.Arguments(0)
o = WScript.Arguments(1)
if WScript.Arguments.Count = 0 then
    WScript.Echo "Missing parameters"
end if
Set j = CreateObject("Scripting.FileSystemObject")
Set b = j.CreateTextFile(o & ".c", True)
Set f = j.OpenTextFile(p, 1)
b.WriteLine("#include <stdio.h>")
b.WriteLine("int main()")
b.WriteLine("{")
b.WriteLine("int i = 0, n = 0, m[30000], b[30000], x[30000];")
Do Until f.AtEndOfStream
	c = f.Read(1)
	Select Case c
	Case "+"
	b.WriteLine("m[n]++;")
	Case "-"
	b.WriteLine("m[n]--;")
	Case ">"
	b.WriteLine("n++;")
	Case "<"
	b.WriteLine("n--;")
	Case "["
	b.WriteLine("b[i] = n;")
	b.WriteLine("i++;")
	b.WriteLine("if( m[n] == 0 ) {")
	b.WriteLine("n = x[n];")
	b.WriteLine("};")
	Case "]"
	b.WriteLine("if( m[n] != 0 ) {")
	b.WriteLine("n = b[i--];")
	b.WriteLine("n++;")
	b.WriteLine("};")
	Case "."
	b.WriteLine("printf(""%d\n"", m[n] );")
	Case ","
	b.WriteLine("gets( inp );")
	b.WriteLine("m[n] = ""%d"", inp;")
	End Select
Loop
b.WriteLine("return 0;")
b.WriteLine("}")
Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

Decided to go back to my Khan Academy account from years ago, wow there's some old stuff on there. Anyway, for this challenge I made this (very) basic raytracing engine:

https://www.khanacademy.org/computer-programming/raycaster/4986599327088640

96 lines without whitespace and comments. Nvidia, eat your heart out.

// Triangle class: translates rays and surfaces to intersection points
var Triangle = function(pta, ptb, ptc, c) {
    this.pta = pta;
    this.ptb = ptb;
    this.ptc = ptc;
    this.c = c;
    
    var ab = PVector.sub(this.ptb, this.pta);
    var ac = PVector.sub(this.ptc, this.pta);
    this.norm = ab.cross(ac);
    this.d = -this.norm.dot(this.pta);
};
Triangle.prototype.castDistance = function(pos, ray) {
    ray.normalize(); // make sure ray is length 1
    return (-this.norm.dot(pos) - this.d) / (this.norm.dot(ray));
    // distance to intersection point
};
Triangle.prototype.castDistanceBounded = function(pos, ray) {
    var k = this.castDistance(pos, ray);
    ray.normalize();
    ray.mult(k); // extend the ray until we reach the surface
    var p = PVector.add(pos, ray); // record coords of collision point
    
    /// IS THE POINT IN THE TRIANGLE?
    // sides of the triangle
    var ab = PVector.sub(this.ptb, this.pta);
    var bc = PVector.sub(this.ptc, this.ptb);
    var ca = PVector.sub(this.pta, this.ptc);
    
    // lines to point
    var ap = PVector.sub(p, this.pta);
    var bp = PVector.sub(p, this.ptb);
    var cp = PVector.sub(p, this.ptc);
    
    // normals from each corner
    var na = ap.cross(ab);
    var nb = bp.cross(bc);
    var nc = cp.cross(ca);
    
    // if we're on the same side of all 3 lines...
    if(na.dot(nb) >= 0 && nc.dot(na) >= 0 && nb.dot(nc) > 0) {
        return k; // we're on the triangle
    } else {
        return Infinity; // we missed
    }
};

// Camera class: translates intersection points to screen space
var Camera = function(pos, dir, projW, projH, projDist) {
    this.pos = pos;
    this.dir = dir;
    dir.normalize();
    this.w = projW;
    this.h = projH;
    this.d = projDist;
};
Camera.prototype.screenRay = function(x, y) {
    var vertical = new PVector(0, 1, 0);
    // define the screen x as perpendicular to view & up direction
    var horizon = this.dir.cross(vertical);
    horizon.normalize();
    // define the screen y as perpendicular to view & screen x
    var zenith = horizon.cross(this.dir);
    zenith.normalize();
    
    // map screen coords to projected location
    horizon.mult(map(x, 0, width, -this.w/2, this.w/2));
    zenith.mult(map(y, 0, height, this.h/2, -this.h/2));
    var screenPoint = PVector.add(horizon, zenith);
    
    // shift forward by look distance
    screenPoint.add(PVector.mult(this.dir, this.d));
    
    return screenPoint;
};
Camera.prototype.castDistance = function(tri, x, y) {
    var dir = this.screenRay(x, y);
    return tri.castDistanceBounded(this.pos, dir);
};
Camera.prototype.renderPoint = function(tris, x, y, pxSize, cullDist, cullColor) {
    var minDist = cullDist;
    var hitColor = cullColor;
    for(var i = 0; i < tris.length; i++) {
        var current = this.castDistance(tris[i], x, y);
        if(current < minDist) {
            minDist = current;
            hitColor = tris[i].c;
        }
    }
    fill(hitColor);
    rect(x, y, pxSize, pxSize);
};

// Shape definitions
var px = new PVector(1, 0, 0);
var py = new PVector(0, 1, 0);
var pz = new PVector(0, 0, 1);
var mx = new PVector(-1, 0, 0);
var my = new PVector(0, -1, 0);
var mz = new PVector(0, 0, -1);
var octahedron = [];
octahedron.push(new Triangle(px, py, pz, color(0)));
octahedron.push(new Triangle(mx, my, pz, color(0)));
octahedron.push(new Triangle(mx, py, mz, color(0)));
octahedron.push(new Triangle(px, my, mz, color(0)));
octahedron.push(new Triangle(mx, my, mz, color(255)));
octahedron.push(new Triangle(mx, py, pz, color(255)));
octahedron.push(new Triangle(px, my, pz, color(255)));
octahedron.push(new Triangle(px, py, mz, color(255)));

// Camera definitions
var pos = new PVector(5, 1, 1); // world position
var dir = new PVector(-5, -1, -1); // look direction
var cam = new Camera(pos, dir, 1, 1, 2); // FOV
var pixelSize = 3;
noStroke();
for(var i = 0; i < width; i += pixelSize) {
    for(var j = 0; j < height; j += pixelSize) {
        cam.renderPoint(octahedron, i, j, pixelSize, 100, color(100));
    }
}

Note: you may notice that the preview window on Khan Academy looks a little pixelated -- I'm rendering at 1/3 the normal resolution since running full resolution has a tendency to time out the page and crash. If you want to try with different scaling, you can play with the pixelSize variable -- I found 2 to work occasionally and 3 and above to be the most reliable, while 1 usually crashed outright, but your mileage may vary.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 1 month later...
On 6/14/2013 at 10:13 PM, IntelvsAMD said:

I can make the most useful program in 1 line. Remove all white spaces ^-^. 

Bash one-liners for the win! (I daily-drive Ubuntu)

Link to comment
Share on other sites

Link to post
Share on other sites

using System.Collections.Generic;
using System.IO;
namespace rename
{ class Program { static void Main(string[] args)
            { args = new string[] { "hello" };
            string strExeFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            FileInfo fi = new FileInfo(strExeFilePath);
            DirectoryInfo di = fi.Directory;
            List<FileInfo> l = new List<FileInfo>();
            string[] s = new string[] { "jpg", "png", "bmp", "jpeg", "JPG", "PNG", "BMP", "JPEG" };
            foreach (var item in s) { l.AddRange(di.GetFiles(string.Format("*.{0}", item).ToString(), SearchOption.TopDirectoryOnly)); }
            foreach (var item in l)
            {   FileInfo newfile = new FileInfo(item.Directory + @"\" + args[0] + item.Name);
                if (!newfile.Exists) { item.MoveTo(newfile.FullName); } } } } }

Here is code I wrote for C# console application to shove text in front of image files.

 

USAGE:

-Place in folder with images

-EXENAME.exe <text to place in front>

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Here is a Jupyter Notebook I use for machine learning super resolution to images.

 

 

import numpy as np
import os
from PIL import Image
img = Image.open('miniconda3/envs/envname/share/images/yacht 6800.jpg')
lr_img = np.array(img)
from ISR.models import RDN
rdn = RDN(weights='psnr-small')
sr_img = rdn.predict(lr_img, by_patch_of_size=50)
Image.fromarray(sr_img)

 

Link to comment
Share on other sites

Link to post
Share on other sites

Here is code I wrote in 2005. Its a snippet from bot software I wrote for World of Warcraft. My bot software was for personal use only so I was never affected by warden or GM banning. 

 

This code is written in VB.net and will capture a screen grab. it uses P-invoke. easily converted to C# my language of choice for some time now.

 

 

Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.VisualBasic

<Serializable()> Public Class TakePicture
    <DllImport("gdi32")> _
    Public Shared Function BitBlt(ByVal hDestDC As Integer, ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal hSrcDC As Integer, ByVal xSrc As Integer, ByVal ySrc As Integer, ByVal dwRop As Integer) As Integer
    End Function

    <DllImport("user32")> _
    Public Shared Function GetWindowDC(ByVal hwnd As Integer) As IntPtr
    End Function

    <DllImport("user32")> _
    Public Shared Function ReleaseDC(ByVal hwnd As Integer, ByVal hdc As Integer) As Integer
    End Function

    Private Const SRCCOPY = &HCC0020
    Public Function GetScreenshot(ByVal PictureWidth As Int16, ByVal PuctureHeight As Int16) As Image
        Dim myImage = New System.Drawing.Bitmap(PictureWidth, PuctureHeight)
        Dim g As Graphics = Graphics.FromImage(myImage)
        Try
            Dim destDeviceContext As IntPtr = g.GetHdc()
            Dim srcDeviceContext As IntPtr = GetWindowDC(0)
            BitBlt(destDeviceContext, 0, 0, PictureWidth, PuctureHeight, srcDeviceContext, 0, 0, SRCCOPY)
            ReleaseDC(0, srcDeviceContext)
            g.ReleaseHdc(destDeviceContext)
        Finally
            g.Dispose()
        End Try
        Return myImage
    End Function
End Class

 

Link to comment
Share on other sites

Link to post
Share on other sites

Cheap place sound. This was from my World of Warcraft botting ventures. There was some kind of trick people were playing with trade windows. I cant remember what exactly it was, they would open a window with a specific item and be able to swap it out. I cant exactly remember. the item was worth a lot so people would fall for the trick but in doing so they lost money and got no item. I decided to create a bot to circumvent the trick and instead steal from them with lightning fast reflexes. I integrated an alarm system to warn about the trade window trick and also a successful grab. I needed to wake up and log out because I did not want my character acting dumb while the complaint to GM's was being made. I tell you that waking up the the enterprise ship alarm was music to my ears.

 

 

Imports System.Runtime.InteropServices

Public Class CheapSound

    <DllImport("winmm.dll", SetLastError:=True)> _
	Private Shared Function PlaySound(ByVal name _
      As String, ByVal hmod As Integer, ByVal flags As Integer) As Integer
    End Function

    Public Const SND_SYNC = &H0 ' play synchronously 
    Public Const SND_ASYNC = &H1 ' play asynchronously 
    Public Const SND_MEMORY = &H4  'Play wav in memory
    Public Const SND_ALIAS = &H10000 'Play system alias wav 
    Public Const SND_NODEFAULT = &H2
    Public Const SND_FILENAME = &H20000 ' name is file name 
    Public Const SND_RESOURCE = &H40004 ' name is resource name or atom 

    Public Sub PlayFile(soundfile As String)

		PlaySound(soundfile, SND_MEMORY, 0)

    End Sub
End Class

 

Link to comment
Share on other sites

Link to post
Share on other sites

A very simple random maze game, with "3D" ray casting graphics. Github

gif.gif.cf523b15150e2edd7d00415cac30cb2c.gif

Spoiler

import numpy as np
from matplotlib import pyplot as plt
import keyboard

#random map generator
size = 15
mapa = [[list(np.random.uniform(0, 1, 3))] * size for i in range(size)]
for i in range(size-2):
    for j in range(size-2):
        if np.random.uniform() > 0.33:
            mapa[i+1][j+1] = 0

posx, posy = (1, np.random.randint(1, size -1))
rot = np.pi/4
x, y = (posx, posy)
mapa[x][y] = 0
count = 0 
while True:
    testx, testy = (x, y)
    if np.random.uniform() > 0.5:
        testx = testx + np.random.choice([-1, 1])
    else:
        testy = testy + np.random.choice([-1, 1])
    if testx > 0 and testx < size -1 and testy > 0 and testy < size -1:
        if mapa[testx][testy] == 0 or count > 5:
            count = 0
            x, y = (testx, testy)
            mapa[x][y] = 0
            if x == size-2:
                exitx, exity = (x, y)
                break
        else:
            count = count+1

while True: #main game loop
    
    plt.hlines(-0.6, 0, 60, colors='gray', lw=165, alpha=0.5)
    plt.hlines(0.6, 0, 60, colors='lightblue', lw=165, alpha=0.5)
    tilex, tiley, tilec = ([], [], [])
    
    for i in range(60): #vision loop
        rot_i = rot + np.deg2rad(i - 30)
        x, y = (posx, posy)
        sin, cos = (0.02*np.sin(rot_i), 0.02*np.cos(rot_i))
        n = 0
        while True: # ray loop
            xx, yy = (x, y)
            x, y = (x + cos, y + sin)
            n = n+1
            if abs(int(3*xx)-int(3*x)) > 0 or abs(int(3*yy)-int(3*y))>0:
                tilex.append(i)
                tiley.append(-1/(0.02 * n))
                if int(x) == exitx and int(y) == exity:
                    tilec.append('b')
                else:
                    tilec.append('k')
                    
            if mapa[int(x)][int(y)] != 0:
                h = np.clip(1/(0.02 * n), 0, 1)
                c = np.asarray(mapa[int(x)][int(y)])*(0.3 + 0.7 * h**2)
                break 
        plt.vlines(i, -h, h, lw = 8, colors = c) # draw vertical lines

    plt.scatter(tilex, tiley, c=tilec) # draw tiles on the floor
    
    plt.axis('off'); plt.tight_layout(); plt.axis([0, 60, -1, 1])
    plt.draw(); plt.pause(0.0001); plt.clf()

    # player's movement
    key = keyboard.read_key()
    x, y = (posx, posy)

    if key == 'up':
        x, y = (x + 0.3*np.cos(rot), y + 0.3*np.sin(rot))
    elif key == 'down':
        x, y = (x - 0.3*np.cos(rot), y - 0.3*np.sin(rot))
    elif key == 'left':
        rot = rot - np.pi/8
    elif key == 'right':
        rot = rot + np.pi/8
    elif key == 'esc':
        break

    if mapa[int(x)][int(y)] == 0:
        if int(posx) == exitx and int(posy) == exity:
            break
        posx, posy = (x, y)

plt.close()

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Calculator for the cost of a "mound" in Minecraft Hypixel Bedwars

Useful for optimizing your base, because my friends are nerds.

from os import system
from math import ceil

def findBlockTable(alias):
	for blockTable in blockPrices:
		for tableAlias in blockTable[1]:
			if(tableAlias == alias):
				return blockTable
	return None

#Name, Aliases, Q, P, Iron/Gold/Emerald (0/1/2)
blockPrices = [
	["WOOL", ["WOOL","WO", "W"], 16, 4, "Iron"],
	["CLAY", ["CLAY","C","CL"], 16, 12, "Iron"],
	["WOOD", ["WOOD","WD"], 16, 4, "Gold"],
	["GLASS", ["GLASS","G"], 4, 12, "Iron"],
	["ENDSTONE", ["ENDSTONE","E","END"], 12, 24, "Iron"],
	["OBSIDIAN", ["OBSIDIAN", "O"], 4, 4,"Emerald"]
]

blocks = []
system('cls')

usr = " "
while (usr==" " or usr.upper() != ""):
	for a in blockPrices:
		for i, b in enumerate(a[1]):
			print(b, end = "")
			if(i <= len(a[1])-2):
				print(" - ", end = "")
		print()
	usr = input("").upper()
	if(block := findBlockTable(usr)):
		blocks.append(block)
	system('cls')

def calcBlocks(layer):
	if layer<0:
		return 0
	else:
		return (6+((layer-1)*4)) + calcBlocks(layer-1)

print("(Individual prices don't carry to a second layer)")
blockCounts = [0] * len(blockPrices)
for k, block in enumerate(blocks):
	i = k + 1
	blockCountIndex = None
	for j, blockTable in enumerate(blockPrices):
		if(block == blockTable):
			blockCountIndex = j
	amount = calcBlocks(i)
	blockCounts[blockCountIndex] += amount
	individualPrice = ceil(amount / block[2]) * block[3]
	print("%s - %4d blocks - %s %s" % (block[0].ljust(8," "), amount, individualPrice, block[4]))


totalPrices = {}
print("Total prices (including carry over)")
for i in range(0, len(blockCounts)):
	table = blockPrices[i]
	cost = ceil(blockCounts[i] / table[2]) * table[3]
	if(cost > 0):
		resource = blockPrices[i][4]
		if(not resource in totalPrices.keys()):
			totalPrices[resource] = cost
		else:
			totalPrices[resource] += cost
	
for key in totalPrices.keys():
	print("%s - %d" % (key.ljust(7, " "), totalPrices[key]))
input()
Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 months later...

I wrote a userscript (you can apply it with something like ViolentMonkey or TamperMonkey) which gets rid of animated GIFs on this forum.

 

52 lines including nice formatting and some "comfort features" such as customising what is put in instead and putting some text at the bottom to indicate that the script ran:

It can be installed from GreasyFork: https://greasyfork.org/en/scripts/424014-animated-gif-pfp-hider-for-linustechtips-invision-community

// ==UserScript==
// @name        Animated GIF PFP Hider for LinusTechTips (Invision Community)
// @namespace   py-mpixel
// @match       https://linustechtips.com/*
// @grant       none
// @version     1.0
// @author      pythonmegapixel
// @description Hides animated GIF profile pictures from linustechtips.com
// @license BSD-3-Clause
// ==/UserScript==
 
 
/* THIS LINE SETS WHAT WILL BE USED INSTEAD OF GIFS. By default it is an 
 * SVG which produces a generic "contacts" icon; you change it to anything 
 * you want. If it's an image be sure to set the height and width to auto;
 * if it's text you may need to experiment with padding and overflow to avoid
 * it being cut off*/
 
const replacementImageData =
  `
  <svg xmlns="http://www.w3.org/2000/svg" width="auto" height="auto" fill="white" style="background-image:linear-gradient(#2196f3, skyblue);" class="bi bi-person-square" viewBox="0 0 16 16">
   <path d="M3 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H3zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/>
</svg>
  `;
 
/****************************************************************************
 ***************************************************************************/
 
 
document.querySelectorAll('.ipsUserPhoto img, .ipsUserPhoto:is(img)').forEach(function(pfp) { // Loop through every profile image
  if (pfp.src.substr(pfp.src.length - 3) === "gif") {                                         // Does the filename end in gif?
      pfp.style.display = "none";                                                             // If so, hide it
      }                                                                                     
    }
  );
 
document.querySelectorAll('.ipsUserPhoto').forEach(function(pfpcontainer) {                   // Now loop through every CONTAINER for the profile images
   
    var newImage = document.createElement('span');                                            // Create a new span element
   
    newImage.innerHTML = replacementImageData;                                                // Put the replacement image data in there
 
    
    pfpcontainer.appendChild(newImage);
    
  });
 
document.querySelectorAll('#elCopyright').forEach(function(thePara) {                                                             
  var newP = document.createElement('p');
  newP.innerHTML = "<a href='https://pythonmegapixel.com' target='_blank'>Modified with a userscript by pythonmegapixel</a>"; // Adds some data to the bottom of the page to show that the userscript worked
  thePara.appendChild(newP);
}
);

 

____________________________________________________________________________________________________________________________________

 

 

____________________________________________________________________________________________________________________________________

pythonmegapixel

into tech, public transport and architecture // amateur programmer // youtuber // beginner photographer

Thanks for reading all this by the way!

By the way, my desktop is a docked laptop. Get over it, No seriously, I have an exterrnal monitor, keyboard, mouse, headset, ethernet and cooling fans all connected. Using it feels no different to a desktop, it works for several hours if the power goes out, and disconnecting just a few cables gives me something I can take on the go. There's enough power for all games I play and it even copes with basic (and some not-so-basic) video editing. Give it a go - you might just love it.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...

I just thought I should share a bit of useful code that I wrote 11 years ago, but still use from time to time. It's a bash script that calculates the date for Easter Sunday for a given year. Save it as 'easter' and run it with a year as argument, ie. 'easter 2022'. That will give you the output 'April 4', now you now 🙂

 

#!/bin/bash
# (C) 2010 Robert Lie Nilsson
#
# Formula:
#        a=year%19
#        b=year/100
#        c=year%100
#        d=b/4
#        e=b%4
#        f=(b+8)/25
#        g=(b-f+1)/3
#        h=(19*a+b-d-g+15)%30
#        i=c/4
#        k=c%4
#        l=(32+2*e+2*i-h-k)%7
#        m=(a+11*h+22*l)/451
#        Easter Month =(h+l-7*m+114)/31  [3=March, 4=April]
#        p=(h+l-7*m+114)%31
#        Easter Date=p+1     (date in Easter Month)

if [[ -z $1 ]] ; then
  echo "Usage: easter YEAR-TO-CALCULATE"
  echo "Example: easter 2011"
fi

year=$(echo $1|grep -e ^[0-9]*$)
if [[ -z $year ]] ; then
  echo "You have to give the year in numbers. For example 2009, 413, 2034...." 
  exit 1
fi

easter=$(echo "a=$year%19;b=$year/100;c=$year%100;d=b/4;e=b%4;f=(b+8)/25;g=(b-f+1)/3;h=(19*a+b-d-g+15)%30;i=c/4;k=c%4;l=(32+2*e+2*i-h-k)%7;m=(a+11*h+22*l)/451;em=(h+l-7*m+114)/31;p=(h+l-7*m+114)%31;ed=p+1;em;ed"|bc) 

easter_month=$(echo $easter|awk '{print $1}')
easter_date=$(echo $easter|awk '{print $2}')

if [[ $easter_month = 3 ]] ; then
  echo "March $easter_date"
else
  echo "April $easter_date"
fi

 

Link to comment
Share on other sites

Link to post
Share on other sites

  • 4 weeks later...

I don't see how this is hard. Just use C++ and put everything on 1 line 😛

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
On 5/6/2021 at 12:40 PM, DevBennyturtle said:

I don't see how this is hard. Just use C++ and put everything on 1 line 😛

computers gonna shit itself

Main PC: the literature club machine

Intel I5 9600k @ 4.2 Ghz | MSI z390-a pro | G.Skill Trident Z RGB 32 GB 3000Mhz | Samsung 970 Evo 500 GB | Seagate barracuda 3.5" 2.5tb  | Thermaltake Floe Riing RGB 240 | Asus GeForce GTX 1660 Ti 6 GB DUAL OC | Thermaltake Core P3 TG Snow Edition

 

Daily drivers

OPPO A52 | Razer Blackwidow Chroma | Razer Deathadder V2 Pro | Beryodynamic DT 990 PRO | Focusrite Scarlett solo gen 2

Link to comment
Share on other sites

Link to post
Share on other sites

15 hours ago, mon1ka said:

computers gonna shit itself

depends if its syntax'ed properly, if it is the computer wont care

Link to comment
Share on other sites

Link to post
Share on other sites

On 5/18/2021 at 10:07 PM, DevBennyturtle said:

depends if its syntax'ed properly, if it is the computer wont care

A decent build system with proper dependency tracking will only compile changed files and dependent files.

In a huge project a clean build can take hours but an incremental build can be done under secs or minutes depending on changes.

ಠ_ಠ

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

You can't put a complete C++ program into one line, unless you don't need one single #.

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
  • 2 weeks later...

I made a powershell script that will get the stuff I need when installing windows, mainly system drivers, gamelaunchers, and other must have apps.

You could probably go in and replace the links to the download pages and use this for yourself, but you might have to change the basic format for the link type, as ive made unziping, number removing, and other ones to make it easier and more adaptable./

clocks in at 106 lines, would be less than 100, but iver added blank lines and markers for what each block does to make it more understandable.

 

powershelldl.ps1

I could use some help with this!

please, pm me if you would like to contribute to my gpu bios database (includes overclocking bios, stock bios, and upgrades to gpus via modding)

Bios database

My beautiful, but not that powerful, main PC:

prior build:

Spoiler

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

On 6/1/2021 at 7:00 AM, Dat Guy said:

You can't put a complete C++ program into one line, unless you don't need one single #.

Yes you can. Write it on many lines, run the C preprocessor, then minify.

Link to comment
Share on other sites

Link to post
Share on other sites

10 hours ago, BadBoyHaloCat said:

Yes you can. Write it on many lines, run the C preprocessor, then minify.

I mean, you're not wrong, but...

 

That's kind of not the point of "one-liners".

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

  • 1 month later...
On 6/15/2013 at 2:27 AM, fletch to 99 said:

The goal here is to make a useful program, that an end user is capable of using, that is under 100 lines! Ofcourse anything near 100 lines is awesome too, try to keep it fairly close though!

 

Please either link your source (if using an external site like pastie or github:gist) 

 

or

 

use code tags for example:


[code]Code here[ /code]

Here are some of my programs:

Biology Protein acronym converter: https://gist.github.com/fletchto99/5786050
Official LTT Story generator: https://gist.github.com/fletchto99/5786808

Screen Snapper: https://gist.github.com/fletchto99/5788659

The first link doesn't work

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


×