##########################
# Dennis's Code Snippets #
##########################


New Snippet

###
php
###

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\r\n",
        '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);

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\r\n",
        '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.
}

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();
}

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();
        }
    })
)

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
    )
));

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()
));



####
bash
####

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

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



###
css
###

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;
}



#####
regex
#####

Regex for ML tags
A regex pattern to identify HTML/XML tags

<[^>]*>



##########
apacheconf
##########

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]



##########
typescript
##########

Load in Service

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

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;

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 Form Group
Adding a form control w/validator

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

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: 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)
  );
};

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()}`;
}

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();



##
c#
##

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));



####
html
####

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>

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 -->



######
dotnet
######

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
}



###
sql
###

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;



#####################
https://0daymusic.org
#####################

BarrySkedo

Hello, 
 
* FTP MP3 server and direct download of everything: https://www.0daymusic.org/premium.php 
* Resellers: PayPal, VISA, Bank Transfer, Bitcoin, Mastercard, Amazon Pay, WebMoney... 
* FTPtxt-16 software: https://www.0daymusic.org/FTPtxt for text search. 
* Server capacity: 440 TB MP3, FLAC, labels, music videos. 
* Supports: FTP, FTPS (File Transfer Protocol Secure), SFTP, and HTTP, HTTPS. 
* Daily updates: 30-100 GB, 300-2000 albums, web, promo, CDM, CDR, CDS, EP, LP, vinyl... 
* Unlimited download speed. 
* Files available anytime. 
* Over 17 years of archive. 
* Total server speed: 1 Gbps. 
* User-friendly. Most genres are sorted by day. 
 
0-DAY TEAM



#########################################
http://78.29.53.57/freeinsurance/?s1=xrum
#########################################

MelvinAbofe
http://78.29.53.57/freeinsurance/?s1=xrum

Get free Blockchain Insurance globally! 
 
Get professional insurance of global importance from an insurer in Chelyabinsk, Russia. 
 
Without personal data, cookie and JS. 
 
We got access to the US market without compromising. 
 
More than 85 types of non-criminal insurance. 
 
Once a month, a document is created that can be shown to the regulatory authorities. We're taking over the negotiations. 
 
We insure risks such as: 
1. Arbitrary legislation 
2. Arbitrariness of the Central Bank 
3. Possible harm to other people 
 
Link (own hosting): http://78.29.53.57/freeinsurance/?s1=xrum 
 
http://78.29.53.57/freeinsurance/?s1=xrum 
 
By brand ChelyabinskMAN