code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
jsonp({"cep":"54530010","logradouro":"Rua da Aurora","bairro":"S\u00e3o Francisco","cidade":"Cabo de Santo Agostinho","uf":"PE","estado":"Pernambuco"});
lfreneda/cepdb
api/v1/54530010.jsonp.js
JavaScript
cc0-1.0
153
jsonp({"cep":"69905602","logradouro":"Travessa Natanael Albuquerque","bairro":"Seis de Agosto","cidade":"Rio Branco","uf":"AC","estado":"Acre"});
lfreneda/cepdb
api/v1/69905602.jsonp.js
JavaScript
cc0-1.0
146
jsonp({"cep":"30730230","logradouro":"Rua Padre N\u00f3brega","bairro":"Minas Brasil","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/30730230.jsonp.js
JavaScript
cc0-1.0
149
jsonp({"cep":"26299201","logradouro":"Estrada Cabenga","bairro":"Prados Verdes","cidade":"Nova Igua\u00e7u","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/26299201.jsonp.js
JavaScript
cc0-1.0
147
jsonp({"cep":"25960003","logradouro":"Avenida Oliveira Botelho","bairro":"Alto","cidade":"Teres\u00f3polis","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/25960003.jsonp.js
JavaScript
cc0-1.0
147
jsonp({"cep":"11710230","logradouro":"Rua Turmalina","bairro":"Cidade da Crian\u00e7a","cidade":"Praia Grande","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/11710230.jsonp.js
JavaScript
cc0-1.0
150
jsonp({"cep":"14883310","logradouro":"Travessa Pedro Dias Brochieri","bairro":"Jardim Nova Aparecida","cidade":"Jaboticabal","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/14883310.jsonp.js
JavaScript
cc0-1.0
164
import {inject, customElement, bindable} from 'aurelia-framework'; import mapsapi from 'google-maps-api'; @customElement('place-picker') // Get an API key from https://developers.google.com/maps/documentation/javascript/get-api-key. @inject(Element, mapsapi('AIzaSyA1QmM_IG94DN0kCl7l1dblf4C8vRiuxus', ['places'])) export class PlacePicker { @bindable location; constructor(element, mapsApi) { this.element = element; this.mapsApi = mapsApi; } attached() { // This loads the Google Maps API asynchronously. this.mapsApi.then(maps => { // Now that it's loaded, add a map to our HTML. var mapContainer = this.element.querySelector('.place-picker-map'); var map = new maps.Map(mapContainer, { center: {lat: -33.8688, lng: 151.2195}, zoom: 13 }); // Also convert our input field into a place autocomplete field. var input = this.element.querySelector('input'); var autocomplete = new google.maps.places.Autocomplete(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); autocomplete.bindTo('bounds', map); // Create a marker that will show where the selected place is. var marker = new google.maps.Marker({ map: map, anchorPoint: new google.maps.Point(0, -29) }); // Create a lambda that moves the marker and the map viewport. let updateMarker = () => { var position = new google.maps.LatLng(this.location.lat, this.location.lng); map.setCenter(position); marker.setPosition(position); marker.setVisible(true); }; // Ensure that the current location is shown properly. updateMarker(); // Update the location and its marker every time a new place is selected. autocomplete.addListener('place_changed', () => { marker.setVisible(false); var place = autocomplete.getPlace(); if (place.geometry) { this.location.name = place.name; this.location.lat = place.geometry.location.lat(); this.location.lng = place.geometry.location.lng(); updateMarker(); } }); }); } }
ne0guille/skeleton-navigation
skeleton-esnext/src/place-picker.js
JavaScript
cc0-1.0
2,167
jsonp({"cep":"88354652","logradouro":"Rua JM - 008","bairro":"Jardim Maluche","cidade":"Brusque","uf":"SC","estado":"Santa Catarina"});
lfreneda/cepdb
api/v1/88354652.jsonp.js
JavaScript
cc0-1.0
136
jsonp({"cep":"30431177","logradouro":"Rua Oscar Trompowsky","bairro":"Graja\u00fa","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/30431177.jsonp.js
JavaScript
cc0-1.0
146
jsonp({"cep":"06703790","logradouro":"Rua Gagliari","bairro":"Jardim Rio das Pedras","cidade":"Cotia","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/06703790.jsonp.js
JavaScript
cc0-1.0
141
jsonp({"cep":"99030320","logradouro":"Rua Arthur Canfield","bairro":"Boqueir\u00e3o","cidade":"Passo Fundo","uf":"RS","estado":"Rio Grande do Sul"});
lfreneda/cepdb
api/v1/99030320.jsonp.js
JavaScript
cc0-1.0
150
jsonp({"cep":"08030560","logradouro":"Rua Alice Dilon Braga","bairro":"Vila Curu\u00e7\u00e1","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/08030560.jsonp.js
JavaScript
cc0-1.0
159
jsonp({"cep":"24924485","logradouro":"Avenida P","bairro":"Jacon\u00e9 (Ponta Negra)","cidade":"Maric\u00e1","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/24924485.jsonp.js
JavaScript
cc0-1.0
148
jsonp({"cep":"13041800","logradouro":"Rua It\u00e1polis","bairro":"Vila Hor\u00e1cio Tulli","cidade":"Campinas","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/13041800.jsonp.js
JavaScript
cc0-1.0
151
jsonp({"cep":"13800543","logradouro":"Rua Benedito Vaz","bairro":"Jardim Calif\u00f3rnia","cidade":"Mogi Mirim","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/13800543.jsonp.js
JavaScript
cc0-1.0
151
jsonp({"cep":"91750030","logradouro":"Beco A","bairro":"Aberta dos Morros","cidade":"Porto Alegre","uf":"RS","estado":"Rio Grande do Sul"});
lfreneda/cepdb
api/v1/91750030.jsonp.js
JavaScript
cc0-1.0
141
jsonp({"cep":"38060450","logradouro":"Rua Aulo Pires de Almeida","bairro":"Merc\u00eas","cidade":"Uberaba","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/38060450.jsonp.js
JavaScript
cc0-1.0
144
(function () { 'use strict'; angular .module('tierraDeColoresApp') .service('fiscalService', fiscalService); fiscalService.$inject = ['$q', '$http', 'cookieService', 'BaseURL', 'toaster', '$rootScope']; function fiscalService($q, $http, cookieService, BaseURL, toaster, $rootScope) { const exec = require('child_process').exec; const http = require('http'); const fs = require('fs'); const path = require('path'); var parser = document.createElement('a'); parser.href = BaseURL; var Auth = { 'usuario': 'AFIP_SMH/P-441F', 'password': 'T13RR4$7j15vker4L-L' }; this.read = function () { var datosRecu = null; var deferred = $q.defer(); var filePath = path.join(__dirname, 'FILE.ans'); fs.readFile(filePath, {encoding: 'utf-8'}, function (err, data) { if (!err) { datosRecu = data; deferred.resolve(datosRecu); } }); return deferred.promise; }; function print(tipo) { exec('wspooler.exe -p4 -l -f FILE.200', function (err, stdout, stderr) { if (err !== null) { console.log(err); $rootScope.$broadcast("printState", {tipo: tipo, status: false}); } else { $rootScope.$broadcast("printState", {tipo: tipo, status: true}); } }); } this.cleanFiles = function () { fs.unlink('FILE.200', function (err) { if (err) { console.log(err); } console.log('successfully deleted FILE.200'); }); fs.unlink('FILE.ans', function (err) { if (err) { console.log(err); } console.log('successfully deleted FILE.ans'); }); return true; }; this.factura_aOrFactura_b = function (factura, cliente, type) { var options = null; var token = cookieService.get('token'); var tipo; token.then(function (data) { options = { host: parser.hostname, port: parser.port, method: 'POST', headers: { 'Authorization': 'Bearer ' + data } }; if (type === 0) { options.path = '/fiscal/factura_a?factura=' + factura + "&cliente=" + cliente; tipo = "Factura A"; } else if (1) { options.path = '/fiscal/factura_b?factura=' + factura + "&cliente=" + cliente; tipo = "Factura B"; } var files = fs.createWriteStream("FILE.200"); var request = http.get(options, function (response) { if (response.statusCode === 200) { response.pipe(files); print(tipo); } }); }); }; this.ticketOrRegalo = function (factura, serial) { var token = cookieService.get('token'); var type; token.then(function (data) { var options = { host: parser.hostname, port: parser.port, method: 'POST', headers: { 'Authorization': 'Bearer ' + data } }; if (serial !== null & typeof serial !== 'undefined') { options.path = '/fiscal/regalo?factura=' + factura + "&serial=" + serial; type = "Regalo"; } else { options.path = '/fiscal/ticket?factura=' + factura; } var files = fs.createWriteStream("FILE.200"); var request = http.get(options, function (response) { if (response.statusCode === 200) { response.pipe(files); print(); } }); }); }; this.comprobanteZ = function () { var deferred = $q.defer(); const exec = require('child_process').exec; exec('wspooler.exe -p4 -l -f compZ.200', (err, stdout, stderr) => { if (err !== null) { deferred.resolve(false); console.log(err); console.log(stderr); console.log(stdout); } else { deferred.resolve(true); } }); return deferred.promise; }; this.isConnected = function () { var deferred = $q.defer(); const exec = require('child_process').exec; exec('wspooler.exe -p4 -l -f CONNECTED.200', (err, stdout, stderr) => { if (err !== null) { deferred.resolve(false); console.log(err); console.log(stderr); console.log(stdout); } else { deferred.resolve(true); } }); return deferred.promise; }; } })();
CosmicaJujuy/TierraDesktop
scripts/angular/service/FiscalService.js
JavaScript
cc0-1.0
5,523
jsonp({"cep":"89812639","logradouro":"Rua Igarassu - D","bairro":"Santa Maria","cidade":"Chapec\u00f3","uf":"SC","estado":"Santa Catarina"});
lfreneda/cepdb
api/v1/89812639.jsonp.js
JavaScript
cc0-1.0
142
jsonp({"cep":"54470240","logradouro":"Rua Serra Negra","bairro":"Barra de Jangada","cidade":"Jaboat\u00e3o dos Guararapes","uf":"PE","estado":"Pernambuco"});
lfreneda/cepdb
api/v1/54470240.jsonp.js
JavaScript
cc0-1.0
158
jsonp({"cep":"60183080","logradouro":"Travessa Leme","bairro":"Vicente Pinzon","cidade":"Fortaleza","uf":"CE","estado":"Cear\u00e1"});
lfreneda/cepdb
api/v1/60183080.jsonp.js
JavaScript
cc0-1.0
135
jsonp({"cep":"42802300","logradouro":"Caminho C-8","bairro":"Pia\u00e7aveira","cidade":"Cama\u00e7ari","uf":"BA","estado":"Bahia"});
lfreneda/cepdb
api/v1/42802300.jsonp.js
JavaScript
cc0-1.0
133
/**! * LibreMoney DgsListing api 0.2 * Copyright (c) LibreMoney Team <[email protected]> * CC0 license */ /* import nxt.Account; import nxt.Attachment; import nxt.Constants; import nxt.NxtException; import nxt.util.Convert; import org.json.simple.JSONStreamAware; import static nxt.http.JSONResponses.INCORRECT_DGS_LISTING_DESCRIPTION; import static nxt.http.JSONResponses.INCORRECT_DGS_LISTING_NAME; import static nxt.http.JSONResponses.INCORRECT_DGS_LISTING_TAGS; import static nxt.http.JSONResponses.MISSING_NAME; */ //super(new APITag[] {APITag.DGS, APITag.CREATE_TRANSACTION}, "name", "description", "tags", "quantity", "priceNQT"); function DgsListing(req, res) { res.send('This is not implemented'); /* String name = Convert.emptyToNull(req.getParameter("name")); String description = Convert.nullToEmpty(req.getParameter("description")); String tags = Convert.nullToEmpty(req.getParameter("tags")); long priceNQT = ParameterParser.getPriceNQT(req); int quantity = ParameterParser.getGoodsQuantity(req); if (name == null) { return MISSING_NAME; } name = name.trim(); if (name.length() > Constants.MAX_DGS_LISTING_NAME_LENGTH) { return INCORRECT_DGS_LISTING_NAME; } if (description.length() > Constants.MAX_DGS_LISTING_DESCRIPTION_LENGTH) { return INCORRECT_DGS_LISTING_DESCRIPTION; } if (tags.length() > Constants.MAX_DGS_LISTING_TAGS_LENGTH) { return INCORRECT_DGS_LISTING_TAGS; } Account account = ParameterParser.getSenderAccount(req); Attachment attachment = new Attachment.DigitalGoodsListing(name, description, tags, quantity, priceNQT); return createTransaction(req, account, attachment); */ } module.exports = DgsListing;
libremoney/main
Lm/Modules/DigitalGoods/Api/DgsListing.js
JavaScript
cc0-1.0
1,680
jsonp({"cep":"78559272","logradouro":"Rua Dois","bairro":"Vila It\u00e1lia","cidade":"Sinop","uf":"MT","estado":"Mato Grosso"});
lfreneda/cepdb
api/v1/78559272.jsonp.js
JavaScript
cc0-1.0
129
import Timeouts from 'platform/testing/e2e/timeouts'; class Confirmation { validatePageLoaded = () => { cy.get('h1', { timeout: Timeouts.slow }) .should('be.visible') .and('have.text', 'You’ve completed pre-check-in'); }; validatePageContent = () => { cy.get('h1', { timeout: Timeouts.slow }) .should('be.visible') .and('have.text', 'You’ve completed pre-check-in'); cy.get("[data-testid='confirmation-wrapper']"); cy.get("p[data-testid='appointment-day-location']"); cy.get("[data-testid='appointment-list']"); cy.get("h3[data-testid='appointment-questions']") .should('be.visible') .and('have.text', 'What if I have questions about my appointment?'); }; validateConfirmWithUpdates = () => { cy.get("[data-testid='confirmation-update-alert']") .should('be.visible') .and( 'have.text', 'A staff member will help you on the day of your appointment to update your information.', ); }; validateConfirmNoUpdates = () => { cy.get("[data-testid='confirmation-update-alert']").should('not.exist'); }; } export default new Confirmation();
department-of-veterans-affairs/vets-website
src/applications/check-in/pre-check-in/tests/e2e/pages/Confirmation.js
JavaScript
cc0-1.0
1,158
jsonp({"cep":"14875335","logradouro":"Avenida Gustavo Dias de Miranda","bairro":"Parque Primeiro de Maio","cidade":"Jaboticabal","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/14875335.jsonp.js
JavaScript
cc0-1.0
168
jsonp({"cep":"96204240","logradouro":"Rua Dezenove","bairro":"Zona Portu\u00e1ria","cidade":"Rio Grande","uf":"RS","estado":"Rio Grande do Sul"});
lfreneda/cepdb
api/v1/96204240.jsonp.js
JavaScript
cc0-1.0
147
jsonp({"cep":"59035660","logradouro":"Rua Luiz Souto","bairro":"Quintas","cidade":"Natal","uf":"RN","estado":"Rio Grande do Norte"});
lfreneda/cepdb
api/v1/59035660.jsonp.js
JavaScript
cc0-1.0
134
jsonp({"cep":"27524712","logradouro":"Rua Dois","bairro":"Bela Vista","cidade":"Resende","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/27524712.jsonp.js
JavaScript
cc0-1.0
128
jsonp({"cep":"54580720","logradouro":"Rua Poty","bairro":"Ponte dos Carvalhos","cidade":"Cabo de Santo Agostinho","uf":"PE","estado":"Pernambuco"});
lfreneda/cepdb
api/v1/54580720.jsonp.js
JavaScript
cc0-1.0
149
jsonp({"cep":"03534040","logradouro":"Rua Francisco Lacerda","bairro":"Vila Talarico","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/03534040.jsonp.js
JavaScript
cc0-1.0
151
jsonp({"cep":"17026886","logradouro":"Rua Dulce Seabra Parisi","bairro":"Jardim Silvestri","cidade":"Bauru","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/17026886.jsonp.js
JavaScript
cc0-1.0
147
jsonp({"cep":"07802070","logradouro":"Viela Vinte e Seis","bairro":"Companhia Fazenda Bel\u00e9m","cidade":"Franco da Rocha","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/07802070.jsonp.js
JavaScript
cc0-1.0
164
jsonp({"cep":"35702246","logradouro":"Rua G","bairro":"Planalto","cidade":"Sete Lagoas","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/35702246.jsonp.js
JavaScript
cc0-1.0
125
jsonp({"cep":"06693195","logradouro":"Rua Admilson Brito Souza","bairro":"Jardim Dona Elvira","cidade":"Itapevi","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/06693195.jsonp.js
JavaScript
cc0-1.0
152
jsonp({"cep":"02362205","logradouro":"Travessa Santa Edwirges","bairro":"Jardim Campo Limpo (Zona Norte)","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/02362205.jsonp.js
JavaScript
cc0-1.0
171
jsonp({"cep":"32670512","logradouro":"Avenida Manducaia","bairro":"Dom Bosco","cidade":"Betim","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/32670512.jsonp.js
JavaScript
cc0-1.0
132
jsonp({"cep":"12922735","logradouro":"Rua Professor Gilberto Venturini","bairro":"Cidade Planejada II","cidade":"Bragan\u00e7a Paulista","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/12922735.jsonp.js
JavaScript
cc0-1.0
176
jsonp({"cep":"27511660","logradouro":"Avenida Saturnino Braga","bairro":"Barbosa Lima","cidade":"Resende","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/27511660.jsonp.js
JavaScript
cc0-1.0
145
jsonp({"cep":"41310305","logradouro":"1\u00aa Travessa do Bom Viver","bairro":"\u00c1guas Claras","cidade":"Salvador","uf":"BA","estado":"Bahia"});
lfreneda/cepdb
api/v1/41310305.jsonp.js
JavaScript
cc0-1.0
148
jsonp({"cep":"04963110","logradouro":"Rua Alan Napier","bairro":"Ch\u00e1cara da Enseada","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/04963110.jsonp.js
JavaScript
cc0-1.0
155
/* ========================================================================== Shallow Extends Copyright (c) 2014 Alexey Maslennikov ========================================================================== */ 'use strict'; /** * @param {object} JavaScript object. * @returns {boolean} True if object is plain Javascript object. */ function _isPlainObject( object ) { return toString.call( object ) === '[object Object]'; } /** * Copies properties of all sources to the destination object overriding its own * existing properties. When extending from multiple sources, fields of every * next source will override same named fields of previous sources. * * @param {object} destination object. * @returns {bbject} extended destination object. */ function extend( destination ) { destination = destination || {}; for ( var i = 1; i < arguments.length; i++ ) { var source = arguments[i] || {}; for ( var key in source ) { if ( source.hasOwnProperty( key ) ) { var value = source[key]; if ( _isPlainObject( value ) ) { extend( destination[key] = {}, value ); }else { destination[key] = source[key]; } } } } return destination; } // Expose public methods. module.exports = { extend: extend };
imuchnik/cfgov-refresh
src/static/js/modules/util/shallow-extend.js
JavaScript
cc0-1.0
1,290
jsonp({"cep":"51260150","logradouro":"Rua Rubem Berardo","bairro":"Jord\u00e3o","cidade":"Recife","uf":"PE","estado":"Pernambuco"});
lfreneda/cepdb
api/v1/51260150.jsonp.js
JavaScript
cc0-1.0
133
jsonp({"cep":"54510240","logradouro":"Rua Ant\u00f4nio Jos\u00e9 Lins","bairro":"Vila Doutor Manoel Clementino","cidade":"Cabo de Santo Agostinho","uf":"PE","estado":"Pernambuco"});
lfreneda/cepdb
api/v1/54510240.jsonp.js
JavaScript
cc0-1.0
182
jsonp({"cep":"65074440","logradouro":"Rua Quarenta e Cinco","bairro":"Vinhais","cidade":"S\u00e3o Lu\u00eds","uf":"MA","estado":"Maranh\u00e3o"});
lfreneda/cepdb
api/v1/65074440.jsonp.js
JavaScript
cc0-1.0
147
jsonp({"cep":"59073121","logradouro":"Travessa Santo Onofre","bairro":"Planalto","cidade":"Natal","uf":"RN","estado":"Rio Grande do Norte"});
lfreneda/cepdb
api/v1/59073121.jsonp.js
JavaScript
cc0-1.0
142
jsonp({"cep":"31270120","logradouro":"Rua Buritizal","bairro":"Indai\u00e1","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/31270120.jsonp.js
JavaScript
cc0-1.0
139
jsonp({"cep":"91430840","logradouro":"Rua Seriema","bairro":"Jardim Carvalho","cidade":"Porto Alegre","uf":"RS","estado":"Rio Grande do Sul"});
lfreneda/cepdb
api/v1/91430840.jsonp.js
JavaScript
cc0-1.0
144
jsonp({"cep":"94180280","logradouro":"Rua Deolinda Goulart","bairro":"S\u00edtio Ga\u00facho","cidade":"Gravata\u00ed","uf":"RS","estado":"Rio Grande do Sul"});
lfreneda/cepdb
api/v1/94180280.jsonp.js
JavaScript
cc0-1.0
161
jsonp({"cep":"15707170","logradouro":"Rua Jorge Amado","bairro":"Conjunto Habitacional Jardim Arapu\u00e3","cidade":"Jales","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/15707170.jsonp.js
JavaScript
cc0-1.0
163
jsonp({"cep":"72001115","logradouro":"Ch\u00e1cara Gem\u00e9tris Ch\u00e1cara 4","bairro":"Setor Habitacional Samambaia (Taguatinga)","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
lfreneda/cepdb
api/v1/72001115.jsonp.js
JavaScript
cc0-1.0
200
jsonp({"cep":"36083744","logradouro":"Rua Am\u00e9lia Salles de Oliveira","bairro":"J\u00f3quei Clube","cidade":"Juiz de Fora","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/36083744.jsonp.js
JavaScript
cc0-1.0
164
jsonp({"cep":"40365365","logradouro":"Avenida do Maria do Curuzu","bairro":"Curuzu","cidade":"Salvador","uf":"BA","estado":"Bahia"});
lfreneda/cepdb
api/v1/40365365.jsonp.js
JavaScript
cc0-1.0
134
jsonp({"cep":"41750430","logradouro":"Beco do Sossego","bairro":"Arma\u00e7\u00e3o","cidade":"Salvador","uf":"BA","estado":"Bahia"});
lfreneda/cepdb
api/v1/41750430.jsonp.js
JavaScript
cc0-1.0
134
jsonp({"cep":"51200200","logradouro":"Rua Arcelina de Oliveira","bairro":"Ibura","cidade":"Recife","uf":"PE","estado":"Pernambuco"});
lfreneda/cepdb
api/v1/51200200.jsonp.js
JavaScript
cc0-1.0
134
jsonp({"cep":"59115530","logradouro":"Rua dos Madrigais","bairro":"Nossa Senhora da Apresenta\u00e7\u00e3o","cidade":"Natal","uf":"RN","estado":"Rio Grande do Norte"});
lfreneda/cepdb
api/v1/59115530.jsonp.js
JavaScript
cc0-1.0
169
jsonp({"cep":"86088160","logradouro":"Rua Pintagol","bairro":"Jacomo Violin","cidade":"Londrina","uf":"PR","estado":"Paran\u00e1"});
lfreneda/cepdb
api/v1/86088160.jsonp.js
JavaScript
cc0-1.0
133
jsonp({"cep":"13142304","logradouro":"Rua Avelino Beraldo","bairro":"Jardim Flamboyant","cidade":"Paul\u00ednia","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/13142304.jsonp.js
JavaScript
cc0-1.0
152
jsonp({"cep":"08695630","logradouro":"Rua Ant\u00f4nio Rom\u00e3o Costa","bairro":"Jardim S\u00e3o Bernardino","cidade":"Suzano","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/08695630.jsonp.js
JavaScript
cc0-1.0
168
jsonp({"cep":"22763576","logradouro":"Travessa Oito","bairro":"Cidade de Deus","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/22763576.jsonp.js
JavaScript
cc0-1.0
144
jsonp({"cep":"09153020","logradouro":"Caminho Dois","bairro":"Est\u00e2ncia Rio Grande","cidade":"Santo Andr\u00e9","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/09153020.jsonp.js
JavaScript
cc0-1.0
155
jsonp({"cep":"58428312","logradouro":"Rua Jos\u00e9 Moura","bairro":"Pedregal","cidade":"Campina Grande","uf":"PB","estado":"Para\u00edba"});
lfreneda/cepdb
api/v1/58428312.jsonp.js
JavaScript
cc0-1.0
142
jsonp({"cep":"26080250","logradouro":"Rua Seis","bairro":"Tinguazinho","cidade":"Nova Igua\u00e7u","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/26080250.jsonp.js
JavaScript
cc0-1.0
138
jsonp({"cep":"64077815","logradouro":"Rua Alexandre Gomes Chaves","bairro":"Parque Ideal","cidade":"Teresina","uf":"PI","estado":"Piau\u00ed"});
lfreneda/cepdb
api/v1/64077815.jsonp.js
JavaScript
cc0-1.0
145
import React from "react" import { Link, graphql } from "gatsby" import Bio from "../components/bio" import Layout from "../components/layout" import SEO from "../components/seo" import { rhythm } from "../utils/typography" class BlogIndex extends React.Component { render() { const { data } = this.props const siteTitle = data.site.siteMetadata.title const posts = data.allMarkdownRemark.edges return ( <Layout location={this.props.location} title={siteTitle}> <SEO title="All posts" keywords={[`blog`, `gatsby`, `javascript`, `react`]} /> <Bio /> {posts.map(({ node }) => { const title = node.frontmatter.title || node.fields.slug; var desc = node.frontmatter.excerpt || node.frontmatter.description; if (!desc || desc.length === 0) { desc = node.excerpt; } return ( <div key={node.fields.slug}> <h3 style={{ marginBottom: rhythm(1 / 4), }} > <Link style={{ boxShadow: `none` }} to={node.fields.slug}> {title} </Link> </h3> <small>{node.frontmatter.date}</small> <p dangerouslySetInnerHTML={{ __html: desc }} /> </div> ) })} </Layout> ) } } export default BlogIndex export const pageQuery = graphql` query { site { siteMetadata { title } } allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) { edges { node { excerpt fields { slug } frontmatter { date(formatString: "MMMM DD, YYYY") title description excerpt } } } } } `
yetanotherchris/yetanotherchris.github.io
src/pages/archive.js
JavaScript
cc0-1.0
1,963
jsonp({"cep":"08390210","logradouro":"Rua Lu\u00eds Antunes Portugal","bairro":"Jardim Santo Andr\u00e9","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/08390210.jsonp.js
JavaScript
cc0-1.0
170
jsonp({"cep":"77015032","logradouro":"Quadra 103 Sul Rua SO 9","bairro":"Plano Diretor Sul","cidade":"Palmas","uf":"TO","estado":"Tocantins"});
lfreneda/cepdb
api/v1/77015032.jsonp.js
JavaScript
cc0-1.0
144
jsonp({"cep":"40313050","logradouro":"Avenida Cl\u00e9ber","bairro":"Cidade Nova","cidade":"Salvador","uf":"BA","estado":"Bahia"});
lfreneda/cepdb
api/v1/40313050.jsonp.js
JavaScript
cc0-1.0
132
jsonp({"cep":"17016070","logradouro":"Rua Vivaldo Guimar\u00e3es","bairro":"Jardim Estoril","cidade":"Bauru","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/17016070.jsonp.js
JavaScript
cc0-1.0
148
jsonp({"cep":"08541310","logradouro":"Rua Jos\u00e9 Milit\u00e3o Soares","bairro":"Jardim S\u00e3o Fernando","cidade":"Ferraz de Vasconcelos","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/08541310.jsonp.js
JavaScript
cc0-1.0
181
jsonp({"cep":"79090320","logradouro":"Pra\u00e7a Faria Lima","bairro":"Jardim Aeroporto","cidade":"Campo Grande","uf":"MS","estado":"Mato Grosso do Sul"});
lfreneda/cepdb
api/v1/79090320.jsonp.js
JavaScript
cc0-1.0
156
jsonp({"cep":"89040350","logradouro":"Rua Leopoldo Holz","bairro":"Velha Central","cidade":"Blumenau","uf":"SC","estado":"Santa Catarina"});
lfreneda/cepdb
api/v1/89040350.jsonp.js
JavaScript
cc0-1.0
141
(function($) { $.Redactor.opts.langs['uk'] = { html: 'Код', video: 'Відео', image: 'Зображення', table: 'Таблиця', link: 'Посилання', link_insert: 'Вставити посилання ...', link_edit: 'Edit link', unlink: 'Видалити посилання', formatting: 'Стилі', paragraph: 'Звичайний текст', quote: 'Цитата', code: 'Код', header1: 'Заголовок 1', header2: 'Заголовок 2', header3: 'Заголовок 3', header4: 'Заголовок 4', header5: 'Заголовок 5', bold: 'Жирний', italic: 'Похилий', fontcolor: 'Колір тексту', backcolor: 'Заливка тексту', unorderedlist: 'Звичайний список', orderedlist: 'Нумерований список', outdent: 'Зменшити відступ', indent: 'Збільшити відступ', cancel: 'Скасувати', insert: 'Вставити', save: 'Зберегти', _delete: 'Видалити', insert_table: 'Вставити таблицю', insert_row_above: 'Додати рядок зверху', insert_row_below: 'Додати рядок знизу', insert_column_left: 'Додати стовпець ліворуч', insert_column_right: 'Додати стовпець праворуч', delete_column: 'Видалити стовпець', delete_row: 'Видалити рядок', delete_table: 'Видалити таблицю', rows: 'Рядки', columns: 'Стовпці', add_head: 'Додати заголовок', delete_head: 'Видалити заголовок', title: 'Підказка', image_view: 'Завантажити зображення', image_position: 'Обтікання текстом', none: 'ні', left: 'ліворуч', right: 'праворуч', image_web_link: 'Посилання на зображення', text: 'Текст', mailto: 'Ел. пошта', web: 'URL', video_html_code: 'Код відео ролика', file: 'Файл', upload: 'Завантажити', download: 'Завантажити', choose: 'Вибрати', or_choose: 'Або виберіть', drop_file_here: 'Перетягніть файл сюди', align_left: 'По лівому краю', align_center: 'По центру', align_right: 'По правому краю', align_justify: 'Вирівняти текст по ширині', horizontalrule: 'Горизонтальная лінійка', fullscreen: 'На весь екран', deleted: 'Закреслений', anchor: 'Anchor', link_new_tab: 'Open link in new tab', underline: 'Underline', alignment: 'Alignment', filename: 'Name (optional)', edit: 'Edit', center: 'Center' }; })(jQuery);
andersonbglaeser/f5digital
f5admin/web-files/plugins/jquery-redactor/lang/uk.js
JavaScript
cc0-1.0
3,271
jsonp({"cep":"25045052","logradouro":"Rua Carmem Miranda","bairro":"S\u00e3o Bento","cidade":"Duque de Caxias","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/25045052.jsonp.js
JavaScript
cc0-1.0
150
jsonp({"cep":"88304380","logradouro":"Rua Ant\u00f4nio de Borba","bairro":"S\u00e3o Jo\u00e3o","cidade":"Itaja\u00ed","uf":"SC","estado":"Santa Catarina"});
lfreneda/cepdb
api/v1/88304380.jsonp.js
JavaScript
cc0-1.0
157
jsonp({"cep":"74840650","logradouro":"Rua Montes Claros","bairro":"Parque Amaz\u00f4nia","cidade":"Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
lfreneda/cepdb
api/v1/74840650.jsonp.js
JavaScript
cc0-1.0
148
jsonp({"cep":"04431040","logradouro":"Rua Guilherme Jos\u00e9 Pereira","bairro":"Jardim Selma","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/04431040.jsonp.js
JavaScript
cc0-1.0
160
module.exports = function(context) { const fs = require('fs'); const cordova_util = context.requireCordovaModule('cordova-lib/src/cordova/util'); let projectRoot = cordova_util.isCordova(); let configXML = cordova_util.projectConfig(projectRoot); let data = fs.readFileSync(configXML, 'utf8'); for (var envVar in process.env) { data = data.replace('$' + envVar, process.env[envVar]); } fs.writeFileSync(configXML, data, 'utf8'); };
eclipsesource/tabris-js-hello-world
cordova/scripts/replace-config-env-vars.js
JavaScript
epl-1.0
454
// Copyright © 2014 John Watson // Licensed under the terms of the MIT License var GameState = function(game) { }; // Load images and sounds GameState.prototype.preload = function() { this.game.load.image('ground', 'assets/gfx/ground.png'); this.game.load.image('player', 'assets/gfx/player.png'); }; // Setup the example GameState.prototype.create = function() { // Set stage background to something sky colored this.game.stage.backgroundColor = 0x4488cc; // Define movement constants this.MAX_SPEED = 500; // pixels/second // Create a player sprite this.player = this.game.add.sprite(this.game.width/2, this.game.height - 64, 'player'); // Enable physics on the player this.game.physics.enable(this.player, Phaser.Physics.ARCADE); // Make player collide with world boundaries so he doesn't leave the stage this.player.body.collideWorldBounds = true; // Capture certain keys to prevent their default actions in the browser. // This is only necessary because this is an HTML5 game. Games on other // platforms may not need code like this. this.game.input.keyboard.addKeyCapture([ Phaser.Keyboard.LEFT, Phaser.Keyboard.RIGHT, Phaser.Keyboard.UP, Phaser.Keyboard.DOWN ]); // Create some ground for the player to walk on this.ground = this.game.add.group(); for(var x = 0; x < this.game.width; x += 32) { // Add the ground blocks, enable physics on each, make them immovable var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground'); this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE); groundBlock.body.immovable = true; groundBlock.body.allowGravity = false; this.ground.add(groundBlock); } }; // The update() method is called every frame GameState.prototype.update = function() { // Collide the player with the ground this.game.physics.arcade.collide(this.player, this.ground); if (this.leftInputIsActive()) { // If the LEFT key is down, set the player velocity to move left this.player.body.velocity.x = -this.MAX_SPEED; } else if (this.rightInputIsActive()) { // If the RIGHT key is down, set the player velocity to move right this.player.body.velocity.x = this.MAX_SPEED; } else { // Stop the player from moving horizontally this.player.body.velocity.x = 0; } }; // This function should return true when the player activates the "go left" control // In this case, either holding the right arrow or tapping or clicking on the left // side of the screen. GameState.prototype.leftInputIsActive = function() { var isActive = false; isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT); isActive |= (this.game.input.activePointer.isDown && this.game.input.activePointer.x < this.game.width/4); return isActive; }; // This function should return true when the player activates the "go right" control // In this case, either holding the right arrow or tapping or clicking on the right // side of the screen. GameState.prototype.rightInputIsActive = function() { var isActive = false; isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT); isActive |= (this.game.input.activePointer.isDown && this.game.input.activePointer.x > this.game.width/2 + this.game.width/4); return isActive; }; var game = new Phaser.Game(640, 320, Phaser.AUTO, 'game'); game.state.add('game', GameState, true);
boniatillo-com/PhaserEditor
source/phasereditor/phasereditor.resources.templates/templates/Game Mechanic Explorer/01 - Mechanic - Walking and jumping - Basic walking/WebContent/ex-walking-01.js
JavaScript
epl-1.0
3,525
var config = { type: Phaser.CANVAS, width: 800, height: 600, parent: 'phaser-example', backgroundColor: '#2d2d2d', useTicker: true, scene: { preload: preload, create: create, update: update } }; var image; var time; var delta; var speed = (600 / 2) / 1000; var game = new Phaser.Game(config); function preload () { this.load.image('bunny', 'assets/sprites/bunny.png'); this.load.atlas('gems', 'assets/tests/columns/gems.png', 'assets/tests/columns/gems.json'); } function create () { delta = this.add.text(32, 32); time = this.add.text(500, 400); image = this.add.image(0, 200, 'bunny'); this.anims.create({ key: 'diamond', frames: this.anims.generateFrameNames('gems', { prefix: 'diamond_', end: 15, zeroPad: 4 }), repeat: -1 }); this.anims.create({ key: 'prism', frames: this.anims.generateFrameNames('gems', { prefix: 'prism_', end: 6, zeroPad: 4 }), repeat: -1 }); this.anims.create({ key: 'ruby', frames: this.anims.generateFrameNames('gems', { prefix: 'ruby_', end: 6, zeroPad: 4 }), repeat: -1 }); this.anims.create({ key: 'square', frames: this.anims.generateFrameNames('gems', { prefix: 'square_', end: 14, zeroPad: 4 }), repeat: -1 }); this.add.sprite(400, 100, 'gems').play('diamond'); this.add.sprite(400, 200, 'gems').play('prism'); this.add.sprite(400, 300, 'gems').play('ruby'); this.add.sprite(400, 400, 'gems').play('square'); } function update (timestep, dt) { image.x += speed * dt; if (image.x > 1000) { image.x = 0; } time.setText('time: ' + this.sys.game.loop.time.toString()); delta.setText(this.sys.game.loop.deltaHistory); }
boniatillo-com/PhaserEditor
source/v2/phasereditor/phasereditor.resources.phaser.examples/phaser3-examples/public/src/timestep/delta history.js
JavaScript
epl-1.0
1,701
/********************************************************** * Common JS function calls. * * Copyright © 2001-2007 E-Blah. * * Part of the E-Blah Software. Released under the GPL. * * Last Update: September 17, 2007 * **********************************************************/ // AJAX: developer.apple.com/internet/webcontent/xmlhttpreq.html var req; function EditMessage(url,saveopen,savemessage,messageid) { EditMessage2(url,saveopen,savemessage); function EditMessage2(url,saveopen,savemessage,messageid) { req = false; if(window.XMLHttpRequest) { // Non IE browsers try { req = new XMLHttpRequest(encoding="utf-8"); } catch(e) { req = false; } } else if(window.ActiveXObject) { // IE try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { req = false; } } } if(req) { req.onreadystatechange = processReqChange; req.open("POST", url, true); // Use POST so we don't get CACHED items! if(saveopen == 1) { req.send("message="+encodeURIComponent(savemessage)); } else if(saveopen == 2) { req.send(savemessage); } else { req.send('TEMP'); } } else { alert('There was an error loading this page.'); } } function processReqChange() { if(req.readyState != 4) { document.getElementById(messageid).innerHTML = '<div class="loading">&nbsp;</div>'; } if(req.readyState == 4) { if (req.status == 200) { document.getElementById(messageid).innerHTML = req.responseText; } else { alert('There was an error loading this page.'); } } } } // Let's do some menus ... // Some code based from: www.quirksmode.org/js/findpos.html function findPosX(obj) { var curleft = 0; if(obj.offsetParent) { while (obj.offsetParent) { curleft += obj.offsetLeft obj = obj.offsetParent; } } else if(obj.x) curleft += obj.x; return curleft; } function findPosY(obj,plussize) { var curtop = plussize; if(navigator.userAgent.indexOf("Firefox") != -1) { curtop = (curtop/2); } if(navigator.userAgent.indexOf("IE") != -1) { curtop = (curtop+12); } if(obj.offsetParent) { while (obj.offsetParent) { curtop += obj.offsetTop obj = obj.offsetParent; } } else if(obj.y) curtop += obj.y; return curtop; } // Creating Menus ... function CreateMenus(obj,plussize,JSinput) { var newX = findPosX(obj); var newY = findPosY(obj,plussize); var x = document.getElementById('menu-eblah'); x.style.top = newY + 'px'; x.style.left = newX + 'px'; document.getElementById('menu-eblah').innerHTML = ConstructLinks(JSinput); document.getElementById('menu-eblah').style.visibility = ''; } function ClearMenu() { document.getElementById('menu-eblah').innerHTML = ''; document.getElementById('menu-eblah').style.visibility = 'hidden'; } function ConstructLinks(JSinput) { GetLinks(JSinput); var link = ''; for(x in MenuItems) { link += '<div style="padding: 5px;" class="win3">' + MenuItems[x] + '</div>'; } return(link); } // Image Resize; from Martin's Mod for E-Blah function resizeImg() { var _resizeWidth = 750; var ResizeMsg = 'Click to view original size ...'; var _resizeClass = 'imgcode'; var imgArray = document.getElementsByTagName('img'); for(var i = 0; i < imgArray.length; i++) { var imgObj = imgArray[i]; if(imgObj.className == _resizeClass && imgObj.width > _resizeWidth) { imgObj.style.width = _resizeWidth + 'px'; imgObj.onclick = ImagecodeWinOpen; imgObj.title = ResizeMsg; imgObj.style.cursor = 'pointer'; } } } function ImagecodeWinOpen(e) { var img = (e)?e.target.src:window.event.srcElement.src; var w = window.open('','IMG','titlebar,scrollbars,resizable'); if (w) { w.document.write('<html><body><div align="center"><a href="#" onclick="window.close(); return false"><img src="'+img+'"></a></div></body></html>'); w.document.close(); } } window.onload = resizeImg;
eblah/E-Blah-Forum
public_html/blahdocs/common.js
JavaScript
gpl-2.0
4,101
/** * @file * Provides functions that enable the selection of elements on a webpage, which can then be manipulated. * * HTML elements on the webpage that have a class containing '.selectable' */ // JavaScript should be made compatible with libraries other than jQuery by // wrapping it with an "anonymous closure". See: // - https://drupal.org/node/1446420 // - http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth (function ($, Drupal, window, document, undefined) { /** * CONTENTS - variable declarations - Drupal.behaviors.selection.attach() Drupal.edit_selected .find_selectables() .get_selecteds_indexes() .are_selecteds() .set_selecteds_indexes() .selecteds_indexes_push() .selecteds_indexes_remove() .add_selection_listeners() .get_selected_selectables() // Simplest get function. .get_selected_nids() .get_selectable() .get_index() .deselect_all() disable_image_drag() set_up_page() register_selection() register_focus() toggle_selected_element() adjust_buttons() set_up_keypress_mgmt() handle_keypress_see_shortcuts() handle_keypress_select() handle_keypress_prev() get_focussed_prev() handle_keypress_next() get_focussed_next() handle_keypress_group() */ /* * @todo Change primary storage array `selecteds_indexes` * to store the jQ elements rather than their 'indexes' (unreliable!). */ var page_is_setup = false; var selectables; // View row numbers of the // The selecteds array temporarily stores the 'pictures' that are currently selected // The indexes refer to the 'result numbers' of the elements within the view content (for easy JQuery retrieval) var selecteds_indexes = []; // View row numbers of the var selecteds = []; // View row numbers of the var mouseIsDown = false; // Tracks status of mouse button var shift_key_down = false; // To understand behaviors, see https://drupal.org/node/756722#behaviors Drupal.behaviors.selection = { attach: function(context, settings) { // console.log('context: ', context); // console.log('context: ', $(context)); // console.log('selectables: ', selectables); if (! page_is_setup) { // disable_image_drag(); // Not needed anymore. Drupal.selection.find_selectables(); register_focus( selectables.eq(0) ); set_up_keypress_mgmt(context); set_up_page(context); $(document).mousedown(function(event) { // event.preventDefault(); mouseIsDown = true; // When mouse goes down, set mouseIsDown to true // return false; }) .mouseup(function() { mouseIsDown = false; // When mouse goes up, set mouseIsDown to false }); selectables.each(function() { Drupal.selection.add_selection_listeners($(this)); }); $( '#deselect_all', context ).click( function() { Drupal.selection.deselect_all(); }); page_is_setup = true; } }, weight: 3 }; Drupal.selection = { find_selectables: function(context) { if (typeof context === 'undefined') { context = document; } selectables = $('.selectable', context); }, get_selecteds_indexes: function() { return selecteds_indexes; }, /** * Determines if there are any selectables currently selected. */ are_selecteds: function() { // var num_selected = Drupal.selection.get_selecteds_indexes().length; var are_selecteds = selectables.filter('.selected').length > 0 ? true : false; // console.log('are_selecteds: ', are_selecteds); return are_selecteds; }, set_selecteds_indexes: function( array ) { selecteds_indexes = array; }, selecteds_indexes_push: function( index ) { selecteds_indexes.push(index); }, selecteds_indexes_remove: function( index ) { selecteds_indexes.splice( $.inArray( index, selecteds_indexes), 1 ); }, /** * The first element could after the last element (if select was made in reverse). */ select_multiple: function( first_element, last_element ) { // console.log('first_element: ', first_element); // console.log('last_element: ', last_element); var settings = { cleanup: false, push_index: false }; var select_on = false; selectables.each(function(key, element) { var selectable = $(element); if (selectable.is(first_element) || selectable.is(last_element)) { if (! select_on) { select_on = true; } else { register_selection( selectable, settings ); // For the last one. select_on = false; } } if (select_on && (! selectable.hasClass('selected'))) { register_selection( selectable, settings ); } }); selectables.each(function() { selecteds_indexes.push($(this).index()); }); // console.log('selecteds_indexes: ', selecteds_indexes); adjust_buttons(); adjust_toolbar(); $(document).trigger( "selection:select_all" ); }, add_selection_listeners: function(selectable) { selectable.find('.selectable-target').mousedown( function(event) { event.preventDefault(); // Prevents browser's "text selection" var settings = { cleanup: true }; var selectable = $(this).parents('.selectable'); if (shift_key_down) { Drupal.selection.select_multiple( selectables.filter('.focussed'), selectable ); } else { register_selection( selectable, settings ); } register_focus( selectable ); }); selectable.find('.selectable-target').mouseenter( function(event) { var settings = { cleanup: true }; var selectable = $(this).parents('.selectable'); if (mouseIsDown) { register_selection( selectable, settings ); } }); }, /** * @return a list of Jquery elements */ get_selected_selectables: function(id) { // var selecteds_indexes = Drupal.selection.get_selecteds_indexes(); // console.log('selecteds_indexes received: ', selecteds_indexes); // selecteds = []; // $.each( selecteds_indexes, function( key, index ) { // // selecteds.push(selectables.filter('.views-row-' + index )); // selecteds.push(selectables.filter('.selected')); // // console.log('elements: ', element.length); // }); // return selecteds; return selectables.filter('.selected'); }, /** * Gets the array of selectable indexes, and creates an array of the nids from it. */ get_selected_nids: function() { // var selecteds_indexes = Drupal.selection.get_selecteds_indexes(); // console.log('selecteds_indexes received: ', selecteds_indexes); selecteds_nids = []; selectables.filter('.selected').each(function( key, index ) { // var selectable = selectables.filter('.views-row-' + (index - 1) ); // console.log('selectable: ', $(this)); var nid = $(this).find( ".property-nid" ).html().trim(); // console.log('nid: ', nid); selecteds_nids.push( nid ); }); // console.log('selecteds_nids: ', selecteds_nids); return selecteds_nids; }, /** * @return a Jquery element, regardless of whether it's in a group */ get_selectable: function(id) { return selectables.filter('.views-row-' + id ); }, /** * Determines the position that a result is in within view results. */ get_index: function(target) { var index; var classes = target.attr( "class" ).split( " " ); // console.log('classes: ', classes); if(classes) { // Determine the picture's result number (within view) $.each( classes, function( key, value ) { // We use "views-row-#" because it's reliable, and doesn't change (as long as the layout is 'list') if ( value.substr( 0, 10 ) == "views-row-" ) { // console.log('substr: ', value.substr( 10, value.length)); index = parseInt( value.substr( 10, value.length ), 10 ); } else return; }); } return index; }, /** * Deselects all selected elements. */ deselect_all: function() { // console.log('call: Drupal.selection.deselect_all()'); selectables.filter('.selected').removeClass( "selected" ); adjust_buttons(); adjust_toolbar(); $(window).trigger( "selection:deselect_all" ); } } function disable_image_drag() { // Disable firefox's 'image drag' feature, which messes with our ‘drag-select’ $(document).on("dragstart", function(event) { event.preventDefault(); // console.log('On: dragstart'); return false; }); } function set_up_page(context) { var toolbar = $('[role="toolbar"][aria-label="primary toolbar"]', context); $( '.page__title', context ) .after('<div class="action_buttons"></div>'); toolbar .append("<button id='deselect_all' type='button' disabled>Un-select all</button>"); toolbar.find('#deselect_all').prepend("<span class='icon-select_all'></span> "); } /** * Adds or removes the result number from the selected array. * * @param target * JQuery object that was selected or unselected. * * @param checked * Boolean indicating if the target's checked attribute should be set to true. */ function register_selection(target, settings) { // console.log('Call: register_selection'); var checked = toggle_selected_element( target ); // console.log('checked: ', checked); var index = Drupal.selection.get_index(target); // console.log('index: ', index); if (typeof settings.push_index == 'undefined') { settings.push_index = true; } if (checked && settings.push_index) { // Add the picture to the 'selecteds' arrays selecteds_indexes.push( index ); } else if (settings.push_index) { // Remove the picture from the 'selecteds' arrays selecteds_indexes.splice( $.inArray( index, selecteds_indexes), 1 ); } // console.log("selecteds_indexes: ", selecteds_indexes); settings = (typeof settings !== 'undefined') ? settings : { cleanup: false }; if (settings.cleanup) { // console.log('cleanup'); adjust_buttons(); adjust_toolbar(); target.trigger( "selection:select" ); } } /** * Adds or removes the result number from the selected array. */ function register_focus(target) { selectables.removeClass('focussed'); target.toggleClass('focussed'); } /** * Toggles the selected state of the selected element. * * @return boolean * Returns true if the selected element is now 'selected', or false otherwise. */ function toggle_selected_element(target) { target.toggleClass( "selected" ); var checked = target.hasClass( "selected" ); return checked; } /** * Enables and disables the buttons according to selections. */ function adjust_buttons() { // console.log('adjust_buttons()'); // if( selecteds_indexes.length ) { // $( '#deselect_all' ).attr('disabled', false); // } else { // $( '#deselect_all' ).attr('disabled', true); // } $( '#deselect_all' ).attr('disabled', ! Drupal.selection.are_selecteds()); } /** * Shows or hides the toolbar according to selections. */ function adjust_toolbar() { var toolbar = $('[role="toolbar"][aria-label*="primary"]'); toolbar.attr('aria-expanded', Drupal.selection.are_selecteds()); var selection_count = selectables.filter('.selected').length; toolbar.find('.selection-count .count').html(selection_count); } function set_up_keypress_mgmt(context) { Drupal.casabio.add_keypress_info( "<tr><td><strong>shift</strong> <small>+</small> <strong>/</strong> : </td><td>Show shortcuts</td></tr>" ); // Further keypress info will be customised by page and added by edit_selected.js. // Drupal.casabio.add_keypress_info(); // console.log('document, context: ', $(context).find(document)); $('body', context).bind('keydown', 'shift+/', handle_keypress_see_shortcuts); $('body', context).bind('keydown', 'x', handle_keypress_select); $('body', context).bind('keydown', 'c', handle_keypress_unselect_all); $('body', context).bind('keydown', 'left', handle_keypress_prev, context); $('body', context).bind('keydown', 'right', handle_keypress_next, context); $('body', context).bind('keydown', 'ctrl+a', handle_keypress_select_all, context); $('body', context).bind('keydown', 'shift', handle_keypress_shift_down); $('body', context).bind('keyup', 'shift', handle_keypress_shift_up); } function handle_keypress_see_shortcuts() { // console.log('handle_keypress_see_shortcuts'); var is_open = $( '#display-shortcuts[style*="display: block"]' ).length > 0; if (is_open) { $( '#display-shortcuts' ).dialog('close'); } else { $( '#display-shortcuts' ).dialog('open'); } } function handle_keypress_select() { var settings = { cleanup: true, push_index: false }; var focussed = selectables.filter('.focussed'); register_selection(focussed, settings); } function handle_keypress_unselect_all() { Drupal.selection.deselect_all(); } function handle_keypress_prev() { var selectable = selectables.filter('.focussed'); prev = get_focussed_prev(selectable); if (prev !== null) { register_focus(prev); } $(window).trigger( "selection:prev", prev ); } /** * Gets the previous selectable before an element (which can be a selectable or a group). */ function get_focussed_prev(element) { var prev; // If in a group and is the last in the group if ((element.parent('.group').length > 0) && (element.prev().length == 0)) { // console.log('is in group') prev = get_focussed_prev(element.parent()); } // If the previous li or ul is a group else if (element.prevAll('li, ul').eq(0).hasClass('group')) { // console.log('next is group') prev = element.prevAll('li, ul').eq(0).children('.selectable').eq(-1); } // If this is the first selectable else if (element.prevAll('.selectable').length == 0) { prev = null; } else { prev = element.prevAll('.selectable').eq(0); } return prev; } function handle_keypress_next(context) { // console.log('called: handle_keypress_next()'); var selectable = selectables.filter('.focussed'); next = get_focussed_next(selectable); if (next !== null) { register_focus(next); } $(window).trigger( "selection:next", next ); } function handle_keypress_select_all(context) { // Drupal.casa_utilities.start_timer('select_all'); Drupal.selection.select_multiple(selectables.first(), selectables.last()); // Drupal.casa_utilities.end_timer('select_all'); return false; } /** * Gets the next selectable following an element (which can be a selectable or a group). */ function get_focussed_next(element) { // console.log('element class: ', element.attr('class')); var next; // If in a group and is the last in the group if ((element.parent('.group').length > 0) && (element.nextAll('li, ul').eq(0).length == 0)) { // console.log('is in group') next = get_focussed_next(element.parent()); } // If the next li or ul is a group else if (element.nextAll('li, ul').eq(0).hasClass('group')) { // console.log('next is group') next = element.nextAll('li, ul').eq(0).children('.selectable').eq(0); } // If this is the last selectable else if (element.nextAll('.selectable').length == 0) { next = null; } else { next = element.nextAll('.selectable').eq(0); // console.log('next class: ', next.attr('class')); } return next; } function handle_keypress_group() { group(); } function handle_keypress_ungroup() { ungroup_all(); } function handle_keypress_shift_down() { shift_key_down = true; } function handle_keypress_shift_up() { shift_key_down = false; } })(jQuery, Drupal, this, this.document);
Droces/casabio
sites/all/modules/custom/selection/scripts/selection.js
JavaScript
gpl-2.0
15,835
'use strict'; import BaseContentService from './BaseContentService.js'; import {Question} from 'common/models.js'; import {Injector} from 'kusema.js'; var I = new Injector('$http', '$q'); var QuestionService = function() { BaseContentService.call(this, true); I.init(); this.urlStem = 'api/questions'; } QuestionService.prototype = Object.create(BaseContentService.prototype, { model: {writable: false, enumerable: false, value: Question} }); QuestionService.prototype.getNextTenQuestions = function (requestNumber, group) { var groupURL = (group) ? ('/'+group) : ''; return I.$http.get(this.urlBase + '/tenMore' + groupURL + '/' + requestNumber) .then(function(response) { return this.createClientModels(response.data); }.bind(this)); }; QuestionService.prototype.getFeed = function(requestNumber, group) { var groupURL = (group) ? (group+'/') : ''; return I.$http.get(this.urlBase+'/feed/'+groupURL+requestNumber) .then( (response) => { if (response.status == 204) { return I.$q.reject(new Error('No more questions')); } return this.createClientModels(response.data) } ); } import kusema from 'kusema.js'; kusema.service('questionService', QuestionService);
akdor1154/kusema
Client/lib/common/services/QuestionService.js
JavaScript
gpl-2.0
1,296
/** A modal view for handling user logins @class LoginView @extends Discourse.ModalBodyView @namespace Discourse @module Discourse **/ Discourse.LoginView = Discourse.ModalBodyView.extend({ templateName: 'modal/login', siteBinding: 'Discourse.site', title: Em.String.i18n('login.title'), authenticate: null, loggingIn: false, showView: function(view) { return this.get('controller').show(view); }, newAccount: function() { return this.showView(Discourse.CreateAccountView.create()); }, forgotPassword: function() { return this.showView(Discourse.ForgotPasswordView.create()); }, loginButtonText: (function() { if (this.get('loggingIn')) { return Em.String.i18n('login.logging_in'); } return Em.String.i18n('login.title'); }).property('loggingIn'), loginDisabled: (function() { if (this.get('loggingIn')) { return true; } if (this.blank('loginName') || this.blank('loginPassword')) { return true; } return false; }).property('loginName', 'loginPassword', 'loggingIn'), login: function() { var _this = this; this.set('loggingIn', true); $.post("/session", { login: this.get('loginName'), password: this.get('loginPassword') }).success(function(result) { if (result.error) { _this.set('loggingIn', false); if( result.reason === 'not_activated' ) { return _this.showView(Discourse.NotActivatedView.create({username: _this.get('loginName'), sentTo: result.sent_to_email, currentEmail: result.current_email})); } _this.flash(result.error, 'error'); } else { return window.location.reload(); } }).fail(function(result) { _this.flash(Em.String.i18n('login.error'), 'error'); return _this.set('loggingIn', false); }); return false; }, authMessage: (function() { if (this.blank('authenticate')) { return ""; } return Em.String.i18n("login." + (this.get('authenticate')) + ".message"); }).property('authenticate'), twitterLogin: function() { var left, top; this.set('authenticate', 'twitter'); left = this.get('lastX') - 400; top = this.get('lastY') - 200; return window.open("/auth/twitter", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); }, facebookLogin: function() { var left, top; this.set('authenticate', 'facebook'); left = this.get('lastX') - 400; top = this.get('lastY') - 200; return window.open("/auth/facebook", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); }, openidLogin: function(provider) { var left, top; left = this.get('lastX') - 400; top = this.get('lastY') - 200; if (provider === "yahoo") { this.set("authenticate", 'yahoo'); return window.open("/auth/yahoo", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); } else { window.open("/auth/google", "_blank", "menubar=no,status=no,height=500,width=850,left=" + left + ",top=" + top); return this.set("authenticate", 'google'); } }, githubLogin: function() { var left, top; this.set('authenticate', 'github'); left = this.get('lastX') - 400; top = this.get('lastY') - 200; return window.open("/auth/github", "_blank", "menubar=no,status=no,height=400,width=800,left=" + left + ",top=" + top); }, personaLogin: function() { navigator.id.request(); }, authenticationComplete: function(options) { if (options.awaiting_approval) { this.flash(Em.String.i18n('login.awaiting_approval'), 'success'); this.set('authenticate', null); return; } if (options.awaiting_activation) { this.flash(Em.String.i18n('login.awaiting_confirmation'), 'success'); this.set('authenticate', null); return; } // Reload the page if we're authenticated if (options.authenticated) { window.location.reload(); return; } return this.showView(Discourse.CreateAccountView.create({ accountEmail: options.email, accountUsername: options.username, accountName: options.name, authOptions: Em.Object.create(options) })); }, mouseMove: function(e) { this.set('lastX', e.screenX); return this.set('lastY', e.screenY); }, didInsertElement: function(e) { var _this = this; return Em.run.next(function() { return $('#login-account-password').keydown(function(e) { if (e.keyCode === 13) { return _this.login(); } }); }); } });
SuperSonicDesignINC/FXDD
app/assets/javascripts/discourse/views/modal/login_view.js
JavaScript
gpl-2.0
4,631
/* global Package, Npm */ Package.describe({ name: 'procempa:keycloak-auth', version: '1.0.0', summary: 'Meteor Keycloak Handshake flow', git: 'https://github.com/Procempa/meteor-keycloak-auth.git', documentation: 'README.md' }); Package.onUse(function(api) { api.use('[email protected]'); api.use('[email protected]'); api.export('KeycloakServer', 'server'); api.export('KeycloakClient', 'client'); api.mainModule('client-main.js', 'client'); api.mainModule('server-main.js', 'server'); }); Npm.depends({ 'lodash': '4.16.1', 'fallbackjs': '1.1.8', 'localforage': '1.4.2', 'keycloak-auth-utils': '2.2.1', 'babel-plugin-transform-decorators-legacy': '1.3.4', 'babel-plugin-transform-class-properties': '6.11.5', 'babel-plugin-transform-strict-mode': '6.11.3', 'q': '1.4.1' });
Procempa/meteor-keycloak-auth
package.js
JavaScript
gpl-2.0
808
/** * XTemplate 所有的扩展函数集合,用于处理html中常见的格式转换,默认值等处理。 * 如果需要自行扩展,请使用window.Render的addFunc函数 * * @class Render.funcs */ (function (r, undefined) { 'use strict'; /** * 指定输出的默认值,如果有值就原样输出,如果空或是null,就输出默认值。 * * 示例: * * {name|default,'小明'} * * @method default * @param val {string} 变量名 * @param defaultVal 默认值 * @returns {object} */ r.addFunc('default', function (val, defaultVal) { if (val === undefined || typeof(val) == 'undefined' || val === '' || val === 'null') { return defaultVal; } return val; }); /** * 判断变量是否为空。 * * 示例: * * {name|empty,'空','不空'} * * @method default * @param val {string} 变量名 * @param emptyValue 为空时显示值 * @param notEmptyValue 不为空时显示的值 * @returns {object} */ r.addFunc('empty', function (val, emptyValue, notEmptyValue) { if (val === undefined || typeof(val) == 'undefined' || val === '' || val === 'null') { return emptyValue; } else { return notEmptyValue; } }); /** * 根据设定值返回指定内容 * * 示例: * * {status|case,-1,'审核不通过',1,'审核通过','待审核'} * {status|case,-1,'审核不通过',1,'审核通过',2,'VIP','待审核'} * * 参数说明:参数成对出现,第一个是设定值,第二是要返回的值;后续可以增加多个成队的参数;最后一个参数为默认值,所有设定值都不满足时输出 * @method case * @param val {string} 变量名 * @returns {object} */ r.addFunc('case', function (val) { for (var i = 1; i < arguments.length; i += 2) { if (val == arguments[i] && i < arguments.length - 1) { return arguments[i + 1]; } } return arguments[arguments.length - 1]; }); /** * 格式化货币,最少小数显示, * 示例: * * {price|format_money} * 如果price为10.0100,显示10.01 * 如果price为10.000,显示10 * * @method format_money * @param val {string} 变量名 * @returns {number} */ r.addFunc('format_money', function (val) { return parseFloat(val); }); /** * 将 Date 转化为指定格式的String * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * 示例: * * {date|format_date,"yyyy-MM-dd hh:mm:ss.S"} 输出 2006-07-02 08:09:04.423 * {date|format_date,"yyyy-M-d h:m:s.S"} 输出 2006-7-2 8:9:4.18 * {date|format_date,"yyyy-M-d h:m:s"} 输出 2006-7-2 8:9:4 * * @method format_date * @param val {string} 变量名 * @param fmt {string} 格式串 * @returns {string} 格式化后的日期串 */ r.addFunc('format_date', function (val, fmt) { if (typeof(val) != 'object') { val = new Date(parseInt(val)); } if (!fmt) { fmt = 'yyyy-MM-dd hh:mm:ss'; } var format_data_o = { "M+": val.getMonth() + 1, //月份 "d+": val.getDate(), //日 "h+": val.getHours(), //小时 "m+": val.getMinutes(), //分 "s+": val.getSeconds(), //秒 "q+": Math.floor((val.getMonth() + 3) / 3), //季度 "S": val.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (val.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in format_data_o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (format_data_o[k]) : (("00" + format_data_o[k]).substr(("" + format_data_o[k]).length))); return fmt; }); /** * 数字保留小数位数 * 示例: * * {float_num|fixed,2} * * @method fixed * @param val {string} 要格式的变量名 * @param c {number} 保留的小数位置,默认为0 * @returns {number} */ r.addFunc('fixed', function (val, c) { if (typeof c == 'undefined') { c = 0; } if (typeof(val) == 'number') { return val.toFixed(c); } else { return val; } }); /** * 没有正确的函数处理时,用此函数处理,直接输出变量值 * 外部不要使用 * @param val {string} 变量名 * @returns {string} */ r.addFunc('noFunc', function (val) { return '没有找到正确的处理函数'; }); /** * 重复输出num次val * * 示例: * * {num|repeat,'*'},当num=4时,输出**** * * @method repeat * @param val {string} 重复次数 * @param res {string}要重复的内容 * @returns {string} */ r.addFunc('repeat', function (val, res) { var result = ''; for (var i = 0; i < val; i++) { result += res; } return result; }); /** * 内部实现简单的循环,注意,内部模板和普通模板有区别,需要使用小括号代替大扩号。 * 常用于嵌套循环显示。 * * 示例: * * {array|range,'(id),'},如果array=[{id:0},{id:1}],会输出0,1, * * @method range * @param list {string} 要循环的数组变量名 * @param tmpl {string} 模板 * @returns {string} 输出的html */ r.addFunc('range', function (list, tmpl) { var html = ''; if (tmpl) { tmpl = tmpl.replace(/\(/g, '{').replace(/\)/g, '}'); var func = r.syntax.buildFunc('range', tmpl); if (func) { for (var i = 0; i < list.length; i++) { html += func(r, list[i]); } } } return html; }); /** * 过滤html字符,因为系统默认已过滤html,所以此函数一般外部不使用 * * 示例: * * {code|filter_html} * * @method filter_html * @param html {string} 待过滤的html代码 * @returns {string} */ r.addFunc('filter_html', function (html) { return r.util.html(html); }); /** * 从左侧按指定长度截断字串,注意一个汉字按2个字符计算,这样可以准确的控制格式 * * 示例: * * {str|left,20,'...'} * {str|left,20} * * @method left * @param str {string} 要截断的字串变量名 * @param len {number} 截断后的字串长度,一个汉字按2个字符计算 * @param dot {string} [可选] 截断后补充的串,示例:"..." * @returns {string} */ r.addFunc('left', function (str, len, dot) { var newLength = 0; var newStr = ""; var chineseRegex = /[^\x00-\xff]/g; var singleChar = ""; var dotLen = 0; if (dot) { dotLen = dot.length; } var strLength = str.replace(chineseRegex, "**").length; for (var i = 0; i < strLength; i++) { singleChar = str.charAt(i).toString(); if (singleChar.match(chineseRegex) !== null) { newLength += 2; } else { newLength++; } if (newLength + dotLen > len) { if (dotLen > 0) { newStr += dot; } break; } newStr += singleChar; } return newStr; }); })(window.Render);
seefan/xtemplate
src/funcs.js
JavaScript
gpl-2.0
8,148
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery-ui-1.9.2.js //= require jquery_ujs //= require jquery_mods //= require jquery.mobile.custom.js //= require jquery.waypoints.js //= require bootstrap //= require bootstrap-notify.js //= require notify.js //= require intro.js //= require modern-business/modern-business.js //= require cocoon //= require smart_listing //= require highcharts/highcharts.js //= require highcharts/highcharts-more.js //= require highcharts/highcharts-3d.js //= require startup.js //= require scrollspy.js //= require typeahead.bundle.js //= require charts.js //= require reports.js //= require stats.js //= require users.js //= require dashboard.js //= require ls_reports.js //= require ls_reports_filter.js //= require ls_reports_graph.js //= require ls_reports_spreadsheet.js //= require_tree ./assignments //= require sync_triggers.js //= require dataTables/dataTables.js //= require dataTables/extensions/TableTools/js/dataTables.tableTools.js //= require sessions.js //= require animations.js //= require form-utils.js //= require select2 //= require simplemde/simplemde.min.js
PatrickVChung/reindeer
app/assets/javascripts/application.js
JavaScript
gpl-2.0
1,679
/* * MultiSelect v0.9.8 * Copyright (c) 2012 Louis Cuny * * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://sam.zoy.org/wtfpl/COPYING for more details. */ !function ($) { "use strict"; /* MULTISELECT CLASS DEFINITION * ====================== */ var MultiSelect = function (element, options) { this.options = options; this.$element = $(element); this.$container = $('<div/>', { 'class': "ms-container" }); this.$selectableContainer = $('<div/>', { 'class': 'ms-selectable' }); this.$selectionContainer = $('<div/>', { 'class': 'ms-selection' }); this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' }); this.$selectionUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' }); this.scrollTo = 0; this.sanitizeRegexp = new RegExp("\\W+", 'gi'); this.elemsSelector = 'li:visible:not(.ms-optgroup-label,.ms-optgroup-container,.'+options.disabledClass+')'; }; MultiSelect.prototype = { constructor: MultiSelect, init: function(){ var that = this, ms = this.$element; if (ms.next('.ms-container').length === 0){ ms.css({ position: 'absolute', left: '-9999px' }); ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'multiselect'); this.$container.attr('id', 'ms-'+ms.attr('id')); ms.find('option').each(function(){ that.generateLisFromOption(this); }); this.$selectionUl.find('.ms-optgroup-label').hide(); if (that.options.selectableHeader){ that.$selectableContainer.append(that.options.selectableHeader); } that.$selectableContainer.append(that.$selectableUl); if (that.options.selectableFooter){ that.$selectableContainer.append(that.options.selectableFooter); } if (that.options.selectionHeader){ that.$selectionContainer.append(that.options.selectionHeader); } that.$selectionContainer.append(that.$selectionUl); if (that.options.selectionFooter){ that.$selectionContainer.append(that.options.selectionFooter); } that.$container.append(that.$selectableContainer); that.$container.append(that.$selectionContainer); ms.after(that.$container); that.activeMouse(that.$selectableUl); that.activeKeyboard(that.$selectableUl); var action = that.options.dblClick ? 'dblclick' : 'click'; that.$selectableUl.on(action, '.ms-elem-selectable', function(){ that.select($(this).data('ms-value')); }); that.$selectionUl.on(action, '.ms-elem-selection', function(){ that.deselect($(this).data('ms-value')); }); that.activeMouse(that.$selectionUl); that.activeKeyboard(that.$selectionUl); ms.on('focus', function(){ that.$selectableUl.focus(); }) } var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get(); that.select(selectedValues, 'init'); if (typeof that.options.afterInit === 'function') { that.options.afterInit.call(this, this.$container); } }, 'generateLisFromOption' : function(option){ var that = this, ms = that.$element, attributes = "", $option = $(option); for (var cpt = 0; cpt < option.attributes.length; cpt++){ var attr = option.attributes[cpt]; if(attr.name !== 'value' && attr.name !== 'disabled'){ attributes += attr.name+'="'+attr.value+'" '; } } var selectableLi = $('<li '+attributes+'><span>'+$option.text()+'</span></li>'), selectedLi = selectableLi.clone(), value = $option.val(), elementId = that.sanitize(value, that.sanitizeRegexp); selectableLi .data('ms-value', value) .addClass('ms-elem-selectable') .attr('id', elementId+'-selectable'); selectedLi .data('ms-value', value) .addClass('ms-elem-selection') .attr('id', elementId+'-selection') .hide(); if ($option.prop('disabled') || ms.prop('disabled')){ selectedLi.addClass(that.options.disabledClass); selectableLi.addClass(that.options.disabledClass); } var $optgroup = $option.parent('optgroup'); if ($optgroup.length > 0){ var optgroupLabel = $optgroup.attr('label'), optgroupId = that.sanitize(optgroupLabel, that.sanitizeRegexp), $selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId), $selectionOptgroup = that.$selectionUl.find('#optgroup-selection-'+optgroupId); if ($selectableOptgroup.length === 0){ var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>', optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>'; $selectableOptgroup = $(optgroupContainerTpl); $selectionOptgroup = $(optgroupContainerTpl); $selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId); $selectionOptgroup.attr('id', 'optgroup-selection-'+optgroupId); $selectableOptgroup.append($(optgroupTpl)); $selectionOptgroup.append($(optgroupTpl)); if (that.options.selectableOptgroup){ $selectableOptgroup.find('.ms-optgroup-label').on('click', function(){ var values = $optgroup.children(':not(:selected)').map(function(){ return $(this).val() }).get(); that.select(values); }); $selectionOptgroup.find('.ms-optgroup-label').on('click', function(){ var values = $optgroup.children(':selected').map(function(){ return $(this).val() }).get(); that.deselect(values); }); } that.$selectableUl.append($selectableOptgroup); that.$selectionUl.append($selectionOptgroup); } $selectableOptgroup.children().append(selectableLi); $selectionOptgroup.children().append(selectedLi); } else { that.$selectableUl.append(selectableLi); that.$selectionUl.append(selectedLi); } }, 'activeKeyboard' : function($list){ var that = this; $list.on('focus', function(){ $(this).addClass('ms-focus'); }) .on('blur', function(){ $(this).removeClass('ms-focus'); }) .on('keydown', function(e){ switch (e.which) { case 40: case 38: e.preventDefault(); e.stopPropagation(); that.moveHighlight($(this), (e.which === 38) ? -1 : 1); return; case 37: case 39: e.preventDefault(); e.stopPropagation(); that.switchList($list); return; case 9: if(that.$element.is('[tabindex]')){ e.preventDefault(); var tabindex = parseInt(that.$element.attr('tabindex'), 10); tabindex = (e.shiftKey) ? tabindex-1 : tabindex+1; $('[tabindex="'+(tabindex)+'"]').focus(); return; }else{ if(e.shiftKey){ that.$element.trigger('focus'); } } } if($.inArray(e.which, that.options.keySelect) > -1){ e.preventDefault(); e.stopPropagation(); that.selectHighlighted($list); return; } }); }, 'moveHighlight': function($list, direction){ var $elems = $list.find(this.elemsSelector), $currElem = $elems.filter('.ms-hover'), $nextElem = null, elemHeight = $elems.first().outerHeight(), containerHeight = $list.height(), containerSelector = '#'+this.$container.prop('id'); // Deactive mouseenter event when move is active // It fixes a bug when mouse is over the list $elems.off('mouseenter'); $elems.removeClass('ms-hover'); if (direction === 1){ // DOWN $nextElem = $currElem.nextAll(this.elemsSelector).first(); if ($nextElem.length === 0){ var $optgroupUl = $currElem.parent(); if ($optgroupUl.hasClass('ms-optgroup')){ var $optgroupLi = $optgroupUl.parent(), $nextOptgroupLi = $optgroupLi.next(':visible'); if ($nextOptgroupLi.length > 0){ $nextElem = $nextOptgroupLi.find(this.elemsSelector).first(); } else { $nextElem = $elems.first(); } } else { $nextElem = $elems.first(); } } } else if (direction === -1){ // UP $nextElem = $currElem.prevAll(this.elemsSelector).first(); if ($nextElem.length === 0){ var $optgroupUl = $currElem.parent(); if ($optgroupUl.hasClass('ms-optgroup')){ var $optgroupLi = $optgroupUl.parent(), $prevOptgroupLi = $optgroupLi.prev(':visible'); if ($prevOptgroupLi.length > 0){ $nextElem = $prevOptgroupLi.find(this.elemsSelector).last(); } else { $nextElem = $elems.last(); } } else { $nextElem = $elems.last(); } } } if ($nextElem.length > 0){ $nextElem.addClass('ms-hover'); var scrollTo = $list.scrollTop() + $nextElem.position().top - containerHeight / 2 + elemHeight / 2; $list.scrollTop(scrollTo); } }, 'selectHighlighted' : function($list){ var $elems = $list.find(this.elemsSelector), $highlightedElem = $elems.filter('.ms-hover').first(); if ($highlightedElem.length > 0){ if ($list.parent().hasClass('ms-selectable')){ this.select($highlightedElem.data('ms-value')); } else { this.deselect($highlightedElem.data('ms-value')); } $elems.removeClass('ms-hover'); } }, 'switchList' : function($list){ $list.blur(); if ($list.parent().hasClass('ms-selectable')){ this.$selectionUl.focus(); } else { this.$selectableUl.focus(); } }, 'activeMouse' : function($list){ var that = this; var lastMovedDom = false; $list.on('mousemove', function(){ if (lastMovedDom === this) return; lastMovedDom = this; var elems = $list.find(that.elemsSelector); elems.on('mouseenter', function(){ elems.removeClass('ms-hover'); $(this).addClass('ms-hover'); }); }); }, 'refresh' : function() { this.destroy(); this.$element.multiSelect(this.options); }, 'destroy' : function(){ $("#ms-"+this.$element.attr("id")).remove(); this.$element.removeData('multiselect'); }, 'select' : function(value, method){ if (typeof value === 'string'){ value = [value]; } var that = this, ms = this.$element, msIds = $.map(value, function(val){ return(that.sanitize(val, that.sanitizeRegexp)); }), selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'), options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); }); if (selectables.length > 0){ selectables.addClass('ms-selected').hide(); selections.addClass('ms-selected').show(); options.prop('selected', true); var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container'); if (selectableOptgroups.length > 0){ selectableOptgroups.each(function(){ var selectablesLi = $(this).find('.ms-elem-selectable'); if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){ $(this).find('.ms-optgroup-label').hide(); } }); var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container'); selectionOptgroups.each(function(){ var selectionsLi = $(this).find('.ms-elem-selection'); if (selectionsLi.filter('.ms-selected').length > 0){ $(this).find('.ms-optgroup-label').show(); } }); } else { if (that.options.keepOrder){ var selectionLiLast = that.$selectionUl.find('.ms-selected'); if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) { selections.insertAfter(selectionLiLast.last()); } } } if (method !== 'init'){ ms.trigger('change'); if (typeof that.options.afterSelect === 'function') { that.options.afterSelect.call(this, value); } } } }, 'deselect' : function(value){ if (typeof value === 'string'){ value = [value]; } var that = this, ms = this.$element, msIds = $.map(value, function(val){ return(that.sanitize(val, that.sanitizeRegexp)); }), selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'), selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected'), options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); }); if (selections.length > 0){ selectables.removeClass('ms-selected').show(); selections.removeClass('ms-selected').hide(); options.prop('selected', false); var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container'); if (selectableOptgroups.length > 0){ selectableOptgroups.each(function(){ var selectablesLi = $(this).find('.ms-elem-selectable'); if (selectablesLi.filter(':not(.ms-selected)').length > 0){ $(this).find('.ms-optgroup-label').show(); } }); var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container'); selectionOptgroups.each(function(){ var selectionsLi = $(this).find('.ms-elem-selection'); if (selectionsLi.filter('.ms-selected').length === 0){ $(this).find('.ms-optgroup-label').hide(); } }); } ms.trigger('change'); if (typeof that.options.afterDeselect === 'function') { that.options.afterDeselect.call(this, value); } } }, 'select_all' : function(){ var ms = this.$element, values = ms.val(); ms.find('option:not(":disabled")').prop('selected', true); this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide(); this.$selectionUl.find('.ms-optgroup-label').show(); this.$selectableUl.find('.ms-optgroup-label').hide(); this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show(); this.$selectionUl.focus(); ms.trigger('change'); if (typeof this.options.afterSelect === 'function') { var selectedValues = $.grep(ms.val(), function(item){ return $.inArray(item, values) < 0; }); this.options.afterSelect.call(this, selectedValues); } }, 'deselect_all' : function(){ var ms = this.$element, values = ms.val(); ms.find('option').prop('selected', false); this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show(); this.$selectionUl.find('.ms-optgroup-label').hide(); this.$selectableUl.find('.ms-optgroup-label').show(); this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide(); this.$selectableUl.focus(); ms.trigger('change'); if (typeof this.options.afterDeselect === 'function') { this.options.afterDeselect.call(this, values); } }, sanitize: function(value, reg){ return(value.replace(reg, '_')); } }; /* MULTISELECT PLUGIN DEFINITION * ======================= */ $.fn.multiSelect = function () { var option = arguments[0], args = arguments; return this.each(function () { var $this = $(this), data = $this.data('multiselect'), options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option); if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); } if (typeof option === 'string'){ data[option](args[1]); } else { data.init(); } }); }; $.fn.multiSelect.defaults = { keySelect: [32], selectableOptgroup: false, disabledClass : 'disabled', dblClick : false, keepOrder: false }; $.fn.multiSelect.Constructor = MultiSelect; }(window.jQuery);
jvvlimme/www.zenstore.dev
wp-content/plugins/codespacing-progress-map/js/jquery.multi-select.js
JavaScript
gpl-2.0
17,428
import { computed, toRefs } from '@vue/composition-api' export const useInputValueToggleProps = { label: { type: String }, options: { type: Array, default: () => ([ { value: 0 }, { value: 1, color: 'var(--primary)' } ]) }, hints: { type: Array } } export const useInputValueToggle = (valueProps, props, context) => { const { value: rxValue, onInput: rxOnInput } = valueProps const { options } = toRefs(props) // middleware const txValue = computed(() => options.value.findIndex(map => { if (!map.value && !rxValue.value) return true // compare False(y) w/ [null|undefined] else return `${map.value}` === `${rxValue.value}` // compare String(s) })) const txOnInput = value => { const { 0: { value: defaultValue } = {}, // 0th option is default [value]: { value: mappedValue } = {}, // map value (N) w/ Nth option [value]: { promise: mappedPromise } = {} // map promise } = options.value const rxValue = (mappedValue !== undefined) ? mappedValue : defaultValue if (mappedPromise) // handle Promise return mappedPromise(rxValue, props, context) else // otherwise emit return rxOnInput(rxValue) } // state const max = computed(() => `${options.value.length - 1}`) const label = computed(() => { const { 0: { label: defaultLabel } = {} , [txValue.value]: { label: mappedLabel } = {} } = options.value return mappedLabel || defaultLabel }) const color = computed(() => { const { 0: { color: defaultColor } = {} , [txValue.value]: { color: mappedColor } = {} } = options.value return mappedColor || defaultColor }) const icon = computed(() => { const { 0: { icon: defaultIcon } = {} , [txValue.value]: { icon: mappedIcon } = {} } = options.value return mappedIcon || defaultIcon }) const tooltip = computed(() => { const { 0: { tooltip: defaultTooltip } = {} , [txValue.value]: { tooltip: mappedTooltip } = {} } = options.value return mappedTooltip || defaultTooltip }) return { // middleware value: txValue, onInput: txOnInput, // state max, label, color, icon, tooltip } }
inverse-inc/packetfence
html/pfappserver/root/src/composables/useInputValueToggle.js
JavaScript
gpl-2.0
2,215
var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var bodyParser = require('body-parser') var chip = require('../../chip.js'); var Syndicate = require('../../model/syndicate'); var Account = require('../../model/account'); var Group = require('../../model/group'); var Engine = require('../../model/engine'); var util = require('../../lib/util'); module.exports = function(face, rootPath) { face.post('/api/register', bodyParser.json(), bodyParser.urlencoded(), register); face.get('/groups/:token', function(req, res) { res.sendFile(rootPath + 'assets/static/groups.html'); }); face.get('/api/groups/:token', function(req, res) { Account.getByToken(req.params.token).then(function(account) { return Engine.get(account.eid); }).then(function(engine) { var e = chip.getEngine(engine.sid); // I dunno what's going on here, but sometimes this gets weird e.loadGroups().then(function() { res.json({ synd: e.synd, groups: e.groups }); }); }); }); face.route('/api/group/:gid') .get(getGroup) .post(bodyParser.json(), bodyParser.urlencoded(), updateGroup, getGroup); face.put('/api/group', createGroup); }; function register(req, res) { return Syndicate.getByName(req.body.synd).then(function(synd) { if (synd) { return Engine.getBySynd(synd.sid).then(function(engine) { if (engine) { res.json({ error: 'Syndicate already registered' }); } else { var e = Engine.create({ sid: synd.sid }); var token = Math.random().toString(36).slice(2); return e.save().then(function() { return chip.db.queryAsync('INSERT INTO account SET ?', { email: req.body.email, eid: e.eid, token: token }); }).then(function(result) { chip.addEngine(e); res.json({ token: token }); }); } }); } else { res.json({ error: 'Syndicate not found' }); } }) }; function getGroup(req, res) { return Group.get(req.params.gid).then(function(group) { var g = chip.getGroup(group.groupme_id); res.json(g); }) } function createGroup(req, res) { var g = Group.create({ sid: req.body.sid, groupme_id: req.body.groupme_id, bot_key: req.body.bot_key, output: req.body.output == 'true', scout: req.body.scout == 'true', debug: req.body.debug == 'true' }); return g.save().then(function() { req.params.gid = g.gid; chip.addGroup(g); res.json(g); }); } function updateGroup(req, res, next) { return Group.get(req.params.gid).then(function(group) { var g = chip.getGroup(group.groupme_id); if (g) chip.removeGroup(g.groupme_id); else g = group; g.groupme_id = req.body.groupme_id; g.bot_key = req.body.bot_key; g.bot_id = null; g.output = req.body.output == 'true'; g.scout = req.body.scout == 'true'; g.debug = req.body.debug == 'true'; return g.save().then(function() { delete g.bot_id; g.getEngine().loadGroups().then(function() { res.json(g); }); }); }); } passport.use(new LocalStrategy( function(key, password, done) { //chip.db.queryAsync( /* connection.query("SELECT * FROM player p WHERE sid IS NOT NULL AND name='"+username+"'", function(err, result) { if (err) throw err; if (result.length > 0 && password == 'oredic37') { var player = User.createPlayer(result[0]); done(null, player); } else { done(null, null, { message: 'Invalid login' }); } }); */ }) ); passport.serializeUser(function(player, done) { done(null, player.pid); }); passport.deserializeUser(function(pid, done) { User.getUser(pid).then(function(user) { done(null, user); }); }); function loggedIn(req, res, next) { if (req.isAuthenticated()) { next(); } else { req.session.loginRedirect = req.url; res.redirect('/'); } }
uzrbin/chip
src/face/routes/account.js
JavaScript
gpl-2.0
3,788
/* general map generation class Since September 2013 | [email protected] This code is provided as-is under the GPL v2 licence, which is available via http://www.gnu.org/licenses/gpl-2.0.html, and may be freely used, adapted and built upon. No guarantee is provided or implied. Test your code! http://www.gnu.org/licenses/gpl.html Simplify generation of Google Maps on a web page The existing default usage via Google's own implementation is great, but this version adds an improved overlay function, the option to add MarkerLabel functionality by setting an option to true, and much easier addition of custom map styles. • Labels are displayed with the markers. Label content is displayed directly in the map. • Markercontent is displayed in the overlay when a marker is clicked. • The current implementation (July 2015) requires that markerclusterer_compiled.js and markerwithlabel_packed.js be linked in the HTML head if you need to use this functionality. This file is quite heavy and heavily commented. Use class.googlemaps.min.js instead. See class.googlemaps.html for a demo of how to use this script with a couple of simple options. */ var mhmli_googlemaps_rootclass, MarkerWithLabel, marker, bounds, mhmli_googlemaps, google, customStyle; (function($){ mhmli_googlemaps = { map: null, mapContainer: null, infowindow: null, infowindowContent: null, locations: [], pins: [], map_clustered: null, //////////////////////////////////////////////////////////////////////////////// // Options. Can be reset externally before drawing the map. text: { reset: 'Reset', close: 'Close' }, asset_path:'', pin_default: function(){ return null; }, useStyledMarkers: false, options: { cluster: false, // cluster markers together, when there are too many to be displayed in one go clusterstyles: null, // array containing custom attributes for the MarkerClusterer object. e.g. styles. mapTypeID: null, // e,g. google.maps.MapTypeId.HYBRID mapTypes: null, // array of types google.maps.MapTypeId lat_default: 46.817918, // default latitude lon_default: 8.227386, // default longitude zoomlevel_start: 7, // default zoom level zoomlevel_default: 7, // default zoom level zoomlevel_near: 10, // if map zooms when clicking on a marker, the zoom level to go to zoomlevel_minimum: 1, // don't let the user zoom out to more than this zoom level focus_centre: true, // when clicking on a marker, should the map centre itself on the clicked marker showLabels: false, // should labels be added to the markers? fitToBounds: false, // should the map automatically set itself to include all markers in the default view? hasInfoWindow: true, // does an infowindow appear when clicking on a marker focus_zoom: true, // when clicking on a marker, should the map zoom in to the clicked marker icon_offset: [0,0], // default icon offset icon_size: [16,16], // default icon size icon: null // optional: use your own icon }, controls: { // these options are here in order to comply with Google logic for separating controls and other options blockUI: false, // completely block all UI options including zoom, scroll etc resetbutton:true, // add a reset button to the map? visualRefresh:true, // use the new Google Maps (Summer 2013) - https://developers.google.com/maps/documentation/javascript/basics#VisualRefresh disableDefaultUI: false, // disable all default map features with one command panControl: false, // enable/disable pan controls mapTypeControl: false, // enable/disable map type controls scaleControl: true, // enable/disable scaling (zoom) controls streetViewControl: false, // enable/disable street view control overviewMapControl: false, // enable/disable overview control (bottom right; small controller to see where current section of map is, in relation to e.g. Europe) zoomControl: true, // enable/disable zoom control. if zoomControlOptions are set, they will override this option. zoomControlOptions: { // customization of individual zoom control options - https://developers.google.com/maps/documentation/javascript/controls#ControlOptions style: null, position:null } }, //////////////////////////////////////////////////////////////////////////////// setMapStyle: function(mapStyle) { if (mapStyle && mapStyle!==null) { if(this.options.mapTypes && this.options.mapTypes.length){ this.options.mapTypes.push(customStyle); } var customStyle = new google.maps.StyledMapType( mapStyle, { name: 'customStyle' }); this.map.mapTypes.set('customStyle', customStyle); this.map.setMapTypeId('customStyle'); } },//setMapStyle //////////////////////////////////////////////////////////////////////////////// Marker: function(atts) { if(atts.baseClass.options.showLabels){ marker = new MarkerWithLabel({ position: atts.position, zIndex: atts.zIndex, map: atts.map, icon: atts.icon, labelContent: atts.labelContent, markerContent: atts.markerContent, labelAnchor: new google.maps.Point(12,8), title: atts.title, locationID: atts.locationID }); }else{ marker = new google.maps.Marker({ position: atts.position, zIndex: atts.zIndex, map: atts.map, icon: atts.icon, labelContent: atts.labelContent, markerContent: atts.markerContent, title: atts.title, locationID: atts.locationID }); } marker.baseClass = atts.baseClass; return marker; },//Marker //////////////////////////////////////////////////////////////////////////////// makeMap: function(divID, layout) { if(this.controls.visualRefresh){ google.maps.visualRefresh = true; } this.mapContainer = $('#'+divID); var mapOptions = { zoom: this.options.zoomlevel_default, center: this.centrePoint(), panControl: this.controls.panControl, mapTypeControl: this.controls.mapTypeControl, scaleControl: this.controls.scaleControl, streetViewControl: this.controls.streetViewControl, overviewMapControl: this.controls.overviewMapControl, zoomControl: this.controls.zoomControl, zoomControlOptions: this.controls.zoomControlOptions }; if(this.options.mapTypes && this.options.mapTypes.length){ mapOptions.mapTypeControlOptions = { mapTypeIds: this.options.mapTypes }; mapOptions.mapTypeControl = true; } if(this.options.mapTypeID){ mapOptions.mapTypeId = this.options.mapTypeID; } if(this.controls.disableDefaultUI){ mapOptions.disableDefaultUI = true; } if(this.controls.blockUI){ mapOptions.draggable = false; mapOptions.zoomable = false; mapOptions.scrollwheel = false; mapOptions.navigationControl = false; mapOptions.mapTypeControl = false; mapOptions.scaleControl = false; mapOptions.draggable = false; } this.map = new google.maps.Map(document.getElementById(divID), mapOptions); this.map.setZoom(this.options.zoomlevel_start); this.setMapStyle(layout); if(this.options.fitToBounds){ bounds = new google.maps.LatLngBounds(); } var marker, i, baseClass=this, markers = []; for (i in this.locations) { if(this.locations.hasOwnProperty(i)){ var rp = this.locations[i].rankedPosition; marker = new this.Marker({ //map: this.map, position: new google.maps.LatLng(this.locations[i].longitude, this.locations[i].latitude), title: this.locations[i].title, labelContent: this.locations[i].labelContent, markerContent: this.locations[i].markerContent, rankedPosition: rp + '', zIndex: 10000 - i, locationID: this.locations[i].locationID, icon: this.options.icon, baseClass: this }); if(this.locations[i] && this.locations[i].icon){ var icon_offset = this.locations[i].offset ? this.locations[i].offset : this.options.icon_offset; var icon_size = this.locations[i].icon_size ? this.locations[i].icon_size : this.options.icon_size; marker.setIcon({ url: this.locations[i].icon, anchor: new google.maps.Point(icon_offset[0],icon_offset[1]), size: new google.maps.Size(icon_size[0], icon_size[1]) }); } if(this.options.fitToBounds){ bounds.extend(marker.position); } google.maps.event.addListener(marker, 'click', function(event){ baseClass.markerClickHandler(event,this,baseClass); }); markers.push(marker); } } google.maps.event.addListener(this.map, 'zoom_changed', function() { if (baseClass.map.getZoom() < baseClass.options.zoomlevel_minimum){ baseClass.map.setZoom(baseClass.options.zoomlevel_minimum); } }); if(this.options.cluster){ var markerClustererExtras = this.options.clusterstyles ? {styles:this.options.clusterstyles} : {}; this.map_clustered = new MarkerClusterer(this.map, markers, markerClustererExtras); }else{ for (var i = 0; i < markers.length; i++) { markers[i].setMap(this.map); } } if(this.options.fitToBounds){ this.map.fitBounds(bounds); } this.addResetButton(); this.monitorEscapeButton(); },//makeMap //////////////////////////////////////////////////////////////////////////////// centrePoint: function(){ return new google.maps.LatLng(this.options.lat_default, this.options.lon_default); },//centrePoint //////////////////////////////////////////////////////////////////////////////// resetMap: function(){ this.hideOverlay(); this.map.setZoom(this.options.zoomlevel_default); this.map.setCenter(this.centrePoint()); },//resetMap //////////////////////////////////////////////////////////////////////////////// markerClickHandler: function(event,marker,baseClass){ if(baseClass.options.focus_centre){ baseClass.map.panTo(marker.getPosition()); } if(baseClass.options.focus_zoom){ var currentZoom = baseClass.map.getZoom(); if(currentZoom < baseClass.options.zoomlevel_near){ baseClass.map.setZoom(baseClass.options.zoomlevel_near); } } if(baseClass.options.hasInfoWindow){ baseClass.showOverlay(baseClass.map, marker); } },//markerClickHandler //////////////////////////////////////////////////////////////////////////////// showOverlay: function(map,marker){ if(!this.infowindow){ this.infowindow = $('<div class="overlay window"><div class="wrapper"><div class="inner"><a class="close button" href="#">' +this.text.close+ '</a><div class="content"></div></div></div></div>'); this.infowindowContent = this.infowindow.find('div.content'); var mhmli_googlemaps_rootclass = this; this.infowindow.find('a.close').click(function(e){ e.preventDefault(); mhmli_googlemaps_rootclass.hideOverlay(); }); this.mapContainer.append(this.infowindow); } this.fillOverlay(marker.markerContent); this.infowindow.show(); },//showOverlay //////////////////////////////////////////////////////////////////////////////// fillOverlay: function(content){ if(this.infowindowContent){ this.infowindowContent.html(content); } },//fillOverlay //////////////////////////////////////////////////////////////////////////////// hideOverlay: function(){ if(this.infowindow){ this.infowindowContent.empty(); this.infowindow.hide(); } },//hideOverlay //////////////////////////////////////////////////////////////////////////////// addResetButton: function(){ if(this.controls.resetbutton){ this.resetButton = $('<button class="reset">' +this.text.reset+ '</button>'); baseClass=this; this.resetButton.click(function(event){ baseClass.resetMap(); }); $(this.map.b).append(this.resetButton); } },//addResetButton //////////////////////////////////////////////////////////////////////////////// monitorEscapeButton: function(){ mhmli_googlemaps_rootclass = this; $(document).keydown(function(e) { if(e.keyCode === 27 && mhmli_googlemaps_rootclass.hideOverlay){ mhmli_googlemaps_rootclass.hideOverlay(); } }); }//monitorEscapeButton }; })(jQuery);
mhmli/mhmli_googlemaps
general class/class.googlemaps.js
JavaScript
gpl-2.0
12,311
module.exports = { user : 'Your Github Username', cal : 'Google calendar id to update' };
mike-audi/gh-gcal
example.config.js
JavaScript
gpl-2.0
92
/** * Util of json ajax. * author: firstboy * require: jquery */ function Jsoncallback(url, callback, method, data, loadid) { if (loadid) $('#'+loadid).fadeIn(200); $.ajax({ type: method, data: data, scriptCharset: 'UTF-8', dataType: 'json', url: url, success: function(json) { if (loadid) $('#'+loadid).fadeOut(200); callback(json); }, error: function(json, textStatus, errorThrown) { if (loadid) $('#'+loadid).fadeOut(200); alert('[ERROR] -- JSON CALLBACK:\n' + '[ERROR:textStatus]: ' + textStatus + '[ERROR:errorThrown]: ' + errorThrown + '[ERROR:json.responseText]: ' + json.responseText); } }); } function getURLParameter(name) { return decodeURI( (RegExp(name + "=" + "(.+?)(&|$)").exec(location.search)||[,null])[1] ); } function addslashes(string) { return string.replace(/\\/g, '\\\\'). replace(/\u0008/g, '\\b'). replace(/\t/g, '\\t'). replace(/\n/g, '\\n'). replace(/\f/g, '\\f'). replace(/\r/g, '\\r'). replace(/'/g, '\\\''). replace(/"/g, '\\"'); } function trim(str){ return str.replace(/(^\s*)|(\s*$)/g, ""); } function ltrim(str){ return str.replace(/(^\s*)/g,""); } function rtrim(str){ return str.replace(/(\s*$)/g,""); }
firstboy0513/lexstat
cgi/js/util.js
JavaScript
gpl-2.0
1,281
/*! Responsive JS Library v1.2.2 */ /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ /*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */ window.matchMedia = window.matchMedia || (function(doc, undefined){ var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, // fakeBody required for <FF4 when executed in <head> fakeBody = doc.createElement('body'), div = doc.createElement('div'); div.id = 'mq-test-1'; div.style.cssText = "position:absolute;top:-100em"; fakeBody.style.background = "none"; fakeBody.appendChild(div); return function(q){ div.innerHTML = '&shy;<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>'; docElem.insertBefore(fakeBody, refNode); bool = div.offsetWidth == 42; docElem.removeChild(fakeBody); return { matches: bool, media: q }; }; })(document); /*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ (function( win ){ //exposed namespace win.respond = {}; //define update even in native-mq-supporting browsers, to avoid errors respond.update = function(){}; //expose media query support flag for external use respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches; //if media queries are supported, exit here if( respond.mediaQueriesSupported ){ return; } //define vars var doc = win.document, docElem = doc.documentElement, mediastyles = [], rules = [], appendedEls = [], parsedSheets = {}, resizeThrottle = 30, head = doc.getElementsByTagName( "head" )[0] || docElem, base = doc.getElementsByTagName( "base" )[0], links = head.getElementsByTagName( "link" ), requestQueue = [], //loop stylesheets, send text content to translate ripCSS = function(){ var sheets = links, sl = sheets.length, i = 0, //vars for loop: sheet, href, media, isCSS; for( ; i < sl; i++ ){ sheet = sheets[ i ], href = sheet.href, media = sheet.media, isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet"; //only links plz and prevent re-parsing if( !!href && isCSS && !parsedSheets[ href ] ){ // selectivizr exposes css through the rawCssText expando if (sheet.styleSheet && sheet.styleSheet.rawCssText) { translate( sheet.styleSheet.rawCssText, href, media ); parsedSheets[ href ] = true; } else { if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base) || href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){ requestQueue.push( { href: href, media: media } ); } } } } makeRequests(); }, //recurse through request queue, get css text makeRequests = function(){ if( requestQueue.length ){ var thisRequest = requestQueue.shift(); ajax( thisRequest.href, function( styles ){ translate( styles, thisRequest.href, thisRequest.media ); parsedSheets[ thisRequest.href ] = true; makeRequests(); } ); } }, //find media blocks in css text, convert to style blocks translate = function( styles, href, media ){ var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ), ql = qs && qs.length || 0, //try to get CSS path href = href.substring( 0, href.lastIndexOf( "/" )), repUrls = function( css ){ return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" ); }, useMedia = !ql && media, //vars used in loop i = 0, j, fullq, thisq, eachq, eql; //if path exists, tack on trailing slash if( href.length ){ href += "/"; } //if no internal queries exist, but media attr does, use that //note: this currently lacks support for situations where a media attr is specified on a link AND //its associated stylesheet has internal CSS media queries. //In those cases, the media attribute will currently be ignored. if( useMedia ){ ql = 1; } for( ; i < ql; i++ ){ j = 0; //media attr if( useMedia ){ fullq = media; rules.push( repUrls( styles ) ); } //parse for styles else{ fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1; rules.push( RegExp.$2 && repUrls( RegExp.$2 ) ); } eachq = fullq.split( "," ); eql = eachq.length; for( ; j < eql; j++ ){ thisq = eachq[ j ]; mediastyles.push( { media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all", rules : rules.length - 1, hasquery: thisq.indexOf("(") > -1, minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ), maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ) } ); } } applyMedia(); }, lastCall, resizeDefer, // returns the value of 1em in pixels getEmValue = function() { var ret, div = doc.createElement('div'), body = doc.body, fakeUsed = false; div.style.cssText = "position:absolute;font-size:1em;width:1em"; if( !body ){ body = fakeUsed = doc.createElement( "body" ); body.style.background = "none"; } body.appendChild( div ); docElem.insertBefore( body, docElem.firstChild ); ret = div.offsetWidth; if( fakeUsed ){ docElem.removeChild( body ); } else { body.removeChild( div ); } //also update eminpx before returning ret = eminpx = parseFloat(ret); return ret; }, //cached container for 1em value, populated the first time it's needed eminpx, //enable/disable styles applyMedia = function( fromResize ){ var name = "clientWidth", docElemProp = docElem[ name ], currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp, styleBlocks = {}, lastLink = links[ links.length-1 ], now = (new Date()).getTime(); //throttle resize calls if( fromResize && lastCall && now - lastCall < resizeThrottle ){ clearTimeout( resizeDefer ); resizeDefer = setTimeout( applyMedia, resizeThrottle ); return; } else { lastCall = now; } for( var i in mediastyles ){ var thisstyle = mediastyles[ i ], min = thisstyle.minw, max = thisstyle.maxw, minnull = min === null, maxnull = max === null, em = "em"; if( !!min ){ min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); } if( !!max ){ max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 ); } // if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){ if( !styleBlocks[ thisstyle.media ] ){ styleBlocks[ thisstyle.media ] = []; } styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] ); } } //remove any existing respond style element(s) for( var i in appendedEls ){ if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){ head.removeChild( appendedEls[ i ] ); } } //inject active styles, grouped by media type for( var i in styleBlocks ){ var ss = doc.createElement( "style" ), css = styleBlocks[ i ].join( "\n" ); ss.type = "text/css"; ss.media = i; //originally, ss was appended to a documentFragment and sheets were appended in bulk. //this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one! head.insertBefore( ss, lastLink.nextSibling ); if ( ss.styleSheet ){ ss.styleSheet.cssText = css; } else { ss.appendChild( doc.createTextNode( css ) ); } //push to appendedEls to track for later removal appendedEls.push( ss ); } }, //tweaked Ajax functions from Quirksmode ajax = function( url, callback ) { var req = xmlHttp(); if (!req){ return; } req.open( "GET", url, true ); req.onreadystatechange = function () { if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){ return; } callback( req.responseText ); } if ( req.readyState == 4 ){ return; } req.send( null ); }, //define ajax obj xmlHttp = (function() { var xmlhttpmethod = false; try { xmlhttpmethod = new XMLHttpRequest(); } catch( e ){ xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" ); } return function(){ return xmlhttpmethod; }; })(); //translate CSS ripCSS(); //expose update for re-running respond later on respond.update = ripCSS; //adjust on resize function callMedia(){ applyMedia( true ); } if( win.addEventListener ){ win.addEventListener( "resize", callMedia, false ); } else if( win.attachEvent ){ win.attachEvent( "onresize", callMedia ); } })(this); /** * jQuery Scroll Top Plugin 1.0.0 */ jQuery(document).ready(function ($) { $('a[href=#scroll-top]').click(function () { $('html, body').animate({ scrollTop: 0 }, 'slow'); return false; }); }); /*! http://mths.be/placeholder v2.0.7 by @mathias */ ;(function(window, document, $) { var isInputSupported = 'placeholder' in document.createElement('input'), isTextareaSupported = 'placeholder' in document.createElement('textarea'), prototype = $.fn, valHooks = $.valHooks, hooks, placeholder; if (isInputSupported && isTextareaSupported) { placeholder = prototype.placeholder = function() { return this; }; placeholder.input = placeholder.textarea = true; } else { placeholder = prototype.placeholder = function() { var $this = this; $this .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]') .not('.placeholder') .bind({ 'focus.placeholder': clearPlaceholder, 'blur.placeholder': setPlaceholder }) .data('placeholder-enabled', true) .trigger('blur.placeholder'); return $this; }; placeholder.input = isInputSupported; placeholder.textarea = isTextareaSupported; hooks = { 'get': function(element) { var $element = $(element); return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value; }, 'set': function(element, value) { var $element = $(element); if (!$element.data('placeholder-enabled')) { return element.value = value; } if (value == '') { element.value = value; // Issue #56: Setting the placeholder causes problems if the element continues to have focus. if (element != document.activeElement) { // We can't use `triggerHandler` here because of dummy text/password inputs :( setPlaceholder.call(element); } } else if ($element.hasClass('placeholder')) { clearPlaceholder.call(element, true, value) || (element.value = value); } else { element.value = value; } // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363 return $element; } }; isInputSupported || (valHooks.input = hooks); isTextareaSupported || (valHooks.textarea = hooks); $(function() { // Look for forms $(document).delegate('form', 'submit.placeholder', function() { // Clear the placeholder values so they don't get submitted var $inputs = $('.placeholder', this).each(clearPlaceholder); setTimeout(function() { $inputs.each(setPlaceholder); }, 10); }); }); // Clear placeholder values upon page reload $(window).bind('beforeunload.placeholder', function() { $('.placeholder').each(function() { this.value = ''; }); }); } function args(elem) { // Return an object of element attributes var newAttrs = {}, rinlinejQuery = /^jQuery\d+$/; $.each(elem.attributes, function(i, attr) { if (attr.specified && !rinlinejQuery.test(attr.name)) { newAttrs[attr.name] = attr.value; } }); return newAttrs; } function clearPlaceholder(event, value) { var input = this, $input = $(input); if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) { if ($input.data('placeholder-password')) { $input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id')); // If `clearPlaceholder` was called from `$.valHooks.input.set` if (event === true) { return $input[0].value = value; } $input.focus(); } else { input.value = ''; $input.removeClass('placeholder'); input == document.activeElement && input.select(); } } } function setPlaceholder() { var $replacement, input = this, $input = $(input), $origInput = $input, id = this.id; if (input.value == '') { if (input.type == 'password') { if (!$input.data('placeholder-textinput')) { try { $replacement = $input.clone().attr({ 'type': 'text' }); } catch(e) { $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' })); } $replacement .removeAttr('name') .data({ 'placeholder-password': true, 'placeholder-id': id }) .bind('focus.placeholder', clearPlaceholder); $input .data({ 'placeholder-textinput': $replacement, 'placeholder-id': id }) .before($replacement); } $input = $input.removeAttr('id').hide().prev().attr('id', id).show(); // Note: `$input[0] != input` now! } $input.addClass('placeholder'); $input[0].value = $input.attr('placeholder'); } else { $input.removeClass('placeholder'); } } }(this, document, jQuery)); /*global jQuery */ /*jshint multistr:true browser:true */ /*! * FitVids 1.0 * * Copyright 2011, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/ * Released under the WTFPL license - http://sam.zoy.org/wtfpl/ * * Date: Thu Sept 01 18:00:00 2011 -0500 */ (function( $ ){ "use strict"; $.fn.fitVids = function( options ) { var settings = { customSelector: null }; var div = document.createElement('div'), ref = document.getElementsByTagName('base')[0] || document.getElementsByTagName('script')[0]; div.className = 'fit-vids-style'; div.innerHTML = '&shy;<style> \ .fluid-width-video-wrapper { \ width: 100%; \ position: relative; \ padding: 0; \ } \ \ .fluid-width-video-wrapper iframe, \ .fluid-width-video-wrapper object, \ .fluid-width-video-wrapper embed { \ position: absolute; \ top: 0; \ left: 0; \ width: 100%; \ height: 100%; \ } \ </style>'; ref.parentNode.insertBefore(div,ref); if ( options ) { $.extend( settings, options ); } return this.each(function(){ var selectors = [ "iframe[src*='player.vimeo.com']", "iframe[src*='www.youtube.com']", "iframe[src*='www.youtube-nocookie.com']", "iframe[src*='fast.wistia.com']", "embed" ]; if (settings.customSelector) { selectors.push(settings.customSelector); } var $allVideos = $(this).find(selectors.join(',')); $allVideos.each(function(){ var $this = $(this); if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; } var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(), width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(), aspectRatio = height / width; if(!$this.attr('id')){ var videoID = 'fitvid' + Math.floor(Math.random()*999999); $this.attr('id', videoID); } $this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%"); $this.removeAttr('height').removeAttr('width'); }); }); }; })( jQuery ); /*! * Mobile Menu */ (function($) { var current = $('.main-nav li.current-menu-item a').html(); current = $('.main-nav li.current_page_item a').html(); if( $('span').hasClass('custom-mobile-menu-title') ) { current = $('span.custom-mobile-menu-title').html(); } else if( typeof current == 'undefined' || current === null ) { if( $('body').hasClass('home') ) { if( $('#logo span').hasClass('site-name') ) { current = $('#logo .site-name a').html(); } else { current = $('#logo img').attr('alt'); } } else { if( $('body').hasClass('woocommerce') ) { current = $('h1.page-title').html(); } else if( $('body').hasClass('archive') ) { current = $('h6.title-archive').html(); } else if( $('body').hasClass('search-results') ) { current = $('h6.title-search-results').html(); } else if( $('body').hasClass('page-template-blog-excerpt-php') ) { current = $('.current_page_item').text(); } else if( $('body').hasClass('page-template-blog-php') ) { current = $('.current_page_item').text(); } else { current = $('h1.post-title').html(); } } }; $('.main-nav').append('<a id="responsive_menu_button"></a>'); $('.main-nav').prepend('<div id="responsive_current_menu_item">Menu</div>'); $('a#responsive_menu_button, #responsive_current_menu_item').click(function(){ $('.js .main-nav .menu').slideToggle( function() { if( $(this).is(':visible') ) { $('a#responsive_menu_button').addClass('responsive-toggle-open'); } else { $('a#responsive_menu_button').removeClass('responsive-toggle-open'); $('.js .main-nav .menu').removeAttr('style'); } }); }); })(jQuery); // Close the mobile menu when clicked outside of it. (function($) { $('html').click(function() { // Check if the menu is open, close in that case. if( $('a#responsive_menu_button').hasClass('responsive-toggle-open') ){ $('.js .main-nav .menu').slideToggle( function() { $('a#responsive_menu_button').removeClass('responsive-toggle-open'); $('.js .main-nav .menu').removeAttr('style'); }); } }) })(jQuery); // Stop propagation on click on menu. jQuery('.main-nav').click(function(event){ var pathname = window.location.pathname; if( pathname != '/wp-admin/customize.php' ){ event.stopPropagation(); } }); // Placeholder jQuery(function(){ jQuery('input[placeholder], textarea[placeholder]').placeholder(); }); // FitVids jQuery(document).ready(function(){ // Target your #container, #wrapper etc. jQuery("#wrapper").fitVids(); }); // Have a custom video player? We now have a customSelector option where you can add your own specific video vendor selector (mileage may vary depending on vendor and fluidity of player): // jQuery("#thing-with-videos").fitVids({ customSelector: "iframe[src^='http://example.com'], iframe[src^='http://example.org']"}); // Selectors are comma separated, just like CSS // Note: This will be the quickest way to add your own custom vendor as well as test your player's compatibility with FitVids.
kevinreilly/ivsn-wp
wp-content/themes/responsive/core/js-dev/responsive-scripts.js
JavaScript
gpl-2.0
21,660
var http = require("http"), url = require("url"), path = require("path"), fs = require("fs"), DS = "/"; var settings = { port: 8080, indexFile: "index.html", folder: { serverside: "serverside", clientside: "clientside", static: "static_server", admin: "admin" } }; var paths = {}; paths.origin = process.cwd(); paths.base = paths.origin.slice(0, -1 * settings.folder.serverside.length - 1); paths.clientside = paths.base + DS + settings.folder.clientside; paths.serverside = paths.base + DS + settings.folder.serverside; paths.static = paths.base + DS + settings.folder.serverside + DS + settings.folder.static; clientside_exists = false; path.exists(paths.clientside, function(exists) { clientside_exists = exists; }); var static_server = http.createServer(function(request, response) { var uri = url.parse(request.url).pathname, filename; var DS_admin = DS + settings.folder.admin + DS; if (uri.slice(0, DS_admin.length) === DS_admin) { filename = path.join(paths.static, uri); } else if (clientside_exists) { filename = path.join(paths.clientside, uri); } else { filename = path.join(paths.origin, uri); } fs.exists(filename, function(exists) { if (!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); return; } if (fs.statSync(filename).isDirectory()) { var indexFound = false; var rawlist = fs.readdirSync(filename); var filelist = []; rawlist.forEach(function(element) { if (!fs.statSync(path.join(filename, element)).isDirectory() && !indexFound) { if (element === settings.indexFile) { indexFound = true; } else { filelist.push(element); } } }); if (filelist.length > 0 && !indexFound) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write(JSON.stringify(filelist)); response.end(); return; } filename = path.join(filename, settings.indexFile); } fs.readFile(filename, "binary", function(err, file) { if (err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); return; } response.writeHead(200); response.write(file, "binary"); response.end(); }); }); }); static_server.listen(parseInt(settings.port, 10)); module.exports = static_server;
ninjinx/nadeplanet
serverside/static_server/static_server.js
JavaScript
gpl-2.0
2,872
/*global gdn, jQuery*/ jQuery(($) => { const $preview = $('<div class="Preview"></div>') .insertBefore('#ConversationForm .bodybox-wrap, #Form_ConversationMessage .bodybox-wrap') .hide(); const $textbox = $('#ConversationForm textarea[name="Body"], #Form_ConversationMessage textarea[name="Body"]'); $('<a class="Button PreviewButton">' + gdn.getMeta('conversationsPreview.preview') + '</a>') .insertBefore('#ConversationForm input[type="submit"], #Form_ConversationMessage input[type="submit"]') .click(({target}) => { const $this = $(target); if ($this.hasClass('WriteButton')) { $preview.hide(); $textbox.show(); $this .addClass('PreviewButton') .removeClass('WriteButton') .text(gdn.getMeta('conversationsPreview.preview')); return; } gdn.disable($this); $this.toggleClass('PreviewButton').toggleClass('WriteButton'); $.post( gdn.url('messages/preview'), { Body: $this.closest('form').find('textarea[name="Body"]').val(), Format: $this.closest('form').find('input[name="Format"]').val(), TransientKey: gdn.definition('TransientKey') }, (data) => { $preview.html(data).show(); $textbox.hide(); $this .addClass('WriteButton') .removeClass('PreviewButton') .text(gdn.getMeta('conversationsPreview.edit')); $(document).trigger('PreviewLoaded'); }, 'html' ).always(() => { gdn.enable($this); }); }); $(document).on('MessageAdded', () => { $('.WriteButton').click(); }); });
bleistivt/conversationspreview
js/preview.js
JavaScript
gpl-2.0
1,997
(function (root, factory) { if (root === undefined && window !== undefined) root = window; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define('wavesurfer', [], function () { return (root['WaveSurfer'] = factory()); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { root['WaveSurfer'] = factory(); } }(this, function () { 'use strict'; var WaveSurfer = { defaultParams: { audioContext : null, audioRate : 1, autoCenter : true, backend : 'WebAudio', barHeight : 1, closeAudioContext: false, container : null, cursorColor : '#333', cursorWidth : 1, dragSelection : true, fillParent : true, forceDecode : false, height : 128, hideScrollbar : false, interact : true, loopSelection : true, mediaContainer: null, mediaControls : false, mediaType : 'audio', minPxPerSec : 20, partialRender : false, pixelRatio : window.devicePixelRatio || screen.deviceXDPI / screen.logicalXDPI, progressColor : '#555', normalize : false, renderer : 'MultiCanvas', scrollParent : false, skipLength : 2, splitChannels : false, waveColor : '#999', }, init: function (params) { // Extract relevant parameters (or defaults) this.params = WaveSurfer.util.extend({}, this.defaultParams, params); this.container = 'string' == typeof params.container ? document.querySelector(this.params.container) : this.params.container; if (!this.container) { throw new Error('Container element not found'); } if (this.params.mediaContainer == null) { this.mediaContainer = this.container; } else if (typeof this.params.mediaContainer == 'string') { this.mediaContainer = document.querySelector(this.params.mediaContainer); } else { this.mediaContainer = this.params.mediaContainer; } if (!this.mediaContainer) { throw new Error('Media Container element not found'); } // Used to save the current volume when muting so we can // restore once unmuted this.savedVolume = 0; // The current muted state this.isMuted = false; // Will hold a list of event descriptors that need to be // cancelled on subsequent loads of audio this.tmpEvents = []; // Holds any running audio downloads this.currentAjax = null; this.createDrawer(); this.createBackend(); this.createPeakCache(); this.isDestroyed = false; }, createDrawer: function () { var my = this; this.drawer = Object.create(WaveSurfer.Drawer[this.params.renderer]); this.drawer.init(this.container, this.params); this.drawer.on('redraw', function () { my.drawBuffer(); my.drawer.progress(my.backend.getPlayedPercents()); }); // Click-to-seek this.drawer.on('click', function (e, progress) { setTimeout(function () { my.seekTo(progress); }, 0); }); // Relay the scroll event from the drawer this.drawer.on('scroll', function (e) { if (my.params.partialRender) { my.drawBuffer(); } my.fireEvent('scroll', e); }); }, createBackend: function () { var my = this; if (this.backend) { this.backend.destroy(); } // Back compat if (this.params.backend == 'AudioElement') { this.params.backend = 'MediaElement'; } if (this.params.backend == 'WebAudio' && !WaveSurfer.WebAudio.supportsWebAudio()) { this.params.backend = 'MediaElement'; } this.backend = Object.create(WaveSurfer[this.params.backend]); this.backend.init(this.params); this.backend.on('finish', function () { my.fireEvent('finish'); }); this.backend.on('play', function () { my.fireEvent('play'); }); this.backend.on('pause', function () { my.fireEvent('pause'); }); this.backend.on('audioprocess', function (time) { my.drawer.progress(my.backend.getPlayedPercents()); my.fireEvent('audioprocess', time); }); }, createPeakCache: function() { if (this.params.partialRender) { this.peakCache = Object.create(WaveSurfer.PeakCache); this.peakCache.init(); } }, getDuration: function () { return this.backend.getDuration(); }, getCurrentTime: function () { return this.backend.getCurrentTime(); }, play: function (start, end) { this.fireEvent('interaction', this.play.bind(this, start, end)); this.backend.play(start, end); }, pause: function () { this.backend.isPaused() || this.backend.pause(); }, playPause: function () { this.backend.isPaused() ? this.play() : this.pause(); }, isPlaying: function () { return !this.backend.isPaused(); }, skipBackward: function (seconds) { this.skip(-seconds || -this.params.skipLength); }, skipForward: function (seconds) { this.skip(seconds || this.params.skipLength); }, skip: function (offset) { var position = this.getCurrentTime() || 0; var duration = this.getDuration() || 1; position = Math.max(0, Math.min(duration, position + (offset || 0))); this.seekAndCenter(position / duration); }, seekAndCenter: function (progress) { this.seekTo(progress); this.drawer.recenter(progress); }, seekTo: function (progress) { this.fireEvent('interaction', this.seekTo.bind(this, progress)); var paused = this.backend.isPaused(); // avoid draw wrong position while playing backward seeking if (!paused) { this.backend.pause(); } // avoid small scrolls while paused seeking var oldScrollParent = this.params.scrollParent; this.params.scrollParent = false; this.backend.seekTo(progress * this.getDuration()); this.drawer.progress(this.backend.getPlayedPercents()); if (!paused) { this.backend.play(); } this.params.scrollParent = oldScrollParent; this.fireEvent('seek', progress); }, stop: function () { this.pause(); this.seekTo(0); this.drawer.progress(0); }, /** * Set the playback volume. * * @param {Number} newVolume A value between 0 and 1, 0 being no * volume and 1 being full volume. */ setVolume: function (newVolume) { this.backend.setVolume(newVolume); }, /** * Get the playback volume. */ getVolume: function () { return this.backend.getVolume(); }, /** * Set the playback rate. * * @param {Number} rate A positive number. E.g. 0.5 means half the * normal speed, 2 means double speed and so on. */ setPlaybackRate: function (rate) { this.backend.setPlaybackRate(rate); }, /** * Get the playback rate. */ getPlaybackRate: function () { return this.backend.getPlaybackRate(); }, /** * Toggle the volume on and off. It not currenly muted it will * save the current volume value and turn the volume off. * If currently muted then it will restore the volume to the saved * value, and then rest the saved value. */ toggleMute: function () { this.setMute(!this.isMuted); }, setMute: function (mute) { // ignore all muting requests if the audio is already in that state if (mute === this.isMuted) { return; } if (mute) { // If currently not muted then save current volume, // turn off the volume and update the mute properties this.savedVolume = this.backend.getVolume(); this.backend.setVolume(0); this.isMuted = true; } else { // If currently muted then restore to the saved volume // and update the mute properties this.backend.setVolume(this.savedVolume); this.isMuted = false; } }, /** * Get the current mute status. */ getMute: function () { return this.isMuted; }, /** * Get the list of current set filters as an array. * * Filters must be set with setFilters method first */ getFilters: function() { return this.backend.filters || []; }, toggleScroll: function () { this.params.scrollParent = !this.params.scrollParent; this.drawBuffer(); }, toggleInteraction: function () { this.params.interact = !this.params.interact; }, drawBuffer: function () { var nominalWidth = Math.round( this.getDuration() * this.params.minPxPerSec * this.params.pixelRatio ); var parentWidth = this.drawer.getWidth(); var width = nominalWidth; var start = this.drawer.getScrollX(); var end = Math.min(start + parentWidth, width); // Fill container if (this.params.fillParent && (!this.params.scrollParent || nominalWidth < parentWidth)) { width = parentWidth; start = 0; end = width; } if (this.params.partialRender) { var newRanges = this.peakCache.addRangeToPeakCache(width, start, end); for (var i = 0; i < newRanges.length; i++) { var peaks = this.backend.getPeaks(width, newRanges[i][0], newRanges[i][1]); this.drawer.drawPeaks(peaks, width, newRanges[i][0], newRanges[i][1]); } } else { start = 0; end = width; var peaks = this.backend.getPeaks(width, start, end); this.drawer.drawPeaks(peaks, width, start, end); } this.fireEvent('redraw', peaks, width); }, zoom: function (pxPerSec) { this.params.minPxPerSec = pxPerSec; this.params.scrollParent = true; this.drawBuffer(); this.drawer.progress(this.backend.getPlayedPercents()); this.drawer.recenter( this.getCurrentTime() / this.getDuration() ); this.fireEvent('zoom', pxPerSec); }, /** * Internal method. */ loadArrayBuffer: function (arraybuffer) { this.decodeArrayBuffer(arraybuffer, function (data) { if (!this.isDestroyed) { this.loadDecodedBuffer(data); } }.bind(this)); }, /** * Directly load an externally decoded AudioBuffer. */ loadDecodedBuffer: function (buffer) { this.backend.load(buffer); this.drawBuffer(); this.fireEvent('ready'); }, /** * Loads audio data from a Blob or File object. * * @param {Blob|File} blob Audio data. */ loadBlob: function (blob) { var my = this; // Create file reader var reader = new FileReader(); reader.addEventListener('progress', function (e) { my.onProgress(e); }); reader.addEventListener('load', function (e) { my.loadArrayBuffer(e.target.result); }); reader.addEventListener('error', function () { my.fireEvent('error', 'Error reading file'); }); reader.readAsArrayBuffer(blob); this.empty(); }, /** * Loads audio and re-renders the waveform. */ load: function (url, peaks, preload) { this.empty(); this.isMuted = false; switch (this.params.backend) { case 'WebAudio': return this.loadBuffer(url, peaks); case 'MediaElement': return this.loadMediaElement(url, peaks, preload); } }, /** * Loads audio using Web Audio buffer backend. */ loadBuffer: function (url, peaks) { var load = (function (action) { if (action) { this.tmpEvents.push(this.once('ready', action)); } return this.getArrayBuffer(url, this.loadArrayBuffer.bind(this)); }).bind(this); if (peaks) { this.backend.setPeaks(peaks); this.drawBuffer(); this.tmpEvents.push(this.once('interaction', load)); } else { return load(); } }, /** * Either create a media element, or load * an existing media element. * @param {String|HTMLElement} urlOrElt Either a path to a media file, * or an existing HTML5 Audio/Video * Element * @param {Array} [peaks] Array of peaks. Required to bypass * web audio dependency */ loadMediaElement: function (urlOrElt, peaks, preload) { var url = urlOrElt; if (typeof urlOrElt === 'string') { this.backend.load(url, this.mediaContainer, peaks, preload); } else { var elt = urlOrElt; this.backend.loadElt(elt, peaks); // If peaks are not provided, // url = element.src so we can get peaks with web audio url = elt.src; } this.tmpEvents.push( this.backend.once('canplay', (function () { this.drawBuffer(); this.fireEvent('ready'); }).bind(this)), this.backend.once('error', (function (err) { this.fireEvent('error', err); }).bind(this)) ); // If no pre-decoded peaks provided or pre-decoded peaks are // provided with forceDecode flag, attempt to download the // audio file and decode it with Web Audio. if (peaks) { this.backend.setPeaks(peaks); } if ((!peaks || this.params.forceDecode) && this.backend.supportsWebAudio()) { this.getArrayBuffer(url, (function (arraybuffer) { this.decodeArrayBuffer(arraybuffer, (function (buffer) { this.backend.buffer = buffer; this.backend.setPeaks(null); this.drawBuffer(); this.fireEvent('waveform-ready'); }).bind(this)); }).bind(this)); } }, decodeArrayBuffer: function (arraybuffer, callback) { this.arraybuffer = arraybuffer; this.backend.decodeArrayBuffer( arraybuffer, (function (data) { // Only use the decoded data if we haven't been destroyed or another decode started in the meantime if (!this.isDestroyed && this.arraybuffer == arraybuffer) { callback(data); this.arraybuffer = null; } }).bind(this), this.fireEvent.bind(this, 'error', 'Error decoding audiobuffer') ); }, getArrayBuffer: function (url, callback) { var my = this; var ajax = WaveSurfer.util.ajax({ url: url, responseType: 'arraybuffer' }); this.currentAjax = ajax; this.tmpEvents.push( ajax.on('progress', function (e) { my.onProgress(e); }), ajax.on('success', function (data, e) { callback(data); my.currentAjax = null; }), ajax.on('error', function (e) { my.fireEvent('error', 'XHR error: ' + e.target.statusText); my.currentAjax = null; }) ); return ajax; }, onProgress: function (e) { if (e.lengthComputable) { var percentComplete = e.loaded / e.total; } else { // Approximate progress with an asymptotic // function, and assume downloads in the 1-3 MB range. percentComplete = e.loaded / (e.loaded + 1000000); } this.fireEvent('loading', Math.round(percentComplete * 100), e.target); }, /** * Exports PCM data into a JSON array and opens in a new window. */ exportPCM: function (length, accuracy, noWindow) { length = length || 1024; accuracy = accuracy || 10000; noWindow = noWindow || false; var peaks = this.backend.getPeaks(length, accuracy); var arr = [].map.call(peaks, function (val) { return Math.round(val * accuracy) / accuracy; }); var json = JSON.stringify(arr); if (!noWindow) { window.open('data:application/json;charset=utf-8,' + encodeURIComponent(json)); } return json; }, /** * Save waveform image as data URI. * * The default format is 'image/png'. Other supported types are * 'image/jpeg' and 'image/webp'. */ exportImage: function(format, quality) { if (!format) { format = 'image/png'; } if (!quality) { quality = 1; } return this.drawer.getImage(format, quality); }, cancelAjax: function () { if (this.currentAjax) { this.currentAjax.xhr.abort(); this.currentAjax = null; } }, clearTmpEvents: function () { this.tmpEvents.forEach(function (e) { e.un(); }); }, /** * Display empty waveform. */ empty: function () { if (!this.backend.isPaused()) { this.stop(); this.backend.disconnectSource(); } this.cancelAjax(); this.clearTmpEvents(); this.drawer.progress(0); this.drawer.setWidth(0); this.drawer.drawPeaks({ length: this.drawer.getWidth() }, 0); }, /** * Remove events, elements and disconnect WebAudio nodes. */ destroy: function () { this.fireEvent('destroy'); this.cancelAjax(); this.clearTmpEvents(); this.unAll(); this.backend.destroy(); this.drawer.destroy(); this.isDestroyed = true; } }; WaveSurfer.create = function (params) { var wavesurfer = Object.create(WaveSurfer); wavesurfer.init(params); return wavesurfer; }; WaveSurfer.util = { extend: function (dest) { var sources = Array.prototype.slice.call(arguments, 1); sources.forEach(function (source) { Object.keys(source).forEach(function (key) { dest[key] = source[key]; }); }); return dest; }, debounce: function (func, wait, immediate) { var args, context, timeout; var later = function() { timeout = null; if (!immediate) { func.apply(context, args); } }; return function() { context = this; args = arguments; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) { func.apply(context, args); } }; }, min: function (values) { var min = +Infinity; for (var i in values) { if (values[i] < min) { min = values[i]; } } return min; }, max: function (values) { var max = -Infinity; for (var i in values) { if (values[i] > max) { max = values[i]; } } return max; }, getId: function () { return 'wavesurfer_' + Math.random().toString(32).substring(2); }, ajax: function (options) { var ajax = Object.create(WaveSurfer.Observer); var xhr = new XMLHttpRequest(); var fired100 = false; xhr.open(options.method || 'GET', options.url, true); xhr.responseType = options.responseType || 'json'; xhr.addEventListener('progress', function (e) { ajax.fireEvent('progress', e); if (e.lengthComputable && e.loaded == e.total) { fired100 = true; } }); xhr.addEventListener('load', function (e) { if (!fired100) { ajax.fireEvent('progress', e); } ajax.fireEvent('load', e); if (200 == xhr.status || 206 == xhr.status) { ajax.fireEvent('success', xhr.response, e); } else { ajax.fireEvent('error', e); } }); xhr.addEventListener('error', function (e) { ajax.fireEvent('error', e); }); xhr.send(); ajax.xhr = xhr; return ajax; } }; /* Observer */ WaveSurfer.Observer = { /** * Attach a handler function for an event. */ on: function (event, fn) { if (!this.handlers) { this.handlers = {}; } var handlers = this.handlers[event]; if (!handlers) { handlers = this.handlers[event] = []; } handlers.push(fn); // Return an event descriptor return { name: event, callback: fn, un: this.un.bind(this, event, fn) }; }, /** * Remove an event handler. */ un: function (event, fn) { if (!this.handlers) { return; } var handlers = this.handlers[event]; if (handlers) { if (fn) { for (var i = handlers.length - 1; i >= 0; i--) { if (handlers[i] == fn) { handlers.splice(i, 1); } } } else { handlers.length = 0; } } }, /** * Remove all event handlers. */ unAll: function () { this.handlers = null; }, /** * Attach a handler to an event. The handler is executed at most once per * event type. */ once: function (event, handler) { var my = this; var fn = function () { handler.apply(this, arguments); setTimeout(function () { my.un(event, fn); }, 0); }; return this.on(event, fn); }, fireEvent: function (event) { if (!this.handlers) { return; } var handlers = this.handlers[event]; var args = Array.prototype.slice.call(arguments, 1); handlers && handlers.forEach(function (fn) { fn.apply(null, args); }); } }; /* Make the main WaveSurfer object an observer */ WaveSurfer.util.extend(WaveSurfer, WaveSurfer.Observer); 'use strict'; WaveSurfer.WebAudio = { scriptBufferSize: 256, PLAYING_STATE: 0, PAUSED_STATE: 1, FINISHED_STATE: 2, supportsWebAudio: function () { return !!(window.AudioContext || window.webkitAudioContext); }, getAudioContext: function () { if (!WaveSurfer.WebAudio.audioContext) { WaveSurfer.WebAudio.audioContext = new ( window.AudioContext || window.webkitAudioContext ); } return WaveSurfer.WebAudio.audioContext; }, getOfflineAudioContext: function (sampleRate) { if (!WaveSurfer.WebAudio.offlineAudioContext) { WaveSurfer.WebAudio.offlineAudioContext = new ( window.OfflineAudioContext || window.webkitOfflineAudioContext )(1, 2, sampleRate); } return WaveSurfer.WebAudio.offlineAudioContext; }, init: function (params) { this.params = params; this.ac = params.audioContext || this.getAudioContext(); this.lastPlay = this.ac.currentTime; this.startPosition = 0; this.scheduledPause = null; this.states = [ Object.create(WaveSurfer.WebAudio.state.playing), Object.create(WaveSurfer.WebAudio.state.paused), Object.create(WaveSurfer.WebAudio.state.finished) ]; this.createVolumeNode(); this.createScriptNode(); this.createAnalyserNode(); this.setState(this.PAUSED_STATE); this.setPlaybackRate(this.params.audioRate); this.setLength(0); }, disconnectFilters: function () { if (this.filters) { this.filters.forEach(function (filter) { filter && filter.disconnect(); }); this.filters = null; // Reconnect direct path this.analyser.connect(this.gainNode); } }, setState: function (state) { if (this.state !== this.states[state]) { this.state = this.states[state]; this.state.init.call(this); } }, // Unpacked filters setFilter: function () { this.setFilters([].slice.call(arguments)); }, /** * @param {Array} filters Packed ilters array */ setFilters: function (filters) { // Remove existing filters this.disconnectFilters(); // Insert filters if filter array not empty if (filters && filters.length) { this.filters = filters; // Disconnect direct path before inserting filters this.analyser.disconnect(); // Connect each filter in turn filters.reduce(function (prev, curr) { prev.connect(curr); return curr; }, this.analyser).connect(this.gainNode); } }, createScriptNode: function () { if (this.ac.createScriptProcessor) { this.scriptNode = this.ac.createScriptProcessor(this.scriptBufferSize); } else { this.scriptNode = this.ac.createJavaScriptNode(this.scriptBufferSize); } this.scriptNode.connect(this.ac.destination); }, addOnAudioProcess: function () { var my = this; this.scriptNode.onaudioprocess = function () { var time = my.getCurrentTime(); if (time >= my.getDuration()) { my.setState(my.FINISHED_STATE); my.fireEvent('pause'); } else if (time >= my.scheduledPause) { my.pause(); } else if (my.state === my.states[my.PLAYING_STATE]) { my.fireEvent('audioprocess', time); } }; }, removeOnAudioProcess: function () { this.scriptNode.onaudioprocess = null; }, createAnalyserNode: function () { this.analyser = this.ac.createAnalyser(); this.analyser.connect(this.gainNode); }, /** * Create the gain node needed to control the playback volume. */ createVolumeNode: function () { // Create gain node using the AudioContext if (this.ac.createGain) { this.gainNode = this.ac.createGain(); } else { this.gainNode = this.ac.createGainNode(); } // Add the gain node to the graph this.gainNode.connect(this.ac.destination); }, /** * Set the gain to a new value. * * @param {Number} newGain The new gain, a floating point value * between 0 and 1. 0 being no gain and 1 being maximum gain. */ setVolume: function (newGain) { this.gainNode.gain.value = newGain; }, /** * Get the current gain. * * @returns {Number} The current gain, a floating point value * between 0 and 1. 0 being no gain and 1 being maximum gain. */ getVolume: function () { return this.gainNode.gain.value; }, decodeArrayBuffer: function (arraybuffer, callback, errback) { if (!this.offlineAc) { this.offlineAc = this.getOfflineAudioContext(this.ac ? this.ac.sampleRate : 44100); } this.offlineAc.decodeAudioData(arraybuffer, (function (data) { callback(data); }).bind(this), errback); }, /** * Set pre-decoded peaks. */ setPeaks: function (peaks) { this.peaks = peaks; }, /** * Set the rendered length (different from the length of the audio). */ setLength: function (length) { // No resize, we can preserve the cached peaks. if (this.mergedPeaks && length == ((2 * this.mergedPeaks.length - 1) + 2)) { return; } this.splitPeaks = []; this.mergedPeaks = []; // Set the last element of the sparse array so the peak arrays are // appropriately sized for other calculations. var channels = this.buffer ? this.buffer.numberOfChannels : 1; for (var c = 0; c < channels; c++) { this.splitPeaks[c] = []; this.splitPeaks[c][2 * (length - 1)] = 0; this.splitPeaks[c][2 * (length - 1) + 1] = 0; } this.mergedPeaks[2 * (length - 1)] = 0; this.mergedPeaks[2 * (length - 1) + 1] = 0; }, /** * Compute the max and min value of the waveform when broken into * <length> subranges. * @param {Number} length How many subranges to break the waveform into. * @param {Number} first First sample in the required range. * @param {Number} last Last sample in the required range. * @returns {Array} Array of 2*<length> peaks or array of arrays * of peaks consisting of (max, min) values for each subrange. */ getPeaks: function (length, first, last) { if (this.peaks) { return this.peaks; } this.setLength(length); var sampleSize = this.buffer.length / length; var sampleStep = ~~(sampleSize / 10) || 1; var channels = this.buffer.numberOfChannels; for (var c = 0; c < channels; c++) { var peaks = this.splitPeaks[c]; var chan = this.buffer.getChannelData(c); for (var i = first; i <= last; i++) { var start = ~~(i * sampleSize); var end = ~~(start + sampleSize); var min = 0; var max = 0; for (var j = start; j < end; j += sampleStep) { var value = chan[j]; if (value > max) { max = value; } if (value < min) { min = value; } } peaks[2 * i] = max; peaks[2 * i + 1] = min; if (c == 0 || max > this.mergedPeaks[2 * i]) { this.mergedPeaks[2 * i] = max; } if (c == 0 || min < this.mergedPeaks[2 * i + 1]) { this.mergedPeaks[2 * i + 1] = min; } } } return this.params.splitChannels ? this.splitPeaks : this.mergedPeaks; }, getPlayedPercents: function () { return this.state.getPlayedPercents.call(this); }, disconnectSource: function () { if (this.source) { this.source.disconnect(); } }, destroy: function () { if (!this.isPaused()) { this.pause(); } this.unAll(); this.buffer = null; this.disconnectFilters(); this.disconnectSource(); this.gainNode.disconnect(); this.scriptNode.disconnect(); this.analyser.disconnect(); // close the audioContext if closeAudioContext option is set to true if (this.params.closeAudioContext) { // check if browser supports AudioContext.close() if (typeof this.ac.close === 'function' && this.ac.state != 'closed') { this.ac.close(); } // clear the reference to the audiocontext this.ac = null; // clear the actual audiocontext, either passed as param or the // global singleton if (!this.params.audioContext) { WaveSurfer.WebAudio.audioContext = null; } else { this.params.audioContext = null; } // clear the offlineAudioContext WaveSurfer.WebAudio.offlineAudioContext = null; } }, load: function (buffer) { this.startPosition = 0; this.lastPlay = this.ac.currentTime; this.buffer = buffer; this.createSource(); }, createSource: function () { this.disconnectSource(); this.source = this.ac.createBufferSource(); //adjust for old browsers. this.source.start = this.source.start || this.source.noteGrainOn; this.source.stop = this.source.stop || this.source.noteOff; this.source.playbackRate.value = this.playbackRate; this.source.buffer = this.buffer; this.source.connect(this.analyser); }, isPaused: function () { return this.state !== this.states[this.PLAYING_STATE]; }, getDuration: function () { if (!this.buffer) { return 0; } return this.buffer.duration; }, seekTo: function (start, end) { if (!this.buffer) { return; } this.scheduledPause = null; if (start == null) { start = this.getCurrentTime(); if (start >= this.getDuration()) { start = 0; } } if (end == null) { end = this.getDuration(); } this.startPosition = start; this.lastPlay = this.ac.currentTime; if (this.state === this.states[this.FINISHED_STATE]) { this.setState(this.PAUSED_STATE); } return { start: start, end: end }; }, getPlayedTime: function () { return (this.ac.currentTime - this.lastPlay) * this.playbackRate; }, /** * Plays the loaded audio region. * * @param {Number} start Start offset in seconds, * relative to the beginning of a clip. * @param {Number} end When to stop * relative to the beginning of a clip. */ play: function (start, end) { if (!this.buffer) { return; } // need to re-create source on each playback this.createSource(); var adjustedTime = this.seekTo(start, end); start = adjustedTime.start; end = adjustedTime.end; this.scheduledPause = end; this.source.start(0, start, end - start); if (this.ac.state == 'suspended') { this.ac.resume && this.ac.resume(); } this.setState(this.PLAYING_STATE); this.fireEvent('play'); }, /** * Pauses the loaded audio. */ pause: function () { this.scheduledPause = null; this.startPosition += this.getPlayedTime(); this.source && this.source.stop(0); this.setState(this.PAUSED_STATE); this.fireEvent('pause'); }, /** * Returns the current time in seconds relative to the audioclip's duration. */ getCurrentTime: function () { return this.state.getCurrentTime.call(this); }, /** * Returns the current playback rate. */ getPlaybackRate: function () { return this.playbackRate; }, /** * Set the audio source playback rate. */ setPlaybackRate: function (value) { value = value || 1; if (this.isPaused()) { this.playbackRate = value; } else { this.pause(); this.playbackRate = value; this.play(); } } }; WaveSurfer.WebAudio.state = {}; WaveSurfer.WebAudio.state.playing = { init: function () { this.addOnAudioProcess(); }, getPlayedPercents: function () { var duration = this.getDuration(); return (this.getCurrentTime() / duration) || 0; }, getCurrentTime: function () { return this.startPosition + this.getPlayedTime(); } }; WaveSurfer.WebAudio.state.paused = { init: function () { this.removeOnAudioProcess(); }, getPlayedPercents: function () { var duration = this.getDuration(); return (this.getCurrentTime() / duration) || 0; }, getCurrentTime: function () { return this.startPosition; } }; WaveSurfer.WebAudio.state.finished = { init: function () { this.removeOnAudioProcess(); this.fireEvent('finish'); }, getPlayedPercents: function () { return 1; }, getCurrentTime: function () { return this.getDuration(); } }; WaveSurfer.util.extend(WaveSurfer.WebAudio, WaveSurfer.Observer); 'use strict'; WaveSurfer.MediaElement = Object.create(WaveSurfer.WebAudio); WaveSurfer.util.extend(WaveSurfer.MediaElement, { init: function (params) { this.params = params; // Dummy media to catch errors this.media = { currentTime: 0, duration: 0, paused: true, playbackRate: 1, play: function () {}, pause: function () {} }; this.mediaType = params.mediaType.toLowerCase(); this.elementPosition = params.elementPosition; this.setPlaybackRate(this.params.audioRate); this.createTimer(); }, /** * Create a timer to provide a more precise `audioprocess' event. */ createTimer: function () { var my = this; var playing = false; var onAudioProcess = function () { if (my.isPaused()) { return; } my.fireEvent('audioprocess', my.getCurrentTime()); // Call again in the next frame var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame; requestAnimationFrame(onAudioProcess); }; this.on('play', onAudioProcess); }, /** * Create media element with url as its source, * and append to container element. * @param {String} url path to media file * @param {HTMLElement} container HTML element * @param {Array} peaks array of peak data * @param {String} preload HTML 5 preload attribute value */ load: function (url, container, peaks, preload) { var my = this; var media = document.createElement(this.mediaType); media.controls = this.params.mediaControls; media.autoplay = this.params.autoplay || false; media.preload = preload == null ? 'auto' : preload; media.src = url; media.style.width = '100%'; var prevMedia = container.querySelector(this.mediaType); if (prevMedia) { container.removeChild(prevMedia); } container.appendChild(media); this._load(media, peaks); }, /** * Load existing media element. * @param {MediaElement} elt HTML5 Audio or Video element * @param {Array} peaks array of peak data */ loadElt: function (elt, peaks) { var my = this; var media = elt; media.controls = this.params.mediaControls; media.autoplay = this.params.autoplay || false; this._load(media, peaks); }, /** * Private method called by both load (from url) * and loadElt (existing media element). * @param {MediaElement} media HTML5 Audio or Video element * @param {Array} peaks array of peak data * @private */ _load: function (media, peaks) { var my = this; // load must be called manually on iOS, otherwise peaks won't draw // until a user interaction triggers load --> 'ready' event if (typeof media.load == 'function') { media.load(); } media.addEventListener('error', function () { my.fireEvent('error', 'Error loading media element'); }); media.addEventListener('canplay', function () { my.fireEvent('canplay'); }); media.addEventListener('ended', function () { my.fireEvent('finish'); }); this.media = media; this.peaks = peaks; this.onPlayEnd = null; this.buffer = null; this.setPlaybackRate(this.playbackRate); }, isPaused: function () { return !this.media || this.media.paused; }, getDuration: function () { var duration = (this.buffer || this.media).duration; if (duration >= Infinity) { // streaming audio duration = this.media.seekable.end(0); } return duration; }, getCurrentTime: function () { return this.media && this.media.currentTime; }, getPlayedPercents: function () { return (this.getCurrentTime() / this.getDuration()) || 0; }, getPlaybackRate: function () { return this.playbackRate || this.media.playbackRate; }, /** * Set the audio source playback rate. */ setPlaybackRate: function (value) { this.playbackRate = value || 1; this.media.playbackRate = this.playbackRate; }, seekTo: function (start) { if (start != null) { this.media.currentTime = start; } this.clearPlayEnd(); }, /** * Plays the loaded audio region. * * @param {Number} start Start offset in seconds, * relative to the beginning of a clip. * @param {Number} end End offset in seconds, * relative to the beginning of a clip. */ play: function (start, end) { this.seekTo(start); this.media.play(); end && this.setPlayEnd(end); this.fireEvent('play'); }, /** * Pauses the loaded audio. */ pause: function () { this.media && this.media.pause(); this.clearPlayEnd(); this.fireEvent('pause'); }, setPlayEnd: function (end) { var my = this; this.onPlayEnd = function (time) { if (time >= end) { my.pause(); my.seekTo(end); } }; this.on('audioprocess', this.onPlayEnd); }, clearPlayEnd: function () { if (this.onPlayEnd) { this.un('audioprocess', this.onPlayEnd); this.onPlayEnd = null; } }, getPeaks: function (length, start, end) { if (this.buffer) { return WaveSurfer.WebAudio.getPeaks.call(this, length, start, end); } return this.peaks || []; }, getVolume: function () { return this.media.volume; }, setVolume: function (val) { this.media.volume = val; }, destroy: function () { this.pause(); this.unAll(); this.media && this.media.parentNode && this.media.parentNode.removeChild(this.media); this.media = null; } }); //For backwards compatibility WaveSurfer.AudioElement = WaveSurfer.MediaElement; 'use strict'; WaveSurfer.Drawer = { init: function (container, params) { this.container = container; this.params = params; this.width = 0; this.height = params.height * this.params.pixelRatio; this.lastPos = 0; this.initDrawer(params); this.createWrapper(); this.createElements(); }, createWrapper: function () { this.wrapper = this.container.appendChild( document.createElement('wave') ); this.style(this.wrapper, { display: 'block', position: 'relative', userSelect: 'none', webkitUserSelect: 'none', height: this.params.height + 'px' }); if (this.params.fillParent || this.params.scrollParent) { this.style(this.wrapper, { width: '100%', overflowX: this.params.hideScrollbar ? 'hidden' : 'auto', overflowY: 'hidden' }); } this.setupWrapperEvents(); }, handleEvent: function (e, noPrevent) { !noPrevent && e.preventDefault(); var clientX = e.targetTouches ? e.targetTouches[0].clientX : e.clientX; var bbox = this.wrapper.getBoundingClientRect(); var nominalWidth = this.width; var parentWidth = this.getWidth(); var progress; if (!this.params.fillParent && nominalWidth < parentWidth) { progress = ((clientX - bbox.left) * this.params.pixelRatio / nominalWidth) || 0; if (progress > 1) { progress = 1; } } else { progress = ((clientX - bbox.left + this.wrapper.scrollLeft) / this.wrapper.scrollWidth) || 0; } return progress; }, setupWrapperEvents: function () { var my = this; this.wrapper.addEventListener('click', function (e) { var scrollbarHeight = my.wrapper.offsetHeight - my.wrapper.clientHeight; if (scrollbarHeight != 0) { // scrollbar is visible. Check if click was on it var bbox = my.wrapper.getBoundingClientRect(); if (e.clientY >= bbox.bottom - scrollbarHeight) { // ignore mousedown as it was on the scrollbar return; } } if (my.params.interact) { my.fireEvent('click', e, my.handleEvent(e)); } }); this.wrapper.addEventListener('scroll', function (e) { my.fireEvent('scroll', e); }); }, drawPeaks: function (peaks, length, start, end) { this.setWidth(length); this.params.barWidth ? this.drawBars(peaks, 0, start, end) : this.drawWave(peaks, 0, start, end); }, style: function (el, styles) { Object.keys(styles).forEach(function (prop) { if (el.style[prop] !== styles[prop]) { el.style[prop] = styles[prop]; } }); return el; }, resetScroll: function () { if (this.wrapper !== null) { this.wrapper.scrollLeft = 0; } }, recenter: function (percent) { var position = this.wrapper.scrollWidth * percent; this.recenterOnPosition(position, true); }, recenterOnPosition: function (position, immediate) { var scrollLeft = this.wrapper.scrollLeft; var half = ~~(this.wrapper.clientWidth / 2); var target = position - half; var offset = target - scrollLeft; var maxScroll = this.wrapper.scrollWidth - this.wrapper.clientWidth; if (maxScroll == 0) { // no need to continue if scrollbar is not there return; } // if the cursor is currently visible... if (!immediate && -half <= offset && offset < half) { // we'll limit the "re-center" rate. var rate = 5; offset = Math.max(-rate, Math.min(rate, offset)); target = scrollLeft + offset; } // limit target to valid range (0 to maxScroll) target = Math.max(0, Math.min(maxScroll, target)); // no use attempting to scroll if we're not moving if (target != scrollLeft) { this.wrapper.scrollLeft = target; } }, getScrollX: function() { return Math.round(this.wrapper.scrollLeft * this.params.pixelRatio); }, getWidth: function () { return Math.round(this.container.clientWidth * this.params.pixelRatio); }, setWidth: function (width) { if (this.width == width) { return; } this.width = width; if (this.params.fillParent || this.params.scrollParent) { this.style(this.wrapper, { width: '' }); } else { this.style(this.wrapper, { width: ~~(this.width / this.params.pixelRatio) + 'px' }); } this.updateSize(); }, setHeight: function (height) { if (height == this.height) { return; } this.height = height; this.style(this.wrapper, { height: ~~(this.height / this.params.pixelRatio) + 'px' }); this.updateSize(); }, progress: function (progress) { var minPxDelta = 1 / this.params.pixelRatio; var pos = Math.round(progress * this.width) * minPxDelta; if (pos < this.lastPos || pos - this.lastPos >= minPxDelta) { this.lastPos = pos; if (this.params.scrollParent && this.params.autoCenter) { var newPos = ~~(this.wrapper.scrollWidth * progress); this.recenterOnPosition(newPos); } this.updateProgress(pos); } }, destroy: function () { this.unAll(); if (this.wrapper) { this.container.removeChild(this.wrapper); this.wrapper = null; } }, /* Renderer-specific methods */ initDrawer: function () {}, createElements: function () {}, updateSize: function () {}, drawWave: function (peaks, max) {}, clearWave: function () {}, updateProgress: function (position) {} }; WaveSurfer.util.extend(WaveSurfer.Drawer, WaveSurfer.Observer); 'use strict'; WaveSurfer.Drawer.Canvas = Object.create(WaveSurfer.Drawer); WaveSurfer.util.extend(WaveSurfer.Drawer.Canvas, { createElements: function () { var waveCanvas = this.wrapper.appendChild( this.style(document.createElement('canvas'), { position: 'absolute', zIndex: 1, left: 0, top: 0, bottom: 0 }) ); this.waveCc = waveCanvas.getContext('2d'); this.progressWave = this.wrapper.appendChild( this.style(document.createElement('wave'), { position: 'absolute', zIndex: 2, left: 0, top: 0, bottom: 0, overflow: 'hidden', width: '0', display: 'none', boxSizing: 'border-box', borderRightStyle: 'solid', borderRightWidth: this.params.cursorWidth + 'px', borderRightColor: this.params.cursorColor }) ); if (this.params.waveColor != this.params.progressColor) { var progressCanvas = this.progressWave.appendChild( document.createElement('canvas') ); this.progressCc = progressCanvas.getContext('2d'); } }, updateSize: function () { var width = Math.round(this.width / this.params.pixelRatio); this.waveCc.canvas.width = this.width; this.waveCc.canvas.height = this.height; this.style(this.waveCc.canvas, { width: width + 'px'}); this.style(this.progressWave, { display: 'block'}); if (this.progressCc) { this.progressCc.canvas.width = this.width; this.progressCc.canvas.height = this.height; this.style(this.progressCc.canvas, { width: width + 'px'}); } this.clearWave(); }, clearWave: function () { this.waveCc.clearRect(0, 0, this.width, this.height); if (this.progressCc) { this.progressCc.clearRect(0, 0, this.width, this.height); } }, drawBars: function (peaks, channelIndex, start, end) { var my = this; // Split channels if (peaks[0] instanceof Array) { var channels = peaks; if (this.params.splitChannels) { this.setHeight(channels.length * this.params.height * this.params.pixelRatio); channels.forEach(function(channelPeaks, i) { my.drawBars(channelPeaks, i, start, end); }); return; } else { peaks = channels[0]; } } // Bar wave draws the bottom only as a reflection of the top, // so we don't need negative values var hasMinVals = [].some.call(peaks, function (val) { return val < 0; }); // Skip every other value if there are negatives. var peakIndexScale = 1; if (hasMinVals) { peakIndexScale = 2; } // A half-pixel offset makes lines crisp var $ = 0.5 / this.params.pixelRatio; var width = this.width; var height = this.params.height * this.params.pixelRatio; var offsetY = height * channelIndex || 0; var halfH = height / 2; var length = peaks.length / peakIndexScale; var bar = this.params.barWidth * this.params.pixelRatio; var gap = Math.max(this.params.pixelRatio, ~~(bar / 2)); var step = bar + gap; var absmax = 1 / this.params.barHeight; if (this.params.normalize) { var max = WaveSurfer.util.max(peaks); var min = WaveSurfer.util.min(peaks); absmax = -min > max ? -min : max; } var scale = length / width; this.waveCc.fillStyle = this.params.waveColor; if (this.progressCc) { this.progressCc.fillStyle = this.params.progressColor; } [ this.waveCc, this.progressCc ].forEach(function (cc) { if (!cc) { return; } for (var i = (start / scale); i < (end / scale); i += step) { var peak = peaks[Math.floor(i * scale * peakIndexScale)] || 0; var h = Math.round(peak / absmax * halfH); cc.fillRect(i + $, halfH - h + offsetY, bar + $, h * 2); } }, this); }, drawWave: function (peaks, channelIndex, start, end) { var my = this; // Split channels if (peaks[0] instanceof Array) { var channels = peaks; if (this.params.splitChannels) { this.setHeight(channels.length * this.params.height * this.params.pixelRatio); channels.forEach(function(channelPeaks, i) { my.drawWave(channelPeaks, i, start, end); }); return; } else { peaks = channels[0]; } } // Support arrays without negative peaks var hasMinValues = [].some.call(peaks, function (val) { return val < 0; }); if (!hasMinValues) { var reflectedPeaks = []; for (var i = 0, len = peaks.length; i < len; i++) { reflectedPeaks[2 * i] = peaks[i]; reflectedPeaks[2 * i + 1] = -peaks[i]; } peaks = reflectedPeaks; } // A half-pixel offset makes lines crisp var $ = 0.5 / this.params.pixelRatio; var height = this.params.height * this.params.pixelRatio; var offsetY = height * channelIndex || 0; var halfH = height / 2; var length = ~~(peaks.length / 2); var scale = 1; if (this.params.fillParent && this.width != length) { scale = this.width / length; } var absmax = 1 / this.params.barHeight; if (this.params.normalize) { var max = WaveSurfer.util.max(peaks); var min = WaveSurfer.util.min(peaks); absmax = -min > max ? -min : max; } this.waveCc.fillStyle = this.params.waveColor; if (this.progressCc) { this.progressCc.fillStyle = this.params.progressColor; } [ this.waveCc, this.progressCc ].forEach(function (cc) { if (!cc) { return; } cc.beginPath(); cc.moveTo(start * scale + $, halfH + offsetY); for (var i = start; i < end; i++) { var h = Math.round(peaks[2 * i] / absmax * halfH); cc.lineTo(i * scale + $, halfH - h + offsetY); } // Draw the bottom edge going backwards, to make a single // closed hull to fill. for (var i = end - 1; i >= start; i--) { var h = Math.round(peaks[2 * i + 1] / absmax * halfH); cc.lineTo(i * scale + $, halfH - h + offsetY); } cc.closePath(); cc.fill(); // Always draw a median line cc.fillRect(0, halfH + offsetY - $, this.width, $); }, this); }, updateProgress: function (pos) { this.style(this.progressWave, { width: pos + 'px' }); }, getImage: function(type, quality) { return this.waveCc.canvas.toDataURL(type, quality); } }); 'use strict'; WaveSurfer.Drawer.MultiCanvas = Object.create(WaveSurfer.Drawer); WaveSurfer.util.extend(WaveSurfer.Drawer.MultiCanvas, { initDrawer: function (params) { this.maxCanvasWidth = params.maxCanvasWidth != null ? params.maxCanvasWidth : 4000; this.maxCanvasElementWidth = Math.round(this.maxCanvasWidth / this.params.pixelRatio); if (this.maxCanvasWidth <= 1) { throw 'maxCanvasWidth must be greater than 1.'; } else if (this.maxCanvasWidth % 2 == 1) { throw 'maxCanvasWidth must be an even number.'; } this.hasProgressCanvas = this.params.waveColor != this.params.progressColor; this.halfPixel = 0.5 / this.params.pixelRatio; this.canvases = []; }, createElements: function () { this.progressWave = this.wrapper.appendChild( this.style(document.createElement('wave'), { position: 'absolute', zIndex: 2, left: 0, top: 0, bottom: 0, overflow: 'hidden', width: '0', display: 'none', boxSizing: 'border-box', borderRightStyle: 'solid', borderRightWidth: this.params.cursorWidth + 'px', borderRightColor: this.params.cursorColor }) ); this.addCanvas(); }, updateSize: function () { var totalWidth = Math.round(this.width / this.params.pixelRatio), requiredCanvases = Math.ceil(totalWidth / this.maxCanvasElementWidth); while (this.canvases.length < requiredCanvases) { this.addCanvas(); } while (this.canvases.length > requiredCanvases) { this.removeCanvas(); } for (var i in this.canvases) { // Add some overlap to prevent vertical white stripes, keep the width even for simplicity. var canvasWidth = this.maxCanvasWidth + 2 * Math.ceil(this.params.pixelRatio / 2); if (i == this.canvases.length - 1) { canvasWidth = this.width - (this.maxCanvasWidth * (this.canvases.length - 1)); } this.updateDimensions(this.canvases[i], canvasWidth, this.height); this.clearWaveForEntry(this.canvases[i]); } }, addCanvas: function () { var entry = {}, leftOffset = this.maxCanvasElementWidth * this.canvases.length; entry.wave = this.wrapper.appendChild( this.style(document.createElement('canvas'), { position: 'absolute', zIndex: 1, left: leftOffset + 'px', top: 0, bottom: 0, height: '100%' }) ); entry.waveCtx = entry.wave.getContext('2d'); if (this.hasProgressCanvas) { entry.progress = this.progressWave.appendChild( this.style(document.createElement('canvas'), { position: 'absolute', left: leftOffset + 'px', top: 0, bottom: 0, height: '100%' }) ); entry.progressCtx = entry.progress.getContext('2d'); } this.canvases.push(entry); }, removeCanvas: function () { var lastEntry = this.canvases.pop(); lastEntry.wave.parentElement.removeChild(lastEntry.wave); if (this.hasProgressCanvas) { lastEntry.progress.parentElement.removeChild(lastEntry.progress); } }, updateDimensions: function (entry, width, height) { var elementWidth = Math.round(width / this.params.pixelRatio), totalWidth = Math.round(this.width / this.params.pixelRatio); // Where the canvas starts and ends in the waveform, represented as a decimal between 0 and 1. entry.start = (entry.waveCtx.canvas.offsetLeft / totalWidth) || 0; entry.end = entry.start + elementWidth / totalWidth; entry.waveCtx.canvas.width = width; entry.waveCtx.canvas.height = height; this.style(entry.waveCtx.canvas, { width: elementWidth + 'px'}); this.style(this.progressWave, { display: 'block'}); if (this.hasProgressCanvas) { entry.progressCtx.canvas.width = width; entry.progressCtx.canvas.height = height; this.style(entry.progressCtx.canvas, { width: elementWidth + 'px'}); } }, clearWave: function () { for (var i in this.canvases) { this.clearWaveForEntry(this.canvases[i]); } }, clearWaveForEntry: function (entry) { entry.waveCtx.clearRect(0, 0, entry.waveCtx.canvas.width, entry.waveCtx.canvas.height); if (this.hasProgressCanvas) { entry.progressCtx.clearRect(0, 0, entry.progressCtx.canvas.width, entry.progressCtx.canvas.height); } }, drawBars: function (peaks, channelIndex, start, end) { var my = this; // Split channels if (peaks[0] instanceof Array) { var channels = peaks; if (this.params.splitChannels) { this.setHeight(channels.length * this.params.height * this.params.pixelRatio); channels.forEach(function(channelPeaks, i) { my.drawBars(channelPeaks, i, start, end); }); return; } else { peaks = channels[0]; } } // Bar wave draws the bottom only as a reflection of the top, // so we don't need negative values var hasMinVals = [].some.call(peaks, function (val) { return val < 0; }); // Skip every other value if there are negatives. var peakIndexScale = 1; if (hasMinVals) { peakIndexScale = 2; } // A half-pixel offset makes lines crisp var width = this.width; var height = this.params.height * this.params.pixelRatio; var offsetY = height * channelIndex || 0; var halfH = height / 2; var length = peaks.length / peakIndexScale; var bar = this.params.barWidth * this.params.pixelRatio; var gap = Math.max(this.params.pixelRatio, ~~(bar / 2)); var step = bar + gap; var absmax = 1 / this.params.barHeight; if (this.params.normalize) { var max = WaveSurfer.util.max(peaks); var min = WaveSurfer.util.min(peaks); absmax = -min > max ? -min : max; } var scale = length / width; for (var i = (start / scale); i < (end / scale); i += step) { var peak = peaks[Math.floor(i * scale * peakIndexScale)] || 0; var h = Math.round(peak / absmax * halfH); this.fillRect(i + this.halfPixel, halfH - h + offsetY, bar + this.halfPixel, h * 2); } }, drawWave: function (peaks, channelIndex, start, end) { var my = this; // Split channels if (peaks[0] instanceof Array) { var channels = peaks; if (this.params.splitChannels) { this.setHeight(channels.length * this.params.height * this.params.pixelRatio); channels.forEach(function(channelPeaks, i) { my.drawWave(channelPeaks, i, start, end); }); return; } else { peaks = channels[0]; } } // Support arrays without negative peaks var hasMinValues = [].some.call(peaks, function (val) { return val < 0; }); if (!hasMinValues) { var reflectedPeaks = []; for (var i = 0, len = peaks.length; i < len; i++) { reflectedPeaks[2 * i] = peaks[i]; reflectedPeaks[2 * i + 1] = -peaks[i]; } peaks = reflectedPeaks; } // A half-pixel offset makes lines crisp var height = this.params.height * this.params.pixelRatio; var offsetY = height * channelIndex || 0; var halfH = height / 2; var absmax = 1 / this.params.barHeight; if (this.params.normalize) { var max = WaveSurfer.util.max(peaks); var min = WaveSurfer.util.min(peaks); absmax = -min > max ? -min : max; } this.drawLine(peaks, absmax, halfH, offsetY, start, end); // Always draw a median line this.fillRect(0, halfH + offsetY - this.halfPixel, this.width, this.halfPixel); }, drawLine: function (peaks, absmax, halfH, offsetY, start, end) { for (var index in this.canvases) { var entry = this.canvases[index]; this.setFillStyles(entry); this.drawLineToContext(entry, entry.waveCtx, peaks, absmax, halfH, offsetY, start, end); this.drawLineToContext(entry, entry.progressCtx, peaks, absmax, halfH, offsetY, start, end); } }, drawLineToContext: function (entry, ctx, peaks, absmax, halfH, offsetY, start, end) { if (!ctx) { return; } var length = peaks.length / 2; var scale = 1; if (this.params.fillParent && this.width != length) { scale = this.width / length; } var first = Math.round(length * entry.start), last = Math.round(length * entry.end); if (first > end || last < start) { return; } var canvasStart = Math.max(first, start); var canvasEnd = Math.min(last, end); ctx.beginPath(); ctx.moveTo((canvasStart - first) * scale + this.halfPixel, halfH + offsetY); for (var i = canvasStart; i < canvasEnd; i++) { var peak = peaks[2 * i] || 0; var h = Math.round(peak / absmax * halfH); ctx.lineTo((i - first) * scale + this.halfPixel, halfH - h + offsetY); } // Draw the bottom edge going backwards, to make a single // closed hull to fill. for (var i = canvasEnd - 1; i >= canvasStart; i--) { var peak = peaks[2 * i + 1] || 0; var h = Math.round(peak / absmax * halfH); ctx.lineTo((i - first) * scale + this.halfPixel, halfH - h + offsetY); } ctx.closePath(); ctx.fill(); }, fillRect: function (x, y, width, height) { var startCanvas = Math.floor(x / this.maxCanvasWidth); var endCanvas = Math.min(Math.ceil((x + width) / this.maxCanvasWidth) + 1, this.canvases.length); for (var i = startCanvas; i < endCanvas; i++) { var entry = this.canvases[i], leftOffset = i * this.maxCanvasWidth; var intersection = { x1: Math.max(x, i * this.maxCanvasWidth), y1: y, x2: Math.min(x + width, i * this.maxCanvasWidth + entry.waveCtx.canvas.width), y2: y + height }; if (intersection.x1 < intersection.x2) { this.setFillStyles(entry); this.fillRectToContext(entry.waveCtx, intersection.x1 - leftOffset, intersection.y1, intersection.x2 - intersection.x1, intersection.y2 - intersection.y1); this.fillRectToContext(entry.progressCtx, intersection.x1 - leftOffset, intersection.y1, intersection.x2 - intersection.x1, intersection.y2 - intersection.y1); } } }, fillRectToContext: function (ctx, x, y, width, height) { if (!ctx) { return; } ctx.fillRect(x, y, width, height); }, setFillStyles: function (entry) { entry.waveCtx.fillStyle = this.params.waveColor; if (this.hasProgressCanvas) { entry.progressCtx.fillStyle = this.params.progressColor; } }, updateProgress: function (pos) { this.style(this.progressWave, { width: pos + 'px' }); }, /** * Combine all available canvasses together. * * @param {String} type - an optional value of a format type. Default is image/png. * @param {Number} quality - an optional value between 0 and 1. Default is 0.92. * */ getImage: function(type, quality) { var availableCanvas = []; this.canvases.forEach(function (entry) { availableCanvas.push(entry.wave.toDataURL(type, quality)); }); return availableCanvas.length > 1 ? availableCanvas : availableCanvas[0]; } }); 'use strict'; WaveSurfer.Drawer.SplitWavePointPlot = Object.create(WaveSurfer.Drawer.Canvas); WaveSurfer.util.extend(WaveSurfer.Drawer.SplitWavePointPlot, { defaultPlotParams: { plotNormalizeTo: 'whole', plotTimeStart: 0, plotMin: 0, plotMax: 1, plotColor : '#f63', plotProgressColor : '#F00', plotPointHeight: 2, plotPointWidth: 2, plotSeparator: true, plotSeparatorColor: 'black', plotRangeDisplay: false, plotRangeUnits: '', plotRangePrecision: 4, plotRangeIgnoreOutliers: false, plotRangeFontSize: 12, plotRangeFontType: 'Ariel', waveDrawMedianLine: true, plotFileDelimiter: '\t' }, //object variables that get manipulated by various object functions plotTimeStart: 0, //the start time of our wave according to plot data plotTimeEnd: -1, //the end of our wave according to plot data plotArrayLoaded: false, plotArray: [], //array of plot data objects containing time and plot value plotPoints: [], //calculated average plot points corresponding to value of our wave plotMin: 0, plotMax: 1, /** * Initializes the plot array. If params.plotFileUrl is provided an ajax call will be * executed and drawing of the wave is delayed until plot info is retrieved * @param params */ initDrawer: function (params) { var my = this; //set defaults if not passed in for(var paramName in this.defaultPlotParams) { if(this.params[paramName] === undefined) { this.params[paramName] = this.defaultPlotParams[paramName]; } } //set the plotTimeStart this.plotTimeStart = this.params.plotTimeStart; //check to see if plotTimeEnd if(this.params.plotTimeEnd !== undefined) { this.plotTimeEnd = this.params.plotTimeEnd; } //set the plot array if (Array.isArray(params.plotArray)) { this.plotArray = params.plotArray; this.plotArrayLoaded = true; } //Need to load the plot array from ajax with our callback else { var onPlotArrayLoaded = function (plotArray) { my.plotArray = plotArray; my.plotArrayLoaded = true; my.fireEvent('plot_array_loaded'); }; this.loadPlotArrayFromFile(params.plotFileUrl, onPlotArrayLoaded, this.params.plotFileDelimiter); } }, /** * Draw the peaks - this overrides the drawer.js function and does the following additional steps * - ensures that the plotArray has already been loaded, if not it loads via ajax * - moves the wave form to where channel 1 would normally be * @param peaks * @param length * @param start * @param end */ drawPeaks: function (peaks, length, start, end) { //make sure that the plot array is already loaded if (this.plotArrayLoaded == true) { this.setWidth(length); //fake that we are splitting channels this.splitChannels = true; this.params.height = this.params.height/2; if (peaks[0] instanceof Array) { peaks = peaks[0]; } this.params.barWidth ? this.drawBars(peaks, 1, start, end) : this.drawWave(peaks, 1, start, end); //set the height back to the original this.params.height = this.params.height*2; this.calculatePlots(); this.drawPlots(); } //otherwise wait for the plot array to be loaded and then draw again else { var my = this; my.on('plot-array-loaded', function () { my.drawPeaks(peaks, length, start, end); }); } }, /** * Loop through the calculated plot values and actually draw them */ drawPlots: function() { var height = this.params.height * this.params.pixelRatio / 2; var $ = 0.5 / this.params.pixelRatio; this.waveCc.fillStyle = this.params.plotColor; if(this.progressCc) { this.progressCc.fillStyle = this.params.plotProgressColor; } for(var i in this.plotPoints) { var x = parseInt(i); var y = height - this.params.plotPointHeight - (this.plotPoints[i] * (height - this.params.plotPointHeight)); var pointHeight = this.params.plotPointHeight; this.waveCc.fillRect(x, y, this.params.plotPointWidth, pointHeight); if(this.progressCc) { this.progressCc.fillRect(x, y, this.params.plotPointWidth, pointHeight); } } //draw line to separate the two waves if(this.params.plotSeparator) { this.waveCc.fillStyle = this.params.plotSeparatorColor; this.waveCc.fillRect(0, height, this.width, $); } if(this.params.plotRangeDisplay) { this.displayPlotRange(); } }, /** * Display the range for the plot graph */ displayPlotRange: function() { var fontSize = this.params.plotRangeFontSize * this.params.pixelRatio; var maxRange = this.plotMax.toPrecision(this.params.plotRangePrecision) + ' ' + this.params.plotRangeUnits; var minRange = this.plotMin.toPrecision(this.params.plotRangePrecision) + ' ' + this.params.plotRangeUnits; this.waveCc.font = fontSize.toString() + 'px ' + this.params.plotRangeFontType; this.waveCc.fillText(maxRange, 3, fontSize); this.waveCc.fillText(minRange, 3, this.height/2); }, /** * This function loops through the plotArray and converts it to the plot points * to be drawn on the canvas keyed by their position */ calculatePlots: function() { //reset plots array this.plotPoints = {}; //make sure we have our plotTimeEnd this.calculatePlotTimeEnd(); var pointsForAverage = []; var previousWaveIndex = -1; var maxPlot = 0; var minPlot = 99999999999999; var maxSegmentPlot = 0; var minSegmentPlot = 99999999999999; var duration = this.plotTimeEnd - this.plotTimeStart; //loop through our plotArray and map values to wave indexes and take the average values for each wave index for(var i = 0; i < this.plotArray.length; i++) { var dataPoint = this.plotArray[i]; if(dataPoint.value > maxPlot) {maxPlot = dataPoint.value;} if(dataPoint.value < minPlot) {minPlot = dataPoint.value;} //make sure we are in the specified range if(dataPoint.time >= this.plotTimeStart && dataPoint.time <= this.plotTimeEnd) { //get the wave index corresponding to the data point var waveIndex = Math.round(this.width * (dataPoint.time - this.plotTimeStart) / duration); pointsForAverage.push(dataPoint.value); //if we have moved on to a new position in our wave record average and reset previousWaveIndex if(waveIndex !== previousWaveIndex) { if(pointsForAverage.length > 0) { //get the average plot for this point var avgPlot = this.avg(pointsForAverage); //check for min max if(avgPlot > maxSegmentPlot) {maxSegmentPlot = avgPlot;} if(avgPlot < minSegmentPlot) {minSegmentPlot = avgPlot;} //add plot to the position this.plotPoints[previousWaveIndex] = avgPlot; pointsForAverage = []; } } previousWaveIndex = waveIndex; } } //normalize the plots points if(this.params.plotNormalizeTo == 'whole') { this.plotMin = minPlot; this.plotMax = maxPlot; } else if(this.params.plotNormalizeTo == 'values') { this.plotMin = this.params.plotMin; this.plotMax = this.params.plotMax; } else { this.plotMin = minSegmentPlot; this.plotMax = maxSegmentPlot; } this.normalizeValues(); }, /** * Function to take all of the plots in this.plots and normalize them from 0 to one * depending on this.plotMin and this.plotMax values */ normalizeValues: function() { var normalizedValues = {}; //check to make sure we should be normalizing if(this.params.plotNormalizeTo === 'none') {return;} for(var i in this.plotPoints) { //get the normalized value between 0 and 1 var normalizedValue = (this.plotPoints[i] - this.plotMin) / (this.plotMax - this.plotMin); //check if the value is above our specified range max if(normalizedValue > 1) { if(!this.params.plotRangeIgnoreOutliers) { normalizedValues[i] = 1; } } //check if hte value is below our specified rant else if(normalizedValue < 0) { if(!this.params.plotRangeIgnoreOutliers) { normalizedValues[i] = 0; } } //in our range add the normalized value else { normalizedValues[i] = normalizedValue; } } this.plotPoints = normalizedValues; }, /** * */ /** * Function to load the plot array from a external file * * The text file should contain a series of lines. * Each line should contain [audio time] [delimiter character] [plot value] * e.g. "1.2355 [tab] 124.2321" * * @param plotFileUrl url of the file containing time and value information * @param onSuccess function to run on success * @param delimiter the delimiter that separates the time and values on each line */ loadPlotArrayFromFile: function(plotFileUrl, onSuccess, delimiter) { //default delimiter to tab character if (delimiter === undefined) {delimiter = '\t';} var plotArray = []; var options = { url: plotFileUrl, responseType: 'text' }; var fileAjax = WaveSurfer.util.ajax(options); fileAjax.on('load', function (data) { if (data.currentTarget.status == 200) { //split the file by line endings var plotLines = data.currentTarget.responseText.split('\n'); //loop through each line and find the time and plot values (delimited by tab) for (var i = 0; i < plotLines.length; i++) { var plotParts = plotLines[i].split(delimiter); if(plotParts.length == 2) { plotArray.push({time: parseFloat(plotParts[0]), value: parseFloat(plotParts[1])}); } } //run success function onSuccess(plotArray); } }); }, /*** * Calculate the end time of the plot */ calculatePlotTimeEnd: function() { if(this.params.plotTimeEnd !== undefined) { this.plotTimeEnd = this.params.plotTimeEnd; } else { this.plotTimeEnd = this.plotArray[this.plotArray.length -1].time; } }, /** * Quick convenience function to average numbers in an array * @param array of values * @returns {number} */ avg: function(values) { var sum = values.reduce(function(a, b) {return a+b;}); return sum/values.length; } }); WaveSurfer.util.extend(WaveSurfer.Drawer.SplitWavePointPlot, WaveSurfer.Observer); 'use strict'; WaveSurfer.PeakCache = { init: function() { this.clearPeakCache(); }, clearPeakCache: function() { // Flat array with entries that are always in pairs to mark the // beginning and end of each subrange. This is a convenience so we can // iterate over the pairs for easy set difference operations. this.peakCacheRanges = []; // Length of the entire cachable region, used for resetting the cache // when this changes (zoom events, for instance). this.peakCacheLength = -1; }, addRangeToPeakCache: function(length, start, end) { if (length != this.peakCacheLength) { this.clearPeakCache(); this.peakCacheLength = length; } // Return ranges that weren't in the cache before the call. var uncachedRanges = []; var i = 0; // Skip ranges before the current start. while (i < this.peakCacheRanges.length && this.peakCacheRanges[i] < start) { i++; } // If |i| is even, |start| falls after an existing range. Otherwise, // |start| falls between an existing range, and the uncached region // starts when we encounter the next node in |peakCacheRanges| or // |end|, whichever comes first. if (i % 2 == 0) { uncachedRanges.push(start); } while (i < this.peakCacheRanges.length && this.peakCacheRanges[i] <= end) { uncachedRanges.push(this.peakCacheRanges[i]); i++; } // If |i| is even, |end| is after all existing ranges. if (i % 2 == 0) { uncachedRanges.push(end); } // Filter out the 0-length ranges. uncachedRanges = uncachedRanges.filter(function(item, pos, arr) { if (pos == 0) { return item != arr[pos + 1]; } else if (pos == arr.length - 1) { return item != arr[pos - 1]; } else { return item != arr[pos - 1] && item != arr[pos + 1]; } }); // Merge the two ranges together, uncachedRanges will either contain // wholly new points, or duplicates of points in peakCacheRanges. If // duplicates are detected, remove both and extend the range. this.peakCacheRanges = this.peakCacheRanges.concat(uncachedRanges); this.peakCacheRanges = this.peakCacheRanges.sort(function(a, b) { return a - b; }).filter(function(item, pos, arr) { if (pos == 0) { return item != arr[pos + 1]; } else if (pos == arr.length - 1) { return item != arr[pos - 1]; } else { return item != arr[pos - 1] && item != arr[pos + 1]; } }); // Push the uncached ranges into an array of arrays for ease of // iteration in the functions that call this. var uncachedRangePairs = []; for (i = 0; i < uncachedRanges.length; i += 2) { uncachedRangePairs.push([uncachedRanges[i], uncachedRanges[i+1]]); } return uncachedRangePairs; }, // For testing getCacheRanges: function() { var peakCacheRangePairs = []; for (var i = 0; i < this.peakCacheRanges.length; i += 2) { peakCacheRangePairs.push([this.peakCacheRanges[i], this.peakCacheRanges[i+1]]); } return peakCacheRangePairs; } }; 'use strict'; /* Init from HTML */ (function () { var init = function () { var containers = document.querySelectorAll('wavesurfer'); Array.prototype.forEach.call(containers, function (el) { var params = WaveSurfer.util.extend({ container: el, backend: 'MediaElement', mediaControls: true }, el.dataset); el.style.display = 'block'; var wavesurfer = WaveSurfer.create(params); if (el.dataset.peaks) { var peaks = JSON.parse(el.dataset.peaks); } wavesurfer.load(el.dataset.url, peaks); }); }; if (document.readyState === 'complete') { init(); } else { window.addEventListener('load', init); } }()); return WaveSurfer; }));
NaturalHistoryMuseum/scratchpads2
sites/all/libraries/wavesurfer/dist/wavesurfer.js
JavaScript
gpl-2.0
86,080
/** * Copyright 2014 Red Hat, Inc. * * This software is licensed to you under the GNU General Public * License as published by the Free Software Foundation; either version * 2 of the License (GPLv2) or (at your option) any later version. * There is NO WARRANTY for this software, express or implied, * including the implied warranties of MERCHANTABILITY, * NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should * have received a copy of GPLv2 along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. **/ describe('Controller: ContentViewVersionsController', function() { var $scope beforeEach(module('Bastion.content-views', 'Bastion.test-mocks')); beforeEach(inject(function($injector) { var $controller = $injector.get('$controller'), ContentView = $injector.get('MockResource').$new(), translate = function (string) { return string; }; $scope = $injector.get('$rootScope').$new(); $scope.contentView = ContentView.get({id: 1}); $scope.reloadVersions = function () {}; $scope.taskTypes = { promotion: "promotion", publish: "publish" }; spyOn($scope, 'reloadVersions'); $controller('ContentViewVersionsController', { $scope: $scope, translate: translate }); })); it("puts an empty table object on the scope", function() { expect($scope.table).toBeDefined(); }); it("correctly hide a version's progress", function() { var version = {active_history: [], task: {state: 'running', progressbar: {type: 'success'}}}; expect($scope.hideProgress(version)).toBe(true); version = {active_history: [{}], task: {state: 'running', progressbar: {type: 'success'}}}; expect($scope.hideProgress(version)).toBe(false); version = {active_history: [], task: {state: 'stopped', progressbar: {type: 'success'}}}; expect($scope.hideProgress(version)).toBe(true); version = {active_history: [{}], task: {state: 'stopped', progressbar: {type: 'error'}}}; expect($scope.hideProgress(version)).toBe(false); }); it("determines what history text to display", function() { var version = {active_history: [], last_event: {environment: {name: 'test'}, task: {label: $scope.taskTypes.promotion} }}; expect($scope.historyText(version)).toBe("Promoted to test"); version.last_event.task.label = $scope.taskTypes.publish; expect($scope.historyText(version)).toBe("Published"); }); });
dustints/katello
engines/bastion/test/content-views/details/content-view-versions.controller.test.js
JavaScript
gpl-2.0
2,686
var searchData= [ ['lab',['lab',['../laby__game_8c.html#a25906a99ac156db2a45fb02be50f480b',1,'laby_game.c']]], ['laby_5fcell_5fstr',['Laby_Cell_str',['../struct_laby___cell__str.html',1,'']]], ['laby_5fcell_5fstr_5ft',['Laby_Cell_str_t',['../labyrinthe_8h.html#a82736ab0a9cebda7089540f9e7d9564e',1,'labyrinthe.h']]], ['laby_5fconfig_5fstr_5ft',['Laby_Config_str_t',['../struct_laby___config__str__t.html',1,'']]], ['laby_5fempty',['LABY_EMPTY',['../labyrinthe_8h.html#a7040aafffdec4ece2c4d64d6e9a1afec',1,'labyrinthe.h']]], ['laby_5fempty_5ftype_5fentrance',['LABY_EMPTY_TYPE_ENTRANCE',['../labyrinthe_8h.html#aa1d8a167e47d56b098bbb9cbb96f68d1',1,'labyrinthe.h']]], ['laby_5fempty_5ftype_5fexit',['LABY_EMPTY_TYPE_EXIT',['../labyrinthe_8h.html#a1379f41f6c3db34ed5e8185f5ea90123',1,'labyrinthe.h']]], ['laby_5fenemy',['LABY_ENEMY',['../labyrinthe_8h.html#a0e5472b80e21a4d72f83b2d78e54c0df',1,'labyrinthe.h']]], ['laby_5fenemy_5ftype_5fbasic',['LABY_ENEMY_TYPE_BASIC',['../labyrinthe_8h.html#ac956013719cf938f7827ee809cdb7eb0',1,'labyrinthe.h']]], ['laby_5fenemy_5ftype_5fghost',['LABY_ENEMY_TYPE_GHOST',['../labyrinthe_8h.html#ab5717345aea06e2630c7d218855da882',1,'labyrinthe.h']]], ['laby_5fentity_5fstr_5ft',['Laby_Entity_str_t',['../struct_laby___entity__str__t.html',1,'']]], ['laby_5fgame_2ec',['laby_game.c',['../laby__game_8c.html',1,'']]], ['laby_5fgame_2eh',['laby_game.h',['../laby__game_8h.html',1,'']]], ['laby_5fgame_5fcheck_5fif_5fplayer_5fdead',['laby_game_check_if_player_dead',['../laby__game_8c.html#afd5521d2ad5f69e53580fbb9cfb192f2',1,'laby_game_check_if_player_dead(void):&#160;laby_game.c'],['../laby__game_8h.html#afd5521d2ad5f69e53580fbb9cfb192f2',1,'laby_game_check_if_player_dead(void):&#160;laby_game.c']]], ['laby_5fgame_5fcheck_5fvictory',['laby_game_check_victory',['../laby__game_8c.html#a626d1a95ec0919111ec10ae9ed9f4de0',1,'laby_game_check_victory():&#160;laby_game.c'],['../laby__game_8h.html#a7563854b86a59db03da0b9180647effd',1,'laby_game_check_victory(void):&#160;laby_game.c']]], ['laby_5fgame_5fcycle',['laby_game_cycle',['../laby__game_8c.html#a8f01d7717e82dcd1a006aadf515bc5e2',1,'laby_game_cycle():&#160;laby_game.c'],['../laby__game_8h.html#a9a2c88267f39f8809b99700f888a9720',1,'laby_game_cycle(void):&#160;laby_game.c']]], ['laby_5fgame_5fend',['laby_game_end',['../laby__game_8c.html#adfa8872467893cc5b90392212e98bcad',1,'laby_game_end():&#160;laby_game.c'],['../laby__game_8h.html#adfa8872467893cc5b90392212e98bcad',1,'laby_game_end():&#160;laby_game.c']]], ['laby_5fgame_5fenemies_5fmove',['laby_game_enemies_move',['../laby__game_8c.html#ae8e5f14b6f68e3e975e3302f85597670',1,'laby_game.c']]], ['laby_5fgame_5fgraphics_5fdraw',['laby_game_graphics_draw',['../laby__game_8c.html#a6645dab946fc12f63cefa299406e834b',1,'laby_game.c']]], ['laby_5fgame_5finit',['laby_game_init',['../laby__game_8c.html#afb743615e4fc41dd9839d7910d67dfae',1,'laby_game_init():&#160;laby_game.c'],['../laby__game_8h.html#a8bc40a2ba969ae52650a0f64cad5cc29',1,'laby_game_init(void):&#160;laby_game.c']]], ['laby_5fgame_5finit_5foptions',['laby_game_init_options',['../laby__game_8c.html#a15bb4b3be948b3e2b2b52ec913f4db8d',1,'laby_game_init_options():&#160;laby_game.c'],['../laby__game_8h.html#a43cf1bbb8a004d1347c85ca1f5681136',1,'laby_game_init_options(void):&#160;laby_game.c']]], ['laby_5fgame_5floader_5finit',['laby_game_loader_init',['../laby__game_8c.html#a5dcf27ad8883689ccb97e549ad36b9bc',1,'laby_game_loader_init(void):&#160;laby_game.c'],['../laby__game_8h.html#a5dcf27ad8883689ccb97e549ad36b9bc',1,'laby_game_loader_init(void):&#160;laby_game.c']]], ['laby_5fgame_5fmenu_5fhandler',['laby_game_menu_handler',['../laby__game_8c.html#ae87b5883324b961eb3dd9261b354b0a4',1,'laby_game_menu_handler(void):&#160;laby_game.c'],['../laby__game_8h.html#ae87b5883324b961eb3dd9261b354b0a4',1,'laby_game_menu_handler(void):&#160;laby_game.c']]], ['laby_5fgame_5fmenu_5finit',['laby_game_menu_init',['../laby__game_8c.html#a91040ac5235a2ead6c51f28c4fd6de18',1,'laby_game_menu_init(void):&#160;laby_game.c'],['../laby__game_8h.html#a91040ac5235a2ead6c51f28c4fd6de18',1,'laby_game_menu_init(void):&#160;laby_game.c']]], ['laby_5fgame_5fplayer_5fcheck_5fdeath',['laby_game_player_check_death',['../laby__game_8c.html#aa38b62b4825facaeb4a9901b6182193c',1,'laby_game.c']]], ['laby_5fgame_5fplayer_5fmove',['laby_game_player_move',['../laby__game_8c.html#a3301e05a6d96749fe61475a5cff9c501',1,'laby_game_player_move():&#160;laby_game.c'],['../laby__game_8h.html#ab99f8d1b0fb6d6ae6079657ffd898827',1,'laby_game_player_move(void):&#160;laby_game.c']]], ['laby_5fgame_5fprint_5fscore',['laby_game_print_score',['../laby__game_8c.html#a13da3c052ffa242147f30a2da4413132',1,'laby_game.c']]], ['laby_5fgame_5fscoring_5fhandling',['laby_game_scoring_handling',['../laby__game_8c.html#a3f98370460e68ecdcd1046511902ac95',1,'laby_game.c']]], ['laby_5fgameplay_5fcalculate_5fscore',['laby_gameplay_calculate_score',['../gameplay_8c.html#a6b67e07de23004352fb18dc4b94c4d71',1,'laby_gameplay_calculate_score(uint32_t computerMoves, Player_Score_str_t *player):&#160;gameplay.c'],['../gameplay_8h.html#a6b67e07de23004352fb18dc4b94c4d71',1,'laby_gameplay_calculate_score(uint32_t computerMoves, Player_Score_str_t *player):&#160;gameplay.c']]], ['laby_5fgameplay_5fget_5fmoves',['laby_gameplay_get_moves',['../gameplay_8c.html#a020ae71731d1b4ccee65cc61fe9fdcc1',1,'laby_gameplay_get_moves(void):&#160;gameplay.c'],['../gameplay_8h.html#a020ae71731d1b4ccee65cc61fe9fdcc1',1,'laby_gameplay_get_moves(void):&#160;gameplay.c']]], ['laby_5fgameplay_5fget_5fscore',['laby_gameplay_get_score',['../gameplay_8c.html#ac109d4e65da6bb6e34eef4fc93c6ed7d',1,'laby_gameplay_get_score(void):&#160;gameplay.c'],['../gameplay_8h.html#ac109d4e65da6bb6e34eef4fc93c6ed7d',1,'laby_gameplay_get_score(void):&#160;gameplay.c']]], ['laby_5fgameplay_5finit',['laby_gameplay_init',['../gameplay_8c.html#a1738e9f4654500206c94951ebd43e26b',1,'laby_gameplay_init():&#160;gameplay.c'],['../gameplay_8h.html#a1738e9f4654500206c94951ebd43e26b',1,'laby_gameplay_init():&#160;gameplay.c']]], ['laby_5fgameplay_5fmove',['laby_gameplay_move',['../gameplay_8c.html#af1450dd5ad4d1a3f55ce2407620022f3',1,'laby_gameplay_move(Laby_Cell_str_t *src, Laby_Cell_str_t *dst):&#160;gameplay.c'],['../gameplay_8h.html#af1450dd5ad4d1a3f55ce2407620022f3',1,'laby_gameplay_move(Laby_Cell_str_t *src, Laby_Cell_str_t *dst):&#160;gameplay.c']]], ['laby_5fgameplay_5fmove_5fbasic_5fenemy',['laby_gameplay_move_basic_enemy',['../gameplay_8c.html#ab5c9589e730947c8915436e3dd2aefd6',1,'laby_gameplay_move_basic_enemy(Laby_Cell_str_t *src, Laby_Cell_str_t *dst):&#160;gameplay.c'],['../gameplay_8h.html#ab5c9589e730947c8915436e3dd2aefd6',1,'laby_gameplay_move_basic_enemy(Laby_Cell_str_t *src, Laby_Cell_str_t *dst):&#160;gameplay.c']]], ['laby_5fgameplay_5fmove_5fdown',['laby_gameplay_move_down',['../gameplay_8c.html#a1d4d5a96e2b75e871198a5eeb438e981',1,'laby_gameplay_move_down(Laby_Cell_str_t *src):&#160;gameplay.c'],['../gameplay_8h.html#a1d4d5a96e2b75e871198a5eeb438e981',1,'laby_gameplay_move_down(Laby_Cell_str_t *src):&#160;gameplay.c']]], ['laby_5fgameplay_5fmove_5fghost',['laby_gameplay_move_ghost',['../gameplay_8c.html#a72cfd78fb30fec04b859711f327611fe',1,'laby_gameplay_move_ghost(Laby_Cell_str_t *src, Laby_Cell_str_t *dst):&#160;gameplay.c'],['../gameplay_8h.html#a72cfd78fb30fec04b859711f327611fe',1,'laby_gameplay_move_ghost(Laby_Cell_str_t *src, Laby_Cell_str_t *dst):&#160;gameplay.c']]], ['laby_5fgameplay_5fmove_5fhero',['laby_gameplay_move_hero',['../gameplay_8c.html#abf34abb082272357b82861c3661684d8',1,'laby_gameplay_move_hero(Laby_Cell_str_t *src, Laby_Cell_str_t *dst):&#160;gameplay.c'],['../gameplay_8h.html#abf34abb082272357b82861c3661684d8',1,'laby_gameplay_move_hero(Laby_Cell_str_t *src, Laby_Cell_str_t *dst):&#160;gameplay.c']]], ['laby_5fgameplay_5fmove_5fleft',['laby_gameplay_move_left',['../gameplay_8c.html#a4a982c48ba9299fa01c4b17bdd92188d',1,'laby_gameplay_move_left(Laby_Cell_str_t *src):&#160;gameplay.c'],['../gameplay_8h.html#a4a982c48ba9299fa01c4b17bdd92188d',1,'laby_gameplay_move_left(Laby_Cell_str_t *src):&#160;gameplay.c']]], ['laby_5fgameplay_5fmove_5fright',['laby_gameplay_move_right',['../gameplay_8c.html#a52443170a01d4b405ed02a7c477af305',1,'laby_gameplay_move_right(Laby_Cell_str_t *src):&#160;gameplay.c'],['../gameplay_8h.html#a52443170a01d4b405ed02a7c477af305',1,'laby_gameplay_move_right(Laby_Cell_str_t *src):&#160;gameplay.c']]], ['laby_5fgameplay_5fmove_5fup',['laby_gameplay_move_up',['../gameplay_8c.html#ac3bc9b8ab1cbeae7259f523e91a3d227',1,'laby_gameplay_move_up(Laby_Cell_str_t *src):&#160;gameplay.c'],['../gameplay_8h.html#ac3bc9b8ab1cbeae7259f523e91a3d227',1,'laby_gameplay_move_up(Laby_Cell_str_t *src):&#160;gameplay.c']]], ['laby_5fgameplay_5fplayer_5finput',['laby_gameplay_player_input',['../gameplay_8c.html#aac4be0426f0eff0b561646bf33ad3141',1,'laby_gameplay_player_input():&#160;gameplay.c'],['../gameplay_8h.html#aac4be0426f0eff0b561646bf33ad3141',1,'laby_gameplay_player_input():&#160;gameplay.c']]], ['laby_5fgen_5fall_5fvisited',['LABY_GEN_ALL_VISITED',['../labyrinthe_8h.html#a67dbafcd5b2a22452175bd08372d1d61',1,'labyrinthe.h']]], ['laby_5fgen_5frealloc_5flimit',['LABY_GEN_REALLOC_LIMIT',['../labyrinthe_8h.html#a6d8aee36eaae8f5495324fc78104990f',1,'labyrinthe.h']]], ['laby_5fgen_5frealloc_5fsize',['LABY_GEN_REALLOC_SIZE',['../labyrinthe_8h.html#aadbe6404d4628529cd617e80b88359d9',1,'labyrinthe.h']]], ['laby_5fgen_5fvisited_5fe',['LABY_GEN_VISITED_E',['../labyrinthe_8h.html#a899cf38cead1964da67f72eb1a613564',1,'labyrinthe.h']]], ['laby_5fgen_5fvisited_5fn',['LABY_GEN_VISITED_N',['../labyrinthe_8h.html#a63f02595af32f103a98d47a40453c84e',1,'labyrinthe.h']]], ['laby_5fgen_5fvisited_5fs',['LABY_GEN_VISITED_S',['../labyrinthe_8h.html#a2f63bf71c907e56196534f7fbbc30d15',1,'labyrinthe.h']]], ['laby_5fgen_5fvisited_5fw',['LABY_GEN_VISITED_W',['../labyrinthe_8h.html#a3c5645e3cf78f3e1011a07b8558634f3',1,'labyrinthe.h']]], ['laby_5fhero',['LABY_HERO',['../labyrinthe_8h.html#a23294b9907bccab85c6cc632fd8ae4e0',1,'labyrinthe.h']]], ['laby_5fitems',['LABY_ITEMS',['../labyrinthe_8h.html#a84f9ebbac3ab864abef83cff63af59c8',1,'labyrinthe.h']]], ['laby_5fitems_5ftype_5faverage_5ftreasure',['LABY_ITEMS_TYPE_AVERAGE_TREASURE',['../labyrinthe_8h.html#afd2935523280d213a006b3ddba55ae0c',1,'labyrinthe.h']]], ['laby_5fitems_5ftype_5fbig_5ftreasure',['LABY_ITEMS_TYPE_BIG_TREASURE',['../labyrinthe_8h.html#aca0331706230e19ae10ec84f1ce54916',1,'labyrinthe.h']]], ['laby_5fitems_5ftype_5flittle_5ftreasure',['LABY_ITEMS_TYPE_LITTLE_TREASURE',['../labyrinthe_8h.html#a53ccb9ba928499b45965bf29e048e908',1,'labyrinthe.h']]], ['laby_5fpercent_5fprobability_5fof_5fentity',['LABY_PERCENT_PROBABILITY_OF_ENTITY',['../labyrinthe_8h.html#ad82a27f7b19c5fbed859c0a620300076',1,'labyrinthe.h']]], ['laby_5fswap_5fcells_5fproperties',['laby_swap_cells_properties',['../labyrinthe_8c.html#af8778cd9da0908cb34bae721a2200acb',1,'laby_swap_cells_properties(Laby_Cell_str_t *src, Laby_Cell_str_t *dst):&#160;labyrinthe.c'],['../labyrinthe_8h.html#af8778cd9da0908cb34bae721a2200acb',1,'laby_swap_cells_properties(Laby_Cell_str_t *src, Laby_Cell_str_t *dst):&#160;labyrinthe.c']]], ['laby_5ftraps',['LABY_TRAPS',['../labyrinthe_8h.html#a58373484ec9509bf0c6d51e3e8381744',1,'labyrinthe.h']]], ['laby_5funinitialized',['LABY_UNINITIALIZED',['../labyrinthe_8h.html#af043d71b99734527d6b38ad751bdfeea',1,'labyrinthe.h']]], ['laby_5fwall',['LABY_WALL',['../labyrinthe_8h.html#a7970b5ad431f74fba8521a5a12e67d2d',1,'labyrinthe.h']]], ['laby_5fwall_5ftype_5fbasic',['LABY_WALL_TYPE_BASIC',['../labyrinthe_8h.html#a146a69ea5a79f8b73db7e99eccaa8cd8',1,'labyrinthe.h']]], ['laby_5fwall_5ftype_5fsolid',['LABY_WALL_TYPE_SOLID',['../labyrinthe_8h.html#a6c0e03774f2be694353d29b5ac9aa012',1,'labyrinthe.h']]], ['labyrinthe',['Labyrinthe',['../labyrinthe_8h.html#a635e69b4b8a1e09ca9a01d30559ebec7',1,'labyrinthe.h']]], ['labyrinthe_2ec',['labyrinthe.c',['../labyrinthe_8c.html',1,'']]], ['labyrinthe_2eh',['labyrinthe.h',['../labyrinthe_8h.html',1,'']]], ['labyrinthe_5falloc',['labyrinthe_alloc',['../labyrinthe_8c.html#a135c723a5811ad30fd17c09e92fce63a',1,'labyrinthe_alloc(int length, int width, Labyrinthe *lab):&#160;labyrinthe.c'],['../labyrinthe_8h.html#a135c723a5811ad30fd17c09e92fce63a',1,'labyrinthe_alloc(int length, int width, Labyrinthe *lab):&#160;labyrinthe.c']]], ['labyrinthe_5fbuild_5fentities',['labyrinthe_build_entities',['../labyrinthe_8c.html#af31048c6392c48aa2b8fdc901f70362e',1,'labyrinthe_build_entities(Labyrinthe *lab, Laby_Config_str_t c):&#160;labyrinthe.c'],['../labyrinthe_8h.html#aac177994ca4921b20bbaab61d033509c',1,'labyrinthe_build_entities(Labyrinthe *lab, Laby_Config_str_t config):&#160;labyrinthe.c']]], ['labyrinthe_5fbuild_5fwalls',['labyrinthe_build_walls',['../labyrinthe_8c.html#ade1ff948ab7682c54fda3710281a7092',1,'labyrinthe_build_walls(Labyrinthe *lab):&#160;labyrinthe.c'],['../labyrinthe_8h.html#ade1ff948ab7682c54fda3710281a7092',1,'labyrinthe_build_walls(Labyrinthe *lab):&#160;labyrinthe.c']]], ['labyrinthe_5ffree',['labyrinthe_free',['../labyrinthe_8c.html#adef95afa6763b393ca4bccbf8c2df69b',1,'labyrinthe_free(Labyrinthe *lab):&#160;labyrinthe.c'],['../labyrinthe_8h.html#adef95afa6763b393ca4bccbf8c2df69b',1,'labyrinthe_free(Labyrinthe *lab):&#160;labyrinthe.c']]], ['labyrinthe_5fgenerate',['labyrinthe_generate',['../labyrinthe_8c.html#a9c76a800094b1f36452310e6253a022c',1,'labyrinthe_generate(Laby_Config_str_t config, Labyrinthe *lab):&#160;labyrinthe.c'],['../labyrinthe_8h.html#a9c76a800094b1f36452310e6253a022c',1,'labyrinthe_generate(Laby_Config_str_t config, Labyrinthe *lab):&#160;labyrinthe.c']]], ['labyrinthe_5finit',['labyrinthe_init',['../labyrinthe_8c.html#a86e89ccff6ea4a6cc95478652f228782',1,'labyrinthe_init(char *filename, Labyrinthe *lab):&#160;labyrinthe.c'],['../labyrinthe_8h.html#a86e89ccff6ea4a6cc95478652f228782',1,'labyrinthe_init(char *filename, Labyrinthe *lab):&#160;labyrinthe.c']]], ['labyrinthe_5fresolve',['labyrinthe_resolve',['../labyrinthe_8c.html#a09b2603c97d215d144844e4a863fb70c',1,'labyrinthe_resolve(Labyrinthe *lab):&#160;labyrinthe.c'],['../labyrinthe_8h.html#a09b2603c97d215d144844e4a863fb70c',1,'labyrinthe_resolve(Labyrinthe *lab):&#160;labyrinthe.c']]], ['largeur',['largeur',['../struct_laby___config__str__t.html#ae8ded75fa279600ce4e01be4d2da8914',1,'Laby_Config_str_t']]], ['line',['line',['../struct_laby___cell__str.html#a311196674133e618759342d6be698474',1,'Laby_Cell_str']]], ['loadedlabyname',['loadedLabyName',['../laby__game_8c.html#a43800d03f5b68e26143d30f275af2c2c',1,'laby_game.c']]], ['longueur',['longueur',['../struct_laby___config__str__t.html#ad2fe22a2049e955665d05b11f59e4bab',1,'Laby_Config_str_t']]] ];
Benjix12/Labyrinth_C
doc/html/search/all_8.js
JavaScript
gpl-2.0
14,862