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":"78335000","cidade":"Colniza","uf":"MT","estado":"Mato Grosso"});
| lfreneda/cepdb | api/v1/78335000.jsonp.js | JavaScript | cc0-1.0 | 79 |
jsonp({"cep":"81490292","logradouro":"Rua Francisca Veiga do Amaral","bairro":"Campo de Santana","cidade":"Curitiba","uf":"PR","estado":"Paran\u00e1"});
| lfreneda/cepdb | api/v1/81490292.jsonp.js | JavaScript | cc0-1.0 | 153 |
jsonp({"cep":"74937510","logradouro":"Rua H 152","bairro":"Cidade Vera Cruz","cidade":"Aparecida de Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
| lfreneda/cepdb | api/v1/74937510.jsonp.js | JavaScript | cc0-1.0 | 149 |
jsonp({"cep":"74683630","logradouro":"Rua GB-0023","bairro":"Jardim Guanabara II","cidade":"Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
| lfreneda/cepdb | api/v1/74683630.jsonp.js | JavaScript | cc0-1.0 | 141 |
jsonp({"cep":"13487064","logradouro":"Rua Jo\u00e3o Geraldello","bairro":"Jardim Manoel Francisco","cidade":"Limeira","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/13487064.jsonp.js | JavaScript | cc0-1.0 | 157 |
jsonp({"cep":"07955020","logradouro":"Rua Cinquenta e Cinco","bairro":"Jardim Vassouras","cidade":"Francisco Morato","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/07955020.jsonp.js | JavaScript | cc0-1.0 | 156 |
jsonp({"cep":"21515001","logradouro":"Avenida Brasil","bairro":"Barros Filho","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
| lfreneda/cepdb | api/v1/21515001.jsonp.js | JavaScript | cc0-1.0 | 143 |
jsonp({"cep":"88318435","logradouro":"Rua Vicente Policarpo de Borba Filho","bairro":"Campeche","cidade":"Itaja\u00ed","uf":"SC","estado":"Santa Catarina"});
| lfreneda/cepdb | api/v1/88318435.jsonp.js | JavaScript | cc0-1.0 | 158 |
jsonp({"cep":"76913650","logradouro":"Rua J\u00falio Prestes","bairro":"S\u00e3o Pedro","cidade":"Ji-Paran\u00e1","uf":"RO","estado":"Rond\u00f4nia"});
| lfreneda/cepdb | api/v1/76913650.jsonp.js | JavaScript | cc0-1.0 | 152 |
jsonp({"cep":"26021310","logradouro":"Rua Bicuiba","bairro":"Vila S\u00e3o Teodoro","cidade":"Nova Igua\u00e7u","uf":"RJ","estado":"Rio de Janeiro"});
| lfreneda/cepdb | api/v1/26021310.jsonp.js | JavaScript | cc0-1.0 | 151 |
jsonp({"cep":"44004016","logradouro":"Travessa 28 de Fevereiro","bairro":"Ch\u00e1cara S\u00e3o Cosme","cidade":"Feira de Santana","uf":"BA","estado":"Bahia"});
| lfreneda/cepdb | api/v1/44004016.jsonp.js | JavaScript | cc0-1.0 | 161 |
jsonp({"cep":"91787790","logradouro":"Rua Doutor Jos\u00e9 Sanfelice Neto","bairro":"Restinga","cidade":"Porto Alegre","uf":"RS","estado":"Rio Grande do Sul"});
| lfreneda/cepdb | api/v1/91787790.jsonp.js | JavaScript | cc0-1.0 | 161 |
jsonp({"cep":"69092130","logradouro":"Avenida Madre Tereza","bairro":"Nova Cidade","cidade":"Manaus","uf":"AM","estado":"Amazonas"});
| lfreneda/cepdb | api/v1/69092130.jsonp.js | JavaScript | cc0-1.0 | 134 |
jsonp({"cep":"38444322","logradouro":"Rua Dezesseis","bairro":"Santiago","cidade":"Araguari","uf":"MG","estado":"Minas Gerais"});
| lfreneda/cepdb | api/v1/38444322.jsonp.js | JavaScript | cc0-1.0 | 130 |
jsonp({"cep":"27970650","logradouro":"Rua Dez","bairro":"S\u00e3o Jos\u00e9 do Barreto","cidade":"Maca\u00e9","uf":"RJ","estado":"Rio de Janeiro"});
| lfreneda/cepdb | api/v1/27970650.jsonp.js | JavaScript | cc0-1.0 | 149 |
jsonp({"cep":"74445080","logradouro":"Pra\u00e7a Odarcino Dutra de Oliveira","bairro":"Vila Jo\u00e3o Vaz","cidade":"Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
| lfreneda/cepdb | api/v1/74445080.jsonp.js | JavaScript | cc0-1.0 | 166 |
jsonp({"cep":"99050270","logradouro":"Rua Giuseppe Marchi","bairro":"Petr\u00f3polis","cidade":"Passo Fundo","uf":"RS","estado":"Rio Grande do Sul"});
| lfreneda/cepdb | api/v1/99050270.jsonp.js | JavaScript | cc0-1.0 | 151 |
jsonp({"cep":"40254380","logradouro":"2\u00aa Avenida Salustiano","bairro":"Cosme de Farias","cidade":"Salvador","uf":"BA","estado":"Bahia"});
| lfreneda/cepdb | api/v1/40254380.jsonp.js | JavaScript | cc0-1.0 | 143 |
jsonp({"cep":"66065090","logradouro":"Passagem Ant\u00f4nio Monteiro","bairro":"Condor","cidade":"Bel\u00e9m","uf":"PA","estado":"Par\u00e1"});
| lfreneda/cepdb | api/v1/66065090.jsonp.js | JavaScript | cc0-1.0 | 144 |
jsonp({"cep":"36774156","logradouro":"Rua Ana \u00c1vila Thome","bairro":"Thom\u00e9","cidade":"Cataguases","uf":"MG","estado":"Minas Gerais"});
| lfreneda/cepdb | api/v1/36774156.jsonp.js | JavaScript | cc0-1.0 | 145 |
jsonp({"cep":"60330165","logradouro":"Rua Joaquim Machado da Ponte","bairro":"Barra do Cear\u00e1","cidade":"Fortaleza","uf":"CE","estado":"Cear\u00e1"});
| lfreneda/cepdb | api/v1/60330165.jsonp.js | JavaScript | cc0-1.0 | 155 |
jsonp({"cep":"40050126","logradouro":"Vila Escada do Toror\u00f3","bairro":"Toror\u00f3","cidade":"Salvador","uf":"BA","estado":"Bahia"});
| lfreneda/cepdb | api/v1/40050126.jsonp.js | JavaScript | cc0-1.0 | 139 |
jsonp({"cep":"89095970","logradouro":"Rua Josef Woerner","bairro":"Vila Itoupava","cidade":"Blumenau","uf":"SC","estado":"Santa Catarina"});
| lfreneda/cepdb | api/v1/89095970.jsonp.js | JavaScript | cc0-1.0 | 141 |
jsonp({"cep":"06653460","logradouro":"Rua Dora","bairro":"Jardim Julieta","cidade":"Itapevi","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/06653460.jsonp.js | JavaScript | cc0-1.0 | 132 |
jsonp({"cep":"07811130","logradouro":"Rua Ilha","bairro":"Jardim das Colinas","cidade":"Franco da Rocha","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/07811130.jsonp.js | JavaScript | cc0-1.0 | 144 |
jsonp({"cep":"16027213","logradouro":"Rua Alice Raimundo Cini","bairro":"Ch\u00e1caras de Recreio Monteiro","cidade":"Ara\u00e7atuba","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/16027213.jsonp.js | JavaScript | cc0-1.0 | 173 |
jsonp({"cep":"71615220","logradouro":"Quadra SHIS QI 7 Conjunto 2","bairro":"Setor de Habita\u00e7\u00f5es Individuais Sul","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
| lfreneda/cepdb | api/v1/71615220.jsonp.js | JavaScript | cc0-1.0 | 190 |
jsonp({"cep":"82030262","logradouro":"Jardinete Professora P\u00f3rcia Guimar\u00e3es Alves","bairro":"Santa Felicidade","cidade":"Curitiba","uf":"PR","estado":"Paran\u00e1"});
| lfreneda/cepdb | api/v1/82030262.jsonp.js | JavaScript | cc0-1.0 | 177 |
jsonp({"cep":"72578240","logradouro":"Ch\u00e1cara Ch\u00e1caras 14","bairro":"N\u00facleo Rural Hortigranjeiro de Santa Maria","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
| lfreneda/cepdb | api/v1/72578240.jsonp.js | JavaScript | cc0-1.0 | 194 |
jsonp({"cep":"08473580","logradouro":"Travessa Jos\u00e9 C\u00e2ndido de Andrade Murici","bairro":"Conjunto Habitacional Barro Branco II","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/08473580.jsonp.js | JavaScript | cc0-1.0 | 203 |
jsonp({"cep":"58400976","logradouro":"Rua Antenor Navarro","bairro":"Prata","cidade":"Campina Grande","uf":"PB","estado":"Para\u00edba"});
| lfreneda/cepdb | api/v1/58400976.jsonp.js | JavaScript | cc0-1.0 | 139 |
jsonp({"cep":"66085110","logradouro":"Travessa Curuzu","bairro":"Pedreira","cidade":"Bel\u00e9m","uf":"PA","estado":"Par\u00e1"});
| lfreneda/cepdb | api/v1/66085110.jsonp.js | JavaScript | cc0-1.0 | 131 |
jsonp({"cep":"41280610","logradouro":"Rua Ant\u00f4nio Carlista","bairro":"Marechal Rondon","cidade":"Salvador","uf":"BA","estado":"Bahia"});
| lfreneda/cepdb | api/v1/41280610.jsonp.js | JavaScript | cc0-1.0 | 142 |
jsonp({"cep":"29167016","logradouro":"Rua Fortaleza","bairro":"Alterosas","cidade":"Serra","uf":"ES","estado":"Esp\u00edrito Santo"});
| lfreneda/cepdb | api/v1/29167016.jsonp.js | JavaScript | cc0-1.0 | 135 |
jsonp({"cep":"65916480","logradouro":"Travessa Dois","bairro":"Parque do Buriti","cidade":"Imperatriz","uf":"MA","estado":"Maranh\u00e3o"});
| lfreneda/cepdb | api/v1/65916480.jsonp.js | JavaScript | cc0-1.0 | 141 |
jsonp({"cep":"54767770","logradouro":"Rua Jos\u00e9 Clementino Melo","bairro":"Santa M\u00f4nica","cidade":"Camaragibe","uf":"PE","estado":"Pernambuco"});
| lfreneda/cepdb | api/v1/54767770.jsonp.js | JavaScript | cc0-1.0 | 155 |
jsonp({"cep":"07113210","logradouro":"Rua Sargento J. Donz\u00edlio dos Santos","bairro":"Vila Edgar","cidade":"Guarulhos","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/07113210.jsonp.js | JavaScript | cc0-1.0 | 162 |
// Joe Presbrey <presbrey@mit.edu>
// 2007-07-15
// 2010-08-08 TimBL folded in Kenny's WEBDAV
// 2010-12-07 TimBL addred local file write code
const docpart = require('./uri').docpart
const Fetcher = require('./fetcher')
const graph = require('./data-factory').graph
import IndexedFormula from './indexed-formula'
const namedNode = require('./data-factory').namedNode
const Namespace = require('./namespace')
const Serializer = require('./serializer')
const uriJoin = require('./uri').join
const Util = require('./util')
var UpdateManager = (function () {
var sparql = function (store) {
this.store = store
if (store.updater) {
throw new Error("You can't have two UpdateManagers for the same store")
}
if (!store.fetcher) { // The store must also/already have a fetcher
new Fetcher(store)
}
store.updater = this
this.ifps = {}
this.fps = {}
this.ns = {}
this.ns.link = Namespace('http://www.w3.org/2007/ont/link#')
this.ns.http = Namespace('http://www.w3.org/2007/ont/http#')
this.ns.httph = Namespace('http://www.w3.org/2007/ont/httph#')
this.ns.ldp = Namespace('http://www.w3.org/ns/ldp#')
this.ns.rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
this.ns.rdfs = Namespace('http://www.w3.org/2000/01/rdf-schema#')
this.ns.rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
this.ns.owl = Namespace('http://www.w3.org/2002/07/owl#')
this.patchControl = [] // index of objects fro coordinating incomng and outgoing patches
}
sparql.prototype.patchControlFor = function (doc) {
if (!this.patchControl[doc.uri]) {
this.patchControl[doc.uri] = []
}
return this.patchControl[doc.uri]
}
// Returns The method string SPARQL or DAV or LOCALFILE or false if known, undefined if not known.
//
// Files have to have a specific annotaton that they are machine written, for safety.
// We don't actually check for write access on files.
//
sparql.prototype.editable = function (uri, kb) {
if (!uri) {
return false // Eg subject is bnode, no known doc to write to
}
if (!kb) {
kb = this.store
}
if (uri.slice(0, 8) === 'file:///') {
if (kb.holds(
kb.sym(uri),
namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
namedNode('http://www.w3.org/2007/ont/link#MachineEditableDocument')
)) {
return 'LOCALFILE'
}
var sts = kb.statementsMatching(kb.sym(uri), undefined, undefined)
console.log('sparql.editable: Not MachineEditableDocument file ' +
uri + '\n')
console.log(sts.map(function (x) {
return x.toNT()
}).join('\n'))
return false
// @@ Would be nifty of course to see whether we actually have write acess first.
}
var request
var definitive = false
var requests = kb.each(undefined, this.ns.link('requestedURI'),
docpart(uri))
// Hack for the moment @@@@ 2016-02-12
if (kb.holds(namedNode(uri), this.ns.rdf('type'), this.ns.ldp('Resource'))) {
return 'SPARQL'
}
var i
var method
for (var r = 0; r < requests.length; r++) {
request = requests[r]
if (request !== undefined) {
var response = kb.any(request, this.ns.link('response'))
if (request !== undefined) {
var acceptPatch = kb.each(response, this.ns.httph('accept-patch'))
if (acceptPatch.length) {
for (i = 0; i < acceptPatch.length; i++) {
method = acceptPatch[i].value.trim()
if (method.indexOf('application/sparql-update') >= 0) return 'SPARQL'
}
}
var author_via = kb.each(response, this.ns.httph('ms-author-via'))
if (author_via.length) {
for (i = 0; i < author_via.length; i++) {
method = author_via[i].value.trim()
if (method.indexOf('SPARQL') >= 0) {
return 'SPARQL'
}
if (method.indexOf('DAV') >= 0) {
return 'DAV'
}
}
}
var status = kb.each(response, this.ns.http('status'))
if (status.length) {
for (i = 0; i < status.length; i++) {
if (status[i] === 200 || status[i] === 404) {
definitive = true
// return false // A definitive answer
}
}
}
} else {
console.log('sparql.editable: No response for ' + uri + '\n')
}
}
}
if (requests.length === 0) {
console.log('sparql.editable: No request for ' + uri + '\n')
} else {
if (definitive) {
return false // We have got a request and it did NOT say editable => not editable
}
}
console.log('sparql.editable: inconclusive for ' + uri + '\n')
return undefined // We don't know (yet) as we haven't had a response (yet)
}
// ///////// The identification of bnodes
sparql.prototype.anonymize = function (obj) {
return (obj.toNT().substr(0, 2) === '_:' && this._mentioned(obj))
? '?' + obj.toNT().substr(2)
: obj.toNT()
}
sparql.prototype.anonymizeNT = function (stmt) {
return this.anonymize(stmt.subject) + ' ' +
this.anonymize(stmt.predicate) + ' ' +
this.anonymize(stmt.object) + ' .'
}
// A list of all bnodes occuring in a statement
sparql.prototype._statement_bnodes = function (st) {
return [st.subject, st.predicate, st.object].filter(function (x) {
return x.isBlank
})
}
// A list of all bnodes occuring in a list of statements
sparql.prototype._statement_array_bnodes = function (sts) {
var bnodes = []
for (var i = 0; i < sts.length; i++) {
bnodes = bnodes.concat(this._statement_bnodes(sts[i]))
}
bnodes.sort() // in place sort - result may have duplicates
var bnodes2 = []
for (var j = 0; j < bnodes.length; j++) {
if (j === 0 || !bnodes[j].sameTerm(bnodes[j - 1])) {
bnodes2.push(bnodes[j])
}
}
return bnodes2
}
sparql.prototype._cache_ifps = function () {
// Make a cached list of [Inverse-]Functional properties
// Call this once before calling context_statements
this.ifps = {}
var a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('InverseFunctionalProperty'))
for (var i = 0; i < a.length; i++) {
this.ifps[a[i].uri] = true
}
this.fps = {}
a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('FunctionalProperty'))
for (i = 0; i < a.length; i++) {
this.fps[a[i].uri] = true
}
}
// Returns a context to bind a given node, up to a given depth
sparql.prototype._bnode_context2 = function (x, source, depth) {
// Return a list of statements which indirectly identify a node
// Depth > 1 if try further indirection.
// Return array of statements (possibly empty), or null if failure
var sts = this.store.statementsMatching(undefined, undefined, x, source) // incoming links
var y
var res
for (var i = 0; i < sts.length; i++) {
if (this.fps[sts[i].predicate.uri]) {
y = sts[i].subject
if (!y.isBlank) {
return [ sts[i] ]
}
if (depth) {
res = this._bnode_context2(y, source, depth - 1)
if (res) {
return res.concat([ sts[i] ])
}
}
}
}
// outgoing links
sts = this.store.statementsMatching(x, undefined, undefined, source)
for (i = 0; i < sts.length; i++) {
if (this.ifps[sts[i].predicate.uri]) {
y = sts[i].object
if (!y.isBlank) {
return [ sts[i] ]
}
if (depth) {
res = this._bnode_context2(y, source, depth - 1)
if (res) {
return res.concat([ sts[i] ])
}
}
}
}
return null // Failure
}
// Returns the smallest context to bind a given single bnode
sparql.prototype._bnode_context_1 = function (x, source) {
// Return a list of statements which indirectly identify a node
// Breadth-first
var self = this
for (var depth = 0; depth < 3; depth++) { // Try simple first
var con = this._bnode_context2(x, source, depth)
if (con !== null) return con
}
// If we can't guarantee unique with logic just send all info about node
return this.store.connectedStatements(x, source) // was:
// throw new Error('Unable to uniquely identify bnode: ' + x.toNT())
}
sparql.prototype._mentioned = function (x) {
return (this.store.statementsMatching(x).length !== 0) || // Don't pin fresh bnodes
(this.store.statementsMatching(undefined, x).length !== 0) ||
(this.store.statementsMatching(undefined, undefined, x).length !== 0)
}
sparql.prototype._bnode_context = function (bnodes, doc) {
var context = []
if (bnodes.length) {
this._cache_ifps()
for (var i = 0; i < bnodes.length; i++) { // Does this occur in old graph?
var bnode = bnodes[i]
if (!this._mentioned(bnode)) continue
context = context.concat(this._bnode_context_1(bnode, doc))
}
}
return context
}
/* Weird code does not make sense -- some code corruption along the line -- st undefined -- weird
sparql.prototype._bnode_context = function(bnodes) {
var context = []
if (bnodes.length) {
if (this.store.statementsMatching(st.subject.isBlank?undefined:st.subject,
st.predicate.isBlank?undefined:st.predicate,
st.object.isBlank?undefined:st.object,
st.why).length <= 1) {
context = context.concat(st)
} else {
this._cache_ifps()
for (x in bnodes) {
context = context.concat(this._bnode_context_1(bnodes[x], st.why))
}
}
}
return context
}
*/
// Returns the best context for a single statement
sparql.prototype._statement_context = function (st) {
var bnodes = this._statement_bnodes(st)
return this._bnode_context(bnodes, st.why)
}
sparql.prototype._context_where = function (context) {
var sparql = this
return (!context || context.length === 0)
? ''
: 'WHERE { ' +
context.map(function (x) {
return sparql.anonymizeNT(x)
}).join('\n') + ' }\n'
}
sparql.prototype._fire = function (uri, query, callback) {
if (!uri) {
throw new Error('No URI given for remote editing operation: ' + query)
}
console.log('sparql: sending update to <' + uri + '>')
var xhr = Util.XMLHTTPFactory()
xhr.options = {}
xhr.onreadystatechange = function () {
// dump("SPARQL update ready state for <"+uri+"> readyState="+xhr.readyState+"\n"+query+"\n")
if (xhr.readyState === 4) {
var success = (!xhr.status || (xhr.status >= 200 && xhr.status < 300))
if (!success) {
console.log('sparql: update failed for <' + uri + '> status=' +
xhr.status + ', ' + xhr.statusText + ', body length=' + xhr.responseText.length + '\n for query: ' + query)
} else {
console.log('sparql: update Ok for <' + uri + '>')
}
callback(uri, success, xhr.responseText, xhr)
}
}
xhr.open('PATCH', uri, true) // async=true
xhr.setRequestHeader('Content-type', 'application/sparql-update')
xhr.send(query)
}
// This does NOT update the statement.
// It returns an object whcih includes
// function which can be used to change the object of the statement.
//
sparql.prototype.update_statement = function (statement) {
if (statement && !statement.why) {
return
}
var sparql = this
var context = this._statement_context(statement)
return {
statement: statement ? [statement.subject, statement.predicate, statement.object, statement.why] : undefined,
statementNT: statement ? this.anonymizeNT(statement) : undefined,
where: sparql._context_where(context),
set_object: function (obj, callback) {
var query = this.where
query += 'DELETE DATA { ' + this.statementNT + ' } ;\n'
query += 'INSERT DATA { ' +
this.anonymize(this.statement[0]) + ' ' +
this.anonymize(this.statement[1]) + ' ' +
this.anonymize(obj) + ' ' + ' . }\n'
sparql._fire(this.statement[3].uri, query, callback)
}
}
}
sparql.prototype.insert_statement = function (st, callback) {
var st0 = st instanceof Array ? st[0] : st
var query = this._context_where(this._statement_context(st0))
if (st instanceof Array) {
var stText = ''
for (var i = 0; i < st.length; i++) stText += st[i] + '\n'
query += 'INSERT DATA { ' + stText + ' }\n'
} else {
query += 'INSERT DATA { ' +
this.anonymize(st.subject) + ' ' +
this.anonymize(st.predicate) + ' ' +
this.anonymize(st.object) + ' ' + ' . }\n'
}
this._fire(st0.why.uri, query, callback)
}
sparql.prototype.delete_statement = function (st, callback) {
var st0 = st instanceof Array ? st[0] : st
var query = this._context_where(this._statement_context(st0))
if (st instanceof Array) {
var stText = ''
for (var i = 0; i < st.length; i++) stText += st[i] + '\n'
query += 'DELETE DATA { ' + stText + ' }\n'
} else {
query += 'DELETE DATA { ' +
this.anonymize(st.subject) + ' ' +
this.anonymize(st.predicate) + ' ' +
this.anonymize(st.object) + ' ' + ' . }\n'
}
this._fire(st0.why.uri, query, callback)
}
// Request a now or future action to refresh changes coming downstream
//
// This is designed to allow the system to re-request the server version,
// when a websocket has pinged to say there are changes.
// If thewebsocket, by contrast, has sent a patch, then this may not be necessary.
// This may be called out of context so *this* cannot be used.
sparql.prototype.requestDownstreamAction = function (doc, action) {
var control = this.patchControlFor(doc)
if (!control.pendingUpstream) {
action(doc)
} else {
if (control.downstreamAction) {
if (control.downstreamAction === action) {
return
} else {
throw new Error("Can't wait for > 1 differnt downstream actions")
}
} else {
control.downstreamAction = action
}
}
}
// We want to start counting websockt notifications
// to distinguish the ones from others from our own.
sparql.prototype.clearUpstreamCount = function (doc) {
var control = this.patchControlFor(doc)
control.upstreamCount = 0
}
sparql.prototype.getUpdatesVia = function (doc) {
var linkHeaders = this.store.fetcher.getHeader(doc, 'updates-via')
if (!linkHeaders || !linkHeaders.length) return null
return linkHeaders[0].trim()
}
sparql.prototype.addDownstreamChangeListener = function (doc, listener) {
var control = this.patchControlFor(doc)
if (!control.downstreamChangeListeners) control.downstreamChangeListeners = []
control.downstreamChangeListeners.push(listener)
var self = this
this.setRefreshHandler(doc, function(doc){ // a function not a method
self.reloadAndSync(doc)
})
}
sparql.prototype.reloadAndSync = function (doc) {
var control = this.patchControlFor(doc)
var updater = this
if (control.reloading) {
console.log(' Already reloading - stop')
return // once only needed
}
control.reloading = true
var retryTimeout = 1000 // ms
var tryReload = function () {
console.log('try reload - timeout = ' + retryTimeout)
updater.reload(updater.store, doc, function (ok, message, xhr) {
control.reloading = false
if (ok) {
if (control.downstreamChangeListeners) {
for (var i = 0; i < control.downstreamChangeListeners.length; i++) {
console.log(' Calling downstream listener ' + i)
control.downstreamChangeListeners[i]()
}
}
} else {
if (xhr.status === 0) {
console.log('Network error refreshing the data. Retrying in ' +
retryTimeout / 1000)
control.reloading = true
retryTimeout = retryTimeout * 2
setTimeout(tryReload, retryTimeout)
} else {
console.log('Error ' + xhr.status + 'refreshing the data:' +
message + '. Stopped' + doc)
}
}
})
}
tryReload()
}
// Set up websocket to listen on
//
// There is coordination between upstream changes and downstream ones
// so that a reload is not done in the middle of an upsteeam patch.
// If you usie this API then you get called when a change happens, and you
// have to reload the file yourself, and then refresh the UI.
// Alternative is addDownstreamChangeListener(), where you do not
// have to do the reload yourslf. Do mot mix them.
//
// kb contains the HTTP metadata from prefvious operations
//
sparql.prototype.setRefreshHandler = function (doc, handler) {
var wssURI = this.getUpdatesVia(doc) // relative
// var kb = this.store
var theHandler = handler
var self = this
var updater = this
var retryTimeout = 1500 // *2 will be 3 Seconds, 6, 12, etc
var retries = 0
if (!wssURI) {
console.log('Server doies not support live updates thoughUpdates-Via :-(')
return false
}
wssURI = uriJoin(wssURI, doc.uri)
wssURI = wssURI.replace(/^http:/, 'ws:').replace(/^https:/, 'wss:')
console.log('Web socket URI ' + wssURI)
var openWebsocket = function () {
// From https://github.com/solid/solid-spec#live-updates
var socket
if (typeof WebSocket !== 'undefined') {
socket = new WebSocket(wssURI)
} else if (typeof Services !== 'undefined') { // Firefox add on http://stackoverflow.com/questions/24244886/is-websocket-supported-in-firefox-for-android-addons
socket = (Services.wm.getMostRecentWindow('navigator:browser').WebSocket)(wssURI)
} else if (typeof window !== 'undefined' && window.WebSocket) {
socket = window.WebSocket(wssURI)
} else {
console.log('Live update disabled, as WebSocket not supported by platform :-(')
return
}
socket.onopen = function () {
console.log(' websocket open')
retryTimeout = 1500 // reset timeout to fast on success
this.send('sub ' + doc.uri)
if (retries) {
console.log('Web socket has been down, better check for any news.')
updater.requestDownstreamAction(doc, theHandler)
}
}
var control = self.patchControlFor(doc)
control.upstreamCount = 0
// https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
//
// 1000 CLOSE_NORMAL Normal closure; the connection successfully completed whatever purpose for which it was created.
// 1001 CLOSE_GOING_AWAY The endpoint is going away, either
// because of a server failure or because the browser is navigating away from the page that opened the connection.
// 1002 CLOSE_PROTOCOL_ERROR The endpoint is terminating the connection due to a protocol error.
// 1003 CLOSE_UNSUPPORTED The connection is being terminated because the endpoint
// received data of a type it cannot accept (for example, a text-only endpoint received binary data).
// 1004 Reserved. A meaning might be defined in the future.
// 1005 CLOSE_NO_STATUS Reserved. Indicates that no status code was provided even though one was expected.
// 1006 CLOSE_ABNORMAL Reserved. Used to indicate that a connection was closed abnormally (
//
//
socket.onclose = function (event) {
console.log('*** Websocket closed with code ' + event.code +
", reason '" + event.reason + "' clean = " + event.clean)
retryTimeout *= 2
retries += 1
console.log('Retrying in ' + retryTimeout + 'ms') // (ask user?)
setTimeout(function () {
console.log('Trying websocket again')
openWebsocket()
}, retryTimeout)
}
socket.onmessage = function (msg) {
if (msg.data && msg.data.slice(0, 3) === 'pub') {
if ('upstreamCount' in control) {
control.upstreamCount -= 1
if (control.upstreamCount >= 0) {
console.log('just an echo: ' + control.upstreamCount)
return // Just an echo
}
}
console.log('Assume a real downstream change: ' + control.upstreamCount + ' -> 0')
control.upstreamCount = 0
self.requestDownstreamAction(doc, theHandler)
}
}
} // openWebsocket
openWebsocket()
return true
}
// This high-level function updates the local store iff the web is changed successfully.
//
// - deletions, insertions may be undefined or single statements or lists or formulae.
// (may contain bnodes which can be indirectly identified by a where clause)
//
// - callback is called as callback(uri, success, errorbody, xhr)
//
sparql.prototype.update = function (deletions, insertions, callback) {
try {
var kb = this.store
var ds = !deletions ? []
: deletions instanceof IndexedFormula ? deletions.statements
: deletions instanceof Array ? deletions : [ deletions ]
var is = !insertions ? []
: insertions instanceof IndexedFormula ? insertions.statements
: insertions instanceof Array ? insertions : [ insertions ]
if (!(ds instanceof Array)) {
throw new Error('Type Error ' + (typeof ds) + ': ' + ds)
}
if (!(is instanceof Array)) {
throw new Error('Type Error ' + (typeof is) + ': ' + is)
}
if (ds.length === 0 && is.length === 0) {
return callback(null, true) // success -- nothing needed to be done.
}
var doc = ds.length ? ds[0].why : is[0].why
var control = this.patchControlFor(doc)
var startTime = Date.now()
var props = ['subject', 'predicate', 'object', 'why']
var verbs = ['insert', 'delete']
var clauses = { 'delete': ds, 'insert': is }
verbs.map(function (verb) {
clauses[verb].map(function (st) {
if (!doc.sameTerm(st.why)) {
throw new Error('update: destination ' + doc +
' inconsistent with delete quad ' + st.why)
}
props.map(function (prop) {
if (typeof st[prop] === 'undefined') {
throw new Error('update: undefined ' + prop + ' of statement.')
}
})
})
})
var protocol = this.editable(doc.uri, kb)
if (!protocol) {
throw new Error("Can't make changes in uneditable " + doc)
}
var i
var newSts
var documentString
var sz
if (protocol.indexOf('SPARQL') >= 0) {
var bnodes = []
if (ds.length) bnodes = this._statement_array_bnodes(ds)
if (is.length) bnodes = bnodes.concat(this._statement_array_bnodes(is))
var context = this._bnode_context(bnodes, doc)
var whereClause = this._context_where(context)
var query = ''
if (whereClause.length) { // Is there a WHERE clause?
if (ds.length) {
query += 'DELETE { '
for (i = 0; i < ds.length; i++) {
query += this.anonymizeNT(ds[i]) + '\n'
}
query += ' }\n'
}
if (is.length) {
query += 'INSERT { '
for (i = 0; i < is.length; i++) {
query += this.anonymizeNT(is[i]) + '\n'
}
query += ' }\n'
}
query += whereClause
} else { // no where clause
if (ds.length) {
query += 'DELETE DATA { '
for (i = 0; i < ds.length; i++) {
query += this.anonymizeNT(ds[i]) + '\n'
}
query += ' } \n'
}
if (is.length) {
if (ds.length) query += ' ; '
query += 'INSERT DATA { '
for (i = 0; i < is.length; i++) {
query += this.anonymizeNT(is[i]) + '\n'
}
query += ' }\n'
}
}
// Track pending upstream patches until they have fnished their callback
control.pendingUpstream = control.pendingUpstream ? control.pendingUpstream + 1 : 1
if ('upstreamCount' in control) {
control.upstreamCount += 1 // count changes we originated ourselves
console.log('upstream count up to : ' + control.upstreamCount)
}
this._fire(doc.uri, query,
function (uri, success, body, xhr) {
xhr.elapsedTime_ms = Date.now() - startTime
console.log(' sparql: Return ' + (success ? 'success' : 'FAILURE ' + xhr.status) +
' elapsed ' + xhr.elapsedTime_ms + 'ms')
if (success) {
try {
kb.remove(ds)
} catch (e) {
success = false
body = 'Remote Ok BUT error deleting ' + ds.length + ' from store!!! ' + e
} // Add in any case -- help recover from weirdness??
for (var i = 0; i < is.length; i++) {
kb.add(is[i].subject, is[i].predicate, is[i].object, doc)
}
}
callback(uri, success, body, xhr)
control.pendingUpstream -= 1
// When upstream patches have been sent, reload state if downstream waiting
if (control.pendingUpstream === 0 && control.downstreamAction) {
var downstreamAction = control.downstreamAction
delete control.downstreamAction
console.log('delayed downstream action:')
downstreamAction(doc)
}
})
} else if (protocol.indexOf('DAV') >= 0) {
// The code below is derived from Kenny's UpdateCenter.js
documentString
var request = kb.any(doc, this.ns.link('request'))
if (!request) {
throw new Error('No record of our HTTP GET request for document: ' +
doc)
} // should not happen
var response = kb.any(request, this.ns.link('response'))
if (!response) {
return null // throw "No record HTTP GET response for document: "+doc
}
var content_type = kb.the(response, this.ns.httph('content-type')).value
// prepare contents of revised document
newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice() // copy!
for (i = 0; i < ds.length; i++) {
Util.RDFArrayRemove(newSts, ds[i])
}
for (i = 0; i < is.length; i++) {
newSts.push(is[i])
}
// serialize to te appropriate format
sz = Serializer(kb)
sz.suggestNamespaces(kb.namespaces)
sz.setBase(doc.uri) // ?? beware of this - kenny (why? tim)
switch (content_type) {
case 'application/rdf+xml':
documentString = sz.statementsToXML(newSts)
break
case 'text/n3':
case 'text/turtle':
case 'application/x-turtle': // Legacy
case 'application/n3': // Legacy
documentString = sz.statementsToN3(newSts)
break
default:
throw new Error('Content-type ' + content_type + ' not supported for data write')
}
// Write the new version back
var candidateTarget = kb.the(response, this.ns.httph('content-location'))
var targetURI
if (candidateTarget) {
targetURI = uriJoin(candidateTarget.value, targetURI)
}
var xhr = Util.XMLHTTPFactory()
xhr.options = {}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// formula from sparqlUpdate.js, what about redirects?
var success = (!xhr.status || (xhr.status >= 200 && xhr.status < 300))
if (success) {
for (var i = 0; i < ds.length; i++) {
kb.remove(ds[i])
}
for (i = 0; i < is.length; i++) {
kb.add(is[i].subject, is[i].predicate, is[i].object, doc)
}
}
callback(doc.uri, success, xhr.responseText)
}
}
xhr.open('PUT', targetURI, true)
// assume the server does PUT content-negotiation.
xhr.setRequestHeader('Content-type', content_type) // OK?
xhr.send(documentString)
} else {
if (protocol.indexOf('LOCALFILE') >= 0) {
try {
console.log('Writing back to local file\n')
// See http://simon-jung.blogspot.com/2007/10/firefox-extension-file-io.html
// prepare contents of revised document
newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice() // copy!
for (i = 0; i < ds.length; i++) {
Util.RDFArrayRemove(newSts, ds[i])
}
for (i = 0; i < is.length; i++) {
newSts.push(is[i])
}
// serialize to the appropriate format
documentString
sz = Serializer(kb)
sz.suggestNamespaces(kb.namespaces)
sz.setBase(doc.uri) // ?? beware of this - kenny (why? tim)
var dot = doc.uri.lastIndexOf('.')
if (dot < 1) {
throw new Error('Rewriting file: No filename extension: ' + doc.uri)
}
var ext = doc.uri.slice(dot + 1)
switch (ext) {
case 'rdf':
case 'owl': // Just my experence ...@@ we should keep the format in which it was parsed
case 'xml':
documentString = sz.statementsToXML(newSts)
break
case 'n3':
case 'nt':
case 'ttl':
documentString = sz.statementsToN3(newSts)
break
default:
throw new Error('File extension .' + ext + ' not supported for data write')
}
// Write the new version back
// create component for file writing
console.log('Writing back: <<<' + documentString + '>>>')
var filename = doc.uri.slice(7) // chop off file:// leaving /path
// console.log("Writeback: Filename: "+filename+"\n")
var file = Components.classes['@mozilla.org/file/local;1']
.createInstance(Components.interfaces.nsILocalFile)
file.initWithPath(filename)
if (!file.exists()) {
throw new Error('Rewriting file <' + doc.uri +
'> but it does not exist!')
}
// {
// file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420)
// }
// create file output stream and use write/create/truncate mode
// 0x02 writing, 0x08 create file, 0x20 truncate length if exist
var stream = Components.classes['@mozilla.org/network/file-output-stream;1']
.createInstance(Components.interfaces.nsIFileOutputStream)
// Various JS systems object to 0666 in struct mode as dangerous
stream.init(file, 0x02 | 0x08 | 0x20, parseInt('0666', 8), 0)
// write data to file then close output stream
stream.write(documentString, documentString.length)
stream.close()
for (i = 0; i < ds.length; i++) {
kb.remove(ds[i])
}
for (i = 0; i < is.length; i++) {
kb.add(is[i].subject, is[i].predicate, is[i].object, doc)
}
callback(doc.uri, true, '') // success!
} catch (e) {
callback(doc.uri, false,
'Exception trying to write back file <' + doc.uri + '>\n'
// + tabulator.Util.stackString(e))
)
}
} else {
throw new Error("Unhandled edit method: '" + protocol + "' for " + doc)
}
}
} catch (e) {
callback(undefined, false, 'Exception in update: ' + e + '\n' + $rdf.Util.stackString(e))
}
} // wnd update
// This suitable for an inital creation of a document
//
// data: string, or array of statements
//
sparql.prototype.put = function (doc, data, content_type, callback) {
var documentString
var kb = this.store
if (typeof data === typeof '') {
documentString = data
} else {
// serialize to te appropriate format
var sz = Serializer(kb)
sz.suggestNamespaces(kb.namespaces)
sz.setBase(doc.uri)
switch (content_type) {
case 'application/rdf+xml':
documentString = sz.statementsToXML(data)
break
case 'text/n3':
case 'text/turtle':
case 'application/x-turtle': // Legacy
case 'application/n3': // Legacy
documentString = sz.statementsToN3(data)
break
default:
throw new Error('Content-type ' + content_type +
' not supported for data PUT')
}
}
var xhr = Util.XMLHTTPFactory()
xhr.options = {}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// formula from sparqlUpdate.js, what about redirects?
var success = (!xhr.status || (xhr.status >= 200 && xhr.status < 300))
if (success && typeof data !== 'string') {
data.map(function (st) {
kb.addStatement(st)
})
// kb.fetcher.requested[doc.uri] = true // as though fetched
}
if (success) {
delete kb.fetcher.nonexistant[doc.uri]
delete kb.fetcher.requested[doc.uri]
// @@ later we can fake it has been requestd if put gives us the header sand we save them.
}
callback(doc.uri, success, xhr.responseText, xhr)
}
}
xhr.open('PUT', doc.uri, true)
xhr.setRequestHeader('Content-type', content_type)
xhr.send(documentString)
}
// Reload a document.
//
// Fast and cheap, no metaata
// Measure times for the document
// Load it provisionally
// Don't delete the statemenst before the load, or it will leave a broken document
// in the meantime.
sparql.prototype.reload = function (kb, doc, callback) {
var startTime = Date.now()
// force sets no-cache and
kb.fetcher.nowOrWhenFetched(doc.uri, {force: true, noMeta: true, clearPreviousData: true}, function (ok, body, xhr) {
if (!ok) {
console.log(' ERROR reloading data: ' + body)
callback(false, 'Error reloading data: ' + body, xhr)
} else if (xhr.onErrorWasCalled || xhr.status !== 200) {
console.log(' Non-HTTP error reloading data! onErrorWasCalled=' +
xhr.onErrorWasCalled + ' status: ' + xhr.status)
callback(false, 'Non-HTTP error reloading data: ' + body, xhr)
} else {
var elapsedTime_ms = Date.now() - startTime
if (!doc.reloadTime_total) doc.reloadTime_total = 0
if (!doc.reloadTime_count) doc.reloadTime_count = 0
doc.reloadTime_total += elapsedTime_ms
doc.reloadTime_count += 1
console.log(' Fetch took ' + elapsedTime_ms + 'ms, av. of ' +
doc.reloadTime_count + ' = ' +
(doc.reloadTime_total / doc.reloadTime_count) + 'ms.')
callback(true)
}
})
}
sparql.prototype.oldReload = function (kb, doc, callback) {
var g2 = graph() // A separate store to hold the data as we load it
var f2 = fetcher(g2)
var startTime = Date.now()
// force sets no-cache and
f2.nowOrWhenFetched(doc.uri, {force: true, noMeta: true, clearPreviousData: true}, function (ok, body, xhr) {
if (!ok) {
console.log(' ERROR reloading data: ' + body)
callback(false, 'Error reloading data: ' + body, xhr)
} else if (xhr.onErrorWasCalled || xhr.status !== 200) {
console.log(' Non-HTTP error reloading data! onErrorWasCalled=' +
xhr.onErrorWasCalled + ' status: ' + xhr.status)
callback(false, 'Non-HTTP error reloading data: ' + body, xhr)
} else {
var sts1 = kb.statementsMatching(undefined, undefined, undefined, doc).slice() // Take a copy!!
var sts2 = g2.statementsMatching(undefined, undefined, undefined, doc).slice()
console.log(' replacing ' + sts1.length + ' with ' + sts2.length +
' out of total statements ' + kb.statements.length)
kb.remove(sts1)
kb.add(sts2)
var elapsedTime_ms = Date.now() - startTime
if (sts2.length === 0) {
console.log('????????????????? 0000000')
}
if (!doc.reloadTime_total) doc.reloadTime_total = 0
if (!doc.reloadTime_count) doc.reloadTime_count = 0
doc.reloadTime_total += elapsedTime_ms
doc.reloadTime_count += 1
console.log(' fetch took ' + elapsedTime_ms + 'ms, av. of ' + doc.reloadTime_count + ' = ' +
(doc.reloadTime_total / doc.reloadTime_count) + 'ms.')
callback(true)
}
})
}
return sparql
})()
module.exports = UpdateManager
| aolite/SemanticHub | node_modules/rdflib/src/update-manager.js | JavaScript | cc0-1.0 | 37,528 |
jsonp({"cep":"12510524","logradouro":"Rua Otto Schellenberg","bairro":"Jardim Fran\u00e7a I","cidade":"Guaratinguet\u00e1","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/12510524.jsonp.js | JavaScript | cc0-1.0 | 162 |
jsonp({"cep":"29146576","logradouro":"Rua Benedito Ces\u00e1rio","bairro":"Campo Grande","cidade":"Cariacica","uf":"ES","estado":"Esp\u00edrito Santo"});
| lfreneda/cepdb | api/v1/29146576.jsonp.js | JavaScript | cc0-1.0 | 154 |
jsonp({"cep":"74490190","logradouro":"Estrada S\u00e3o de Paulo","bairro":"Parque Bom Jesus","cidade":"Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
| lfreneda/cepdb | api/v1/74490190.jsonp.js | JavaScript | cc0-1.0 | 152 |
jsonp({"cep":"73751271","logradouro":"Quadra 14 MR 1","bairro":"Setor Norte","cidade":"Planaltina de Goi\u00e1s","uf":"GO","estado":"Goi\u00e1s"});
| lfreneda/cepdb | api/v1/73751271.jsonp.js | JavaScript | cc0-1.0 | 148 |
jsonp({"cep":"64009295","logradouro":"Rua Miguel Furtado Bacellar","bairro":"Memorare","cidade":"Teresina","uf":"PI","estado":"Piau\u00ed"});
| lfreneda/cepdb | api/v1/64009295.jsonp.js | JavaScript | cc0-1.0 | 142 |
jsonp({"cep":"74863070","logradouro":"Rua Cruzeiro do Sul","bairro":"Jardim Bela Vista","cidade":"Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
| lfreneda/cepdb | api/v1/74863070.jsonp.js | JavaScript | cc0-1.0 | 147 |
jsonp({"cep":"29706320","logradouro":"Rua Jos\u00e9 de Anchieta","bairro":"Vila Am\u00e9lia","cidade":"Colatina","uf":"ES","estado":"Esp\u00edrito Santo"});
| lfreneda/cepdb | api/v1/29706320.jsonp.js | JavaScript | cc0-1.0 | 157 |
jsonp({"cep":"06320170","logradouro":"Rua Pedro Lobas","bairro":"Jardim das Belezas","cidade":"Carapicu\u00edba","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/06320170.jsonp.js | JavaScript | cc0-1.0 | 152 |
jsonp({"cep":"57601322","logradouro":"Rua Tabeli\u00e3o Luiz Vieira de Barros","bairro":"S\u00e3o Crist\u00f3v\u00e3o","cidade":"Palmeira dos \u00cdndios","uf":"AL","estado":"Alagoas"});
| lfreneda/cepdb | api/v1/57601322.jsonp.js | JavaScript | cc0-1.0 | 187 |
jsonp({"cep":"73805345","logradouro":"Rua Virg\u00edlio Alves Ferreira","bairro":"Setor Pampulha","cidade":"Formosa","uf":"GO","estado":"Goi\u00e1s"});
| lfreneda/cepdb | api/v1/73805345.jsonp.js | JavaScript | cc0-1.0 | 152 |
jsonp({"cep":"14178057","logradouro":"Rua Hugo Gaiofatto","bairro":"Jardim Campo Belo","cidade":"Sert\u00e3ozinho","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/14178057.jsonp.js | JavaScript | cc0-1.0 | 154 |
jsonp({"cep":"13256566","logradouro":"Rua Angelo Capeletto","bairro":"Loteamento Residencial Terra Nova","cidade":"Itatiba","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/13256566.jsonp.js | JavaScript | cc0-1.0 | 163 |
jsonp({"cep":"02254030","logradouro":"Pra\u00e7a Ataliba da Costa Vida","bairro":"Vila Nivi","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/02254030.jsonp.js | JavaScript | cc0-1.0 | 158 |
jsonp({"cep":"74391150","logradouro":"Rua Desembargador Em\u00edlio Fleury de Brito","bairro":"Jardim Marques de Abreu","cidade":"Goi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
| lfreneda/cepdb | api/v1/74391150.jsonp.js | JavaScript | cc0-1.0 | 179 |
jsonp({"cep":"12214425","logradouro":"Rua Quatro","bairro":"Condom\u00ednio Villagio Fazend\u00e3o","cidade":"S\u00e3o Jos\u00e9 dos Campos","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/12214425.jsonp.js | JavaScript | cc0-1.0 | 180 |
jsonp({"cep":"02721200","logradouro":"Avenida Deputado Em\u00edlio Carlos","bairro":"Lim\u00e3o","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/02721200.jsonp.js | JavaScript | cc0-1.0 | 162 |
jsonp({"cep":"08140438","logradouro":"Travessa Jonatas Batista","bairro":"Jardim Benfica","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/08140438.jsonp.js | JavaScript | cc0-1.0 | 155 |
jsonp({"cep":"25250439","logradouro":"Travessa Jos\u00e9 Zito Santana","bairro":"Mantiquira","cidade":"Duque de Caxias","uf":"RJ","estado":"Rio de Janeiro"});
| lfreneda/cepdb | api/v1/25250439.jsonp.js | JavaScript | cc0-1.0 | 159 |
// Global Vars to set
var musicas = new Array(11);
musicas[0] = 0; // Wheel A
musicas[1] = 0; // Whell B
musicas[2] = "0;"; // A1
musicas[3] = "0;"; // A2
musicas[4] = "0;"; // A3
musicas[5] = "0;"; // A4
musicas[6] = "0;"; // B1
musicas[7] = "0;"; // B2
musicas[8] = "0;"; // B3
musicas[9] = "0;"; // B4
musicas[10] = 0; // Sings
function ativa_facebook(){
alert('Aguarde...');
FB.api('/me', function(response) {
// console.log(response);
// NORMAL ACTION
$.post('getUser.php', { facebookId: response.id}, function(data){
if(data.success){
//INSERE APENAS BATIDA
$.post('salva_som.php?opc=1', {
m1: musicas[0],
m2: musicas[1],
m3: musicas[2]+musicas[3]+musicas[4]+musicas[5]+musicas[6]+musicas[7]+musicas[8]+musicas[9],
m4: musicas[10],
usuario: data.usuario
}, function(data){
if(data.success){
var image = Math.floor((Math.random()*3)+1);
FB.api('/me/feed', 'post', { message: 'Sinta o sabor da minha batida no FLAVOR DJ: o gerador de som exclusivo do BH DANCE FESTIVAL. BH Dance Festival. A CIDADE NA PISTA.', link: 'https://apps.facebook.com/flavordj/?minhaBatida='+data.batida, picture: 'https://lit-castle-9930.herokuapp.com/img/share/flavor'+image+'.jpg' }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Sua batida foi compartilhada com sucesso!');
}
});
}
}, 'json');
}else{
//INSERE BATIDA E USUARIO
$.post('salva_som.php?opc=2', {
m1: musicas[0],
m2: musicas[1],
m3: musicas[2]+musicas[3]+musicas[4]+musicas[5]+musicas[6]+musicas[7]+musicas[8]+musicas[9],
m4: musicas[10],
facebookId: response.id,
nome: response.name,
email: response.email,
sexo: response.gender,
cidade: ''
}, function(data){
if(data.success){
var image = Math.floor((Math.random()*3)+1);
FB.api('/me/feed', 'post', { message: 'Sinta o sabor da minha batida no FLAVOR DJ: o gerador de som exclusivo do BH DANCE FESTIVAL. BH Dance Festival. A CIDADE NA PISTA.', link: 'https://apps.facebook.com/flavordj/?minhaBatida='+data.batida, picture: 'https://lit-castle-9930.herokuapp.com/img/share/flavor'+image+'.jpg' }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Sua batida foi compartilhada com sucesso!');
}
});
}
}, 'json');
}
}, 'json');
});
}
function computa_voto(batida){
FB.api('/me', function(response) {
//console.log(response);
// NORMAL ACTION
$.post('getVoto.php', { facebookId: response.id}, function(data){
if(data.success){
alert('Você já votou em uma batida, obrigado por participar!');
}else{
//INSERE NO BD
$.post('computa_voto.php', {
facebookId: response.id,
batida: batida
}, function(data){
if(data.success){
}
}, 'json');
}
}, 'json');
});
}
function login() {
alert('Você ainda não tem o aplicativo do Flavor DJ. Instale-o primeiro para compartilhar sua batida.');
FB.login(function(response) {
if (response.authResponse) {
ativa_facebook();
} else {
}
}, {scope: 'email, publish_stream'});
}
function desativaetp1(){
$('.audio1').jPlayer("stop");
$('.audio2').jPlayer("stop");
$('.audio3').jPlayer("stop");
$('.audio4').jPlayer("stop");
musicas[0] = "0;";
$('.etapa1, .guide .etapa1 div, .etapa1 li').removeClass('ativo');
$('.etapa1').css('z-index', 2);
}
function desativaetp2(){
$('.audio5').jPlayer("stop");
$('.audio6').jPlayer("stop");
$('.audio7').jPlayer("stop");
$('.audio8').jPlayer("stop");
musicas[1] = "0;";
$('.etapa2, .guide .etapa2 div, .etapa2 li').removeClass('ativo');
$('.etapa2').css('z-index', 2);
}
function desativaetpr(idPlayer, cod){
musicas[cod] = "0;";
$('.audio'+idPlayer).jPlayer("stop");
$('.etapa3').css('z-index', 2);
}
function desativaetp5(){
$('.audio17').jPlayer("stop");
$('.audio18').jPlayer("stop");
$('.audio19').jPlayer("stop");
$('.audio20').jPlayer("stop");
musicas[10] = "0;";
$('.etapa5, .guide .etapa5 div, .etapa5 li').removeClass('ativo');
$('.etapa5').css('z-index', 2);
}
function ativa_anima(){
$('.whel1 div.a').delay(300).animate({ height: '0px' }, 1000);
$('.whel1 div.b').delay(300).animate({ height: '0px' }, 1000, function(){
$('.whel2 div.a').delay(300).animate({ width: '0px' }, 1000);
$('.whel2 div.b').delay(300).animate({ width: '0px' }, 1000);
});
}
$(document).ready(function(){
//login_start();
$('.etapa1').click(function(){
if($(this).hasClass('ativo')){
desativaetp1();
}else{
desativaetp1();
$(this).addClass('ativo');
$(this).css('z-index', 1);
var audioPlayer = $(this).attr('href');
musicas[0] = audioPlayer;
$('.guide .etapa1 div.p'+audioPlayer).addClass('ativo');
$('.visor .etapa1 li.p'+audioPlayer).addClass('ativo');
$(".audio"+audioPlayer).jPlayer("play", 0);
}
return false;
})
$('.etapa2').click(function(){
if($(this).hasClass('ativo')){
desativaetp2();
}else{
desativaetp2();
$(this).addClass('ativo');
$(this).css('z-index', 1);
var audioPlayer = $(this).attr('href');
musicas[1] = audioPlayer;
$('.guide .etapa2 div.p'+audioPlayer).addClass('ativo');
$('.visor .etapa2 li.p'+audioPlayer).addClass('ativo');
$(".audio"+audioPlayer).jPlayer("play", 0);
}
return false;
})
$('.etapa3').click(function(){
var audioPlayer = $(this).attr('href');
var codigo = $(this).data('codigo');
if($(this).hasClass('ativo')){
desativaetpr(audioPlayer,codigo);
$('.guide .etapa3 div.p'+audioPlayer).removeClass('ativo');
$('.visor .etapa3 li.p'+audioPlayer).removeClass('ativo');
$(this).removeClass('ativo');
}else{
$(this).addClass('ativo');
$('.guide .etapa3 div.p'+audioPlayer).addClass('ativo');
$('.visor .etapa3 li.p'+audioPlayer).addClass('ativo');
$(this).css('z-index', 1);
musicas[codigo] = audioPlayer+";";
$(".audio"+audioPlayer).jPlayer("play", 0);
}
return false;
})
$('.etapa4').click(function(){
var audioPlayer = $(this).attr('href');
var cod = $(this).data('codigo');
if($(this).hasClass('ativo')){
desativaetpr(audioPlayer, cod);
$('.guide .etapa4 div.p'+audioPlayer).removeClass('ativo');
$('.visor .etapa4 li.p'+audioPlayer).removeClass('ativo');
$(this).removeClass('ativo');
}else{
$(this).addClass('ativo');
$('.guide .etapa4 div.p'+audioPlayer).addClass('ativo');
$('.visor .etapa4 li.p'+audioPlayer).addClass('ativo');
musicas[cod] = audioPlayer+";";
$(".audio"+audioPlayer).jPlayer("play", 0);
}
return false;
})
$('.etapa5').click(function(){
if($(this).hasClass('ativo')){
desativaetp5();
}else{
desativaetp5();
$(this).addClass('ativo');
var audioPlayer = $(this).attr('href');
musicas[10] = audioPlayer;
$('.guide .etapa5 div.p'+audioPlayer).addClass('ativo');
$('.visor .etapa5 li.p'+audioPlayer).addClass('ativo');
$(".audio"+audioPlayer).jPlayer("play", 0);
}
return false;
})
$(".audio1").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct1/1.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct1/1.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio2").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct1/2.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct1/2.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio3").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct1/3.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct1/3.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio4").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct1/4.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct1/4.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio5").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct2/1.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct2/1.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio6").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct2/2.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct2/2.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio7").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct2/3.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct2/3.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio8").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct2/4.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct2/4.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio9").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct3/1.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct3/1.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio10").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct3/2.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct3/2.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio11").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct3/3.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct3/3.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio12").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct3/4.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct3/4.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio13").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct4/1.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct4/1.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio14").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct4/2.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct4/2.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio15").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct4/3.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct4/3.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio16").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct4/4.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct4/4.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio17").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct5/1.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct5/1.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio18").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct5/2.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct5/2.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio19").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct5/3.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct5/3.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$(".audio20").jPlayer({
ready: function (event) {
$(this).jPlayer("setMedia", { oga: "https://lit-castle-9930.herokuapp.com/sounds/pct5/4.ogg", mp3: "https://lit-castle-9930.herokuapp.com/sounds/pct5/4.mp3" }
)}, swfPath: "js", supplied: "oga, mp3", wmode: "window", loop: true, preload: 'auto'
});
$('body').queryLoader2( { onLoadComplete: ativa_anima() } );
function login_start() {
//alert('Você ainda não tem o aplicativo do Flavor DJ. Instale-o primeiro para compartilhar sua batida.');
FB.login(function(response) {
if (response.authResponse) {
// ativa_facebook();
} else {
}
}, {scope: 'email, publish_stream'});
}
// Share
var cont = 0
var i = 0;
$('a.share').click(function(){
cont = 0;
for(i = 0; i<11; i++){
if((musicas[i] == "0;") || (musicas[i] == 0)){
cont++;
}
}
if(cont == 11){
alert('Você precisa selecionar pelo menos um ingrediente para sua batida.');
}else{
FB.getLoginStatus(function(response) {
// console.log(response);
if (response.status === 'connected') {
// NORMAL ACTION
ativa_facebook();
} else if (response.status === 'not_authorized') {
login();
window.location.reload();
} else {
login();
window.location.reload();
}
});
}
return false;
});
$('.votarBatida').click(function(){
var batida = $(this).attr('href');
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// NORMAL ACTION
computa_voto(batida);
} else if (response.status === 'not_authorized') {
FB.login(function(response) {
if (response.authResponse) {
// NORMAL ACTION
computa_voto(batida);
} else {
// console.log('Sua batida não foi compartilhada.');
}
}, {scope: 'email, publish_stream'});
} else {
FB.login(function(response) {
if (response.authResponse) {
// NORMAL ACTION
computa_voto(batida);
} else {
//console.log('Sua batida não foi compartilhada.');
}
}, {scope: 'email, publish_stream'});
}
});
});
});
| mateuslopesbh/flavordj | js/funcoes.js | JavaScript | cc0-1.0 | 16,201 |
jsonp({"cep":"61610135","logradouro":"Rua Santo Ant\u00f4nio","bairro":"Padre Julio Maria","cidade":"Caucaia","uf":"CE","estado":"Cear\u00e1"});
| lfreneda/cepdb | api/v1/61610135.jsonp.js | JavaScript | cc0-1.0 | 145 |
jsonp({"cep":"24745360","logradouro":"Rua Expedicion\u00e1rio Aprigio Jos\u00e9 Vieira","bairro":"Coelho","cidade":"S\u00e3o Gon\u00e7alo","uf":"RJ","estado":"Rio de Janeiro"});
| lfreneda/cepdb | api/v1/24745360.jsonp.js | JavaScript | cc0-1.0 | 178 |
jsonp({"cep":"87114166","logradouro":"Rua 11","bairro":"Jardim Ouro Verde II","cidade":"Sarandi","uf":"PR","estado":"Paran\u00e1"});
| lfreneda/cepdb | api/v1/87114166.jsonp.js | JavaScript | cc0-1.0 | 133 |
jsonp({"cep":"02846010","logradouro":"Estrada L\u00e1zaro Am\u00e2ncio de Barros","bairro":"Vila Itaberaba","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/02846010.jsonp.js | JavaScript | cc0-1.0 | 173 |
jsonp({"cep":"96506661","logradouro":"Rua Batista Carlos","bairro":"Barcelos","cidade":"Cachoeira do Sul","uf":"RS","estado":"Rio Grande do Sul"});
| lfreneda/cepdb | api/v1/96506661.jsonp.js | JavaScript | cc0-1.0 | 148 |
jsonp({"cep":"35171331","logradouro":"Rua Rio Branco","bairro":"Amaro Lanari","cidade":"Coronel Fabriciano","uf":"MG","estado":"Minas Gerais"});
| lfreneda/cepdb | api/v1/35171331.jsonp.js | JavaScript | cc0-1.0 | 145 |
jsonp({"cep":"25730410","logradouro":"Avenida Country Club","bairro":"Nogueira","cidade":"Petr\u00f3polis","uf":"RJ","estado":"Rio de Janeiro"});
| lfreneda/cepdb | api/v1/25730410.jsonp.js | JavaScript | cc0-1.0 | 146 |
jsonp({"cep":"70377070","logradouro":"Quadra SQS 114 Bloco G","bairro":"Asa Sul","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
| lfreneda/cepdb | api/v1/70377070.jsonp.js | JavaScript | cc0-1.0 | 147 |
jsonp({"cep":"36070570","logradouro":"Rua Jo\u00e3o Surerus J\u00fanior","bairro":"Lourdes","cidade":"Juiz de Fora","uf":"MG","estado":"Minas Gerais"});
| lfreneda/cepdb | api/v1/36070570.jsonp.js | JavaScript | cc0-1.0 | 153 |
$(document).ready( function () {
// Add return on top button
$('body').append('<div id="returnOnTop" title="Retour en haut"> </div>');
// On button click, let's scroll up to top
$('#returnOnTop').click( function() {
$('html,body').animate({scrollTop: 0}, 'slow');
});
});
$(window).scroll(function() {
// If on top fade the bouton out, else fade it in
if ( $(window).scrollTop() == 0 )
$('#returnOnTop').fadeOut();
else
$('#returnOnTop').fadeIn();
}); | samszo/THYP-1516 | FatihiZakaria/trombino/returnOnTop.js | JavaScript | cc0-1.0 | 497 |
jsonp({"cep":"40060240","logradouro":"Rua do Sodr\u00e9","bairro":"Dois de Julho","cidade":"Salvador","uf":"BA","estado":"Bahia"});
| lfreneda/cepdb | api/v1/40060240.jsonp.js | JavaScript | cc0-1.0 | 132 |
jsonp({"cep":"08671155","logradouro":"Rua Luciano de Godoi","bairro":"Jardim M\u00e1rcia","cidade":"Suzano","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/08671155.jsonp.js | JavaScript | cc0-1.0 | 147 |
jsonp({"cep":"80820132","logradouro":"Jardinete Aline de Souza Thomaszeck","bairro":"Vista Alegre","cidade":"Curitiba","uf":"PR","estado":"Paran\u00e1"});
| lfreneda/cepdb | api/v1/80820132.jsonp.js | JavaScript | cc0-1.0 | 155 |
jsonp({"cep":"07176635","logradouro":"Rua Jo\u00e3o Garcia e Garcia","bairro":"Jardim \u00c1lamo","cidade":"Guarulhos","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/07176635.jsonp.js | JavaScript | cc0-1.0 | 158 |
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const {ipcMain} = require('electron')
const {dialog} = require('electron')
const {Menu} = require('electron')
import {enableLiveReload} from 'electron-compile'
const path = require('path')
const url = require('url')
const fs = require('fs')
enableLiveReload()
//Window Creation
var windowArray = []
exports.windowCount = 0
function createWindow () {
// Create the new browser window.
windowArray.push( new BrowserWindow({width: 800, height: 600}) )
exports.windowCount = windowArray.length
var newWindow = windowArray[exports.windowCount-1]
// windowArray[windowCount-1].maximize()
// and load the index.html of the app.
newWindow.loadURL(url.format({
pathname: path.join(__dirname, 'html/index.html'),
protocol: 'file:',
slashes: true
}))
// Emitted when the window is closed.
newWindow.on('closed', function () {
newWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
// app.on('activate', function () {
// // On OS X it's common to re-create a window in the app when the
// // dock icon is clicked and there are no other windows open.
// if (mainWindow === null) {
// createWindow()
// }
// })
//Menus
var template = [
{
label: 'File',
submenu: [
{label: 'New Project'},
{label: 'Open Project'},
{label: 'Import File'},
{type: 'separator'},
{label: 'Save'},
{label: 'Save As'},
{label: 'Settings'}
]
},
{
label: 'Edit',
submenu: [
{role: 'undo'},
{role: 'redo'},
{type: 'separator'},
{role: 'cut'},
{role: 'copy'},
{role: 'paste'},
{role: 'delete'},
{role: 'selectall'}
]
},
{
label: 'Window',
submenu: [
{label: 'New Window', click: createWindow},
{role: 'minimize'},
{type: 'separator'},
{role: 'toggledevtools'},
{role: 'close'}
]
},
]
var mainMenu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(mainMenu)
//File Functions
function importFile (event) {
dialog.showOpenDialog({properties: ['openFile', 'multiSelections']}, (filePaths) => {
console.log(filePaths)
event.sender.send('importer', filePaths)
})
}
//IPC Functions
ipcMain.on('window-manager', (event, arg) => {
console.log(arg)
if (arg == "New Window") { //Create new window
createWindow()
}
})
ipcMain.on('file-manager', (event, arg) => {
console.log(arg)
if (arg == "Import Files") {
importFile(event)
}
})
| samfromcadott/kettle | main.js | JavaScript | cc0-1.0 | 2,539 |
// npm
var chalk = require('chalk')
// local
var Copper = require('../copper')
var copper = new Copper
var util = require('../util')
module.exports = function (config, wallet, keys, args) {
var abort = false
var name
if (args._.length > 0) {
name = args._.join(' ')
}
var key = copper.newKey()
console.log(' pub:', chalk.green(key.pub))
console.log('priv:', chalk.blue(key.priv))
var wkey = {pub: key.pub, priv: key.priv, date: new Date()}
if (name) {
var keynames = wallet.keys.map(function (k) {return k.name})
if (keynames.indexOf(name) > -1) {
console.log('abort!', chalk.red('key named', name, 'already exists'))
abort = true
} else {
wkey.name = name
console.log('name:', JSON.stringify(wkey.name))
}
}
if (!abort) {
wallet.keys.push(wkey)
util.saveJSON(config.wallet.file, wallet)
}
}
| donpdonp/coindust | lib/commands/new.js | JavaScript | cc0-1.0 | 874 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _lib = require('../../lib');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A title sub-component for Accordion component
*/
var AccordionTitle = function (_Component) {
(0, _inherits3.default)(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this, _ret;
(0, _classCallCheck3.default)(this, AccordionTitle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = AccordionTitle.__proto__ || Object.getPrototypeOf(AccordionTitle)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e, _this.props);
}, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
}
(0, _createClass3.default)(AccordionTitle, [{
key: 'render',
value: function render() {
var _props = this.props,
active = _props.active,
children = _props.children,
className = _props.className;
var classes = (0, _classnames2.default)((0, _lib.useKeyOnly)(active, 'active'), 'title', className);
var rest = (0, _lib.getUnhandledProps)(AccordionTitle, this.props);
var ElementType = (0, _lib.getElementType)(AccordionTitle, this.props);
return _react2.default.createElement(
ElementType,
(0, _extends3.default)({}, rest, { className: classes, onClick: this.handleClick }),
children
);
}
}]);
return AccordionTitle;
}(_react.Component);
AccordionTitle.displayName = 'AccordionTitle';
AccordionTitle._meta = {
name: 'AccordionTitle',
type: _lib.META.TYPES.MODULE,
parent: 'Accordion'
};
exports.default = AccordionTitle;
process.env.NODE_ENV !== "production" ? AccordionTitle.propTypes = {
/** An element type to render as (string or function). */
as: _lib.customPropTypes.as,
/** Whether or not the title is in the open state. */
active: _react.PropTypes.bool,
/** Primary content. */
children: _react.PropTypes.node,
/** Additional classes. */
className: _react.PropTypes.string,
/**
* Called on blur.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick: _react.PropTypes.func
} : void 0;
AccordionTitle.handledProps = ['active', 'as', 'children', 'className', 'onClick']; | jessicaappelbaum/cljs-update | node_modules/semantic-ui-react/dist/commonjs/modules/Accordion/AccordionTitle.js | JavaScript | epl-1.0 | 3,484 |
var config = {
width: 800,
height: 600,
type: Phaser.AUTO,
parent: 'phaser-example',
scene: {
create: create,
update: update
}
};
var game = new Phaser.Game(config);
var graphics;
var pointerRect;
var rectangles;
function create ()
{
graphics = this.add.graphics({ lineStyle: { color: 0x0000aa }, fillStyle: { color: 0x0000aa, alpha: 0.5 } });
pointerRect = new Phaser.Geom.Rectangle(0, 0, 80, 60);
rectangles = [];
for(var x = 0; x < 10; x++)
{
rectangles[x] = [];
for(var y = 0; y < 10; y++)
{
rectangles[x][y] = new Phaser.Geom.Rectangle(x * 80, y * 60, 80, 60);
}
}
this.input.on('pointermove', function (pointer) {
var x = Math.floor(pointer.x / 80);
var y = Math.floor(pointer.y / 60);
pointerRect.setPosition(x * 80, y * 60);
Phaser.Geom.Rectangle.CopyFrom(pointerRect, rectangles[x][y]);
});
}
function update ()
{
graphics.clear();
graphics.fillRectShape(pointerRect);
for(var x = 0; x < 10; x++)
{
for(var y = 0; y < 10; y++)
{
var rect = rectangles[x][y];
if(rect.width > 10)
{
rect.width *= 0.95;
rect.height *= 0.95;
}
graphics.strokeRectShape(rect);
}
}
} | boniatillo-com/PhaserEditor | source/v2/phasereditor/phasereditor.resources.phaser.examples/phaser3-examples/public/src/geom/rectangle/copy from.js | JavaScript | epl-1.0 | 1,367 |
var config = {
type: Phaser.WEBGL,
parent: 'phaser-example',
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload() {
this.load.image('bunny', 'assets/sprites/bunny.png');
}
function create() {
var parent = this.add.image(0, 0, 'bunny');
var child = this.add.image(100, 100, 'bunny');
parent.alpha = 0.5;
}
| boniatillo-com/PhaserEditor | source/v2/phasereditor/phasereditor.resources.phaser.examples/phaser3-examples/public/src/archived/091 image parent alpha.js | JavaScript | epl-1.0 | 411 |
if (NABUCCO === undefined || !NABUCCO)
{
var NABUCCO = {};
}
(function()
{
NABUCCO.component = NABUCCO.component || {};
NABUCCO.component.CMISDocumentList = function(htmlId)
{
// replace Bubbling.on with NO-OP, so the superclass can't register its event listeners (never-ever)
var on = YAHOO.Bubbling.on;
YAHOO.Bubbling.on = function()
{
// NO-OP
return;
};
try
{
NABUCCO.component.CMISDocumentList.superclass.constructor.call(this, htmlId);
// restore
YAHOO.Bubbling.on = on;
}
catch (e)
{
// restore
YAHOO.Bubbling.on = on;
throw e;
}
this.name = "NABUCCO.component.CMISDocumentList";
Alfresco.util.ComponentManager.reregister(this);
this.dataSourceUrl = Alfresco.constants.URL_SERVICECONTEXT + 'nabucco/components/cmis-documentlist/data?';
if (htmlId !== "null")
{
// we actually want to react to metadataRefresh
YAHOO.Bubbling.on("metadataRefresh", this.onDocListRefresh, this);
YAHOO.Bubbling.on("filterChanged", this.onFilterChanged, this);
YAHOO.Bubbling.on("changeFilter", this.onChangeFilter, this);
}
this.dragAndDropAllowed = false;
this.setOptions(
{
preferencePrefix : "org.nabucco.cmis-documentlibrary"
});
};
YAHOO.extend(NABUCCO.component.CMISDocumentList, Alfresco.DocumentList,
{
onSortAscending : function()
{
NABUCCO.component.CMISDocumentList.withPreferencePrefixOverride.call(this,
NABUCCO.component.CMISDocumentList.superclass.onSortAscending, arguments);
},
onSortField : function()
{
NABUCCO.component.CMISDocumentList.withPreferencePrefixOverride.call(this,
NABUCCO.component.CMISDocumentList.superclass.onSortField, arguments);
},
onShowFolders : function()
{
NABUCCO.component.CMISDocumentList.withPreferencePrefixOverride.call(this,
NABUCCO.component.CMISDocumentList.superclass.onShowFolders, arguments);
},
onViewRendererSelect : function()
{
NABUCCO.component.CMISDocumentList.withPreferencePrefixOverride.call(this,
NABUCCO.component.CMISDocumentList.superclass.onViewRendererSelect, arguments);
},
onSimpleDetailed : function()
{
NABUCCO.component.CMISDocumentList.withPreferencePrefixOverride.call(this,
NABUCCO.component.CMISDocumentList.superclass.onSimpleDetailed, arguments);
},
_buildDocListParams : function(p_obj)
{
var params = "", obj =
{
path : this.currentPath
};
// Pagination in use?
if (this.options.usePagination)
{
obj.page = this.widgets.paginator.getCurrentPage() || this.currentPage;
obj.pageSize = this.widgets.paginator.getRowsPerPage();
}
// Passed-in overrides
if (typeof p_obj === "object")
{
obj = YAHOO.lang.merge(obj, p_obj);
}
params = "path=" + obj.path;
// Paging parameters
if (this.options.usePagination)
{
params += "&pageSize=" + obj.pageSize + "&pos=" + obj.page;
}
// Sort parameters
params += "&sortAsc=" + this.options.sortAscending + "&sortField=" + encodeURIComponent(this.options.sortField);
// View mode and No-cache
params += "&view=" + this.actionsView + "&noCache=" + new Date().getTime();
return params;
}
});
NABUCCO.component.CMISDocumentList.withPreferencePrefixOverride = function(callback, args)
{
var prefSet, result, scope = this;
if (YAHOO.lang.isString(this.options.preferencePrefix) && this.options.preferencePrefix !== "org.alfresco.share.documentList")
{
prefSet = this.services.preferences.set;
this.services.preferences.set = function(prefKey, value, responseConfig)
{
prefKey = prefKey.replace("org.alfresco.share.documentList.", scope.options.preferencePrefix + '.');
return prefSet.call(this, prefKey, value, responseConfig);
};
try
{
result = callback.apply(this, args);
this.services.preferences.set = prefSet;
}
catch (e)
{
this.services.preferences.set = prefSet;
throw e;
}
return result;
}
return callback.apply(this, args);
};
// necessary to fix default thumbnail icons for non-standard node types, especially non-file-folder types
NABUCCO.component.CMISDocumentList.withFileIconOverride = function(callback, args)
{
var getFileIcon = Alfresco.util.getFileIcon, node = args[1].getData().jsNode, result;
Alfresco.util.getFileIcon = function(p_fileName, p_fileType, p_iconSize, p_fileParentType)
{
if (p_fileType === undefined)
{
if (node.isLink && YAHOO.lang.isObject(node.linkedNode) && YAHOO.lang.isString(node.linkedNode.type))
{
p_fileType = node.linkedNode.type;
}
else
{
p_fileType = node.type;
}
}
return getFileIcon.call(Alfresco.util, p_fileName, p_fileType, p_iconSize, p_fileParentType);
};
Alfresco.util.getFileIcon.types = getFileIcon.types;
try
{
result = callback.apply(this, args);
Alfresco.util.getFileIcon = getFileIcon;
}
catch (e)
{
Alfresco.util.getFileIcon = getFileIcon;
throw e;
}
return result;
};
// necessary to fix thumbnail URL generation to avoid HTTP 400 responses for attempts on items without content
NABUCCO.component.CMISDocumentList.withThumbnailOverride = function(callback, args)
{
var generateThumbnailUrl = Alfresco.DocumentList.generateThumbnailUrl, result;
Alfresco.DocumentList.generateThumbnailUrl = function(record)
{
var node = record.jsNode;
if ((node.isContent || (node.isLink && node.linkedNode.isContent))
&& (YAHOO.lang.isString(node.contentURL) || (node.isLink && YAHOO.lang.isString(node.linkedNode.contentURL))))
{
return generateThumbnailUrl(record);
}
return Alfresco.constants.URL_RESCONTEXT + 'components/images/filetypes/' + Alfresco.util.getFileIcon(record.displayName);
};
try
{
result = callback.apply(this, args);
Alfresco.DocumentList.generateThumbnailUrl = generateThumbnailUrl;
}
catch (e)
{
Alfresco.DocumentList.generateThumbnailUrl = generateThumbnailUrl;
throw e;
}
return result;
};
// adapt the document list fnRenderCellThumbnail to remove preview when no preview can be generated (node without content) and use
// information available for file icon determination
Alfresco.DocumentList.prototype._nbc_fnRenderCellThumbnail = Alfresco.DocumentList.prototype.fnRenderCellThumbnail;
Alfresco.DocumentList.prototype.fnRenderCellThumbnail = function(renderChain)
{
var scope = this, realRenderer = this._nbc_fnRenderCellThumbnail(), renderCallback = renderChain;
return function(elCell, oRecord, oColumn, oData)
{
var id, node = oRecord.getData().jsNode;
NABUCCO.component.CMISDocumentList.withFileIconOverride.call(this, function()
{
NABUCCO.component.CMISDocumentList.withThumbnailOverride.call(this, function()
{
if (YAHOO.lang.isFunction(renderCallback))
{
renderCallback.call(this, realRenderer, arguments);
}
else
{
realRenderer.apply(this, arguments);
}
}, arguments);
}, [ elCell, oRecord, oColumn, oData ]);
// OOTB view renderer always prepare preview even if node has no content
if (!(node.isContainer || (node.isLink && node.linkedNode.isContainer))
&& !(YAHOO.lang.isString(node.contentURL) || (node.isLink && YAHOO.lang.isString(node.linkedNode.contentURL))))
{
// check for any thumbnails that are not supported due to node without content
id = scope.id + '-preview-' + oRecord.getId();
if (Alfresco.util.arrayContains(scope.previewTooltips, id))
{
scope.previewTooltips = Alfresco.util.arrayRemove(scope.previewTooltips, id);
}
}
};
};
// adapt size renderer for items without content as well as links
Alfresco.DocumentList.prototype._nbc_setupMetadataRenderers = Alfresco.DocumentList.prototype._setupMetadataRenderers;
Alfresco.DocumentList.prototype._setupMetadataRenderers = function()
{
this._nbc_setupMetadataRenderers();
/**
* File size
*/
this.registerRenderer("size", function(record, label)
{
var jsNode = record.jsNode, html = "";
if ((YAHOO.lang.isString(jsNode.contentURL) || YAHOO.lang.isNumber(jsNode.size)) || (jsNode.isLink && (YAHOO.lang.isString(jsNode.linkedNode.contentURL) || YAHOO.lang.isNumber(jsNode.linkedNode.size))))
{
html += '<span class="item">' + label
+ Alfresco.util.formatFileSize(YAHOO.lang.isString(jsNode.contentURL) || YAHOO.lang.isNumber(jsNode.size) ? jsNode.size : jsNode.linkedNode.size)
+ '</span>';
}
return html;
});
};
(function()
{
// additional properties for jsNode
var additionalJsNodeProps = [ "isContent" ];
// adapt Node to support our additional properties
Alfresco.util._nbc_Node = Alfresco.util.Node;
Alfresco.util.Node = function(p_node)
{
var jsNode = Alfresco.util._nbc_Node(p_node), idx, propName;
if (YAHOO.lang.isObject(jsNode))
{
for (idx = 0; idx < additionalJsNodeProps.length; idx++)
{
propName = additionalJsNodeProps[idx];
// override only if no such property has been defined yet
if (p_node.hasOwnProperty(propName) && !jsNode.hasOwnProperty(propName))
{
if (propName.indexOf("Node") !== -1 && propName.substr(propName.indexOf("Node")) === "Node"
&& YAHOO.lang.isString(p_node[propName]))
{
jsNode[propName] = new Alfresco.util.NodeRef(p_node[propName]);
}
else
{
jsNode[propName] = p_node[propName];
}
}
}
}
return jsNode;
};
}());
Alfresco.util.getFileIcon.types["D:cmiscustom:document"] = "file";
Alfresco.util.getFileIcon.types["cmis:document"] = "file";
Alfresco.util.getFileIcon.types["cmis:folder"] = "folder";
}()); | AFaust/alfresco-cmis-documentlist | share/src/main/webapp/nabucco/components/cmis-documentlibrary/documentlist.js | JavaScript | epl-1.0 | 11,911 |
requirejs(['bmotion.config'], function() {
requirejs(['bms.integrated.root'], function() {});
});
| ladenberger/bmotion-frontend | app/js/bmotion.integrated.js | JavaScript | epl-1.0 | 100 |
var page = require('webpage').create();
var url;
if (phantom.args) {
url = phantom.args[0];
} else {
url = require('system').args[1];
}
page.onConsoleMessage = function (message) {
console.log(message);
};
function exit(code) {
setTimeout(function(){ phantom.exit(code); }, 0);
phantom.onError = function(){};
}
console.log("Loading URL: " + url);
page.open(url, function (status) {
if (status != "success") {
console.log('Failed to open ' + url);
phantom.exit(1);
}
console.log("Running test.");
var result = page.evaluate(function() {
return chess_game.test_runner.runner();
});
if (result != 0) {
console.log("*** Test failed! ***");
exit(1);
}
else {
console.log("Test succeeded.");
exit(0);
}
});
| tmtwd/chess-om | env/test/js/unit-test.js | JavaScript | epl-1.0 | 765 |
// Compiled by ClojureScript 1.9.946 {}
goog.provide('eckersdorf.window.db');
goog.require('cljs.core');
goog.require('re_frame.core');
eckersdorf.window.db.window_state = new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword("window","height","window/height",1310154766),(0),new cljs.core.Keyword("window","width","window/width",-1138776901),(0)], null);
//# sourceMappingURL=db.js.map?rel=1510703504091
| ribelo/eckersdorf | resources/public/js/out/eckersdorf/window/db.js | JavaScript | epl-1.0 | 417 |
/**
* Created by Paul on 24/01/2015.
*/
var install_url = $("#install_url").val();
$("#updateCase").click(function () {
var case_id = $('#case_id').val();
var case_priority = $('#case_priority').val();
var case_status = $('#case_status').val();
var case_type = $('#case_type').val();
var assignedTo = $('#assignedTo').val();
var case_subject = $('#case_subject').val();
var case_description = $('#case_description').val();
var case_resolution = $('#case_resolution').val();
$.ajax({
url: install_url + '/web/front.php/tickets/update_case_ajax',
type: 'POST',
data: "id=" + case_id + "&case_priority=" + case_priority +
"&case_status=" + case_status + "&case_type=" + case_type + "&assignedTo=" + assignedTo + "&case_subject=" + case_subject
+ "&case_description=" + case_description + "&case_resolution=" + case_resolution,
dataType: 'json',
success: function (data) {
if (data.error == "no") {
toastr.options = {
"closeButton": true,
"showDuration": 3
};
toastr['success']('MyCRM', "Case updated");
} else {
toastr.options = {
"closeButton": true,
"showDuration": 3
};
toastr['error']('MyCRM', "Error while updating case");
}
},
error: function (data) {
toastr.options = {
"closeButton": true,
"showDuration": 3
};
toastr['error']('MyCRM', "Error while updating case : " + data);
}
});
}); | paulcoiffier/Mobissime-Liberta | src/MyCrm/Modules/LibertaTickets/Js/edit_case.js | JavaScript | gpl-2.0 | 1,698 |
/**
Copyright 2011 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.
*/
KT.panel.list.registerPage('gpg_keys', {
create : 'new_gpg_key',
extra_create_data : function(){
return { 'gpg_key[name]' : $('#gpg_key_name').val() };
}
});
$(document).ready(function(){
$('#upload_gpg_key').live('click', function(event){
KT.gpg_key.upload();
});
$('#upload_new_gpg_key').live('submit', function(e){
e.preventDefault();
KT.gpg_key.upload();
});
$('#update_upload_gpg_key').live('click', function(event){
KT.gpg_key.upload_update();
});
$('#gpg_key_content').live('input keyup paste', function(){
if( $(this).val() !== '' ){
$('#gpg_key_content_upload').attr('disabled', 'disabled');
$('#upload_gpg_key').attr('disabled', 'disabled');
$('#clear_gpg_key').removeAttr('disabled');
} else {
$('#gpg_key_content_upload').removeAttr('disabled');
$('#upload_gpg_key').removeAttr('disabled');
$('#clear_gpg_key').attr('disabled', 'disabled');
}
});
$('#gpg_key_content_upload').live('change', function(){
if( $(this).val() !== '' ){
$('#gpg_key_content').attr('disabled', 'disabled');
$('#save_gpg_key').attr('disabled', 'disabled');
$('#clear_upload_gpg_key').removeAttr('disabled');
} else {
$('#gpg_key_content').removeAttr('disabled');
$('#save_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
}
});
$('#clear_upload_gpg_key').live('click', function(){
$('#gpg_key_content_upload').val('');
$('#gpg_key_content').removeAttr('disabled');
$('#save_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
$('#clear_gpg_key').attr('disabled', 'disabled');
});
$('#clear_gpg_key').live('click', function(){
$('#gpg_key_content').val('');
$('#gpg_key_content_upload').removeAttr('disabled');
$('#upload_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
$('#clear_gpg_key').attr('disabled', 'disabled');
});
$('#gpg_key_content_upload_update').live('change', function(){
if( $(this).val() !== '' ){
$('#update_upload_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').removeAttr('disabled');
} else {
$('#update_upload_gpg_key').attr('disabled', 'disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
}
});
$('#clear_upload_gpg_key').live('click', function(){
$('#update_upload_gpg_key').attr('disabled', 'disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
$('#gpg_key_content_upload_update').val('');
});
});
KT.gpg_key = (function($){
var self = this,
get_buttons = function(){
return {
'gpg_key_save' : $('#save_gpg_key'),
'gpg_key_upload': $('#upload_gpg_key')
}
},
enable_buttons = function(){
var buttons = get_buttons();
buttons.gpg_key_save.removeAttr('disabled');
buttons.gpg_key_upload.removeAttr('disabled');
},
disable_buttons = function(){
var buttons = get_buttons();
buttons.gpg_key_save.attr('disabled', 'disabled');
buttons.gpg_key_upload.attr('disabled', 'disabled');
};
self.upload = function(){
var submit_data = { 'gpg_key[name]' : $('#gpg_key_name').val() };
disable_buttons();
$('#upload_new_gpg_key').ajaxSubmit({
url : KT.routes['gpg_keys_path'](),
type : 'POST',
data : submit_data,
iframe : true,
success : function(data, status, xhr){
var parsed_data = $(data);
if( parsed_data.get(0).tagName === 'PRE' ){
notices.displayNotice('error', parsed_data.html());
} else {
KT.panel.list.createSuccess(data);
}
enable_buttons();
},
error : function(){
enable_buttons();
notices.checkNotices();
}
});
};
self.upload_update = function(){
$('#update_upload_gpg_key').attr('disabled', 'disabled');
$('#clear_upload_gpg_key').attr('disabled', 'disabled');
$('#upload_gpg_key').ajaxSubmit({
url : $(this).data('url'),
type : 'POST',
iframe : true,
success : function(data, status, xhr){
if( !data.match(/notices/) ){
$('#gpg_key_content').html(data);
$('#upload_gpg_key').val('');
}
notices.checkNotices();
$('#update_upload_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').removeAttr('disabled');
},
error : function(){
$('#update_upload_gpg_key').removeAttr('disabled');
$('#clear_upload_gpg_key').removeAttr('disabled');
notices.checkNotices();
}
});
};
return self;
})(jQuery);
| iNecas/katello | src/public/javascripts/gpg_key.js | JavaScript | gpl-2.0 | 5,150 |
function isPrime(n) {
if (n === 2) {
return true;
}
if (n % 2 === 0 || n === 1) {
return false;
}
for (var i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i === 0) {
return false;
}
}
return true;
}
function nthPrimeNumber(n) {
if (n <= 0) {
throw new Error('Must be an integer >= 1');
}
var numPrime = 1;
var i = 1;
if (n === 1) {
return 2;
}
while (numPrime < n) {
i += 2;
if (isPrime(i)) {
numPrime++;
}
}
return i;
}
console.log(nthPrimeNumber(10001));
| pbjr23/project-euler-js | pr7.js | JavaScript | gpl-2.0 | 536 |
/*
* Copyright (C) 2008-2010 Surevine Limited.
*
* Although intended for deployment and use alongside Alfresco this module should
* be considered 'Not a Contribution' as defined in Alfresco'sstandard contribution agreement, see
* http://www.alfresco.org/resource/AlfrescoContributionAgreementv2.pdf
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// Get the change password url
model.changePasswordUrlNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/url_change_password.txt');
//Get the security label header
model.securityLabelHeaderNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/security_label.txt');
//Get the help url
model.helpLinkNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/url_help.txt');
model.launchChatUrlNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Chat Dashlet/url_launch_chat.txt');
//Get the logo node
model.appLogoNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/app_logo');
model.surevineLinkUrlNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Footer/url_surevine_link.txt');
cache.neverCache=false;
cache.isPublic=false;
cache.maxAge=36000; //10 hours
cache.mustRevalidate=false;
cache.ETag = 100;
| surevine/alfresco-repository-client-customisations | config/alfresco/webscripts/com/surevine/svTheme/configuration/configuration.get.js | JavaScript | gpl-2.0 | 2,004 |
/*
YUI 3.7.3 (build 5687)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('dom-class', function(Y) {
var addClass, hasClass, removeClass;
Y.mix(Y.DOM, {
/**
* Determines whether a DOM element has the given className.
* @method hasClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to search for
* @return {Boolean} Whether or not the element has the given class.
*/
hasClass: function(node, className) {
var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
return re.test(node.className);
},
/**
* Adds a class name to a given DOM element.
* @method addClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to add to the class attribute
*/
addClass: function(node, className) {
if (!Y.DOM.hasClass(node, className)) { // skip if already present
node.className = Y.Lang.trim([node.className, className].join(' '));
}
},
/**
* Removes a class name from a given element.
* @method removeClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to remove from the class attribute
*/
removeClass: function(node, className) {
if (className && hasClass(node, className)) {
node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' +
className + '(?:\\s+|$)'), ' '));
if ( hasClass(node, className) ) { // in case of multiple adjacent
removeClass(node, className);
}
}
},
/**
* Replace a class with another class for a given element.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @for DOM
* @param {HTMLElement} element The DOM element
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
*/
replaceClass: function(node, oldC, newC) {
//Y.log('replaceClass replacing ' + oldC + ' with ' + newC, 'info', 'Node');
removeClass(node, oldC); // remove first in case oldC === newC
addClass(node, newC);
},
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @for DOM
* @param {HTMLElement} element The DOM element
* @param {String} className the class name to be toggled
* @param {Boolean} addClass optional boolean to indicate whether class
* should be added or removed regardless of current state
*/
toggleClass: function(node, className, force) {
var add = (force !== undefined) ? force :
!(hasClass(node, className));
if (add) {
addClass(node, className);
} else {
removeClass(node, className);
}
}
});
hasClass = Y.DOM.hasClass;
removeClass = Y.DOM.removeClass;
addClass = Y.DOM.addClass;
}, '3.7.3' ,{requires:['dom-core']});
| artefactual-labs/trac | sites/all/libraries/yui/build/dom-class/dom-class-debug.js | JavaScript | gpl-2.0 | 3,423 |
var options={}; options.login=true;
LoginRadius_SocialLogin.util.ready(function ()
{ $ui = LoginRadius_SocialLogin.lr_login_settings;
$ui.interfacesize = Drupal.settings.lrsociallogin.interfacesize;
$ui.lrinterfacebackground=Drupal.settings.lrsociallogin.lrinterfacebackground;
$ui.noofcolumns= Drupal.settings.lrsociallogin.noofcolumns;
$ui.apikey = Drupal.settings.lrsociallogin.apikey;
$ui.is_access_token=true;
$ui.callback=Drupal.settings.lrsociallogin.location;
$ui.lrinterfacecontainer ="interfacecontainerdiv"; LoginRadius_SocialLogin.init(options); });
LoginRadiusSDK.setLoginCallback(function () {
var token = LoginRadiusSDK.getToken();
var form = document.createElement('form');
form.action = Drupal.settings.lrsociallogin.location;
form.method = 'POST';
var hiddenToken = document.createElement('input');
hiddenToken.type = 'hidden';
hiddenToken.value = token;
hiddenToken.name = 'token';
form.appendChild(hiddenToken);
document.body.appendChild(form);
form.submit();
}); | bedesign323/aimhigh | sites/all/modules/contrib/sociallogin/js/sociallogin_interface.js | JavaScript | gpl-2.0 | 1,057 |
module.exports = function(grunt) {
require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks);
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
copy: {
main: {
expand: true,
cwd: "src/",
src: ["**", "!css/**/*.scss", "!css/**/*.less"],
dest: "dist/"
}
},
less: {
options: {
paths: ["src/css"]
},
src: {
expand: true,
cwd: "src/css",
src: "*.less",
ext: ".css",
dest: "src/css"
}
},
sass: {
dist:{
options:{
style: 'expanded', // values: nested, expanded, compact, compressed
noCache: true
},
files:[{
expand: true,
cwd: "src/css",
src: ["*.scss"],
dest: "src/css",
ext: ".css"
}]
}
},
watch: {
options: {
nospawn: true,
livereload: true
},
less: {
files: ["src/css/**/*.less"],
tasks: ["less"]
},
sass: {
files: ["src/css/**/*.scss"],
tasks: ["sass"]
},
copy: {
files: ["src/**"],
tasks: ["copy:main"]
}
}
});
grunt.registerTask("default", ["watch"]);
};
| MDIAZ88/mad-css-less-sass | Gruntfile.js | JavaScript | gpl-2.0 | 1,266 |
var ModuleManager = (function(){
//Directorio donde se encuentran los modulos
const BASE_PATH = "js/modules/";
//modules
var modules = {
"templateManager":{
"className":"TemplateManager",
"fileName":"templateManagerModule.js",
"order":1,
"loaded":false,
"dependences":null,
"instance":null
},
"preferences":{
"className":"Preferences",
"fileName":"preferencesModule.js",
"order":1,
"loaded":false,
"dependences":["templateManager"],
"instance":null
},
"logger":{
"className":"Logger",
"fileName":"logModule.js",
"order":2,
"loaded":false,
"dependences":null,
"instance":null
},
"webSpeech":{
"className":"WebSpeech",
"fileName":"webSpeechModule.js",
"order":3,
"loaded":false,
"dependences":null,
"instance":null
},
"utils":{
"className":"Utils",
"fileName":"utils.js",
"order":4,
"loaded":false,
"dependences":null,
"instance":null
},
"serviceLocator":{
"className":"ServiceLocator",
"fileName":"serviceLocatorModule.js",
"order":3,
"loaded":false,
"dependences":["logger","utils"],
"instance":null
},
"geoLocation":{
"className":"GeoLocation",
"fileName":"geolocationModule.js",
"order":4,
"loaded":false,
"dependences":["serviceLocator"],
"instance":null
},
"notificator":{
"className":"Notificator",
"fileName":"notificationsModule.js",
"order":5,
"loaded":false,
"dependences":["templateManager"],
"instance":null
},
"applicationsManager":{
"className":"ApplicationsManager",
"fileName":"applicationsModule.js",
"order":6,
"loaded":false,
"dependences":["templateManager","serviceLocator","notificator"],
"instance":null
},
"searchs":{
"className":"Searchs",
"fileName":"searchsModule.js",
"order":7,
"loaded":false,
"dependences":["templateManager","serviceLocator","webSpeech","applicationsManager","notificator"],
"instance":null
},
"contacts":{
"className":"Contacts",
"fileName":"contactsModule.js",
"order":8,
"loaded":false,
"dependences":["templateManager","serviceLocator","webSpeech","notificator","geoLocation"],
"instance":null
},
"gui":{
"className":"GUI",
"fileName":"guiModule.js",
"order":9,
"loaded":false,
"dependences":["serviceLocator","searchs","contacts","applicationsManager","notificator"],
"instance":null
}
};
/**
* Devuelve las dependencias a partir de los nombres.
*
* @param {Array} arr: names of the dependencies
* @return {Array} dependencies to bind
*/
var getDependencies = function(arr) {
return arr instanceof Array && arr.length ? arr.map(function (value) {
var o = modules[value] && modules[value].instance;
if (!o) {
throw new Error('Dependency ' + value + ' not found');
}else{
return o;
}
}) : false;
}
/**
* Extrae los nombres de las dependencias a inyectar.
*
* @param {Function} target: function to process
* @return {Array}
*/
var getArgs = function(target) {
if (!target instanceof Function) {
throw new TypeError('Target to process should be a Function');
}else{
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var SPACES = /[\s|\t|\n|\r]+/mg;
var result = target.toString().match(FN_ARGS);
//Comprobamos si existe alguna dependencia a inyectar
if(result && result[1])
var args = result[1].replace(COMMENTS,'').replace(SPACES,'').split(',');
else
var args = false;
return args;
}
}
/**
* Crea el objeto con las dependencias previamente inyectadas.
*
* @param {Function} constructor: function to call as constructor
* @return {Object} object created from its constructor
*/
var create = function(constructor) {
var args = getArgs(constructor);
if (args) {
var args = [null].concat(getDependencies(args));
var o = new (Function.prototype.bind.apply(constructor, args))();
}else{
var o = new (Function.prototype.bind.apply(constructor))();
}
return o;
}
var loadScript = function(src, callback) {
var s,r,t;
r = false ;
s = document. createElement ('script' );
s.type = 'text/javascript' ;
s.src = src;
s.onload = s.onreadystatechange = function () {
if ( !r && (!this .readyState || this .readyState == 'complete' )){
r = true ;
typeof(callback) == "function" && callback();
}
};
t = document.getElementsByTagName ('script')[0];
t.parentNode.insertBefore (s, t);
}
var downloadModules = function(callback){
console.log(modules);
for(var module in modules)
(function(currentModule){
loadScript(BASE_PATH+currentModule.fileName,function(){
currentModule.loaded = true;
Object.keys(modules).map(function(key){
return modules[key].loaded;
}).indexOf(false) == -1 && typeof(callback) == "function" && callback();
});
})(modules[module]);
}
var loadModules = function(callback){
downloadModules(function(){
for(var module in modules){
console.log("Cargando Módulo : " + modules[module].className);
modules[module].instance = create(window[modules[module].className]);
delete window[modules[module].className];
}
typeof(callback) == "function" && callback();
});
}
//API pública
return{
loadModules:loadModules
}
})(); | sergio11/teVeo | js/managerModule.js | JavaScript | gpl-2.0 | 6,834 |
var SPHERE = {
getSphereVertex: function (radius, res) { // Se obtienen los vértices, normales y coordenadas de textura
var vertexData = [], alpha, beta, x, y, z, u, v;
for (var i = 0; i <= res; i++) { // Se recorren las latitudes
alpha = i * Math.PI / res; // Ángulo latitud
for (var j = 0; j <= res; j++) { // Se recorren las longitudes
beta = j * 2 * Math.PI / res; // Ángulo longitud
// Cálculo de x, y, z para vértices y normales
x = Math.cos(beta) * Math.sin(alpha);
y = Math.cos(alpha);
z = Math.sin(beta) * Math.sin(alpha);
// Cálculo de u, v para las coordenadas de textura
u = 1 - (j / res);
v = 1 - (i / res);
// Vértices
vertexData.push(radius * x);
vertexData.push(radius * y);
vertexData.push(radius * z);
// Normales
vertexData.push(x);
vertexData.push(y);
vertexData.push(z);
// Coordenadas de textura
vertexData.push(u);
vertexData.push(v);
}
}
return vertexData;
},
getShereFaces: function (res) { // Se obtienen los índices para crear las caras
var indexData = [], first, second;
for (var i = 0; i < res; i++) { // Se recorren las latitudes
for (var j = 0; j < res; j++) { // Se recorren las longitudes
// Cálculo de las esquinas superior e inferior izquierda
first = (i * (res + 1)) + j;
second = first + res + 1;
// Cara par
indexData.push(first); // Esquina superior izquierda
indexData.push(second); // Esquina inferior izquierda
indexData.push(first + 1); // Esquina superior derecha
// Cara impar
indexData.push(second); // Esquina inferior izquierda
indexData.push(second + 1); // Esquina inferior derecha
indexData.push(first + 1); // Esquina superior derecha
}
}
return indexData;
}
}; | fblupi/grado_informatica-SG | P2/P2_1/SistemaSolar/js/sphere.js | JavaScript | gpl-2.0 | 2,248 |
dojo.require("dijit.Dialog");
dojo.require("dijit.form.FilteringSelect");
dojo.require('dijit.form.Button');
dojo.require('dijit.TooltipDialog');
dojo.require('dijit.form.DropDownButton');
dojo.require('dijit.form.CheckBox');
dojo.require('dojox.grid.DataGrid');
dojo.require('dojo.data.ItemFileWriteStore');
dojo.require('openils.widget.OrgUnitFilteringSelect');
dojo.require('openils.acq.CurrencyType');
dojo.require('openils.Event');
dojo.require('openils.Util');
dojo.require('openils.User');
dojo.require('openils.CGI');
dojo.require('openils.PermaCrud');
dojo.require('openils.widget.AutoGrid');
dojo.require('openils.widget.ProgressDialog');
dojo.require('fieldmapper.OrgUtils');
dojo.requireLocalization('openils.acq', 'acq');
var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
var contextOrg;
var rolloverResponses;
var rolloverMode = false;
var fundFleshFields = [
'spent_balance',
'combined_balance',
'spent_total',
'encumbrance_total',
'debit_total',
'allocation_total'
];
var adminPermOrgs = [];
var cachedFunds = [];
function initPage() {
contextOrg = openils.User.user.ws_ou();
/* Reveal controls for rollover without money if org units say ok.
* Actual ability to do the operation is controlled in the database, of
* course. */
var ouSettings = fieldmapper.aou.fetchOrgSettingBatch(
openils.User.user.ws_ou(), ["acq.fund.allow_rollover_without_money"]
);
if (
ouSettings["acq.fund.allow_rollover_without_money"] &&
ouSettings["acq.fund.allow_rollover_without_money"].value
) {
dojo.query(".encumb_only").forEach(
function(o) { openils.Util.show(o, "table-row"); }
);
}
var connect = function() {
dojo.connect(contextOrgSelector, 'onChange',
function() {
contextOrg = this.attr('value');
dojo.byId('oils-acq-rollover-ctxt-org').innerHTML =
fieldmapper.aou.findOrgUnit(contextOrg).shortname();
rolloverMode = false;
gridDataLoader();
}
);
};
dojo.connect(refreshButton, 'onClick',
function() { rolloverMode = false; gridDataLoader(); });
new openils.User().buildPermOrgSelector(
['ADMIN_ACQ_FUND', 'VIEW_FUND'],
contextOrgSelector, contextOrg, connect);
dojo.byId('oils-acq-rollover-ctxt-org').innerHTML =
fieldmapper.aou.findOrgUnit(contextOrg).shortname();
loadYearSelector();
lfGrid.onItemReceived = function(item) {cachedFunds.push(item)};
new openils.User().getPermOrgList(
'ADMIN_ACQ_FUND',
function(list) {
adminPermOrgs = list;
loadFundGrid(
new openils.CGI().param('year')
|| new Date().getFullYear().toString());
},
true, true
);
}
function gridDataLoader() {
lfGrid.resetStore();
if(rolloverMode) {
var offset = lfGrid.displayOffset;
for(var i = offset; i < (offset + lfGrid.displayLimit - 1); i++) {
var fund = rolloverResponses[i];
if(!fund) break;
lfGrid.store.newItem(fieldmapper.acqf.toStoreItem(fund));
}
} else {
loadFundGrid();
}
}
function getBalanceInfo(rowIdx, item) {
if (!item) return '';
var fundId = this.grid.store.getValue(item, 'id');
var fund = cachedFunds.filter(function(f) { return f.id() == fundId })[0];
var cb = fund.combined_balance();
return cb ? cb.amount() : '0';
}
function loadFundGrid(year) {
openils.Util.hide('acq-fund-list-rollover-summary');
year = year || fundFilterYearSelect.attr('value');
cachedFunds = [];
lfGrid.loadAll(
{
flesh : 1,
flesh_fields : {acqf : fundFleshFields},
// by default, sort funds I can edit to the front
order_by : [
{ 'class' : 'acqf',
field : 'org',
compare : {'in' : adminPermOrgs},
direction : 'desc'
},
{ 'class' : 'acqf',
field : 'name'
}
]
}, {
year : year,
org : fieldmapper.aou.descendantNodeList(contextOrg, true)
}
);
}
function loadYearSelector() {
fieldmapper.standardRequest(
['open-ils.acq', 'open-ils.acq.fund.org.years.retrieve'],
{ async : true,
params : [openils.User.authtoken, {}, {limit_perm : 'VIEW_FUND'}],
oncomplete : function(r) {
var yearList = openils.Util.readResponse(r);
if(!yearList) return;
yearList = yearList.map(function(year){return {year:year+''};}); // dojo wants strings
var yearStore = {identifier:'year', name:'year', items:yearList};
yearStore.items = yearStore.items.sort().reverse();
fundFilterYearSelect.store = new dojo.data.ItemFileWriteStore({data:yearStore});
// default to this year
fundFilterYearSelect.setValue(new Date().getFullYear().toString());
dojo.connect(
fundFilterYearSelect,
'onChange',
function() {
rolloverMode = false;
gridDataLoader();
}
);
}
}
);
}
function performRollover(args) {
rolloverMode = true;
progressDialog.show(true, "Processing...");
rolloverResponses = [];
var method = 'open-ils.acq.fiscal_rollover';
if(args.rollover[0] == 'on') {
method += '.combined';
} else {
method += '.propagate';
}
var dryRun = args.dry_run[0] == 'on';
if(dryRun) method += '.dry_run';
var encumbOnly = args.encumb_only[0] == 'on';
var count = 0;
var amount_rolled = 0;
var year = fundFilterYearSelect.attr('value'); // TODO alternate selector?
fieldmapper.standardRequest(
['open-ils.acq', method],
{
async : true,
params : [
openils.User.authtoken,
year,
contextOrg,
(args.child_orgs[0] == 'on'),
{ encumb_only : encumbOnly }
],
onresponse : function(r) {
var resp = openils.Util.readResponse(r);
rolloverResponses.push(resp.fund);
count += 1;
amount_rolled += Number(resp.rollover_amount);
},
oncomplete : function() {
var nextYear = Number(year) + 1;
rolloverResponses = rolloverResponses.sort(
function(a, b) {
if(a.code() > b.code())
return 1;
return -1;
}
)
// add the new, rolled funds to the cache. Note that in dry-run
// mode, these are ephemeral and no longer exist on the server.
cachedFunds = cachedFunds.concat(rolloverResponses);
dojo.byId('acq-fund-list-rollover-summary-header').innerHTML =
dojo.string.substitute(
localeStrings.FUND_LIST_ROLLOVER_SUMMARY,
[nextYear]
);
dojo.byId('acq-fund-list-rollover-summary-funds').innerHTML =
dojo.string.substitute(
localeStrings.FUND_LIST_ROLLOVER_SUMMARY_FUNDS,
[nextYear, count]
);
dojo.byId('acq-fund-list-rollover-summary-rollover-amount').innerHTML =
dojo.string.substitute(
localeStrings.FUND_LIST_ROLLOVER_SUMMARY_ROLLOVER_AMOUNT,
[nextYear, amount_rolled]
);
if(!dryRun) {
openils.Util.hide('acq-fund-list-rollover-summary-dry-run');
// add the new year to the year selector if it's not already there
fundFilterYearSelect.store.fetch({
query : {year : nextYear},
onComplete:
function(list) {
if(list && list.length > 0) return;
fundFilterYearSelect.store.newItem({year : nextYear});
}
});
}
openils.Util.show('acq-fund-list-rollover-summary');
progressDialog.hide();
gridDataLoader();
}
}
);
}
openils.Util.addOnLoad(initPage);
| ubcic/evergreen | Open-ILS/web/js/ui/default/acq/financial/list_funds.js | JavaScript | gpl-2.0 | 8,907 |
/**
* Copyright (C) SiteSupra SIA, Riga, Latvia, 2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
YUI.add('itemmanager.itemlist-uploader', function (Y) {
//Invoke strict mode
"use strict";
//Shortcut
var Manager = Supra.Manager,
Action = Manager.PageContent;
/*
* Editable content
*/
function ItemListUploader (config) {
ItemListUploader.superclass.constructor.apply(this, arguments);
}
ItemListUploader.NAME = 'itemmanager-itemlist-uploader';
ItemListUploader.NS = 'uploader';
ItemListUploader.ATTRS = {};
Y.extend(ItemListUploader, Y.Plugin.Base, {
/**
* Supra.Uploader instance
* @type {Object}
* @private
*/
uploader: null,
/**
* File uploader ids to item ids
* @type {Object}
* @private
*/
ids: null,
/**
*
*/
initializer: function () {
var itemlist = this.get('host'),
container = itemlist.get('contentElement');
this.ids = {};
this.listeners = [];
this.listeners.push(itemlist.after('contentElementChange', this.reattachListeners, this));
if (container) {
this.reattachListeners();
}
},
destructor: function () {
this.resetAll();
// Listeners
var listeners = this.listeners,
i = 0,
ii = listeners.length;
for (; i < ii; i++) listeners[i].detach();
this.listeners = null;
},
/**
* Attach drag and drop listeners
*/
reattachListeners: function () {
var itemlist = this.get('host'),
container = itemlist.get('contentElement'),
//doc = null,
target = null;
if (this.uploader) {
this.uploader.destroy();
this.uploader = null;
}
if (!container) {
return false;
}
//Create uploader
target = itemlist.get('iframe').one('.supra-itemmanager-wrapper');
this.uploader = new Supra.Uploader({
'dropTarget': target,
'allowBrowse': false,
'allowMultiple': true,
'accept': 'image/*',
'requestUri': Supra.Url.generate('media_library_upload'),
'uploadFolderId': itemlist.get('host').options.imageUploadFolder
});
this.uploader.on('file:upload', this.onFileUploadStart, this);
this.uploader.on('file:complete', this.onFileUploadEnd, this);
this.uploader.on('file:error', this.onFileUploadError, this);
},
/**
* Reset all iframe content bindings, etc.
*/
resetAll: function () {
var uploader = this.uploader;
if (uploader) {
uploader.destroy(true);
this.uploader = null;
}
},
/* ------------------------ FILE UPLOAD ------------------------ */
/**
* Handle file upload start
*/
onFileUploadStart: function (e) {
var data = e.details[0],
itemlist = this.get('host'),
item = null;
// Prevent item from being opened for editing
itemlist.initializing = true;
item = itemlist.addItem({'title': e.title.replace(/\..+$/, '')});
itemlist.initializing = false;
this.ids[e.id] = item.__suid;
},
/**
* Handle file upload end
*/
onFileUploadEnd: function (e) {
var data = e.details[0],
itemlist = this.get('host'),
itemdrop = itemlist.drop;
if (e.old_id in this.ids) {
itemdrop.updateItemInCollection(data, this.ids[e.old_id]);
delete(this.ids[e.old_id]);
} else {
itemdrop.addItemToCollection(data);
}
},
/**
* Handle file upload error
*/
onFileUploadError: function (e) {
var itemlist = this.get('host');
itemlist.removeItem(this.ids[e.id]);
delete(this.ids[e.id]);
}
});
Supra.ItemManagerItemListUploader = ItemListUploader;
//Since this widget has Supra namespace, it doesn't need to be bound to each YUI instance
//Make sure this constructor function is called only once
delete(this.fn); this.fn = function () {};
}, YUI.version, {requires: ['plugin', 'supra.uploader']});
| sitesupra/sitesupra | lib/Supra/Package/Cms/Resources/public/content-manager/itemmanager/modules/itemlist-uploader.js | JavaScript | gpl-2.0 | 4,508 |
(function ($, window, document) {
"use strict";
$(document).on( 'ready', function(){
var $body = $('body'),
$topbar = $( document.getElementById('topbar') ),
$products_sliders = $('.products-slider-wrapper, .categories-slider-wrapper');
/*************************
* SHOP STYLE SWITCHER
*************************/
$('#list-or-grid').on( 'click', 'a', function(){
var trigger = $(this),
view = trigger.attr( 'class' ).replace('-view', '');
$( 'ul.products li' ).removeClass( 'list grid' ).addClass( view );
trigger.parent().find( 'a' ).removeClass( 'active' );
trigger.addClass( 'active' );
$.cookie( yit_shop_view_cookie, view );
return false;
});
/*************************
* Fix Product Name and Price
*************************/
var padding_nameprice = function () {
$('li.product .product-wrapper .info-product.slideup').each(function () {
$(this).find('h3').css( 'padding-' + ( ! yit.isRtl ? 'right' : 'left' ), $(this).find('span.price').width() + 10 );
});
};
if( $(window).width() > 1199 ){
padding_nameprice();
}
$(document).on('yith-wcan-ajax-filtered', padding_nameprice );
/*************************
* ADD TO CART
*************************/
var product, product_onsale;
var add_to_cart = function() {
$('ul.products').on('click', 'li.product .add_to_cart_button', function () {
product = $(this).parents('li.product');
product_onsale = product.find('.product-wrapper > .onsale');
if( typeof yit.load_gif != 'undefined' ) {
product.find('.thumb-wrapper').block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}});
}
else{
product.find('.thumb-wrapper').block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}});
}
});
}
add_to_cart();
$(document).on('yith-wcan-ajax-filtered', add_to_cart );
$body.on('added_to_cart', function () {
if( typeof product_onsale === 'undefined' && typeof product === 'undefined' ) return;
$( '.products-slider.swiper .swiper-slide .opacity .swiper-product-informations span.product-add-to-cart a.added_to_cart.wc-forward')
.addClass( 'btn btn-flat' )
.prev('a').remove();
if ( product_onsale.length ) {
product_onsale.remove();
}
product.find('.thumb-wrapper').append('<div class="added_to_cart_box"><div class="added_to_cart_label">' + yit.added_to_cart + '</div></div>');
product.find('.added_to_cart_label').append(product.find('a.added_to_cart'));
product.find('.product-wrapper div:first-child').addClass('nohover');
setTimeout( function(){
product.find('.added_to_cart_box').fadeOut(2000, function(){ $(this).remove(); });
product.find('.product-wrapper div:first-child').removeClass('nohover');
}, 3000 );
if (product.find('.product-wrapper > .added_to_cart_ico').length == 0) {
setTimeout(function() {
product.find('.product-wrapper').append('<span class="added_to_cart_ico">' + yit.added_to_cart_ico + '</span>');
}, 4000);
}
product.find('.thumb-wrapper').unblock();
});
/*************************
* PRODUCTS SLIDER
*************************/
if( $.fn.owlCarousel && $.fn.imagesLoaded && $products_sliders.length ) {
var product_slider = function(t) {
t.imagesLoaded(function(){
var cols = t.data('columns') ? t.data('columns') : 4;
var autoplay = (t.attr('data-autoplay')=='true') ? 3000 : false;
var owl = t.find('.products').owlCarousel({
items : cols,
responsiveClass : true,
responsive:{
0 : {
items: 2
},
479 : {
items: 3
},
767 : {
items: 4
},
992 : {
items: cols
}
},
autoplay : autoplay,
autoplayTimeout : 2000,
autoplayHoverPause: true,
loop : true,
rtl: yit.isRtl == true
});
// Custom Navigation Events
t.on('click', '.es-nav-next', function () {
owl.trigger('next.owl.carousel');
});
t.on('click', '.es-nav-prev', function () {
owl.trigger('prev.owl.carousel');
});
});
};
// initialize slider in only visible tabs
$products_sliders.each(function(){
var t = $(this);
if( ! t.closest('.panel.group').length || t.closest('.panel.group').hasClass('showing') ){
product_slider( t );
}
});
$('.tabs-container').on( 'yit_tabopened', function( e, tab ) {
product_slider( tab.find( $products_sliders ) );
});
}
/*************************
* VARIATIONS SELECT
*************************/
var variations_select = function(){
// variations select
if( $.fn.selectbox ) {
var form = $('form.variations_form');
var select = form.find('select:not(.yith_wccl_custom)');
if( form.data('wccl') ) {
select = select.filter(function(){
return $(this).data('type') == 'select'
});
}
select.selectbox({
effect: 'fade',
onOpen: function() {
//$('.variations select').trigger('focusin');
}
});
var update_select = function(event){ // console.log(event);
select.selectbox("detach");
select.selectbox("attach");
};
// fix variations select
form.on( 'woocommerce_update_variation_values', update_select);
form.find('.reset_variations').on('click.yit', update_select);
}
};
variations_select();
/*************************
* TOPBAR INDICATORS
*************************/
$topbar.find('#lang_sel .lang_sel_sel').append('<span class="sf-sub-indicator"> +</span>');
$topbar.find('#wcml_currency_switcher > ul > li a.sbSelector').append('<span class="sf-sub-indicator"> +</span>');
/*************************
* PRODUCT TABS
*************************/
$('.single-product-tabs.vertical').on('click', 'ul.tabs li .tab_name', function () {
var tab_trigger = $(this),
panel = tab_trigger.siblings('.panel'),
container = tab_trigger.closest('.single-product-tabs');
if ( ! tab_trigger.hasClass('active') ) {
//remove opened tab
container.find('.tab_name.active').siblings('div.panel').slideToggle('slow');
container.find('.tab_name.active').removeClass('active');
//open tab
tab_trigger.addClass('active');
} else {
tab_trigger.removeClass('active');
}
panel.slideToggle('slow');
});
/*************************
* INQUIRY FORM
*************************/
var inquiry_form = function(){
if ( $('#inquiry-form .product-inquiry').length ) {
$(document).on('click', '#inquiry-form .product-inquiry', function(event){
event.stopImmediatePropagation('click');
$(this).next('form.contact-form').slideToggle('slow');
});
}
};
inquiry_form();
$(document).on('yit_quick_view_loaded', inquiry_form);
if( $( 'body').hasClass( 'single-product' ) ) {
setTimeout( function() {
if( $.trim( $( 'div.user-message').html() ) != '' || $.trim( $( '.contact-form li div.msg-error' ).text() ) != '' ) {
$('form.contact-form').slideToggle('slow');
}
}, 200 );
}
/*************************
* Wishlist
*************************/
var wishlist_share = function() {
if ( $('#wishlist-share div.share-text').length ) {
$(document).on('click', '#wishlist-share div.share-text', function(){
$(this).next('div.share-link-container').slideToggle('slow');
});
}
};
wishlist_share();
$(document).on('yit_quick_view_loaded', wishlist_share);
/*************************
* Update Calculate Shipping Select
*************************/
var wc_version = 2.2;
if (typeof yit_woocommerce != 'undefined') wc_version = parseFloat(yit_woocommerce.version);
if ( wc_version < 2.3 && $.fn.selectbox ) {
$('#calc_shipping_state').next('.sbHolder').addClass('stateHolder');
$body.on('country_to_state_changing', function(){
$('.stateHolder').remove();
$('#calc_shipping_state').show().attr('sb', '');
$('select#calc_shipping_state').selectbox({
effect: 'fade',
classHolder: 'stateHolder sbHolder'
});
});
}
/*************************
* Login Form
*************************/
// $('#login-form').on('submit', function(){
// var a = $('#reg_password').val();
// var b = $('#reg_password_retype').val();
// if(!(a==b)){
// $('#reg_password_retype').addClass('invalid');
// return false;
// }else{
// $('#reg_password_retype').removeClass('invalid');
// return true;
// }
// });
/*************************
* PRODUCT QUICK VIEW
*************************/
function quick_view_trigger() {
$('div.quick-view a.trigger').yit_quick_view({
item_container: 'li.product',
loader : 'div.single-product.woocommerce',
assets : yit_quick_view.assets,
before : function (trigger, item) {
// add loading in the button
if( typeof yit.load_gif != 'undefined' ) {
trigger.parent().block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}});
}
else{
trigger.parent().block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}});
}
item.find('.thumb-wrapper').addClass('hover');
},
openDialog : function (trigger, item) {
// remove loading from button
trigger.parent().unblock();
item.find('.thumb-wrapper').removeClass('hover');
},
completed : function (trigger, item, html, overlay) {
var data = $('<div>' + html + '</div>'),
title = data.find('h1.product_title').html(),
price = data.find('p.price').html(),
rating = data.find('div.star-rating').html(),
container = document.getElementById('wrapper'),
wrapper = $(overlay).find('.main .container');
// add main class to dialog container
$(overlay).addClass('product-quick-view');
// head
$('<p />').addClass('price').html(price).prependTo(wrapper.find('.head'));
$('<div />').addClass('star-rating').html(rating).prependTo(wrapper.find('.head'));
$('<h4 />').html(title).prependTo(wrapper.find('.head'));
//prettyPhoto
if ( typeof $.prettyPhoto != 'undefined' ) {
data.find( "a[rel^='thumbnails'], a.zoom" ).prettyPhoto({
social_tools : false,
theme : 'pp_woocommerce',
horizontal_padding: 40,
opacity : 0.9,
deeplinking : false
});
}
// quantity fields
$('div.quantity:not(.buttons_added), td.quantity:not(.buttons_added)').addClass('buttons_added').append('<input type="button" value="+" class="plus" />').prepend('<input type="button" value="-" class="minus" />');
variations_select();
// add to cart
$('form.cart', overlay).on('submit', function (e) {
e.preventDefault();
var form = $(this),
button = form.find('button'),
product_url = item.find('a.thumb').attr('href');
if( typeof yit.load_gif != 'undefined' ) {
button.block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}});
}
else if (typeof( woocommerce_params.plugin_url ) != 'undefined') {
button.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.plugin_url + '/assets/images/ajax-loader.gif) no-repeat center', opacity: 0.3, cursor: 'none'}});
}
else {
button.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}});
}
$.post(product_url, form.serialize() + '&_wp_http_referer=' + product_url, function (result) {
var message = $( '.woocommerce-message', result ),
cart_dropdown = $( '#header .yit_cart_widget', result);
if( typeof wc_cart_fragments_params != 'undefined') {
// update fragments
var $supports_html5_storage;
try {
$supports_html5_storage = ( 'sessionStorage' in window && window.sessionStorage !== null );
window.sessionStorage.setItem('wc', 'test');
window.sessionStorage.removeItem('wc');
} catch (err) {
$supports_html5_storage = false;
}
$.ajax({
url : wc_cart_fragments_params.wc_ajax_url.toString().replace('%%endpoint%%', 'get_refreshed_fragments'),
type : 'POST',
success: function (data) {
if (data && data.fragments) {
$.each(data.fragments, function (key, value) {
$(key).replaceWith(value);
});
if ($supports_html5_storage) {
sessionStorage.setItem(wc_cart_fragments_params.fragment_name, JSON.stringify(data.fragments));
sessionStorage.setItem('wc_cart_hash', data.cart_hash);
}
$(document.body).trigger('wc_fragments_refreshed');
}
}
});
}
// add message
$('div.product', overlay).before(message);
// remove loading
button.unblock();
});
});
// others
$('#wishlist-share').find('.share-link-container').hide();
$('#inquiry-form').find('form.contact-form').hide();
},
action : 'yit_load_product_quick_view'
});
}
if ($.fn.yit_quick_view && typeof yit_quick_view != 'undefined') {
quick_view_trigger();
$(document).on('yith-wcan-ajax-filtered', quick_view_trigger);
}
/*************************
* WISHLIST LABEL
*************************/
$( '.yith-wcwl-add-button .add_to_wishlist').on( 'click', function() {
var feedback = $(this).closest('.yith-wcwl-add-to-wishlist').find('.yith-wcwl-wishlistaddedbrowse span.feedback');
feedback.fadeIn();
setTimeout( function(){
feedback.fadeOut('slow');
}, 4000 );
});
/*************************
* Widget Woo Price Filter
*************************/
if( yit.price_filter_slider == 'no' || typeof yit.price_filter_slider == 'undefined' ) {
var removePriceFilterSlider = function() {
$( 'input#min_price, input#max_price' ).show();
$('form > div.price_slider_wrapper').find( 'div.price_slider, div.price_label' ).hide();
};
removePriceFilterSlider();
}
/*****************************
* TERMS AND CONDITIONS POPUP
*****************************/
if ($.fn.yit_quick_view ) {
var term_popup = function() {
$('p.terms a').yit_quick_view({
item_container: 'p.terms',
loader: '#primary .content',
loadPage: true,
before: function( trigger, item ) {
// add loading in the button
if( typeof yit.load_gif != 'undefined' ) {
item.block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}});
} else {
item.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}});
}
},
completed: function( trigger, item, html, overlay ) {
var data = $('<div>' + html + '</div>'),
title = trigger.text(),
container = document.getElementById( 'wrapper' ),
wrapper = $(overlay).find('.main .container');
// head
$('<h4 />').html(title).prependTo( wrapper.find('.head') );
$(overlay).addClass('terms-popup');
$(overlay).find('.content').removeClass('col-sm-12 col-sm-9');
},
openDialog: function( trigger, item ) {
item.unblock();
}
});
};
$body.on('updated_checkout', term_popup);
term_popup();
}
});
})( jQuery, window, document ); | lieison/IndustriasFenix | wp-content/themes/bishop/theme/assets/js/woocommerce.js | JavaScript | gpl-2.0 | 21,939 |
if (Meteor.isServer) {
var
//// A lookup-table whose keys are generated each time an ‘you.register’ form is rendered using the `babelslug()` method.
//// The key is a babelslug, followed by hyphen, followed by a Meteor connection ID (like a session ID for anon users).
//// The value is the unix timestamp in milliseconds, which allows us to clear out old and unused babelslugs.
//// Two examples are shown here:
recentBabelslugs = { // @todo for a multi-servo project, move this functionality to a shared mongoDB collection
// 'MagentaMouse-KukNJw4d4vjGzzrQa': 1409341347912,
// 'BlueChessCat-YYJWMWTPq7RFWdKr6': 1409341399283
}
//// Clear out stale elements in the `recentBabelslugs` lookup-table.
, recentBabelslugsHousekeeping = function () {
var key
, now = Date.now()
;
for (key in recentBabelslugs) {
if (15 * 60 * 1000 < now - recentBabelslugs[key]) { // allow a user 15 minutes to fill in the registration form
delete recentBabelslugs[key];
}
}
}
//// Check how many times a given `username` exists in the user database. If all’s well, this should only ever return `0` or `1`.
, usernameCount = function (username) {
return Meteor.users.find({ 'profile.username': username }).count();
}
//// BabelSlug, from Rich Plastow’s work, 2014-02-09.
, ucs2 = [
[ // animal
{ en:'slug' ,es:'babosa' ,ru:'\u0441\u043B\u0438\u0437\u043D\u044F\u043A',fr:'limace' ,zh:'\u86DE\u8753',ar:'\u064A\u0631\u0642\u0627\u0646\u0629' }
, { en:'mouse' ,es:'rat\u00F3n',ru:'\u043C\u044B\u0448\u044C' ,fr:'souris' ,zh:'\u9F20\u6807',ar:'\u0641\u0623\u0631' }
, { en:'cow' ,es:'vaca' ,ru:'\u043A\u043E\u0440\u043E\u0432\u0430' ,fr:'vache' ,zh:'\u725B' ,ar:'\u0628\u0642\u0631\u0629' }
, { en:'cat' ,es:'gato' ,ru:'\u043A\u043E\u0448\u043A\u0430' ,fr:'chat' ,zh:'\u732B' ,ar:'\u0642\u0637' }
, { en:'rabbit',es:'conejo' ,ru:'\u043A\u0440\u043E\u043B\u0438\u043A' ,fr:'lapin' ,zh:'\u5154' ,ar:'\u0623\u0631\u0646\u0628' }
, { en:'deer' ,es:'ciervo' ,ru:'\u043E\u043B\u0435\u043D\u044C' ,fr:'cerf' ,zh:'\u9E7F' ,ar:'\u0623\u064A\u0644' }
, { en:'bear' ,es:'oso' ,ru:'\u043C\u0435\u0434\u0432\u0435\u0434\u044C',fr:'ours' ,zh:'\u718A' ,ar:'\u062F\u064F\u0628\u0651' }
, { en:'frog' ,es:'rana' ,ru:'\u043B\u044F\u0433\u0443\u0448\u043A\u0430',fr:'grenouille',zh:'\u9752\u86D9',ar:'\u0636\u0641\u062F\u0639' }
]
// , [ // texture
// { en:'-' ,es:'-' ,ru:'-' ,fr:'-' ,zh:'-' ,ar:'-' }
// , { en:'dotted' ,es:'punteado',ru:[1087,1091,1085,1082,1090,1080,1088,1085,1099,1081],fr:'pointill\u00E9',zh:[26001,28857],ar:[1605,1606,1602,1591] }
// , { en:'striped',es:'rayas' ,ru:[1087,1086,1083,1086,1089,1072,1090,1099,1081] ,fr:'ray\u00E9' ,zh:[26465,32441],ar:[1605,1602,1604,1605] }
// , { en:'chess' ,es:'ajedrez' ,ru:[1096,1072,1093,1084,1072,1090,1099] ,fr:'\u00E9checs' ,zh:[26827] ,ar:[1588,1591,1585,1606,1580] }
// ]
, [ // color1
{ en:'-' ,es:'-' ,ru:'-' ,fr:'-' ,zh:'-' ,ar:'-' }
, { en:'red' ,es:'rojo' ,ru:[1082,1088,1072,1089,1085,1099,1081] ,fr:'rouge' ,zh:[32418] ,ar:[1571,1581,1605,1585] }
, { en:'orange' ,es:'naranja' ,ru:[1086,1088,1072,1085,1078,1077,1074,1099,1081],fr:'orange' ,zh:[27225] ,ar:[1575,1604,1576,1585,1578,1602,1575,1604,1610] }
, { en:'yellow' ,es:'amarillo',ru:[1078,1077,1083,1090,1099,1081] ,fr:'jaune' ,zh:[40644] ,ar:[1571,1589,1601,1585] }
, { en:'green' ,es:'verde' ,ru:[1079,1077,1083,1077,1085,1099,1081] ,fr:'vert' ,zh:[32511] ,ar:[1571,1582,1590,1585] }
// , { en:'cyan' ,es:'cian' ,ru:[1075,1086,1083,1091,1073,1086,1081] ,fr:'cyan' ,zh:[38738] ,ar:[1587,1605,1575,1608,1610] }
, { en:'blue' ,es:'azul' ,ru:[1089,1080,1085,1080,1081] ,fr:'bleu' ,zh:[34013] ,ar:[1571,1586,1585,1602] }
, { en:'purple' ,es:'magenta' ,ru:[1087,1091,1088,1087,1091,1088,1085,1099,1081],fr:'magenta',zh:[27915,32418],ar:[1571,1585,1580,1608,1575,1606,1610] } // @todo translate purple (these are for magenta)
]
, [ // emotion @todo convert remaining languages from 2014-Work/BabelSlug/README.md
{ en:'-' ,es:'-' ,fr:'-' }
, { en:'happy' ,es:'feliz' ,fr:'heureux' }
// , { en:'sad' ,es:'triste' ,fr:'triste' }
, { en:'laughing' ,es:'risa' ,fr:'rire' }
, { en:'sleepy' ,es:'soñoliento' ,fr:'somnolent' }
, { en:'surprised',es:'sorprendido',fr:'étonné' }
// , { en:'playful' ,es:'juguetón' ,fr:'espiègle' }
, { en:'confused' ,es:'confundido' ,fr:'embrouillé' }
]
]
//// Prepare an empty cache, which may contain HTML entities converted from `ucs2`, if required.
, html = (function () {
var i, j, l, m ,html = {};
for (i=0, l=ucs2.length; i<l; i++) {
html[i] = [];
for (j=0, m=ucs2[i].length; j<m; j++) {
html[i][j] = {};
}
}
return html
} ())
// !!!! `numberToPhrase()`, then `i` becomes `num`, and then `ucs2` becomes an array, and `i` is iterator !!!!
, numberToPhrase = function (number, options) {
var key, len, rem, word
, num = ~~(number < 0 ? -number : number) // ensure `num` is a positive whole number, or zero
, opt = options || {}
, l18n = ucs2[0][0][opt.l18n] ? opt.l18n : 'en' // set to English if the localization option is invalid or unspecified
, phrase = []
;
for (key in ucs2) {
len = ucs2[key].length;
rem = num % len;
if (! opt.format || 'ucs2' === opt.format) {
word = ucs2[key][rem][l18n];
// console.log('key ' + key + ' format ' + 'ucs2' + ' word ' + word);
} else if ('html' === opt.format) {
word = html[key][rem][l18n];
if (! word) {
word = html[key][rem][l18n] = ucs2[key][rem][l18n].replace(/[\u00A0-\u2666]/g, function(c) {
return '&#' + c.charCodeAt(0) + ';';
});
// console.log('ADD TO CACHE key ' + key + ' format ' + 'html' + ' word ' + word);
} else {
// console.log('GET IN CACHE key ' + key + ' format ' + 'html' + ' word ' + word);
}
} else {
// @todo format error
}
if ('-' !== word) { phrase.unshift(word); }
num = ~~(num / len); // prepare for the next part in `ucs2`
if (0 === num) { break; } // low numbers don't need to step through every section in `ucs2`
}
return phrase.join('-');
}
;
Meteor.methods({
babelslug: function () {
var i, key, babelslug;
if (this.isSimulation) { return; } // clientside stub (return value is ignored)
//// Housekeeping on the `recentBabelslugs` lut.
recentBabelslugsHousekeeping();
//// Try, 200 times, to find a username which has not been taken. @todo this is quite brute-force ... can we come up with a more elegant solution?
for (i=200; i>0; i--) {
babelslug = numberToPhrase( Math.floor(Math.random() * 50000) );
if ( 3 === babelslug.split('-').length && ! recentBabelslugs[babelslug] && ! usernameCount(babelslug) ) { break; } // we are only using three-part usernames at present
}
if (! i) { throw new Meteor.Error(500, "Cannot generate a username! Please email " + Config.about.webmaster); } // @todo check `(! i)` can ever be truthy
recentBabelslugs[babelslug] = { // later, when the form is submitted, we will check that the babelslug value is expected
now: Date.now() // allows `recentBabelslugsHousekeeping()` to find stale babelslugs
, cid: this.connection.id
}
return babelslug + '_' + this.connection.id; // @todo is `this.connection.id` ever some unexpected value, for example `null`?
}
});
Accounts.onCreateUser(function (options, user) {
var babelslug, connectionId;
//// Housekeeping on the `recentBabelslugs` lut.
recentBabelslugsHousekeeping();
//// Validate the value of `<input id="AT_field_you-babelslug" ...>`.
babelslug = options.profile['you-babelslug'].split('_')[0];
connectionId = options.profile['you-babelslug'].split('_')[1];
if (! babelslug || ! connectionId) {
throw new Meteor.Error(500, "The ‘username’ field is invalid."); // @todo better error-code than 500?
}
if (! recentBabelslugs[babelslug]) {
throw new Meteor.Error(500, "Your registration form expired after 15 minutes. Please refresh the browser and try again."); // The ‘username’ value is unexpected, so this may actually be a hack attempt
}
if ( usernameCount(babelslug) ) {
throw new Meteor.Error(500, "The ‘username’ is already in use."); // prevent two `Meteor.user` records having the same username, which could happen on a multi-servo project, until we change `recentBabelslugs` to a shared mongoDB collection @todo
}
//// Remove the babelslug, as it’s not needed any more.
delete recentBabelslugs[babelslug];
//// Record the username (‘info@loop.coop’ gets a special username).
options.profile = options.profile || {};
options.profile.username = 'info@loop.coop' === options.email ? 'red-cat' : babelslug;
//// Record other registration data.
if (options.profile['you-age-group-code']) { options.profile.agc = options.profile['you-age-group-code']; }
if (options.profile['you-based-in-code']) { options.profile.bic = options.profile['you-based-in-code']; }
if (options.profile['you-hear-about-code']) { options.profile.hac = options.profile['you-hear-about-code']; }
if (options.profile['you-hear-about-text']) { options.profile.hat = options.profile['you-hear-about-text']; }
if (options.profile['you-newsletter-opt']) { options.profile.nlo = options.profile['you-newsletter-opt']; }
//// The registration is valid, so record it as usual. http://docs.meteor.com/#accounts_oncreateuser
user.profile = options.profile;
return user;
});
}
| loopdotcoop/looptopia | you/you.create-user.js | JavaScript | gpl-2.0 | 11,763 |
var iconhead={
title:"Icon Heading Shortcode",
id :'oscitas-form-iconhead',
pluginName: 'iconhead',
setRowColors:false
};
(function() {
_create_tinyMCE_options(iconhead,800);
})();
function create_oscitas_iconhead(pluginObj){
if(jQuery(pluginObj.hashId).length){
jQuery(pluginObj.hashId).remove();
}
// creates a form to be displayed everytime the button is clicked
// you should achieve this using AJAX instead of direct html code like this
var iconhead_fa='';
/*if(ebs.ebs_fa_inclusion==1){
iconhead_fa='<h4>Font Awesome</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsfaicons+'</ul>';
}*/
iconhead_fa='<h4>Font Awesome</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsfaicons+'</ul>';
// creates a form to be displayed everytime the button is clicked
// you should achieve this using AJAX instead of direct html code like this
var form = jQuery('<div id="'+pluginObj.id+'" class="oscitas-container" title="'+pluginObj.title+'"><table id="gallery-table" class="form-table">\
<tr>\
<th><label for="oscitas-heading-icon">Select Icon:</label></th>\
<td><div id="click_icon_list" class="oscitas-icon-div"><span id="osc_show_icon"></span><span class="show-drop"></span></div><input type="hidden" id="oscitas-iconhead-icon" value=""><input type="hidden" id="oscitas-iconhead-icontype" value="">\
<div id="osc_show_iconlist" class="oscitas-icon" style="display:none;width:100%"><h4>Glyphicons</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsicons+'</ul>'+iconhead_fa+'</div>\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-iconcolor">Icon Color:</label></th>\
<td><input type="text" name="label" id="oscitas-iconhead-iconcolor" class="color" value="" /><br />\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-headingtype">Heading Type:</label></th>\
<td><select name="oscitas-iconhead-headingtype" id="oscitas-iconhead-headingtype">\
<option value="h1">H1</option>\
<option value="h2">H2</option>\
<option value="h3">H3</option>\
<option value="h4">H4</option>\
<option value="h5">H5</option>\
<option value="h6">H6</option>\
</select><br />\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-heading">Heading:</label></th>\
<td><input type="text" name="oscitas-iconhead-heading" id="oscitas-iconhead-heading" value="Heading"/><br />\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-class">Custom Class:</label></th>\
<td><input type="text" name="line" id="oscitas-iconhead-class" value=""/><br />\
</td>\
</tr>\
</table>\
<p class="submit">\
<input type="button" id="oscitas-iconhead-submit" class="button-primary" value="Insert Icon Heading" name="submit" />\
</p>\
</div>');
var table = form.find('table');
jQuery('.glyphicon').css('display','inline');
form.appendTo('body').hide();
form.find('.color').wpColorPicker();
table.find('#click_icon_list').click(function(){
if(!jQuery(this).hasClass('osc_icon_showing')){
jQuery(this).addClass('osc_icon_showing')
table.find('#osc_show_iconlist').show();
} else{
jQuery(this).removeClass('osc_icon_showing')
table.find('#osc_show_iconlist').hide();
}
});
table.find('.oscitas-heading-icon li').click(function(){
var val=jQuery(this).attr('data-value');
var type=jQuery(this).attr('type');
table.find('.oscitas-heading-icon li').removeClass('osc_icon_selected');
jQuery(this).addClass('osc_icon_selected');
table.find('#click_icon_list').removeClass('osc_icon_showing');
table.find('#osc_show_iconlist').hide();
table.find('#osc_show_icon').removeClass().addClass(type).addClass(val);
table.find('#oscitas-iconhead-icon').val(val);
table.find('#oscitas-iconhead-icontype').val(type);
});
// // handles the click event of the submit button
form.find('#oscitas-iconhead-submit').click(function() {
// defines the options and their default values
// again, this is not the most elegant way to do this
// but well, this gets the job done nonetheless
var type=jQuery('#oscitas-iconhead-headingtype').val();
var cusclass='',style='';
if(table.find('#oscitas-iconhead-icon').val()!=''){
style=' style="' + table.find('#oscitas-iconhead-icon').val()+'"' ;
}
if(table.find('#oscitas-iconhead-icontype').val()!=''){
style+=' icontype="' + table.find('#oscitas-iconhead-icontype').val()+'"' ;
}
if(table.find('#oscitas-iconhead-iconcolor').val()!=''){
cusclass+= ' color="'+table.find('#oscitas-iconhead-iconcolor').val()+'"';
}
if(table.find('#oscitas-iconhead-class').val()!=''){
cusclass+= ' class="'+table.find('#oscitas-iconhead-class').val()+'"';
}
var shortcode = '[iconheading type="'+type+'"';
shortcode += style+cusclass ;
shortcode += ']'+table.find('#oscitas-iconhead-heading').val()+'[/iconheading]' ;
// inserts the shortcode into the active editor
tinyMCE.activeEditor.execCommand('mceInsertContent',0 , shortcode);
// closes Dialoguebox
close_dialogue(pluginObj.hashId);
});
}
| wjmendez/easy-bootstrap-shortcodes | shortcode/iconhead/iconhead_plugin.js | JavaScript | gpl-2.0 | 5,742 |
$('#section').on('click', '[id$="Empty"]', function(event) {
event.preventDefault();
var match = /(.+)Empty/.exec($(event.target).closest('.unwell').attr('id'));
var id = match[1];
var emptyId = match[0];
$('#'+id).trigger('addrow');
$('#'+emptyId).addClass('hidden');
return false;
});
$('#section').on('submit', 'form[name="formItem"]', function(e) {
e.preventDefault();
var form = $(this),
btn = form.find('.btn-primary'),
valid = isFormValid(form);
$('select[name$=".type"]:not(:disabled)').each(function(i,e){
if($(e).val() == "Select an option"){
valid = false;
showPermanentError(form, "Please select a valid action.");
}
});
if (valid) {
btn.button('loading');
resetAlert($('#section'));
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize()
}).always(function() {
btn.button('reset');
}).done(function(data, textStatus, jqXHR) {
showSuccess(form, "Saved");
window.location.hash = "#config/portal_module/"+form.find('input[name="id"]').val()+"/read"
}).fail(function(jqXHR) {
$("body,html").animate({scrollTop:0}, 'fast');
var status_msg = getStatusMsg(jqXHR);
showPermanentError(form, status_msg);
});
}
});
$('#section').on('click', '.delete-portal-module', function(e){
e.preventDefault();
var button = $(e.target);
button.button('loading');
$.ajax({
type: 'GET',
url: button.attr('href'),
}).always(function() {
}).done(function(data, textStatus, jqXHR) {
showSuccess(button.closest('.table'), "Deleted");
button.closest('tr').remove();
}).fail(function(jqXHR) {
button.button('reset');
$("body,html").animate({scrollTop:0}, 'fast');
var status_msg = getStatusMsg(jqXHR);
showPermanentError(button.closest('.table'), status_msg);
});
return false;
});
$('#section').on('click', '.expand', function(e){
e.preventDefault();
$(e.target).hide(function(){
$($(e.target).attr('data-expand')).slideDown();
});
return false;
});
$('#section').on('change', '#actions select[name$=".type"]', function(event) {
var type_input = $(event.currentTarget);
updateActionMatchInput(type_input,false);
});
$('#section').on('click', '#actionsContainer a[href="#add"]', function(event) {
setTimeout(initActionMatchInput, 3000);
});
function initActionMatchInput() {
$('select[name$=".type"]:not(:disabled)').each(function(i,e){
updateActionMatchInput($(e),true);
});
}
function updateActionMatchInput(type_input, keep) {
var match_input = type_input.next();
var type_value = type_input.val();
var match_input_template_id = '#' + type_value + "_action_match";
var match_input_template = $(match_input_template_id);
if ( match_input_template.length == 0 ) {
match_input_template = $('#default_action_match');
}
if ( match_input_template.length ) {
changeInputFromTemplate(match_input, match_input_template, keep);
if (type_value == "switch") {
type_input.next().typeahead({
source: searchSwitchesGenerator($('#section h2')),
minLength: 2,
items: 11,
matcher: function(item) { return true; }
});
}
}
}
| jrouzierinverse/packetfence | html/pfappserver/root/static/admin/config/portal_modules.js | JavaScript | gpl-2.0 | 3,343 |
jQuery(function($){
$.supersized({
//Functionality
slideshow : 1, //Slideshow on/off
autoplay : 1, //Slideshow starts playing automatically
start_slide : 1, //Start slide (0 is random)
slide_interval : 4000, //Length between transitions
slideshow_interval : 4000, //Length between transitions
transition : 1, //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
transition_speed : 500, //Speed of transition
new_window : 1, //Image links open in new window/tab
pause_hover : 0, //Pause slideshow on hover
keyboard_nav : 1, //Keyboard navigation on/off
performance : 1, //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
image_protect : 1, //Disables image dragging and right click with Javascript
image_path : 'img/', //Default image path
//Size & Position
min_width : 0, //Min width allowed (in pixels)
min_height : 0, //Min height allowed (in pixels)
vertical_center : 1, //Vertically center background
horizontal_center : 1, //Horizontally center background
fit_portrait : 1, //Portrait images will not exceed browser height
fit_landscape : 0, //Landscape images will not exceed browser width
//Components
navigation : 1, //Slideshow controls on/off
thumbnail_navigation : 1, //Thumbnail navigation
slide_counter : 1, //Display slide numbers
slide_captions : 1, //Slide caption (Pull from "title" in slides array)
slides : (function(){
var ret = new Array();
for(var i in supersizedImgs){
ret.push({image: supersizedImgs[i]});
}
return ret;
})()
});
}); | infosecdev/markroxberry | wp-content/themes/widephoto/supersized/js/supersized.imgs.js | JavaScript | gpl-2.0 | 2,098 |
define(function () {
return {
customerAccount: ['CustomerAccountService', function (CustomerAccountService) {
return CustomerAccountService.getCurrent();
}]
};
});
| lordmarkm/tyrael-laundry | tyrael-laundry-dist/src/main/webapp/common/resolve/JobOrderListResolve.js | JavaScript | gpl-2.0 | 182 |
'use strict';
angular.module('sbAdminApp')
.controller('CustomerListCtrl', function ($scope, $http, $rootScope, $stateParams, $location) {
$scope.page = {itemsPerPage: 20};
$scope.iForm = {pageSize : $scope.page.itemsPerPage};
$scope.showLevel = true;
if ($stateParams.searchFounder == 1) {
$scope.searchFounder = true;
}
$scope.level = $stateParams.level;
if ($stateParams.page) {
$scope.iForm.page = parseInt($stateParams.page);
}
$http.get("/org/customer/level-enumeration")
.success(function (data) {
$scope.levels = data;
});
$http.get("/org/customer/status-enumeration")
.success(function (data) {
$scope.statuses = data;
});
$http({
url: "/org/team/all",
method: "GET"
})
.success(function (data) {
$scope.teams = data;
});
$http({
url: "/org/customer/list",
method: "GET",
params: $scope.iForm
})
.success(function (data) {
$scope.items = data.content;
$scope.page.totalItems = data.total;
$scope.page.currentPage = data.page + 1;
});
$scope.pageChanged = function() {
$scope.iForm.page = $scope.page.currentPage - 1;
$location.search($scope.iForm);
}
$scope.search = function () {
$scope.iForm.page = 0;
$location.search($scope.iForm);
}
}); | wangguodong577/qqj-backend | admin/src/main/webapp/app/org/customer-list.js | JavaScript | gpl-2.0 | 1,606 |
(function() {
tinymce.PluginManager.requireLangPack('kotofey_shortcodes');
tinymce.create('tinymce.plugins.kotofey_shortcodes', {
init : function(ed, url) {
ed.addCommand('mcekotofey_shortcodes', function() {
ed.windowManager.open({
file : url + '/interface.php',
width : 290 + ed.getLang('kotofey_shortcodes.delta_width', 0),
height : 150 + ed.getLang('kotofey_shortcodes.delta_height', 0),
inline : 1
}, {
plugin_url : url
});
});
ed.addButton('kotofey_shortcodes', {
title : 'Click to add a shortcode',
cmd : 'mcekotofey_shortcodes',
image : url + '/shortcode_button.png'
});
ed.onNodeChange.add(function(ed, cm, n) {
cm.setActive('kotofey_shortcodes', n.nodeName == 'IMG');
});
},
createControl : function(n, cm) {
return null;
},
getInfo : function() {
return {
longname : 'kotofey_shortcodes',
author : 'kotofey',
authorurl : 'http://themeforest.net/user/kotofey',
infourl : 'http://themeforest.net/user/kotofey',
version : "1.0"
};
}
});
tinymce.PluginManager.add('kotofey_shortcodes', tinymce.plugins.kotofey_shortcodes);
})();
| nizaranand/New-Life-Office | dev/wp-content/themes/teardrop/extends/wysiwyg/editor.js | JavaScript | gpl-2.0 | 1,181 |
const fs = require('fs');
const util = require('../../util');
// test equality
function equal(a, b, options) {
if (a === b) {
return options.fn(this);
}
return options.inverse(this);
}
// great than
function gt(a, b, options) {
if (a >= b) {
return options.fn(this);
}
return options.inverse(this);
}
// between
function between(a, b, c, options) {
if (a >= b && a <= c) {
return options.fn(this);
}
return options.inverse(this);
}
// less than
function lt(a, b, options) {
if (a < b) {
return options.fn(this);
}
return options.inverse(this);
}
function ignoreNan(val, symbol) {
const isNumber = (val >= 0 || val < 0);
return isNumber ? `${util.roundDecimal(val, 2)} ${symbol}` : '';
}
// test inequality
function inequal(a, b, options) {
if (a !== b) {
return options.fn(this);
}
return options.inverse(this);
}
// test File Exit
function fileExist(a, b, options) {
try {
fs.statSync(`${a}${b}`);
return options.fn(this);
} catch (err) {
return options.inverse(this);
}
}
exports.equal = equal;
exports.gt = gt;
exports.lt = lt;
exports.between = between;
exports.ignoreNan = ignoreNan;
exports.inequal = inequal;
exports.fileExist = fileExist;
| IMA-WorldHealth/bhima | server/lib/template/helpers/logic.js | JavaScript | gpl-2.0 | 1,228 |
Subsets and Splits