Friday, April 14

SVGs: Cut shapes out of other shapes. Transparencies


Introduction

While making a SVG graphic of an "id card" I realized I needed the top part of the card to have a transparent hole in it. Searching the internet mainly shows the "fill=odd" trick, and drawing the objects with paths. Which is ok if you want to cut a square out of a circle, or a circle out of a star. If you want to cut a rectangle with rounded corners, creating a path becomes much harder.





and then came Mask

I am not sure which article, or which blogger I first read about masks on. My initial thoughts were that it followed the same lines as the "fill=odd" trick. Then I saw a code example, and it all became clear. Mask is exactly what I was looking for.



Example

Before I used mask, I had a rectangle with rounded corners, with the fill color set to the same as the background color.




Using the mask feature, we define the mask in the DEF section, and anything colored #FFFFFF is shown, anything #000000 is transparent.

Monday, April 10

JavaScript: Draggable DOM Element


Introduction

I wanted to create a completly Vanilla JavaScript draggable DOM element tool. This will be used in a future project idea. You can watch the time lapse of this being created:


dragItem.js   (JavaScript Source Code)

(function() {
  'use strict';
  
  var inDrag = false
    , dragElement = null
    , dragOffsetX = 0
    , dragOffsetY = 0
    , body = document.getElementsByTagName('body')[0];
    ;
  
  function dragHandler( event ) {
    if (event.button != 0) return;
    dragElement = event.target;
    var canDrag = dragElement.getAttribute('drag')
      ;
    while (!canDrag && dragElement.parentElement) {
      dragElement = dragElement.parentElement;
      canDrag = dragElement.getAttribute('drag');
    }
    if (!canDrag) return dragElement = false;
    dragOffsetX = event.clientX - dragElement.offsetLeft;
    dragOffsetY = event.clientY - dragElement.offsetTop;
    body.appendChild(dragElement);
    body.style.userSelect = 'none';
    inDrag = true;
  }
  
  function dragMove( event ) {
    if (!inDrag) return false;
    dragElement.style.left = event.clientX-dragOffsetX+'.px';
    dragElement.style.top = event.clientY-dragOffsetY+'.px';
  }
  
  function dragStop() {
    if (!inDrag) return;
    if (event.button != 0) return;
    inDrag = false;
    if ( (dragElement.offsetTop + dragElement.offsetHeight)<20) dragElement.style.top = 20 - dragElement.offsetHeight+'.px';
    if ( (dragElement.offsetLeft + dragElement.offsetWidth)<20) dragElement.style.left = 20 - dragElement.offsetWidth+'.px';
    if ( (dragElement.offsetTop+20)>window.innerHeight) dragElement.style.top = window.innerHeight - 20+'.px';
    if ( (dragElement.offsetLeft+20)>window.innerWidth) dragElement.style.left = window.innerWidth - 20+'.px';
    dragElement.zIndex = '10';
    body.style.userSelect = '';
    dragElement = null;
  }
  
  function init() {
    var dragableItems = document.querySelectorAll('[drag]')
      ;
    for (let itemID=0; itemID<dragableItems.length; itemID++) {
      let item = dragableItems[itemID];
      item.className+=' dragable';
    }
    window.addEventListener('mousedown', dragHandler );
    window.addEventListener('mouseup', dragStop );
    window.addEventListener('mousemove', dragMove );
  }
  
  window.addEventListener('load', init);
})();


index.html   (HTML Source Code)




Check out the CodePen

See the Pen Draggable DOM Element by Failed Sleep (@FailedSleep) on CodePen.

Wednesday, April 5

Simple OBS Overlay System: NodeJS, Express, WebSockets


Introduction

I have noticed after watching a number of live streams on Twitch.tv that one of the things most starting streamers have problems with is setting up some overlays for their stream. After a number of people asked for a simple overlay system, I decided to write a simple system which anybody with even limited HTML, CSS, JavaScript capability could modify for their use.

I go through the steps of installing Open Broadcaster Software. Downloading and installing NodeJS v6.10.2. Then I continue on with programming a simple overlay system, which could be upgraded to support remote control.



Directory Sturcture
  • OBS_Overlay_System
    • public
      • images
        • 0.background.png

        • 1.online.png
        • 2.streaming.png
        • 3.brb.png
        • 3.oops.png
        • 4.done.png
      • index.html
    • overlay.js
    • package.json


Source Code
overlay.js
var server = require('http').createServer()
  , Express = require('express')
  , app = Express()
  , port = 2017
  /* WebSocket */
  , wsServer = require('ws').Server
  , wss = new wsServer({
                          server: server
                       })
  ;

wss.broadcast = function(data) {
  wss.clients.forEach( function each(client){
    if (client.readyState === 1) {
      client.send(data);
    }
  });
}

wss.on('connection', function(socket){
  console.log('Client Connected!');
  socket.send('online');
  socket.on('close', function() {
    console.log('Client Disconnected!');
  });
});

app.use( function(req, res, next){
  if (req.path != '/overlay/broadcast') return next();
  var data = req.query['stage'];
  wss.broadcast(data);
  res.send('confirmed.');
});

app.use( Express.static( __dirname+'/public' ) );

server.on( 'request', app );

server.listen( port, function() {
  console.log('Listening on http://localhost:'+port);
});

public/index.html

package.json
{
  "name": "fs-obs-overlay",
  "version": "0.1.0",
  "description": "A Very Minimilistic Overlay System for use with OBS. Uses Express, WebSockets",
  "homepage": "http://www.failedsleep.com",
  "main": "overlay.js",
  "config": {
    "port": "2017"
  },
  "dependencies": {
    "express": "^4.15.2",
    "ws": "^2.2.3"
  }
}



Install Instructions

  1. Download Source Code
  2. Extract Source Code to a Directory
  3. Open command shell
  4. Change directory to the directory the Source Code was extracted to
  5. run "npm install"
    1. This will install the node modules required in "package.json"
  6. run "node ."
    1. this will run the overlay program
    2. "Control+C" will terminate the program.

External Links


Wednesday, March 29

Hacking Game: Part 1 - Electron Setup & Initial Code


Introduction

Today I started programming the beginnings of a yet unnamed hacking game. I know there have been, and will be, many fantastic games already developed in this genre. I am not expecting this game to live up to the likes of Uplink, Hacker Evolution, or Hackmud.

The one thing that might set this one apart a little is the fact that I am streaming the development on twitch.tv/failedsleep. The other small thing is that I will be posting the source code, so it is available for download and experimenting with in days of the stream.


Accomplishments

  • Created the Main Menu
  • Started the Game Intro
  • Started the main Terminal console


Electron.atom.io

Build cross platform desktop apps with JavaScript, HTML, and CSS. You can download pre compiled versions for most systems at: github.com/electron/electron/releases.


Screen shots






The Links


Tuesday, March 28

NodeJS, Socket.io: Simple Client / Server


Introduction

The minimum amount of code to have NodeJS serve a simple socket.io client and server.



Requirements

This code uses NodeJS module "socket.io" which you install with the following command:
npm install socket.io


Server.js Source Code

var http = require('http')
 , fs = require('fs')

 , webpage = fs.readFileSync(__dirname + '/client.html')
 , port = 2017
 ;

// Send client.html to all requests
var server = http.createServer(
 function(req, res) {
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.end( webpage );
 }
);

// Socket.io server listens to our app
var io = require('socket.io').listen( server );

// Send current time to all connected clients
function sendEveryone( msg ) {
 io.emit('msg', msg );
}


// Listen for connections
io.on('connection', function( socket ) {
    // Single Client's socket
    socket.emit('confirm', 'Server here');
    socket.on('from Client', function( msg ){
     console.log( msg );
   });
});

server.listen( port );




client.html Source Code

<!doctype html>
<html>
<head>
   <script src='/socket.io/socket.io.js'></script>
</head>
<body>

 <script>
   var socket = io();

   socket.on( 'welcome' , function( msg ) {
       console.log( msg );

       // Contact Server
       socket.emit('from Client', 'Client Here');
   });

   socket.on( 'msg' , function( msg ) {
       console.log( 'incoming:' , msg );
   });

 </script>
</body>
</html>

Wednesday, March 22

Fix:Windows 10 ( Not finding Linux Workstations )


The Problem

Recently I ran into the problem where most of the machines on a network could see the linux server by network name. The two computers which could not see the linux samba file server are both running Windows 10.

While using my google ninja skills I came across many other people who were having the same problem. Some of the people attributed the issue to Samba on linux. Other people said it was Microsoft's implementation of the SMB protocol. Yet others, like myself, were just puzzled.



The Fix

On the Windows 10 computer start powershell. You can search for powershell by holding down your windows key and pressing the letter "S". Typing "powershell" into the search box will after a brief moment present "Windows PowerShell". Right click on "Windows PowerShell" and select "run as administrator".


  1. Turn on SMB 1.0 support
    • sc.exe config lanmanworkstation depend=bowser/mrxsmb10/nsi
  2. Disable SMB 2.0
    • sc.exe config mrxsmb20 start=disabled


Revert Fix

If you need to reverse the previous fix for any reason.
  1. Add SMB 2.0 support
    • sc.exe config lanmanworkstation depend=bowser/mrxsmb10/mrxsmb20/nsi
  2. Start SMB 2.0 support on boot
    • sc.exe config mrxsmb20 start=auto


Updates

  • 17.03.28 
    • Changed title to be less "clickbate/clickbatie/clickbaty"???
      • From: "Fix: Windows 10"
      • To: "Fix:Windows 10 ( Not finding Linux Workstations )"

Monday, March 20

Fetching value from nested object, or null ( JavaScript )


Introduction

A simple function which will safely return the value or null from a nested set of objects. With this function it makes it much easier for you to know that you are always either going to get the existing value, or if that object path does not exist, you will get a value of null.






Source Code

Example Data - JavaScript (ES6)

var savedata = { data: { users: { username: { name: 'first last', pass: 'password' }, test: { name: 'test user', pass: '12345' } }, version: '17.03.20' } } ;


Source Code - JavaScript (ES6)

const getVal = ( obj, path ) =>
   path.reduce(
       ( child, prop ) => child && child [prop] ? child [ prop ] : null, obj
   );

console.log( getVal( savedata, [‘data’, ‘users’, ‘username’] ) );
// [ ‘cool’, ‘yup’]

console.log( getVal( savedata, [‘data’, ’user’, ‘bob’] ) );
// null



Source Code - Javascript ( ! ES6 )

function getVal( obj, path ) {
   return path.reduce(
     function ( child, prop) {
       return child && child[ prop ] ? child[ prop ] : null;
     }, obj
   );
};