WordPress Development

Note: All code was migrated into plugins. They are combined here for brevity.


<?php
/**
 * Shopkeeper child functions and definitions
 * PHP 5.4, Apache 2.4, CentOS 7.3
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @author Joe Rocha <&#91;REDACTED&#93;@ucla.edu>
 * @package WordPress
 * @subpackage shopkeeper-child
 * @since 1.0
 */

/**
 * Check if page template
 * If so, register an agreement form pop-up
 *
 * @param object $template Used to validate user is on 'page'.
 * @return string $template "".
 */
function check_page_template( $template ) {
	if ( is_page( 'checkout' ) ) {
		wp_register_script( 'agreement', get_stylesheet_directory_uri() . '/js/agreement.js', array( 'jquery' ) );\
		wp_enqueue_script( 'agreement' );
	}
	return $template;
}
add_filter( 'template_include', 'check_page_template', 10, 1 );



/**
 * Add product_page.js
 * File to display warning when not purchasing back-up and sync dropdowns
 *
 * @param string $template Content of the current post.
 * @return string $template "".
 */
function js_product( $template ) {
	if ( is_front_page() ) {
		wp_register_script( 'js-prod', get_stylesheet_directory_uri() . '/js/product_page.js', array( 'jquery' ),'1.1', true );
		wp_enqueue_script( 'js-prod',  true );
	}

	return $template;
}
add_action( 'template_include', 'js_product', 1, 1 );



/**
 * Limit to one item in cart
 * Objective is to limit user to one item purchase at a time
 *
 * @param object $cart_item_data Users cart item and attributes.
 */
function woo_custom_add_to_cart( $cart_item_data ) {
	global $woocommerce;
	$woocommerce->cart->empty_cart();

	return $cart_item_data; /* Do nothing with the data and return */
}
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );



/**
 * Change status of new orders from "on-hold" to "processing"
 *
 * @param int $order_id Order's Unique Identifier.
 */
function custom_woocommerce_auto_complete_order( $order_id ) {
	if ( ! $order_id ) {
		return;
	}
	$order = new WC_Order( $order_id );
	$order->update_status( 'processing' );
}
add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );



/**
 * Add custom order meta to orders
 * Adds Shibboleth and other metadata to order's custom Meta.
 *
 * @param object $order_id Unique identifier of order.
 * @global object $wpdb WordPress Database call.
 * @global object $woocommerce object Woocommerce objects, used for cart items.
 */
function change_adds_order_meta( $order_id ) {
	// Input Sanitation https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/wiki/Fixing-errors-for-input-data !
	! isset( $_POST['h2_group'] ) ?: $sponsor_group = sanitize_text_field( wp_unslash( $_POST['h2_group'] ) );
	! isset( $_SERVER['HTTP_SHIBUCLAPERSONMIDDLENAME'] ) ?: $shib_middlename = sanitize_text_field( wp_unslash( $_SERVER['HTTP_SHIBUCLAPERSONMIDDLENAME'] ) );
	! isset( $_SERVER['HTTP_SHIBUCLAEMPLOYEECAMPUSPHONE'] ) ?: $shib_phone = sanitize_text_field( wp_unslash( $_SERVER['HTTP_SHIBUCLAEMPLOYEECAMPUSPHONE'] ) );
	! isset( $_SERVER['HTTP_SHIBUCLAEMPLOYEEHOMEDEPARTMENTNAME'] ) ?: $shib_dept = sanitize_text_field( wp_unslash( $_SERVER['HTTP_SHIBUCLAEMPLOYEEHOMEDEPARTMENTNAME'] ) );
	! isset( $_SERVER['REDIRECT_SHIBUCLAPPID'] ) ?: $shib_uclaappid = sanitize_text_field( wp_unslash( $_SERVER['REDIRECT_SHIBUCLAPPID'] ) );

	global $wpdb; /* WP Database */

	$sponsor_contact = wp_cache_get( 'cached_sponsor_query' );
	if ( false === $sponsor_contact ) {
		$sponsor_contact = $wpdb->get_var( $wpdb->prepare( ' SELECT `[REDACTED]` FROM `[REDACTED]` WHERE `gname` = %s' , $sponsor_group ) );
		wp_cache_set( 'cached_sponsor_query', $sponsor_contact, '', 300 );
	}

	$sponsor_gid = wp_cache_get( 'cached_sponsor_gid' );
	if ( false === $sponsor_gid ) {
		$sponsor_gid = $wpdb->get_var( $wpdb->prepare( ' SELECT `[REDACTED]` FROM `[REDACTED]` WHERE `[REDACTED]` = %s' , $sponsor_group ) );
		wp_cache_set( 'cached_sponsor_gid', $sponsor_gid, '', 300 );
	}

	update_post_meta( $order_id, 'middle_name', $shib_middlename );
	update_post_meta( $order_id, 'middle_name', $shib_middlename );
	update_post_meta( $order_id, 'phone_number', $shib_phone );
	update_post_meta( $order_id, 'shib_dept_name', $shib_dept );
	update_post_meta( $order_id, 'shib_app_id', $shib_uclaappid );
	update_post_meta( $order_id, 'sponsor_contact', $sponsor_contact );
	update_post_meta( $order_id, 'gid', $sponsor_gid );

	$cart_items = WC()->cart->get_cart();
	foreach ( $cart_items as $cart_item ) {
		$gravity = $cart_item['_gravity_form_lead'];
	}
	$years = $gravity[19]; // Do not remove!
	update_post_meta( $order_id, 'terabytes', $gravity[16] );
	update_post_meta( $order_id, 'years', $years );

	if ( 149.35 == $gravity[18] ) { // Strict === causes false...
		$backup = 'Yes';
	} else {
		$backup = 'No';
	}
	update_post_meta( $order_id, 'backup', $backup );
	update_post_meta( $order_id, 'total', $gravity[20] );
	update_post_meta( $order_id, 'upfront_cost', $gravity );

	// Calculate Expiration date.
	$date = date( 'Y-m-d' );
	$date_num = strtotime( $date );

	! isset( $_POST['fau_expiration_date'] ) ?: $fau_expiration_date = sanitize_text_field( wp_unslash( $_POST['fau_expiration_date'] ) );

	update_post_meta( $order_id, 'fau_expiration_date', $fau_expiration_date );
	$fau_expiration_date_num = date( 'Y-m-d', strtotime( $fau_expiration_date ) ); // Parse textual datetime description into a Unix timestamp.

	switch ( $years ) {

		case 1:
			$order_end_date = strtotime( date( 'Y-m-d', $date_num ) . ' +12 month' );
			$order_end_date_formatted = date( 'Y-m-d', $order_end_date );
		break;

		case 2:
			$order_end_date = strtotime( date( 'Y-m-d', $date_num ) . ' +24 month' );
			$order_end_date_formatted = date( 'Y-m-d', $order_end_date );
		break;

		case 3:
			$order_end_date = strtotime( date( 'Y-m-d', $date_num ) . ' +36 month' );
			$order_end_date_formatted = date( 'Y-m-d', $order_end_date );
		break;

		case 4:
			$order_end_date = strtotime( date( 'Y-m-d', $date_num ) . ' +48 month' );
			$order_end_date_formatted = date( 'Y-m-d', $order_end_date );
		break;

		case 5:
			$order_end_date = strtotime( date( 'Y-m-d', $date_num ) . ' +60 month' );
			$order_end_date_formatted = date( 'Y-m-d', $order_end_date );
		break;
	}

	update_post_meta( $order_id, 'order_end_date', $order_end_date_formatted );

	// Check if FAU Expiration is prior to length of Order period.
	if ( $fau_expiration_date_num < $order_end_date && 1 != $years && ! empty( $fau_expiration_date ) ) {
		update_post_meta( $order_id, 'fau_expire_early', 'yes' );
	} else {
		update_post_meta( $order_id, 'fau_expire_early', 'no' );
	}

} //END - ADD SHIB TO CUSTOM META
add_action( 'woocommerce_checkout_update_order_meta', 'change_adds_order_meta', 10, 1 );


/**
 * WooCommerce: Allow editing of all orders regardless of status
 */
function add_order_statuses_to_editable() {
	return true;
} // END WooCommerce: Allow editing of all orders regardless of status
add_filter( 'wc_order_is_editable', 'add_order_statuses_to_editable' );


/**
 * AutoFill Checkout
 * https://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/
 *
 * @param string $fields Data fields on checkout.
 */
function custom_override_checkout_fields( $fields ) {
	$current_user = wp_get_current_user();
	$fields&#91;'billing'&#93;&#91;'billing_first_name'&#93;&#91;'default'&#93; = $current_user->user_firstname;
	$fields['billing']['billing_last_name']['default'] = $current_user->user_lastname;
	$orders = get_posts(
		apply_filters(
			'woocommerce_my_account_my_orders_query', array(
			'author'		=> $current_user->ID,
			'numberposts'	=> 1, /* -1 for all orders */
			'meta_key'		=> '_customer_user',
			'post_type'		=> 'shop_order',
			'post_status'	=> 'wc-completed',
			)
		)
	);
	$order_obj = $orders[0];
	$pastid = $order_obj->ID;

	$labels = array(
		'h2_user',
		'h2_group',
		'mountpoint',
		'checkout_deptchoice',
		'sharing-pref',
		'quota',
		'technical_contact_first',
		'technical_contact_last',
		'technical_contact_email',
		'business_firstname',
		'business_lastname',
		'business_email',
		'dept_code',
		'recharge_id',
		'loc',
		'account',
		'cc',
		'fund',
		'project',
		'sub',
		'object',
		'source',
		'order_memo',
	);

	foreach ( $labels as $label ) {
		$fields['order'][ $label ]['default'] = get_post_meta( $pastid, $label , true );
	}

	return $fields;
} /* END AutoFill Checkout */
add_filter( 'woocommerce_checkout_fields', 'custom_override_checkout_fields', 1001 );



/**
 * ADD CUSTOM FIELDS TO ORDER EMAILS
 *
 * @param string $keys Key value of custom checkout fields.
 */
function my_woocommerce_email_order_meta_keys( $keys ) {
	$keys['H2 User'] = 'h2_user';
	$keys['H2 Group'] = 'h2_group';
	$keys['billing first name'] = 'billing_first_name';
	$keys['billing last name'] = 'billing_last_name';
	$keys['billing email'] = 'billing_email';
	$keys['Mount Point'] = 'mountpoint';
	$keys['Sharing Preferences'] = 'sharing-pref';
	$keys['Quota Sharing'] = 'quota';
	$keys['Specific Requests'] = 'quota-req';
	$keys['Department Information'] = 'department-information';
	$keys['Department list'] = 'checkout_deptchoice';
	$keys['Technical Contact First Name'] = 'technical_contact_first';
	$keys['Technical Contact Last Name'] = 'technical_contact_last';
	$keys['Technical Contact Email'] = 'technical_contact_email';
	$keys['Business First Name'] = 'business_firstname';
	$keys['Business Last Name'] = 'business_lastname';
	$keys['Business Email'] = 'business_email';
	$keys['Department code'] = 'dept_code';
	$keys['Recharge id'] = 'recharge_id';
	$keys['Loc'] = 'loc';
	$keys['Account'] = 'account';
	$keys['CC'] = 'cc';
	$keys['Fund'] = 'fund';
	$keys['Project'] = 'project';
	$keys['Sub'] = 'sub';
	$keys['Object'] = 'object';
	$keys['Source'] = 'source';
	$keys['FAU expiration'] = 'fau_expiration_date';
	$keys['Order Memo Joe'] = 'order_memo';
} // END - ADD CUSTOM FIELDS TO ORDER EMAILS
add_filter( 'woocommerce_email_order_meta_keys', 'my_woocommerce_email_order_meta_keys' );



/**
 * Validate FAU at checkout
 */
function validate_fau() {
	include_once 'fau_validation_checkout.php';

	if ( 'S' !== $decoded['Flag'] ) {
		wc_add_notice(
			__(
				'FAU Invalid. Please update to complete your order.'
				 . '<br>DEBUG INFO:' . $curl_response
			), 'error'
		);
	}
} // End - Validate FAU at checkout
add_action( 'woocommerce_checkout_process', 'validate_fau' );



/**
 * Validate H2Group at checkout
 */
function validate_h2_group() {
	global $wpdb; /* Database Interaction */

	$sponsors_1 = wp_cache_get( 'cached_sponsor_1' );
	if ( false === $sponsors_1 ) {
		$sponsors_1 = $wpdb->get_col( 'SELECT [REDACTED] FROM [REDACTED]' );
		wp_cache_set( 'cached_sponsor_1', $sponsors_1, '', 300 );
	}

	$sponsors_2 = wp_cache_get( 'cached_sponsor_2' );
	if ( false === $sponsors_2 ) {
		$sponsors_2 = $wpdb->get_col( 'SELECT [REDACTED] FROM ProjectGroupSponsor' );
		wp_cache_set( 'cached_sponsor_2', $sponsors_2, '', 300 );
	}

	$sponsors = array_merge( $sponsors_1, $sponsors_2 );

	! isset( $_POST['h2_group'] ) ?: $sponsor_group = sanitize_text_field( wp_unslash( $_POST['h2_group'] ) );
	if ( ! in_array( $sponsor_group, $sponsors ) ) {
		wc_add_notice( __( 'H2 User Group does not exist. Please update to complete your order.' ), 'error' );
	}
}
add_action( 'woocommerce_checkout_process', 'validate_h2_group' );



/**
 * Extend Calendar length
 */
function custom_adjust_datepicker_range() {
	if ( is_checkout() ) {
		wp_enqueue_script( 'jquery' );
?>
<script type="text/javascript">
jQuery( document ).ready( function ( e ) {
	if ( jQuery( '.checkout-date-picker' ).length ) {
		jQuery( '.checkout-date-picker' ).datepicker( 'option', 'changeYear', true );
		jQuery( '.checkout-date-picker' ).datepicker( 'option', 'yearRange', '-0:+10' );
	}
});
</script>
<?php
	}
}
add_action( 'wp_footer', 'custom_adjust_datepicker_range', 50 );


/**
 * Add Email table data to order details page
 *
 * @param object $order Order information.
 * @return void
 */
function new_custom_fields( $order ) {
	include_once get_stylesheet_directory() . '/email_table_add.php';
}
add_action( 'woocommerce_admin_order_data_after_order_details', 'new_custom_fields', 10, 1 );



/**
 * Include email table items
 *
 * @param object $order Order data.
 */
function custom_woocommerce_email_after_order_table( $order ) {
	include_once get_stylesheet_directory() . '/email_table_add.php';
}
add_action( 'woocommerce_email_after_order_table', 'custom_woocommerce_email_after_order_table', 10, 1 );



/**
 * Convert Woocommerce Text
 *
 * @param string $translated Filtered Core strings.
 */
function translate_text( $translated ) {
	$translated = str_ireplace( 'Billing Address', 'User Info', $translated );
	$translated = str_ireplace( 'Billing Details', 'Edit Order Initiator', $translated );
	$translated = str_ireplace( 'Shipping Details', '', $translated );
	$translated = str_ireplace( 'Subscription Information:', 'Entitlement Information', $translated );
	$translated = str_ireplace( 'Years:', 'Months:', $translated );
	$translated = str_ireplace( '3 year', '36 months', $translated );
	return $translated;
} // END - Convert Text
add_filter( 'gettext', 'translate_text' );
add_filter( 'ngettext', 'translate_text' );
&#91;/code&#93;

<h3>Laravel Controller</h3>



<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Title as Title;
use App\Client as Client;

class ClientController extends Controller
{
    //
    public function __construct( Title $titles, Client $client )
    {
        $this->titles = $titles->all();
        $this->client = $client;
    }

    public function di()
    {
        dd($this->titles);
    }

    public function index()
    {
        $data = [];

        $data['clients'] = $this->client->all();
        return view('client/index', $data);
    }

    public function newClient( Request $request, Client $client )
    {
        $data = [];

        $data['title'] = $request->input('title');
        $data['name'] = $request->input('name');
        $data['last_name'] = $request->input('last_name');
        $data['address'] = $request->input('address');
        $data['zip_code'] = $request->input('zip_code');
        $data['city'] = $request->input('city');
        $data['state'] = $request->input('state');
        $data['email'] = $request->input('email');
        

        if( $request->isMethod('post') )
        {
            //dd($data);
            $this->validate(
                $request,
                [
                    'name'          =>  'required | min:3',
                    'last_name'     =>  'required',
                    'address'       =>  'required',
                    'zip_code'      =>  'required',
                    'city'          =>  'required',
                    'state'         =>  'required',
                    'email'         =>  'required',
                ]
            );

            $client->insert($data);

            return redirect('clients');
        }
        $data['titles'] = $this->titles;
        $data['modify'] = 0;
        return view('client/form', $data);
    }

    public function create()
    {
            return view('client/create');
    }

    public function show($client_id)
    {
        $data = []; 
        $data['client_id'] = $client_id;
        $data['titles'] = $this->titles;
        $data['modify'] = 1;
        $client_data = $this->client->find($client_id);
        $data['name'] = $client_data->name;
        $data['last_name'] = $client_data->last_name;
        $data['title'] = $client_data->title;
        $data['address'] = $client_data->address;
        $data['zip_code'] = $client_data->zip_code;
        $data['city'] = $client_data->city;
        $data['state'] = $client_data->state;
        $data['email'] = $client_data->email;

        return view('client/form', $data);
    }
    
    public function modify( Request $request, $client_id, Client $client )
    {
        $data = [];

        $data['title'] = $request->input('title');
        $data['name'] = $request->input('name');
        $data['last_name'] = $request->input('last_name');
        $data['address'] = $request->input('address');
        $data['zip_code'] = $request->input('zip_code');
        $data['city'] = $request->input('city');
        $data['state'] = $request->input('state');
        $data['email'] = $request->input('email');
        

        if( $request->isMethod('post') )
        {
            //dd($data);
            $this->validate(
                $request,
                [
                    'name'          =>  'required | min:3',
                    'last_name'     =>  'required',
                    'address'       =>  'required',
                    'zip_code'      =>  'required',
                    'city'          =>  'required',
                    'state'         =>  'required',
                    'email'         =>  'required',
                ]
            );

            $client_data = $this->client->find($client_id);

            $client_data->title = $request->input('title');
            $client_data->name = $request->input('name');
            $client_data->last_name = $request->input('last_name');
            $client_data->address = $request->input('address');
            $client_data->zip_code = $request->input('zip_code');
            $client_data->city = $request->input('city');
            $client_data->state = $request->input('state');
            $client_data->email = $request->input('email');

            $client_data->save();

            return redirect('clients');
        }

        return view('client/form', $data);
    }


}


 

FAU Validation API Developed in PHP framework WordPress/WooCommerce

$loc = ! empty( $_POST['loc'] ) ? (string) $_POST['loc'] : '4';
$acct = ! empty ( $_POST['account'] ) ? (string) $_POST['account'] : '';
$cc = ! empty ( $_POST['cc'] ) ? (string) $_POST['cc'] : '';
$fund = ! empty ( $_POST['fund'] ) ? (string) $_POST['fund'] : '';
$project = ! empty( $_POST['project'] ) ? (string) $_POST['project'] : '';
$sub = ! empty( $_POST['sub'] ) ? (string) $_POST['sub'] : $sub = '03';
$obj = ! empty( $_POST['object'] ) ? (string) $_POST['object'] : '';
$source = ! empty( $_POST['source'] ) ? (string) $_POST['source'] : '';
$effective_date = date("c", time());
$doc_date = date("c", time());
$order_total = WC()->cart->total;
$rech_id = ! empty( $_POST['recharge_id'] ) ? (string) $_POST['recharge_id'] : 'RCH';

$data = [
            array(
    "Location" => $loc,
    "Account" => $acct,
    "CC" => $cc,
    "Fund" => $fund,
    "Project" => $project,
    "SubCode" => $sub,
    "ObjectCode" => $obj,
    "Source" => $source,
    "Description" => "HPC Storage",
    "Amount" => $order_total,
    "Ssid" => "RCH",
    "TypeEntry" => "59",
    "EffectiveDate" => $effectiveDate,
    "DocumentDate" => $docDate,
)];

$curl_post_data = json_encode($data);
$service_url = "https://xxxxxxx"

curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($curl, CURLOPT_HTTPHEADER, array(  
    'Accept: application/json',                                                                        
    'Content-Type: application/json',                                                                               
    'Content-Length: ' . strlen($curl_post_data),
    )
);
$curl_response = curl_exec($curl);

 

Python script developed to fix 35k+ broken html links for UCLA's Statistics website

#!/usr/bin/python
import re
import os

root_directory = '/Users/JoeRocha/Desktop/stat/'
replacements = {}

def go_up(subdir, num_level):
	x = subdir
	for i in range(num_level):
		x = os.path.split(x)[0]
	return x

for subdir, dirs, files in os.walk(root_directory):
	
	for file in files:

		if file.endswith(".htm") or file.endswith(".html"):
			full_path = os.path.join(subdir, file)
			out_path = os.path.join('/Users/JoeRocha/Desktop/NEW'+subdir)
			out_path = out_path.replace('/NEW/Users/JoeRocha/Desktop/','/NEW/')
			out_path_full = full_path.replace('/Desktop/','/Desktop/NEW/')

			if not os.path.exists(out_path):
				os.makedirs(out_path)
	
			with open(full_path, "r") as infile, open(out_path+"/"+file, 'w') as outfile:

				for line in infile:
					
					relative = re.findall(r'href="(\.\.\/.\.\/\.\.\/\.\.\/.+?"|\.\.\/\.\.\/\.\.\/.+?"|\.\.\/\.\.\/.+?"|\.\.\/.+?")', line, flags=re.I | re.M)
					alllinks = re.findall(r'href="([^/].+?")', line, flags=re.I | re.M)
					
					for link in relative: #converts relative list to string
						link = link.replace("\"","")
						oldlink = link
						print 'Original link:',oldlink, "in",out_path_full
						link = link.replace("../../../../", go_up(subdir, 4)+"/")
						link = link.replace("../../../", go_up(subdir, 3)+"/")
						link = link.replace("../../", go_up(subdir, 2)+"/")
						link = link.replace("../", "/"+go_up(subdir, 1)+"/")
						link = link.replace("/Users/JoeRocha/Desktop/","/")
						link = link.replace("/stat/","/")
						link = link.replace("//","/")
						print 'Modified by 1st:',link
						print '\n'
						replacements = {oldlink:link}
					
					for links in alllinks:
						if (not links.startswith('HTTP')) and (not links.startswith('http')) and (not links.startswith('ftp')):
							subdirfix = subdir.replace("/Users/JoeRocha/Desktop","")
							if not links.startswith(subdirfix):
								links = links.replace("\"","")
								oldlink = links
								print "Original:",oldlink
								link = "/"+subdirfix+"/"+links
								link = "/"+subdirfix+"/"+links
								link = link.replace("/Users/JoeRocha/Desktop/","")
								link = link.replace("/stat/","")
								link = link.replace("//","/")
								print "Modified by 2nd:",link
								print '\n'
								replacements = {oldlink:link}
					
					for src, target in replacements.iteritems():
						line = line.replace(src, target)
					outfile.write(line)


			print "written to",out_path_full
			print '\n'

Python HTML parsing libraries would not work because of numerous human errors in original mark-up.

 

Development in Python Framework Pyramid

from pyramid.response import Response
from pyramid.renderers import render_to_response
from pyramid.view import view_config
from sqlalchemy.exc import DBAPIError
import logging
import transaction
import json
from sqlalchemy import (
    update,
    and_,
    select,
    desc
    )

from .models import (
    DBSession,
    #MyModel,
    t_dept,
    t_human,
    )

@view_config(route_name='secure', renderer='templates/xxxxxx')
def logged_in(request):

    """
    Shibboleth Attributes passed to HTTP HEADER once logged in with IAMUCLA. URL = "xxxxxx" 
    """

    header = dict(request.headers.items()) 
    name = 'Full Name: ' + header["Ajp-*****"]
    email = 'Email: ' + header["Ajp-****"]
    firstname = 'First Name: ' + header["Ajp-*****"]
    lastname = 'Last Name: ' + header["Ajp-*****"]
    uclalogin = 'UCLA Login ID: ' + header["Ajp-*****"] 
    return {'project':"Shibboleth attributes demo", 'tal_name':name, 'tal_email':email, 'tal_firstname':firstname,'tal_lastname':lastname, 'tal_uclalogin':uclalogin}


@view_config(route_name='home', renderer='templates/xxxx')
def update_db(request):
     
    try:

        email_query = DBSession.query(*****.c.email).all();

        name_query = DBSession.query(****.c['firstname'], *****.c['lastname']).all();

        concat_names = [ str(t[0]+' '+t[1]) for t in name_query]

        to_change = request.POST.get('selected_name')

        update_email = request.POST.get('new_email')


        if 'form.submitted' in request.POST:

            try:
 
                last_name = to_change.split(' ', 1)[1]

                new_email = ****.update().\
                                where(****.**** == last_name).\
                                values(email = update_email)



                DBSession.execute(new_email)

                DBSession.commit() 

            except DBAPIError:
                return Response(conn_err_msg, content_type='text/plain', status_int=500)

    except DBAPIError:
        return Response(conn_err_msg, content_type='text/plain', status_int=500)
    
    return {'project':"xxxx", 'names': concat_names, 'to_change':to_change, 'show_email':update_email}


conn_err_msg = """\
Pyramid is having a problem using your SQL database.  The problem
might be caused by one of the following things:

1.  You may need to run the "initialize_sim_db" script
    to initialize your database tables.  Check your virtual
    environment's "bin" directory for this script and try to run it.

2.  Your database server may not be running.  Check that the
    database server referred to by the "sqlalchemy.url" setting in
    your "development.ini" file is running.

3.  Joe, check on xxxxx.

After you fix the problem, please restart the Pyramid application to
try it again.
"""

 

Java "Fun" Fundamental's OIT Workshop

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

import static java.lang.System.out;

/**
 * OIT's "Intro to Java" Workshop
 * Your presenter: Joe S. Rocha 
 */

public class Playground {

    // Primitive Types
    boolean answer = true; // of false
    char a = 'A';
    byte byteMin = -128; // 8-bit signed integer (-128 - 127)
    short shortMin = -32; // 16-bit signed integer
    int age = 32; // 32-bit signed integer
    long rando = 234232; // 64-bit signed integer
    float pi = 3.14f; // 32-bit floating point (decimal point value)
    double sixtyFour = 3.14159; // 64-bit floating point (decimal point value)

    // Constructor
    Playground() {
        out.println("Constructor!");
    }

    // Static Method
    static int staticMethod(int staticMethodArg) {
        return staticMethodArg;
    }

    // Instance Method
    int instanceMethod(int instanceMethodArg) {
        return instanceMethodArg;
    }

    // Static Method for Loops
    static void staticLoopMethod() {
        // While Loop
        int i = 0;
        while (i <= 5) {
            out.println("i (while) = " + i);
            i++;
        }

        // Do While Loop
        do {
            out.println("i (do while) = " + i);
            i++;
        } while (i <= 10);
    }

     static String staticArrayListMethod() {
        // Array List: An "ordered list" that holds a dynamic amount of objects or types of object
         ArrayList<String> family = new ArrayList<>(); //declare
         family.add("Joe");
         family.add("Savannah");
         family.add("Joey");
         family.add("Unkown");
         family.set(3, "Adrian!");
         String fam = String.join(" and ", family);
         return fam;
     }

     static HashMap<String, Double> staticHashMapMethod() {
         // Hash Map: A collection of key/value pair.
         HashMap<String, Double> famAge = new HashMap<>();
         famAge.put("Joe", 32.0);
         famAge.put("Van", 27.0);
         famAge.put("Joey", 2.0);
         famAge.put("Adrian", 0.2);

         return famAge;
     }

     static void staticScannerInput() {
         out.println("Enter your name:");
         Scanner scan = new Scanner(System.in);
         String name = scan.next();
         out.println("Enter your age:");
         int age = scan.nextInt();
         out.println("Hello, " + name + ". I understand you are " + age + " years old." );
     }

    public static void main(String[] args) {

        out.println("Hello World!");

        out.println(staticMethod(2));

        Playground newPlayground = new Playground(); // New instance of Playground instantiated

        int instanceMethodPassed = newPlayground.instanceMethod(4); // New instance method accessed and instantiated
        out.println(instanceMethodPassed);


        // Array
        int [] numbers = {-5, -4, -3, -2, -1};

        // For each Loop
        for ( int x : numbers ) out.println("x (for) = " + x);

        // While Method retrieved
        staticLoopMethod();

        boolean answer = newPlayground.answer;
        // if / else statement
        if ( !answer ) {
            out.println("It's not true!");
        } else if ( answer ) {
            out.println("It's true!");
        }

        out.println(staticArrayListMethod());

        out.println(staticHashMapMethod());

        out.println("Enter your name:");
        Scanner scan = new Scanner(System.in);
        String name = scan.next();
        out.println("Enter your age:");
        int age = scan.nextInt();
        out.println("Hello " + name + ". I understand you are " + age + " years old." );
    }

}

 

Hoffman2 Script Generator, created in JS/jQuery

jQuery(document).ready(function($) {

  // Global App Variables
  var dunnoMem;
  var timeLimit;
  var tasks;
  var exclusive;
  var memSize;
  var cpu;
  var dunnoMemChecked = false;

window.onerror = function(msg, url, linenumber) {
    alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
    return true;
}

  // Change on Job choice
$('input:radio[name="job-type"]').change(function(){

  // Hide output and notes on change of Job Choice
  $(".reveal-output").hide()
  $("#notes").hide();
  $("#notes2").hide();
  $("#notes3").hide();
  $("#warning-cores").hide();
  $("#warning-cores2").hide();

  // Single-Core Chosen
  if ($(this).val() == 'Single') {
    $(".reveal-form").show();
    $("#cpu-cores-sms").hide();
    $('.num_cores').removeAttr('required');
    cpu = "single";

    if($('#array-box').is(':checked')){
      $(".tasks").show();
      $(".num_tasks").prop('required',true);
    } else {
      $(".tasks").hide();
      $('.num_tasks').removeAttr('required');
    }
  }


  // Same-node Multi-cpu
  if ($(this).val() == 'Same-Node-Multi') {
    $(".reveal-form").show();
    $("#cpu-cores-sms").show();
    $('.num_cores').attr('max', '32');
    $(".num_cores").prop('required',true);
    cpu = "same-node-multi";

    if($('#array-box').is(':checked')){
      $(".tasks").show();
      $(".num_tasks").prop('required',true);
    } else {
      $(".tasks").hide();
      $('.num_tasks').removeAttr('required');
    }

  }


  // Multi-nodes
  if ($(this).val() == 'Multiple-Nodes') {
    $(".reveal-form").show();
    $(".tasks").hide();
    $("#cpu-cores-sms").show();
    $('.num_cores').attr('max', '999999');
    $(".num_cores").prop('required',true);
    cpu = "multiple-nodes";

    if($('#array-box').is(':checked')){
      $(".tasks").show();
      $(".num_tasks").prop('required',true);
    } else {
      $(".tasks").hide();
      $('.num_tasks').removeAttr('required');
    }

  }

}); // End of Change on Job choice


// Check CPU cores and display warnings
$('.reveal-form').focusout(function(){

  if (cpu == "same-node-multi" || cpu == "same-node-multi-array" ) {

    numCores = document.getElementsByClassName("num_cores")[0].value;
    memSize = document.getElementsByClassName("Memory_Size")[0].value;
    gbOfMem = numCores * memSize;

    if ( gbOfMem > 24 ) {
      $( "#warning-cores2" ).replaceWith( "<div id = 'warning-cores2'><p>You requested " + gbOfMem + " GB of memory (" + numCores + " CPU cores * " + memSize + " GB" + "); depending on the availability of higher-memory compute nodes and your account’s access level, the job may or may not start.</p></div>" );
    } else {
      $("#warning-cores2").hide();
    }

    if (numCores > 8 && cpu == "same-node-multi") {
      $( "#warning-cores" ).replaceWith( "<div id = 'warning-cores'><p>You specified more than 8 CPUs; not all compute nodes satisfy this requirement. Please expect possibly longer wait time for the job to start.</p></div>");
      $("#warning-cores").show();
    } else if ( numCores > 8 && cpu == "same-node-multi-array" ) {
      $( "#warning-cores" ).replaceWith( "<div id = 'warning-cores'><p>You have requested more than 8 CPU cores. Please make sure you have access to such compute nodes.</p></div>");
      $("#warning-cores").show();
    } else if ( numCores > 128 && cpu == "multiple-nodes" || numCores > 128 && cpu == "multiple-nodes-array") {
      $( "#warning-cores" ).replaceWith( "<div id = 'warning-cores'><p>You have requested more than 128 CPU cores. Please make sure you have access to such compute nodes.</p></div>");
      $("#warning-cores").show();
    } else {
      $("#warning-cores").hide();
    }
  }
}); // End of Check CPU cores and display warnings


// Dont know memory box checked
$('#dont-know-memory').click(function(){
  if($(this).is(':checked') || exclusive == true ){
    dunnoMem = "exclusive,";
    memSize = 64;
    dunnoMemChecked = document.getElementsByClassName("Memory_Size")[0].disabled = true;
  } else {
    dunnoMem = "";
    dunnoMemChecked = document.getElementsByClassName("Memory_Size")[0].disabled = false;
    memSize = document.getElementsByClassName("Memory_Size")[0].value;
  }
});
// Dont know time box checked
$('#dont-know-time').click(function(){
  if($(this).is(':checked')){
    document.getElementsByClassName("Number_Limit")[0].disabled = true;
    timeLimit = 24;
  } else {
    document.getElementsByClassName("Number_Limit")[0].disabled = false;
    timeLimit = document.getElementsByClassName("Number_Limit")[0].value;
  }
}); // End of Dont know checkboxes


// exclusive box checked
$('#exclusive-node').change(function(){
  if($(this).is(':checked')){
    dunnoMem = "exclusive,";
    exclusive = true;
  } else {
    dunnoMem = "";
    exclusive = false;
  }
}); // End of exclusive



//  Array checked
$('#array-box').change(function(){
  if($(this).is(':checked')){
    $(".tasks").show();
    $("#notes").hide();
    $("#notes2").hide();
    $("#notes3").hide();
    $(".num_tasks").prop('required',true);

      if (cpu == "single" ) {
        cpu = "single-cpu-array";
      } else if ( cpu == "same-node-multi" ) {
        cpu = "same-node-multi-array"
      } else if ( cpu == "multiple-nodes" ) {
        cpu = "multiple-nodes-array";
      }

  } else {
    $(".tasks").hide();
    $('.num_tasks').removeAttr('required');

    if (cpu == "single-cpu-array" ) {
      cpu = "single";
    } else if ( cpu == "same-node-multi-array" ) {
      cpu = "same-node-multi"
    } else if ( cpu == "multiple-nodes-array" ) {
      cpu = "multiple-nodes";
    }

  }
}); // End of Single-Cpu Array



// Hook at submit Generate Script
$( "#generateScript" ).submit(function( event ) {

  $("#notes").hide();
  $("#notes2").hide();
  $("#notes3").hide();

  if(dunnoMemChecked == true || exclusive == true){
    dunnoMem = "exclusive,";
  } else {
    dunnoMem = "";
  }

    // Capture Input Fields
    if ( timeLimit != 24 ) {
      timeLimit = document.getElementsByClassName("Number_Limit")[0].value;
    }

    if ( memSize != 64 ) {
      memSize = document.getElementsByClassName("Memory_Size")[0].value;
    }

    tasks = document.getElementsByClassName("num_tasks")[0].value;

    $numCores = document.getElementsByClassName("num_cores")[0].value;

    //Single-Core output
    if (cpu == "single") {

      $("#notes").show();
      if (dunnoMem == "exclusive,") {
        memSize = 24;
      }

    document.getElementsByClassName('reveal-output')[0].innerHTML ='\
<div id="output">\
#!/bin/bash<br>' + '\r\n' + '\
#<br>' + '\r\n' + '\
# SGE job script: sequential job (using only 1 CPU core)<br>' + '\r\n' + '\
#<br><br>' + '\r\n\r\n' + '\
#$ -j y<br>' + '\r\n' + '\
#$ -o stdout.$JOB_ID<br>' + '\r\n' + '\
#$ -cwd<br>' + '\r\n' + '\
#$ -l h_data=' + memSize + 'G,' + dunnoMem + 'h_rt=' + timeLimit + ':00:00<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
source /u/local/Modules/default/init/modules.sh<br><br>' + '\r\n' + '\
module load intel<br>' + '\r\n' + '\
module load python<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# source your own startup script if needed<br>' + '\r\n' + '\
# source ~/.bash_profile<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# run the executable<br>' + '\r\n' + '\
./a.out<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
</div>\
';

    // Same-Node Output
  } else if (cpu == "same-node-multi") {
    memSize = Math.round( (24 / numCores) * 10 ) / 10;
    $("#notes").show();
    document.getElementsByClassName('reveal-output')[0].innerHTML ='\
<div id="output">\
#!/bin/bash<br>' + '\r\n' + '\
#<br>' + '\r\n' + '\
# SGE job script: multi-core/SMP job (using multiple cores on one node)<br>' + '\r\n' + '\
#<br><br>' + '\r\n\r\n' + '\
#$ -j y<br>' + '\r\n' + '\
#$ -o stdout.$JOB_ID<br>' + '\r\n' + '\
#$ -cwd<br>' + '\r\n' + '\
#$ -l h_data=' + memSize + 'G,' + dunnoMem + 'h_rt=' + timeLimit + ':00:00<br>' + '\r\n' + '\
#$ -pe shared ' + numCores + '<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
source /u/local/Modules/default/init/modules.sh<br><br>' + '\r\n' + '\
module load intel<br>' + '\r\n' + '\
module load python<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# source your own startup script if needed<br>' + '\r\n' + '\
# source ~/.bash_profile<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# run the executable<br>' + '\r\n' + '\
export OMP_NUM_THREADS=$NSLOTS<br>' + '\r\n' + '\
./a.out<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
</div> ' + '\r\n' + '\
';


// Multi-Node output
} else if (cpu == "multiple-nodes") {

  $("#notes2").show();

    document.getElementsByClassName('reveal-output')[0].innerHTML ='\
<div id="output">\
#!/bin/bash<br>' + '\r\n' + '\
#<br>' + '\r\n' + '\
# SGE job script: distributed-memory/MPI job (using multiple compute nodes)<br>' + '\r\n' + '\
#<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
#$ -j y<br>' + '\r\n' + '\
#$ -o stdout.$JOB_ID<br>' + '\r\n' + '\
#$ -cwd<br>' + '\r\n' + '\
#$ -l h_data=' + memSize + 'G,' + dunnoMem + 'h_rt=' + timeLimit + ':00:00<br>' + '\r\n' + '\
#$ -pe dc* ' + $numCores + '<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
source /u/local/Modules/default/init/modules.sh<br><br>' + '\r\n' + '\
module load intel<br>' + '\r\n' + '\
module load python<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# source your own startup script if needed<br>' + '\r\n' + '\
# source ~/.bash_profile<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# run the executable<br>' + '\r\n' + '\
mpirun -np $NSLOTS ./a.out<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
</div> ' + '\r\n' + '\
';

// Single CPU Array
} else if (cpu == "single-cpu-array") {
  $("#notes3").show();
  if (dunnoMem == "exclusive,") {
    memSize = 24;
  }

    //Same-Node output
    document.getElementsByClassName('reveal-output')[0].innerHTML ='\
<div id="output">\
#!/bin/bash<br>' + '\r\n' + '\
#<br>' + '\r\n' + '\
# SGE job script: sequential job array<br>' + '\r\n' + '\
#<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
#$ -j y<br>' + '\r\n' + '\
#$ -o stdout.$JOB_ID.$SGE_TASK_ID<br>' + '\r\n' + '\
#$ -cwd<br>' + '\r\n' + '\
#$ -l h_data=' + memSize + 'G,' + dunnoMem + 'h_rt=' + timeLimit + ':00:00<br>' + '\r\n' + '\
#$ -t 1-' + tasks +'<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
source /u/local/Modules/default/init/modules.sh<br><br>' + '\r\n' + '\
module load intel<br>' + '\r\n' + '\
module load python<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# source your own startup script if needed<br>' + '\r\n' + '\
# source ~/.bash_profile<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# run the executable<br>' + '\r\n' + '\
./a.out $SGE_TASK_ID<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
</div> ' + '\r\n' + '\
';

// Same-node Multi Array
} else if (cpu == "same-node-multi-array") {
  $("#notes").show();
    //Same-Node output
    document.getElementsByClassName('reveal-output')[0].innerHTML ='\
<div id="output">\
#!/bin/bash<br>' + '\r\n' + '\
#<br>' + '\r\n' + '\
# SGE job script: multi-core/SMP job array<br>' + '\r\n' + '\
#<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
#$ -j y<br>' + '\r\n' + '\
#$ -o stdout.$JOB_ID<br>' + '\r\n' + '\
#$ -cwd<br>' + '\r\n' + '\
#$ -l h_data=' + memSize + 'G,' + dunnoMem + 'h_rt=' + timeLimit + ':00:00<br>' + '\r\n' + '\
#$ -pe shared ' + $numCores + '<br>' + '\r\n' + '\
#$ -t 1-' + tasks +'<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
source /u/local/Modules/default/init/modules.sh<br><br>' + '\r\n' + '\
module load intel<br>' + '\r\n' + '\
module load python<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# source your own startup script if needed<br>' + '\r\n' + '\
# source ~/.bash_profile<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# run the executable<br>' + '\r\n' + '\
export OMP_NUM_THREADS=$NSLOTS<br>' + '\r\n' + '\
./a.out $SGE_TASK_ID<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
</div> ' + '\r\n' + '\
';

// Same-node Multi Array
} else if (cpu == "multiple-nodes-array") {
  $("#notes").show();
    //Same-Node output
    document.getElementsByClassName('reveal-output')[0].innerHTML ='\
<div id="output">\
#!/bin/bash<br>' + '\r\n' + '\
#<br>' + '\r\n' + '\
# SGE job script: multi-core/SMP job array<br>' + '\r\n' + '\
#<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
#$ -j y<br>' + '\r\n' + '\
#$ -o stdout.$JOB_ID<br>' + '\r\n' + '\
#$ -cwd<br>' + '\r\n' + '\
#$ -l h_data=' + memSize + 'G,' + dunnoMem + 'h_rt=' + timeLimit + ':00:00<br>' + '\r\n' + '\
#$ -pe dc* ' + $numCores + '<br>' + '\r\n' + '\
#$ -t 1-' + tasks +'<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
source /u/local/Modules/default/init/modules.sh<br><br>' + '\r\n' + '\
module load intel<br>' + '\r\n' + '\
module load python<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# source your own startup script if needed<br>' + '\r\n' + '\
# source ~/.bash_profile<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
# run the executable<br>' + '\r\n' + '\
export OMP_NUM_THREADS=$NSLOTS<br>' + '\r\n' + '\
./a.out $SGE_TASK_ID<br>' + '\r\n' + '\
<br>' + '\r\n' + '\
</div> ' + '\r\n' + '\
';

  } // End logic

    // reveal output
    $(".reveal-output").show()
    event.preventDefault();


    //generate download file
    (function () {
    var textFile = null,
    makeTextFile = function (text) {
      var data = new Blob(, {type: 'text/x.shellscript'});

      // If we are replacing a previously generated file we need to
      // manually revoke the object URL to avoid memory leaks.
      if (textFile !== null) {
        window.URL.revokeObjectURL(textFile);
      }

      textFile = window.URL.createObjectURL(data);

      return textFile;
    };

    //var create = document.getElementById('create');
    var output = document.getElementById('output').textContent;
    var link = document.getElementById('downloadlink');
    //var link = document.getElementById('buttonDownload');
    link.href = makeTextFile(output);
    link.style.display = 'block';

    })(); // Closing of "generate download file"
  }); // Closing of "reveal output"


}); //jQuery end

See in action here: Hoffman2.idre.ucla.edu