Return to Level1Techs.com

Post your coding projects

programming

#182

Putting probability and theory to the test.

Tests to see if the probability of winning a basic straight “Pick 3” lottery is in fact (1/10)^3.

Horsing around with some function JS

`        //Generate a combo
    function generateCombo(numBalls){
            let localArr = [];

            for (var i = 0; i<numBalls; i++)
                    localArr.push(Math.floor(Math.random() * 10));

            return localArr;
    }

    //used to see if our ticket matches winner
    //compares two arrays
    function compareArrs(arrX, arrY){
            let areEqual = true;

            if(arrX.length == arrY.length){
                    for(var i = 0; i < arrX.length; i++){
                            if(arrX[i] != arrY[i])
                                    areEqual = false;
                    }
            } else
                    areEqual = false;

            return areEqual;

    }

    //Play using recursion
    //WARNING CAN OVERFLOW MEMORY LIMIT
    function recurPlay(numBalls,iterator){
            let myTicket = generateCombo(numBalls); // Generate our Lotto Ticket
            let winningCombo = generateCombo(numBalls); // Generate winning comobo

            let didWeWin = compareArrs(myTicket, winningCombo);

            if (didWeWin == true){
                    console.log("Won");
                    console.log(myTicket + " : " + winningCombo + " : " + iterator);
            } else {
                    iterator++;
                    return recurPlay(numBalls,iterator);
            }

            return iterator;
    }

    //Play using a loop
    function loopPlay(numBalls,iterator){

            let didWeWin = false;

            do {
                    let myTicket = generateCombo(numBalls); // Generate our Lotto Ticket
                    let winningCombo = generateCombo(numBalls); // Generate winning comobo

                    didWeWin = compareArrs(myTicket,winningCombo);
                    iterator++;
            }
                    while (didWeWin == false);

            return iterator;

    }


    function findAverage (iterations, numBalls){
            let localArr = [];
            let runningTotal = 0;

            for (var i = 0; i < iterations; i++){
                    //runningTotal += recurPlay(numBalls,0);
                    runningTotal += loopPlay(numBalls,0);
            }

            console.log(runningTotal/iterations);

    }

    //findaverage(numberOfIteration, numberOfBalls);
    findAverage(1000, 4);

`

**Edit or pick 4 — whatever, just change the second arguement on the findav func at the bottom. Test “Pick 45” if you want -


#183

JS Script implementation of a Graham Scan.

In other words it randomly generates points for a scatter plot “Graph” and then returns the convex hull using a Graham Scan.

It still needs logic for instances for collinear points. So that’s a bug I have to fix, but whatever…

/generates points
    function generatePoints(numOfPoints, max){
            var numPoints=numOfPoints;
            var max = max + 1;
            var pointArray=[];

            for (var i = 0; i < numOfPoints; i++){
                    var x = Math.floor(Math.random() * max);
                    var y = Math.floor(Math.random() * max);
                    var arcTan = 0;

                    var point = {x,y,arcTan};

                    pointArray.push(point);
            }
            
            return pointArray; 
    }
//sort points based on y-coordinate
//if tie, lower x-coordinate is first
        function yAscendSort(listOfPoints){
                var listOfPoints = listOfPoints;
                var sortedPoints = listOfPoints.sort(function(a,b){
                        // return a.x - b.x;
                        return a.y < b.y ? -1 : a.y > b.y ? 1 : a.x < b.x ? -1 : a.x > b.x ? 1 : 0;
                })
                        return sortedPoints;
        }

// returns anchor point of Graph
        function getAnchorPoint(points){
                var points = points;
                var anchorPoint = points.shift();

                return anchorPoint;
        }

    function setArctan(points, anchorPoint){
            var points = points;
            var anchorPoint = anchorPoint;
            for ( var i = 0; i < points.length; i++ ){
                    points[i].arcTan = Math.atan2(points[i].y - anchorPoint.y, points[i].x - anchorPoint.x)
            }
    }

    function sortArctan(points){
            var points = points;
            var sortedPoints = points.sort(function(a,b){
                    return a.arcTan - b.arcTan;
            })
                    return sortedPoints;
    }

    function getHull(anchorPoint,points){
            var hull = [];
            var anchorPoint = anchorPoint;
            var points = points;

            hull.push(anchorPoint);
            hull.push(points.shift());
            hull.push(points.shift());
            
            for( var i = 0; i < points.length; i++) {
                    hull.push(points.shift());
                    var a = hull[hull.length-3];
                    var b = hull[hull.length-2];
                    var c = hull[hull.length-1];

                    function direction(a,b,c){
                            return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);
                    }
                    
                    var result = direction(a,b,c);
                    if (result < 0){
                            hull.pop(c);
                    }
            }
            console.log("The Convex Hull");
            console.log(hull);
    }


    var points = generatePoints(10, 15);
    yAscendSort(points);
    var anchorPoint = getAnchorPoint(points);
    setArctan(points, anchorPoint);
    sortArctan(points);
    getHull(anchorPoint,points);

#184

Just landed a gig making a custom slackbot to handle internal automation tasks.


#185

So close to being done with addition and subtraction in my program which handles big integers. I’ve got one more scenario to code which is (-a)-(-b) where a < b which is very fustrating since I can’t determine the value of a or b


#186

Goofy little “system analyzer” tool we built. My friend wanted to learn Python, so I suggested we work on this together. He got impatient, and just wrote the PowerShell, so I wrote all the Python and Bash lol :man_shrugging:

import platform

import nix as bash
import powershell as posh



def show_win_menu():
    # Prints Menu for PowerShell items
    print("1. Get Event Logs")
    print("2. CPU Info")
    print("3. Disk Info")
    print("4. RAM Info")
    print("5. Network Info")
    print("6. Quit")

def show_nix_menu():
    # Prints Menu for Unix/Linux items
    print("1. Show OS")
    print("2. Network Info")
    print("3. RAM Info")
    print("4. Users")
    print("5. Disk Info")
    print("6. Quit")

def main():
    # platform.system() returns an OS variable and stores it in op_sys
    # Based on the value returned, the Windows or Linux loops will run
    op_sys = platform.system()
    if op_sys == 'Windows':
        while True:    
            show_win_menu()
            option = int(input("Enter menu selection: "))
            if option == 1:
                posh.get_event_logs()
            elif option == 2:
                posh.cpu_info()
            elif option == 3:
                posh.disk_info()
            elif option == 4:
                posh.ram_info()
            elif option == 5:
                posh.network_info()
            elif option == 6:
                break

    elif op_sys == 'Linux' or op_sys == 'Linux2':
        while True:
            show_nix_menu()
            option = int(input("Enter menu selection: "))
            if option == 1:
                bash.os_info()
            elif option == 2:
                bash.network_info()
            elif option == 3:
                bash.memory_info()
            elif option == 4:
                bash.users()
            elif option == 5:
                bash.disk_info()
            elif option == 6:
                break

main()
"""
	Functions for the different PowerShell scripts. 
"""
    
def get_event_logs():
	posh.call([
		"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", 
		"-ExecutionPolicy", "Bypass", '-Command', 
		'. "PowerShell/GetEventLogs.ps1";', '&GetEventLogs'
	])


def ram_info():
    posh.call([
    	"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", 
    	"-ExecutionPolicy", "Bypass", '-Command', 
    	'. "PowerShell/RamMgmt.ps1";', '&Get-RAMSize'
    ])

    posh.call([
    	"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", 
    	"-ExecutionPolicy", "Bypass", '-Command', 
    	'. "PowerShell/CurrentRAMUsage.ps1";', '&CurrentRAMUsage'
    ])


def cpu_info():
    posh.call([
    	"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", 
    	"-ExecutionPolicy", "Bypass", '-Command', 
    	'. "PowerShell/CPUTracker.ps1";', '&CPUTracker'
    ])


def disk_info():
    posh.call([
    	"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", 
    	"-ExecutionPolicy", "Bypass", '-Command', 
    	'. "PowerShell/DiskMgmt.ps1";', '&Get-DiskStats'
    ])


def network_info():
	posh.call([
		"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", 
		"-ExecutionPolicy", "Bypass", '-Command', 
		'. "PowerShell/NetworkMgmt.ps1";', '&NetProtocols'
	])

	posh.call([
		"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", 
		"-ExecutionPolicy", "Bypass", '-Command', 
		'. "PowerShell/TCPConnectionsMgmt.ps1";', '&TCPConnectionsMgmt'
	])
"""The module for running Bash Scripts"""
import subprocess as s

shell = True

def memory_info():
    s.call("Bash/memory.sh", shell)



def os_info():
    s.call("Bash/os.sh", shell)


def network_info():
    s.call("Bash/network.sh", shell)


def disk_info():
    s.call("Bash/disk_info.sh", shell)


def users():
    s.call("Bash/users.sh", shell)

Obviously missing are the scripts and PowerShell functions, but I didn’t want a wall of text. I always over engineer Python, I think, because I want everything in a function.

Working on Django to have web dashboards and graphs. Going to mess with PyQt as well to have a desktop GUI. I’m having more fun with it than he is lol. .NET nubs :grin:


#187

I spent the weekend getting started with Vulkan with MoltenVK. I used to do some OpenGL, so I was not completely clueless. It took me all weekend to get a triangle on the screen though!

I was feeling inspired by a talk by Sean Parent where he put forth the goal to avoid raw loops in your code. To that end, I decided it would also be good to get a little more experience using Boost, so I figured out how to do every for-loop from the tutorial I was following using algorithms from the Boost ranges library. The lambda functions are a little cumbersome (having to explicitly list captures), but I do like the overall result. It is clear at a glance when the use of an algorithm is correct, where it would take some staring to figure out if a loop is right.

    bool checkValidationLayerSupport() {
        uint32_t layerCount;
        vkEnumerateInstanceLayerProperties(&layerCount, nullptr);

        std::vector<VkLayerProperties> availableLayers(layerCount);
        vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());

        boost::sort(availableLayers, CmpByName::lt);

        return boost::includes(availableLayers, validationLayers, CmpByName::lt);
    }

The CmpByName thing is a pretty neat thing I came up with to deal with the fact that availableLayers is a vector of VkLayerProperties while validationLayers is a vector of C-strings. Here’s my definition of it:

    struct CmpByName {
        std::string name;

        CmpByName(char const* const& n) : name(n) {}
        CmpByName(VkExtensionProperties const& p) : name(p.extensionName) {}
        CmpByName(VkLayerProperties const& p) : name(p.layerName) {}

        bool operator < (CmpByName const& other) const {
            return name < other.name;
        }

        static bool lt(CmpByName const& lhs, CmpByName const& rhs) {
            return lhs < rhs;
        }
        static bool eq(CmpByName const& lhs, CmpByName const& rhs) {
            return !(lhs < rhs || rhs < lhs);
        }
    };

As you can see, I’ve reused this for multiple structs. The overloaded constructors means that the library algorithms can easily compare values of different types, and I don’t have to pollute the code with those nuances everywhere.

The Boost ranges really make the code more palatable. I don’t think I would be so content if this had to specify.begin() and .end() for everything:

        auto destroyFence = [this](auto const& fence) {
            vkDestroyFence(device, fence, nullptr);
        };
        boost::for_each(inFlightFences, destroyFence);

        auto destroySemaphore = [this](auto const& semaphore) {
            vkDestroySemaphore(device, semaphore, nullptr);
        };
        boost::for_each(renderFinishedSemaphores, destroySemaphore);
        boost::for_each(imageAvailableSemaphores, destroySemaphore);

        vkDestroyCommandPool(device, commandPool, nullptr);

        auto destroyFramebuffer = [this](auto const& framebuffer) {
            vkDestroyFramebuffer(device, framebuffer, nullptr);
        };
        boost::for_each(swapChainFramebuffers, destroyFramebuffer);

One big time sink was that GLFW for some reason was not detecting MoltenVK and the plugins correctly, so I ended up rewriting the part of GLFW that hooks up the system window with the Vulkan surface extension. That involved duplicating some of the private GLFW structs to get a some members behind opaque objects, and the gist of it boils down to this one little Objective-C++ function:

VkResult
createWindowSurface(VkInstance instance,
                    GLFWwindow* window,
                    VkAllocationCallbacks const* pAllocator,
                    VkSurfaceKHR* pSurface) {
    auto w = reinterpret_cast<_GLFWwindow*>(window);
    w->ns.layer = [CAMetalLayer layer];
    if (!w->ns.layer) {
        std::cerr << "Cocoa: Failed to create layer for view";
        return VK_ERROR_EXTENSION_NOT_PRESENT;
    }

    [w->ns.view setWantsLayer:YES];

    VkMacOSSurfaceCreateInfoMVK createInfo = {
        .sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK,
        .pView = w->ns.view
    };

    return CreateMacOSSurfaceMVK(instance, &createInfo, pAllocator, pSurface);
}

By the way, those XXXCreateInfo structs are everywhere in Vulkan. The guide I was following always initialized the structs as empty and then individually set each field, but I much prefer the inline initialization style. The code is far less cluttered that way (though I could have thrown in some comments or whitespace for grouping).


#188

A friend of mine has a need for backing up a single text file of ~20 tablets to a server

I used python
Haven’t tried with android or iOS (or finished the documentation…) yet but works with linux and it’s async af


#189

Took a sabbatical from ‘coding’ and learning frameworks to prioritize my time on going ‘back to the basics.’

The three distinct areas I’ve decided to focus on are:

  • Data Structures && Algos < - (Data Structs in C and Algos using in a few scripting languages and Java)
  • Object Oriented Design Patterns (Java)
  • Maths (Heavily on Graph and Set Theory) <- Python

This time completely shifted my approach when using code to solve problems. A big one ‘light bulb moment’ happened quickly after constructing several data structures in C. I quickly gained an appreciation for Java’s prebuilt data structure Classes and Interfaces. And, although, I’m not an expert , yet; I am much more confident in what I do when I code. I no longer ‘just code out the problem’ — now, I see myself applying principles of science to problem solving with computer code.

Overall, I’m about 60% where I want to be. The crazy part is I’ve been programming for about 5 years, but the past four months advanced more than all those years.

I slated another two months for this, and I’m feeling really good about where I’m going to be, but I just need to stay focused on my plan.


#190

Thanks for the update cotton.


#191

If you want something in the same vein, look at generalized inner and outter tensor products to solve general problems in a parallel manner. It’s wild.


#192

Hello my fellow hackers -

I’m having a bit of an issue with a linked list data structure. I’ve refactored this a couple of times and can’t seem to spot the bug.

Basically, I think there’s an issue with the “insert_at_end” method in the LL class. When I use the insert_at method and try to insert before an index that was inserted by “insert_at_end” it always appends after it rather than before it.

Any thoughts?

class Node
    def initialize data, ptr_next = nil
            @data = data
            @ptr_next = ptr_next
    end

    def set_next node
            @ptr_next = node
    end
    def get_next
            @ptr_next
    end

    def next?
            [email protected]_next
    end

    def display
            puts @data
    end

end

class LL
    def initialize data
            @head = Node.new(data, nil)
            @length = 1
    end

    def display
            current = @head
            while (!current.next?)
                    current.display
                    current = current.get_next
            end
            current.display
    end

    def insert_at_end data
            current = @head
            tmp = Node.new(data, nil)
            while (!current.next?)
                    current = current.get_next
            end
            current.set_next(tmp)
            @length += 1

   end

    def insert_at_front data
            current = @head
            tmp = Node.new(data, nil)

            tmp.set_next(@head)
            @head = tmp

            @length +=1
    end

    def insert_at index, data
            current = @head
            tmp = Node.new(data,nil)
            iterator = 0
    #check if it's inbounds
            if(index <= @length)
                    if (index == 0)
                            insert_at_front(data)
                    elsif (index == @length)
                            insert_at_end(data)
                            puts "calling insert_at_end"
                    else
                            while (!current.next? && iterator < index)
                                    current = current.get_next
                                    iterator += 1
                            end
                            tmp.set_next(current.get_next)
                            current.set_next(tmp)

                            @length += 1
                    end
            else
                    puts "Index out of Range"
            end
    end


    def get_length
            return @length
    end
end

ll = LL.new(1)
ll.display
puts ll.get_length
puts "\n"

ll.insert_at(1,3)
ll.display
puts ll.get_length
puts "\n"

ll.insert_at(1,2)
ll.display
puts ll.get_length
puts "\n"

OutPut

1
1

calling insert_at_end
1
3
2

1
3   <----WRONG
2   <----WRONG
3

#193
  while (!current.next? && iterator < index)
          current = current.get_next
          iterator += 1
  end

When you’re adding 3, what does current point to when exiting this loop?

(I’m assuming you don’t just want some code that fixes your problem)


#194

I wrote a python script to generate a static blog. It does simple templating and markdown parsing to make the HTML and that’s about it.

https://bitbucket.org/redpandaua/turblog-py/src/master/


#195

Thanks for the feedback. I’ll dig into debugging this, but I’m stuck wondering why this is this easier to implement in C than Ruby?


#196

Is it really that much harder? I don’t really know C, but being able to work with pointers more liberally probably helps. That’s something you don’t really have in ruby.

What exactly is it that you find harder about it in ruby?


#197

Reinventing the wheel here and also still incomplete but I wanted to roll my own for funsies

Checks zpool status and emails you if it changes

edit:
less code, more link


#198

You might be interested in https://github.com/freenas/py-libzfs
I don’t see anything overtly FreeBSD specific about it, so if you’re trying to run on Linux as well it should be a fun thing to try out.


#199

No where near ready to post, but I am working on a C# project for a 7 Days to Die server manager. I know there are several out there, but the goal for me is to learn something about programming, as I am total newbie.

I have ping, port checking, SSH into the server, and server start code working. Before I go on, I need to think about credential security. I need to salt and hash the user password for SSH access to the server. I am going to work on this code when I get home.

The end goal is to have a Windows app that can manage both Windows and Linux servers.

I am making this a console app, just to get the base code working. After I have all of the features working, I will make a Forms app for it.

Wish me luck!


#200

did some documentation/quality of life improvements on the recursive file renaming things, and the thing to print the length of the filenames(as a chart), also added an option to print the entire directory(probably only useful for piping into a file to verify they are all the same length)

but was mostly just help texts with the old ‘-h’ to show syntax and some warnings especially on the delete characters one, in all caps lol


#201

The more C I use the more it just makes sense. You ask for something in C you get it. You need memory - ask. Need to point to something, ask for a pointer to something. Need to free memory - ask it. You get the idea.

Also, I’m noticing that it very clearly expresses what you want done - exactly. No smoke and mirrors or magic. It seems like you can very clearly express what you want done in the language, possibly making it very easy to understand someone else’s code.

It’s kind of a simple language - sort of.