Skip to content
Register Sign in Wishlist

# Code for chapter 19

#### For instructors:

Below are listed all the scripts as shown in chapter 19 of the book. These are free to copy and paste into your code editor.

Quick links to each script:

## Script 19.1

 script_19_1.awk, file.dat ```# Script 19.1 # Processing of the ASCII-file file.tab with tab-separated values awk ' BEGIN {FS="\t"} (NR>1){ if (\$1>2) {print \$1,\$2-\$4 } else {print \$1,\$3} n=n+1 } END {print "This is the End after processing "n" lines."} ' file.dat ``` script_19_1.out ```[ah@hobbes Documents]\$ ./script_19_1.awk 1 S1 Male 66.3 20 TRUE 2 S2 Male 80.2 21 FALSE 0 3 S3 Female 53.1 29 TRUE 0 4 S4 Female 21.3 18 TRUE 0 5 S5 Female 54.6 NA FALSE 0 6 S6 Female 78.1 23 TRUE 0 This is the End after processing 6 lines. ```

## Script 19.2

 script_19_2.py ```# Script 19.2 # Calculate the sum of squares of data in an array s = 0 data = [3, -1, 2, -5, None, 9, -2] for d in data: if not d is None: s += d * d print('The sum of squares is ',s) ``` script_19_2.out ```[ah@hobbes Documents]\$ python script_19_2.py ('The sum of squares is ', 124) ```

## Script 19.3

 script_19_3.R ```# Script 19.3 # Plotting a normal distribution x<-seq(-4,4,length=100)dx<-dnorm(x,mean=0,sd=1)plot(x,dx,type="l",main="Normal Distribution")p1<-seq(-4,-1.5,length=100)dp1<-dnorm(p1)p2<-seq(1.5,4,length=100)dp2<-dnorm(p2)polygon(c(-4,p1,-1.5),c(0,dp1,0),col="gray") ``` script_19_3.png

## Script 19.4

 script_19_4.R ```# Script 19.4 library() # List packages available, not necessarily active data(agriculture) # Attempt to load the Agriculture dataset bannerplot(agnes(agriculture), main = "Bannerplot") # Run bannerplot function library(cluster) # Load the cluster library and try again data(agriculture) bannerplot(agnes(agriculture), main = "Bannerplot") ``` script_19_4.png ` `

## Script 19.7

 script_19_7.R ```# Script 19.7 x<-3 # Set x to hold the value 1 print(x) # Its value can be displayed simply with the print() command x # Or even simply by stating its name x+x # Simple operations are straight forward x*x sqrt(x) # even the square root, using the built-in function sqrt() y<- -3.4 y x-y # Calculate the difference between numbers x and y t<-"Text" # Set t to hold the String "Text" t x-t # Attempt to calculate the difference between x and t which fails typeof(x) # x is a number with double precision typeof(t) # t is a string with character type z<- TRUE # Set a BOOLEAN value TRUE to z z x-z # Calculate the difference between x and z provides an answer typeof(z) typeof(x-z) # The BOOLEAN logical type TRUE is transformed into value 1 in double type 3-1=2``` script_19_7.out ```[ah@hobbes Documents]\$ R R version 3.3.1 (2016-06-21) -- "Bug in Your Hair" Copyright (C) 2016 The R Foundation for Statistical Computing Platform: x86_64-redhat-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > # Script 19.7 > x print(x) # Its value can be displayed simply with the print() command [1] 3 > > x # Or even simply by stating its name [1] 3 > > x+x # Simple operations are straight forward [1] 6 > > x*x [1] 9 > > sqrt(x) # even the square root, using the built-in function sqrt() [1] 1.732051 > > y y [1] -3.4 > > x-y # Calculate the difference between numbers x and y [1] 6.4 > > t t [1] "Text" > > x-t # Attempt to calculate the difference between x and t which fails Error in x - t : non-numeric argument to binary operator > > typeof(x) # x is a number with double precision [1] "double" > > typeof(t) # t is a string with character type [1] "character" > > z z [1] TRUE > > x-z # Calculate the difference between x and z provides an answer [1] 2 > > typeof(z) [1] "logical" > > typeof(x-z) # The BOOLEAN logical type TRUE is transformed into value 1 in double type 3-1=2 [1] "double" > ```

## Script 19.8

 script_19_8.R ```# Script 19.8 v <- c(10, 1.6, 1, 2.6, 1.7) # Create a vector of length 5 with set values v w<-1:10 # Create a vector of length 10 w v+1 # One can operate on all numbers v*w # Even between vectors sqrt(v) # Or more complex operation like square root mean(v) # Average across the values of the vector sd(v) # Standard Deviation sum(v) # Sum length(v) # Length of the vector``` script_19_8.out ```[ah@hobbes Documents]\$ R R version 3.3.1 (2016-06-21) -- "Bug in Your Hair" Copyright (C) 2016 The R Foundation for Statistical Computing Platform: x86_64-redhat-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > # Script 19.8 > v v [1] 10.0 1.6 1.0 2.6 1.7 > w w [1] 1 2 3 4 5 6 7 8 9 10 > v+1 # One can operate on all numbers [1] 11.0 2.6 2.0 3.6 2.7 > v*w # Even between vectors [1] 10.0 3.2 3.0 10.4 8.5 60.0 11.2 8.0 23.4 17.0 > sqrt(v) # Or more complex operation like square root [1] 3.162278 1.264911 1.000000 1.612452 1.303840 > mean(v) # Average across the values of the vector [1] 3.38 > sd(v) # Standard Deviation [1] 3.744596 > sum(v) # Sum [1] 16.9 > length(v) # Length of the vector [1] 5 > ```

## Script 19.9

 script_19_9.R ```# Script 19.9m<-array(2:7,dim=c(2,3))   # Create a 2x3 array containing values from 2 to 7mm[1,3]                     # Access a single cell by indexm[1,]                      # Access a single rowm[,c(1,3)]                 # Access a pair of columns ``` script_19_9.out ```[ah@hobbes Documents]\$ RR version 3.3.1 (2016-06-21) -- "Bug in Your Hair"Copyright (C) 2016 The R Foundation for Statistical ComputingPlatform: x86_64-redhat-linux-gnu (64-bit)R is free software and comes with ABSOLUTELY NO WARRANTY.You are welcome to redistribute it under certain conditions.Type 'license()' or 'licence()' for distribution details.  Natural language support but running in an English localeR is a collaborative project with many contributors.Type 'contributors()' for more information and'citation()' on how to cite R or R packages in publications.Type 'demo()' for some demos, 'help()' for on-line help, or'help.start()' for an HTML browser interface to help.Type 'q()' to quit R.> # Script 19.9> m<-array(2:7,dim=c(2,3))   # Create a 2x3 array containing values from 2 to 7> m     [,1] [,2] [,3][1,]    2    4    6[2,]    3    5    7> m[1,3]                     # Access a single cell by index[1] 6> m[1,]                      # Access a single row[1] 2 4 6> m[,c(1,3)]                 # Access a pair of columns     [,1] [,2][1,]    2    6[2,]    3    7> ```

## Script 19.10

 script_19_10.R ```# Script 19.10hair<-c("black","fair","black","black","brown","fair","white","brown","white","bald")f_hair<-factor(hair)    # Make a factor from this vectorf_hairlevels(f_hair)          # The categories are the levelslevels(hair)            # There are no levels in the original vector ``` script_19_10.out ```[ah@hobbes Documents]\$ RR version 3.3.1 (2016-06-21) -- "Bug in Your Hair"Copyright (C) 2016 The R Foundation for Statistical ComputingPlatform: x86_64-redhat-linux-gnu (64-bit)R is free software and comes with ABSOLUTELY NO WARRANTY.You are welcome to redistribute it under certain conditions.Type 'license()' or 'licence()' for distribution details.  Natural language support but running in an English localeR is a collaborative project with many contributors.Type 'contributors()' for more information and'citation()' on how to cite R or R packages in publications.Type 'demo()' for some demos, 'help()' for on-line help, or'help.start()' for an HTML browser interface to help.Type 'q()' to quit R.> # Script 19.10> hair<-c("black","fair","black","black","brown","fair","white","brown","white","bald")> f_hair<-factor(hair)    # Make a factor from this vector> f_hair [1] black fair  black black brown fair  white brown white bald Levels: bald black brown fair white> levels(f_hair)          # The categories are the levels[1] "bald"  "black" "brown" "fair"  "white"> levels(hair)            # There are no levels in the original vectorNULL> ```

## Script 19.11

 script_19_11.R ```# Script 19.11res <- list(test_name=c("t.test","Fisher_exact"), pval=0.001, df=3, err=c(0.4,0.7,0.9))     # List of 4 componentsresres\$pval             # Access the full element pvalres\$err              # Access the full element errres\$test_name[1]     # Access an element in an element ``` script_19_11.out ```[ah@hobbes Documents]\$ RR version 3.3.1 (2016-06-21) -- "Bug in Your Hair"Copyright (C) 2016 The R Foundation for Statistical ComputingPlatform: x86_64-redhat-linux-gnu (64-bit)R is free software and comes with ABSOLUTELY NO WARRANTY.You are welcome to redistribute it under certain conditions.Type 'license()' or 'licence()' for distribution details.  Natural language support but running in an English localeR is a collaborative project with many contributors.Type 'contributors()' for more information and'citation()' on how to cite R or R packages in publications.Type 'demo()' for some demos, 'help()' for on-line help, or'help.start()' for an HTML browser interface to help.Type 'q()' to quit R.> # Script 19.11> res <- list(test_name=c("t.test","Fisher_exact"), pval=0.001, df=3, err=c(0.4,0.7,0.9))     # List of 4 components> res\$test_name[1] "t.test"       "Fisher_exact"\$pval[1] 0.001\$df[1] 3\$err[1] 0.4 0.7 0.9> res\$pval             # Access the full element pval[1] 0.001> res\$err              # Access the full element err[1] 0.4 0.7 0.9> res\$test_name[1]     # Access an element in an element[1] "t.test"> ```

## Script 19.12

 script_19_12.R ```# Script 19.12# Read the table considering the first row as dataread.table("table.dat") ``` script_19_12.out ```[ah@hobbes Documents]\$ RR version 3.3.1 (2016-06-21) -- "Bug in Your Hair"Copyright (C) 2016 The R Foundation for Statistical ComputingPlatform: x86_64-redhat-linux-gnu (64-bit)R is free software and comes with ABSOLUTELY NO WARRANTY.You are welcome to redistribute it under certain conditions.Type 'license()' or 'licence()' for distribution details.  Natural language support but running in an English localeR is a collaborative project with many contributors.Type 'contributors()' for more information and'citation()' on how to cite R or R packages in publications.Type 'demo()' for some demos, 'help()' for o  var addthis_config = { "data_track_addressbar": false }; var addthis_share = { templates: { twitter: '{{title}} {{url}} via @CUPAcademic', } }; Save 20% off on your next online purchase with Cambridge Alerts Receive email alerts on new books, offers and news... Subscribe Find content that relates to you Find content that relates to you I am a... Author Bookseller Company Journalist Lecturer Librarian Society \$(function() { \$("#aim2").dropkick({ change: function(value, label) { window.location = CCM_REL + '/academic/' + value; } }); }); Join us online LinkedIn Facebook YouTube Twitter This site uses cookies to improve your experience. Read more Close \$('.close').click(function() { \$('.disclosure-container').slideUp(); \$('#content').css("padding-top","0"); \$('.cartWrapper').animate({'top':'55px'}); // GAW-2286 - Search box is pushed ... add code for firefox / ie.. // removed \$.browser.webkit and used 750 for minwidth / ebaluyo - 2015-05-27 if (\$(window).width() <= 750) { \$('.searchWrapper').removeAttr("style"); } else { \$('.searchWrapper').animate({'top':'103px'}); } \$('.openPageSlide').animate({'position':'absolute'}); \$('.openPageSlide.expand').css({'z-index':'200'}); }); \$('#content').before(\$('#cookieNotice')); \$(document).ready(function () { setTimeout(function(){ \$('#cookieNotice').fadeIn(500); }, 1000); }); \$( "#cookieNotice .dismiss").click(function() { \$("#cookieNotice").toggleClass("off"); }); // This is only for academic \$('.openPageSlide.expand').css({'z-index':'32'}); checkCookieMessageHeight(); \$(window).resize(function() { if(\$('.disclosure-container').css('display')=="block") { if(\$(window).width() <= 750) { \$('.searchWrapper').css({'top':'0px'}); } else { checkCookieMessageHeight(); } } }); function checkCookieMessageHeight() { messageDivHeight = \$('#cookieNotice').height(); if(messageDivHeight > 40) { // GAW-2286 - Search box is pushed ... changed 119px -> 55px, 163px -> 103px \$('.cartWrapper').css({'top':'55px'}); // old: 119px \$('.searchWrapper').css({'top':'103px'}); // old: 163px \$('.openPageSlide').css({'position':'relative'}); } else { \$('.cartWrapper').css({'top':'55px'}); \$('.searchWrapper').css({'top':'103px'}); \$('.openPageSlide').css({'position':'relative'}); } } \$('#cookieNotice').remove(); //WSP-797 remove old cookie in all pages What we do Academic Research English Language Learning English Language Assessment Educational resources for schools Bibles Partnership for Education Author support Bookshop Assessment Research Cambridge Assessment International Education Cambridge Assessment Admissions Testing Cambridge Assessment Network OCR About us What we do Our story People and planet Governance News and insights Legal Accessibillity Rights and permissions Contact us © 2022 Cambridge University Press & Assessment Rights and permissions Legal Privacy Modern slavery People and planet Diversity and inclusion Sitemap Location: GMB Are you sure you want to delete your account? This cannot be undone. Cancel Thank you for your feedback which will help us improve our service. If you requested a response, we will make sure to get back to you shortly. × Please fill in the required fields in your feedback submission. × var LOCALE = "en_GM"; var CURRENT_THEME = "Academic_v1"; var ACADEMIC_THEME_HANDLE = "Academic_v1"; var LEARNING_THEME_HANDLE = "Learning"; var isTablet = ''; var isMobile = ''; var data = {"GET":{"query":""},"hHandle":"global_navbar_ccp","pHandle":"cambridge_themes","action":"renderLocaleRevealForm","locale":"en_GM","businessStream":"academic"}; (function () { var euCountryCodes = [ 'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'IS', 'LI', 'NO', 'CH' ]; if (window.CURRENT_SITE === 'corporate') { return; } var msg = ''; var shouldDisplay = false; var currDate = new Date(); if (window.VISTA_SERVICE_REGION === 'E' && Locale.countryCode !== 'JP') { msg = 'Online ordering is currently unavailable. For all order enquiries please contact Customer Services at cs_asia@cambridge.org'; shouldDisplay = true; } if (shouldDisplay) { var \$html = \$('
', { id: 'ccm-headerAnnounce' }) .append( \$('
', { class: 'disclosure-container' }) .append( \$('
', { class: 'disclosure-content row' }) .append(\$('

', { style: 'text-align:center; color:black; font-size:14px;' }).html(msg)) ) ); \$('body > div#content').before(\$html); } })(); \$(function () { if (window.location.href.indexOf('/academic/subjects') >= 0) { \$.each(\$('.relatedItemsWrap .relatedItem a[href^="//journals.cambridge.org"]'), function () { \$(this).attr('href', 'http://' + this.href.substring(this.href.indexOf('journals'))); }); } }); var eduUrlPattern = new RegExp('^\/[a-z]{2}\/education'); if (!CWS_ECOMMERCE_ENABLED && !eduUrlPattern.test(window.location.pathname) && \$('.addToCartBtn').length > 0) { \$(function () { \$('.addToCartBtn').removeClass('addToCartBtn').addClass('addToCartBtnPatch'); if ((VISTA_SERVICE_REGION === 'A' && IS_KK_AUS === '0') || (VISTA_SERVICE_REGION === 'E' && IS_KK_ASIA === '0')) { if (IS_KK_ACS_ENABLED > 0) { getVyreServicePatch(); } } else { getKonakartServicePatch(); } function getKonakartServicePatch() { jQuery('.addToCartBtnPatch').live('click', addToCartEventPatch); // send request to cart WS jQuery.ajax({ url: KK_MINI_CART, dataType: 'xml', success: mini_cart_successful_patch, error: function () { jQuery('#miniCartDetail .qty').show(); jQuery('#cartQty').html('(' + jQuery('#qtyValue').html() + ')'); }, // https://jira.cambridge.org/browse/KEP-453 cache: false }); } function getVyreServicePatch() { // GAW-2570 if (jQuery('.addToCartBtnPatch.konakartLink').length > 0) { jQuery('.addToCartBtnPatch.konakartLink').live('click', addToCartEventPatch); } \$.ajax({ url: "/tools/packages/cambridge_themes/miniCart", data: { source: "Academic_v1" }, success: function (data) { if (\$('#qtyValue').html() == 0) { jQuery('#cartQty').html(''); var cartOpt = { url: KK_MINI_CART, dataType: 'xml', success: mini_cart_successful_patch, error: function () { jQuery('#miniCartDetail .qty').show(); jQuery('#cartQty').html('(' + jQuery('#qtyValue').html() + ')'); }, // https://jira.cambridge.org/browse/KEP-453 cache: false }; // send request to cart WS jQuery.ajax(cartOpt); jQuery("a.viewCart").attr("href", VYRE_BASKET); jQuery("a.academicCheckout").attr("href", VYRE_BASKET); var minicartDetail = '

You have 0 items in your cart.

' + '
' + ''; \$("#miniCartDetail").html(minicartDetail); } else { hasAsp = true; } } }); } }); var errorCallBackPatch = function () { // hide the view cart if (cartItemCount < 1) { jQuery('.viewCart').hide(); } jQuery('#itemAddedMessage').text("There was a problem getting your cart information."); jQuery('#itemAddedModal').reveal(); }; var completeCallBackPatch = function () { alreadyClicked = false; countryChange = true; jQuery('body').css('cursor', 'auto'); }; var addToCartEventPatch = function (event) { event.preventDefault(); // check first if the user hasn't clicked on the link to prevent multiple // AJAX requests if (alreadyClicked == false) { alreadyClicked = true; // make the body to show wait cursor while processing jQuery('body').css('cursor', 'wait'); addToCartPatch(jQuery(this).data()); } }; /** * upon success of calling add to cart WS * @param data xml returned data from ecom * @param textStatus test status * @param isbn string added isbn */ var add_to_cart_successful_patch = function (data, textStatus, isbn) { var \$cartData = jQuery(data); // hack to get HTML content in XML var cartErrorMessage = \$cartData.find('errorMessage').text().trim(); var cartInfoMessage = \$cartData.find('infoMessage').text().trim(); // get cart lines in the cart WS var cartLines = processCartDataPatch(data); refresh_cart_patch(cartLines); // check first if we have error message then display it instead of item added message if (cartErrorMessage !== '') { jQuery('#addToCartCustom h4').html(cartErrorMessage); jQuery('#addToCartCustom h4').css('text-transform', 'none'); jQuery('#addToCartCustom').reveal(); } else if (cartInfoMessage !== '') { jQuery('#addToCartCustom h4').html(cartInfoMessage); jQuery('#addToCartCustom h4').css('text-transform', 'none'); jQuery('#addToCartCustom').reveal(); } else { // hide the view cart if (cartItemCount < 1) { jQuery('.viewCart').hide(); } jQuery('#itemAddedMessage').text("Item added to your cart!"); jQuery('#itemAddedModal').reveal(); googleTagManagerPatch(isbn); } }; // upon success of calling cart WS var mini_cart_successful_patch = function (data, textStatus) { // get cart lines in the cart WS var cartLines = processCartDataPatch(data); refresh_cart_patch(cartLines); }; /** * Convert data collected from the cart WS and traverse and store it in array * @param {XML} xml Expected XML cart data * @return {Array} Array list of lines (products) in the cart */ var processCartDataPatch = function (xml) { // reset cartItemCount = 0; currency = '\$'; subTotal = 0; var \$cartData = jQuery(xml); var cartLines = []; currency = \$cartData.find('symbol').text(); subTotal = \$cartData.find('totalValueOverride').text(); // traverse the orderline \$cartData.find('orderLines').find('orderLine').each(function () { var data = []; data['availabilityLegend'] = getXMLValuePatch("availabilityLegend", this); cartItemCount += getXMLValuePatch('quantity', this) ? parseInt(getXMLValuePatch('quantity', this)) : 1; data['title'] = getXMLValuePatch('title', this); data['author'] = getXMLValuePatch('author', this); var price = getXMLValuePatch('publishedPriceOverride', this); data['price'] = price.length > 0 ? price : getXMLValuePatch('originalValue', this); data['price'] = data['price'].replace(',', ''); data['discountPrice'] = getXMLValuePatch('publishedPriceOverride', this); data['discountPrice'] = data['discountPrice'].replace(',', ''); data['ean'] = getXMLValuePatch('ean', this); data['quantity'] = getXMLValuePatch('quantity', this).replace(',', ''); data['format'] = getXMLValuePatch('format', this); var volumeNumber = getXMLValuePatch('volumeNumber', this); data['volume'] = volumeNumber.length > 0 && volumeNumber != '0' ? 'Volume ' + volumeNumber : ''; var partNumber = getXMLValuePatch('partNumber', this); data['part'] = partNumber.length > 0 && partNumber != '0' ? 'Part ' + partNumber : ''; var edition = getXMLValuePatch('edition', this); data['edition'] = edition.length > 0 ? edition + ' Edition' : ''; var lastModified = new Date(getXMLValuePatch('lastModified', this)); data['lastModified'] = lastModified.getTime(); cartLines.push(data); }); cartLines.sort(function (a, b) { return a['lastModified'] - b['lastModified']; }); return cartLines; }; var getXMLValuePatch = function (key, container) { return jQuery(container).find(key).text(); }; var refresh_cart_patch = function (cartLines) { if (cartLines.length > 0) { var \$miniCartDetail = jQuery('#miniCartDetail'); var \$learningQty = jQuery('p.qty #qtyString', \$miniCartDetail); var \$miniCartItems = jQuery('#miniCartItems'); var \$subTotal = jQuery('#subtotalValue'); var cartItemString = '' + cartItemCount + '' + (cartItemCount == 0 || cartItemCount > 1 ? ' items' : ' item'); \$learningQty.html(cartItemString); var cartItems = ''; var itemDisplayCount = 1; for (var i = 0; i < cartLines.length; i++) { cartItems += '

' + cartLines[i]['title'] + ''; cartItems += '

' + cartLines[i]['volume'] + ' ' + cartLines[i]['part'] + ' ' + cartLines[i]['edition'] + '' + ' ' + cartLines[i]['author'] + '

'; cartItems += '

' + cartLines[i]['format'] + '

'; cartItems += '

' + cartLines[i]['availabilityLegend'] + ' | Qty: ' + cartLines[i]['quantity'] + ' | Price: ' + currency + (parseFloat(cartLines[i]['quantity']) * parseFloat(cartLines[i]['price'])).toFixed(2) + '

'; itemDisplayCount++; if (itemDisplayCount > 3 && CURRENT_SITE === 'cambridgeenglish') { break; } } \$miniCartItems.html(cartItems); \$subTotal.html(currency + subTotal); jQuery('#mobileCartQty').html('(' + jQuery('#qtyValue').html() + ')'); jQuery('.withItems').show(); } else { if (jQuery('#miniCartItems > h4').length == 0) { jQuery('.withItems').hide(); } jQuery('#miniCartDetail .qty').show(); } jQuery('#cartQty').html('(' + jQuery('#qtyValue').html() + ')'); }; var addToCartPatch = function (data) { var params = { isbn: isbn = typeof data.isbn !== 'undefined' ? data.isbn : '', locale: typeof data.country !== 'undefined' ? data.country : '', page: typeof data.page !== 'undefined' ? data.page : '', discountCode: typeof data.discountcode !== 'undefined' ? data.discountcode : '' }; if (params.page === "schools") { params['institutiononly'] = typeof data.institutiononly !== 'undefined' ? data.institutiononly : 0; params['qty'] = typeof data.qty !== 'undefined' ? data.qty : ''; } var urlTarget = location.protocol + "//" + location.host + "/wm-ecommerce-web/" + params.page + "/addtocart?" + \$.param(params); jQuery.ajax({ url: urlTarget, dataType: 'xml', success: function (data, textStatus) { add_to_cart_successful_patch(data, textStatus, isbn) }, error: errorCallBackPatch, complete: completeCallBackPatch, cache: false }); }; /** * firing google tag manager after adding to cart * the try catch block will take care of the logic for firing GTM if applicable, which is for ELT ATM. * @param isbn string */ function googleTagManagerPatch(isbn) { try { var gtm = new GoogleTagManager(); if (\$.isFunction(gtm.addToCart)) { \$.post( '/tools/packages/cambridge_core/titleService', {"isbn": isbn, "data": "gtm_data"}, function (data, status) { gtm.addToCart(data); } ); } } catch (err) { // Google Tag Manager is not loaded. return; } } } \$(window).on("load", function () { \$("a[href*='/elt/blog'], a[href*='/core']").each(function () { var href = \$(this).attr("href"); var urlSlug = href.split('/'); if (urlSlug[3] && urlSlug[3].length === 2) { urlSlug.splice(0, 4); href = '/' + urlSlug.join('/'); } var startsWithEltBlog = new RegExp("^\/elt\/blog"); if (startsWithEltBlog.test(href)) { href = CCM_BASE_URL + href; href = href.replace('https://', 'http://'); } \$(this).attr("href", href); }); if (CCM_BASE_URL.includes('//admin')) { \$("#global-nav a[href*='cambridge.org']").each(function () { var href = \$(this).attr("href"); href = href.replace('https://', 'http://'); href = href.replace('//www.', '//admin.'); \$(this).attr("href", href); }); } }); if (window.location.href.indexOf('/academic/conferences') >= 0) { \$('.conferenceWrap').find('.seven.columns').first().addClass('twelve').removeClass('seven'); \$('.conferenceWrap img.ccm-image-block').css('margin', 'auto'); \$(".conferenceWrap .conferenceDetails").insertAfter('.row.conferenceWrap .columns.twelve h1'); \$('.conferenceWrap .conferenceDetails').css('float', 'left'); \$('.conferenceWrap .conferenceDetails').css('border', '0'); \$('.conferenceWrap .conferenceDetails').css('padding', '10px 0 10px 0'); } if (window.location.pathname === '/cart' || window.location.pathname === '/checkout/confirm' || window.location.pathname === '/checkout/vista_confirm') { \$(".item-quantity input.qty").on('keypress', function (e) { if (!\$.isNumeric(e.key) && e.key !== 'Enter') { return false; } }); } if (window.location.href.indexOf('/cambridgeenglish/better-learning-insights') >= 0 || window.location.href.indexOf('/cambridgeenglish/better-learning-insights/pedagogy') >= 0 || window.location.href.indexOf('/cambridgeenglish/better-learning-insights/corpus') >= 0 || window.location.href.indexOf('/cambridgeenglish/better-learning-insights/cambridge-english-curriculum') >= 0 || window.location.href.indexOf('/cambridgeenglish/better-learning-insights/cambridgelifecompetenciesframework') >= 0 || window.location.href.indexOf('/cambridgeenglish/better-learning-content') >= 0 || window.location.href.indexOf('/cambridgeenglish/better-learning-results') >= 0) { \$(document).ready(function() { \$('.fancybox-media').removeAttr('data-lity'); }); } \$('#ccm-headerAnnounce .disclosure-content').css('width', '100%'); var GTM = (typeof GTM === 'undefined') ? { cambridgeId: "", areaOfInterest: "", jobTitle: "", userType: "", clientId: '', currencyCode: "GBP" } : GTM; GTMCart.init(GTM); \$(document).ready(function() { \$('#ccm-nav-edit').parent().remove(); \$('#ccm-nav-dashboard').parent().remove(); }); ```