Dennis Sauve
  • Login
apacheconf bash cs css dotnet html javascript php regex sql typescript
Apache Force HTTPS

Use the .htaccess file to force https

# Force HTTPS
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
24 Hour Weather Report (CLI)

From the command line, get a simple weather report.

#!/bin/bash

# Check for w3m install on Mac
install=0;

command -v w3m >/dev/null || {
	install=1
	echo >&2 "I require w3m but it's not installed. Install? (Y/n)"
}

if [ "$install" = "1" ] 
then
	read userAnswer
	
	if [ "$userAnswer" = "Y" ]
	then
		echo "installing w3m"
		command -v brew update >/dev/null || {
			echo >&2 "I require brew to install w3m. Please install homebrew."
			break
		}
		brew install w3m
		w3m -dump weather.dennissauve.com | sed -n 13,20p
	else
		echo "aborting"
	fi
else
	w3m -dump weather.dennissauve.com | sed -n 13,20p
fi
Apple Notification from Bash

Use osascript bin to trigger a notification, handy when running longer build/push operations

osascript -e 'display notification "More detailed info about this task" with title "Task Status"'
Kill All PHP Processes

On a unix system, kill all running php processes

kill $(ps aux | grep '[p]hp' | awk '{print $2}')
SSH Config

Example of SSH Config file

Host example
    User exampleuser
    HostName cloud.example.com
    IdentityFile ~/.ssh/exampleKeyFile.pem
Restart VirtualBox Mac

Restarts with the startup script, useful for troubleshooting VirtualBoxCLI errors

sudo "/Library/Application Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh" restart
Wake me up...

September Cron Example

59 23 30 9 * ~/scripts/wake.sh
dotnet ModelState Dump

Helps with troubleshooting and debugging where model states may be a problem

var allErrors = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage));
No HTML Button Outline

Remove that damn pesky blue outline from your beautiful buttons

.button:focus{
    outline: none;
}
Absolute Center HTML El

Use CSS to absolutely center a CSS element

.main-header {
    display: inline-block;
    position: absolute;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
}
HTML bgcolor for print

Element styling to ensure the correct colors show for printing

body {
    -webkit-print-color-adjust: exact;
}
Filtering by apiRecordRequest - dotnet core

Example of filtering through apiRecordRequest filters - assumes the query has already been made, and refines it

foreach (var filter in apiRecordRequest.Filter.Filters)
{
    if (filter.Field == "id")
    {
        query = query.Where(x => x.Id == id);
    }
    // ... and so on and on
}
Bootstrap 4 Card Deck Break

Using a div with d-*-block to break card decks at certain views

<div class="card">
    <div class="card-body">
        <h5 class="card-title">Title</h5>
        <h6 class="card-subtitle mb-2 text-muted">Subtitle</h6>
        <p class="card-text">Text</p>
        <a href="#" class="card-link">Link</a>
    </div>
</div>

<div class="w-100 d-none d-sm-block d-md-block d-lg-none"><!-- wrap every 2 on sm--></div>

<div class="card">
    ...
</div>
Toast

Plain toast in JavaScript

<style type="text/css">
    #toastbar {
        visibility: hidden;
        min-width: 250px;
        margin-left: -125px;
        background-color: #333;
        color: #fff;
        text-align: center;
        border-radius: 2px;
        padding: 16px;
        position: fixed;
        z-index: 1;
        left: 50%;
        bottom: 30px;
        font-size: 17px;
    }

    #toastbar.show {
        visibility: visible;
        -webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
        animation: fadein 0.5s, fadeout 0.5s 2.5s;
    }

    @-webkit-keyframes fadein {
        from {bottom: 0; opacity: 0;}
        to {bottom: 30px; opacity: 1;}
    }

    @keyframes fadein {
        from {bottom: 0; opacity: 0;}
        to {bottom: 30px; opacity: 1;}
    }

    @-webkit-keyframes fadeout {
        from {bottom: 30px; opacity: 1;}
        to {bottom: 0; opacity: 0;}
    }

    @keyframes fadeout {
        from {bottom: 30px; opacity: 1;}
        to {bottom: 0; opacity: 0;}
    }
</style>

<button onclick='doThing()'>Copy</button>

<div id="toastbar">Toast Message</div>

<script type="text/javascript">
    function doThing() {
        // Something
        showToast();
    }
    function showToast() {
        let toast = document.getElementById("toastbar");
        toast.className = "show";
        setTimeout(function(){ toast.className = toast.className.replace("show", ""); }, 3000);
    }
</script>
CSS Pagebreak for Printing

CSS style and HTML div for creating pagebreaks when printing

<style>
@media print {
    .pagebreak {
        clear: both;
        page-break-after: always;
    }
}
</style>

<!-- page 1 content here -->

<div class="pagebreak"></div>

<!-- page 2 content here -->
Angular KendoGrid Loading Template

Shows a loading spinner in a kendo grid

<kendo-grid [data]="yourData" [loading]="isDataLoading">
    <ng-template #noRecordsTemplate kendoGridNoRecordsTemplate>
      <div [innerHTML]="noDataMessage"></div>
      </ng-template>
      ...
</kendo-grid>
Angular KendoGrid Id Link

Template for kendo-grid-column to be an edit link

<kendo-grid-column>
    <ng-template kendoGridCellTemplate let-dataItem>
        <a style="text-decoration: underline" [routerLink]="[dataItem.id]+'/edit'">\{\{ dataItem.id \}\}</a>
    </ng-template>
</kendo-grid-column>
Vue Single File Component

Template

<template>

</template>

<script>
export default {
    data: function () {
        return {}
    }
}
</script>

<style scoped>

</style>
Single File Vue Component Template

Basic Single File Template

<template>
    
</template>

<script>
module.exports = {
    data: function () {
        return {}
    }

}
</script>

<style scoped>

</style>
Copy to Clipboard

Use JS to copy text to clipboard

function copyLinkToClipboard(link) {
    navigator.clipboard.writeText(link).then(function() {
        // Success condition
    }, function() {
        // failure condition
    });
}
Symfony Callback Constraints

Symfony form builder - Callback constraints using closure to compare against other form fields

'constraints'     => array(
    new Callback(function($zip, ExecutionContextInterface $context) {
        $addressType = $context->getObject()->getParent()['summ_address_type']->getData();
        if($addressType == "Domestic" && !$zip) {
            $context->buildViolation('A zipcode is required for domestic addresses.')->addViolation();
        }
    })
)
Non-Curl Post in PHP

Make a post request and handle response

$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded
",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);
CSV (w/headers) to array

Creates an array of associative arrays with headers/data from CSV

private function csvToArray($filename)
{
    $rows   = array_map('str_getcsv', file($filename));
    $header = array_shift($rows);
    $csv    = array();
    foreach($rows as $row) {
        $csv[] = array_combine($header, $row);
    }

    return $csv;
}
Google reCaptcha v2 in PHP

Verification code for google's reCaptcha system, version 2. This is for a checkbox style verification.

// URL to verify reCaptcha was successful
$url = 'https://www.google.com/recaptcha/api/siteverify';

// Parameters to pass in POST
$g_response = $_POST['g-recaptcha-response'];
$g_secret = 'yourSecretHere';
$data = array(
    'secret' => $g_secret,
    'response' => $g_response,
);

// config context options
$options = array(
    'http' => array(
        'header' => "Content-type: application/x-www-form-urlencoded
",
        'method' => 'POST',
        'content' => http_build_query($data)
    )
);

// create context and get result
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

// Check if valid result from reCaptcha verification
if ($result === FALSE) {
    // bad request handler
} else {
    // decode response to JSON
    $g_result = json_decode($result);

    // Check if reCaptcha was validated
    if (!$g_result->success) {
        // bad reCaptcha handler
    }
    // Let page load normally if reCaptcha was successfully validated.
}
Imagick from S3 & Conversion

Secured S3 Retrieval & png conversion

$handle = file_get_contents($s3SecureBucketLink);
$image = new Imagick();
$image->readImageBlob($handle);
$image->setImageFormat("png");
echo "<img src="data:image/png;base64," . base64_encode($image->getImageBlob()) . " />";
Upload File to S3

Using AWS's PHP SDK, upload a file from a request to an S3 bucket

$file           = $request->files->get('fileInput');
$documentName   = 'thisfile.ext'; // based on framework, methods for getting name will vary
$fileName       = time() . $documentName; // ensuring minimal chance of duplicate file names in bucket
$bucket         = $this->getParameter('aws_config')['bucket'];

$s3Client = $this->getS3Client();
$s3Client->putObject(array(
    'Bucket'    => $bucket,
    'Key'       => $fileName,
    'Body'      => fopen($file, 'r+'),
    'Metadata'  => array()
));
AWS S3 Client

Create an S3 Client in PHP using the AWS PHP SDK

$s3Client = S3Client::factory(array(
    'region' => $region,
    'credentials' => array(
        'key' => $key,
        'secret' => $secret
    )
));
Laravel - Moodle API Request

Example of an API call to Moodle from Laravel

// Build parameters for API query.
$params = [
    'wsfunction' => 'core_enrol_get_users_courses',
    'moodlewsrestformat' => 'json',
    'userid' => $userID,
];

// Add the moodle token to the request
$params['wstoken'] = env('MOODLE_TOKEN', 'moodle_token');

// Build the request URL
$url = rtrim(env('MOODLE_URL'), '/') .
    '/webservice/rest/server.php?' .
    http_build_query($params);

file_get_contents($url, false, stream_context_create([
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
]));
Laravel - Modify JSON

Add a new item to a JSON array that belongs to an object and is stored.

function addSource($source)
{
    $data = $this->data;
    $arr = [];

    if(isset($this->data['target'])) $arr = $data['target'];

    array_push($arr, $source);
    $data['target'] = $arr;
    $this->data = $data;

    $this->save();
}
Regex for ML tags

A regex pattern to identify HTML/XML tags

<[^>]*>
Search for column name

Search DB tables for columns with a keyword in its name

select t.table_schema,
       t.table_name
from information_schema.tables t
inner join information_schema.columns c on c.table_name = t.table_name 
                                and c.table_schema = t.table_schema
where c.column_name = 'last_name'
      and t.table_schema not in ('information_schema', 'pg_catalog')
      and t.table_type = 'BASE TABLE'
order by t.table_schema;
Load in Service

constructor( private offenseCategoryApiService : OffenseCategoriesApiService) {
    this.offenseCategoryApiService.getAll().toPromise().then();
Await Observable (finally)

Await on an observable's next n emit(s)

// n is the number of emits from the subscription
const n = 1
await subscription.take(n).toPromise();
Time Difference from DateTimes

Get the Day:Hour:Minute:Second time difference between two dates

getDateTimeDiff(a: string, b: string) {
    let aTime = new Date(a);
    let bTime = new Date(b);
    let diff = Math.floor((aTime.getTime() - bTime.getTime()) / 1000);
    
    let days = Math.floor(diff / 86400);
    diff = diff - (days * 86400);
    let hours = Math.floor(diff / 3600);
    diff = diff - (hours * 3600);
    let minutes = Math.floor(diff / 60);
    diff = diff - (minutes * 60);
    
    return `${days.toString()}:${hours.toString()}:${minutes.toString()}:${diff.toString()}`;
}
Angular: Element in ViewPort

Be able to see in Angular if an element is currently in the viewport

// Must be passed a ViewChild.nativeElement
isInViewport(elem) {
  let bounding = elem.getBoundingClientRect();
  return (
      bounding.top >= 0 &&
      bounding.left >= 0 &&
      bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
};
Angular Provide Download from API

Passing through a download to the end user, using an api service

import { HttpClient } from "@angular/common/http";
import { saveAs } from "file-saver";

@Injectable()
export class ApiService {
  constructor(
      private http: HttpClient
  ) {
  }

  getFile(path: string): void {
    const url = `${environment.apiUrl}${path}`;

    // cast to json make interpreter happy, @see https://github.com/angular/angular/issues/18586
    const options = { responseType: 'blob' as 'json' };
    const req = this.http.get<Blob>(url, options);

    req.subscribe((data) => {
      saveAs(data, 'info');
    });
  }
}
Angular Form Group

Adding a form control w/validator

let editForm = new FormGroup({
    formControlName: new FormControl(defaultItem, Validators.required),
});
Form Loading

Some basic form loading logic for and Angular form

@Component({
  selector: 'app-my-form',
  template: `
    <div class="grid-wrapper">
      <form>...</form>
      <div *ngIf="isLoading" class="k-i-loading"></div>
    </div>`,
  styles: [`
    .grid-wrapper {
      position: relative;
    }
    .k-i-loading {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      font-size: 64px;
      background-color: rgba(255,255,255,.3);
      color: #ff6757;
    }
  `]
})
export class MyFormComponent {
  private isLoading;

  // Whenever you're done loading
  this.isLoading = false;
}
Angular KendoGrid Loading Logic

Controls KendoGrid loading spinners display

@ViewChild('noRecordsTemplate', {static: false}) noRecordsTemplate;
noDataMessage = "<br/><br/>";
isDataLoading: boolean = false;

this.isDataLoading = true;
this.noDataMessage = result.total == 0 ? "No Records to Display" : "<br/><br/>";
this.isDataLoading = false;
Check out my resume