language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
as$(){ const $nerdtouche = $('<span>').html(this.emoji.join('<br>')); $nerdtouche.attr('title', this.handle); $nerdtouche.addClass('nerdtouche badge badge-secondary badge-pill p-1 m-1 align-middle'); $nerdtouche.css({ fontSize: '0.5em', lineHeight: 1.5 }); return $nerdtouche; }
as$(){ const $nerdtouche = $('<span>').html(this.emoji.join('<br>')); $nerdtouche.attr('title', this.handle); $nerdtouche.addClass('nerdtouche badge badge-secondary badge-pill p-1 m-1 align-middle'); $nerdtouche.css({ fontSize: '0.5em', lineHeight: 1.5 }); return $nerdtouche; }
JavaScript
appendTo($container){ if(is.not.object($container) || !$container.jquery){ throw new TypeError('the container must be a jQuery object'); } return $container.append(this.as$()); }
appendTo($container){ if(is.not.object($container) || !$container.jquery){ throw new TypeError('the container must be a jQuery object'); } return $container.append(this.as$()); }
JavaScript
static $find($container){ if(is.not.undefined($container)){ if(is.not.object($container) || !$container.jquery){ throw new TypeError('If passed, the container must be a jQuery object'); } }else{ $container = $(document); } return $('.nerdtouche', $container); }
static $find($container){ if(is.not.undefined($container)){ if(is.not.object($container) || !$container.jquery){ throw new TypeError('If passed, the container must be a jQuery object'); } }else{ $container = $(document); } return $('.nerdtouche', $container); }
JavaScript
as$(){ // build the nerdtouche const $nerdtouche = $('<span>').html(this.emoji.join('<br>')); $nerdtouche.attr('title', this.handle); $nerdtouche.addClass('nerdtouche badge badge-secondary badge-pill p-1 m-1 align-middle'); $nerdtouche.addClass(this.uniqueClass); $nerdtouche.css({ fontSize: '0.5em', lineHeight: 1.5 }); // add a data attribute linking back to the instance object $nerdtouche.data('nerdtouche-object', this); // return the nerdtouche return $nerdtouche; }
as$(){ // build the nerdtouche const $nerdtouche = $('<span>').html(this.emoji.join('<br>')); $nerdtouche.attr('title', this.handle); $nerdtouche.addClass('nerdtouche badge badge-secondary badge-pill p-1 m-1 align-middle'); $nerdtouche.addClass(this.uniqueClass); $nerdtouche.css({ fontSize: '0.5em', lineHeight: 1.5 }); // add a data attribute linking back to the instance object $nerdtouche.data('nerdtouche-object', this); // return the nerdtouche return $nerdtouche; }
JavaScript
$find($container){ if(is.not.undefined($container)){ if(is.not.object($container) || !$container.jquery){ throw new TypeError('If passed, the container must be a jQuery object'); } }else{ $container = $(document); } return $(`.${this.uniqueClass}`, $container); }
$find($container){ if(is.not.undefined($container)){ if(is.not.object($container) || !$container.jquery){ throw new TypeError('If passed, the container must be a jQuery object'); } }else{ $container = $(document); } return $(`.${this.uniqueClass}`, $container); }
JavaScript
set radius(radius){ const radiusNumber = parseFloat(radius); if(isNaN(radiusNumber)){ throw new TypeError('radius must be a number greater than or equal to zero'); } if(radiusNumber < 0){ throw new RangeError('radius cannot be negative'); } this._radius = radiusNumber; }
set radius(radius){ const radiusNumber = parseFloat(radius); if(isNaN(radiusNumber)){ throw new TypeError('radius must be a number greater than or equal to zero'); } if(radiusNumber < 0){ throw new RangeError('radius cannot be negative'); } this._radius = radiusNumber; }
JavaScript
async function loadCurrencyRates(){ const eurData = await $.ajax({ // could throw Error url: CURRENCY_API_URL, method: 'GET', cache: false, data: { base: 'EUR' } }); console.debug(`received Euro exchange rates: `, eurData); // store the Euro rates and throw an error if any expected currency is missing CURRENCIES.EUR.rates = {}; for(const toCur of SORTED_CURRENCY_CODES){ // deal with the special case of the Euro mapping to itself if(toCur === 'EUR'){ // store the Euro to Euro rate CURRENCIES.EUR.rates.EUR = 1; }else{ // store the rate or throw an error if(eurData.rates[toCur]){ CURRENCIES.EUR.rates[toCur] = eurData.rates[toCur]; }else{ throw RangeError(`no data received for currency '${toCur}'`); } } }; // generate the rates for all other currencies for(const fromCode of SORTED_CURRENCY_CODES){ // skip the Euro if(fromCode === 'EUR') continue; // calculate the rate to Euro by inverting the rate from Euro const toEuro = 1 / eurData.rates[fromCode]; CURRENCIES[fromCode].rates = { EUR: toEuro}; for(const toCode of SORTED_CURRENCY_CODES){ // skip the Euro if(toCode === 'EUR') continue; // check for self if(fromCode === toCode){ CURRENCIES[fromCode].rates[toCode] = 1; }else{ const rate = toEuro * eurData.rates[toCode]; CURRENCIES[fromCode].rates[toCode] = rate; } } } console.debug('Finished currency rate conversions'); }
async function loadCurrencyRates(){ const eurData = await $.ajax({ // could throw Error url: CURRENCY_API_URL, method: 'GET', cache: false, data: { base: 'EUR' } }); console.debug(`received Euro exchange rates: `, eurData); // store the Euro rates and throw an error if any expected currency is missing CURRENCIES.EUR.rates = {}; for(const toCur of SORTED_CURRENCY_CODES){ // deal with the special case of the Euro mapping to itself if(toCur === 'EUR'){ // store the Euro to Euro rate CURRENCIES.EUR.rates.EUR = 1; }else{ // store the rate or throw an error if(eurData.rates[toCur]){ CURRENCIES.EUR.rates[toCur] = eurData.rates[toCur]; }else{ throw RangeError(`no data received for currency '${toCur}'`); } } }; // generate the rates for all other currencies for(const fromCode of SORTED_CURRENCY_CODES){ // skip the Euro if(fromCode === 'EUR') continue; // calculate the rate to Euro by inverting the rate from Euro const toEuro = 1 / eurData.rates[fromCode]; CURRENCIES[fromCode].rates = { EUR: toEuro}; for(const toCode of SORTED_CURRENCY_CODES){ // skip the Euro if(toCode === 'EUR') continue; // check for self if(fromCode === toCode){ CURRENCIES[fromCode].rates[toCode] = 1; }else{ const rate = toEuro * eurData.rates[toCode]; CURRENCIES[fromCode].rates[toCode] = rate; } } } console.debug('Finished currency rate conversions'); }
JavaScript
function buildRatesSelectionFormUI(){ // build the show/hide rates form const $currencySelectionForm = $(Mustache.render( TEMPLATES.ui.showHideRates, CURRENCY_CONTROL_VIEW )); // add event handlers to all the toggles and trigger them to get the // inital rendering right $('input[type="checkbox"]', $currencySelectionForm).on('input', function(){ // get a reference to a jQuery object representing the toggle const $toggle = $(this); // get the currency the toggle controls const curCode = $toggle.val(); // save the state to the global variable DISPLAY_CURRENCIES[curCode] = $toggle.prop('checked') ? true : false; // update the rendering for the currency in all cards and in the grid if(DISPLAY_CURRENCIES[curCode]){ showCurrencyCardConversions(curCode); showGridCurrency(curCode); }else{ hideCurrencyCardConversions(curCode); hideGridCurrency(curCode); } // update the rates show/hide UI updateRatesUI(); }).trigger('input'); // return the form return $currencySelectionForm; }
function buildRatesSelectionFormUI(){ // build the show/hide rates form const $currencySelectionForm = $(Mustache.render( TEMPLATES.ui.showHideRates, CURRENCY_CONTROL_VIEW )); // add event handlers to all the toggles and trigger them to get the // inital rendering right $('input[type="checkbox"]', $currencySelectionForm).on('input', function(){ // get a reference to a jQuery object representing the toggle const $toggle = $(this); // get the currency the toggle controls const curCode = $toggle.val(); // save the state to the global variable DISPLAY_CURRENCIES[curCode] = $toggle.prop('checked') ? true : false; // update the rendering for the currency in all cards and in the grid if(DISPLAY_CURRENCIES[curCode]){ showCurrencyCardConversions(curCode); showGridCurrency(curCode); }else{ hideCurrencyCardConversions(curCode); hideGridCurrency(curCode); } // update the rates show/hide UI updateRatesUI(); }).trigger('input'); // return the form return $currencySelectionForm; }
JavaScript
function buildNewCardFormUI(){ // build the form const $addCardForm = $(Mustache.render( TEMPLATES.cards.addCardForm, CURRENCY_CONTROL_VIEW )); // select the first currency in the list $('select option', $addCardForm).first().prop('selected', true); // add a submit handler to the add currency card form $('form', $addCardForm).on('submit', function(){ // get a reference to the form as a jQuery object $form = $(this); // get the selected currency const curCode = $('select', $form).val(); // show the requested card showCurrencyCard(curCode); }); // return the form return $addCardForm; }
function buildNewCardFormUI(){ // build the form const $addCardForm = $(Mustache.render( TEMPLATES.cards.addCardForm, CURRENCY_CONTROL_VIEW )); // select the first currency in the list $('select option', $addCardForm).first().prop('selected', true); // add a submit handler to the add currency card form $('form', $addCardForm).on('submit', function(){ // get a reference to the form as a jQuery object $form = $(this); // get the selected currency const curCode = $('select', $form).val(); // show the requested card showCurrencyCard(curCode); }); // return the form return $addCardForm; }
JavaScript
function buildCurrencyCardCol(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // build the view for the card const cardView = { base: { code: curCode, ...CURRENCIES[curCode] }, rates: [] }; for(const toCurCode of SORTED_CURRENCY_CODES){ if(toCurCode === curCode) continue; // skip self cardView.rates.push({ code: toCurCode, rate: formatCurrencyAmount(CURRENCIES[curCode].rates[toCurCode], toCurCode), rawRate: CURRENCIES[curCode].rates[toCurCode], ...CURRENCIES[toCurCode] }); } console.debug(`generated view for '${curCode}':`, cardView); // generate the HTML const cardHTML = Mustache.render(TEMPLATES.cards.currencyCardCol, cardView); // convert the HTML to a jQuery object const $card = $(cardHTML); // hide the currencies that should not be showing for(const toCurCode of SORTED_CURRENCY_CODES){ if(!DISPLAY_CURRENCIES[toCurCode]){ $(`li.currencyRate[data-currency='${toCurCode}']`, $card).hide(); } } // add a click handler to the close button $('button.close', $card).click(function(){ hideCurrencyCard(curCode); }); // add an input handler to the base amount text box $('input.baseAmount', $card).on('input', function(){ // convert the DOM object for the input to a jQuery object const $input = $(this); // get a reference to the card's form const $form = $input.closest('form'); // enable the display of the validation state on the form $form.addClass('was-validated'); // read the base amount for the form let baseAmount = $input.val(); // default to 1 if invalid if($input.is(':invalid')){ baseAmount = 1; } // remove a trailing dot if present ('4.' to '4') baseAmount = String(baseAmount).replace(/[.]$/, ''); // do the conversion updateCardConversions(curCode, baseAmount); }); // return the card return $card; }
function buildCurrencyCardCol(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // build the view for the card const cardView = { base: { code: curCode, ...CURRENCIES[curCode] }, rates: [] }; for(const toCurCode of SORTED_CURRENCY_CODES){ if(toCurCode === curCode) continue; // skip self cardView.rates.push({ code: toCurCode, rate: formatCurrencyAmount(CURRENCIES[curCode].rates[toCurCode], toCurCode), rawRate: CURRENCIES[curCode].rates[toCurCode], ...CURRENCIES[toCurCode] }); } console.debug(`generated view for '${curCode}':`, cardView); // generate the HTML const cardHTML = Mustache.render(TEMPLATES.cards.currencyCardCol, cardView); // convert the HTML to a jQuery object const $card = $(cardHTML); // hide the currencies that should not be showing for(const toCurCode of SORTED_CURRENCY_CODES){ if(!DISPLAY_CURRENCIES[toCurCode]){ $(`li.currencyRate[data-currency='${toCurCode}']`, $card).hide(); } } // add a click handler to the close button $('button.close', $card).click(function(){ hideCurrencyCard(curCode); }); // add an input handler to the base amount text box $('input.baseAmount', $card).on('input', function(){ // convert the DOM object for the input to a jQuery object const $input = $(this); // get a reference to the card's form const $form = $input.closest('form'); // enable the display of the validation state on the form $form.addClass('was-validated'); // read the base amount for the form let baseAmount = $input.val(); // default to 1 if invalid if($input.is(':invalid')){ baseAmount = 1; } // remove a trailing dot if present ('4.' to '4') baseAmount = String(baseAmount).replace(/[.]$/, ''); // do the conversion updateCardConversions(curCode, baseAmount); }); // return the card return $card; }
JavaScript
function buildCurrencyCardCols(){ let $cards = $(); // empty jQuery object // build and store each card for(const baseCurCode of SORTED_CURRENCY_CODES){ // generate a card for the currency const $card = buildCurrencyCardCol(baseCurCode); // hide the card $card.hide(); // append the card into the collection of cards $cards = $cards.add($card); } // return the placeholder cards return $cards; }
function buildCurrencyCardCols(){ let $cards = $(); // empty jQuery object // build and store each card for(const baseCurCode of SORTED_CURRENCY_CODES){ // generate a card for the currency const $card = buildCurrencyCardCol(baseCurCode); // hide the card $card.hide(); // append the card into the collection of cards $cards = $cards.add($card); } // return the placeholder cards return $cards; }
JavaScript
function buildCurrencyGrid(){ // build the view const gridView = _.cloneDeep(CURRENCY_CONTROL_VIEW); for(const curObj of gridView.currencies){ curObj.conversions = []; for(const toCode of SORTED_CURRENCY_CODES){ curObj.conversions.push({ ...CURRENCIES[toCode], code: toCode, rate: numeral(CURRENCIES[curObj.code].rates[toCode]).format('0,0[.]0000'), rawRate: CURRENCIES[curObj.code].rates[toCode], base: { name: curObj.name, code: curObj.code, icon: curObj.icon, symbol: curObj.symbol } }); } } console.debug('generated view for currency grid:', gridView); // build the table const $table = $(Mustache.render( TEMPLATES.grid.table, gridView )); // hide all the currency grid rows and columns $('.currencyGridCell, .currencyGridRow', $table).hide(); // return the table return $table; }
function buildCurrencyGrid(){ // build the view const gridView = _.cloneDeep(CURRENCY_CONTROL_VIEW); for(const curObj of gridView.currencies){ curObj.conversions = []; for(const toCode of SORTED_CURRENCY_CODES){ curObj.conversions.push({ ...CURRENCIES[toCode], code: toCode, rate: numeral(CURRENCIES[curObj.code].rates[toCode]).format('0,0[.]0000'), rawRate: CURRENCIES[curObj.code].rates[toCode], base: { name: curObj.name, code: curObj.code, icon: curObj.icon, symbol: curObj.symbol } }); } } console.debug('generated view for currency grid:', gridView); // build the table const $table = $(Mustache.render( TEMPLATES.grid.table, gridView )); // hide all the currency grid rows and columns $('.currencyGridCell, .currencyGridRow', $table).hide(); // return the table return $table; }
JavaScript
function showRate(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // show the currency card conversions showCurrencyCardConversions(curCode) // show the grid row & column for the currency showGridCurrency(curCode); // mark the currency as active DISPLAY_CURRENCIES[curCode] = true; // update the show/hide rate UI updateRatesUI(); }
function showRate(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // show the currency card conversions showCurrencyCardConversions(curCode) // show the grid row & column for the currency showGridCurrency(curCode); // mark the currency as active DISPLAY_CURRENCIES[curCode] = true; // update the show/hide rate UI updateRatesUI(); }
JavaScript
function hideCurrency(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // hide the currency card conversions hideCurrencyCardConversions(curCode) // hide the grid row & column for the currency hideGridCurrency(curCode); // mark the currency as inactive DISPLAY_CURRENCIES[curCode] = fale; // update the show/hide rate UI updateRatesUI(); }
function hideCurrency(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // hide the currency card conversions hideCurrencyCardConversions(curCode) // hide the grid row & column for the currency hideGridCurrency(curCode); // mark the currency as inactive DISPLAY_CURRENCIES[curCode] = fale; // update the show/hide rate UI updateRatesUI(); }
JavaScript
function showCurrencyCard(curCode, skipFocus){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // get the col for the currency const $curCol = $currencyCardCol(curCode); // show the col $curCol.show(); // mark the card as active $curCol.data('active', true); // focus the card if appropriate if(!skipFocus) $('input.baseAmount', $curCol).focus(); // update the select in the add card form updateAddCardSelectOptions(); }
function showCurrencyCard(curCode, skipFocus){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // get the col for the currency const $curCol = $currencyCardCol(curCode); // show the col $curCol.show(); // mark the card as active $curCol.data('active', true); // focus the card if appropriate if(!skipFocus) $('input.baseAmount', $curCol).focus(); // update the select in the add card form updateAddCardSelectOptions(); }
JavaScript
function hideCurrencyCard(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // get the col for the currency const $curCol = $currencyCardCol(curCode); // hide the col $curCol.hide(); // mark the card as inactive $curCol.data('active', false); // update the select in the add card form updateAddCardSelectOptions(); }
function hideCurrencyCard(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // get the col for the currency const $curCol = $currencyCardCol(curCode); // hide the col $curCol.hide(); // mark the card as inactive $curCol.data('active', false); // update the select in the add card form updateAddCardSelectOptions(); }
JavaScript
function showCurrencyCardConversions(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // show the rows $currencyCardLi(curCode).show(); }
function showCurrencyCardConversions(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // show the rows $currencyCardLi(curCode).show(); }
JavaScript
function hideCurrencyCardConversions(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // hide the rows $currencyCardLi(curCode).hide(); }
function hideCurrencyCardConversions(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // hide the rows $currencyCardLi(curCode).hide(); }
JavaScript
function updateRatesUI(){ // loop over all the switches $('input:checkbox', $('#showHideRatesForm')).each(function(){ // get a reference to a jQuery object representing the toggle const $toggle = $(this); // get the currency the toggle controls const curCode = $toggle.val(); // set the state of the toggle to match the stored state $toggle.prop('checked', DISPLAY_CURRENCIES[curCode] ? true : false ); // updating the styling of the toggle as appropriate if($toggle.prop('checked')){ $toggle.closest('li') .removeClass('border-secondary') .addClass('border-primary font-weight-bold'); }else{ $toggle.closest('li') .removeClass('border-primary font-weight-bold') .addClass('border-secondary'); } }); }
function updateRatesUI(){ // loop over all the switches $('input:checkbox', $('#showHideRatesForm')).each(function(){ // get a reference to a jQuery object representing the toggle const $toggle = $(this); // get the currency the toggle controls const curCode = $toggle.val(); // set the state of the toggle to match the stored state $toggle.prop('checked', DISPLAY_CURRENCIES[curCode] ? true : false ); // updating the styling of the toggle as appropriate if($toggle.prop('checked')){ $toggle.closest('li') .removeClass('border-secondary') .addClass('border-primary font-weight-bold'); }else{ $toggle.closest('li') .removeClass('border-primary font-weight-bold') .addClass('border-secondary'); } }); }
JavaScript
function updateAddCardSelectOptions(){ // get a reference to the options in the select as a jQuery object const $opts = $('#add_currency_sel option'); // loop over all the options in the select and enable/disable as needed for(const opt of $opts){ // convert DOM object to jQuery object const $opt = $(opt); // get the currency code the option represents const curCode = $opt.val(); // get a reference to the col for this currency const $curCol = $currencyCardCol(curCode); // enabled/disable this option based on the visibility // of the matching card $opt.prop('disabled', $curCol.data('active') ? true : false ); } // select the first enabled option for(const opt of $opts){ // convert DOM object to jQuery object const $opt = $(opt); // if the current option is not disabled, select it and exit the loop if(!$opt.prop('disabled')){ $opt.prop('selected', true); break; // end the loop } } }
function updateAddCardSelectOptions(){ // get a reference to the options in the select as a jQuery object const $opts = $('#add_currency_sel option'); // loop over all the options in the select and enable/disable as needed for(const opt of $opts){ // convert DOM object to jQuery object const $opt = $(opt); // get the currency code the option represents const curCode = $opt.val(); // get a reference to the col for this currency const $curCol = $currencyCardCol(curCode); // enabled/disable this option based on the visibility // of the matching card $opt.prop('disabled', $curCol.data('active') ? true : false ); } // select the first enabled option for(const opt of $opts){ // convert DOM object to jQuery object const $opt = $(opt); // if the current option is not disabled, select it and exit the loop if(!$opt.prop('disabled')){ $opt.prop('selected', true); break; // end the loop } } }
JavaScript
function updateCardConversions(curCode, baseAmount){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // get the col for the currency const $curCol = $(`.currencyCol[data-currency='${curCode}']`); // validate the amount if(!String(baseAmount).match(/^\d+(?:[.]\d+)?$/)){ throw new TypeError(`Invalid base amount: ${baseAmount}`); } // update all the renderings of the base amount $('.baseAmount', $curCol).text(formatCurrencyAmount(baseAmount, curCode)); // loop through each currency in the card and update the conversion //const $rateLis = $(`li.currencyRate[data-currency='${curCode}']`); const $rateLis = $('li.currencyRate', $curCol); for(const li of $rateLis){ // convert the DOM object to a jQuery object const $li = $(li); // get the rate const rate = $li.data('rate'); // get a reference to the converted value place holder $convSpan = $('.convertedAmount', $li); // do the conversion const convAmount = baseAmount * rate; // output the value $convSpan.text(formatCurrencyAmount(convAmount, $li.data('currency'))); } }
function updateCardConversions(curCode, baseAmount){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // get the col for the currency const $curCol = $(`.currencyCol[data-currency='${curCode}']`); // validate the amount if(!String(baseAmount).match(/^\d+(?:[.]\d+)?$/)){ throw new TypeError(`Invalid base amount: ${baseAmount}`); } // update all the renderings of the base amount $('.baseAmount', $curCol).text(formatCurrencyAmount(baseAmount, curCode)); // loop through each currency in the card and update the conversion //const $rateLis = $(`li.currencyRate[data-currency='${curCode}']`); const $rateLis = $('li.currencyRate', $curCol); for(const li of $rateLis){ // convert the DOM object to a jQuery object const $li = $(li); // get the rate const rate = $li.data('rate'); // get a reference to the converted value place holder $convSpan = $('.convertedAmount', $li); // do the conversion const convAmount = baseAmount * rate; // output the value $convSpan.text(formatCurrencyAmount(convAmount, $li.data('currency'))); } }
JavaScript
function $currencyCardCol(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); return $(`.currencyCol[data-currency=${curCode}]`); }
function $currencyCardCol(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); return $(`.currencyCol[data-currency=${curCode}]`); }
JavaScript
function $currencyCardLi(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); return $(`li.currencyRate[data-currency='${curCode}']`); }
function $currencyCardLi(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); return $(`li.currencyRate[data-currency='${curCode}']`); }
JavaScript
function showGridCurrency(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // get the row and column (th & tds) for the currency const $curRow = $currencyGridRow(curCode); const $curCol = $currencyGridCol(curCode); // show the row and column $curRow.show(); $curCol.show(); }
function showGridCurrency(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // get the row and column (th & tds) for the currency const $curRow = $currencyGridRow(curCode); const $curCol = $currencyGridCol(curCode); // show the row and column $curRow.show(); $curCol.show(); }
JavaScript
function hideGridCurrency(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // get the row and column (th & tds) for the currency const $curRow = $currencyGridRow(curCode); const $curCol = $currencyGridCol(curCode); // hide the row and column $curRow.hide(); $curCol.hide(); }
function hideGridCurrency(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // get the row and column (th & tds) for the currency const $curRow = $currencyGridRow(curCode); const $curCol = $currencyGridCol(curCode); // hide the row and column $curRow.hide(); $curCol.hide(); }
JavaScript
function $currencyGridRow(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); return $(`tr[data-row-currency=${curCode}]`, $('#currency_grid')); }
function $currencyGridRow(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); return $(`tr[data-row-currency=${curCode}]`, $('#currency_grid')); }
JavaScript
function $currencyGridCol(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); return $(`th[data-col-currency=${curCode}], td[data-col-currency=${curCode}]`, $('#currency_grid')); }
function $currencyGridCol(curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); return $(`th[data-col-currency=${curCode}], td[data-col-currency=${curCode}]`, $('#currency_grid')); }
JavaScript
function formatCurrencyAmount(amount, curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // build the format string based on the number of digits const numDigits = CURRENCIES[curCode].decimalDigits; let formatString = '0,0'; // default to no decimal places if(numDigits){ // more than zero digits after the decimal place // add the optional period formatString += '[.]'; // add the needed decimal places for(let d = numDigits; d > 0; d--){ formatString += '0'; } } // format and return the amount return numeral(amount).format(formatString); }
function formatCurrencyAmount(amount, curCode){ // force the code to upper case and validate curCode = assertCurrencyCode(curCode); // build the format string based on the number of digits const numDigits = CURRENCIES[curCode].decimalDigits; let formatString = '0,0'; // default to no decimal places if(numDigits){ // more than zero digits after the decimal place // add the optional period formatString += '[.]'; // add the needed decimal places for(let d = numDigits; d > 0; d--){ formatString += '0'; } } // format and return the amount return numeral(amount).format(formatString); }
JavaScript
set diameter(diameter){ const diameterNumber = parseFloat(diameter); if(isNaN(diameterNumber)){ throw new TypeError('diameter must be a number greater than or equal to zero'); } if(diameterNumber < 0){ throw new RangeError('diameter cannot be negative'); } if(diameterNumber === 0){ this._radius = 0; // avoid divide-by-zero error }else{ this._radius = diameterNumber / 2; } }
set diameter(diameter){ const diameterNumber = parseFloat(diameter); if(isNaN(diameterNumber)){ throw new TypeError('diameter must be a number greater than or equal to zero'); } if(diameterNumber < 0){ throw new RangeError('diameter cannot be negative'); } if(diameterNumber === 0){ this._radius = 0; // avoid divide-by-zero error }else{ this._radius = diameterNumber / 2; } }
JavaScript
set circumference(circumference){ const circumferenceNumber = parseFloat(circumference); if(isNaN(circumferenceNumber)){ throw new TypeError('circumerence must be a number greater than or equal to zero'); } if(circumferenceNumber < 0){ throw new RangeError('circumference cannot be negative'); } if(circumferenceNumber === 0){ this._radius = 0; // avoid divide-by-zero error }else{ this._radius = circumferenceNumber / (2 * Math.PI); } }
set circumference(circumference){ const circumferenceNumber = parseFloat(circumference); if(isNaN(circumferenceNumber)){ throw new TypeError('circumerence must be a number greater than or equal to zero'); } if(circumferenceNumber < 0){ throw new RangeError('circumference cannot be negative'); } if(circumferenceNumber === 0){ this._radius = 0; // avoid divide-by-zero error }else{ this._radius = circumferenceNumber / (2 * Math.PI); } }
JavaScript
set area(area){ const areaNumber = parseFloat(area); if(isNaN(areaNumber)){ throw new TypeError('area must be a number greater than or equal to zero'); } if(areaNumber < 0){ throw new RangeError('area cannot be negative'); } if(areaNumber === 0){ this._radius = 0; // avoid divide-by-zero error }else{ this._radius = Math.sqrt(areaNumber / Math.PI); } }
set area(area){ const areaNumber = parseFloat(area); if(isNaN(areaNumber)){ throw new TypeError('area must be a number greater than or equal to zero'); } if(areaNumber < 0){ throw new RangeError('area cannot be negative'); } if(areaNumber === 0){ this._radius = 0; // avoid divide-by-zero error }else{ this._radius = Math.sqrt(areaNumber / Math.PI); } }
JavaScript
set circumference(circumference){ const circumferenceNumber = parseFloat(circumference); if(isNaN(circumferenceNumber)){ throw new TypeError('circumerence must be a number greater than or equal to zero'); } if(circumferenceNumber < 0){ throw new RangeError('circumference cannot be negative'); } if(circumferenceNumber === 0){ this._radius = 0; // avoid divide-by-zero error }else{ this._radius = circumferenceNumber / (2 * this.π); } }
set circumference(circumference){ const circumferenceNumber = parseFloat(circumference); if(isNaN(circumferenceNumber)){ throw new TypeError('circumerence must be a number greater than or equal to zero'); } if(circumferenceNumber < 0){ throw new RangeError('circumference cannot be negative'); } if(circumferenceNumber === 0){ this._radius = 0; // avoid divide-by-zero error }else{ this._radius = circumferenceNumber / (2 * this.π); } }
JavaScript
set area(area){ const areaNumber = parseFloat(area); if(isNaN(areaNumber)){ throw new TypeError('area must be a number greater than or equal to zero'); } if(areaNumber < 0){ throw new RangeError('area cannot be negative'); } if(areaNumber === 0){ this._radius = 0; // avoid divide-by-zero error }else{ this._radius = Math.sqrt(areaNumber / this.π); } }
set area(area){ const areaNumber = parseFloat(area); if(isNaN(areaNumber)){ throw new TypeError('area must be a number greater than or equal to zero'); } if(areaNumber < 0){ throw new RangeError('area cannot be negative'); } if(areaNumber === 0){ this._radius = 0; // avoid divide-by-zero error }else{ this._radius = Math.sqrt(areaNumber / this.π); } }
JavaScript
function updateSigninStatus(isSignedIn) { if (isSignedIn) { console.log("Signed In."); $(".load-copy-authed").show(); $(".load-button-authed").show(); $(".load-copy-unauthed").hide(); $(".load-button-unauthed").hide(); $(".save-copy-authed").show(); $(".save-button-authed").show(); $(".save-copy-unauthed").hide(); $(".save-button-unauthed").hide(); } else { console.log("Not Signed In."); $(".load-copy-authed").hide(); $(".load-button-authed").hide(); $(".load-copy-unauthed").show(); $(".load-button-unauthed").show(); $(".save-copy-authed").hide(); $(".save-button-authed").hide(); $(".save-copy-unauthed").show(); $(".save-button-unauthed").show(); } }
function updateSigninStatus(isSignedIn) { if (isSignedIn) { console.log("Signed In."); $(".load-copy-authed").show(); $(".load-button-authed").show(); $(".load-copy-unauthed").hide(); $(".load-button-unauthed").hide(); $(".save-copy-authed").show(); $(".save-button-authed").show(); $(".save-copy-unauthed").hide(); $(".save-button-unauthed").hide(); } else { console.log("Not Signed In."); $(".load-copy-authed").hide(); $(".load-button-authed").hide(); $(".load-copy-unauthed").show(); $(".load-button-unauthed").show(); $(".save-copy-authed").hide(); $(".save-button-authed").hide(); $(".save-copy-unauthed").show(); $(".save-button-unauthed").show(); } }
JavaScript
function handleFileSelect(evt) { var files = evt.target.files; // FileList object var reader = new FileReader(); reader.onload = function(e) { $(".module").remove(); fileBuilder(reader.result); $("input[type='color']").spectrum("destroy"); $(".sp-replacer").remove(); //sweep away empty shells $("input[type='color']").spectrum(); //rehook the colorpickers $("#project-decription").keyup(); closeAllMenus(); } reader.readAsText(files[0]); }
function handleFileSelect(evt) { var files = evt.target.files; // FileList object var reader = new FileReader(); reader.onload = function(e) { $(".module").remove(); fileBuilder(reader.result); $("input[type='color']").spectrum("destroy"); $(".sp-replacer").remove(); //sweep away empty shells $("input[type='color']").spectrum(); //rehook the colorpickers $("#project-decription").keyup(); closeAllMenus(); } reader.readAsText(files[0]); }
JavaScript
function pseudoConfig(){ $(".program-button").attr("style", "opacity: 0.4; pointer-events: none"); var attrString = ""; attrString += $("#project-name").html() + ","; attrString += $("#project-decription").html() + ","; $(".canvas").find(".module").each(function(){ attrString += $(this).find(".actions-list").attr("class").split(' ')[1] + ","; $(this).find(".actions-list").find(".action").each(function(){ attrString += $(this).attr("class").split(' ')[1] + ","; $(this).find("input").each(function(){ if($(this).hasClass("radio")){ if($(this).attr("data-checked")!=undefined){ attrString += "1,"; }else{ attrString += "0,"; } }else if($(this).hasClass("color")){ attrString += $(this).attr("value") + ","; }else{ attrString += $(this).val() + ","; } }); }); }); attrString += "<end>"; console.log(attrString); return(attrString); }
function pseudoConfig(){ $(".program-button").attr("style", "opacity: 0.4; pointer-events: none"); var attrString = ""; attrString += $("#project-name").html() + ","; attrString += $("#project-decription").html() + ","; $(".canvas").find(".module").each(function(){ attrString += $(this).find(".actions-list").attr("class").split(' ')[1] + ","; $(this).find(".actions-list").find(".action").each(function(){ attrString += $(this).attr("class").split(' ')[1] + ","; $(this).find("input").each(function(){ if($(this).hasClass("radio")){ if($(this).attr("data-checked")!=undefined){ attrString += "1,"; }else{ attrString += "0,"; } }else if($(this).hasClass("color")){ attrString += $(this).attr("value") + ","; }else{ attrString += $(this).val() + ","; } }); }); }); attrString += "<end>"; console.log(attrString); return(attrString); }
JavaScript
function audio_serial_write(data, callback) { var sampleRate = 44100; var header = 200; // preamble/postable var baud = 450; var samplesPerByte = parseInt(sampleRate*11/baud, 10); // the number of PCM samples per byte var lfc = 0; // linefeed count data.split("").forEach(function(c) { // count the number of linefeeds and thus checksums for buffer sizing var lfcbyte = c.charCodeAt(0); if(lfcbyte==10){lfc++;} }); var bufferSize = samplesPerByte*data.length/*samples*/ + header*2 + lfc*samplesPerByte; var buffer = context.createBuffer(1, bufferSize, sampleRate); var b = buffer.getChannelData(0); var debug = 0; // print bits to console (stupid) for (var i=0;i<header;i++) b[i]=1; // Construct a preamble var offset = header; // offset will keep our place in the PCM buffer that we're constructing var runningSum = 0; // variable for adding the checksum data.split("").forEach(function(c) { // split the incoming data into bytes, process each byte var byte = c.charCodeAt(0); // get the ascii character code for the current byte runningSum+=byte; // add the current character to the running checksum if (byte>=0 && byte<=255) { // if that character code is out of range we insert a pause for (var i=0;i<samplesPerByte;i++) { // for the number of samples in a byte... var bit = Math.floor(i*baud/sampleRate); // find out which bit in the current byte we're working on var value = 1; // make a place to store the value of this PCM sample if (bit==0) {value=0; if(debug){console.log(value)};} // bit 0 is always a start bit and writes 0 else if (bit==9 || bit==10) {value=1; if(debug){console.log(value)};} // bit 9 and 10 are always stop bits and write 1 else {value = (byte&(0x01<<(8-bit))) ? 1 : 0; if(debug){console.log(value)};} // for each data bit, invert the data and write to the PCM buffer b[offset++] = value*2-1; // shift from binary data to -1/1 range of full-swing PCM data } if (byte==10) { // if the current byte is a linefeed, append a checksum var checksum = runningSum % 256; // "roll" the checksum over if(debug){console.log("Linefeed detected. Checksum " + checksum + " to follow.");}; runningSum = 0; // reset the runningSum // buffer packing scheme from above for (var i=0;i<samplesPerByte;i++) { var bit = Math.floor(i*baud/sampleRate); var value = 1; if (bit==0) {value=0; if(debug){console.log(value)};} else if (bit==9 || bit==10) {value=1; if(debug){console.log(value)};} else {value = (checksum&(0x01<<(8-bit))) ? 1 : 0; if(debug){console.log(value)};} b[offset++] = value*2-1; } } } else { // if ASCII character code is out of range we insert a pause for (var i=0;i<samplesPerByte;i++) b[offset++] = 1; } }); // End of transmission checksum (because every document doesn't end in a LF) if(runningSum!=0){ var checksum = runningSum % 256; // "roll" the checksum over if(debug){console.log("End of transmission. Checksum " + checksum + " to follow.")}; runningSum = 0; // reset the runningSum // buffer packing scheme from above for (var i=0;i<samplesPerByte;i++) { var bit = Math.floor(i*baud/sampleRate); var value = 1; if (bit==0) {value=0; if(debug){console.log(value)};} else if (bit==9 || bit==10) {value=1; if(debug){console.log(value)};} else {value = (checksum&(0x01<<(8-bit))) ? 1 : 0; if(debug){console.log(value)};} b[offset++] = value*2-1; } } for (var i=0;i<header;i++) b[offset+i]=1; // Construct a postamble // prepare our audio chain to create FSK waveform var modGain = context.createGain(); // Create a gain module modGain.gain.value = 1000; // Set gain to 500x var osc = context.createOscillator(); // Create our carrier oscillator osc.frequency.value = 4000; // Set sine carrier frequency var source = context.createBufferSource(); // Create an "audio source" for our modulating waveform source.buffer = buffer; // Use our pre-constructed PCM buffer as the modulating source source.connect(modGain); // Connect the modulating source (-1/1) to the gain module // Connect the gain module (-gain/gain) to the frequency control of the carrier oscillator modGain.connect(osc.frequency); // Connect the source-modulated-carrier oscillator to the soundcard osc.connect(context.destination); // Start the carrier oscillator osc.start(); // Start the modulating source source.start(); // When the modulating source finishes chewing on our buffer, stop the carrier oscillator source.onended = function() { osc.stop(); $(".program-button").attr("style", "opacity: 1; pointer-events: auto"); }; if (callback) window.setTimeout(callback, 1000*bufferSize/sampleRate); }
function audio_serial_write(data, callback) { var sampleRate = 44100; var header = 200; // preamble/postable var baud = 450; var samplesPerByte = parseInt(sampleRate*11/baud, 10); // the number of PCM samples per byte var lfc = 0; // linefeed count data.split("").forEach(function(c) { // count the number of linefeeds and thus checksums for buffer sizing var lfcbyte = c.charCodeAt(0); if(lfcbyte==10){lfc++;} }); var bufferSize = samplesPerByte*data.length/*samples*/ + header*2 + lfc*samplesPerByte; var buffer = context.createBuffer(1, bufferSize, sampleRate); var b = buffer.getChannelData(0); var debug = 0; // print bits to console (stupid) for (var i=0;i<header;i++) b[i]=1; // Construct a preamble var offset = header; // offset will keep our place in the PCM buffer that we're constructing var runningSum = 0; // variable for adding the checksum data.split("").forEach(function(c) { // split the incoming data into bytes, process each byte var byte = c.charCodeAt(0); // get the ascii character code for the current byte runningSum+=byte; // add the current character to the running checksum if (byte>=0 && byte<=255) { // if that character code is out of range we insert a pause for (var i=0;i<samplesPerByte;i++) { // for the number of samples in a byte... var bit = Math.floor(i*baud/sampleRate); // find out which bit in the current byte we're working on var value = 1; // make a place to store the value of this PCM sample if (bit==0) {value=0; if(debug){console.log(value)};} // bit 0 is always a start bit and writes 0 else if (bit==9 || bit==10) {value=1; if(debug){console.log(value)};} // bit 9 and 10 are always stop bits and write 1 else {value = (byte&(0x01<<(8-bit))) ? 1 : 0; if(debug){console.log(value)};} // for each data bit, invert the data and write to the PCM buffer b[offset++] = value*2-1; // shift from binary data to -1/1 range of full-swing PCM data } if (byte==10) { // if the current byte is a linefeed, append a checksum var checksum = runningSum % 256; // "roll" the checksum over if(debug){console.log("Linefeed detected. Checksum " + checksum + " to follow.");}; runningSum = 0; // reset the runningSum // buffer packing scheme from above for (var i=0;i<samplesPerByte;i++) { var bit = Math.floor(i*baud/sampleRate); var value = 1; if (bit==0) {value=0; if(debug){console.log(value)};} else if (bit==9 || bit==10) {value=1; if(debug){console.log(value)};} else {value = (checksum&(0x01<<(8-bit))) ? 1 : 0; if(debug){console.log(value)};} b[offset++] = value*2-1; } } } else { // if ASCII character code is out of range we insert a pause for (var i=0;i<samplesPerByte;i++) b[offset++] = 1; } }); // End of transmission checksum (because every document doesn't end in a LF) if(runningSum!=0){ var checksum = runningSum % 256; // "roll" the checksum over if(debug){console.log("End of transmission. Checksum " + checksum + " to follow.")}; runningSum = 0; // reset the runningSum // buffer packing scheme from above for (var i=0;i<samplesPerByte;i++) { var bit = Math.floor(i*baud/sampleRate); var value = 1; if (bit==0) {value=0; if(debug){console.log(value)};} else if (bit==9 || bit==10) {value=1; if(debug){console.log(value)};} else {value = (checksum&(0x01<<(8-bit))) ? 1 : 0; if(debug){console.log(value)};} b[offset++] = value*2-1; } } for (var i=0;i<header;i++) b[offset+i]=1; // Construct a postamble // prepare our audio chain to create FSK waveform var modGain = context.createGain(); // Create a gain module modGain.gain.value = 1000; // Set gain to 500x var osc = context.createOscillator(); // Create our carrier oscillator osc.frequency.value = 4000; // Set sine carrier frequency var source = context.createBufferSource(); // Create an "audio source" for our modulating waveform source.buffer = buffer; // Use our pre-constructed PCM buffer as the modulating source source.connect(modGain); // Connect the modulating source (-1/1) to the gain module // Connect the gain module (-gain/gain) to the frequency control of the carrier oscillator modGain.connect(osc.frequency); // Connect the source-modulated-carrier oscillator to the soundcard osc.connect(context.destination); // Start the carrier oscillator osc.start(); // Start the modulating source source.start(); // When the modulating source finishes chewing on our buffer, stop the carrier oscillator source.onended = function() { osc.stop(); $(".program-button").attr("style", "opacity: 1; pointer-events: auto"); }; if (callback) window.setTimeout(callback, 1000*bufferSize/sampleRate); }
JavaScript
function encodeFile(){ var attrString = ""; attrString += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?> \n\n"; attrString += "<config>\n\n"; attrString += "<title>" + $("#project-name").html() + "</title>\n"; attrString += "<description>" + $("#project-decription").html() + "</description>\n\n"; $(".canvas").find(".module").each(function(){ attrString += "<board type=\"" + $(this).find(".actions-list").attr("class").split(' ')[1] + "\" nickname=\""; attrString += $(this).find("#mod-nick").html() + "\">\n\n"; $(this).find(".actions-list").find(".action").each(function(){ attrString += "\t\t<action type=\"" + $(this).attr("class").split(' ')[1] + "\">\n"; $(this).find("input").each(function(){ if($(this).hasClass("radio")){ if($(this).attr("data-checked")!=undefined){ attrString += "\t\t<entry>1</entry>\n"; }else{ attrString += "\t\t<entry>0</entry>\n"; } }else if($(this).hasClass("color")){ attrString += "\t\t<entry>" + $(this).attr("value") + "</entry>\n"; }else{ attrString += "\t\t<entry>" + $(this).val() + "</entry>\n"; } }); attrString += "\t\t</action>\n\n"; }); attrString += "</board>\n\n"; }); attrString += "\n</config>"; console.log(attrString); return(attrString); }
function encodeFile(){ var attrString = ""; attrString += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?> \n\n"; attrString += "<config>\n\n"; attrString += "<title>" + $("#project-name").html() + "</title>\n"; attrString += "<description>" + $("#project-decription").html() + "</description>\n\n"; $(".canvas").find(".module").each(function(){ attrString += "<board type=\"" + $(this).find(".actions-list").attr("class").split(' ')[1] + "\" nickname=\""; attrString += $(this).find("#mod-nick").html() + "\">\n\n"; $(this).find(".actions-list").find(".action").each(function(){ attrString += "\t\t<action type=\"" + $(this).attr("class").split(' ')[1] + "\">\n"; $(this).find("input").each(function(){ if($(this).hasClass("radio")){ if($(this).attr("data-checked")!=undefined){ attrString += "\t\t<entry>1</entry>\n"; }else{ attrString += "\t\t<entry>0</entry>\n"; } }else if($(this).hasClass("color")){ attrString += "\t\t<entry>" + $(this).attr("value") + "</entry>\n"; }else{ attrString += "\t\t<entry>" + $(this).val() + "</entry>\n"; } }); attrString += "\t\t</action>\n\n"; }); attrString += "</board>\n\n"; }); attrString += "\n</config>"; console.log(attrString); return(attrString); }
JavaScript
function Child() { React.useLayoutEffect(() => { Scheduler.unstable_yieldValue('Mount'); return () => { Scheduler.unstable_yieldValue('Unmount'); }; }, []); return <Text text="Child" />; }
function Child() { React.useLayoutEffect(() => { Scheduler.unstable_yieldValue('Mount'); return () => { Scheduler.unstable_yieldValue('Unmount'); }; }, []); return <Text text="Child" />; }
JavaScript
topFunction() { //console.log("scroll-to-top-wc: initiating scroll"); let event = new CustomEvent("scrolling", { detail: { message: "activated scroll to top", }, bubbles: true, composed: true, }); this.dispatchEvent(event); window.scrollTo({ top: 0, behavior: "smooth" }); }
topFunction() { //console.log("scroll-to-top-wc: initiating scroll"); let event = new CustomEvent("scrolling", { detail: { message: "activated scroll to top", }, bubbles: true, composed: true, }); this.dispatchEvent(event); window.scrollTo({ top: 0, behavior: "smooth" }); }
JavaScript
function calculatePopoverPosition(anchorBounds, popoverBounds, requestedPosition, buffer, positions) { if (buffer === void 0) { buffer = 16; } if (positions === void 0) { positions = ['top', 'right', 'bottom', 'left']; } if (typeof buffer !== 'number') { throw new Error("calculatePopoverPosition received a buffer argument of " + buffer + "' but expected a number"); } var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var popoverWidth = popoverBounds.width, popoverHeight = popoverBounds.height; var positionToBoundsMap = {}; var positionToVisibleAreaMap = {}; positions.forEach(function (position) { var bounds = positionToPositionerMap[position](anchorBounds, popoverWidth, popoverHeight, buffer); positionToBoundsMap[position] = bounds; // Calculate how much area of the popover is visible at each position. positionToVisibleAreaMap[position] = getVisibleArea(bounds, windowWidth, windowHeight); }); // If the requested position clips the popover, find the position which clips the popover the least. // Default to use the requested position. var calculatedPopoverPosition = positions.reduce(function (mostVisiblePosition, position) { if (positionToVisibleAreaMap[position] > positionToVisibleAreaMap[mostVisiblePosition]) { return position; } return mostVisiblePosition; }, requestedPosition); return __assign({ position: calculatedPopoverPosition }, positionToBoundsMap[calculatedPopoverPosition]); }
function calculatePopoverPosition(anchorBounds, popoverBounds, requestedPosition, buffer, positions) { if (buffer === void 0) { buffer = 16; } if (positions === void 0) { positions = ['top', 'right', 'bottom', 'left']; } if (typeof buffer !== 'number') { throw new Error("calculatePopoverPosition received a buffer argument of " + buffer + "' but expected a number"); } var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var popoverWidth = popoverBounds.width, popoverHeight = popoverBounds.height; var positionToBoundsMap = {}; var positionToVisibleAreaMap = {}; positions.forEach(function (position) { var bounds = positionToPositionerMap[position](anchorBounds, popoverWidth, popoverHeight, buffer); positionToBoundsMap[position] = bounds; // Calculate how much area of the popover is visible at each position. positionToVisibleAreaMap[position] = getVisibleArea(bounds, windowWidth, windowHeight); }); // If the requested position clips the popover, find the position which clips the popover the least. // Default to use the requested position. var calculatedPopoverPosition = positions.reduce(function (mostVisiblePosition, position) { if (positionToVisibleAreaMap[position] > positionToVisibleAreaMap[mostVisiblePosition]) { return position; } return mostVisiblePosition; }, requestedPosition); return __assign({ position: calculatedPopoverPosition }, positionToBoundsMap[calculatedPopoverPosition]); }
JavaScript
function colorPalette(hexStart, hexEnd, len) { if (len === void 0) { len = 10; } if (isHex(hexStart) && isHex(hexEnd)) { var colorArray = []; var hexPalette = []; var count = len - 1; var startHex = hexToRgb(hexStart); // get RGB equivalent values as array var endHex = hexToRgb(hexEnd); // get RGB equivalent values as array colorArray[0] = new Color(startHex[0], startHex[1], startHex[2]); // create first color obj colorArray[count] = new Color(endHex[0], endHex[1], endHex[2]); // create last color obj var step = stepCalc(count, colorArray[0], colorArray[count]); // create array of step increments // build the color palette array hexPalette[0] = colorArray[0].text; // set the first color in the array for (var i = 1; i < count; i++) { // set the intermediate colors in the array var r = colorArray[0].r + step[0] * i; var g = colorArray[0].g + step[1] * i; var b = colorArray[0].b + step[2] * i; colorArray[i] = new Color(r, g, b); hexPalette[i] = colorArray[i].text; } // all the colors in between hexPalette[count] = colorArray[count].text; // set the last color in the array return hexPalette; } else { throw new Error('Please provide two valid hex color codes.'); } }
function colorPalette(hexStart, hexEnd, len) { if (len === void 0) { len = 10; } if (isHex(hexStart) && isHex(hexEnd)) { var colorArray = []; var hexPalette = []; var count = len - 1; var startHex = hexToRgb(hexStart); // get RGB equivalent values as array var endHex = hexToRgb(hexEnd); // get RGB equivalent values as array colorArray[0] = new Color(startHex[0], startHex[1], startHex[2]); // create first color obj colorArray[count] = new Color(endHex[0], endHex[1], endHex[2]); // create last color obj var step = stepCalc(count, colorArray[0], colorArray[count]); // create array of step increments // build the color palette array hexPalette[0] = colorArray[0].text; // set the first color in the array for (var i = 1; i < count; i++) { // set the intermediate colors in the array var r = colorArray[0].r + step[0] * i; var g = colorArray[0].g + step[1] * i; var b = colorArray[0].b + step[2] * i; colorArray[i] = new Color(r, g, b); hexPalette[i] = colorArray[i].text; } // all the colors in between hexPalette[count] = colorArray[count].text; // set the last color in the array return hexPalette; } else { throw new Error('Please provide two valid hex color codes.'); } }
JavaScript
function createHex(rgbValues) { var result = ''; var val = 0; var piece; var base = 16; for (var k = 0; k < 3; k++) { val = Math.round(rgbValues[k]); piece = val.toString(base); // Converts to radix 16 based value (0-9, A-F) if (piece.length < 2) { piece = "0" + piece; } result = result + piece; } result = "#" + result.toUpperCase(); // Return in #RRGGBB format return result; }
function createHex(rgbValues) { var result = ''; var val = 0; var piece; var base = 16; for (var k = 0; k < 3; k++) { val = Math.round(rgbValues[k]); piece = val.toString(base); // Converts to radix 16 based value (0-9, A-F) if (piece.length < 2) { piece = "0" + piece; } result = result + piece; } result = "#" + result.toUpperCase(); // Return in #RRGGBB format return result; }
JavaScript
function stepCalc(st, cStart, cEnd) { var steps = st; var step = [ (cEnd.r - cStart.r) / steps, (cEnd.g - cStart.g) / steps, (cEnd.b - cStart.b) / steps, ]; return step; }
function stepCalc(st, cStart, cEnd) { var steps = st; var step = [ (cEnd.r - cStart.r) / steps, (cEnd.g - cStart.g) / steps, (cEnd.b - cStart.b) / steps, ]; return step; }
JavaScript
function nextTick() { draining = true; var i, oldQueue; var len = queue.length; while (len) { oldQueue = queue; queue = []; i = -1; while (++i < len) { oldQueue[i](); } len = queue.length; } draining = false; }
function nextTick() { draining = true; var i, oldQueue; var len = queue.length; while (len) { oldQueue = queue; queue = []; i = -1; while (++i < len) { oldQueue[i](); } len = queue.length; } draining = false; }
JavaScript
function _encodeBlob(blob) { return new Promise$1(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); }
function _encodeBlob(blob) { return new Promise$1(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); }
JavaScript
function _fullyReady(callback) { var self = this; var promise = self._initReady().then(function () { var dbContext = dbContexts[self._dbInfo.name]; if (dbContext && dbContext.dbReady) { return dbContext.dbReady; } }); executeTwoCallbacks(promise, callback, callback); return promise; }
function _fullyReady(callback) { var self = this; var promise = self._initReady().then(function () { var dbContext = dbContexts[self._dbInfo.name]; if (dbContext && dbContext.dbReady) { return dbContext.dbReady; } }); executeTwoCallbacks(promise, callback, callback); return promise; }
JavaScript
function createTransaction(dbInfo, mode, callback, retries) { if (retries === undefined) { retries = 1; } try { var tx = dbInfo.db.transaction(dbInfo.storeName, mode); callback(null, tx); } catch (err) { if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) { return Promise$1.resolve().then(function () { if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) { // increase the db version, to create the new ObjectStore if (dbInfo.db) { dbInfo.version = dbInfo.db.version + 1; } // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } }).then(function () { return _tryReconnect(dbInfo).then(function () { createTransaction(dbInfo, mode, callback, retries - 1); }); })["catch"](callback); } callback(err); } }
function createTransaction(dbInfo, mode, callback, retries) { if (retries === undefined) { retries = 1; } try { var tx = dbInfo.db.transaction(dbInfo.storeName, mode); callback(null, tx); } catch (err) { if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) { return Promise$1.resolve().then(function () { if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) { // increase the db version, to create the new ObjectStore if (dbInfo.db) { dbInfo.version = dbInfo.db.version + 1; } // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } }).then(function () { return _tryReconnect(dbInfo).then(function () { createTransaction(dbInfo, mode, callback, retries - 1); }); })["catch"](callback); } callback(err); } }
JavaScript
function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = createDbContext(); // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(self); // Replace the default `ready()` function with the specialized one. if (!self._initReady) { self._initReady = self.ready; self.ready = _fullyReady; } // Create an array of initialization states of the related localForages. var initPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise$1.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== self) { // Don't wait for itself... initPromises.push(forage._initReady()["catch"](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise$1.all(initPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k = 0; k < forages.length; k++) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); }
function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = createDbContext(); // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(self); // Replace the default `ready()` function with the specialized one. if (!self._initReady) { self._initReady = self.ready; self.ready = _fullyReady; } // Create an array of initialization states of the related localForages. var initPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise$1.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== self) { // Don't wait for itself... initPromises.push(forage._initReady()["catch"](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise$1.all(initPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k = 0; k < forages.length; k++) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); }
JavaScript
function iterate(iterator, callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { if (err) { return reject(err); } try { var store = transaction.objectStore(self._dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); // when the iterator callback returns any // (non-`undefined`) value, then we stop // the iteration immediately if (result !== void 0) { resolve(result); } else { cursor["continue"](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; } catch (e) { reject(e); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; }
function iterate(iterator, callback) { var self = this; var promise = new Promise$1(function (resolve, reject) { self.ready().then(function () { createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) { if (err) { return reject(err); } try { var store = transaction.objectStore(self._dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); // when the iterator callback returns any // (non-`undefined`) value, then we stop // the iteration immediately if (result !== void 0) { resolve(result); } else { cursor["continue"](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; } catch (e) { reject(e); } }); })["catch"](reject); }); executeCallback(promise, callback); return promise; }
JavaScript
function serialize(value, callback) { var valueType = ''; if (value) { valueType = toString$1.call(value); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueType === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueType === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueType === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueType === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueType === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueType === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueType === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueType === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueType === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueType === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } }
function serialize(value, callback) { var valueType = ''; if (value) { valueType = toString$1.call(value); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueType === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueType === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueType === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueType === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueType === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueType === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueType === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueType === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueType === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueType === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } }
JavaScript
function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } }
function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } }
JavaScript
function _initStorage$1(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise$1(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return reject(e); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { createDbTable(t, dbInfo, function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }, reject); }); dbInfo.serializer = localforageSerializer; return dbInfoPromise; }
function _initStorage$1(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise$1(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return reject(e); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { createDbTable(t, dbInfo, function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }, reject); }); dbInfo.serializer = localforageSerializer; return dbInfoPromise; }
JavaScript
function checkIfLocalStorageThrows() { var localStorageTestKey = '_localforage_support_test'; try { localStorage.setItem(localStorageTestKey, true); localStorage.removeItem(localStorageTestKey); return false; } catch (e) { return true; } }
function checkIfLocalStorageThrows() { var localStorageTestKey = '_localforage_support_test'; try { localStorage.setItem(localStorageTestKey, true); localStorage.removeItem(localStorageTestKey); return false; } catch (e) { return true; } }
JavaScript
function _initStorage$2(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig); if (!_isLocalStorageUsable()) { return Promise$1.reject(); } self._dbInfo = dbInfo; dbInfo.serializer = localforageSerializer; return Promise$1.resolve(); }
function _initStorage$2(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig); if (!_isLocalStorageUsable()) { return Promise$1.reject(); } self._dbInfo = dbInfo; dbInfo.serializer = localforageSerializer; return Promise$1.resolve(); }
JavaScript
function iterate$2(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; }
function iterate$2(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; }
JavaScript
function key$2(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; }
function key$2(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; }
JavaScript
function length$2(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; }
function length$2(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; }
JavaScript
function removeItem$2(key, callback) { var self = this; key = normalizeKey(key); var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; }
function removeItem$2(key, callback) { var self = this; key = normalizeKey(key); var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; }
JavaScript
function trapFocusForm() { modal = document.querySelector('#modal-form'); // select the modal by id firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal focusableContent = modal.querySelectorAll(focusableElements); lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal trapFocus(); }
function trapFocusForm() { modal = document.querySelector('#modal-form'); // select the modal by id firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal focusableContent = modal.querySelectorAll(focusableElements); lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal trapFocus(); }
JavaScript
function trapFocusSuccess() { modal = document.querySelector('#modal-success'); // select the modal by id firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal focusableContent = modal.querySelectorAll(focusableElements); lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal trapFocus(); }
function trapFocusSuccess() { modal = document.querySelector('#modal-success'); // select the modal by id firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal focusableContent = modal.querySelectorAll(focusableElements); lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal trapFocus(); }
JavaScript
function trapFocusLightbox() { modal = document.querySelector('#lightbox__container'); // select the modal by ID firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal focusableContent = modal.querySelectorAll(focusableElements); lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal trapFocus(); console.log(firstFocusableElement, focusableContent, lastFocusableElement); }
function trapFocusLightbox() { modal = document.querySelector('#lightbox__container'); // select the modal by ID firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal focusableContent = modal.querySelectorAll(focusableElements); lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal trapFocus(); console.log(firstFocusableElement, focusableContent, lastFocusableElement); }
JavaScript
function trapFocusDropdown() { modal = document.querySelector('#dropdown'); // select the modal by id firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal focusableContent = modal.querySelectorAll(focusableElements); lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal trapFocus(); }
function trapFocusDropdown() { modal = document.querySelector('#dropdown'); // select the modal by id firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal focusableContent = modal.querySelectorAll(focusableElements); lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal trapFocus(); }
JavaScript
function inspect(obj, showHidden, depth, colors) { var ctx = { showHidden: showHidden, seen: [], stylize: colors ? stylizeWithColor : stylizeNoColor }; return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); }
function inspect(obj, showHidden, depth, colors) { var ctx = { showHidden: showHidden, seen: [], stylize: colors ? stylizeWithColor : stylizeNoColor }; return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); }
JavaScript
sync() { // Await current sync status from the sync queue const syncStatus = this.gateway.syncQueue.get(this.id); if (syncStatus) return syncStatus; // If it's not currently synchronizing, create a new sync status for the sync queue const sync = this.gateway.provider.get(this.gateway.type, this.id).then(data => { if (data) { if (!this._existsInDB) this._existsInDB = true; this._patch(data); } else { this._existsInDB = false; } this.gateway.syncQueue.delete(this.id); return this; }); this.gateway.syncQueue.set(this.id, sync); return sync; }
sync() { // Await current sync status from the sync queue const syncStatus = this.gateway.syncQueue.get(this.id); if (syncStatus) return syncStatus; // If it's not currently synchronizing, create a new sync status for the sync queue const sync = this.gateway.provider.get(this.gateway.type, this.id).then(data => { if (data) { if (!this._existsInDB) this._existsInDB = true; this._patch(data); } else { this._existsInDB = false; } this.gateway.syncQueue.delete(this.id); return this; }); this.gateway.syncQueue.set(this.id, sync); return sync; }
JavaScript
async destroy() { if (this._existsInDB) { await this.gateway.provider.delete(this.gateway.type, this.id); if (this.client.listenerCount('configDeleteEntry')) this.client.emit('configDeleteEntry', this); } this.gateway.cache.delete(this.id); return this; }
async destroy() { if (this._existsInDB) { await this.gateway.provider.delete(this.gateway.type, this.id); if (this.client.listenerCount('configDeleteEntry')) this.client.emit('configDeleteEntry', this); } this.gateway.cache.delete(this.id); return this; }
JavaScript
sweepMessages(lifetime = this.options.messageCacheLifetime, commandLifetime = this.options.commandMessageLifetime) { if (typeof lifetime !== 'number' || isNaN(lifetime)) throw new TypeError('The lifetime must be a number.'); if (lifetime <= 0) { this.emit('debug', 'Didn\'t sweep messages - lifetime is unlimited'); return -1; } const lifetimeMs = lifetime * 1000; const commandLifetimeMs = commandLifetime * 1000; const now = Date.now(); let channels = 0; let messages = 0; let commandMessages = 0; for (const channel of this.channels.values()) { if (!channel.messages) continue; channels++; channel.messages.sweep(message => { if ((message.command || message.author === this.user) && now - (message.editedTimestamp || message.createdTimestamp) > commandLifetimeMs) return commandMessages++; if (!message.command && message.author !== this.user && now - (message.editedTimestamp || message.createdTimestamp) > lifetimeMs) return messages++; return false; }); } this.emit('debug', `Swept ${messages} messages older than ${lifetime} seconds and ${commandMessages} command messages older than ${commandLifetime} seconds in ${channels} text-based channels`); return messages; }
sweepMessages(lifetime = this.options.messageCacheLifetime, commandLifetime = this.options.commandMessageLifetime) { if (typeof lifetime !== 'number' || isNaN(lifetime)) throw new TypeError('The lifetime must be a number.'); if (lifetime <= 0) { this.emit('debug', 'Didn\'t sweep messages - lifetime is unlimited'); return -1; } const lifetimeMs = lifetime * 1000; const commandLifetimeMs = commandLifetime * 1000; const now = Date.now(); let channels = 0; let messages = 0; let commandMessages = 0; for (const channel of this.channels.values()) { if (!channel.messages) continue; channels++; channel.messages.sweep(message => { if ((message.command || message.author === this.user) && now - (message.editedTimestamp || message.createdTimestamp) > commandLifetimeMs) return commandMessages++; if (!message.command && message.author !== this.user && now - (message.editedTimestamp || message.createdTimestamp) > lifetimeMs) return messages++; return false; }); } this.emit('debug', `Swept ${messages} messages older than ${lifetime} seconds and ${commandMessages} command messages older than ${commandLifetime} seconds in ${channels} text-based channels`); return messages; }
JavaScript
function handleRateLimit(res, description, callback){ if(res.statusCode === 429) { logger.log('limit exceeded for '+description+'. Trying again after '+res.headers['retry-after']+'.5s.'); setTimeout(callback, res.headers['retry-after'] * 1000 + 500); return true; } else { return false; } }
function handleRateLimit(res, description, callback){ if(res.statusCode === 429) { logger.log('limit exceeded for '+description+'. Trying again after '+res.headers['retry-after']+'.5s.'); setTimeout(callback, res.headers['retry-after'] * 1000 + 500); return true; } else { return false; } }
JavaScript
function checkForRateLimit(res, description, callback){ return new Promise(resolve => { if(res.statusCode === 429) { logger.log('limit exceeded for '+description+'. Trying again after '+res.headers['retry-after']+'.5s.'); let timeout = new Promise(resolveTimeout => { setTimeout(() => resolveTimeout(), res.headers['retry-after'] * 1000 + 500); }); resolve(timeout.then(callback)) } else { resolve(); } }); }
function checkForRateLimit(res, description, callback){ return new Promise(resolve => { if(res.statusCode === 429) { logger.log('limit exceeded for '+description+'. Trying again after '+res.headers['retry-after']+'.5s.'); let timeout = new Promise(resolveTimeout => { setTimeout(() => resolveTimeout(), res.headers['retry-after'] * 1000 + 500); }); resolve(timeout.then(callback)) } else { resolve(); } }); }
JavaScript
async function swaggerToMarkdown(jsonUrl) { let i18n = loadI18n(); let response = await Docsify.get(jsonUrl, true); let swaggerJson = parse(response); let info = swaggerJson.info; let swaggerMarkdown = ""; if (info.title) { swaggerMarkdown += h1(info.title); } swaggerMarkdown += paragraph(`${info.description}\n`); if (info.version) { swaggerMarkdown += bullet(`Version: ${info.version}\n`); } if (info.license) { let license = info.license; swaggerMarkdown += bullet(`License: ${link(license.name, license.url)}\n`); } let markdownMap = new Map(); swaggerJson.tags.forEach(tag => { markdownMap.set(tag.name, `${h2(tag.name)}\n${paragraph(tag.description)}\n\n`); }); let apis = swaggerJson.apis; for (let index = 0; index < apis.length; index++) { let api = apis[index]; let tag = api.tag; let deprecated = api.deprecated; let markdown = markdownMap.get(tag); let summary = api.summary; if (deprecated) { summary = strikethrough(summary); } markdown += h3(summary) + bullet(`${monospace(api.method)} ${api.path}\n`); /* add requst parameters */ let request = api.request; markdown += h4(i18n.request); if (request.length == 0) { markdown += `${i18n.none}\n`; } else { let nestedParams = []; let tableData = []; for (let index = 0; index < request.length; index++) { let param = request[index]; tableData.push([ param.name, param.type, param.required, param.description ]); let refParam = param.refParam; if (refParam && refParam.length != 0) { nestedParams.push({ name: param.refType, ref: refParam }); } } markdown += table([i18n.name, i18n.type, i18n.required, i18n.description], tableData) + handleNestedParams(nestedParams); } /* add response parameters */ let response = api.response; markdown += h4(i18n.response); if (response.length == 0) { markdown += `${i18n.none}\n`; } else { let nestedParams = []; let tableData = []; for (let index = 0; index < response.length; index++) { let param = response[index]; tableData.push([ param.name, param.type, param.required, param.description ]); let refParam = param.refParam; if (refParam && refParam.length != 0) { nestedParams.push({ name: param.refType, ref: refParam }); } } markdown += table([i18n.name, i18n.type, i18n.required, i18n.description], tableData) + handleNestedParams(nestedParams); } markdownMap.set(tag, markdown); } for (let value of markdownMap.values()) { swaggerMarkdown += value; } return swaggerMarkdown; }
async function swaggerToMarkdown(jsonUrl) { let i18n = loadI18n(); let response = await Docsify.get(jsonUrl, true); let swaggerJson = parse(response); let info = swaggerJson.info; let swaggerMarkdown = ""; if (info.title) { swaggerMarkdown += h1(info.title); } swaggerMarkdown += paragraph(`${info.description}\n`); if (info.version) { swaggerMarkdown += bullet(`Version: ${info.version}\n`); } if (info.license) { let license = info.license; swaggerMarkdown += bullet(`License: ${link(license.name, license.url)}\n`); } let markdownMap = new Map(); swaggerJson.tags.forEach(tag => { markdownMap.set(tag.name, `${h2(tag.name)}\n${paragraph(tag.description)}\n\n`); }); let apis = swaggerJson.apis; for (let index = 0; index < apis.length; index++) { let api = apis[index]; let tag = api.tag; let deprecated = api.deprecated; let markdown = markdownMap.get(tag); let summary = api.summary; if (deprecated) { summary = strikethrough(summary); } markdown += h3(summary) + bullet(`${monospace(api.method)} ${api.path}\n`); /* add requst parameters */ let request = api.request; markdown += h4(i18n.request); if (request.length == 0) { markdown += `${i18n.none}\n`; } else { let nestedParams = []; let tableData = []; for (let index = 0; index < request.length; index++) { let param = request[index]; tableData.push([ param.name, param.type, param.required, param.description ]); let refParam = param.refParam; if (refParam && refParam.length != 0) { nestedParams.push({ name: param.refType, ref: refParam }); } } markdown += table([i18n.name, i18n.type, i18n.required, i18n.description], tableData) + handleNestedParams(nestedParams); } /* add response parameters */ let response = api.response; markdown += h4(i18n.response); if (response.length == 0) { markdown += `${i18n.none}\n`; } else { let nestedParams = []; let tableData = []; for (let index = 0; index < response.length; index++) { let param = response[index]; tableData.push([ param.name, param.type, param.required, param.description ]); let refParam = param.refParam; if (refParam && refParam.length != 0) { nestedParams.push({ name: param.refType, ref: refParam }); } } markdown += table([i18n.name, i18n.type, i18n.required, i18n.description], tableData) + handleNestedParams(nestedParams); } markdownMap.set(tag, markdown); } for (let value of markdownMap.values()) { swaggerMarkdown += value; } return swaggerMarkdown; }
JavaScript
function linkedList(data, start, end, dim, clockwise) { var i, last; if (clockwise === signedArea(data, start, end, dim) > 0) { for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); } else { for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); } if (last && equals(last, last.next)) { removeNode(last); last = last.next; } return last; }
function linkedList(data, start, end, dim, clockwise) { var i, last; if (clockwise === signedArea(data, start, end, dim) > 0) { for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); } else { for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); } if (last && equals(last, last.next)) { removeNode(last); last = last.next; } return last; }
JavaScript
function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { if (!ear) return; // interlink polygon nodes in z-order if (!pass && invSize) indexCurve(ear, minX, minY, invSize); var stop = ear, prev, next; // iterate through ears, slicing them one by one while (ear.prev !== ear.next) { prev = ear.prev; next = ear.next; if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { // cut off the triangle triangles.push(prev.i / dim); triangles.push(ear.i / dim); triangles.push(next.i / dim); removeNode(ear); // skipping the next vertice leads to less sliver triangles ear = next.next; stop = next.next; continue; } ear = next; // if we looped through the whole remaining polygon and can't find any more ears if (ear === stop) { // try filtering points and slicing again if (!pass) { earcutLinked( filterPoints(ear), triangles, dim, minX, minY, invSize, 1 ); // if this didn't work, try curing all small self-intersections locally } else if (pass === 1) { ear = cureLocalIntersections(ear, triangles, dim); earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two } else if (pass === 2) { splitEarcut(ear, triangles, dim, minX, minY, invSize); } break; } } }
function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { if (!ear) return; // interlink polygon nodes in z-order if (!pass && invSize) indexCurve(ear, minX, minY, invSize); var stop = ear, prev, next; // iterate through ears, slicing them one by one while (ear.prev !== ear.next) { prev = ear.prev; next = ear.next; if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { // cut off the triangle triangles.push(prev.i / dim); triangles.push(ear.i / dim); triangles.push(next.i / dim); removeNode(ear); // skipping the next vertice leads to less sliver triangles ear = next.next; stop = next.next; continue; } ear = next; // if we looped through the whole remaining polygon and can't find any more ears if (ear === stop) { // try filtering points and slicing again if (!pass) { earcutLinked( filterPoints(ear), triangles, dim, minX, minY, invSize, 1 ); // if this didn't work, try curing all small self-intersections locally } else if (pass === 1) { ear = cureLocalIntersections(ear, triangles, dim); earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two } else if (pass === 2) { splitEarcut(ear, triangles, dim, minX, minY, invSize); } break; } } }
JavaScript
function isEar(ear) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; // reflex, can't be an ear // now make sure we don't have other points inside the potential ear var p = ear.next.next; while (p !== ear.prev) { if ( pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0 ) return false; p = p.next; } return true; }
function isEar(ear) { var a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; // reflex, can't be an ear // now make sure we don't have other points inside the potential ear var p = ear.next.next; while (p !== ear.prev) { if ( pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0 ) return false; p = p.next; } return true; }
JavaScript
function cureLocalIntersections(start, triangles, dim) { var p = start; do { var a = p.prev, b = p.next.next; if ( !equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a) ) { triangles.push(a.i / dim); triangles.push(p.i / dim); triangles.push(b.i / dim); // remove two nodes involved removeNode(p); removeNode(p.next); p = start = b; } p = p.next; } while (p !== start); return p; }
function cureLocalIntersections(start, triangles, dim) { var p = start; do { var a = p.prev, b = p.next.next; if ( !equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a) ) { triangles.push(a.i / dim); triangles.push(p.i / dim); triangles.push(b.i / dim); // remove two nodes involved removeNode(p); removeNode(p.next); p = start = b; } p = p.next; } while (p !== start); return p; }
JavaScript
function eliminateHoles(data, holeIndices, outerNode, dim) { var queue = [], i, len, start, end, list; for (i = 0, len = holeIndices.length; i < len; i++) { start = holeIndices[i] * dim; end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; list = linkedList(data, start, end, dim, false); if (list === list.next) list.steiner = true; queue.push(getLeftmost(list)); } queue.sort(compareX); // process holes from left to right for (i = 0; i < queue.length; i++) { eliminateHole(queue[i], outerNode); outerNode = filterPoints(outerNode, outerNode.next); } return outerNode; }
function eliminateHoles(data, holeIndices, outerNode, dim) { var queue = [], i, len, start, end, list; for (i = 0, len = holeIndices.length; i < len; i++) { start = holeIndices[i] * dim; end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; list = linkedList(data, start, end, dim, false); if (list === list.next) list.steiner = true; queue.push(getLeftmost(list)); } queue.sort(compareX); // process holes from left to right for (i = 0; i < queue.length; i++) { eliminateHole(queue[i], outerNode); outerNode = filterPoints(outerNode, outerNode.next); } return outerNode; }
JavaScript
function findHoleBridge(hole, outerNode) { var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m; // find a segment intersected by a ray from the hole's leftmost point to the left; // segment's endpoint with lesser x will be potential connection point do { if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { var x = p.x + ((hy - p.y) * (p.next.x - p.x)) / (p.next.y - p.y); if (x <= hx && x > qx) { qx = x; if (x === hx) { if (hy === p.y) return p; if (hy === p.next.y) return p.next; } m = p.x < p.next.x ? p : p.next; } } p = p.next; } while (p !== outerNode); if (!m) return null; if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint // look for points inside the triangle of hole point, segment intersection and endpoint; // if there are no points found, we have a valid connection; // otherwise choose the point of the minimum angle with the ray as connection point var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan; p = m.next; while (p !== stop) { if ( hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { tan = Math.abs(hy - p.y) / (hx - p.x); // tangential if ( (tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole) ) { m = p; tanMin = tan; } } p = p.next; } return m; }
function findHoleBridge(hole, outerNode) { var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m; // find a segment intersected by a ray from the hole's leftmost point to the left; // segment's endpoint with lesser x will be potential connection point do { if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { var x = p.x + ((hy - p.y) * (p.next.x - p.x)) / (p.next.y - p.y); if (x <= hx && x > qx) { qx = x; if (x === hx) { if (hy === p.y) return p; if (hy === p.next.y) return p.next; } m = p.x < p.next.x ? p : p.next; } } p = p.next; } while (p !== outerNode); if (!m) return null; if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint // look for points inside the triangle of hole point, segment intersection and endpoint; // if there are no points found, we have a valid connection; // otherwise choose the point of the minimum angle with the ray as connection point var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan; p = m.next; while (p !== stop) { if ( hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { tan = Math.abs(hy - p.y) / (hx - p.x); // tangential if ( (tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole) ) { m = p; tanMin = tan; } } p = p.next; } return m; }
JavaScript
function zOrder(x, y, minX, minY, invSize) { // coords are transformed into non-negative 15-bit integer range x = 32767 * (x - minX) * invSize; y = 32767 * (y - minY) * invSize; x = (x | (x << 8)) & 0x00ff00ff; x = (x | (x << 4)) & 0x0f0f0f0f; x = (x | (x << 2)) & 0x33333333; x = (x | (x << 1)) & 0x55555555; y = (y | (y << 8)) & 0x00ff00ff; y = (y | (y << 4)) & 0x0f0f0f0f; y = (y | (y << 2)) & 0x33333333; y = (y | (y << 1)) & 0x55555555; return x | (y << 1); }
function zOrder(x, y, minX, minY, invSize) { // coords are transformed into non-negative 15-bit integer range x = 32767 * (x - minX) * invSize; y = 32767 * (y - minY) * invSize; x = (x | (x << 8)) & 0x00ff00ff; x = (x | (x << 4)) & 0x0f0f0f0f; x = (x | (x << 2)) & 0x33333333; x = (x | (x << 1)) & 0x55555555; y = (y | (y << 8)) & 0x00ff00ff; y = (y | (y << 4)) & 0x0f0f0f0f; y = (y | (y << 2)) & 0x33333333; y = (y | (y << 1)) & 0x55555555; return x | (y << 1); }
JavaScript
function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { return ( (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0 ); }
function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { return ( (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0 ); }
JavaScript
function isValidDiagonal(a, b) { return ( a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) ); }
function isValidDiagonal(a, b) { return ( a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) ); }
JavaScript
function intersectsPolygon(a, b) { var p = a; do { if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b) ) return true; p = p.next; } while (p !== a); return false; }
function intersectsPolygon(a, b) { var p = a; do { if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b) ) return true; p = p.next; } while (p !== a); return false; }
JavaScript
function middleInside(a, b) { var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2; do { if ( p.y > py !== p.next.y > py && p.next.y !== p.y && px < ((p.next.x - p.x) * (py - p.y)) / (p.next.y - p.y) + p.x ) inside = !inside; p = p.next; } while (p !== a); return inside; }
function middleInside(a, b) { var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2; do { if ( p.y > py !== p.next.y > py && p.next.y !== p.y && px < ((p.next.x - p.x) * (py - p.y)) / (p.next.y - p.y) + p.x ) inside = !inside; p = p.next; } while (p !== a); return inside; }
JavaScript
function processScrollEvents() { //the low scroll sensitivity functions need not be triggered so many more number of times if(readyToScroll == true) { readyToScroll = false; forEach(onScrollFunctions,function(callback){ callback(); }); setTimeout(function(){ readyToScroll = true; },scrollCooldownTime) } //the high sensitivity functions are to be triggered every scroll event forEach(onScrollFunctionsHighSensitivity,function(callback){ callback(); }); }
function processScrollEvents() { //the low scroll sensitivity functions need not be triggered so many more number of times if(readyToScroll == true) { readyToScroll = false; forEach(onScrollFunctions,function(callback){ callback(); }); setTimeout(function(){ readyToScroll = true; },scrollCooldownTime) } //the high sensitivity functions are to be triggered every scroll event forEach(onScrollFunctionsHighSensitivity,function(callback){ callback(); }); }
JavaScript
save(msg, hash, certificate, done) { const chat = new Chat({ certificateSubject: certificate, certificateAuthor: null, messageHash: hash, message: msg }); chat.save() .then((reply) => { let resource = new Resource({ created: !chat.isNew, data: reply._doc }, req.url); let str = req.url; if (str.substr(-1) != '/') str += '/'; str += chat._id; resource.link(chat._id, str); res.send(resource); }) .catch(err => { console.log('can not create chat. ', err); res.status(200); res.send(new Hal.Resource({ message: 'can not create chat.', errors: err }, req.url)); }); done((true)); }
save(msg, hash, certificate, done) { const chat = new Chat({ certificateSubject: certificate, certificateAuthor: null, messageHash: hash, message: msg }); chat.save() .then((reply) => { let resource = new Resource({ created: !chat.isNew, data: reply._doc }, req.url); let str = req.url; if (str.substr(-1) != '/') str += '/'; str += chat._id; resource.link(chat._id, str); res.send(resource); }) .catch(err => { console.log('can not create chat. ', err); res.status(200); res.send(new Hal.Resource({ message: 'can not create chat.', errors: err }, req.url)); }); done((true)); }
JavaScript
function initializePageAction(tab) { if (protocolIsApplicable(tab.url)) { browser.pageAction.setIcon({tabId: tab.id, path: "icons/page-16.png"}); browser.pageAction.setTitle({tabId: tab.id, title: browser.i18n.getMessage("pageAction")}); browser.pageAction.show(tab.id); } }
function initializePageAction(tab) { if (protocolIsApplicable(tab.url)) { browser.pageAction.setIcon({tabId: tab.id, path: "icons/page-16.png"}); browser.pageAction.setTitle({tabId: tab.id, title: browser.i18n.getMessage("pageAction")}); browser.pageAction.show(tab.id); } }
JavaScript
function onContextMenuItemCreated() { if (browser.runtime.lastError) { console.log(`Error: ${browser.runtime.lastError}`); } else { console.log("Item created successfully"); } }
function onContextMenuItemCreated() { if (browser.runtime.lastError) { console.log(`Error: ${browser.runtime.lastError}`); } else { console.log("Item created successfully"); } }
JavaScript
function radioButtonChecker() { if ($('.had-outside').is(":checked")) { $('#education-outside-us').show(); $('#education-outside-us :input').attr('required', true); totalRequiredFields = $('.required-marker').length; } else { $('#education-outside-us').hide(); $('#education-outside-us :input').removeAttr('required'); totalRequiredFields = $('.required-marker:visible').length; } }
function radioButtonChecker() { if ($('.had-outside').is(":checked")) { $('#education-outside-us').show(); $('#education-outside-us :input').attr('required', true); totalRequiredFields = $('.required-marker').length; } else { $('#education-outside-us').hide(); $('#education-outside-us :input').removeAttr('required'); totalRequiredFields = $('.required-marker:visible').length; } }
JavaScript
function addToHighSchoolList(highSchool) { if (highSchool.isLastAttended == "True") { highSchoolList.unshift(highSchool); $('input[name="SchoolInfo.LastYearAttended"]').val(highSchool.year); } else { highSchoolList.push(highSchool); } }
function addToHighSchoolList(highSchool) { if (highSchool.isLastAttended == "True") { highSchoolList.unshift(highSchool); $('input[name="SchoolInfo.LastYearAttended"]').val(highSchool.year); } else { highSchoolList.push(highSchool); } }
JavaScript
function RemoveBottomNavBarForIE(){ if ((C.ie)&&(document.getElementById('Reading') != null)){ if (document.getElementById('BottomNavBar') != null){ document.getElementById('TheBody').removeChild(document.getElementById('BottomNavBar')); } } }
function RemoveBottomNavBarForIE(){ if ((C.ie)&&(document.getElementById('Reading') != null)){ if (document.getElementById('BottomNavBar') != null){ document.getElementById('TheBody').removeChild(document.getElementById('BottomNavBar')); } } }
JavaScript
function Finish(){ //If there's a form, fill it out and submit it if (document.store != null){ Frm = document.store; Frm.starttime.value = HPNStartTime; Frm.endtime.value = (new Date()).getTime(); Frm.mark.value = Score; Frm.detail.value = Detail; Frm.submit(); } }
function Finish(){ //If there's a form, fill it out and submit it if (document.store != null){ Frm = document.store; Frm.starttime.value = HPNStartTime; Frm.endtime.value = (new Date()).getTime(); Frm.mark.value = Score; Frm.detail.value = Detail; Frm.submit(); } }
JavaScript
function findAPI(win) { while ((win.API == null) && (win.parent != null) && (win.parent != win)) { win = win.parent; } API = win.API; }
function findAPI(win) { while ((win.API == null) && (win.parent != null) && (win.parent != win)) { win = win.parent; } API = win.API; }
JavaScript
function ScormStartUp(){ initAPI(window); if (API != null){ API.LMSInitialize(''); API.LMSSetValue('cmi.core.lesson_status', 'browsed'); API.LMSSetValue('cmi.core.score.min', 0); API.LMSSetValue('cmi.core.score.max', 100); API.LMSCommit(''); } }
function ScormStartUp(){ initAPI(window); if (API != null){ API.LMSInitialize(''); API.LMSSetValue('cmi.core.lesson_status', 'browsed'); API.LMSSetValue('cmi.core.score.min', 0); API.LMSSetValue('cmi.core.score.max', 100); API.LMSCommit(''); } }
JavaScript
function SetScormScore(){ //Reports the current score and any other information back to the LMS if (API != null){ API.LMSSetValue('cmi.core.score.raw', Score); //Now send detailed reports about each item for (var i=0; i<State.length; i++){ if (State[i] != null){ var ItemLabel = 'Item_' + (i+1).toString(); var ThisItemScore = ''; var ThisItemStatus = ''; API.LMSSetValue('cmi.objectives.' + i + '.id', 'obj'+ItemLabel); API.LMSSetValue('cmi.interactions.' + i + '.id', 'int'+ItemLabel); API.LMSSetValue('cmi.objectives.' + i + '.score.min', '0'); API.LMSSetValue('cmi.objectives.' + i + '.score.max', '100'); if (State[i][2] > 0){ ThisItemScore = Math.floor(State[i][0] * 100) + ''; ThisItemStatus = 'completed'; } else{ ThisItemScore = '0'; ThisItemStatus = 'incomplete'; } API.LMSSetValue('cmi.objectives.' + i + '.score.raw', ThisItemScore); API.LMSSetValue('cmi.objectives.' + i + '.status', ThisItemStatus); API.LMSSetValue('cmi.interactions.' + i + '.weighting', I[i][0]); //We can only use the performance type, because we're storing multiple responses of various types. API.LMSSetValue('cmi.interactions.' + i + '.type', 'performance'); API.LMSSetValue('cmi.interactions.' + i + '.student_response', State[i][5]); } } API.LMSCommit(''); } }
function SetScormScore(){ //Reports the current score and any other information back to the LMS if (API != null){ API.LMSSetValue('cmi.core.score.raw', Score); //Now send detailed reports about each item for (var i=0; i<State.length; i++){ if (State[i] != null){ var ItemLabel = 'Item_' + (i+1).toString(); var ThisItemScore = ''; var ThisItemStatus = ''; API.LMSSetValue('cmi.objectives.' + i + '.id', 'obj'+ItemLabel); API.LMSSetValue('cmi.interactions.' + i + '.id', 'int'+ItemLabel); API.LMSSetValue('cmi.objectives.' + i + '.score.min', '0'); API.LMSSetValue('cmi.objectives.' + i + '.score.max', '100'); if (State[i][2] > 0){ ThisItemScore = Math.floor(State[i][0] * 100) + ''; ThisItemStatus = 'completed'; } else{ ThisItemScore = '0'; ThisItemStatus = 'incomplete'; } API.LMSSetValue('cmi.objectives.' + i + '.score.raw', ThisItemScore); API.LMSSetValue('cmi.objectives.' + i + '.status', ThisItemStatus); API.LMSSetValue('cmi.interactions.' + i + '.weighting', I[i][0]); //We can only use the performance type, because we're storing multiple responses of various types. API.LMSSetValue('cmi.interactions.' + i + '.type', 'performance'); API.LMSSetValue('cmi.interactions.' + i + '.student_response', State[i][5]); } } API.LMSCommit(''); } }
JavaScript
function displayData(data) { // create a new tab chrome.tabs.create({ url: "bootstrap/index.html" }, function(tab) { // wait for new tab page to load setTimeout(function () { // send the data to the new tab chrome.tabs.sendMessage(tab.id, { "action": "display", "data": data }); }, 100); }); }
function displayData(data) { // create a new tab chrome.tabs.create({ url: "bootstrap/index.html" }, function(tab) { // wait for new tab page to load setTimeout(function () { // send the data to the new tab chrome.tabs.sendMessage(tab.id, { "action": "display", "data": data }); }, 100); }); }
JavaScript
function initClientRendered(componentDefs, doc) { // Ensure that event handlers to handle delegating events are // always attached before initializing any components eventDelegation.___init(doc); doc = doc || defaultDocument; for (var i = componentDefs.length - 1; i >= 0; i--) { var componentDef = componentDefs[i]; initComponent(componentDef, doc); } }
function initClientRendered(componentDefs, doc) { // Ensure that event handlers to handle delegating events are // always attached before initializing any components eventDelegation.___init(doc); doc = doc || defaultDocument; for (var i = componentDefs.length - 1; i >= 0; i--) { var componentDef = componentDefs[i]; initComponent(componentDef, doc); } }
JavaScript
error(key, message) { this[key] = this[key] || new Field(); this[key].errorMessage = message; return this; }
error(key, message) { this[key] = this[key] || new Field(); this[key].errorMessage = message; return this; }
JavaScript
merge(other = new Context()) { Context.fields(other).forEach(({ key, field }) => { this[key] = field; }); return this; }
merge(other = new Context()) { Context.fields(other).forEach(({ key, field }) => { this[key] = field; }); return this; }
JavaScript
withValues(values = {}) { Object.keys(values).forEach(key => { this[key] = this[key] || new Field(); this[key].value = values[key]; }); return this; }
withValues(values = {}) { Object.keys(values).forEach(key => { this[key] = this[key] || new Field(); this[key].value = values[key]; }); return this; }
JavaScript
values() { const values = {}; Context.fields(this) .filter(({ field }) => isString(field.value) || isArray(field.value)) .forEach(({ key, field }) => { values[key] = field.value; }); return values; }
values() { const values = {}; Context.fields(this) .filter(({ field }) => isString(field.value) || isArray(field.value)) .forEach(({ key, field }) => { values[key] = field.value; }); return values; }
JavaScript
withErrors(errors = []) { if (!isArray(errors)) return this; errors.forEach(error => { const { param, msg, value } = error; this[param] = this[param] || new Field(); this[param].errorMessage = msg; this[param].value = value || this[param].value; }); return this; }
withErrors(errors = []) { if (!isArray(errors)) return this; errors.forEach(error => { const { param, msg, value } = error; this[param] = this[param] || new Field(); this[param].errorMessage = msg; this[param].value = value || this[param].value; }); return this; }
JavaScript
errors() { return Context.fields(this) .filter(({ field }) => field.error) .map(({ key, field }) => { return { param: key, msg: field.errorMessage, value: field.value }; }); }
errors() { return Context.fields(this) .filter(({ field }) => field.error) .map(({ key, field }) => { return { param: key, msg: field.errorMessage, value: field.value }; }); }