Posts by @intersex (239)

@intersex's profile photo

I've written code to translate this website from any language that people will see posts in your language.


@intersex, likes this, one comment.

intersex's profile photo

Uglek also now displays the language of posts.

@intersex's profile photo

A Simple Jumping Game in JavaScript with CreateJS and TweenJS This is the code for the game at uglek.com/post/150/. This game is a simple game focused on tapping, the challenge is to jump over the square without turning blue (by tapping at the right time). I have commented the code below so you can see what's going on in the game.

// Jasper Camber Holton, Uglek, 2021
function getRandomInt(max) { // Random integer
    return Math.floor(Math.random() * max);
}
function init() {
    var last = 0; // Last time we tapped the screen
    var stage = new createjs.Stage("game"); // New stage
    stage.on("stagemousedown", function(evt) { // On mousedown (click, tap or touch)
        if (createjs.Ticker.getTime() > last + 1000) { // If it has been 1 second since we jumped
            createjs.Tween.get(circle, { // Animate jump
                    loop: false
                })
                .to({
                    y: 50
                }, 350, createjs.Ease.getPowInOut(4))
                .to({
                    y: 160
                }, 300, createjs.Ease.getPowInOut(2));
            last = createjs.Ticker.getTime();
        }
    });
    circle = new createjs.Shape(); // New player (circle)
    circle.graphics.beginFill("red").drawCircle(0, 0, 20);
    // Set position
    circle.x = 50;
    circle.y = 160;
    // Add Shape instance to stage display list.
    stage.addChild(circle);
    // Update stage will render next frame

    var rect = new createjs.Shape(); // Create new enemy rectangle
    rect.graphics.beginFill("red").drawRect(0, 0, 20, 20);
    // Set position 
    rect.x = 300;
    rect.y = 160;
    // Add Shape instance to stage display list.
    stage.addChild(rect);

    var hit; // Whether the player was hit
    var score = 0; // Keep track of a score
    var text = new createjs.Text("Score: 0", "15px Arial", "#000000"); // Score text
    text.x = 10; // Positioning
    text.y = 10;
    stage.addChild(text); // Add to stage

    var high = 0; // High score
    var text2 = new createjs.Text("High: 0", "15px Arial", "#000000"); // Score text
    text2.x = 100; // Positioning
    text2.y = 10;
    stage.addChild(text2); // Add to stage
    function handleTick(event) { // Game loop
        rect.x = rect.x - 2; // Move the enemy
        if (rect.x < -20) { // If it's off screen, move it back
            rect.x = 300 + getRandomInt(200);
            circle.graphics.beginFill("red").drawCircle(0, 0, 20); // Fill circle red
            if (hit) { // If the player is hit
                if (score > high) { // Reset high score
                    high = score;
                    text2.text = "High: " + high;
                }
                score = 0; // Reset score and text
                text.text = "Score: " + score;
            } else { // Increment score
                score = score + 1;
                text.text = "Score: " + score;
            }
            hit = false; // Set hit to false
        }
        if (rect.x > 45 && rect.x < 50 && circle.y > 120) { // Check if player is in bounds to be hit
            circle.graphics.beginFill("blue").drawCircle(0, 0, 20);
            hit = true;
        }
        stage.update(); // Update the stage
    }
    stage.update();
    createjs.Ticker.setFPS(60);
    createjs.Ticker.addEventListener("tick", stage);
    createjs.Ticker.addEventListener("tick", handleTick);
}
init(); // Initialize
The game, as generated, is pictured below.

View the photo from a post by @intersex

@intersex's profile photo

Asynchronous Database Driven Email Daemon and Client for Django Websites I created a Django site in 2020. One of the things I have needed for this site for a while is a good email editor and scheduler, so I can edit, see, and schedule emails for the site on the go, and they are sent out automatically on time. I wrote some software to do just this. The first part of the code is a database model. This stores the email and passes it to the daemon. It contains a send at date and time, recipients list, subject, HTML content, and a method which calls the send email function.

# app/models.py
class ScheduledEmail(models.Model):
    id = models.AutoField(primary_key=True)
    recipients = models.ManyToManyField(User, related_name='email_recipients')
    send_at = models.DateTimeField(default=timezone.now)
    subject = models.CharField(blank=True, max_length=100, default='')
    html_content = models.TextField()
    def send(self):
        send_users_email(self.recipients.all(),self.subject,self.html_content)
This next part is the daemon. This is included in __init__.py of the new app tasks (python manage.py startapp tasks) and imported in the apps.py
# tasks/__init__.py
import threading
import time
from blog.models import ScheduledEmail
import datetime
from django.template import Template, Context
def elapsed_minute(): # Get time elapsed since last minute
    now = datetime.datetime.now()
    time1 = now
    time2 = now
    time2 = time2.replace(second=0,microsecond=0)
    return (time1-time2).total_seconds()
def send_pending_emails(): # Send emails due for sending
    emails = ScheduledEmail.objects.filter(send_at__lt=datetime.datetime.now())
    for email in emails:
        email.send()
        email.delete()
def async_tasks(): # Run tasks asynchronously
    sleep_time = 60 - elapsed_minute() # Seconds left in minute
    time.sleep(sleep_time) # Sleep until the turn of the minute
    while True:
        send_pending_emails()
        time.sleep(60)
def start_async(): # Start a new thread for our tasks
    async_thread = threading.Thread(target=async_tasks, name="Uglek async tasks", args=())
    async_thread.start()
This is initialized in the AppConfig, by calling the method
# app/apps.py
import sys
...
from tasks import start_async, send_pending_emails, async_tasks
if not ('shell' in sys.argv or 'migrate' in sys.argv or 'makemigrations' in sys.argv):
    start_async()
Putting this together, you can asynchronously send a scheduled email with the following code:
# wherever you send email
email = ScheduledEmail.objects.create(send_at=dateandtime, subject=subject, html_content=html) # Create a new scheduled email
email.recipients.set(users) # Set the recipients to a list of users
email.save() # Save the email to the database
I hope this is useful as a solution for sending emails asynchronously. Below is a photo of a simple HTML email sending client I created using JavaScript. I can use this client to email subscribers on this site.

View the photo from a post by @intersex

@intersex's profile photo

A spiderweb spotted while hiking in Washington state This spiderweb was by the side of a trail and I managed to snap an awesome photo of it in focus. I am always looking for beautiful natural photos like this to take and post here.

View the photo from a post by @intersex

@intersex's profile photo

This is a hat I made with embedded LEDs I made this LED hat using the Arduino Mega as a microcontroller and shift registers to control the LEDs. I created this hat back in 2013 and I still do projects like this. I have moved mostly to writing code instead of working with embedded electronics but I plan to work more with electronics in the near future and make some cool LED stuff. Light-up electronics are an awesome thing to build myself, especially because I do 3D design and I have a 3D printer.

View the photo from a post by @intersex

@intersex's profile photo

Uglek will be undergoing scheduled maintenance in the process of moving over to a new server. This maintenance will occur between Saturday, October 23, and Sunday, October 24, 2021. The site may be offline or inaccessible, and the mail server may not be working until maintenance is completed. Please stand by for this scheduled maintenance. The purpose of this maintenance is to migrate to a new server that will be more expandable and reliable. Thank you for your cooperation.


one comment.

intersex's profile photo

Scheduled maintenance is completed. Thank you.

@intersex's profile photo

A photo from the hike to Summit Lake This hike is beautiful in the fall colors and sun. I thought this was an especially nice photo to share because of the natural beauty of the trail.

View the photo from a post by @intersex

@AussieinthePNW, likes this,

@intersex's profile photo

Highlight Your Code With a Django Regex Template Filter This is a Django template filter that uses python regex to highlight code. It works by using regular expressions to get all occurrences of code beginning with *(language)* followed by ***, in this example, (python) for the language. It then takes the code from these and including the language and formats it for an embed using PrismJS.com. The comments explain what each line of code does. In the below example, the *\** is escaped with concatenation (same with the HTML) to prevent it from messing up the template filter. One drawback of this is it does mean you can't use three stars (*) anywhere on a post with embedding (that's why I have it escaped).

@register.filter(name='embedcode') # Register the filter
def embedcode(value):
    sections = value.split("**" + "*") # Split by sections of code followed by delimiter
    rvalue = "" # Init return value
    for index, section in enumerate(sections): # Enumerate over the code blocks
        if index < len(sections)-1: # Add delimiter except for last block
            section = section + "**" + "*"
        scripts = re.findall(r"(\*\((\w+)\)\*([\d\D]+)\*\*\*)", section) # Three groups, a main group for the entire text, sub groups for language and code.
        dic = {} # Empty dictionary for find and replace
        for script in scripts: # Iterate through the scripts, get the language and code
            language = script[1]
            code = script[2]
            if language != 'language':
                dic[script[0]] = '<' + 'pre>' + '<' + 'code class=\"language-' + language + '\">' + code + '<' + '/code><' + '/pre>' # Add the embed code to the dictionary with the main group, language and code
        for i, j in dic.items(): # Find and replace
            section = section.replace(i, j)
        rvalue = rvalue + section
    return rvalue
Below is a photo of the regex in action.

View the photo from a post by @intersex

@intersex's profile photo

I added code embeds so now I can show off code directly on the site. I'm not supporting every language to start with, but a lot of languages are already supported. To add code, use *(language)* before the code you want to embed, and *** after the code. For example, here is some code below.

// Reload the suggested posts div with more posts
function reloadSuggested(){
    $.ajax({
    url : "/suggested/",
    success : function(result){ 
    document.getElementById("suggested").innerHTML = result;
        $('#reloadsuggested').on('click', reloadSuggested);
      }
    });
}
$('#reloadsuggested').on('click', reloadSuggested);


@intersex's profile photo

I forgot to post when I added it, but you can make rainbow elements in Uglek posts by adding class="rainbow" to any tag. The below is a paragraph (p) tag with a rainbow class.

Here's an example. This is some rainbow text. This is some more rainbow text so you can truly see the rainbow effect. It works better with more text.


© Uglek, 2022

Terms of Use and Privacy Policy