Tuesday, October 16, 2012

MyBB Post BBCode Button Problem

I wanted to post this a couple days ago when the problem was brought to my attention at a forum I code for, but was too busy to get it up until now. The problem has a fix for it, here. I just want to go over quickly what is the cause of the problem and let people know it may effect Chrome and Opera. The fix was simply changing some variable names, so it wasn't anything too complicated.

So Firefox implemented something called Microdata API. This is a new thing for HTML5 that adds more information to your markup. The catch is, whether or not you are using HTML5, it still effects your site. It adds new DOM attributes that MyBB 1.6.8 is using. This particular one is itemData. That is now an object and due to the way the script was made for the post editor, it just screws it up. From what I've read, Chrome and Opera will be implementing them soon. I hope eventually it will be made to only effect HTML5 pages.

I have yet to read up how to use the Microdata API, but if you are interested, you can find notes on it here.

Friday, September 28, 2012

Haskell Network not found (Ubuntu)

So for a bit recently, I've been looking into Haskell. I really want to get into some functional programming. On thing I like doing is network programming because it actually gives me something extra to interact with than my own I/O or bugging a friend to help out or check something out. So I gave a quick glance at sockets and wanted to just see what the types look like on ghci, and of course it cannot find anything related to the network package.

> import Network.Socket

:
    Could not find module `Network.Socket':
      it is not a module in the current program, or in any known package.
Leaving GHCi.
$ ghc-pkg field network exposed-modules
ghc-pkg: cannot find package network

After a few minutes of banging my head against my desk, I say screw the gui package manager and just poke around with apt-cache search. Manage to find the library and for some reason, it was not installed by default. So here's what lead me to the package and the quick and easy fix for it.

$ apt-cache search haskell | grep network
libghc6-network-dev - Haskell network library for GHC
libghc6-network-doc - Haskell network library for GHC; documentation
libghc6-network-prof - Haskell network library for GHC; profiling libraries
$ sudo apt-get install libghc6-network-dev

Then problem solved, hoped over to ghci and it's there.

$ ghc-pkg field network exposed-modules
exposed-modules: Network Network.BSD Network.Socket.Internal
                 Network.Socket Network.URI
$ ghci
> :t Network.Socket.socket
Network.Socket.socket
  :: Network.Socket.Internal.Family
     -> Network.Socket.SocketType
     -> Network.Socket.ProtocolNumber
     -> IO Network.Socket.Socket
> 

So yeah, if you run into this, there you go. I think everyone looking into this can probably figure it out on their own, but if not, hopefully this helps. Edited the command stuff to just remove some information and lots of text in between.

Thursday, September 20, 2012

Recursive Fibonacci

So after bashing my head against the wall working on Fibonacci recursively and thinking "why on earth is this so slow," I realized the solution was reducing everything to a lot of ones and adding them all up. While addition and basic arithmetic for a CPU is exceptionally fast, this was slow due to the magnitude, and would cause way too much recursion for it to even be considered a correct solution. So I searched the web figuring someone far smarter than myself would have not only realized this, but come up with a real solution for it. Sure enough, I found one. The solution they used was in C, so I found it a bit ugly as it required two function calls (so you can call it with one argument). So I converted it to Haskell.

Before posting, the short explanation is this. Fibonacci numbers are found by adding up the previous two numbers. This is not to say you should call it inappropriately like this.

fib :: Integer-> Integer
fib 0 = 0
fib 1 = 1
fib x = fib (x - 1) + fib (x - 2)

However, this is often the solution I see in tutorials about recursion and very legitimate sources. I feel the reasoning for this is to use only one function call and as little code as possible to make an "elegant", or at least readable solution. The solution I found, while it is not the prettiest thing, it is far more efficient and very fast and after taking some time to really read it, makes far more sense true to the derivation of Fibonacci numbers. So here is the solution I found and converted to Haskell.

fib :: Integer-> Integer
fib 0 = 0
fib n =
    let
        fib2 1 _ n2 = n2
        fib2 x n1 n2 = fib2 (x - 1) n2 (n1 + n2)
    in
        fib2 n 0 1

Credit to the solution here. Glad to see people finding valid recursive solutions and letting people like myself know there's a better way.

Friday, July 27, 2012

Technical Speak (some thoughts and advice)

This post is not going to be technical so much as I really want to write about some tech things people say that are either completely wrong or just down right annoying. So take this how you will, but this is an opinion piece.

Something I once did before I knew much about computers but now that drives me crazy when I hear it, is when people talk about Java and call it Javascript or visa versa. Let us get a few things straight. Java is not related to Javascript nor the other way around. Javascript is a scripting language based on ECMAScript whereas Java is an interpreted language developed by Sun Microsystems. While Java can be used as a web technology, it is not the same as Javascript and while they have some similar naming conventions, any real depth into some code would reveal they are very dissimilar. So stop mixing them up, it is frustrating.

Another irritating point for me was created by the media, "Mac vs PC." The real goal of this is Mac OS vs Windows. Mac computers are PC's, as PC stands for personal computer. Furthermore, Mac computers can run Windows and if you're crafty, you can run a Mac OS on another PC, virtual machines being the easiest to get things going. Also some people throw Linux into the list. Well, OS X is Unix based as well. So they have some similar things to them. As to which is better, all three of them suck. It is just a matter of picking which one sucks less at what you personally need to accomplish. None of them are good at everything no matter what they claim.

Overuse of acronyms. In the technical world, many acronyms exist. Many acronyms overlap and it depends on what you are talking about. Overuse of acronyms in situations where it is not necessary is annoying and even a tech geek can get lost in such conversations. Granted there are exceptions where some technologies are explicitly referred to their acronym based name because some of the names are long and annoying. Some examples are XML (eXtensible Markup Language), HTML (HyperText Markup Language), or even php (Personal Home Page/Hypertext Preprocessor [it has changed over time]). Choosing to use all those acronyms in an environment outside of a situation that deals directly with such things is annoying, confusing and not many people can follow clearly. Use words.

Being able to navigate a website does not make you tech savvy, same goes for navigating software. I am relatively tech savvy and I get lost on so many websites and various user interfaces. One annoying example is of Microsoft Office. They keep changing the interface, and while I know what I want to do, I can spend a lot of time looking for various options. These things are esoteric and not standardized. While many try to keep similar conventions in an attempt to create better ease of use, they do not have to. Reliance on people trying to make similar and familiar interfaces is not possible.

Do not use tech terms you do not understand. If the media is to teach us anything, let it be this. For example the famous CIS line, "I'll make a GUI interface in visual basic, see if I can track an IP address" (GUI pronounced "gooey"). Taking this I would have to respond, okay, I will make an OS in Piet, see if I can make a super computer. Despite the lack of need to sum up why this is dumb, I am going to do it anyway. A GUI is not necessary for any of this. A good deal of tools for sniffing are done in command line interfaces because there is no point in the extra computational time and effort going to making a pretty window. Visual Basic is a dumb choice. I don't even know if you could make a sniffer from VB. If you can, it is probably some random .NET feature that is a waste of time. Now you do not "track" an ip, you can trace a route. Tracing would be following something along its path. That is a small thing to pick at, but tracking an ip would be like sniffing just that ip. Tracing would be finding the origin.

Using tech terms from one thing for a separate case.When drawing a comparison it is fine. However, using that comparison like the cases are equal is usually not fine.

Comparing things on levels that they are not comparable. I am sure at some point you have come across things like Perl vs Python, where they argue about dumb things like which is easier to read or application. Seeing as how Perl was more so made for text processing and Python is more of a general purpose language, they are obviously not going to be good at the same things. Benchmarking comparisons are one thing, but arguing about readability or which way of doing things is better is dumb because it depends on the application and the person.

Skids. Script kiddies. People that claim to hack when they are using premade tools without knowledge of the underlying innerworks of how or why things work they way they do. Downloading things like custom firmware to break a game system or opening up a tool to do some network scanning. Some of these can be dangerous if you do not have some understanding of how they work. In this light, the use is not that of a tool but a black box effect. Someone puts something in and gets the desired result out without understanding what just happened. So not everyone that uses these tools are skids or something to that effect, some actually understand in general how they work and use a premade tool to build something else faster.

So those are just some thoughts and opinions based off of things I have heard people said that just really catch me the wrong way and I have seen them criticized for saying such things as well. An easy way to keep yourself from saying something that will annoy others, whether you are right or wrong, is to remember you do not need to prove anything to anyone what you know, because you already know you know it.

Sunday, July 22, 2012

IRC Bot (logbot)

After my first post on IRC bots, I decided to make a bot for logging a chat that was a bit better designed than the one I posted. It is far from perfect, however it will write formatted logs to a file for you, won't sit around if it is kicked and if it sees a message it cannot format, it will log the raw data. Also to keep in mind, it only joins a channel ofter the motd finishes with a certain number code. If there is no motd or it does not send the right number code it won't join. The reason for this is I just wrote the thing today and don't have the time to check all possibilities. So use it as a skeleton and develop on it further. Or ignore it and move on with your day. All descriptions will be commented in the code.

#!/usr/bin/env python
# Import all the packages we will be using
import logging
import socket
import ssl
import os
import sys
import re

# Some global variables for configuration
HOST = "irc.69megabytes.com"
PORT = 6697
NICK = "PyLogBot46"
CHANNEL = "#allthefallen"
SSL = True
FLOG = os.path.join(sys.path[0], "ircbot.log")
PWD = "supersecretpassword"
# This is for use later on to know when to join the channel and do it only once
notInChan = True

# Regex parsing of a standard IRC message
def parse(data):
    temp=re.match(r"^(:(?P<prefix>\S+) )?(?P<command>\S+)( (?!:)(?P<params>.+?))?( :(?P<trail>.+))?$", data)
    if temp:
        temp=temp.groupdict()
    return temp

# Where the magic happens
if __name__ == '__main__':
    # Set up the logging format
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt="%Y-%d-%m (%H:%M:%S %Z)", filename=FLOG)
    # Message format strings so we can easily alter them
    format_privmsg = "{1} <{0}>: {2}"
    format_notice = "(notice) <{0}>: {1}"
    format_join = "{0} has entered {1}"
    format_nick = "{0} is now known as {1}"
    format_mode = "{0} set mode {1}"
    format_modes = "Mode set {0}"
    format_kick = "{0} kicked from {1} by {2} ({3})"
    format_srvmsg = "-!- {0} {1} {2}"
    try:
        # Create socket
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # Set up SSL if necessary
        if SSL:
            s = ssl.wrap_socket(s)

        # Connect to the server
        s.connect((HOST, PORT))

        # Authenticate
        s.send("NICK " + NICK + "\r\n")
        s.send("USER " + NICK + " www.anarchy46.net PY :Python LogBot\r\n")

        # Main loop
        while 1:
            # Reset information received and processed
            data = ""
            info = {}
            # Retreive data 1 byte at a time, stop at newline
            while data.find("\n") == -1:
                data += s.recv(1)
            # Remove unnecessary whitespace
            data = data.strip()
            # Parse the raw data
            info = parse(data)
            # Privmsg handler
            if info['command'] == "PRIVMSG":
                logging.info(format_privmsg.format(info['prefix'], info['params'], info['trail']))
            # Notices
            elif info['command'] == "NOTICE":
                # If to self from someone
                if info['params'] == NICK:
                    # To quit properly
                    if info['trail'] == PWD:
                        s.send("QUIT :Done logging.\r\n")
                        break
                    # So we don't log the password
                    logging.info(format_notice.format(info['prefix'], info['trail']))
                # Server notices
                else:
                    logging.info(format_srvmsg.format(info['prefix'], info['params'], info['trail']))
            # Respond to server pings (no need to log)
            elif info['command'] == "PING":
                s.send("PONG " + info['trail'] + "\r\n")
            # Someone joins
            elif info['command'] == "JOIN":
                logging.info(format_join.format(info['prefix'], info['trail']))
            # Someone changes nick
            elif info['command'] == "NICK":
                logging.info(format_join.format(info['prefix'], info['trail']))
            # Modes
            elif info['command'] == "MODE":
                # Normal mode changes
                if info['trail']:
                    logging.info(format_modes.format(info['trail']))
                # Modes for self (set by server)
                else:
                    logging.info(format_mode.format(info['prefix'], info['params']))
            # Someone gets kicked
            elif info['command'] == "KICK":
                # Quit if it's the bot
                temp = info['params'].split(' ')
                if temp[1] == NICK:
                    logging.info("Kicked from channel.")
                    s.send("QUIT :Bye bye...\r\n")
                    break
                # Log everyone else being kicked :D
                else:
                    logging.info(format_kick.format(temp[0], temp[1], info['prefix'], info['trail'])
            # Special server messages
            elif info['command'].isdigit():
                if info['trail']:
                    logging.info(format_srvmsg.format(info['prefix'], info['command'], info['trail']))
                else:
                    logging.info(format_srvmsg.format(info['prefix'], info['command'], info['params']))
                # End of MOTD
                if notInChan and info['command'] == "376":
                    s.send("JOIN " + CHANNEL + "\r\n")
                    notInChan = False
            else:
                logging.info(data)
    # Abort!
    except socket.error as err:
        logging.critical("Socket error: " + str(err.errno))
        sys.exit(err.errno)

It's not the prettiest of code, but it works. When launching from the command line, make sure to add an ampersand (&) at the end so you don't need to wait for it or leave a window open with it running. Enjoy, and remember this thing only took me a couple of hours to write and sort out some formats.

Saturday, July 21, 2012

Making an IRC Bot

A common question I get from people I know is about making an IRC bot. The problem I run into with people trying to do this is they are usually very new to programming and half the time they are struggling with the basics of simply how to write a program. So before getting into more detail, there are some prerequisites you need to know first.
  • Understanding the programming language syntax you want to use
  • Basic programming
  • Networking knowledge of basic sockets (nothing in depth but more so how network communication should be modeled)
  • Knowledge of the IRC protocol raw (access to an RFC is very useful)

Now f you are still reading, I will assume you at the very least plan on doing the research before actually trying anything. For this, I will be writing it in Python as it is very simple and easy to do. So let us work through this piece by piece.

The first thing we want to do is run our imports so we can have all the modules we need to work with. Rather than using some third party IRC module, we will work with raw sockets because I can and it gives more insight as to what is going on. We need the module for sockets, and regular expressions. We will also import time and I'll get to why later.

import socket
impor re
import time

So now that we have the packages we need, now we need to create a socket object. With a socket object, we can establish a connection over TCP/IP, among other types of socket connections. For our purposes we will use IPv4 and a stream. For this we use the variables AF_INET and SOCK_STREAM. The AF in AF_INET stands for "address family." Now let's create the socket.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Now we have the socket object s. In another post I will explain how to put an SSL wrapper on it to use a secure connection. As for now, just a socket will be used. Now we need to connect to a server.

s.connect((HOST, PORT))

Here the connection info is passed as a tuple, so yes the parentheses are on purpose. In this, HOST will be a string of either the IP address or domain and PORT is the port number you will connect to. Now that the connection is established, we need to send identifying information for the IRC. To simplify things we will have the program sleep for a second as some servers do not let you authenticate immediately and instead send a signal for it. However I do not feel like writing out something to check for that signal right away.

time.sleep(1>)
s.send("NICK MyIRCbotNick\r\n")
s.send("USER MyIRCbotNick anarchy46.net PY :Python Bot\r\n")

Okay, so now that we've authenticated, we will sleep again then join a channel because yet again, cannot join right away.

time.sleep(1)
s.send("JOIN #somechannel\r\n")

Now we set up the loop to read the server data. Because this will go on indefinitely, we will use an infinite loop.

while 1:
    data = "" # Reset data each time
    while data.find("\n") == -1:
        data += s.recv(1) # Receives data 1 byte at a time
    data = data.strip() # No need for leading or trailing whitespace
    print data
    # Watch for and respond to server pings
    if re.search(r"^PING", data):
        s.send("PONG" + data[4:])

Now you have all the code needed to connect to an IRC server, join a channel and stay connected. A few things to keep in mind. The socket is blocking, so the bot will wait on the recv() until it gets some data. Without blocking the program would be too CPU intensive without some extra work. Also note that printing data will print raw IRC data, which is a lot different than the messages you see in a client, and will include control characters like char 1 and 3. Furthermore, there is no error handling or autojoining should the bot be kicked. This is simply a small and poorly made IRC bot that is to demonstrate what is needed to connect to an IRC and I do not recommend this design as a base for a larger scale bot that will be used more often. Sometime later I will divulge a more robust bot that has the purpose of logging an IRC channel or channels.

Saturday, July 14, 2012

Flip a web page

I know there are a lot of people out there that like messing with others, so I got bored and decided to make a quick little bit of Javascript to do that. This will only work in browsers that support CSS3 and is a bit lengthy because certain browsers need their own special tags. So if you want to flip a page someone is browsing, or maybe even yourself, just enter this code in the address bar of the browser to flip a site:

javascript:document.body.setAttribute("style", "transform:rotate(180deg);-ms-transform:rotate(180deg);-moz-transform:rotate(180deg);-webkit-transform:rotate(180deg);-o-transform:rotate(180deg);");void(0);

It's as simple as that, the page should be flipped. Also, here's a link to do it, you can set it as a bookmark to make a bookmarklet: flip

Thursday, June 28, 2012

MyBB Registered-only view BBCode

Decided to make another quick MyBB addon, this adds some BBCode. You can use [paranoid][/paranoid] tags to prevent non-registered and banned members from viewing stuff selectively. I am using it to cover up various resource links. If you are logged in, it will appear like nothing is changed, you can only tell what's covered up by logging out or being banned.

[Download v1.0]

Maintained: https://github.com/anarchywolf46/MyBB-Plugins

Friday, June 22, 2012

Firebug Quick Info (remove)

One of the things that has been annoying me on firebug, is the quick info popup. It's always in the way. So I looked up how to disable it because I didn't have a clue where the options where. In my version of firefox, under Tools > Web Development > Firebug > Options and clicked to uncheck the "Quick Info" option. I think on older versions it was just under the Tools menu. Either way, if you didn't know how to do that, now you know.

Friday, June 15, 2012

Python Lambda Intro (with simple example)

While really a simple thing to do, I wanted to post an example of a very simple program using something a little less common. Instead of the more common way of making a function, I will instead use lambda. In Python, lambda is used for passing an anonymous functions to a method or can be used to have a function generate simple functions. For the latter, decorators can be used for a more complex function generation, however I have yet to fully grasp using it, so I'll save explaining that for when I know how to practically use it.

Now anonymous functions are cool because you can either pass them to a function without creating some permanent function that will only be used in that one particular instance or you can pass it to a variable reference. Passing to variable reference is as simple as defining any variable. The difference in this particular instance is that lambda is limited to very simple functions, and returning variables is not as clear as a return statement. Let's view a quick example.

import sys

ftoc = lambda(f): (f-32.0)*(5.0/9.0)
ctof = lambda(c): (9.0/5.0)*c+32.0

while(1):
    try:
        print """Pick a conversion (EOF to end ctrl+z win/ctrl+c *nix)
1 - Fahrenheit to Celsius
2 - Celsius to Fahrenheit
3 - Exit

>""",
        choice = raw_input()

        if choice == 3:
            break;
        else:
            print "What is the tempurature?",
            temp = raw_input()
            if choice == "1":
                print str(ftoc(float(temp)))+" Celsius"
            elif choice == "2":
                print str(ctof(float(temp)))+" Fahrenheit"
            else:
                print "Unknown option"

    except KeyboardInterrupt:
        break;

    except Exception as e:
        print "An error occured: "+str(e)
print "Goodbye."
exit(0)


The main point to focus on is the 2 lines following the import statements. To break it down, ftoc = lambda(f): (f-32.0)*(5.0/9.0) is actually very simple. It starts out with a normal variable declaration, variable name being ctof. We then assign it to the value of the lambda statement. The word lambda in Python means an anonymous function, then the (x) is the arguments the function accepts. This does not need to be in parenthesis can could just as easily be lambda x:. I use the parentheses to more clearly show that it's not the function name, but arguments being passed to it, I find it to be more clear for myself reading it. The next part is just a formula for converting the temperature. The question may arise, where is the return value? Quite simply, it's whatever the code in the lambda statement evaluates to at the very end.

Now some caveats. Lambda functions cannot span multiple lines, it's only a 1 liner function (with the exception being if a docstring is used). It also supports nested scope, so if it is within a scope where it uses a variable name, it will use that variable, however if the variable is the name of an argument variable, that value will be used instead. Finally, semicolons are ending delimiters and cannot be used to include multiple lines of code, it is only a single statement.

One more little catch I ran into, while I doubt anyone has a need for it, trying to define a list of lambda functions through list comprehension will not work to make different functions. Using something like y = [lambda (x): x+z for z in range(10)] will result in all 10 list items having z as 9 because it will use z as a reference to z and not replace the value, therefore the last value of z is the one that is used. However, if you replace the lambda function with a function that returns lambda functions, it works, and looks like this.

def a(x):
    return lambda(y): x+y

y = [a(z) for z in range(10)]


I was also informed of an alternative way to do this through default values, which looks a little uglier, but can condense things if you really want to. You can do something like y = [(lambda x, z=z: x+z) for z in range(10)], which will place the value of z as the default argument. Note however, that since it is a default argument, it can then be changed, which does not seem like a clean solution.

Sunday, June 10, 2012

Refused to set unsafe header

*** If interested in CORS, try this.

This is an annoying little error that I've seen some people mention and even ran into with JavaScript. Moreover, it appears only in Webkit based browsers. So what's the problem? Basically a browser like Google Chrome will not change certain http headers in an XMLHttpRequest using setRequestHeader(). This is not a problem in Firefox or Opera from my testing so far. According to W3, it is actually the behavior they have as "standard" in their working draft. Headers they don't want you to overwrite are
"
  • Accept-Charset
  • Accept-Encoding
  • Access-Control-Request-Headers
  • Access-Control-Request-Method
  • Connection
  • Content-Length
  • Cookie
  • Cookie2
  • Date
  • DNT
  • Expect
  • Host
  • Keep-Alive
  • Origin
  • Referer
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade
  • User-Agent
  • Via
Or if the start of header is a case-insensitive match for Proxy- or Sec- (including when header is just Proxy- or Sec-)."[1]
Now as to where this could be a problem, for me at least, is when I am trying to spoof some headers and want to do so in a browser as apposed to writing a script or getting an addon to do so for me. However, there is a security risk it could open up called HTTP Request Smuggling. As to how one would pull it off, I think an XSS vulnerability would need to be there as well for this in JavaScript to do anything. Bottom line for the security of it on the design end, make sure you check your sources before you use things like external scripts. As for user-end security, just be careful what sites you go to and use some common sense when you can.

Now as for ways around this, you would need either an addon to modify this for you or use related command line arguments. For example, to change the User-Agent header, you launch Chrome from your terminal with the option --user-agent="Some new UA string". As for an addon to do this, I do not know of any or if it is even possible, but if I find something I will update that here.

*[1] - http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

Wednesday, May 9, 2012

WebGL Firefox Error

So I figured I'd post about this, since I ran into a problem and had to dig through some forum posts to find how to fix this. My problem was on Ubuntu 10.04 LTS using Firefox 12.0, with NVIDIA GeForce Go 6150. Trying to use WebGL gave me the error that I forgot to save because I'm smart like that.

Anyway, the quick fix was to enter in your url about:config, then search for WebGL, then enable webgl.force-enabled. No idea if it will cause any problems, but for now it works.

***Edit:
Updated to Ubuntu 12.04 LTS, same settings and everything and now WebGL just refuses to work at all. No solution found yet, all the ones that I tried did absolutely nothing.

Sunday, April 29, 2012

2D Rectangular Collison Detection

I was just looking through some old code and came across something I couldn't quite work out in my head but had to find. Circles was very self explanatory, but rectangular shapes are a bit more awkward, so here's a simple way that will return either a true or false based on the idea that 0 is false and a number greater than 0 is true, assuming rectangle 1 is made of points a and b and rectangle 2 is made of points c and d.
Points relative to rectangle (showing collision)
We also assume each point is a list of the [x, y].

int checkCollision(int a[], int b[], int c[], int d[]) {
    int c1, c2, c3, c4, c5;
    c1 = a[0] < d[0];
    c2 = a[1] < d[1];
    c3 = b[0] > c[0];
    c4 = b[1] > c[1];
    c5 = c1 && c2 && c3 && c4;
    return c5;
}

That would (more or less) be the gist of detecting if 2 rectangles collide by finding if there is an overlap. The basic idea is make sure all the points are in an area they could  be in if there was an overlap. Then by making sure all are in an area they can be in if there is an overlap, detects the overlap, since all must be in those areas for an overlap to exist. For any other shapes that are not square, you must use trigonometry, which I may get into some day down the road.

Thursday, April 12, 2012

Minecraft /dev/input/event error

I've been playing Minecraft for a while, and having a computer with Ubuntu, that's what I play it on. However I kept running into a series of error messages about /dev/input/event. Since everything ran fine, I never bothered to see what the error was about. Today I finally searched around and it was a problem with file permissions. A quick command to fix it is sudo chmod go=u /dev/input/event*.

A quick explanation of what it does if you don't understand it, it will copy the permissions for the root (u)ser to the (g)roup and (o)ther, other being anyone else not in the group or that user.

Tuesday, April 3, 2012

CSS3 ::selection

While working on some stuff I cam across a CSS3 pseudo-class selector called ::selection. While this is something you can do in javascript, it makes things a lot easier when styling can all be done in CSS rather than javascript workarounds. The javascript equivalent would be rather annoying to do. So the CSS3 way, as with any CSS, is rather simple and quick to do, minus a few catches here and there. CSS3 still lacks a good deal of support and isn't good if you want some real backwards compatibility, however I'm more interested in how to use this to just screw with things in ways it could be exploited, bad or just annoying and this particular property hit right on the head for some annoying fun.

You may wonder how this could be annoying, and quite simply, think about what would happen if selected text disappears. It would no longer be selected and then have to reappear, unselected. Thus the end result is text you cannot highlight without altering the CSS. So the code for that looks something like this.
::selection {
  display: none;
}
::-moz-selection {
  display: none;
}

I've only tried this in Firefox 10, but when I do it on Firefox, the text is impossible to highlight, however I can drag the text. As to the effects it will have in other browsers that support it, well that's all part in the fun in trying to mess with things to get results like this.

Try to highlight this and see what happens if your browser supports it.

Monday, March 19, 2012

NoScript URL Javascript

I've been messing around with javascript and helping someone learn it, and one thing I've noticed is a lot of people seem to have NoScript now. NoScript is an addon that can allow you to selectively run or block javascript. While this is great, there is one option I don't see openly on the options for it. Whenever trying to run javascript in the url bar, it's blocked. While this is good for people dumb enough to run javascript directly from someone not trustworthy (I have used url run javascript to get someone's cookie information and hijack their session), it can be a problem when just messing around with stuff for someone who knows what they are doing but doesn't know about the way to allow url run javascript.

So to find the option, first go to the about:config (enter about:config in your url). Then in the filter, enter noscript.allowURLBarJS. You can right click and select the toggle option or simply double click the result you get. Once set to true, should be able to run url javascript, but only on sites that the domain is allowed to run javascript. Running javascript in the url still sandboxes it in to whatever tab you're on.

Whatever you do, be careful what you run when using this, can lead to information being taken to breaking some stuff. Other times, can be just a way to mess around with a site you're on quickly and easily, like bookmarklets.

Tuesday, January 24, 2012

IRC message Regex

So I'm in the process of making an irc bot, and one of the problems I always seem to have is parsing the message. If you don't know what parsing means, the simplest explanation is changing the message, in this case breaking it down into some form of an object that organizes the data for it.

Normally I would split it and then check various information from it being split then check all the split parameters and try to organize it, however when searching recently I found an easier way. Now keep in mind, this is client side parsing. I found the original on Caleb Delnay, so original credit goes here, but I wanted to expand upon it and convert it to work with the other subtle changes in regex across other languages.

*** There were further improvements added by someone else who I found thanks to some referrals in the stats thanks to a lovely accreditation to this post. Check out more info at mybuddymichael.com. I'll try to integrate the changes into my post once I can take some time to give it a good lookover and try it out a bit (hopefully it will help out with a new bot I'm currently working on in Haskell).

The original .NET compatible regex is
^(:(?<prefix>\S+) )?(?<command>\S+)( (?!:)(?<params>.+?))?( :(?<trail>.+))?$

Python (place in an r"" string so you won't need to escape backslashes), Perl, PHP, and AS3:
^(:(?P<prefix>\S+) )?(?P<command>\S+)( (?!:)(?P<params>.+?))?( :(?P<trail>.+))?$

Java (before 7 didn't support named groups, want to look at groups 2, 3, 5 and 7):
^(:(\\S+) )?(\\S+)( (?!:)(.+?))?( :(.+))?$

Java (7 and up supports named groups, have not tried this yet):
^(:(?<prefix>\\S+) )?(?<command>\\S+)( (?!:)(?<params>.+?))?( :(?<trail>.+))?$

JavaScript (no named grouping, use groups 2, 3, 5, and 7, does not need to be in a string):
/^(:(\S+) )?(\S+)( (?!:)(.+?))?( :(.+))?$/

The basic premise is under the assumption messages are formatted along the lines of :<prefix> <command> <params> :<trailing>, where any values are optional. If you know a better way to do any of them are know ways in languages I left out, let me know. As far as the regex methods and ways to work it out, that is up to you, I am just supplying the pattern and it is up to you so use it correctly.

Since regex can be complicated, hopefully this saves everyone some time, figuring out the needed methods to use it shouldn't be too hard.



***Edit:
After a comment about some stuff in the RFC, I played around with trying to make the regex work with that specification, I came up with a partially working version. Due to the complexity, my lack of knowledge and lack of benefit from this, I will only post the one edit I made and hopefully not bother with this again. While this is good for something quick and dirty, string methods seem to be more practical.

^(:(?P<prefix>\S+) )?(?P<command>\S+)( (?!:)(?P<params>\S{14} (:)?|.+ :?))?((?P<trail>.+))?$

The params section will end up with either a trailing space or a space and colon. That's the best I could do, and the last I'll do of this.

Wednesday, January 18, 2012

Javascript Ajax and keeping order

The title is about as descriptive as I could come up with for this, but allow me to elaborate. On a forum I code for, basically my coding is fixing and editing shit that's either broken or unsatisfactory, they decided to install a shoutbox. The shoutbox program worked with one major flaw. The Ajax requests for the shout were not being tracked and therefore jumping out of flow, which broke shit causing the script to shit itself and led to a bunch of problems down to my browser throwing an error with the socket, posts duplicating, just pure stupidity really. Upon hunting for the error, it was blatantly obvious and something I never thought I'd run into.

The metaphor of it goes like this... you send out messengers in regular intervals, but don't track them when you only need one messenger who is tracked. So all these anonymous messengers have information of what to get the update on, but it's only as recent as when they were sent. Therefore if they don't get back before the next one is sent for whatever reason, another messenger is sent for the same information. When they return, you now have double, possibly even triplicates of the same update info. So rather than handle that, it then dumps all the info in, duplicates and all, which then everything is overwhelmed, can't establish the right new request to make and then just shits itself.

Here's the remedy, and it should be the first thing you learn with Ajax requests. First, assign the object to a variable name. Then you check for two things, the readyState and the status. It's not done until the readyState is 4 and the status is 200. Once that is satisfied, then and only then do you send out a new request. This allows things that need to be done in order to be done in order.

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    // Process what to do when done.
}

You should preform this check even if you are waiting for the onreadystatechange event, as just because it has changed does not mean that it is done. Now for this particular script, it used a javascript framework called Prototype. When you create an Ajax object with that, the readyState and status are available in the object's transport object.

The bottom line is remember the flow and to control anything asynchronous, do not rely on delay or speed to maintain the flow in those cases.

Tag Cloud

.NET (2) A+ (5) ad ds (1) addon (4) Android (4) anonymous functions (1) application (9) arduino (1) artificial intelligence (1) backup (1) bash (6) camera (2) certifications (3) comptia (5) css (2) customize (11) encryption (3) error (13) exploit (5) ftp (1) funny (4) gadget (4) games (3) GUI (5) hardware (16) haskell (6) help (14) HTML (3) imaging (2) irc (1) it (1) java (2) javascript (13) jobs (1) Linux (19) lua (1) Mac (4) malware (1) math (6) msp (1) network (13) perl (2) php (3) plugin (2) powershell (8) privacy (2) programming (24) python (10) radio (2) regex (3) repair (2) security (16) sound (2) speakers (2) ssh (1) story (5) Techs from the Crypt (5) telnet (1) tools (13) troubleshooting (11) tutorial (9) Ubuntu (4) Unix (2) virtualization (2) web design (6) Windows (16) world of warcraft (1) wow (1) wx (1)