Jump to content

The under 100 line challenge!

fletch to 99

My first Haxe program (learning it for a course)

It's a file shredder - drag files and folders onto it (or specify them in the command line) to shred them

It does 10 passes of pseudo-random data (no renames)

package;
import sys.FileSystem;
import sys.io.File;
import sys.io.FileSeek;

class Main
{
	static function shredFile(s:String):Void
	{
		Sys.println("Shredding x10: " + s);
		var fr = File.read(s);
		fr.seek(0, FileSeek.SeekEnd);
		var l = fr.tell();
		fr.close();
		var fw = File.write(s);
		for (w in 0...10)
		{
			Sys.println("Pass " + (w + 1));
			fw.seek(0, FileSeek.SeekBegin);
			for (i in 0...l)
			{
				var r = Std.int(Math.random() * 256);
				fw.writeByte(r);
			}
		}
		fw.close();
		FileSystem.deleteFile(s);
		Sys.println("Deleted");
	}

	static function main():Void
	{
		Sys.print("Press any key to begin shredding...");
		Sys.getChar(false);
		Sys.println("");
		var q = new List<String>();
		var dq = new List<String>();
		for (s in Sys.args())
			q.add(s);
		while (!q.isEmpty())
		{
			var s = q.pop();
			if (!FileSystem.exists(s))
			{
				Sys.println("Path not found: " + s);
				continue;
			}
			if (FileSystem.isDirectory(s))
			{
				Sys.println("Found directory " + s);
				dq.push(s);
				for (f in FileSystem.readDirectory(s))
					q.add(s + "/" + f);
				continue;
			}
			shredFile(s);
		}
		for (d in dq)
		{
			FileSystem.deleteDirectory(d);
			Sys.println("Removed directory " + d);
		}
		Sys.print("Finished. Press any key to exit...");
		Sys.getChar(false);
	}
}

 

Link to comment
Share on other sites

Link to post
Share on other sites


import java.util.Scanner;

/**
 * Created by ElfFriend.
 *
 * Calculates average and SEM.
 */
public class Main {

    public static void main(String[] arg){
        double[] values;

        print("Enter number of values.\n");
        int total=userInputB();

        print("Enter the values.\n");
        values=userInputValues(total);

        double average=averageCalc(values,total);
        print("Average: "+average);


        double sem=rootCalculate(sumCalc(values,total,average),total);
        print("SEM: "+sem);

    }
    private static double sumCalc(double[] values,int total, double average){
        double finalValue=0;
        for (int x=0;x<total;x++){
            finalValue+=Math.pow(average-values[x],2);
        }
        return finalValue;
    }
    private static double averageCalc(double[] values,int total){
        double finalValue=0;
        for (int x=0;x<total;x++){
            double tempValue=values[x];
            finalValue+=tempValue;
        }
        return finalValue/total;
    }

    private static int userInputB(){
        Scanner scan = new Scanner(System.in);
        return scan.nextInt();
    }
    private static double[] userInputValues(int total){
        Scanner scan = new Scanner(System.in);
        double[] values=new double[total];

        for (int x=0;x<total;x++) {
            values[x]=scan.nextDouble();
        }
        return values;
    }
    private static void print(String text){
        System.out.println(text);
    }
    private static double rootCalculate(double sum,int total){
        return Math.sqrt((sum)/(total*(total-1)));
    }
}

Had to calculate SEM and mean for a bio assignment. Since I was given a pdf with the numbers, I decided to quickly write some java code to do it for me instead of trying to enter in all the values into a calculator. It's not pretty but it works and it's under 100 lines! I apologize to anyone that's going to try and read this as I didn't comment it and it's probably terrible since efficiency or appearance came second to getting this done quickly.

Link to comment
Share on other sites

Link to post
Share on other sites


#define _ F-->00 || F-OO--;
long F=00,OO=00;
main(){F_OO();printf("%1.3f\n", 4.*-F/OO/OO);}F_OO()
{
            _-_-_-_
       _-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_
       _-_-_-_-_-_-_-_-_
            _-_-_-_
}

I didn't do this but it's worth sharing.

It calculates pi by measuring the area and diameter of itself.

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

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Here's a ray marcher in GLSL. Its way under 100 lines at 23 lines.

Go see in action at Shadertoy. I'm planning on rewriting it in C++ and with global illumination, so I can print it on a business card.

#define R iResolution
#define T iGlobalTime
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
	vec3 u=(2.*vec3(fragCoord.xy,0).xyz-R)/R.y;
	float t=0.,r=1.,c=t,h=3.;
	u.z=r;
	vec3 o=u,p=u,q=vec3(7,abs(sin(T*h)),3),l=q.zxz;
	q.x=t;
	for(int i=0;i<128;i++)
	{
		p=u*t+o;
		h=min(length(p-q)-1.,p.y+1.);
		i>63 ?r=min(r,8.*h/t):h<.001 ? c=5./length(p-l):t;
		t+=h; 
		if(i==63){
			o=p;
			u=normalize(l-o);
			t=.1;
		}
	}
	fragColor=vec4(c*r);
}

 

 

 

Disregard females, acquire currency
Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

Over the last couple of days, I took it upon myself to learn Python.

I'm used to C# and a little JavaScript, so I thought this would be a nice thing to try out.

 

I created a sinusoidal wave script that allows the user to enter text, choose whether or not they want it rainbow coloured or black and white, alter the wavelength and all of that jazz. And it took a little while, but I managed to suss it out.

Spoiler

import math
import sys

def main():
  print("\033[1mThe Rainbow Sine Wave Machine by Daniel Learmouth - http://daniellearmouth.com")
  print("\033[1m==============================================================================")
  print("\033[39;22mThis little app is only one hundred lines of code long, if you're curious.")
  print("All you have to do is type in a phrase and say whether or not you want the text to be in colour or black and white.")
  print("The result will be a sinusoidal wave with your text, colour of choice, and an additive character before it to make the wave.")
  print("Do note, however, that this app is intended to run in Windows' command prompt, and requires Python 3.5 to be installed.")
  print("\033[1m=======================================================================================================================")
  start()

def start():
  colset=''
  f=''
  t=0.0
  c=1
  colset = input("\033[39;22mWould you like the wave to be in rainbow colours? 'No' will return white. Y or N. ")
  if colset not in ['Y', 'y', 'N', 'n']:
    print("Sorry, I don't understand the command '"+colset+"'.")
    start()
  else:
    phrase = input("Please type a phrase. The wave will be created from this. ")
    lines = input("How many lines would you like the wave to take? Whole numbers only. ")
    wave = input("What frequency would you like the wave at? Numbers between 0.25 and 0.75 are recommended. ")
    depth = input("How big an amplitude do you want the wave to have? Whole numbers only. ")
    offset = input("How much of an offset would you like to add to the wave? Whole numbers only. ")
    additive = input("Please select a character that will create the wave. Only one character. ")

  try:
    iLines = int(lines)
    fWave = float(wave)
    iDepth = int(depth)
    iOffset = int(offset)
  except ValueError:
  	print("Sorry. It appears that there are characters besides numbers and decimal points in variables where that's not allowed.")
  	print("Please only use numbers for where it asks for a number, and a decimal point for frequency if applicable.")
  	print("Restarting......")
  	print("")
  	start()
  finally:
    iLines = int(lines)
    fWave = float(wave)
    iDepth = int(depth)
    iOffset = int(offset)
    print("")
    print("Colour?: "+colset+" // Phrase: "+phrase+" // Number of Lines: "+lines+" // Wavelength: "+wave)
    print("Amplitude: "+depth+" // Offset: "+offset+" // Additive character: "+additive)
    conkey = input("\033[1mAre these selections OK? Any key other than Y will default to a restart. ")
    if conkey in ['Y', 'y']:
      for x in range(,iLines):
        t += fWave
        s = " "
        v = int(round(math.sin(t)*iDepth))+iDepth+iOffset
        for k in range(,v):
          s += additive
        if colset in ['Y', 'y']:
          if c == 1:
            print("\033[31;1m"+s+phrase)
            c += 1
          elif c == 2:
            print("\033[33;1m"+s+phrase)
            c += 1
          elif c == 3:
            print("\033[32;1m"+s+phrase)
            c += 1
          elif c == 4:
            print("\033[36;1m"+s+phrase)
            c += 1
          elif c == 5:
            print("\033[34;1m"+s+phrase)
            c += 1
          elif c == 6:
            print("\033[35;1m"+s+phrase)
            c += 1
          else:
            c = 1
            x += 1
        elif colset in ['N', 'n']:
          print("\033[37;1m"+s+phrase)
    else:
      start()
  print("\033[39;22mComplete!")
  again()

def again():
  option = ""
  option = input("Do you want another one? Y or N. ")
  if option in ['Y', 'y']:
    start()
  elif option in ['N', 'n']:
    print("OK then. Thank you for checking this out!")
    print("Don't forget to check my website for more stuff! http://daniellearmouth.com")
    sys.exit()
  else:
    print("Sorry, I don't understand the command '"+option+"'.")
  again()

main()

 

I've probably broken a billion conventions just to get this under the 100 line limit, but if it works, it works. And having tried it, it works for me.

Here's a link to the file through GitHub.

DAYTONA

PROCESSOR - AMD RYZEN 7 3700X
MOTHERBOARD - ASUS PRIME X370-PRO
RAM - 32GB (4x8GB) CORSAIR VENGEANCE LPX DDR4-2400
CPU COOLING - NOCTUA NH-D14
GRAPHICS CARD - EVGA NVIDIA GEFORCE GTX 980Ti SC+ ACX 2.0 w/ BACKPLATE
BOOT and PROGRAMS - CORSAIR MP600 1TB
GAMES and FILES - TOSHIBA 2TB
INTERNAL BACKUP - WESTERN DIGITAL GREEN 4TB
POWER SUPPLY - CORSAIR RM850i
CASE - CORSAIR OBSIDIAN 750D

Link to comment
Share on other sites

Link to post
Share on other sites

Simple Math Functions:

 

public class MathFunctions {

    private Double diameter;
    private Double circumference;
    private Double radius;
    private Double area;
    private Double perimeter;
    private Double height;
    private Double length;
    private Double triangleSide;
    
    public Double getCircleCircum(Double diameter) {
        this.diameter = diameter;
        circumference = Math.PI * diameter;
        return circumference;
    }

    private Double getCircleArea(Double diameter) {
        this.diameter = diameter;
        this.radius = diameter / 2;
        area = Math.PI * Math.pow(radius, radius);
        return area;
    }

    private Double getRectangleArea(Double height, Double length) {
        this.height = height;
        this.length = length;
        area = height * length;
        return area;
    }

    private Double getRectanglePerimeter(Double height, Double length) {
        this.height = height;
        this.length = length;
        perimeter = (height * 2) + (length * 2);
        return perimeter;
    }
    
    private Double getTriangleSide(Double side1, Double side2) {
        Double pythag = Math.pow(side1, side1) + Math.pow(side2, side2);
        triangleSide = Math.sqrt(pythag);
        return triangleSide;
    }
}

 

Nothing brilliant at all. Just worth sharing.

Link to comment
Share on other sites

Link to post
Share on other sites

I doubt I've ever actually written a useful program under 100 lines of code.  I was thinking about posting a college and friend's code however. Which is a Java application which doesn't use the Google Maps API, and converts an address into coordinates using the harversine formula.   

 

Other than that, I wanted to say that some of these are fantastic and are great ideas in under 100 lines! I think I'm going to try and work on a network monitor or something.  But that's only if I can make one useful enough at under 100 lines.  

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

I'll have to rewrite my prime number sieve and submit it to this. I used some pretty serious optimizations to get it to run actually decently fast.

Euler's sieve FTW

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
On 15 June 2013 at 2:29 AM, deafboy said:

Under 100 lines... does that include comments?

 

This might be fun :)

Are you good with programming? Can you help me?

Link to comment
Share on other sites

Link to post
Share on other sites

Need help with programming.

Hi guys I have a question, how can I make a Keylogger through Python, I know there are many tutorials on YouTube but I have tried them to no avail. If anyone could help me it would be appreciated. I don't want to download one as the recorded logs could be sent to a server; and I'll have no control over them. The use of the Keylogger will not be illegal. Thanks.

Link to comment
Share on other sites

Link to post
Share on other sites

On 4/22/2016 at 6:08 AM, DJHenjin said:

I'll have to rewrite my prime number sieve and submit it to this. I used some pretty serious optimizations to get it to run actually decently fast.

Euler's sieve FTW

Why not Eratosthenes' Sieve? In practice it's faster.

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

Link to comment
Share on other sites

Link to post
Share on other sites

If it was made for the web does the HTML and CSS count? If not I made this: http://codepen.io/piecedigital/full/yYWxZB

 

	var lastNumber = null;
	var currentNumber = null;
	var currentOperation = null;
	var clearInput = true;
	var getNumber = function(e) {
	  if(clearInput) {
	    document.querySelector("#input").value = "";
	    clearInput = false;
	  }
	  var number = this.innerText;
	  document.querySelector("#input").value += number;
	  
	  currentNumber = parseInt(document.querySelector("#input").value);
	};
	var getOperation = function(e) {
	  console.log(this)
	  var operations = {
	    add: function(leftNum, rightNum) {
	      lastNumber = leftNum + Math.abs(rightNum);
	    },
	    subtract: function(leftNum, rightNum) {
	      lastNumber = leftNum - rightNum;
	    },
	    multiply: function(leftNum, rightNum) {
	      lastNumber = leftNum * rightNum;
	    },
	    divide: function(leftNum, rightNum) {
	      lastNumber = leftNum / rightNum;
	    },
	    equal: function(leftNum, rightNum) {
	      currentOperation(leftNum, rightNum);
	    }
	  }
	  
	  if(this.name !== "reset") {
	    // call functions based on input name
	    if(currentOperation !== null &amp;&amp; currentNumber !== null &amp;&amp; this.name === "equal") {
	      currentOperation(lastNumber, currentNumber);
	    } else {
	      lastNumber = currentNumber;
	    }
	    clearInput = true;
	    if(this.name !== "equal") { currentOperation = operations[this.name]; };
	    document.querySelector("#input").value = lastNumber;
	    console.log(lastNumber, currentNumber);
	  } else {
	    lastNumber = null;
	    currentNumber = null;
	    currentOperation = null;
	    clearInput = true;
	    document.querySelector("#input").value = 0;
	  }
	};
	var btnArray = document.querySelectorAll("button");
	
	// assign buttons click event listeners
	for(var btn = 0; btn &lt; btnArray.length; btn++) {
	  (btnArray[btn].name === "number") ? btnArray[btn].addEventListener("click", getNumber, false) : btnArray[btn].addEventListener("click", getOperation, false);
	};
	

Link to comment
Share on other sites

Link to post
Share on other sites

Totally dumb monte carlo method to approximate pi using the Buffon's Needle.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Test
{
    public class Program
    {
        static void Main(string[] args)
        {
            BuffonsNeedles bn = new BuffonsNeedles();
            Console.WriteLine($"Calculated pi to be approximately {bn.RatioIntersecting()}.");
            Console.ReadKey();
        }
    }


    /* Monte Carlo Simulation of Buffons Needles to Approximate PI using the random distribution of line segments of random orientation and position on a field. 
       PI is approximately equal to the total number of line segments divided by the number of line segments that intersect the line x = n where n is a multiple of 2. */
    public class BuffonsNeedles
    {
        internal struct Needle
        {
            internal double MidpointX;
            internal double Angle; // The angle from vertical we only care about [0-180) as > 180 angles are symetrical.

            internal bool Crosses2N()
            {
                int minX, maxX;

                minX = (int)Math.Ceiling(MinX());
                maxX = (int)Math.Floor(MaxX());
                int diff = maxX - minX;
                if (diff == 0 && (minX & 1) == 0 && (maxX & 1) == 0)
                    return true;
                return false;
            }

            // returns the X value of the line end with the largest X coordinate
            private double MaxX()
            {
                return MidpointX + (Math.Sin(Math.PI * Angle / 180.0) * 0.5);
            }

            private double MinX()
            {
                return MidpointX - (Math.Sin(Math.PI * Angle / 180.0) * 0.5);
            }
        }

        private static readonly int SIZE = 5000;
        private const double NeedleLength = 1.0;
        private long NeedlesCount { get; }
        private List<Needle> needles;

        public BuffonsNeedles(long samples = 1000000)
        {
            // Possible problems with collections of greater than Int.MaxValue elements in older .net versions
            if (samples > UInt32.MaxValue)
            {
                Console.WriteLine($"Warning : samples used was greater than {UInt32.MaxValue}! sample size is being set to this value");
                samples = UInt32.MaxValue;
            }
            NeedlesCount = samples;
            initialise();
        }

        public float RatioIntersecting()
        {
            var intersecting = (from n in needles where n.Crosses2N() select n).Count();
            return needles.Count() / (float)intersecting;
        }

        private void initialise()
        {

            Random rnd = new Random();
            needles = new List<Needle>();

            for (long i = 0; i < NeedlesCount; i++)
            {
                int xint = rnd.Next(SIZE);
                double xfraction = rnd.NextDouble();

                double angle = rnd.NextDouble() * 180;
                Needle res = new Needle { MidpointX = xint + xfraction, Angle = angle };

                needles.Add(res);
            }
        }
    }
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

On 5/2/2016 at 3:15 PM, ShayMaster [PC Noob] said:

Need help with programming.

Hi guys I have a question, how can I make a Keylogger through Python, I know there are many tutorials on YouTube but I have tried them to no avail. If anyone could help me it would be appreciated. I don't want to download one as the recorded logs could be sent to a server; and I'll have no control over them. The use of the Keylogger will not be illegal. Thanks.

So I wouldn't know how to do this but I imagine pygame could be useful, just to detect inputs.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...
On 5/2/2016 at 9:15 AM, ShayMaster [PC Noob] said:

Need help with programming.

Hi guys I have a question, how can I make a Keylogger through Python, I know there are many tutorials on YouTube but I have tried them to no avail. If anyone could help me it would be appreciated. I don't want to download one as the recorded logs could be sent to a server; and I'll have no control over them. The use of the Keylogger will not be illegal. Thanks.

If you still need help PM me and I'll see if I can help. I'm working on one of my own atm

  Christian 

 

Use the following style specs in your sig to spread the LTT revolution!

Rig Specs:

Screeninator: Gigabyte GeForce GTX960

Powermathingy: Corsair CX600W

Stickiminator: 2x G.Skill ARES 4GB DDR3-1866

Procrastinator: AMD FX-8350 @4.1GHz 1.3V

Holdametalicizor: DIYPC Gamemax-BK

Noisoundacreator: Cyber Acoustics CA-3072 (loudamagargle) Onn Wireless FM Radio Headset (earamagargle)

Attachamathingy: ASRock 990FX Extreme9

Remembrerthing: Western Digital 1TB Blue, Western Digital 40GB Blue

Flat-Colorful-Thing: Acer K272HL

See-A-Move-O: Logitech Hyperion Fury G402

ButtonBoard: Cooler Master CMSTORM Devastator Blue

Talkamagargle: Blue Snowball Ice

 

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Simple .NET C# Sieve of Eratosthenes. Decent practice. I'll update it later to make use of classes (class for sieve generator, one for counter, one for summing... whatever) The attached file is a .doc file with the correct syntax highlighting.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Under100Lines
{
    class Program
    {
        static void Main(string[] args)
        {
            start:
            Console.WriteLine("How many primes do you want to solve?");

            int upperLimit = Convert.ToInt32(Console.ReadLine());
            int optimizeMe = Convert.ToInt32(Math.Sqrt(upperLimit));
            int primeCounter = 0;
            int largestPrime = 0;
            int sumPrimes = 0;
            int productPrimes = 1;

            bool[] seiveContainer = new bool[upperLimit];

            Array.Clear(seiveContainer, 0, upperLimit);

            for (int i = 2; i <= optimizeMe; i++)
            {
                if (seiveContainer[i] == false)
                {
                    for (int j = 2; j * i < upperLimit; j++)
                    {
                        seiveContainer[j * i] = true;
                    }
                }

            }

            for (int i = 2; i < upperLimit; i++)
            {
                if (seiveContainer[i] == false)
                {
                    primeCounter += 1;
                    largestPrime = i;
                    sumPrimes += i;
                    productPrimes *= i;
                }
            }

            Console.WriteLine("There are " + primeCounter + " primes." + "\n" + "The largest prime is " + largestPrime + "\n" + "The sum of the primes is " + sumPrimes + "\n" +
                                "The product of the primes is " + productPrimes + "\n" + "Would you like to list the primes? Y or N then ENTER");
            string writeList = Console.ReadLine();

            if (writeList.ToLower() == "y")
            {
                for (int i = 2; i < upperLimit; i++)
                {
                    if (seiveContainer[i] == false)
                    {
                        Console.WriteLine(i);
                    }
                }
            }

            goto start;

 

100LineChallenge.doc

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

On 5/27/2016 at 4:03 AM, straight_stewie said:

Simple .NET C# Sieve of Eratosthenes. Decent practice. I'll update it later to make use of classes (class for sieve generator, one for counter, one for summing... whatever) The attached file is a .doc file with the correct syntax highlighting.

Hmmm...

#include <bits/stdc++.h>
static const int N=0x989680;
bool v[N];
int main() {
    std::fill(std::begin(v)+2,std::end(v),1);
    for(int i=3;i<=N;i+=2)
        if(v[i])
            for(int k=2;k*i<=N;++k)
                v[k*i]=0;
}

(N is 10'000'000)

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

Link to comment
Share on other sites

Link to post
Share on other sites

37 minutes ago, Nineshadow said:

--snip--

I much prefer look up tables.

import requests
def is_prime(n):
    data = {'numberInput': str(n)}
    return requests.post('http://compoasso.free.fr/primelistweb/page/prime/liste_online_en.php', data).text.find('>{}<'.format(n)) != -1

N <= 1,000,000,000,000

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, fizzlesticks said:

I much prefer look up tables.

Someone has to understand how the lookup tables are generated so that there can continue to be lookup tables!

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

Decided to do some Python for a bit of automation stuff on servers, and I made a library for multi-segmented downloading from FTP servers. I don't really know Python so let me know what I'm doing wrong. https://github.com/MarkPash/pash-ftp/blob/master/pash_ftp.py

import ftplib
import os
import threading
import shutil


class Downloader:
    def __init__(self, ftp_server = '', ftp_user = '', ftp_password = ''):
        if ftp_server is not '':
            self.connect(ftp_server, ftp_user, ftp_password)

    def connect(self, ftp_server, ftp_user, ftp_password = ''):
        self.ftp_server = ftp_server
        self.ftp_user = ftp_user
        self.ftp_password = ftp_password
        self.ftp = ftplib.FTP(self.ftp_server, self.ftp_user, self.ftp_password)

    def download(self, ftp_file_path, threads):
        self.ftp_file_path = ftp_file_path
        self.parts = threads
        self.ftp_file_size = self.ftp.size(self.ftp_file_path)
        self.chunk_size = self.ftp_file_size/self.parts
        self.last_chunk_size = self.ftp_file_size - (self.chunk_size * (self.parts - 1))

        partdownloaders = []
        for part in range(self.parts):
            if part == (self.parts - 1):
                this_chunk_size = self.last_chunk_size
            else:
                this_chunk_size = self.chunk_size
            ftp = ftplib.FTP(self.ftp_server, self.ftp_user, self.ftp_password)
            partdownloaders.append(DownloadPart(ftp, self.ftp_file_path, part, self.chunk_size * part, this_chunk_size))
        for part in partdownloaders:
            part.thread.join()
        with open(os.path.basename(self.ftp_file_path), 'w+b') as f:
            for downloader in partdownloaders:
                shutil.copyfileobj(open(downloader.part_name, 'rb'), f)
        for part in partdownloaders:
            os.remove(part.part_name)


class DownloadPart:
    def __init__(self, ftp, ftp_file_path, part_number, part_start, part_size):
        self.ftp = ftp
        self.ftp_file_path = ftp_file_path
        self.ftp_file = os.path.basename(self.ftp_file_path)
        self.part_number = part_number
        self.part_start = part_start
        self.part_size = part_size
        self.part_name = self.ftp_file + '.part' + str(self.part_number)
        self.thread = threading.Thread(target=self.receive_thread)
        self.thread.start()

    def receive_thread(self):
        try:
            self.ftp.retrbinary('RETR ' + self.ftp_file_path, self.on_data, 100000, self.part_start)
        except:
            pass

    def on_data(self, data):
        with open(self.part_name, 'a+b') as f:
            f.write(data)
        if os.path.getsize(self.part_name) >= self.part_size:
            with open(self.part_name, 'r+b') as f:
                f.truncate(self.part_size)
            raise

 

Comb it with a brick

Link to comment
Share on other sites

Link to post
Share on other sites

Emulates a toggle switch with a momentary switch

 


int buttonPrev = 0;
int state = 0;

 

while(true)
{
    if ((button != buttonPrev) && button != 0)
    {
        state = !state;
    }
    buttonPrev = button;
}

Link to comment
Share on other sites

Link to post
Share on other sites

Hey,

 

Powershell script i quickly wrote for a client school. Their SMS system does not create students automatically and they use Google directory sync and google password sync to sync users into google apps.

 

The script can be improved greatly and will be when I can be bothered / have time.

 

The script will import an CSV with all the student information, First name, last name, email address and password etc, the default user scripts are currently hard coded in the script. script base config can be changed with a config csv that lists the domain name, creation OU and a few other details.

 

The script does the following

 

  1.  Imports all details required for user creation
  2. creates all users from csv into the OU listed in the config csv
  3. creates the user a home drive for folder redirection
  4. gives the user modify rights on said folder
  5. syncs google directory sync(runs as another user due to how we have their site setup), waits for sync to complete
  6. resets user password to what it was in the csv to force google password sync to sync
  7. script outputs to a log file for basic debugging
  8. renames the user import csv to the date and moves it into a old folder

 


# SCHOOL NAME Student Usercreator.
# Rhys Jeffery
# New Era IT
# 24/05/2016

Import-Module ActiveDirectory

# Importing Users fro Template CSV in CSV-Import.
$ul = import-csv ".\CSV-Import\User Template.csv"
$ulp = ".\CSV-Import"

# Importing Configuration Data from Configuration.
$config = import-csv ".\Configuration\config.csv"

# Setting Default Config
$path = $config.path
$homedir = $config.hd
$domain = $config.domain
# Add all default groups for all users being created
$groups = @(“Students")

# Imports each user, and users pulled informaton to create AD objects, assign groups and create home drive.
ForEach($User in $ul)
{
    $s = $user.Username
    $f = $user.FirstName
    $l = $user.LastName
    $fn = $f + " " + $l
    $dn = $user.DN
    $e = $user.Email
    $p = $user.Password
    $hd = Join-Path $homedir -childpath $s
    $upn = $user.Email
    $date = Get-Date
    $dt = "User Created @ $date By Usercreator"

    $check = Get-ADUser -Filter {sAMAccountName -eq $s}
    If ($check -eq $Null) {
        write-output $s "AD Account Created @ " $date  | out-file .\log.txt -Append
        New-ADUser `
        -Name $s `
        -GivenName $f `
        -Surname $l `
        -SamAccountName $s `
        -DisplayName $fn `
        -EmailAddress $e `
        -Path $path `
        -Description $dt `
        -PasswordNeverExpires $true `
        -CannotChangePassword $true `
        -ChangePasswordAtLogon $false `
        -UserPrincipalName $upn `
        -AccountPassword (ConvertTo-SecureString –AsPlaintext $p -Force) `
        -Enable $true

        ForEach($Group in $Groups){Add-ADGroupMember -Identity $Group -Members $s}
        }
    Else {}

    if(!(Test-Path -Path $hd )){
        write-output $s "Home Drive Created @ " $date  | out-file .\log.txt -Append
        New-Item -ItemType directory -Path $hd
        write-output $s "Home Drive Permissions Set @ "$date  | out-file .\log.txt -Append
        $acl = Get-Acl $hd
        $permission = "$domain\$s","Modify","ContainerInherit, ObjectInherit", "None","Allow"
        $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
        $acl.SetAccessRule($accessRule)
        $acl | Set-Acl $hd
        }    
}

write-output $s  "Google Apps Sync Started @ " $date  | out-file .\log.txt -Append
$arg = "C:\Program Files\Google Apps Directory Sync\Xml\GADSXML.xml"
$params = @("-a -c `"$arg`"")
$credential = New-Object System.Management.Automation.PsCredential("Domain\account", (ConvertTo-SecureString "PasswordHere" -AsPlainText -Force))

Start-Process -Credential $credential -Filepath "C:\Program Files\Google Apps Directory Sync\Sync-cmd.exe" -ArgumentList $params -NoNewWindow -Wait

Wait-Process Sync-cmd
write-output $s "Google Apps Sync Completed @ " $Date  | out-file .\log.txt -Append

ForEach($User in $ul){
$s = $user.Username
$p = $user.Password
$check = Get-ADUser -Filter {sAMAccountName -eq $s}
    If ($check -ne $Null) {
        Set-ADAccountPassword -identity $s -reset -newPassword (ConvertTo-SecureString –AsPlaintext $p -Force)
        write-output $s "Password Reset @ " $Date  | out-file .\log.txt -Append
    }
}
move-item "$ulp\User Template.csv" ("$ulp\old\{0:ddMMyyyy}.log" -f (get-date))

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


×