Category Archives: Uncategorized

Set Date Back Twelve Hours – MSSQL

Hey everyone,

A quick post on how to set a date value for twelve hours ago using SQL Server:

UPDATE MyTable
SET MyDate = dateadd(HOUR, -12, CURRENT_TIMESTAMP)

Simply use the dateadd function and specify the unit (hours in this case). The example above will set MyDate to twelve hours ago.

Here’s the offical documentation on the function: https://docs.microsoft.com/en-us/sql/t-sql/functions/dateadd-transact-sql?view=sql-server-2017

Also, thanks to this stackoverflow post for the info: https://stackoverflow.com/a/18518412/522859

Advertisements

Unable to Migrate after Adding Config to Startup

Hi everyone,

Just a quick post on fixing up a migration error after I added new config to startup.cs via DI. The error after running add-migration was pretty unintuitive:

Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

To find out a bit more I ran the following:

add-migration -verbose

This revealed the fact that there was an issue with adding my config line. The error stated that I had to have an empty constructor which led me on a bit of a wild goose chase.

The solution was simply a missed entry in application.json. In my case it was an omitted “assembly” section. Having said that, I did come across a few instances where people had the same problem when omitting commas etc.

Hopefully that’s able to get you on the right track!

Thanks,
Chris

Change i2c address of ina219

Hi everyone,

I wanted to use ina219 with pca9685 but they shared the same i2c address 0x4:
download0.

Luckily, there’s a fairly easy fix for this. All we need to do is solder two pins together. We’re going to bridge a0 and this will change our address to 0x41.

In order to check these run sudo i2cdetect -y 1 pm the raspberry pi:
download

After soldering it becomes:
download

You can solder a combination of pins for different addresses:
None = 0x40 (default)
A0 = 0x41
A1 = 0x44 (the one I’ve soldered to get 44)
A0 + A1 = 0x45

A4988 Stepper motor RaspberryPi

We’re using a 42shd0034-20B Geetech stepping motor taken from a 3d printer:
download

We’ll be driving it with an A4988 stepper motor controller. You can pick up five packs of these for less than $2 online – definitely worth having a few extras around:
download

The datasheet is available here: https://www.pololu.com/file/download/A4988.pdf?file_id=0J450

The following diagram illustrates what we’ll be doing:
download

Once everything is connected it’ll end up looking something like this:
download

To start, connect your stepping and direction pins. I’ve used GPIO16 for stepping and GPIO21 for direction:
download

Each time GPIO16 is set to HIGH it will make the stepper motor take one step. When the direction pin is HIGH the stepper motor will go clockwise, when it’s LOW, anti-clockwise.

If you’re not using the sleep functionality, connect the RESET and SLP pins together and then wire them directly to 3.3v:
download

Using a separate power source wire 12v to the GND and VMOT pins. You should also place a capacitor across these pins as close to the board as possible. Generally the longest leg is positive. You’ll also need to connect the external GND to the Raspberry Pi’s GND:
download

Connect the four pins of the stepper motor:
download

Connect the A4988 to 3.3v and common GND:
download

The code is pretty straight forward but I’ve provided a class below to help you get started:


# System imports
import RPi.GPIO as GPIO
from time import sleep

class StepperHandler():

__CLOCKWISE = 1
__ANTI_CLOCKWISE = 0

def __init__(self, stepPin, directionPin, delay=0.208, stepsPerRevolution=200):

# Configure instance
self.CLOCKWISE = self.__CLOCKWISE
self.ANTI_CLOCKWISE = self.__ANTI_CLOCKWISE
self.StepPin = stepPin
self.DirectionPin = directionPin
self.Delay = delay
self.RevolutionSteps = stepsPerRevolution
self.CurrentDirection = self.CLOCKWISE
self.CurrentStep = 0

# Setup gpio pins
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(self.StepPin, GPIO.OUT)
GPIO.setup(self.DirectionPin, GPIO.OUT)

def Step(self, stepsToTake, direction = __CLOCKWISE):

print("Step Pin: " + str(self.StepPin) + " Direction Pin: " + str(self.DirectionPin) + " Delay: " + str(self.Delay))
print("Taking " + str(stepsToTake) + " steps.")

# Set the direction
GPIO.output(self.DirectionPin, direction)

# Take requested number of steps
for x in range(stepsToTake):
print("Step " + str(x))
GPIO.output(self.StepPin, GPIO.HIGH)
self.CurrentStep += 1
sleep(self.Delay)
GPIO.output(self.StepPin, GPIO.LOW)
sleep(self.Delay)

# Define pins
STEP_PIN = 16
DIRECTION_PIN = 21

# Create a new instance of our stepper class (note if you're just starting out with this you're probably better off using a delay of ~0.1)
stepperHandler = StepperHandler(STEP_PIN, DIRECTION_PIN, 0.0025)

# Go forwards once
stepperHandler.Step(200)

# Go backwards once
stepperHandler.Step(200, stepperHandler.ANTI_CLOCKWISE)

Unable to find a dom node for 19 – Slate.js

Hi everyone,

I ran into the following error while attempting to add an image to a slate.js editor today:

slate.js unable to find dom node for 19

The solution was to add a simple schema to my editor:


const schema = {
    blocks: {
        image: {
            isVoid: true
        }
    }
};
    spellCheck
    autoFocus
    ref={this.ref}
    value={this.state.value}
    onChange={this.onChange}
    onKeyDown={this.onKeyDown}
    onDrop={this.onDropOrPaste}
    onPaste={this.onDropOrPaste}
    renderNode={this.renderNode}
    renderMark={this.renderMark}
    className={classes.editor}
    readOnly={readOnly}
    onFocus={() => { this.setState({ changed: true }); }}
    schema={schema}

There’s more on schemas in the official documentation: https://docs.slatejs.org/guides/schemas

String to Color – Avatar Helpers

Hi everyone,

A quick post on a helper function I came across for generating avatars. This function generates a random color for the specified string:


export const stringToColor = string => {

let hash = 0;
let i;

for (i = 0; i < string.length; i += 1) {
hash = string.charCodeAt(i) + ((hash << 5) - hash);
}

let colour = '#';

for (i = 0; i > (i * 8)) & 0xff;
colour += `00${value.toString(16)}`.substr(-2);
}

return colour;
}

Thanks to oliviertassinari: https://github.com/oliviertassinari/SplitMe/blob/c25fe62187a856386fd0c43c51859d6f973d651e/src/main/member/Avatar.js#L8-L26

Access to fetch from origin has been blocked by CORS policy – AWS SAM Local

Hi everyone,

I’ve been using AWS SAM local lately and ran into a bit of an issue with CORS. It took a looong time to find a solution that worked for all of my local scenarios so hopefully this will be able to help someone else out.

Access to fetch at 'http://127.0.0.1:3000' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

The error above is fairly typical when working with APIs. The request will work from tools such as postman and fiddler but browsers will block it. These are a few good links that explain why CORS is necessary:
https://medium.com/@electra_chong/what-is-cors-what-is-it-used-for-308cafa4df1a
https://stackoverflow.com/a/29167709/522859

As for the solution, add the following to your template.yml:

  PreFlightFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: functions/generic/cors.getPreflightHandler
      Runtime: nodejs8.10
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /pages
            Method: options
            RestApiId: !Ref XXXApi
            Auth:
              Authorizer: NONE

If you haven’t already defined your api in your template.yml file there is a default/omitted one created for you. There are a few examples on the AWS github: https://github.com/awslabs/serverless-application-model/blob/release/v1.8.0/examples/2016-10-31/api_cognito_auth/template.yaml

The next thing to do is to create a handler for the options request:


/* Handles retrieving a specific page */
exports.getPreflightHandler = async (event, context, callback) => {
    callback(null, { body: {} }, headers: { 'content-type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token', 'Access-Control-Allow-Methods': 'OPTIONS,GET,POST,PUT,PATCH,DELETE', 'Access-Control-Allow-Credentials': true }, statusCode: 200 })
};

I’ve moved all mine out to some helper methods but the above should be enough to get it working for you. Hopefully the AWS team will have a simpler solution soon but if you run into any issues in the meantime please let me know!