commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
e2ae9f87817c03cbb45f2b6fb36be4050e2df03a
|
add height fix for profile-info box when it > #page in height
|
mzalendo/core/static/js/desktop-functions.js
|
mzalendo/core/static/js/desktop-functions.js
|
// load all other jquery related resources
Modernizr.load(['//ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js','//ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css']);
// Show a tab and hide the others. Load content from remote source if needed.
function activateSimpleTab( $heading_element ) {
// Check that we have something to work with
if ( ! $heading_element.size() ) return false
var tab_content_id = $heading_element.attr('rel');
var $tab_content = $(tab_content_id);
// If this tab is already open don't open it again
if ( $tab_content.hasClass('open') )
return true;
// hide any currently active tabs
$('#tab-nav ul li.active').removeClass('active');
$('.tab.open').removeClass('open');
$('.tab').not('.open').hide();
// Show and activate the new tab
$heading_element.addClass('active');
$tab_content.addClass('open').show();
// load content using ajax if the div has an data-comment-source-url
// TODO: use a cleaner way to specify this - probably best to have a global object and tell it that certain tabs have special opening behaviour
var content_url = $tab_content.attr('data-comment-source-url')
if ( content_url ) {
$tab_content.load(content_url)
}
}
//generic re-usable hide or show with class states
//todo: add states to trigger elem if provided
function hideShow(elem, trig) {
elem.toggleClass(function() {
if ($(this).is('.open')) {
$(this).hide().removeClass('open');
trig.removeClass('active');
return 'closed';
} else {
$(this).show().removeClass('closed');
trig.addClass('active');
return 'open';
}
});
}
$(function(){
/*
* auto complete
*/
$('#main_search_box')
.autocomplete({
source: "/search/autocomplete/",
minLength: 2,
select: function(event, ui) {
if (ui.item) return window.location = ui.item.url;
}
});
/*
* enable dialog based feedback links
*/
$('a.feedback_link')
.on(
'click',
function(event) {
// Note - we could bail out here if the window is too small, as
// we'd be on a mobile and it might be better just to send them to
// the feedback page. Not done as this js should only be loaded on
// a desktop.
// don't follow the link to the feedback page.
event.preventDefault();
// create a div to use in the dialog
var dialog_div = $('<div>Loading...</div>');
// Load the initial content for the dialog
dialog_div.load( event.target.href + ' #ajax_dialog_subcontent' )
// Form subission should be done using ajax, and only the ajax_dialog_subcontent should be shown.
var handle_form_submission = function( form_submit_event ) {
form_submit_event.preventDefault();
var form = $(form_submit_event.target);
form.ajaxSubmit({
success: function( responseText ) {
dialog_div.html( $(responseText).find('#ajax_dialog_subcontent') );
}
});
};
// catch all form submissions and do them using ajax
dialog_div.on( 'submit', 'form', handle_form_submission );
// Show the dialog
dialog_div.dialog({modal: true});
}
);
/*
* simple tabs
*/
// build the nav from the relavent links dotted around
var $tabnavs = $('h2.tab-nav');
$tabnavs.hide();
$('.tab-wrapper').before('<div id="tab-nav"><ul></ul></div>');
$tabnavs.each(function(){
var rel = $(this).attr('rel');
var txt = $(this).text();
var href = $('a', this).attr('href');
var newElem = '<li rel="'+rel+'"><a href="'+href+'">'+txt+'</a></li>';
$('#tab-nav ul').append(newElem);
}).remove();
if(window.location.hash != '')
{
// get hash from url and activate it
var hash = window.location.hash;
$heading_element = $('li[rel='+hash+']');
activateSimpleTab($heading_element);
}
else
{
//make initial tab active and hide other tabs
if(!$('#tab-nav ul li').hasClass('active')){
var simpleTabActive = $('#tab-nav ul li:first-child').attr('rel');
$('#tab-nav ul li:first-child').addClass('active');
}else{
var simpleTabActive = $('#tab-nav ul li.active').attr('rel');
}
$(simpleTabActive).addClass('open');
$('.tab').not('.open').hide();
}
//for clicks
$("#tab-nav ul li a").click(function(e){
e.preventDefault();
window.location.hash = $(this).parent('li').attr('rel');
activateSimpleTab($(this).parent('li'));
});
$(".tab-static-link").click(function(e){
var hash = $(this).attr('rel');
window.location.hash = hash;
e.preventDefault();
activateSimpleTab($(this));
$("#tab-nav ul li[rel='"+hash+"']").addClass('active');
});
/*
* scorecard
*/
// prep
$('div.details').hide();
// hide/show details
$('ul.scorecard article').live('click', function(){
hideShow($('div.details', $(this)), $(this));
});
});
|
JavaScript
| 0 |
@@ -5322,11 +5322,256 @@
;%0A %7D);%0A
+%0A%0A /*%0A * Height fix for pages with .profile-info box%0A */%0A var pro_h = $('.profile-info').height()+210; //add 210 for the profile pic%0A var main_h = $('#page').height();%0A%0A if(pro_h %3E main_h)%7B%0A $('#page').css(%7B'min-height':pro_h%7D);%0A %7D%0A%0A
%7D);
|
d2e8efd9c92b6f5621b0bd35ef5368bda2d856f8
|
index j=4
|
flava/server.js
|
flava/server.js
|
/**
* Created by Wayne on 16/2/22.
*/
var config = require('./config/config');
var setup = require('./config/setup')();
var express = require('./config/express');
new express().listen(config.port);
console.log('process.env.NODE_ENV', process.env.NODE_ENV);
exports.index = function () {
}
exports.index1 = function () {
}
exports.index3 = function () {
}
exports.index4 = function () {
var j = 0;
}
exports.index5 = function () {
var j = 2;
}
|
JavaScript
| 0.999407 |
@@ -447,13 +447,13 @@
var j =
-2
+4
;%0A%7D%0A
|
2130557ca42bbb89ee4b26db1f39ee562703ed2d
|
re-write hold style links to new html5 style
|
app/assets/javascripts/angular/app.js
|
app/assets/javascripts/angular/app.js
|
angular.module("Prometheus.controllers", []);
angular.module("Prometheus.directives", []);
angular.module("Prometheus.resources", []);
angular.module("Prometheus.services", []);
angular.module("Prometheus.filters", []);
angular.module("Prometheus",
["ui.sortable", "ui.bootstrap", "ui.slider", "Prometheus.controllers", "Prometheus.directives", "Prometheus.resources", "Prometheus.services", "Prometheus.filters"])
.run(['$rootScope', function($rootScope) {
// adds some basic utilities to the $rootScope for debugging purposes
$rootScope.log = function(thing) {
console.log(thing);
};
$rootScope.alert = function(thing) {
alert(thing);
};
}]).config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true);
}]);
|
JavaScript
| 0.999665 |
@@ -430,16 +430,29 @@
tScope',
+ '$location',
functio
@@ -463,16 +463,27 @@
ootScope
+, $location
) %7B%0A //
@@ -678,16 +678,114 @@
g);%0A %7D;
+%0A%0A if ($location.hash()%5B0%5D === %22?%22) %7B%0A $location.url($location.path() + $location.hash());%0A %7D
%0A%7D%5D).con
|
9e11b949979529561e1a4d50ec43995983d1042e
|
Fix typo
|
simplyread.js
|
simplyread.js
|
/*
* SimplyRead - makes webpages more simplyread
*
* See COPYING file for copyright, license and warranty details.
*/
if(window.content && window.content.document.simplyread_original === undefined) window.content.document.simplyread_original = false;
function simplyread()
{
/* count the number of <p> tags that are direct children of parenttag */
function count_p(parenttag)
{
var n = 0;
var c = parenttag.childNodes;
for (var i = 0; i < c.length; i++) {
if (c[i].tagName == "p" || c[i].tagName == "P")
n++;
}
return n;
}
var doc;
if(document.body === undefined)
doc = window.content.document;
else
doc = document;
/* if simplyread_original is set, then the simplyread version is currently active,
* so switch to the simplyread_original html */
if (doc.simplyread_original) {
doc.body.innerHTML = doc.simplyread_original;
for (var i = 0; i < doc.styleSheets.length; i++)
doc.styleSheets[i].disabled = false;
doc.simplyread_original = false
return 0;
}
doc.simplyread_original = doc.body.innerHTML;
var biggest_num = 0;
var biggest_tag;
/* search for tag with most direct children <p> tags */
var t = doc.getElementsByTagName("*");
for (var i = 0; i < t.length; i++) {
var p_num = count_p(t[i]);
if (p_num > biggest_num) {
biggest_num = p_num;
biggest_tag = t[i];
}
}
if (biggest_num == 0) {
alert("Can't find any content");
return 1;
}
/* save and sanitise content of chosen tag */
var fresh = doc.createElement("div");
fresh.innerHTML = biggest_tag.innerHTML;
fresh.innerHTML = fresh.innerHTML.replace(/<\/?font[^>]*>/g, "");
fresh.innerHTML = fresh.innerHTML.replace(/style="[^"]*"/g, "");
fresh.innerHTML = fresh.innerHTML.replace(/<\/?a[^>]*>/g, "");
for (var i = 0; i < doc.styleSheets.length; i++)
doc.styleSheets[i].disabled = true;
doc.body.innerHTML =
"<div style=\"width:38em; margin:auto; text-align:justify; font-family:sans;\">" +
"<h1 style=\"text-align: center\">" + doc.title + "</h1>" +
fresh.innerHTML + "</div>";
return 0;
}
|
JavaScript
| 0.999999 |
@@ -32,26 +32,24 @@
es more
-simply
read
+able
%0A *%0A * S
|
c66f16d30acd4ded046741ae69cf804cbea20fd6
|
Add some specs for actionscript
|
spec/languages/actionscript-spec.js
|
spec/languages/actionscript-spec.js
|
"use babel"
import Parser from '../../lib/languages/actionscript'
describe('ParserActionScript', () => {
let parser;
beforeEach(() => {
waitsForPromise(() => atom.packages.activatePackage('docblockr'))
runs(() => {
parser = new Parser(atom.config.get('docblockr'))
})
})
describe('parse_function()', () => {
it('should be implemented', () => expect(false).toBe(true))
})
describe('parse_var()', () => {
it('should be implemented', () => expect(false).toBe(true))
})
describe('get_arg_name()', () => {
it('should be implemented', () => expect(false).toBe(true))
})
describe('get_arg_type()', () => {
it('should be implemented', () => expect(false).toBe(true))
})
})
|
JavaScript
| 0 |
@@ -324,32 +324,33 @@
ion()', () =%3E %7B%0A
+%0A
it('should b
@@ -352,159 +352,1056 @@
uld
-be implemented', () =%3E expect(false).toBe(true))%0A %7D)%0A%0A describe('parse_var()', () =%3E %7B%0A it('should be implemented', () =%3E expect(false).toBe(true)
+parse anonymous function', () =%3E %7B%0A const out = parser.parse_function('function (a:String)')%0A expect(out).toEqual(%5Bnull, 'a:String', null, %7B%7D %5D)%0A %7D)%0A%0A it('should parse function', () =%3E %7B%0A const out = parser.parse_function('name : function(a:String)')%0A%0A // expect(out).toEqual(%5B 'name', 'a:String', null, %7B%7D %5D)%0A expect(out).toEqual(%5B null, 'a:String', null, %7B%7D %5D)%0A %7D)%0A%0A it('should parse function', () =%3E %7B%0A const out = parser.parse_function('function name(a:String)')%0A%0A // expect(out).toEqual(%5B 'name', 'a:String', null, %7B%7D %5D)%0A expect(out).toEqual(%5B null, 'a:String', null, %7B%7D %5D)%0A %7D)%0A%0A it('should parse function', () =%3E %7B%0A const out = parser.parse_function('name = function(a:String)')%0A%0A // expect(out).toEqual(%5B 'name', 'a:String', null, %7B%7D %5D)%0A expect(out).toEqual(%5B null, 'a:String', null, %7B%7D %5D)%0A %7D)%0A %7D)%0A%0A describe('parse_var()', () =%3E %7B%0A it('should always return null', () =%3E %7B%0A const out = parser.parse_var('foo = %22Bar%22')%0A expect(out).toEqual(null)%0A %7D
)%0A
@@ -1437,32 +1437,33 @@
)', () =%3E %7B%0A
+x
it('should be im
@@ -1568,55 +1568,113 @@
uld
-be implemented', () =%3E expect(false).toBe(true)
+always return null', () =%3E %7B%0A const out = parser.parse_var('')%0A expect(out).toEqual(null)%0A %7D
)%0A
|
3add8cb634810bd562c4459619af1838b61f9181
|
Fix initialization bug.
|
src/link.js
|
src/link.js
|
import {map} from "d3-collection";
import constant from "./constant";
var tau = 2 * Math.PI;
function index(d, i) {
return i;
}
export default function(links) {
var id = index,
strength = constant(0.7),
strengths,
distance = constant(30),
distances,
nodes,
bias,
iterations = 1;
if (links == null) links = [];
function force(alpha) {
for (var k = 0, n = links.length; k < iterations; ++k) {
for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) {
link = links[i], source = link.source, target = link.target;
x = target.x + target.vx - source.x - source.vx;
y = target.y + target.vy - source.y - source.vy;
if (l = x * x + y * y) l = Math.sqrt(l), l = (l - distances[i]) / l;
else l = Math.random() * tau, x = Math.cos(l), y = Math.sin(l), l = distances[i];
l *= alpha * strengths[i], x *= l, y *= l;
target.vx -= x * (b = bias[i]);
target.vy -= y * b;
source.vx += x * (b = 1 - b);
source.vy += y * b;
}
}
}
function initialize() {
if (!nodes) return;
var i,
n = nodes.length,
m = links.length,
count = new Array(n),
nodeById = map(nodes, id),
link;
for (i = 0; i < n; ++i) {
count[i] = 0;
}
for (i = 0, bias = new Array(m); i < m; ++i) {
link = links[i], link.index = i;
if (typeof link.source !== "object") link.source = nodeById.get(link.source);
if (typeof link.target !== "object") link.target = nodeById.get(link.target);
++count[link.source.index], ++count[link.target.index];
}
for (i = 0; i < m; ++i) {
link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);
}
strengths = new Array(m), initializeStrength();
distances = new Array(m), initializeDistance();
}
function initializeStrength() {
for (var i = 0, n = links.length; i < n; ++i) {
strengths[i] = +strength(links[i]);
}
}
function initializeDistance() {
for (var i = 0, n = links.length; i < n; ++i) {
distances[i] = +distance(links[i]);
}
}
force.initialize = function(_) {
nodes = _;
initialize();
};
force.links = function(_) {
return arguments.length ? (links = _, initialize(), force) : links;
};
force.id = function(_) {
return arguments.length ? (id = _, force) : id;
};
force.iterations = function(_) {
return arguments.length ? (iterations = +_, force) : iterations;
};
force.strength = function(_) {
return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initializeStrength(), force) : strength;
};
force.distance = function(_) {
return arguments.length ? (distance = typeof _ === "function" ? _ : constant(+_), initializeDistance(), force) : distance;
};
return force;
}
|
JavaScript
| 0 |
@@ -1936,24 +1936,49 @@
trength() %7B%0A
+ if (!nodes) return;%0A%0A
for (var
@@ -2100,24 +2100,49 @@
istance() %7B%0A
+ if (!nodes) return;%0A%0A
for (var
|
8a464043e4a18e7f33ecd9ec5908c7457011fe59
|
update store.js
|
packages/ember-model/lib/store.js
|
packages/ember-model/lib/store.js
|
function NIL() {}
Ember.Model.Store = Ember.Object.extend({
container: null,
modelFor: function(type) {
return this.container.lookupFactory('model:'+type);
},
adapterFor: function(type) {
var adapter = this.modelFor(type).adapter,
container = this.container;
if (adapter && adapter !== Ember.Model.adapter) {
return adapter;
} else {
adapter = container.lookupFactory('adapter:'+ type) ||
container.lookupFactory('adapter:application') ||
container.lookupFactory('adapter:REST');
return adapter ? adapter.create() : adapter;
}
},
createRecord: function(type, props) {
var klass = this.modelFor(type);
klass.reopenClass({adapter: this.adapterFor(type)});
return klass.create(Ember.merge({container: this.container}, props));
},
find: function(type, id, subgraph) {
if (arguments.length === 1) { id = NIL; }
return this._find(type, id, subgraph, true);
},
_find: function(type, id, subgraph, async) {
var klass = this.modelFor(type);
// if (!klass.adapter) {
klass.reopenClass({adapter: this.adapterFor(type)});
// }
if (id === NIL) {
return klass._findFetchAll(subgraph, async, this.container);
} else if (Ember.isArray(id)) {
return klass._findFetchMany(id, subgraph, async, this.container);
} else if (typeof id === 'object') {
return klass._findFetchQuery(id, subgraph, async, this.container);
} else {
return klass._findFetchById(id, subgraph, async, this.container);
}
},
_findSync: function(type, id, subgraph) {
return this._find(type, id, subgraph, false);
}
});
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "store",
initialize: function(_, application) {
var store = application.Store || Ember.Model.Store;
application.register('store:application', store);
application.register('store:main', store);
application.inject('route', 'store', 'store:main');
application.inject('controller', 'store', 'store:main');
}
});
});
|
JavaScript
| 0.000002 |
@@ -109,24 +109,58 @@
%7B%0A return
+ Ember.Model.detect(type) ? type :
this.contai
@@ -329,16 +329,18 @@
(adapter
+/*
&& adap
@@ -358,32 +358,34 @@
er.Model.adapter
+*/
) %7B%0A return
@@ -1833,24 +1833,188 @@
lication) %7B%0A
+ // YPBUG: old initialization code used deprecated methods but appears to be%0A // the same as the 0.14 tag. Using the newer 0.16 initialization code here.%0A
var st
|
103b9adc57f4f7335d655a4366485d07798f0feb
|
fix createItem plugin method callbacks
|
www/UltravisualPlugin.js
|
www/UltravisualPlugin.js
|
var exec = require('cordova/exec');
var UltravisualPlugin = {
create: function (successCallback, errorCallback) {
UltravisualPlugin.tag = 0;
exec(successCallback, errorCallback, 'UltravisualPlugin', 'create', []);
},
createItem: function(label, details, image, options) {
var tag = UltravisualPlugin.tag++;
if (options && 'onSelect' in options && typeof(options['onSelect']) == 'function') {
UltravisualPlugin.callbacks[tag] = {'onSelect':options.onSelect,'name':name};
}
cordova.exec(successCallback,errorCallback, 'UltravisualPlugin', 'create', label, details, image, options);
},
onItemSelected : function(tag)
{
UltravisualPlugin.selectedItem = tag;
if (typeof(UltravisualPlugin.callbacks[tag].onSelect) == 'function')
UltravisualPlugin.callbacks[tag].onSelect(UltravisualPlugin.callbacks[tag].name);
}
};
module.exports = UltravisualPlugin;
|
JavaScript
| 0.000001 |
@@ -249,16 +249,48 @@
unction(
+successCallback, errorCallback,
label, d
|
a7ed48b7abed6916e45019c6e50806fb7e1b22dc
|
add trailing ./
|
packages/isomorphic-core/index.js
|
packages/isomorphic-core/index.js
|
module.exports = {
Provider: {
Gmail: 'gmail',
IMAP: 'imap',
},
Imap: require('imap'),
IMAPConnection: require('src/imap-connection'),
IMAPErrors: require('src/imap-errors'),
PromiseUtils: require('src/promise-utils'),
}
|
JavaScript
| 0.000001 |
@@ -113,32 +113,34 @@
ction: require('
+./
src/imap-connect
@@ -165,24 +165,26 @@
s: require('
+./
src/imap-err
@@ -215,16 +215,18 @@
equire('
+./
src/prom
|
5470e1e9bbd565960c5f41018bf0d5360879aea5
|
Remove reference to heartbeat as this has been removed from quickconnect prior to version 2
|
site/index.js
|
site/index.js
|
var quickconnect = require('rtc-quickconnect');
var captureConfig = require('rtc-captureconfig');
var media = require('rtc-media');
var crel = require('crel');
var qsa = require('fdom/qsa');
var tweak = require('fdom/classtweak');
var reRoomName = /^\/room\/(.*?)\/?$/;
var room = location.pathname.replace(reRoomName, '$1').replace('/', '');
// local & remote video areas
var local = qsa('.local')[0];
var remotes = qsa('.remote');
// get the message list DOM element
var messages = qsa('#messageList')[0];
var chat = qsa('#commandInput')[0];
// data channel & peers
var channel;
var peerMedia = {};
// use google's ice servers
var iceServers = [
{ url: 'stun:stun.l.google.com:19302' }
// { url: 'turn:192.158.29.39:3478?transport=udp',
// credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
// username: '28224511:1379330808'
// },
// { url: 'turn:192.158.29.39:3478?transport=tcp',
// credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
// username: '28224511:1379330808'
// }
];
// capture local media
var localMedia = media({
constraints: captureConfig('camera min:1280x720').toConstraints()
});
// render a remote video
function renderRemote(id, stream) {
var activeStreams;
// create the peer videos list
peerMedia[id] = peerMedia[id] || [];
activeStreams = Object.keys(peerMedia).filter(function(id) {
return peerMedia[id];
}).length;
console.log('current active stream count = ' + activeStreams);
peerMedia[id] = peerMedia[id].concat(media(stream).render(remotes[activeStreams % 2]));
}
function removeRemote(id) {
var elements = peerMedia[id] || [];
// remove old streams
console.log('peer ' + id + ' left, removing ' + elements.length + ' elements');
elements.forEach(function(el) {
el.parentNode.removeChild(el);
});
peerMedia[id] = undefined;
}
// render our local media to the target element
localMedia.render(local);
// once the local media is captured broadcast the media
localMedia.once('capture', function(stream) {
// handle the connection stuff
quickconnect(location.href + '../../', {
// debug: true,
room: room,
iceServers: iceServers,
disableHeartbeat: true
})
.broadcast(stream)
.createDataChannel('chat')
.on('stream:added', renderRemote)
.on('stream:removed', removeRemote)
.on('channel:opened:chat', function(id, dc) {
qsa('.chat').forEach(tweak('+open'));
dc.onmessage = function(evt) {
if (messages) {
messages.appendChild(crel('li', evt.data));
}
};
// save the channel reference
channel = dc;
console.log('dc open for peer: ' + id);
});
});
// handle chat messages being added
if (chat) {
chat.addEventListener('keydown', function(evt) {
if (evt.keyCode === 13) {
messages.appendChild(crel('li', { class: 'local-chat' }, chat.value));
chat.select();
if (channel) {
channel.send(chat.value);
}
}
});
}
|
JavaScript
| 0 |
@@ -2128,36 +2128,8 @@
vers
-,%0A disableHeartbeat: true
%0A %7D
|
ad91fde956df17a6ddac91df4f7e3c5b5ae24f9b
|
Revert to indexOf
|
Demo2.js
|
Demo2.js
|
'use strict';
import React from 'react';
import Springs from './Springs';
if (!String.prototype.includes) {
String.prototype.includes = function() {'use strict';
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
}
export default React.createClass({
getInitialState: function() {
return {
todos: {
// creation date => task name
1: 'Board the plane',
2: 'Sleep',
3: 'Try to finish coneference slides',
4: 'Eat cheese and drink wine',
5: 'Go around in Uber',
6: 'Talk with conf attendees',
7: 'Show Demo 1',
8: 'Show Demo 2',
9: 'Lament about the state of animation',
10: 'Show Secret Demo',
11: 'Go home',
},
value: '',
};
},
handleChange: function({target: {value}}) {
this.setState({value});
},
handleSubmit: function(e) {
e.preventDefault();
let {todos, value} = this.state;
this.setState({
todos: {
...todos,
[Date.now()]: value,
},
});
},
render: function() {
let {todos, value} = this.state;
return (
<Springs
className="demo2"
finalVals={(currVals, tween) => {
let configs = {};
Object.keys(todos)
.filter(date => {
return todos[date].toUpperCase().includes(value.toUpperCase());
})
.forEach(date => {
configs[date] = {height: 40, opacity: 1};
});
return tween(configs);
}}
// TODO: default: reached dest, v = 0
shouldRemove={(key, tween, destVals, currVals, currV) => {
return currVals[key].opacity === 0 && currV[key].opacity === 0 ?
null :
tween({height: 0, opacity: 0});
}}
// TODO: default: destVals[key]
// lifttable
missingCurrentKey={() => ({height: 0, opacity: 1})}>
{configs =>
<form onSubmit={this.handleSubmit}>
<input value={value} onChange={this.handleChange} />
{Object.keys(configs).map(date =>
<div key={date} className="demo2-todo" style={configs[date]}>
{todos[date]}
</div>
)}
</form>
}
</Springs>
);
}
});
|
JavaScript
| 0 |
@@ -73,173 +73,8 @@
';%0A%0A
-if (!String.prototype.includes) %7B%0A String.prototype.includes = function() %7B'use strict';%0A return String.prototype.indexOf.apply(this, arguments) !== -1;%0A %7D;%0A%7D%0A%0A
expo
@@ -1178,14 +1178,13 @@
).in
-cludes
+dexOf
(val
@@ -1200,16 +1200,21 @@
rCase())
+ %3E= 0
;%0A
|
9610e34f8df6dd55fffa1ef4eb390f310281f53f
|
make the test pass
|
MineField/minefield.js
|
MineField/minefield.js
|
"use strict";
var assert = require('assert');
describe('minefield', function() {
describe('grid', function() {
it('should be able to create a grid', function() {
var grid = new Grid(5,6);
assert.equal(grid.width, 5);
assert.equal(grid.height, 6);
});
});
});
|
JavaScript
| 0.000517 |
@@ -41,16 +41,91 @@
ert');%0A%0A
+var Grid = function(w,h) %7B%0A return %7B%0A width: w,%0A height: h%0A %7D;%0A%7D;%0A%0A
describe
|
f04a6e1416b8a7808df34cb7f23fbdeb971340a7
|
Add bootstrap js to pipeline
|
app/assets/javascripts/application.js
|
app/assets/javascripts/application.js
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
|
JavaScript
| 0 |
@@ -634,8 +634,38 @@
_tree .%0A
+//= require twitter/bootstrap%0A
|
aad8b82917c4c4fef167c4cf2717476e01894998
|
Use map
|
src/list.js
|
src/list.js
|
import Twitter from 'twit';
let T = new Twitter({
consumer_key: process.env.CONSUMER_KEY,
consumer_secret: process.env.CONSUMER_SECRET,
access_token: process.env.ACCESS_TOKEN,
access_token_secret: process.env.ACCESS_TOKEN_SECRET
});
let list_id = null;
//T.get('lists/list', {screen_name: 'akameco', reverse: true}, (err, data, response) => {
// if (err) {
// console.log(err);
// }
// for (let list of data) {
// if (list.name === '絵師') {
// list_id = list.id;
// }
// }
//});
list_id = 106243757;
T.get('lists/members', {list_id: list_id, count: 500}, (err, data, response) => {
console.log(data);
let user_ids = [];
for (let user of data.users) {
console.log(user.name);
console.log(user.id);
user_ids.push(user.id);
}
for (let id of user_ids) {
console.log(id);
}
console.log(user_ids.length);
let userStream = T.stream('statuses/filter', {follow: user_ids.join()});
userStream.on('tweet', (tweet) => {
console.log(tweet.text)
});
});
|
JavaScript
| 0.000003 |
@@ -260,15 +260,8 @@
t_id
- = null
;%0A%0A/
@@ -637,253 +637,87 @@
%3E %7B%0A
- console.log(data);%0A%0A let user_ids = %5B%5D;%0A%0A for (let user of data.users) %7B%0A console.log(user.name);%0A console.log(user.id);%0A user_ids.push(user.id);
+%0A let user_ids = data.users.map((user) =%3E %7B
%0A
-%7D%0A%0A
-for (let id of
+return
user
-_ids) %7B
+.id;
%0A
- console.log(id);%0A %7D
+%7D);%0A
%0A
@@ -885,16 +885,66 @@
ole.log(
+%60$%7Btweet.user.name%7D(@$%7Btweet.user.screen_name%7D) $%7B
tweet.te
@@ -945,17 +945,20 @@
eet.text
-)
+%7D%60);
%0A %7D);
|
40684be255b94a093ef0203c5d4677b6b9b16718
|
Convert numerical values to number type
|
parse.js
|
parse.js
|
"use strict";
/*
Straight-forward node.js arguments parser
Author: eveningkid
License: Apache-2.0
*/
function Parse (argv) {
// Removing node/bin and called script name
argv = argv.slice(2);
// Returned object
var args = {};
var argName, argValue;
// For each argument
argv.forEach(function (arg, index) {
// Seperate argument, for a key/value return
arg = arg.split('=');
// Retrieve the argument name
argName = arg[0];
// Remove "--" or "-"
if (argName.indexOf('-') === 0) {
argName = argName.slice(argName.slice(0, 2).lastIndexOf('-') + 1);
}
// Associate defined value or initialize it to "true" state
argValue = (arg.length === 2) ? arg[1] : true;
// Finally add the argument to the args set
args[argName] = argValue;
});
return args;
}
module.exports = Parse;
|
JavaScript
| 0.999999 |
@@ -444,20 +444,17 @@
%5D;%0A %0A
-
+%09
%09// Remo
@@ -578,17 +578,19 @@
1);%0A%09%09%7D%0A
+%09%09
%0A
-
%09%09// Ass
@@ -678,18 +678,122 @@
= 2)
-
+%0A%09%09%09? parseFloat(arg%5B1%5D).toString() === arg%5B1%5D // check if argument is valid number%0A%09%09%09%09
?
++
arg%5B1%5D
-
+%0A%09%09%09%09: arg%5B1%5D%0A%09%09%09
: tr
@@ -894,16 +894,16 @@
rgs;%0A%7D%0A%0A
-
module.e
@@ -917,8 +917,9 @@
= Parse;
+%0A
|
00f4ea03e7da716d81e990ec1476dd716a3f0102
|
add - default reporter to jslint, fix #14
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var watch = require('gulp-watch');
var rename = require('gulp-rename');
var notify = require('gulp-notify');
var util = require('gulp-util');
var jslint = require('gulp-jslint');
var uglify = require('gulp-uglify');
var stylus = require('gulp-stylus');
// var csslint = require('gulp-csslint');
var autoprefixer = require('gulp-autoprefixer');
var minifycss = require('gulp-minify-css');
function errorNotify(error){
notify.onError("Error: <%= error.message %>")
util.log(util.colors.red('Error'), error.message);
}
gulp.task('js', function() {
gulp.src([
'js/main.js',
'js/library.js'
])
.pipe(jslint({
reporter: function (evt) {
var msg = ' ' + evt.file;
if (evt.pass) {
msg = '[PASS]' + msg;
} else {
msg = '[FAIL]' + msg;
}
console.log(msg);
}
}))
.pipe(uglify())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('js'))
.pipe(notify({ message: 'Js task complete' }));
});
gulp.task('style', function() {
return gulp.src('css/site.styl')
.pipe(stylus())
.on('error', errorNotify)
.pipe(autoprefixer()
.on('error', errorNotify)
// .pipe(csslint())
.pipe(gulp.dest('css'))
.pipe(rename({suffix: '.min'}))
.pipe(minifycss())
.on('error', errorNotify)
.pipe(gulp.dest('css'))
.pipe(notify({ message: 'Style task complete' }));
});
gulp.task('watch', function() {
gulp.watch(['js/main.js'], ['js']);
gulp.watch(['css/site.styl'], ['style']);
});
gulp.task('default', ['watch']);
|
JavaScript
| 0 |
@@ -630,18 +630,16 @@
s'%0A %5D)%0A
-
.pipe(
@@ -649,242 +649,86 @@
int(
-%7B%0A reporter: function (evt) %7B%0A var msg = ' ' + evt.file;%0A if (evt.pass) %7B%0A msg = '%5BPASS%5D' + msg;%0A %7D else %7B%0A msg = '%5BFAIL%5D' + msg;%0A %7D%0A console.log(msg);%0A %7D%0A %7D)
+))%0A .on('error', function (error) %7B%0A console.error(String(error));%0A %7D
)%0A
-
.pip
@@ -735,26 +735,24 @@
e(uglify())%0A
-
.pipe(rena
@@ -771,26 +771,24 @@
'.min'%7D))%0A
-
.pipe(gulp.d
@@ -794,26 +794,24 @@
dest('js'))%0A
-
.pipe(noti
@@ -918,26 +918,24 @@
te.styl')%0A
-
.pipe(stylus
@@ -934,26 +934,24 @@
e(stylus())%0A
-
.on('error
@@ -964,26 +964,24 @@
orNotify)%0A
-
.pipe(autopr
@@ -988,21 +988,20 @@
efixer()
+)
%0A
-
-
.on('err
@@ -1018,16 +1018,18 @@
Notify)%0A
+
// .
@@ -1042,26 +1042,24 @@
sslint())%0A
-
.pipe(gulp.d
@@ -1062,34 +1062,32 @@
lp.dest('css'))%0A
-
.pipe(rename(%7B
@@ -1102,26 +1102,24 @@
'.min'%7D))%0A
-
.pipe(minify
@@ -1125,18 +1125,16 @@
ycss())%0A
-
.on('e
@@ -1151,26 +1151,24 @@
orNotify)%0A
-
.pipe(gulp.d
@@ -1179,18 +1179,16 @@
'css'))%0A
-
.pipe(
|
bef1c523a3e39e8e4d6b6c1fd60c450e07aa716e
|
improve namespaces example,
|
examples/namespaces.js
|
examples/namespaces.js
|
var visit = require('collection-visit');
var minimist = require('minimist');
var methods = require('..');
var app = {
data: {},
get: function (key) {
return app.data[key];
},
set: function (key, value) {
if (typeof key === 'object') {
visit(app, 'set', key);
} else {
app.data[key] = value;
}
return app;
}
};
var cli = require('minimist-plugins')(minimist)
.use(require('minimist-expand'))
.use(require('minimist-events'))
.use(methods(app))
.use(methods('one', app))
.use(methods('two', app))
cli.on('get', console.log.bind(console, '[get]'));
cli.one.on('set', console.log.bind(console, '[set]'));
cli.one.on('get', console.log.bind(console, '[get]'));
var args = process.argv.slice(2);
var argv = cli(args.length ? args : ['--one.set=a:b', '--one.set=c:d', '--get=a']);
console.log(argv);
|
JavaScript
| 0.000001 |
@@ -1,12 +1,108 @@
+var App = require('./app').App;%0Avar app = new App();%0Avar one = new App();%0Avar two = new App();%0A%0A
var visit =
@@ -200,255 +200,8 @@
);%0A%0A
-var app = %7B%0A data: %7B%7D,%0A get: function (key) %7B%0A return app.data%5Bkey%5D;%0A %7D,%0A set: function (key, value) %7B%0A if (typeof key === 'object') %7B%0A visit(app, 'set', key);%0A %7D else %7B%0A app.data%5Bkey%5D = value;%0A %7D%0A return app;%0A %7D%0A%7D;%0A%0A
var
@@ -357,19 +357,19 @@
('one',
-app
+one
))%0A .us
@@ -389,15 +389,21 @@
o',
-app
+two
))%0A%0A
+// set
%0Acli
@@ -403,25 +403,25 @@
set%0Acli.on('
-g
+s
et', console
@@ -433,33 +433,33 @@
bind(console, '%5B
-g
+s
et%5D'));%0Acli.one.
@@ -488,32 +488,36 @@
bind(console, '%5B
+one.
set%5D'));%0Acli.one
@@ -517,59 +517,297 @@
cli.
-one.on('get', console.log.bind(console, '%5Bget%5D'));%0A
+two.on('set', console.log.bind(console, '%5Btwo.set%5D'));%0A%0A// get%0Acli.on('get', console.log.bind(console, '%5Bget%5D'));%0Acli.one.on('get', console.log.bind(console, '%5Bone.get%5D'));%0Acli.two.on('get', console.log.bind(console, '%5Btwo.get%5D'));%0A%0Acli.on('end', function () %7B%0A console.log(app.cache)%0A%7D);
%0A%0Ava
@@ -875,16 +875,38 @@
args : %5B
+%0A '--set=w:x,y,z',%0A
'--one.s
@@ -915,41 +915,96 @@
=a:b
-',
+%7Cc:d%7Ce:f',%0A
'--
-one
+two
.set=
-c:d', '--get=a'
+g.h.i.j:k',%0A '--get=w',%0A '--one.get=a',%0A '--two.get=g',%0A
%5D);%0A
+%0A
cons
@@ -1018,8 +1018,62 @@
(argv);%0A
+console.log(app);%0Aconsole.log(one);%0Aconsole.log(two);%0A
|
f59f4fe0f78078395976e811308e93841ca8dbc9
|
Make cleverbot module behave like a typing human
|
src/modules/managed/cleverbotManager.js
|
src/modules/managed/cleverbotManager.js
|
/**
* Created by Julian/Wolke on 27.11.2016.
*/
let Manager = require('../../structures/manager');
let Cleverbot = require('cleverbot');
let re = /<@[0-9].*>/g;
let cleverbotKey = remConfig.cleverbot_api_key;
class CleverBotManager extends Manager {
constructor() {
super();
this.cleverbot = new Cleverbot({'key': cleverbotKey});
this.continuationStrings = {};
}
talk(msg) {
var message = msg.content.replace(re, '');
var continuationString = this.continuationStrings[msg.channel.id];
if (continuationString && continuationString.length > 2000) {
msg.channel.createMessage("I am having trouble remembering this conversation... Let's start over!");
this.continuationStrings[msg.channel.id] = undefined;
return;
}
this.cleverbot
.query(message, {'cs': continuationString})
.then(response => {
msg.channel.createMessage(':pencil: ' + response.output);
this.continuationStrings[msg.channel.id] = response.cs;
})
.catch(error => {
console.error(error);
return msg.channel.createMessage(':x: An error with cleverbot occured!');
});
}
}
module.exports = {class: CleverBotManager, deps: [], async: false, shortcode: 'cm'};
|
JavaScript
| 0.000019 |
@@ -947,63 +947,271 @@
-msg.channel.createMessage(':pencil: ' + response.output
+setTimeout(() =%3E %7B%0A msg.channel.sendTyping();%0A setTimeout(() =%3E %7B%0A msg.channel.createMessage(response.output);%0A %7D, response.output.length * 65);%0A %7D, message.length * 25
);%0A
|
692847a567b0155964a5bd0eb447020701a81452
|
allow user to provide external templates
|
lib/raml2html.js
|
lib/raml2html.js
|
#!/usr/bin/env node
var raml = require('raml-parser');
var handlebars = require('handlebars');
var marked = require('marked');
var template = require('./template.handlebars');
var resourceTemplate = require('./resource.handlebars');
function parseBaseUri(ramlObj) {
// I have no clue what kind of variables the RAML spec allows in the baseUri.
// For now keep it super super simple.
if (ramlObj.baseUri){
ramlObj.baseUri = ramlObj.baseUri.replace('{version}', ramlObj.version);
}
return ramlObj;
}
function makeUniqueId(resource) {
var fullUrl = resource.parentUrl + resource.relativeUri;
return fullUrl.replace(/[\{\}\/}]/g, '_');
}
function traverse(ramlObj, parentUrl, allUriParameters) {
var resource, index;
for (index in ramlObj.resources) {
resource = ramlObj.resources[index];
resource.parentUrl = parentUrl || '';
resource.uniqueId = makeUniqueId(resource);
resource.allUriParameters = [];
if (allUriParameters) {
resource.allUriParameters.push.apply(resource.allUriParameters, allUriParameters);
}
if (resource.uriParameters) {
var key;
for (key in resource.uriParameters) {
resource.allUriParameters.push(resource.uriParameters[key]);
}
}
traverse(resource, resource.parentUrl + resource.relativeUri, resource.allUriParameters);
}
return ramlObj;
}
function parse(source, onSuccess, onError) {
raml.loadFile(source).then(function(ramlObj) {
ramlObj = parseBaseUri(ramlObj);
ramlObj = traverse(ramlObj);
handlebars.registerHelper('md', function(text) {
if (text && text.length) {
return new handlebars.SafeString(marked(text));
} else {
return '';
}
});
handlebars.registerPartial('resource', resourceTemplate);
var result = template(ramlObj);
onSuccess(result);
}, onError);
}
if (require.main === module) {
var args = process.argv.slice(2);
if (args.length !== 1) {
console.error('You need to specify exactly one argument!');
process.exit(1);
}
// Start the parsing process
parse(args[0], function( result) {
// For now simply output to console
process.stdout.write(result);
process.exit(0);
}, function(error) {
console.log('Error parsing: ' + error);
process.exit(1);
});
}
module.exports.parse = parse;
|
JavaScript
| 0 |
@@ -1463,20 +1463,198 @@
ion
-parse(source
+markDownHelper(text) %7B%0A if (text && text.length) %7B%0A return new handlebars.SafeString(marked(text));%0A %7D else %7B%0A return '';%0A %7D%0A%7D%0A%0Afunction parseWithConfig(source, config
, on
@@ -1802,16 +1802,24 @@
mlObj);%0A
+
%0A
@@ -1823,180 +1823,174 @@
-handlebars.registerHelper('md', function(text) %7B%0A if (text && text.length) %7B%0A return new handlebars.SafeString(marked(text));%0A %7D else %7B
+//register handlebar helpers%0A for (var helperName in config.helpers) %7B%0A handlebars.registerHelper(helperName, config.helpers%5BhelperName%5D);%0A %7D
%0A
@@ -1994,24 +1994,25 @@
+%0A
return '
@@ -2007,111 +2007,182 @@
-return '';%0A %7D%0A %7D);%0A%0A handlebars.registerPartial('resource', resourceTemplate);
+//register handlebar partials%0A for (var partialName in config.partials) %7B%0A handlebars.registerPartial(partialName, config.partials%5BpartialName%5D);%0A %7D%0A
%0A
@@ -2199,16 +2199,23 @@
esult =
+config.
template
@@ -2275,16 +2275,339 @@
or);%0A%7D%0A%0A
+function parse( source, onSuccess, onError) %7B%0A %0A var config = %7B%0A 'template' : template,%0A 'helpers' : %7B %0A 'md' : markDownHelper%0A %7D,%0A 'partials' : %7B %0A 'resource' : resourceTemplate%0A %7D%0A %7D;%0A %0A parseWithConfig(source, config, onSuccess, onError);%0A%7D%0A%0A
if (requ
@@ -3114,9 +3114,58 @@
parse;%0A
+module.exports.parseWithConfig = parseWithConfig;
%0A
|
343e6f2061682338ae495164d2965006f0f42e0c
|
Add encode for global variable
|
lib/middleware/renderHTML.js
|
lib/middleware/renderHTML.js
|
/**
* @file Render html
* @author treelite([email protected])
*/
var extend = require('saber-lang').extend;
var config = require('../config');
var INDEX_FILE = 'index.html';
/**
* 模版编译
*
* @inner
* @param {Object=} options 配置项
* @param {string=} options.indexFile 首页模版
* @return {Function}
*/
function compile(options) {
options = options || {};
var fs = require('fs');
var content = fs.readFileSync(options.indexFile || INDEX_FILE, 'utf8');
// 插入同步数据的注入点
content = content.replace('</head>', '<script>window.__rebas__ = ${rebas}</script>\n</head>');
var etpl = require('etpl');
etpl = new etpl.Engine({defaultFilter: 'raw'});
return etpl.compile(content);
}
/**
* 生成页面渲染中间件
*
* @public
* @param {Object} options 配置参数
* @return {Function}
*/
module.exports = function (options) {
var render = compile(options);
return function (req, res, next) {
if (res.hasOwnProperty('html')) {
var data = extend({}, res.templateData, {content: res.html});
// 传输需要同步的数据
data.rebas = JSON.stringify(
// 合并全局的待同步数据
extend(
{},
config.syncData,
res.syncData,
{
model: res.data,
templateData: options.templateData || {}
}
)
);
// 附加全局的模版数据
data = extend({}, options.templateData, data);
// 渲染HTML页面
return res.send(render(data));
}
next();
};
};
|
JavaScript
| 0.000068 |
@@ -1413,16 +1413,148 @@
);%0A
+ // %E8%BD%AC%E4%B9%89%E5%8D%B1%E9%99%A9%E5%AD%97%E7%AC%A6%0A // %22 ' %5C %E5%B7%B2%E7%BB%8F%E8%A2%ABJSON.stringify %E5%A4%84%E7%90%86%E4%BA%86%EF%BC%8C%E8%BF%98%E5%89%A9%E4%B8%8B%E4%B8%80%E4%B8%AA /%0A data.rebas = data.rebas.replace(/%5C//g, '%5C%5C/');%0A
|
4ca3f440656140aa37ecf505cec5cb99ef781c5f
|
Use strict for gulpfile
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var fs = require('fs-extra');
gulp.task('clean', function (done) {
fs.remove(__dirname + '/build', done);
});
gulp.task('lint', function () {
var jshint = require('gulp-jshint');
return gulp.src(['index.js', 'test/*.js', 'gulpfile.js'])
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.reporter('fail'));
});
gulp.task('build', ['clean'], function () {
var webpack = require('gulp-webpack');
return gulp.src('')
.pipe(webpack({
target: 'node',
context: __dirname + '/test/',
entry: './test.js',
output: {
path: __dirname + '/build/',
filename: "test.js",
}
}))
.pipe(gulp.dest('build/'));
});
gulp.task('test', ['build'], function () {
var mocha = require('gulp-mocha');
require('should');
return gulp.src('build/*.js', { read: false })
.pipe(mocha());
});
gulp.task('default', ['lint', 'test']);
|
JavaScript
| 0.000001 |
@@ -1,12 +1,26 @@
+'use strict';%0A
var gulp = r
|
280820b09fe5652dd2ef8e4ac28c683f81c97e7d
|
fix sending presence for rooms and threads (#388)
|
src/modules/presence/presence-client.js
|
src/modules/presence/presence-client.js
|
/* @flow */
import { bus, cache } from '../../core-client';
import store from '../store/store';
import { setPresence, setItemPresence } from '../store/actions';
import { ROLE_VISITOR } from '../../lib/Constants';
import promisify from '../../lib/promisify';
const getEntityAsync = promisify(cache.getEntity.bind(cache));
async function getRelationAndSetPresence(slice: Object, status: 'online' | 'offline') {
let type;
if (slice.type === 'text') {
type = 'thread';
} else if (slice.type === 'thread') {
type = 'room';
} else {
return;
}
const user = cache.getState('user');
if (slice.filter && slice.filter.parents_cts) {
const item = slice.filter.parents_cts[0];
const result = await getEntityAsync(`${user}_${item}`);
global.requestIdleCallback(() => {
if (result) {
bus.emit('change', setItemPresence(result, type, status));
} else {
bus.emit('change', setItemPresence({
item,
user,
roles: [ ROLE_VISITOR ],
create: true,
}, type, status));
}
});
}
}
store.observe({ type: 'state', path: 'user', source: 'presence' }).forEach(id => {
if (id) {
bus.emit('change', setPresence(id, 'online'));
}
});
store.on('subscribe', options => {
if (options.slice) {
getRelationAndSetPresence(options.slice, 'online');
}
});
store.on('unsubscribe', options => {
if (options.slice) {
getRelationAndSetPresence(options.slice, 'offline');
}
});
|
JavaScript
| 0 |
@@ -317,16 +317,278 @@
che));%0A%0A
+function getItemFromFilter(filter) %7B%0A%09if (filter) %7B%0A%09%09if (filter.thread && filter.thread.parents_cts) %7B%0A%09%09%09return filter.thread.parents_cts%5B0%5D;%0A%09%09%7D else if (filter.text && filter.text.parents_cts) %7B%0A%09%09%09return filter.text.parents_cts%5B0%5D;%0A%09%09%7D%0A%09%7D%0A%0A%09return null;%0A%7D%0A%0A
async fu
@@ -850,30 +850,40 @@
');%0A
-%0A%09if (slice.f
+%09const item = getItemFromF
ilter
- &&
+(
slic
@@ -894,67 +894,24 @@
lter
-.parents_cts) %7B%0A%09%09const item = slice.filter.parents_cts%5B0%5D;
+);%0A%0A%09if (item) %7B
%0A%09%09c
|
3f2ca37dcb6a48fec4270560fb3e39a21edb4291
|
fix issue #19 : improve browser compatibility on scrollTop calculation + remove direct window and document reference (stricter mode)
|
ng-scrollto.js
|
ng-scrollto.js
|
// Version 0.0.5-fix
// AngularJS simple hash-tag scroll alternative
// this directive uses click event to scroll to the target element
//
// <div ng-app="app">
// <div ng-controller="myCtrl">
// <a scroll-to="section1">Section 1</a>
// </div>
// ...
// <div id="section1">
// <h2>Section1</h2>
// <a scroll-to="">Back to Top</a>
// </div>
// ...
// <div id="section1">
// <h2>Section1</h2>
// <a scroll-to="section1" offset="60">Section 1 with 60px offset</a>
// </div>
// </div>
angular.module('ngScrollTo', []);
angular.module('ngScrollTo')
.directive('scrollTo', ['ScrollTo', function(ScrollTo){
return {
restrict : "AC",
compile : function(){
return function(scope, element, attr) {
var handler = function (event) {
event.preventDefault();
ScrollTo.idOrName(attr.scrollTo, attr.offset);
};
element.bind("click", handler);
scope.$on('$destroy', function () {
element.unbind("click", handler);
});
};
}
};
}])
.service('ScrollTo', ['$window', 'ngScrollToOptions', function($window, ngScrollToOptions) {
this.idOrName = function (idOrName, offset, focus) {//find element with the given id or name and scroll to the first element it finds
var document = $window.document;
if(!idOrName) {//move to top if idOrName is not provided
$window.scrollTo(0, 0);
}
if(focus === undefined) { //set default action to focus element
focus = true;
}
//check if an element can be found with id attribute
var el = document.getElementById(idOrName);
if(!el) {//check if an element can be found with name attribute if there is no such id
el = document.getElementsByName(idOrName);
if(el && el.length)
el = el[0];
else
el = null;
}
if(el) { //if an element is found, scroll to the element
if (focus) {
el.focus();
}
ngScrollToOptions.handler(el, offset);
}
//otherwise, ignore
}
}])
.provider("ngScrollToOptions", function() {
this.options = {
handler : function(el, offset) {
if (offset) {
var top = el.getBoundingClientRect().top + el.ownerDocument.body.scrollTop - offset;
window.scrollTo(0, top);
}
else {
el.scrollIntoView();
}
}
};
this.$get = function() {
return this.options;
};
this.extend = function(options) {
this.options = angular.extend(this.options, options);
};
});
|
JavaScript
| 0 |
@@ -12,9 +12,9 @@
0.0.
-5
+6
-fix
@@ -2344,70 +2344,374 @@
var
-top = el.getBoundingClientRect().top + el.ownerDocument.body.s
+currentDocument = el.ownerDocument;%0A var currentWindow = currentDocument.defaultView %7C%7C currentDocument.parentWindow; // parentWindow is for IE8-%0A var currentScrollTop = currentWindow.pageYOffset %7C%7C currentDocument.documentElement.scrollTop %7C%7C currentDocument.body.scrollTop %7C%7C 0;%0A var scrollToY = el.getBoundingClientRect().top + currentS
crol
@@ -2725,16 +2725,17 @@
offset;%0A
+%0A
@@ -2736,17 +2736,24 @@
-w
+currentW
indow.sc
@@ -2762,19 +2762,25 @@
llTo(0,
-top
+scrollToY
);%0A
|
33428df7ad3fd4d8345970fe9f6a31bf49db133a
|
Fix to pass test on /authorized route looking for user_id
|
routes/authorization.js
|
routes/authorization.js
|
"use strict";
var db = require('../models');
var requestHelper = require('../lib/request-helper');
module.exports = function(app, options) {
app.post('/authorized', function(req, res) {
if (!requestHelper.isContentType(req, 'application/x-www-form-urlencoded')) {
res.json(400, { error: 'invalid_request' });
return;
}
var accessToken = req.body.token;
if (!accessToken) {
res.json(400, { error: 'invalid_request' });
return;
}
var serviceProviderId = req.body.service_provider_id;
if (!serviceProviderId) {
res.json(400, { error: 'invalid_request' });
return;
}
// TODO: do this in a single query?
db.ServiceProvider
.find({ where: { name: serviceProviderId } })
.complete(function(err, serviceProvider) {
if (err) {
res.send(500);
return;
}
if (!serviceProvider) {
res.send(401, { error: 'unauthorized' });
return;
}
var query = {
token: accessToken,
service_provider_id: serviceProvider.id
};
db.ServiceAccessToken
.find({ where: query })
.complete(function(err, accessToken) {
if (err) {
res.send(500);
return;
}
if (!accessToken) {
res.send(401, { error: 'unauthorized' });
return;
}
var query = {
id: accessToken.user_id
};
db.User
.find({ where: query })
.complete(function(err, user) {
if (err) {
res.send(500);
return;
}
var rsp = {
client_id: accessToken.client_id
};
if (user) {
rsp.user_id = user.id;
if (user.display_name) {
rsp.display_name = user.display_name;
}
if (user.photo) {
rsp.photo = user.photo;
}
}
res.json(rsp);
});
});
});
});
};
|
JavaScript
| 0 |
@@ -1736,18 +1736,27 @@
var r
+e
sp
+onseData
= %7B%0A
@@ -1802,16 +1802,17 @@
lient_id
+,
%0A
@@ -1824,39 +1824,38 @@
-%7D;%0A%0A if (
+ user_id: accessToken.
user
-) %7B
+_id
%0A
@@ -1871,35 +1871,12 @@
- rsp.user_id = user.id;%0A
+%7D;%0A%0A
@@ -1895,29 +1895,16 @@
if (user
-.display_name
) %7B%0A
@@ -1917,21 +1917,28 @@
- rsp
+responseData
.display
@@ -1986,69 +1986,20 @@
-%7D%0A if (user.photo) %7B%0A rsp
+responseData
.pho
@@ -2019,28 +2019,8 @@
to;%0A
- %7D%0A
@@ -2060,18 +2060,27 @@
s.json(r
+e
sp
+onseData
);%0A
|
c77e4adf1e2d66c2b9665f03fa485f37c239c6f3
|
Use local name instead of title in filepicker if it exists
|
www/filepicker/inner.js
|
www/filepicker/inner.js
|
define([
'jquery',
'/bower_components/chainpad-crypto/crypto.js',
'/bower_components/nthen/index.js',
'/common/sframe-common.js',
'/common/common-interface.js',
'/common/common-ui-elements.js',
'/common/common-util.js',
'/common/common-hash.js',
'json.sortify',
'/customize/messages.js',
'css!/bower_components/bootstrap/dist/css/bootstrap.min.css',
'less!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/customize/src/less2/main.less',
], function (
$,
Crypto,
nThen,
SFCommon,
UI,
UIElements,
Util,
Hash,
Sortify,
Messages)
{
var APP = window.APP = {};
var andThen = function (common) {
var metadataMgr = common.getMetadataMgr();
var $body = $('body');
var sframeChan = common.getSframeChannel();
var filters = metadataMgr.getPrivateData().types;
var hideFileDialog = function () {
sframeChan.event('EV_FILE_PICKER_CLOSE');
};
var onFilePicked = function (data) {
var parsed = Hash.parsePadUrl(data.url);
hideFileDialog();
if (parsed.type === 'file') {
var hexFileName = Util.base64ToHex(parsed.hashData.channel);
var src = '/blob/' + hexFileName.slice(0,2) + '/' + hexFileName;
sframeChan.event("EV_FILE_PICKED", {
type: parsed.type,
src: src,
name: data.name,
key: parsed.hashData.key
});
return;
}
sframeChan.event("EV_FILE_PICKED", {
type: parsed.type,
href: data.url,
name: data.name
});
};
// File uploader
var fmConfig = {
body: $('body'),
noHandlers: true,
onUploaded: function (ev, data) {
onFilePicked(data);
}
};
APP.FM = common.createFileManager(fmConfig);
// Create file picker
var onSelect = function (url, name) {
onFilePicked({url: url, name: name});
};
var data = {
FM: APP.FM
};
var updateContainer;
var createFileDialog = function () {
var types = filters.types || [];
// Create modal
var $blockContainer = UIElements.createModal({
id: 'cp-filepicker-dialog',
$body: $body,
onClose: hideFileDialog
}).show();
// Set the fixed content
var $block = $blockContainer.find('.cp-modal');
// Description
var text = Messages.filePicker_description;
if (types && types.length === 1 && types[0] !== 'file') {
// Should be Templates
text = Messages.selectTemplate;
}
var $description = $('<p>').text(text);
$block.append($description);
var $filter = $('<p>', {'class': 'cp-modal-form'}).appendTo($block);
var to;
$('<input>', {
type: 'text',
'class': 'cp-filepicker-filter',
'placeholder': Messages.filePicker_filter
}).appendTo($filter).on('keypress', function () {
if (to) { window.clearTimeout(to); }
to = window.setTimeout(updateContainer, 300);
});
//If file, display the upload button
if (types.indexOf('file') !== -1 && common.isLoggedIn()) {
$filter.append(common.createButton('upload', false, data));
}
var $container = $('<span>', {'class': 'cp-filepicker-content'}).appendTo($block);
// Update the files list when needed
updateContainer = function () {
$container.html('');
var $input = $filter.find('.cp-filepicker-filter');
var filter = $input.val().trim();
var todo = function (err, list) {
if (err) { return void console.error(err); }
Object.keys(list).forEach(function (id) {
var data = list[id];
var name = data.title || '?';
if (filter && name.toLowerCase().indexOf(filter.toLowerCase()) === -1) {
return;
}
var $span = $('<span>', {
'class': 'cp-filepicker-content-element',
'title': name,
}).appendTo($container);
$span.append(UI.getFileIcon(data));
$('<span>', {'class': 'cp-filepicker-content-element-name'}).text(name)
.appendTo($span);
$span.click(function () {
if (typeof onSelect === "function") { onSelect(data.href, name); }
});
// Add thumbnail if it exists
common.displayThumbnail(data.href, $span);
});
$input.focus();
};
common.getFilesList(filters, todo);
};
updateContainer();
};
sframeChan.on('EV_FILE_PICKER_REFRESH', function (newFilters) {
if (Sortify(filters) !== Sortify(newFilters)) {
$body.html('');
filters = newFilters;
return void createFileDialog();
}
updateContainer();
});
createFileDialog();
UI.removeLoadingScreen();
};
var main = function () {
var common;
nThen(function (waitFor) {
$(waitFor(function () {
UI.addLoadingScreen({hideTips: true, hideLogo: true});
}));
SFCommon.create(waitFor(function (c) { APP.common = common = c; }));
}).nThen(function (/*waitFor*/) {
var metadataMgr = common.getMetadataMgr();
if (metadataMgr.getMetadataLazy() !== 'uninitialized') {
andThen(common);
return;
}
metadataMgr.onChange(function () {
andThen(common);
});
});
};
main();
});
|
JavaScript
| 0.000001 |
@@ -4299,16 +4299,33 @@
r name =
+ data.filename %7C%7C
data.ti
|
32543f79defd1ded321fe5bb205f476d4b227ef6
|
Change database structure
|
www/js/databaseHelper.js
|
www/js/databaseHelper.js
|
/**
* Group a series of functions to interact with PhoneGap built-in database.
*
* @author Lucio Romerio ([email protected])
*/
/**
* Global instance that represent the database itself.
*
* @type {Database}
*/
var db = window.openDatabase("cothority_database", "1.0", "cothority_database", 1000000);
/**
* Given a database error print an error message to the console.
*
* @param e
*/
function dbErrorHandler(e) {
console.log('Database error: ' + e.code + ' ' + e.message);
}
/**
* Open the database, once the db is ready the handler passed as parameter will be triggered.
*
* @param handler
*/
function dbOpen(handler) {
db.transaction(dbSetup, dbErrorHandler, handler);
}
/**
* Create tables if they don't exist yet. Ideally, in a given device, they will be created
* only the very first time the application is launched.
*
* @param tx
*/
function dbSetup(tx) {
var conodes = "create table if not exists conodes(id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"address TEXT, serverId TEXT, deviceId TEXT, keyPair TEXT)";
tx.executeSql(conodes);
var ssh = "create table if not exists ssh(id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"serverAddr TEXT, sshName TEXT, sshKeyPair TEXT)";
tx.executeSql(ssh);
}
/**
* Perform the sql query contained in 'sql' with 'arg' as parameters.
* Once the query is completed the given handler is trigger.
*
* @param sql
* @param arg
* @param handler
*/
function dbAction(sql, arg, handler) {
db.transaction(function (tx) {
tx.executeSql(sql, arg, function (tx, result) {
handler(result);
}, dbErrorHandler);
}, dbErrorHandler, function () {});
}
|
JavaScript
| 0.000001 |
@@ -957,44 +957,32 @@
des(
-id INTEGER PRIMARY KEY AUTOINCREMENT
+address TEXT PRIMARY KEY
, %22
@@ -996,22 +996,8 @@
%22
-address TEXT,
serv
@@ -1030,32 +1030,33 @@
keyPair TEXT)%22;%0A
+%0A
tx.executeSq
@@ -1118,59 +1118,8 @@
ssh(
-id INTEGER PRIMARY KEY AUTOINCREMENT, %22 +%0A %22
serv
@@ -1145,16 +1145,29 @@
e TEXT,
+%22 +%0A %22
sshKeyPa
@@ -1169,24 +1169,58 @@
KeyPair TEXT
+, PRIMARY KEY(serverAddr, sshName)
)%22;%0A tx.e
|
aa473aefae0d07f04d282c60bd593de0d9d23900
|
Add library(jquery.ui.effect.all) to app/assets/javascripts/application.js #65
|
app/assets/javascripts/application.js
|
app/assets/javascripts/application.js
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery.ui.core.js
//= require jquery.ui.widget.js
//= require jquery.ui.mouse.js
//= require jquery.ui.sortable.js
//= require jquery.ui.draggable.js
//= require jquery.ui.droppable.js
//= require_tree .
//= require twitter/bootstrap
function getCSRFtoken(){
return $("meta[name=csrf-token]").attr("content");
}
|
JavaScript
| 0.000001 |
@@ -804,32 +804,65 @@
ui.droppable.js%0A
+//= require jquery.ui.effect.all%0A
//= require_tree
|
72c233dc73cd0a4ea32ef98d7236ecd1a969eb48
|
use switch statement
|
js/lib/document_builder/Psalmody.js
|
js/lib/document_builder/Psalmody.js
|
var CopticCalendar = require('../CopticCalendar.js');
var CopticDateComparator = CopticCalendar.CopticDateComparator;
var moment = require('moment');
var Psalmody = {
MorningPraises: function (attributes) {
var docs = [];
docs.push("hymns/psalmody/morning_praises");
docs.push("hymns/psalmody/concl_adam_theotokia");
return docs;
},
VesperPraises: function (attributes) {
var day = attributes.todayDate.day();
var day_tune = CopticCalendar.AdamOrWatos(attributes.year, attributes.monthIndex, attributes.day);
var docs = [];
docs.push("hymns/psalmody/intro_psalm_116");
docs.push("hymns/psalmody/fourth_canticle");
if (day == 0) {
docs.push("hymns/psalmody/psali/standard_sunday");
}
if (day == 1) {
docs.push("hymns/psalmody/psali/standard_monday");
}
if (day == 2) {
docs.push("hymns/psalmody/psali/standard_tuesday");
}
if (day == 3) {
docs.push("hymns/psalmody/psali/standard_wednesday");
}
if (day == 4) {
docs.push("hymns/psalmody/psali/standard_thursday");
}
if (day == 5) {
docs.push("hymns/psalmody/psali/standard_friday");
}
if (day == 6) {
docs.push("hymns/psalmody/psali/standard_saturday");
}
if (day_tune == "adam") {
docs.push("hymns/psalmody/concl_psali_adam");
} else {
docs.push("hymns/psalmody/concl_psali_watos");
}
if (day_tune == "adam") {
docs.push("hymns/psalmody/concl_adam_theotokia");
} else {
docs.push("hymns/psalmody/concl_watos_theotokia");
}
docs.push("prayers/our_father");
return docs;
},
MidnightPraises: function (attributes) {
var docs = [];
return docs;
}
}
module.exports = Psalmody;
|
JavaScript
| 0.000003 |
@@ -706,23 +706,42 @@
-if (day == 0) %7B
+switch (day) %7B%0A case 0:
%0A
@@ -812,34 +812,38 @@
-%7D %0A if (day == 1) %7B
+ break;%0A case 1:
%0A
@@ -914,34 +914,38 @@
-%7D %0A if (day == 2) %7B
+ break;%0A case 2:
%0A
@@ -1017,34 +1017,38 @@
-%7D %0A if (day == 3) %7B
+ break;%0A case 3:
%0A
@@ -1122,34 +1122,38 @@
-%7D %0A if (day == 4) %7B
+ break;%0A case 4:
%0A
@@ -1226,34 +1226,38 @@
-%7D %0A if (day == 5) %7B
+ break;%0A case 5:
%0A
@@ -1328,34 +1328,38 @@
-%7D %0A if (day == 6) %7B
+ break;%0A case 6:
%0A
@@ -1428,18 +1428,36 @@
-%7D
+ break;%0A %7D
%0A
@@ -1537,24 +1537,86 @@
ali_adam%22);%0A
+ docs.push(%22hymns/psalmody/concl_adam_theotokia%22);%0A
%7D el
@@ -1683,132 +1683,8 @@
%22);%0A
- %7D%0A%0A if (day_tune == %22adam%22) %7B%0A docs.push(%22hymns/psalmody/concl_adam_theotokia%22);%0A %7D else %7B%0A
@@ -1744,32 +1744,33 @@
ia%22);%0A %7D%0A
+%0A
docs.pus
|
cedfc743d900082a4255edfd6b7dc9b325b5a2b3
|
throw err if ssh connect fails in ws:start task
|
gulpfile.js
|
gulpfile.js
|
require('dotenv').config({silent: true});
const _ = require('underscore-plus');
const gulp = require('gulp');
const gutil = require('gulp-util');
const shell = require('shelljs');
const Client = require('ssh2').Client;
const fs = require('fs');
const os = require('os');
const path = require('path');
gulp.task('default', ['ws:start']);
gulp.task('setup', function() {
shell.cp('./.env.example', './.env');
});
gulp.task('clone', function() {
log('Cloning down all Learn IDE repositories...');
var repos = [
'flatiron-labs/students-chef-repo',
'flatiron-labs/go_terminal_server',
'flatiron-labs/fs_server',
'flatiron-labs/learn-ide-mac-packager',
'flatiron-labs/learn-ide-windows-packager',
'learn-co/tree-view',
'flatiron-labs/atom-ile'
];
_.map(repos, function(repo) {
var name = _.last(repo.split('/'));
var cmd = 'git clone [email protected]:' + repo + '.git --progress ../' + name;
exec(cmd, {name: name, async: true});
})
});
gulp.task('ws:start', function(done) {
var conn = new Client();
var host = process.env.IDE_WS_HOST || 'vm02.students.learn.co';
var port = process.env.IDE_WS_PORT || 1337;
var cmd = 'sudo su -c \"websocketd --port=' + port + ' --dir=/home/deployer/websocketd_scripts\" deployer\n'
log('Connecting to ' + host + ' on port ' + port);
conn.on('ready', function() {
log('SSH client ready...');
log('Executing ' + gutil.colors.yellow(cmd.replace('\n', '')) + ' on ' + gutil.colors.magenta(host));
conn.exec(cmd, function(err, stream) {
if (err) { throw err; }
var pids = [];
var pidsStr = '';
conn.exec('ps aux | grep \"websocketd --port=' + port + '\" | grep -v grep | awk \'{print $2}\'', function(err, stream) {
stream.on('data', function(data) {
pids = _.compact(data.toString().split('\n'))
pidsStr = pids.join(' ')
log('WebsocketD processes started with pids: ' + pidsStr);
});
})
process.on('SIGINT', function() {
log('Killing websocket processes ' + pidsStr);
conn.exec('sudo kill ' + pidsStr, function(err, stream) {
stream.on('close', function() {
process.exit(0);
});
});
});
stream.on('close', function(code) {
gutil.log('SSH stream closed with code ' + code);
conn.end();
}).on('data', function(data) {
process.stdout.write('[' + gutil.colors.magenta(host) + '] ' + gutil.colors.blue(data));
}).stderr.on('data', function(data) {
process.stderr.write('[' + gutil.colors.magenta(host) + '] ' + gutil.colors.red(data));
});
})
}).connect({
host: host,
username: process.env['USER'],
agent: process.env.SSH_AUTH_SOCK
});
});
function log (msg) {
gutil.log(gutil.colors.green(msg));
}
function exec (cmd, opts, cb) {
opts || (opts = {});
_.defaults(opts, {
name: cmd,
async: false
});
gutil.log(gutil.colors.green('Executing ') + gutil.colors.yellow(cmd));
var child = shell.exec(cmd, {async: opts.async}, cb);
if (opts.async) {
child.stdout.on('data', function(data) {
process.stdout.write(gutil.colors.green(opts.name + ': ') + data);
});
child.stderr.on('data', function(data) {
process.stderr.write(gutil.colors.green(opts.name + ': ') + data);
});
}
}
|
JavaScript
| 0.000005 |
@@ -1734,32 +1734,63 @@
(err, stream) %7B%0A
+ if (err) %7B throw err %7D%0A
stream.o
|
044e26a180a0879aedd97e719c77148efdfe9063
|
remove debugging
|
goodreads-ssrm.js
|
goodreads-ssrm.js
|
// goodreads SSRM (server-side rendering middleware)
'use strict';
var wait = require('wait.for');
var fs = require('fs');
var jsdom = require('jsdom');
var jsDomGet = function(appFilename, url, callback) {
jsdom.env({
file: appFilename,
windowLocation: url,
features: {
QuerySelector: true
},
created: function(errors, window) {
// angular needs this but jsdom doesn't provide it
window.scrollTo = function() {};
window.history.pushState(null, null, url);
},
done: function(errors, window) {
console.log(errors);
window.document.body.setAttribute('data-prerendered', 'true');
callback(errors, window);
}
});
};
var renderFileUsingJsDom = function(appFilename, url) {
var start = Date.now();
var window = wait.for(jsDomGet, appFilename, url);
var end = Date.now();
console.log('[GRSSRM] jsdom took: ' + (end - start) + 'ms');
return window.document.querySelector('html').innerHTML;
};
var serverSideRender = function(appFilename, req, res) {
try {
var doc = renderFileUsingJsDom(appFilename, req.url);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(doc);
res.end();
} catch (err) {
console.error(err);
res.end('<html><head><title>:-(</title></head><body><img src="http://tailf.blob.core.windows.net/cats/500.jpg"/></body></html>');
}
};
var isAngularRequest = function(url) {
return url.match(/\./) === null;
}
var middlewareFactory = function(appFilename, options) {
if (options !== undefined && options.skipSsr === true) {
return function(req, res, next) {
if (isAngularRequest(req.url)) {
console.log('[GR-SSRM] skipped SSR. just sending ' + appFilename);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(fs.readFileSync(appFilename));
res.end();
} else {
next();
}
}
}
return function(req, res, next) {
if (isAngularRequest(req.url)) {
console.log('[GR-SSRM] server-side rendering ng-app ' + appFilename + ' with route ' + req.url);
wait.launchFiber(serverSideRender, appFilename, req, res);
} else {
next();
}
};
};
module.exports = {
middlewareFor: middlewareFactory
};
|
JavaScript
| 0.000065 |
@@ -503,180 +503,8 @@
l);%0A
- %7D,%0A done: function(errors, window) %7B%0A console.log(errors);%0A window.document.body.setAttribute('data-prerendered', 'true');%0A callback(errors, window);%0A
|
d6f1372a07a19acc7d2f4bbf480aeb4f24a6c8da
|
Fix cover fetch when it has single or doublequotes in its path
|
src/js/components/Shared/Cover.react.js
|
src/js/components/Shared/Cover.react.js
|
import React, { PureComponent } from 'react';
import utils from '../../utils/utils';
/*
|--------------------------------------------------------------------------
| Header - PlayingBar
|--------------------------------------------------------------------------
*/
export default class TrackCover extends PureComponent {
static propTypes = {
path: React.PropTypes.string,
}
constructor(props) {
super(props);
this.state = {
coverPath: null,
};
this.fetchInitialCover = this.fetchInitialCover.bind(this);
}
render() {
if(this.state.coverPath) {
const styles = { backgroundImage: `url('${this.state.coverPath}')` };
return <div className='cover' style={ styles } />;
}
return(
<div className='cover empty'>
<div className='note'>♪</div>
</div>
);
}
componentDidMount() {
this.fetchInitialCover();
}
async componentWillUpdate(nextProps) {
if(nextProps.path !== this.props.path) {
const coverPath = await utils.fetchCover(nextProps.path);
this.setState({ coverPath });
}
}
async fetchInitialCover() {
const coverPath = await utils.fetchCover(this.props.path);
this.setState({ coverPath });
}
}
|
JavaScript
| 0 |
@@ -622,24 +622,164 @@
overPath) %7B%0A
+ const coverPath = encodeURI(this.state.coverPath)%0A .replace(/'/g, '%5C%5C%5C'')%0A .replace(/%22/g, '%5C%5C%22');%0A
@@ -820,27 +820,16 @@
%60url('$%7B
-this.state.
coverPat
|
4be06b3a36b8cfc31c5d57802f465b0c16adf12a
|
Fix coffeescript output
|
lib/plugins/coffee-script.js
|
lib/plugins/coffee-script.js
|
var CoffeeScript = require('coffee-script'),
path = require('path'),
fu = require('../fileUtil');
module.exports = {
mode: 'scripts',
priority: 50,
resource: function(context, next, complete) {
var resource = context.resource;
if (/\.coffee$/.test(resource.src)) {
next(function(err, coffeeScriptSrc) {
if (err) {
return complete(err);
}
complete(undefined, CoffeeScript.compile(coffeeScriptSrc.toString()));
});
} else {
next(complete);
}
}
};
|
JavaScript
| 0.99994 |
@@ -277,24 +277,25 @@
rce.src)) %7B%0A
+%0A
next(f
@@ -311,27 +311,169 @@
rr,
-coffeeScriptSrc) %7B%0A
+resource) %7B%0A function generator(context, callback) %7B%0A // Load the source data%0A context.loadResource(resource, function(err, file) %7B%0A
@@ -497,16 +497,20 @@
+
+
return c
@@ -531,17 +531,22 @@
-%7D
+ %7D%0A
%0A
@@ -550,76 +550,408 @@
-complete(undefined, CoffeeScript.compile(coffeeScriptSrc.toString())
+ // Update the content%0A callback(err, %7B%0A data: CoffeeScript.compile(file.content.toString()),%0A inputs: file.inputs%0A %7D);%0A %7D);%0A %7D%0A%0A // Include any attributes that may have been defined on the base entry%0A if (!_.isString(resource)) %7B%0A _.extend(generator, resource);%0A %7D%0A complete(undefined, generator
);%0A
|
ea98cda60ec1182e4446f393fae86ce26013cbed
|
remove tick draw from signal array
|
packages/element/input-signal-array/index.js
|
packages/element/input-signal-array/index.js
|
import ArrayViewerElement from '../element-viewer-array/index.js';
import Ticker from '../core/util/Ticker.js';
export default class ArraySignalInputElement extends ArrayViewerElement {
static get observedAttributes() {
return [...ArrayViewerElement.observedAttributes, 'position', 'length'];
}
constructor() {
super();
this._length = 1;
this._position = 0;
this._previousValue = undefined;
this.array = new Float32Array(100);
const resizeObserver = new ResizeObserver((entries) => {
this._width = entries[0].contentRect.width;
this._height = entries[0].contentRect.height;
});
resizeObserver.observe(this);
let previousPosition = null;
let pointerOffsetX = 0;
let pointerOffsetY = 0;
this._snap = false;
const keySet = new Set();
window.addEventListener('keydown', (event) => {
if (keySet.has(event.key)) {
return;
}
keySet.add(event.key);
switch (event.key) {
case 'Shift':
previousPosition = null;
this._snap = true;
break;
case 'Control':
this.controls = true;
break;
}
});
window.addEventListener('keyup', (event) => {
switch (event.key) {
case 'Shift':
previousPosition = null;
this._snap = false;
break;
case 'Control':
this.controls = false;
break;
}
keySet.delete(event.key);
});
const setValuesFromPosition = () => {
let value = (1 - pointerOffsetY / this._height) * (this.max - this.min) + (this.min || 0);
value = Math.max(Math.min(this.max, value), this.min);
const newPosition = this._snap ? this.position : ((pointerOffsetX + this.scrollLeft) / this.scrollWidth) * this.length;
previousPosition = previousPosition !== null ? previousPosition : newPosition;
const startPosition = newPosition > previousPosition ? previousPosition : newPosition;
const endPosition = newPosition > previousPosition ? newPosition : previousPosition;
const startIndex = this._getIndexFromPosition(startPosition);
const endIndex = this._getIndexFromPosition(endPosition);
for (let index = startIndex; index <= endIndex; index++) {
this.array[index] = value;
}
this.draw();
previousPosition = newPosition;
this.dispatchEvent(new Event('input', {
bubbles: true,
}));
if (this._snap && value !== this._previousValue) {
this.dispatchEvent(new Event('change', {
bubbles: true,
}));
this._previousValue = value;
}
};
const pointerDown = (event) => {
if (this.controls || !(event.buttons & 1) || this.disabled) {
return;
}
this.canvas.setPointerCapture(event.pointerId);
this.canvas.addEventListener('pointermove', pointerMove);
this.canvas.addEventListener('pointerup', pointerUp);
this.canvas.addEventListener('pointerout', pointerUp);
pointerMove(event);
Ticker.add(setValuesFromPosition);
};
const pointerMove = (event) => {
pointerOffsetX = event.offsetX;
pointerOffsetY = event.offsetY;
};
const pointerUp = (event) => {
Ticker.delete(setValuesFromPosition);
previousPosition = null;
this.canvas.releasePointerCapture(event.pointerId);
this.canvas.removeEventListener('pointermove', pointerMove);
this.canvas.removeEventListener('pointerup', pointerUp);
this.canvas.removeEventListener('pointerout', pointerUp);
};
this.canvas.addEventListener('pointerdown', pointerDown);
}
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case 'position':
this.position = Number(newValue);
break;
case 'length':
this[name] = Number(newValue);
break;
default:
super.attributeChangedCallback(name, oldValue, newValue);
}
}
draw() {
super.draw();
this.context.strokeStyle = 'red';
const position = (this.position / this.length) * this.zoom * this.canvas.width - this.scrollLeft * devicePixelRatio;
this.context.beginPath();
this.context.moveTo(position, 0);
this.context.lineTo(position, this.canvas.height);
this.context.stroke();
}
_getIndexFromPosition(position) {
return Math.min(this.array.length - 1, Math.max(0, Math.floor(position / this.length * this.array.length)));
}
get position() {
return this._position;
}
set position(value) {
if (this._position === value) {
return;
}
this._position = value;
const arrayValue = this.array[this._getIndexFromPosition(this.position)];
if (arrayValue !== this._previousValue && !this._snap) {
this.dispatchEvent(new Event('change', {
bubbles: true,
}));
this._previousValue = arrayValue;
}
this.draw();
}
get value() {
return this.array[this._getIndexFromPosition(this.position)];
}
get length() {
return this._length;
}
set length(value) {
this._length = value;
this.draw();
}
get name() {
return this.getAttribute('name');
}
set name(value) {
this.setAttribute('name', value);
}
get disabled() {
return this.hasAttribute('disabled');
}
set disabled(value) {
if (value) {
this.setAttribute('disabled', '');
} else {
this.removeAttribute('disabled');
}
}
}
if (!customElements.get('damo-input-signal-array')) {
customElements.define('damo-input-signal-array', class DamoArraySignalInputElement extends ArraySignalInputElement { });
}
|
JavaScript
| 0.000001 |
@@ -326,24 +326,363 @@
super();%0A%0A
+ this._head = document.createElement('div');%0A this._head.style.position = 'absolute';%0A this._head.style.willChange = 'transform';%0A this._head.style.height = '100%25';%0A this._head.style.top = '0';%0A this._head.style.left = '0';%0A this._head.style.borderLeft = '1px solid red';%0A this.shadowRoot.appendChild(this._head);%0A%0A
this._le
@@ -4300,351 +4300,8 @@
%7D%0A%0A
- draw() %7B%0A super.draw();%0A this.context.strokeStyle = 'red';%0A const position = (this.position / this.length) * this.zoom * this.canvas.width - this.scrollLeft * devicePixelRatio;%0A this.context.beginPath();%0A this.context.moveTo(position, 0);%0A this.context.lineTo(position, this.canvas.height);%0A this.context.stroke();%0A %7D%0A%0A
_g
@@ -4328,24 +4328,24 @@
position) %7B%0A
+
return M
@@ -4605,24 +4605,150 @@
on = value;%0A
+ this._head.style.transform = %60translateX($%7Bthis._position / this.length * this._width * this.zoom - this.scrollLeft%7Dpx)%60;%0A
const ar
@@ -4999,31 +4999,14 @@
ue;%0A
+
%7D%0A
- this.draw();%0A
%7D%0A
|
a4d178ea18cedd359cbdfe9b0c3fa731b446ce07
|
Fix :filter {artist}.
|
xulmus/content/player.js
|
xulmus/content/player.js
|
//Import Artist List as this can be huge
var artists = getArtistsArray();
function Player() // {{{
{
////////////////////////////////////////////////////////////////////////////////
////////////////////// PRIVATE SECTION /////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
// Get the focus to the visible playlist first
//window._SBShowMainLibrary();
/////////////////////////////////////////////////////////////////////////////}}}
////////////////////// MAPPINGS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
mappings.add([modes.PLAYER],
["x"], "Play Track",
function ()
{
gMM.sequencer.play();
});
mappings.add([modes.PLAYER],
["z"], "Previous Track",
function ()
{
gSongbirdWindowController.doCommand("cmd_control_previous");
});
mappings.add([modes.PLAYER],
["c"], "Pause/Unpause Track",
function ()
{
gSongbirdWindowController.doCommand("cmd_control_playpause");
});
mappings.add([modes.PLAYER],
["b"], "Next Track",
function ()
{
gSongbirdWindowController.doCommand("cmd_control_next");
});
mappings.add([modes.PLAYER],
["v"], "Stop Track",
function ()
{
gMM.sequencer.stop();
});
mappings.add([modes.PLAYER],
["f"], "Filter Library",
function ()
{
commandline.open(":", "filter ", modes.EX);
});
mappings.add([modes.PLAYER],
["s"], "Toggle Shuffle",
function ()
{
if (gMM.sequencer.mode != gMM.sequencer.MODE_SHUFFLE)
gMM.sequencer.mode = gMM.sequencer.MODE_SHUFFLE;
else
gMM.sequencer.mode = gMM.sequencer.MODE_FORWARD;
});
mappings.add([modes.PLAYER],
["r"], "Toggle Repeat",
function ()
{
switch (gMM.sequencer.repeatMode)
{
case gMM.sequencer.MODE_REPEAT_NONE:
gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_ONE;
break;
case gMM.sequencer.MODE_REPEAT_ONE:
gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_ALL;
break;
case gMM.sequencer.MODE_REPEAT_ALL:
gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_NONE;
break;
default:
gMM.sequencer.repeatMode = gMM.sequencer.MODE_REPEAT_NONE;
break;
}
});
mappings.add([modes.PLAYER],
["h"], "Seek -10s",
function ()
{
if (gMM.playbackControl.position >= 10000)
gMM.playbackControl.position = gMM.playbackControl.position - 10000;
else
gMM.playbackControl.position = 0;
});
mappings.add([modes.PLAYER],
["l"], "Seek +10s",
function ()
{
if ((gMM.playbackControl.duration - gMM.playbackControl.position) >= 10000)
gMM.playbackControl.position = gMM.playbackControl.position + 10000;
else
gMM.playbackControl.position = gMM.playbackControl.duration;
});
mappings.add([modes.PLAYER],
["H"], "Seek -1m",
function ()
{
if (gMM.playbackControl.position >= 60000)
gMM.playbackControl.position = gMM.playbackControl.position - 60000;
else
gMM.playbackControl.position = 0;
});
mappings.add([modes.PLAYER],
["L"], "Seek +1m",
function ()
{
if ((gMM.playbackControl.duration - gMM.playbackControl.position) >= 60000)
gMM.playbackControl.position = gMM.playbackControl.position + 60000;
else
gMM.playbackControl.position = gMM.playbackControl.duration;
});
////////////////// ///////////////////////////////////////////////////////////}}}
////////////////////// COMMANDS ////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
commands.add(["f[ilter]"],
"Filter Tracks",
function (args)
{
//Store the old view
//var prev_view = gMM.status.view;
var library = LibraryUtils.mainLibrary;
var mainView = library.createView();
var sqncr = gMM.sequencer;
var customProps = Cc["@songbirdnest.com/Songbird/Properties/MutablePropertyArray;1"]
.createInstance(Ci.sbIMutablePropertyArray);
//args
switch (args.length)
{
case 3:
customProps.appendProperty(SBProperties.trackName,args[2].toString());
case 2:
customProps.appendProperty(SBProperties.albumName,args[1].toString());
case 3:
customProps.appendProperty(SBProperties.artistName,args[0].toString());
break;
default:
break;
}
sqncr.playView(mainView, mainView.getIndexForItem(library.getItemsByProperties(customProps).queryElementAt(0,Ci.sbIMediaItem)));
},
{
completer: function (context, args) completion.song(context, args)
});
/////////////////////////////////////////////////////////////////////////////}} }
////////////////////// PUBLIC SECTION //////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////{{{
//}}}
} // }}}
function getArtists()
{
return this.artists;
}
function getArtistsArray()
{
var list = LibraryUtils.mainLibrary;
// Create an enumeration listener to count each item
var listener = {
count: 0,
onEnumerationBegin: function (aMediaList) {
this.count = 0;
},
onEnumeratedItem: function (aMediaList, aMediaItem) {
this.count++;
},
onEnumerationEnd: function (aMediaList, aStatusCode) {}
};
var artistCounts = {};
var artists = list.getDistinctValuesForProperty(SBProperties.artistName);
var artist;
var artistArray = [];
var i = 0;
// Count the number of media items for each distinct artist
while (artists.hasMore()) {
artist = artists.getNext();
artistArray[i] = [artist,artist];
list.enumerateItemsByProperty(SBProperties.artistName,
artist,
listener,
Ci.sbIMediaList.ENUMERATIONTYPE_LOCKING);
artistCounts[artist] = listener.count;
i++;
}
//liberator.dump("Count : "+artistCounts.toSource());
return artistArray;
}
function getAlbums(artist)
{
var list = LibraryUtils.mainLibrary;
var albumArray = [], returnArray = [];
var items = list.getItemsByProperty(SBProperties.artistName, artist).enumerate();
var i = 0, j = 0;
while (items.hasMoreElements()) {
album = items.getNext().getProperty(SBProperties.albumName);
albumArray[i] = [album, album];
if (i == 0)
{
returnArray[j] = albumArray[i];
j++;
}
else if (albumArray[i-1].toString() != albumArray[i].toString())
{
returnArray[i] = albumArray[i];
j++;
}
i++;
}
return returnArray;
}
function getTracks(artist,album)
{
var list = LibraryUtils.mainLibrary;
var tracksArray = [];
var pa = Cc["@songbirdnest.com/Songbird/Properties/MutablePropertyArray;1"]
.createInstance(Ci.sbIMutablePropertyArray);
var i = 0;
pa.appendProperty(SBProperties.artistName,artist.toString());
pa.appendProperty(SBProperties.albumName,album.toString());
var items = list.getItemsByProperties(pa).enumerate();
while (items.hasMoreElements()) {
track = items.getNext().getProperty(SBProperties.trackName);
tracksArray[i] = [track, track];
i++;
}
return tracksArray;
}
// vim: set fdm=marker sw=4 ts=4 et:
|
JavaScript
| 0.000001 |
@@ -5351,50 +5351,10 @@
ase
-3:
+1:
%0A
|
0a624446f2b1958e2284d0c72c856d6a6c1cf9b2
|
fix sidebar scrolling.
|
chrome/common/extensions/docs/static/js/scroll.js
|
chrome/common/extensions/docs/static/js/scroll.js
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Scroll handling.
//
// Switches the sidebar between floating on the left and position:fixed
// depending on whether it's scrolled into view, and manages the scroll-to-top
// button: click logic, and when to show it.
(function() {
var sidebar = document.getElementById('gc-sidebar');
var scrollToTop = document.getElementById('scroll-to-top');
var offsetTop = sidebar.offsetTop;
window.addEventListener('scroll', function() {
// Obviously, this code executes every time the window scrolls, so avoid
// putting things in here.
var floatSidebar = false;
var showScrollToTop = false;
if (window.scrollY > offsetTop) {
// Scrolled past the top of the sidebar.
if (window.innerHeight >= sidebar.offsetHeight) {
// The whole sidebar fits in the window. Make it always visible.
floatSidebar = true;
} else {
// Whole sidebar doesn't fit, so show the scroll-to-top button instead.
showScrollToTop = true;
}
}
sidebar.classList.toggle('floating', floatSidebar);
scrollToTop.classList.toggle('hidden', !showScrollToTop);
});
scrollToTop.addEventListener('click', function() {
window.scrollTo(0, 0);
});
}());
|
JavaScript
| 0.000007 |
@@ -546,50 +546,25 @@
p;%0A%0A
-window.addEventListener('scroll', function
+function relayout
() %7B
@@ -668,16 +668,155 @@
n here.%0A
+ var isFloatingSidebar = sidebar.classList.contains('floating');%0A var isShowingScrollToTop = !scrollToTop.classList.contains('hidden');%0A%0A
var fl
@@ -986,22 +986,22 @@
sidebar.
-offset
+scroll
Height)
@@ -1232,16 +1232,59 @@
%7D%0A %7D%0A%0A
+ if (floatSidebar != isFloatingSidebar)%0A
sideba
@@ -1329,16 +1329,65 @@
debar);%0A
+ if (isShowingScrollToTop != showScrollToTop)%0A
scroll
@@ -1435,24 +1435,93 @@
ollToTop);%0A%7D
+%0A%0Awindow.addEventListener('scroll', relayout);%0AsetTimeout(relayout, 0
);%0A%0AscrollTo
|
097c712727bc5a48d53345d6bc7e5d1aa30433b6
|
Add spacing in serialize lib #86
|
lib/serialize.js
|
lib/serialize.js
|
Cosmos.serialize = {
getPropsFromQueryString: function(queryString) {
var props = {};
if (queryString.length) {
var pairs = queryString.split('&'),
parts,
key,
value;
for (var i = 0; i < pairs.length; i++) {
parts = pairs[i].split('=');
key = parts[0];
value = decodeURIComponent(parts[1]);
try {
value = JSON.parse(value);
} catch(e) {
// If the prop was a simple type and not a stringified JSON it will
// keep its original value
}
props[key] = value;
}
}
return props;
},
getQueryStringFromProps: function(props) {
var parts = [],
value;
for (var key in props) {
value = props[key];
// Objects can be embedded in a query string as well
if (typeof value == 'object') {
try {
value = JSON.stringify(value);
} catch(e) {
// Props that can't be stringified should be ignored
continue;
}
}
parts.push(key + '=' + encodeURIComponent(value));
}
return parts.join('&');
}
};
|
JavaScript
| 0.000003 |
@@ -85,24 +85,25 @@
s = %7B%7D;%0A
+%0A
if (
queryStr
@@ -94,16 +94,17 @@
if (
+!
queryStr
@@ -115,24 +115,49 @@
length) %7B%0A
+ return props;%0A %7D%0A%0A
var pair
@@ -188,26 +188,24 @@
'),%0A
-
parts,%0A
@@ -211,17 +211,13 @@
-
key,%0A
-
@@ -223,26 +223,25 @@
value;%0A
-
+%0A
for (var
@@ -269,26 +269,24 @@
gth; i++) %7B%0A
-
parts
@@ -314,18 +314,16 @@
;%0A
-
key = pa
@@ -330,18 +330,16 @@
rts%5B0%5D;%0A
-
va
@@ -374,18 +374,17 @@
ts%5B1%5D);%0A
-
+%0A
tr
@@ -379,34 +379,32 @@
);%0A%0A try %7B%0A
-
value =
@@ -420,34 +420,32 @@
e(value);%0A
-
%7D catch(e) %7B%0A
@@ -449,18 +449,16 @@
-
-
// If th
@@ -525,18 +525,16 @@
-
// keep
@@ -552,26 +552,24 @@
l value%0A
-
%7D%0A
@@ -556,26 +556,25 @@
lue%0A %7D%0A
-
+%0A
props%5B
@@ -591,22 +591,15 @@
ue;%0A
- %7D%0A
%7D%0A
+%0A
@@ -617,16 +617,17 @@
s;%0A %7D,%0A
+%0A
getQue
@@ -694,24 +694,25 @@
value;%0A
+%0A
for (var
@@ -754,16 +754,17 @@
s%5Bkey%5D;%0A
+%0A
//
@@ -1025,24 +1025,25 @@
%7D%0A %7D%0A
+%0A
parts.
@@ -1089,24 +1089,25 @@
ue));%0A %7D%0A
+%0A
return p
|
128be6d69cba464b74199c774270ef5fc7b78364
|
exclude validation pattern
|
src/main.js
|
src/main.js
|
define('main', [
"jquery",
"./registry",
"modernizer",
"less",
"prefixfree",
"./patterns/autofocus",
"./patterns/autoscale",
"./patterns/autosubmit",
"./patterns/autosuggest",
"./patterns/breadcrumbs",
"./patterns/bumper",
"./patterns/carousel",
"./patterns/checkedflag",
"./patterns/checklist",
"./patterns/chosen",
"./patterns/collapsible",
"./patterns/depends",
"./patterns/edit-tinymce",
"./patterns/expandable",
"./patterns/focus",
"./patterns/form-state",
"./patterns/fullcalendar",
"./patterns/image-crop",
"./patterns/inject",
"./patterns/markdown",
"./patterns/menu",
"./patterns/modal",
"./patterns/navigation",
"./patterns/placeholder",
"./patterns/setclass",
"./patterns/sortable",
"./patterns/switch",
"./patterns/transforms",
"./patterns/toggle",
"./patterns/tooltip",
"./patterns/validate",
"./patterns/zoom"
], function($, registry) {
registry.init();
});
require(['main']);
|
JavaScript
| 0.000003 |
@@ -913,32 +913,87 @@
s/tooltip%22,%0A
+// has racing problems, might be replaced anyway%0A //
%22./patterns/vali
|
489d9a943abf144cae47d8ade6539d392306f31e
|
make it async
|
tasks/nunjucks.js
|
tasks/nunjucks.js
|
/**
* grunt-nunjucks-2-html
* https://github.com/vitkarpov/grunt-nunjucks-2-html
*
* Copyright (c) 2014 Vit Karpov
* Licensed under the MIT license.
*/
var nunjucks = require('nunjucks');
var path = require('path');
var async = require('async');
var _ = require('lodash');
module.exports = function(grunt) {
'use strict';
grunt.registerMultiTask('nunjucks', 'Renders nunjucks` template to HTML', function() {
var options = this.options();
var completeTask = this.async();
if (!options.data) {
grunt.log.warn('Template`s data is empty. Guess you forget to specify data option');
}
var envOptions = { watch: false };
if (options.tags) {
envOptions.tags = options.tags;
}
var basePath = options.paths || '';
var env = nunjucks.configure(basePath, envOptions);
if (typeof options.configureEnvironment === 'function') {
options.configureEnvironment.call(this, env, nunjucks);
}
async.each(this.files, function(f, done) {
var filepath = path.join(process.cwd(), f.src[0]);
// We need to clone the data
var data = _.cloneDeep(options.data || {});
if (typeof options.preprocessData === 'function') {
data = options.preprocessData.call(f, data);
}
var template = grunt.file.read(filepath);
try {
var html = env.renderString(template, data);
} catch(e) {
done(e);
}
if (html) {
grunt.file.write(f.dest, html);
grunt.log.writeln('File "' + f.dest + '" created.');
done();
}
}, function(err) {
if (err) {
grunt.log.error(err);
}
completeTask();
});
});
};
|
JavaScript
| 0.000272 |
@@ -1381,49 +1381,55 @@
-var template = grunt.file.read(filepath);
+env.render(filepath, data, function(err, res) %7B
%0A
@@ -1441,11 +1441,20 @@
-try
+ if (err)
%7B%0A
@@ -1472,100 +1472,66 @@
-var html = env.renderString(template, data);%0A %7D catch(e) %7B%0A
+ grunt.log.error(err);%0A return
done(
-e
);%0A
@@ -1531,33 +1531,24 @@
ne();%0A
- %7D%0A%0A
@@ -1549,21 +1549,9 @@
- if (html) %7B
+%7D
%0A
@@ -1588,20 +1588,19 @@
f.dest,
-html
+res
);%0A
@@ -1679,32 +1679,32 @@
done();%0A
-
%7D%0A%0A
@@ -1692,32 +1692,34 @@
);%0A %7D
+);
%0A%0A %7D, fun
|
6dadebd94026c6ab608a1ce34b8870d0284322ad
|
Add collapse function to externs
|
externs/twbootstrap.js
|
externs/twbootstrap.js
|
/**
* Externs for Twitter Bootstrap
*
* @externs
*/
/**
* @param {string=} opt_action
* @return {!jQuery}
*/
jQuery.prototype.alert = function(opt_action) {};
/**
* @param {string=} opt_action
* @return {!angular.JQLite}
*/
angular.JQLite.prototype.alert = function(opt_action) {};
/**
* @param {string=} opt_action
* @return {!jQuery}
*/
jQuery.prototype.dropdown = function(opt_action) {};
/**
* @param {string=} opt_action
* @return {!angular.JQLite}
*/
angular.JQLite.prototype.dropdown = function(opt_action) {};
/**
* @param {(string|Object.<string,*>)=} opt_options
* @return {jQuery}
*/
jQuery.prototype.modal = function(opt_options) {};
/**
* @param {(string|Object.<string,*>)=} opt_options
* @return {angular.JQLite}
*/
angular.JQLite.prototype.modal = function(opt_options) {};
/**
* @param {string|Object.<string,*>=} opt_option
* @return {!jQuery}
*/
jQuery.prototype.popover = function(opt_option) {};
/**
* @param {(string|Object.<string,*>)=} opt_options
* @return {angular.JQLite}
*/
angular.JQLite.prototype.popover = function(opt_options) {};
/**
* @param {string} action
* @return {!jQuery}
*/
jQuery.prototype.tab = function(action) {};
/**
* @param {string} action
* @return {!angular.JQLite}
*/
angular.JQLite.prototype.tab = function(action) {};
/**
* @typedef {{
* animation: (boolean|undefined),
* container: (string|boolean|undefined),
* delay: (number|Object.<string,*>|undefined),
* html: (boolean|undefined),
* placement: (string|function(Element, Element)|undefined),
* selector: (string|undefined),
* template: (string|undefined),
* title: (string|function()|undefined),
* trigger: (string|undefined),
* viewport: (string|Object.<string,*>|function(Element)|undefined)
* }}
*/
let TooltipOptions;
/**
* @param {(string|TooltipOptions)=} opt_options
* @return {jQuery}
*/
jQuery.prototype.tooltip = function(opt_options) {};
/**
* @param {(string|TooltipOptions)=} opt_options
* @return {angular.JQLite}
*/
angular.JQLite.prototype.tooltip = function(opt_options) {};
|
JavaScript
| 0 |
@@ -2071,28 +2071,456 @@
= function(opt_options) %7B%7D;%0A
+%0A%0A/**%0A * @typedef %7B%7B%0A * parent: (string%7Cboolean%7Cundefined),%0A * toggle: (boolean%7Cundefined)%0A * %7D%7D%0A */%0Alet CollapseOptions;%0A%0A%0A/**%0A * @param %7Bstring%7CCollapseOptions%7D action_or_options%0A * @return %7BjQuery%7D%0A */%0AjQuery.prototype.collapse = function(action_or_options) %7B%7D;%0A%0A%0A/**%0A * @param %7Bstring%7CCollapseOptions%7D action_or_options%0A * @return %7Bangular.JQLite%7D%0A */%0Aangular.JQLite.prototype.collapse = function(action_or_options) %7B%7D;%0A
|
166a20475a76e1d955faab06a514fea1e69d5814
|
Fix reference to blog in calls to Tumblr
|
app/assets/javascripts/application.js
|
app/assets/javascripts/application.js
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW
//
//= require_tree .
//= require_self
$(function() {
var MAX_OFFSET = 1000;
var MAX_IMAGES_COUNT = 10;
var IMAGE_LOAD_INTERVAL = 2500
var $imagesContainer = $('.images')
var currentWidth = 0;
var isMobile = $(window).width() <= 480;
var imageThreshold = isMobile ? 2.5 : 1.25;
function getImage() {
var offset = Math.floor(Math.random() * MAX_OFFSET);
$.getJSON('http://api.tumblr.com/v2/blog/discom4rt.tumblr.com/likes?callback=?', {
api_key: 'ok1dCktUCXTyOgG0vlyhxcW7oQ4lxUZl0QfZkoEiwwjvU2ZKAv',
offset: offset,
limit: 1
}).then(function(json) {
var $moodSetter = $('<img>');
if(!json.response.liked_posts[0] || !json.response.liked_posts[0].photos || !json.response.liked_posts[0].photos.length) {
console.warn('found post with no images!')
return getImage();
}
var photos = json.response.liked_posts[0].photos;
var rpindex = Math.floor(Math.random() * photos.length);
$moodSetter.on('load', function(event) {
var $images = $('img')
$moodSetter.addClass('mood-setter');
$imagesContainer.append($moodSetter);
currentWidth += $(this).width()
if (currentWidth > imageThreshold * $(window).width()) {
currentWidth -= $images.first().width()
$images.first().remove()
}
}).attr({
src: photos[rpindex].original_size.url
})
});
}
$('.work').randomize()
setInterval(getImage, IMAGE_LOAD_INTERVAL);
getImage();
});
|
JavaScript
| 0.000001 |
@@ -995,17 +995,16 @@
log/
-discom4rt
+mhgbrown
.tum
|
53533e03f8dd1c4420719d2ba3a3468b8c7d4719
|
Add department to title attribute
|
src/force-directed-graph-renderer.js
|
src/force-directed-graph-renderer.js
|
import d3 from 'd3';
export default class ForceDirectedGraphRenderer {
renderSvg(containerElement, users) {
const width = 1200;
const height = 700;
const radius = 15;
const color = d3.scale.category20();
const vis = d3
.select(containerElement)
.append('svg')
.attr('width', width)
.attr('height', height);
const links = users
.filter(user => {
if (!user.manager) {
return false;
}
const manager = users.find(x => x.id === user.manager.id);
if (!manager) {
console.log(`Missing manager for ${user.id} in data.`); // eslint-disable-line no-console
}
return !!manager;
})
.map((user, index) => {
const managerIndex = users.find(x => x.id === user.manager.id);
if (!managerIndex && managerIndex !== 0) {
throw new Error(`managerIndex could be not found for user.manager.id: '${user.manager.id}'.`);
}
return {
source: index,
target: managerIndex,
value: 1
};
});
const link = vis.selectAll('line')
.data(links)
.enter().append('line');
const node = vis.selectAll('.node')
.data(users)
.enter().append('g')
.attr('class', 'node');
node.append('circle')
.attr('r', radius)
.style('fill', d => color(d.department));
node.append('text')
.attr('text-anchor', 'middle')
.text(x => this.getNameAbbreviation(x.displayName));
node.append('title')
.text(x => x.displayName);
const force = d3.layout.force()
.nodes(users)
.links(links)
.size([width, height])
.linkDistance(30)
.charge(-400)
.gravity(0.3)
.start();
node.call(force.drag);
force.on('tick', () => {
link.attr('x1', d => d.source.x)
.attr('y1', d => d.source.y)
.attr('x2', d => d.target.x)
.attr('y2', d => d.target.y);
d3.selectAll('circle')
.attr('cx', d => Math.max(radius, Math.min(width - radius, d.x)))
.attr('cy', d => Math.max(radius, Math.min(height - radius, d.y)));
d3.selectAll('text')
// TODO: Fix labels at svg edges
.attr('x', d => d.x)
.attr('y', d => d.y + 5);
});
}
getNameAbbreviation(displayName) {
const split = displayName.split(' ');
if (split.length > 0) {
const givenName = split[0];
const surName = split[1];
const firstLetter = givenName ? givenName[0] : '?';
const secondLetter = surName ? surName[0] : '';
return `${firstLetter}${secondLetter}`;
}
}
}
|
JavaScript
| 0.000003 |
@@ -1555,16 +1555,19 @@
xt(x =%3E
+%60$%7B
x.displa
@@ -1571,16 +1571,36 @@
playName
+%7D ($%7Bx.department%7D)%60
);%0A%0A
|
6dc0d82a9b241e46da51b04d1ce3e69d80f6bedf
|
fix corner case of non-spread 1-arg tuple functions
|
runtime-js/callables.js
|
runtime-js/callables.js
|
function $JsCallable(f$,parms,targs) {
//Do not wrap another $JsCallable
if (f$.jsc$)return f$;
if (f$.getT$all === undefined) {
f$.getT$all=Callable.getT$all;
}
var set_meta = getrtmm$$(f$) === undefined;
if (set_meta) {
f$.$crtmm$={ps:[],mod:$CCMM$,d:['$','Callable']};
if (parms !== undefined) {
f$.$crtmm$.ps=parms;
}
}
if (targs !== undefined && f$.$$targs$$ === undefined) {
f$.$$targs$$=targs;
if (set_meta) {
f$.$crtmm$.$t=targs.Return$Callable;
}
}
if (f$.$flattened$||f$.$unflattened$)return f$;
function f(){
return f$.apply(0,spread$(arguments,f$));
}
f.$crtmm$=f$.$crtmm$;
f.getT$all=f$.getT$all;
f.jsc$=f$;
f.equals=function(o) {
if (o.jsc$)return o.jsc$===f$;
return o===f;
}
return f;
}
initExistingTypeProto($JsCallable, Function, 'ceylon.language::JsCallable', Callable);
function nop$(){return null;}
//This is used for method references
function JsCallable(o,f,targs) {
if (o===null || o===undefined) return nop$;
if (f.jsc$)f=f.jsc$;
var f2 = function() {
var arg=spread$(arguments,f);
if (targs)arg.push(targs);
return f.apply(o, arg, targs);
};
f2.$crtmm$=f.$crtmm$===undefined?Callable.$crtmm$:f.$crtmm$;
return f2;
}
JsCallable.$crtmm$=function(){return{ sts:[{t:Callable,a:{Return$Callable:'Return$Callable',Arguments$Callable:'Arguments$Callable'}}],
tp:{Return$Callable:{dv:'out'}, Arguments$Callable:{dv:'in'}},pa:1,mod:$CCMM$,d:['$','Callable']};}
function spread$(a,f,targs) {
var arg=[].slice.call(a,0);
//if we get only 1 arg and it's a tuple...
if (arg.length===1 && is$(arg[0],{t:Tuple})) {
//Possible spread, check the metamodel
var mm=getrtmm$$(f);
//If f has only 1 param and it's not sequenced, get its type
var a1t=mm && mm.ps && mm.ps.length===1 && mm.ps[0].seq===undefined ? mm.ps[0].$t : undefined;
//If it's a type param, get the type argument
if (typeof(a1t)==='string')a1t=targs && targs[a1t];
//If the tuple type matches the param type, it's NOT a spread
//(it's just a regular 1-param func which happens to receive a tuple)
if (!(a1t && is$(arg[0],a1t))) {
var typecheck;
if (a1t && arg[0].$$targs$$) {
if (arg[0].$$targs$$.First$Tuple) {
typecheck={t:Tuple,a:arg[0].$$targs$$};
} else if (arg[0].$$targs$$.t==='T') {
typecheck=arg[0].$$targs$$;
} else if (arg[0].$$targs$$.Element$Iterable) {
typecheck={t:Iterable,a:arg[0].$$targs$$.Element$Iterable};
}
}
if (mm && mm.ps && (mm.ps.length>1 || (mm.ps.length===1
&& (mm.ps[0].seq || !extendsType(a1t, typecheck))))) {
var a=arg[0].nativeArray ? arg[0].nativeArray():undefined;
if (a===undefined) {
a=[];
for (var i=0;i<arg[0].size;i++)a.push(arg[0].$_get(i));
}
arg=a;
}
}
}
return arg;
}
//This is used for spread method references
function JsCallableList(value,$mpt) {
return function() {
var a=arguments;
if ($mpt) {
a=[].slice.call(arguments,0);
a.push($mpt);
}
var rval = Array(value.length);
for (var i = 0; i < value.length; i++) {
var c = value[i];
rval[i] = c.f.apply(c.o, a);
}
return value.length===0?empty():sequence(rval,{Element$sequence:{t:Callable},Absent$sequence:{t:Nothing}});
};
}
JsCallableList.$crtmm$={tp:{Return$Callable:{dv:'out'}, Arguments$Callable:{dv:'in'}},pa:1,mod:$CCMM$,d:['$','Callable']};
function mplclist$(orig,clist,params,targs) {
return $JsCallable(function() {
var a=clist.apply(0,arguments);
if (!is$(a,{t:Sequential}))return mplclist$(orig,a,params,targs);
var b=Array(orig.length);
for (var i=0;i<b.length;i++)b[i]={o:orig[i].o,f:a.$_get(i)};
return JsCallableList(b);
},params,targs);
}
ex$.mplclist$=mplclist$;
ex$.JsCallableList=JsCallableList;
ex$.JsCallable=JsCallable;
ex$.$JsCallable=$JsCallable;
|
JavaScript
| 0.000218 |
@@ -617,16 +617,22 @@
ments,f$
+,targs
));%0A %7D%0A
@@ -1103,16 +1103,22 @@
uments,f
+,targs
);%0A i
@@ -1172,15 +1172,8 @@
arg
-, targs
);%0A
@@ -2199,16 +2199,121 @@
(a1t &&
+ targs && targs.Arguments$Callable) %7B%0A typecheck=targs.Arguments$Callable;%0A %7D else if (a1t &&
arg%5B0%5D.
|
4162c672091ab5f4d61eb098f2da5a2bb00fe941
|
Fix bracket on edu wizard (#5829)
|
src/js/edu-benefits/education-wizard.js
|
src/js/edu-benefits/education-wizard.js
|
function toggleClass(element, className) {
element.classList.toggle(className);
}
function openState(element) {
element.setAttribute('data-state', 'open');
}
function closeState(element) {
element.setAttribute('data-state', 'closed');
const selectionElement = element.querySelector('input:checked');
if (selectionElement) {
selectionElement.checked = false;
}
}
function closeStateAndCheckChild(alternateQuestion, container) {
const selectionElement = alternateQuestion.querySelector('input:checked');
if (!selectionElement) {
return closeState(alternateQuestion);
}
const descendentQuestion = selectionElement.dataset.nextQuestion;
if (!descendentQuestion) {
return closeState(alternateQuestion);
}
const descendentElement = container.querySelector(`[data-question=${descendentQuestion}]`);
closeStateAndCheckChild(descendentElement, container);
return closeState(alternateQuestion);
}
function reInitWidget() {
const container = document.querySelector('.wizard-container');
const button = container.querySelector('.wizard-button');
const content = container.querySelector('.wizard-content');
const apply = container.querySelector('#apply-now-button');
const transferWarning = container.querySelector('#transfer-warning');
const nctsWarning = container.querySelector('#ncts-warning');
function resetForm() {
const selections = Array.from(container.querySelectorAll('input:checked'));
// eslint-disable-next-line no-return-assign, no-param-reassign
selections.forEach(selection => selection.checked = false);
}
apply.addEventListener('click', resetForm);
content.addEventListener('change', (e) => {
const radio = e.target;
const otherChoice = radio.dataset.alternate;
const otherNextQuestion = container.querySelector(`#${otherChoice}`).dataset.nextQuestion;
if (otherNextQuestion) {
const otherNextQuestionElement = container.querySelector(`[data-question=${otherNextQuestion}`);
closeStateAndCheckChild(otherNextQuestionElement, container);
}
if ((apply.dataset.state === 'open') && !radio.dataset.selectedForm) {
closeState(apply);
}
if ((transferWarning.dataset.state === 'open') && (radio.id !== 'create-non-transfer')) {
closeState(transferWarning);
}
if ((nctsWarning.dataset.state === 'open') && (radio.id !== 'is-ncts')) {
closeState(nctsWarning);
}
if (radio.dataset.selectedForm) {
if (apply.dataset.state === 'closed') {
openState(apply);
}
if ((transferWarning.dataset.state === 'closed') && (radio.id === 'create-non-transfer')) {
openState(transferWarning);
}
if ((nctsWarning.dataset.state === 'closed') && (radio.id === 'is-ncts')) {
openState(nctsWarning);
}
apply.href = `/education/apply-for-education-benefits/application/${radio.dataset.selectedForm}/introduction`;
}
if (radio.dataset.nextQuestion) {
const nextQuestion = radio.dataset.nextQuestion;
const nextQuestionElement = container.querySelector(`[data-question=${nextQuestion}]`);
openState(nextQuestionElement);
nextQuestionElement.querySelector('input').focus();
}
});
button.addEventListener('click', () => {
toggleClass(content, 'wizard-content-closed');
toggleClass(button, 'va-button-primary');
});
// Ensure form is reset on page load to prevent unexpected behavior
resetForm();
}
document.addEventListener('DOMContentLoaded', reInitWidget);
|
JavaScript
| 0 |
@@ -1968,16 +1968,17 @@
uestion%7D
+%5D
%60);%0A
|
779978a6bd1c6b994a64bf8c1dfcb910abdaa7ac
|
improve docs generation
|
gulpfile.js
|
gulpfile.js
|
var fs = require('fs')
, gulp = require('gulp')
, stylish = require('jshint-stylish')
, jshint = require('gulp-jshint')
, markdox = require('markdox');
var sourceFiles = ['*.js', 'lib/**/*.js', 'bin/**/*.js'];
gulp.task('lint', function() {
var jshintOptions = {
laxcomma: true
};
return gulp.src(sourceFiles)
.pipe(jshint(jshintOptions))
.pipe(jshint.reporter(stylish));
});
gulp.task('docs', function(taskFinished) {
var files = ['lib/flightplan.js', 'lib/transport/transport.js'];
var options = {
output: 'docs/API.md',
template: 'docs/template.md.ejs'
};
markdox.process(files, options, function() {
var apidocs = fs.readFileSync(options.output, 'utf8');
apidocs = apidocs.replace(/'/g, "'").replace(/"/g, '"');
fs.writeFileSync(options.output, apidocs);
var readme = fs.readFileSync('README.md', 'utf8');
readme = readme.replace(/<!-- DOCS -->(?:\r|\n|.)+<!-- ENDDOCS -->/gm, '<!-- DOCS -->' + apidocs +'<!-- ENDDOCS -->');
fs.writeFileSync('README.md', readme);
console.log('Documentation generated.');
taskFinished();
});
});
gulp.task('default', ['lint']);
|
JavaScript
| 0.000001 |
@@ -433,19 +433,21 @@
%7B%0A%09var
-fil
+sourc
es = %5B'l
@@ -498,51 +498,80 @@
js'%5D
-;
%0A%09
-var options = %7B%0A%09%09output: 'docs/API.md',
+%09, readme = 'README.md'%0A%09%09, tmpFile = 'docs/API.md';%0A%0A%09var options = %7B
%0A%09%09t
@@ -601,16 +601,35 @@
.md.ejs'
+,%0A%09%09output: tmpFile
%0A%09%7D;%0A%0A%09m
@@ -647,11 +647,13 @@
ess(
-fil
+sourc
es,
@@ -680,23 +680,23 @@
%7B%0A%09%09var
-api
docs
+Str
= fs.re
@@ -706,30 +706,72 @@
ileSync(
-options.output
+tmpFile, 'utf8')%0A%09%09%09, readmeStr = fs.readFileSync(readme
, 'utf8'
@@ -780,25 +780,25 @@
%0A%0A%09%09
-api
docs
+Str
=
-api
docs
+Str
.rep
@@ -846,116 +846,19 @@
');%0A
-%0A
%09%09
-fs.writeFileSync(options.output, apidocs);%0A%0A%09%09var readme = fs.readFileSync('README.md', 'utf8');%0A%09%09
readme
+Str
= r
@@ -862,16 +862,19 @@
= readme
+Str
.replace
@@ -875,16 +875,17 @@
eplace(/
+(
%3C!-- DOC
@@ -889,16 +889,17 @@
DOCS --%3E
+)
(?:%5Cr%7C%5Cn
@@ -902,16 +902,17 @@
r%7C%5Cn%7C.)+
+(
%3C!-- END
@@ -923,99 +923,111 @@
--%3E
+)
/gm
-, '%3C!-- DOCS --%3E' + apidocs +'%3C!-- ENDDOCS --%3E');%0A%0A%09%09fs.writeFileSync('README.md', readm
+%0A%09%09%09%09%09%09%09%09%09%09, %22$1%22 + docsStr + %22$2%22);%0A%0A%09%09fs.writeFileSync(readme, readmeStr);%0A%09%09fs.unlinkSync(tmpFil
e);%0A
|
65e9e869cf49a2929e50eac630dcbb6a7e5b1a3f
|
Remove commented Closure compiler code for now
|
gulpfile.js
|
gulpfile.js
|
/*jshint node:true */
const gulp = require( 'gulp' ),
concat = require( 'gulp-concat' ),
connect = require( 'gulp-connect' ),
header = require( 'gulp-header' ),
jasmine = require( 'gulp-jasmine' ),
jshint = require( 'gulp-jshint' ),
preprocess = require( 'gulp-preprocess' ),
rename = require( 'gulp-rename' ),
uglify = require( 'gulp-uglify' ),
umd = require( 'gulp-umd' ),
JsDuck = require( 'gulp-jsduck' ),
KarmaServer = require( 'karma' ).Server;
// Project configuration
var banner = createBanner(),
srcFiles = createSrcFilesList(),
srcFilesGlob = './src/**/*.js',
testFilesGlob = './tests/**/*.js',
distFolder = 'dist/',
distFilename = 'Autolinker.js',
minDistFilename = 'Autolinker.min.js',
minDistFilePath = distFolder + minDistFilename;
gulp.task( 'default', [ 'lint', 'build', 'test' ] );
gulp.task( 'lint', lintTask );
gulp.task( 'build', buildTask );
gulp.task( 'test', [ 'build' ], testTask );
gulp.task( 'doc', docTask );
gulp.task( 'serve', serveTask );
function lintTask() {
return gulp.src( [ srcFilesGlob, testFilesGlob ] )
.pipe( jshint() )
.pipe( jshint.reporter( 'jshint-stylish' ) )
.pipe( jshint.reporter( 'fail' ) ); // fail the task if errors
}
function buildTask() {
return gulp.src( srcFiles )
.pipe( concat( distFilename ) )
.pipe( umd() )
.pipe( header( banner, { pkg: require( './package.json' ) } ) )
.pipe( gulp.dest( distFolder ) )
.pipe( preprocess( { context: { DEBUG: false } } ) ) // removes DEBUG tagged code
/*.pipe( closureCompiler({ // in case we want to use closure compiler. Need to define exports and get to work with umd header
compilation_level : 'ADVANCED',
warning_level : 'VERBOSE',
language_in : 'ECMASCRIPT3',
language_out : 'ECMASCRIPT3', // need to output to ES3 so the unicode regular expressions constructed with `new RegExp()` aren't changed into RegExp literals with all of the symbols expanded into \uXXXX. Adds 5kb to the output size in this case.
js_output_file : minDistFilename
}))*/
.pipe( uglify( { preserveComments: 'license' } ) )
.pipe( rename( minDistFilename ) )
.pipe( gulp.dest( distFolder ) );
}
function testTask( done ) {
return new KarmaServer( {
frameworks : [ 'jasmine' ],
reporters : [ 'spec' ],
browsers : [ 'PhantomJS' ],
files : [
'node_modules/lodash/lodash.js', // spec helper
minDistFilePath,
testFilesGlob
],
singleRun : true
}, done ).start();
}
function docTask() {
var jsduck = new JsDuck( [
'--out', './gh-pages/docs',
'--title', 'Autolinker API Docs'
] );
return gulp.src( srcFilesGlob )
.pipe( jsduck.doc() );
}
function serveTask() {
connect.server();
}
/**
* Creates the banner comment with license header that is placed over the
* concatenated/minified files.
*
* @private
* @return {String}
*/
function createBanner() {
return [
'/*!',
' * Autolinker.js',
' * <%= pkg.version %>',
' *',
' * Copyright(c) <%= new Date().getFullYear() %> <%= pkg.author %>',
' * <%= pkg.license %> License',
' *',
' * <%= pkg.homepage %>',
' */\n'
].join( "\n" );
}
/**
* Creates the source files list, in order.
*
* @private
* @return {String[]}
*/
function createSrcFilesList() {
return [
'src/Autolinker.js',
'src/Util.js',
'src/HtmlTag.js',
'src/RegexLib.js',
'src/AnchorTagBuilder.js',
'src/htmlParser/HtmlParser.js',
'src/htmlParser/HtmlNode.js',
'src/htmlParser/CommentNode.js',
'src/htmlParser/ElementNode.js',
'src/htmlParser/EntityNode.js',
'src/htmlParser/TextNode.js',
'src/match/Match.js',
'src/match/Email.js',
'src/match/Hashtag.js',
'src/match/Phone.js',
'src/match/Twitter.js',
'src/match/Url.js',
'src/matcher/Matcher.js',
'src/matcher/Email.js',
'src/matcher/Hashtag.js',
'src/matcher/Phone.js',
'src/matcher/Twitter.js',
'src/matcher/Url.js',
'src/matcher/UrlMatchValidator.js',
'src/truncate/TruncateEnd.js',
'src/truncate/TruncateMiddle.js',
'src/truncate/TruncateSmart.js'
];
}
|
JavaScript
| 0 |
@@ -1574,25 +1574,52 @@
stFolder ) )
+ // output unminified file
%0A
-
%09%09.pipe( pre
@@ -1695,546 +1695,8 @@
ode%0A
-%09%09/*.pipe( closureCompiler(%7B // in case we want to use closure compiler. Need to define exports and get to work with umd header%0A%09%09%09compilation_level : 'ADVANCED',%0A%09%09%09warning_level : 'VERBOSE',%0A%09%09%09language_in : 'ECMASCRIPT3',%0A%09%09%09language_out : 'ECMASCRIPT3', // need to output to ES3 so the unicode regular expressions constructed with %60new RegExp()%60 aren't changed into RegExp literals with all of the symbols expanded into %5CuXXXX. Adds 5kb to the output size in this case.%0A%09%09%09js_output_file : minDistFilename%0A%09%09%7D))*/%0A
%09%09.p
@@ -1773,32 +1773,32 @@
istFilename ) )%0A
-
%09%09.pipe( gulp.de
@@ -1812,24 +1812,49 @@
tFolder ) );
+ // output minified file
%0A%7D%0A%0A%0Afunctio
@@ -3689,8 +3689,9 @@
s'%0A%09%5D;%0A%7D
+%0A
|
d0d7ddeae2695503771a349af85a8a7a6217ecb4
|
Update main.js
|
src/main.js
|
src/main.js
|
import { CatOwners } from './cat.owners';
var catOwners = new CatOwners();
catOwners.init();
|
JavaScript
| 0.000001 |
@@ -5,22 +5,19 @@
rt %7B Cat
-Owners
+App
%7D from
@@ -27,31 +27,51 @@
cat.
-owners';%0A%0Avar catOwners
+app';%0A%0A// instantiating CatApp%0Aconst catApp
= n
@@ -80,22 +80,19 @@
Cat
-Owners
+App
();%0A%0Acat
Owne
@@ -91,14 +91,11 @@
%0Acat
-Owners
+App
.ini
|
697e60ff0a2df03acf066e7c107ba3e543dc0d62
|
Remove broken jquery plugin
|
app/assets/javascripts/application.js
|
app/assets/javascripts/application.js
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-hotkeys
//= require jquery-ui/accordion
//= require turbolinks
//= require jquery.turbolinks
//= require paloma
//= require_tree .
|
JavaScript
| 0.000001 |
@@ -646,40 +646,8 @@
eys%0A
-//= require jquery-ui/accordion%0A
//=
|
96867d553ce40deccf886e8284cd27fa3e663fbe
|
Update gulpfile
|
gulpfile.js
|
gulpfile.js
|
var elixir = require('laravel-elixir'),
build = require('./gulp.build.json');
require('./tasks/angular.task.js');
require('./tasks/bower.task.js');
require('laravel-elixir-livereload');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
'use strict';
if (build.published) {
build.base_directory = "";
build.application = "";
for (var i = 0; i < build.components.length; i++) {
build.components[i] = "";
}
}
mix
.bower()
.angular([
'./' + build.base_directory + build.application + 'angular/modules/app.core.module.js',
'./' + build.base_directory + build.application + 'angular/modules/components.module.js',
'./' + build.base_directory + build.application + 'angular/modules/application.module.js',
'./' + build.base_directory + build.application + 'angular/**/**/**/*.js',
'./' + build.base_directory + build.components[0] + 'angular/**/**/**/*.js',
])
//.sass('./' + build.base_directory + build.sass_directory + 'angular/**/**/**/*.scss', 'public/css')
.sass([
'./' + build.base_directory + build.application + 'angular/**/**/**/*.scss',
'./' + build.base_directory + build.components[0] + 'angular/**/**/**/*.scss'
], 'public/css')
.copy('./' + build.base_directory + build.application + 'angular/**/**/**/*.html', 'public/views/')
.copy('./' + build.base_directory + build.components[0] + 'angular/**/**/**/*.html', 'public/views/')
.livereload([
'public/js/vendor.js',
'public/js/app.js',
'public/css/vendor.css',
'public/css/app.css',
'public/views/!**!/!*.html'
], { liveCSS: true })
.phpUnit();
});
|
JavaScript
| 0.000001 |
@@ -970,23 +970,11 @@
ar/m
-odules/app.core
+ain
.mod
@@ -1034,49 +1034,34 @@
ild.
-application + 'angular/modules/components
+components%5B0%5D + 'angular/*
.mod
@@ -1144,16 +1144,8 @@
lar/
-modules/
appl
@@ -1330,33 +1330,32 @@
r/**/**/**/*.js'
-,
%0A %5D)%0A
@@ -1354,118 +1354,8 @@
%5D)%0A
- //.sass('./' + build.base_directory + build.sass_directory + 'angular/**/**/**/*.scss', 'public/css')%0A
@@ -2042,8 +2042,91 @@
();%0A%7D);%0A
+%0Arequire('gulp').task('generate', require('./tasks/generators/tasks/generate.js'));
|
59365d6d943523c7ec3a98d09edbb4d7c71fa856
|
Use Babel polyfill from browser only
|
src/main.js
|
src/main.js
|
require('../sass/main.scss');
import 'babel-polyfill';
import NamesPanel from './names-panel.js';
import OptionsPanel from './options-panel.js';
new NamesPanel().init();
new OptionsPanel().init();
|
JavaScript
| 0 |
@@ -27,33 +27,8 @@
');%0A
-import 'babel-polyfill';%0A
impo
|
b74ec82127ebfcaec8889cad1624af17d989ea02
|
Return cached value if lazy link field is sleeping
|
src/resources/elements/lazylinkfield.js
|
src/resources/elements/lazylinkfield.js
|
import {containerless} from 'aurelia-framework';
import {Field} from './abstract/field';
/**
* LazyLinkfield is a field that lazily proxies the a whole field (value & UI)
* to another place.
*/
@containerless
export class LazyLinkfield extends Field {
static TYPE = 'lazylink';
target = '#';
overrides = {};
child = undefined;
cachedValue = undefined;
/** @inheritdoc */
init(id = '', args = {}) {
this.target = args.target || '#';
this.overrides = args.overrides || {};
return super.init(id, args);
}
/** @inheritdoc */
get i18nPath() {
const target = this.resolveRef(this.target);
if (!target) {
return this.parent.i18nPath;
}
return target.i18nPath;
}
/**
* Check if this link doesn't currently have a child or if the child is empty.
*/
isEmpty() {
if (!this.child) {
return true;
}
return this.child.isEmpty();
}
/** @inheritdoc */
revalidate(errorCollection) {
const validation = super.revalidate(errorCollection);
if (this.child) {
validation.child = this.child.revalidate(errorCollection);
} else {
validation.child = { valid: true };
}
validation.childrenValid = validation.child.hasOwnProperty('childrenValid')
? validation.child.childrenValid
: validation.child.valid;
return validation;
}
/**
* Create the child of this field. Basically copy the target, set the parent
* and apply field overrides.
* This doesn't return anything, since it just sets the {@link #child} field.
*/
createChild() {
this.child = this.resolveRef(this.target).clone(this);
for (const [field, value] of Object.entries(this.overrides)) {
let target;
let fieldPath;
if (field.includes(';')) {
let elementPath;
[elementPath, fieldPath] = field.split(';');
fieldPath = fieldPath.split('/');
target = this.child.resolveRef(elementPath);
} else {
fieldPath = field.split('/');
target = this.child;
}
const lastFieldPathEntry = fieldPath.splice(-1)[0];
target = this.resolveRawPath(target, fieldPath);
if (value === null) {
delete target[lastFieldPathEntry];
} else {
target[lastFieldPathEntry] = value;
}
}
// Use cached value if it has been set.
if (this.cachedValue) {
this.child.setValue(this.cachedValue);
this.cachedValue = undefined;
}
}
/**
* Recurse through an object to find a specific nested field.
*/
resolveRawPath(object, path) {
if (path.length === 0) {
return object;
} else if (path[0] === '#') {
return this.resolveRawPath(object, path.splice(1));
}
return this.resolveRawPath(object[path[0]], path.splice(1));
}
/**
* Delete the current child.
*/
deleteChild() {
this.child = undefined;
}
/** @inheritdoc */
shouldDisplay() {
// This function is called by Aurelia (due to the if.bind="display" in HTML)
// and so changes to the output of the parent shouldDisplay can be detected
// here.
// When this field appears, the child will be generated. When the field dis-
// appears, the child will be deleted. This is what makes this link field
// lazy.
const display = super.shouldDisplay();
if (display) {
if (this.child === undefined) {
this.createChild();
}
} else if (this.child !== undefined) {
this.deleteChild();
}
return display;
}
/**
* Set the value of the target field.
*
* @override
* @param {Object} value The new value to set to the target field.
*/
setValue(value) {
this.onSetValue(value);
if (!this.child) {
// Caching values helps when using setValue() in a big form. By caching
// the values, we won't lose setValue data due to dependencies of this
// field not getting their value set before this field.
this.cachedValue = value;
return;
}
this.child.setValue(value);
}
/**
* Get the value of the target field.
*
* @override
* @return {Object} The value of the target field, or undefined if
* {@link #resolveTarget} returns {@linkplain undefined}.
*/
getValue() {
return this.child ? this.child.getValue() : undefined;
}
resolvePath(path) {
const parentResolveResult = super.resolvePath(path);
if (parentResolveResult) {
return parentResolveResult;
}
// If the child exists and the next path piece to be resolved targets the
// child, continue recursing from the child.
if (this.child && path[0] === ':child') {
return this.child.resolvePath(path.splice(1));
}
return undefined;
}
}
|
JavaScript
| 0.000003 |
@@ -829,32 +829,53 @@
if (!this.child
+ && !this.cachedValue
) %7B%0A return
@@ -4314,25 +4314,32 @@
lue() :
-undefined
+this.cachedValue
;%0A %7D%0A%0A
|
01cb840e0827333f30ac4d857a5df617ba9aac7b
|
use object
|
yahoo_rainfall/index.js
|
yahoo_rainfall/index.js
|
module.exports = function (context, myTimer) {
var timeStamp = new Date().toISOString();
if(myTimer.isPastDue)
{
context.log('JavaScript is running late!');
}
context.log('JavaScript timer trigger function ran!', timeStamp);
main(context);
};
if (require.main === module) {
var context = {
log : console.log,
done: () => {
console.log(context.bindings.outputQueueItem);
},
bindings : {}
};
main(context);
}
function main(context)
{
const yahoo = require("../Shared/yahoo_rainfall.js");
const api_key = process.env.YAHOO_APP_ID;
const lon = process.env.LONGITUDE;
const lat = process.env.LATITUDE;
const last_date = null;
try {
last_date = context.bindings.inputBlob["last_date"];
} catch(e) {
}
if (last_date && (last_date + 1000 * 60 * 60 > new Date())) return;
yahoo.get_weather_data(api_key, lon, lat)
.then(yahoo.get_rainfall_data)
.then(data => {
var o = data.filter(e => e["Type"] == "observation");
var f = data.filter(e => e["Type"] == "forecast" );
let tbl_data = {
"partitionKey" : "rainfall",
"rowKey" : Date(),
"date" : o[o.length - 1]["Date"],
"rainfall" : o[o.length - 1]["Rainfall"],
"rainfall_prev" : o[o.length - 2]["Rainfall"],
"forecast" : f[0]["Rainfall"]
}
context.log(tbl_data);
context.bindings.rainfall = tbl_data;
return data;
})
.then(yahoo.make_rainfall_message)
.then(messages => {
if (messages.length) {
context.bindings.outputQueueItem = {
"to" : process.env.LINE_PUSH_TO,
"messages" : messages
};
context.bindings.outputBlob["last_date"] = new Date();
}
context.done();
})
.catch(res => {
context.log(res);
context.done();
})
}
|
JavaScript
| 0.000499 |
@@ -1797,25 +1797,35 @@
s.outputBlob
-%5B
+ = %7B%0A%09%09
%22last_date%22%5D
@@ -1823,19 +1823,18 @@
st_date%22
-%5D =
+ :
new Dat
@@ -1836,17 +1836,20 @@
w Date()
-;
+%0A%09%09%7D
%0A
|
8a8333ad256f4893bb53272edb8fefd1d944c4c7
|
Remove console.log form moment_init.js
|
app/assets/javascripts/moment_init.js
|
app/assets/javascripts/moment_init.js
|
var moment = function() {
$('.date').each(function() {
console.log('test');
var date = $(this).data('date');
var date_formatted = moment(date).startOf('minute').fromNow();
$(this).text(date_formatted);
});
};
$(document).ready(moment);
$(document).ajaxComplete(moment);
$(document).on('page:load', moment);
|
JavaScript
| 0.000002 |
@@ -55,32 +55,8 @@
%7B%0D%0A
-%09%09console.log('test');%0D%0A
%09%09va
|
22dc487a724f02bdff22d3d3a2b5ec42b6799258
|
Rename stream_list_hash -> stream_set
|
zephyr/static/js/subs.js
|
zephyr/static/js/subs.js
|
var subs = (function () {
var exports = {};
var stream_list_hash = {};
function case_insensitive_subscription_index(stream_name) {
var i;
var name = stream_name.toLowerCase();
for (i = 1; i < stream_list.length; i++) {
if (name === stream_list[i].toLowerCase()) {
return i;
}
}
return -1;
}
function add_to_stream_list(stream_name) {
if (!exports.have(stream_name)) {
stream_list.push(stream_name);
stream_list_hash[stream_name.toLowerCase()] = true;
$('#subscriptions_table').prepend(templates.subscription({subscription: stream_name}));
}
}
function remove_from_stream_list(stream_name) {
delete stream_list_hash[stream_name.toLowerCase()];
var removal_index = case_insensitive_subscription_index(stream_name);
if (removal_index !== -1) {
stream_list.splice(removal_index, 1);
}
}
exports.fetch = function () {
$.ajax({
type: 'POST',
url: 'json/subscriptions/list',
dataType: 'json',
timeout: 10*1000,
success: function (data) {
$('#subscriptions_table tr').remove();
if (data) {
$.each(data.subscriptions, function (index, name) {
$('#subscriptions_table').append(templates.subscription({subscription: name}));
});
}
$('#streams').focus().select();
},
error: function (xhr) {
report_error("Error listing subscriptions", xhr, $("#subscriptions-status"));
}
});
};
exports.subscribe_for_send = function (stream, prompt_button) {
$.ajax({
type: 'POST',
url: '/json/subscriptions/add',
// The next line is a total hack to format our stream as
// that simplejson will parse as a 1-element array
data: {"streams": '["' + stream + '"]' },
dataType: 'json',
timeout: 10*60*1000, // 10 minutes in ms
success: function (response) {
add_to_stream_list(stream);
compose.finish();
prompt_button.stop(true).fadeOut(500);
},
error: function (xhr, error_type, exn) {
report_error("Unable to subscribe", xhr, $("#home-error"));
}
});
};
exports.have = function (stream_name) {
return (stream_list_hash[stream_name.toLowerCase()] === true);
};
$(function () {
var i;
// Populate stream_list_hash with data handed over to client-side template.
for (i = 0; i < stream_list.length; i++) {
stream_list_hash[stream_list[i].toLowerCase()] = true;
}
// FIXME: It would be nice to move the UI setup into ui.js.
$("#current_subscriptions").ajaxForm({
dataType: 'json', // This seems to be ignored. We still get back an xhr.
success: function (resp, statusText, xhr, form) {
var name = $.parseJSON(xhr.responseText).data;
$('#subscriptions_table').find('button[value="' + name + '"]').parents('tr').remove();
remove_from_stream_list(name);
composebox_typeahead.update_autocomplete();
report_success("Successfully removed subscription to " + name,
$("#subscriptions-status"));
},
error: function (xhr) {
report_error("Error removing subscription", xhr, $("#subscriptions-status"));
}
});
$("#add_new_subscription").on("submit", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/json/subscriptions/add",
dataType: 'json', // This seems to be ignored. We still get back an xhr.
// The next line is a total hack to format our stream as
// that simplejson will parse as a 1-element array
data: {"streams": '["' + $("#streams").val() + '"]' },
success: function (resp, statusText, xhr, form) {
$("#streams").val("");
var name, res = $.parseJSON(xhr.responseText);
if (res.subscribed.length === 0) {
name = res.already_subscribed[0];
report_success("Already subscribed to " + name, $("#subscriptions-status"));
} else {
name = res.subscribed[0];
report_success("Successfully added subscription to " + name,
$("#subscriptions-status"));
}
add_to_stream_list(name);
$("#streams").focus();
},
error: function (xhr) {
report_error("Error adding subscription", xhr, $("#subscriptions-status"));
$("#streams").focus();
}
});
});
});
return exports;
}());
|
JavaScript
| 0.000001 |
@@ -50,25 +50,19 @@
stream_
-list_hash
+set
= %7B%7D;%0A%0A
@@ -462,33 +462,27 @@
stream_
-list_hash
+set
%5Bstream_name
@@ -672,33 +672,27 @@
lete stream_
-list_hash
+set
%5Bstream_name
@@ -2314,33 +2314,27 @@
urn (stream_
-list_hash
+set
%5Bstream_name
@@ -2414,25 +2414,19 @@
stream_
-list_hash
+set
with da
@@ -2531,17 +2531,11 @@
eam_
-list_hash
+set
%5Bstr
|
2bf7b287d4381ff37643113be82084a1425ab158
|
update commands usage
|
cli/commands.js
|
cli/commands.js
|
/**
* Copyright 2013-2021 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see https://www.jhipster.tech/
* for more information.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const defaultCommands = {
app: {
desc: '[Default] Create a new JHipster application based on the selected options',
},
aws: {
desc: 'Deploy the current application to Amazon Web Services',
},
'aws-containers': {
desc: 'Deploy the current application to Amazon Web Services using ECS',
},
'azure-app-service': {
desc: 'Deploy the current application to Azure App Service',
},
'azure-spring-cloud': {
desc: 'Deploy the current application to Azure Spring Cloud',
},
'ci-cd': {
desc: 'Create pipeline scripts for popular Continuous Integration/Continuous Deployment tools',
},
cloudfoundry: {
desc: 'Generate a `deploy/cloudfoundry` folder with a specific manifest.yml to deploy to Cloud Foundry',
},
'docker-compose': {
desc: 'Create all required Docker deployment configuration for the selected applications',
},
download: {
desc: 'Download jdl file from template repository',
cliOnly: true,
argument: ['<jdlFiles...>'],
},
entity: {
desc: 'Create a new JHipster entity: JPA entity, Spring server-side components and Angular client-side components',
},
entities: {
desc: 'Regenerate entities',
},
'export-jdl': {
desc: 'Create a JDL file from the existing entities',
},
gae: {
desc: 'Deploy the current application to Google App Engine',
},
heroku: {
desc: 'Deploy the current application to Heroku',
},
info: {
desc: 'Display information about your current project and system',
},
jdl: {
alias: 'import-jdl',
argument: ['[jdlFiles...]'],
cliOnly: true,
options: [
{
option: '--fork',
desc: 'Run generators using fork',
},
{
option: '--interactive',
desc: 'Run generation in series so that questions can be interacted with',
},
{
option: '--json-only',
desc: 'Generate only the JSON files and skip entity regeneration',
default: false,
},
{
option: '--ignore-application',
desc: 'Ignores application generation',
default: false,
},
{
option: '--ignore-deployments',
desc: 'Ignores deployments generation',
default: false,
},
{
option: '--skip-sample-repository',
desc: 'Disable fetching sample files when the file is not a URL',
default: false,
},
{
option: '--inline <value>',
desc: 'Pass JDL content inline. Argument can be skipped when passing this',
},
{
option: '--skip-user-management',
desc: 'Skip the user management module during app generation',
},
],
desc: `Create entities from the JDL file/content passed in argument.
By default everything is run in parallel. If you like to interact with the console use '--interactive' flag.`,
help: `
Arguments:
jdlFiles # The JDL file names Type: String[] Required: true if --inline is not set
Example:
jhipster jdl myfile.jdl
jhipster jdl myfile.jdl --interactive
jhipster jdl myfile1.jdl myfile2.jdl
jhipster jdl --inline "application { config { baseName jhapp, testFrameworks [protractor] }}"
jhipster jdl --inline \\
"application {
config {
baseName jhapp,
testFrameworks [protractor]
}
}"
`,
},
kubernetes: {
alias: 'k8s',
desc: 'Deploy the current application to Kubernetes',
},
'kubernetes-helm': {
alias: 'helm',
desc: 'Deploy the current application to Kubernetes using Helm package manager',
},
'kubernetes-knative': {
alias: 'knative',
desc: 'Deploy the current application to Kubernetes using knative constructs',
},
languages: {
desc: 'Select languages from a list of available languages. The i18n files will be copied to the /webapp/i18n folder',
},
openshift: {
desc: 'Deploy the current application to OpenShift',
},
page: {
desc: 'Create a new page. (Supports vue clients)',
},
'spring-service': {
alias: 'service',
desc: 'Create a new Spring service bean',
},
'spring-controller': {
desc: 'Create a new Spring controller',
},
'openapi-client': {
desc: 'Generates java client code from an OpenAPI/Swagger definition',
},
upgrade: {
desc: 'Upgrade the JHipster version, and upgrade the generated application',
},
'upgrade-config': {
desc: 'Upgrade the JHipster configuration',
},
};
module.exports = defaultCommands;
|
JavaScript
| 0.000001 |
@@ -3658,16 +3658,23 @@
e names
+or URL
Type: St
@@ -3790,60 +3790,246 @@
l --
-interactive%0A jhipster jdl myfile1.jdl myfile2.jdl
+fork%0A jhipster jdl myfile1.jdl myfile2.jdl%0A jhipster jdl https://gist.githubusercontent.com/user/path/app.jdl%0A jhipster jdl jdl-name-from-jdl-samples-repo.jdl (just pass any file name from https://github.com/jhipster/jdl-samples)
%0A
|
5a10b5367e93662859b697a1c8e8e06534b49fa1
|
Fix race in gulpfile.js
|
gulpfile.js
|
gulpfile.js
|
var babelify = require('babelify');
var browserify = require('browserify');
var gulp = require('gulp');
var concat = require('gulp-concat');
var headerfooter = require('gulp-headerfooter');
var replace = require('gulp-replace');
var streamify = require('gulp-streamify');
var strip = require('gulp-strip-comments');
var spawn = require('child_process').spawn;
var source = require('vinyl-source-stream');
var paths = {
scripts: [
'src/es5-polyfills.js',
'src/Dollchan_Extension_Tools.es6.user.js',
'Dollchan_Extension_Tools.meta.js'
],
modules: [
'src/modules/Head.js',
'src/modules/DefaultCfg.js',
'src/modules/Localization.js',
'src/modules/GlobalVars.js',
'src/modules/Utils.js',
'src/modules/Storage.js',
'src/modules/Panel.js',
'src/modules/WindowUtils.js',
'src/modules/WindowVidHid.js',
'src/modules/WindowFavorites.js',
'src/modules/WindowSettings.js',
'src/modules/MenuPopups.js',
'src/modules/Hotkeys.js',
'src/modules/ContentLoad.js',
'src/modules/TimeCorrection.js',
'src/modules/Players.js',
'src/modules/Ajax.js',
'src/modules/Pages.js',
'src/modules/Spells.js',
'src/modules/Form.js',
'src/modules/FormSubmit.js',
'src/modules/FormFile.js',
'src/modules/FormCaptcha.js',
'src/modules/Posts.js',
'src/modules/PostPreviews.js',
'src/modules/PostImages.js',
'src/modules/PostBuilders.js',
'src/modules/RefMap.js',
'src/modules/Threads.js',
'src/modules/ThreadUpdater.js',
'src/modules/DelForm.js',
'src/modules/Browser.js',
'src/modules/BoardDefaults.js',
'src/modules/BoardCustom.js',
'src/modules/Misc.js',
'src/modules/SvgIcons.js',
'src/modules/Css.js',
'src/modules/Main.js',
'src/modules/Tail.js'
]
};
gulp.task('updatecommit', function(cb) {
var git = spawn('git', ['rev-parse', 'HEAD']);
var stdout, stderr;
git.stdout.on('data', function(data) {
stdout = String(data);
});
git.stderr.on('data', function(data) {
stderr = String(data);
});
git.on('close', function(code) {
if(code !== 0) {
throw 'Git error:\n' + (stdout ? stdout + '\n' : '') + stderr;
}
gulp.src('src/Dollchan_Extension_Tools.es6.user.js')
.pipe(replace(/^const commit = '[^']*';$/m, 'const commit = \'' + stdout.trim().substr(0, 7) + '\';'))
.pipe(gulp.dest('./src/'))
.on('end', cb);
});
});
gulp.task('makees5', ['updatecommit'], function() {
return browserify(['./src/es5-polyfills.js', './src/Dollchan_Extension_Tools.es6.user.js'])
.transform(babelify)
.bundle()
.pipe(source('Dollchan_Extension_Tools.user.js'))
.pipe(streamify(strip()))
.pipe(streamify(headerfooter('(function de_main_func_outer(localData) {\n', '})(null);')))
.pipe(streamify(headerfooter.header('Dollchan_Extension_Tools.meta.js')))
.pipe(gulp.dest('./'));
});
gulp.task('makees6', function() {
return gulp.src(paths.modules)
.pipe(concat('Dollchan_Extension_Tools.es6.user.js', {newLine: '\n'}))
.pipe(gulp.dest('./src/'));
});
gulp.task('make', ['makees6', 'makees5']);
gulp.task('makeall', ['make'], function() {
return gulp.src('./Dollchan_Extension_Tools.user.js')
.pipe(replace('global.regenerator', 'window.regenerator'))
.pipe(gulp.dest('./dollchan-extension/data'));
});
gulp.task('watch', function() {
gulp.watch(paths.scripts, ['make']);
});
gulp.task('default', ['make', 'watch']);
|
JavaScript
| 0.000034 |
@@ -2144,41 +2144,20 @@
src/
-Dollchan_Extension_Tools.es6.user
+modules/Head
.js'
@@ -2284,22 +2284,27 @@
p.dest('
-./
src/
+modules
'))%0A%09%09%09.
@@ -2343,19 +2343,20 @@
sk('make
+:
es
-5
+6
', %5B'upd
@@ -2373,32 +2373,218 @@
%5D, function() %7B%0A
+%09return gulp.src(paths.modules)%0A%09%09.pipe(concat('Dollchan_Extension_Tools.es6.user.js', %7BnewLine: '%5Cn'%7D))%0A%09%09.pipe(gulp.dest('src'));%0A%7D);%0A%0Agulp.task('make:es5', %5B'make:es6'%5D, function() %7B%0A
%09return browseri
@@ -2588,18 +2588,16 @@
erify(%5B'
-./
src/es5-
@@ -2612,18 +2612,16 @@
s.js', '
-./
src/Doll
@@ -2963,184 +2963,8 @@
st('
-./'));%0A%7D);%0A%0Agulp.task('makees6', function() %7B%0A%09return gulp.src(paths.modules)%0A%09%09.pipe(concat('Dollchan_Extension_Tools.es6.user.js', %7BnewLine: '%5Cn'%7D))%0A%09%09.pipe(gulp.dest('./src/
'));
@@ -2997,19 +2997,9 @@
make
-es6', 'make
+:
es5'
@@ -3065,18 +3065,16 @@
lp.src('
-./
Dollchan
@@ -3184,10 +3184,8 @@
st('
-./
doll
|
f2f315e17533f948d8c618108403e02f5c94fe48
|
Fix onhashchange event.
|
src/main.js
|
src/main.js
|
require(['mustache', 'browsers', 'features'], function (Mustache, browsers, features) {
var featureTemplate = document.getElementById('feature').innerHTML,
resultCountTemplate = document.getElementById('count').innerHTML,
resultCountWrapper = document.getElementById('result-count')
resultsWrapper = document.getElementById('results'),
splashWrapper = document.getElementById('splash-page'),
search = document.getElementById('search');
function find(input) {
var result = [];
function findAux(feature) {
var keywords = feature.keywords || [];
keywords.push(feature.name);
for (var i = 0; i < keywords.length; i++) {
if (keywords[i].indexOf(input) !== -1) {
result.push(feature);
break;
}
}
if (feature.features) {
feature.features.forEach(findAux);
}
}
Object.keys(features).forEach(function (featureId) {
var feature = features[featureId];
findAux(features[featureId]);
});
return result.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
}
function debounce(fn, n) {
var timeout,
args;
return function () {
args = arguments;
var later = function () {
timeout = null;
fn.apply(null, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, n);
};
}
function renderFeatures(features) {
resultsWrapper.innerHTML = features.map(function (feature) {
return Mustache.render(featureTemplate, feature);
}).join('');
}
function renderResultCount(features) {
resultCountWrapper.innerHTML = Mustache.render(resultCountTemplate, { number: features.length, singular: features.length === 1 });
}
var updateHash = debounce(function (value) {
location.hash = "#" + encodeURIComponent(value);
}, 1000);
search.addEventListener('input', function (e) {
var input = search.value.trim();
if (document.documentElement.classList.contains("splash")) {
document.documentElement.classList.remove("splash");
document.documentElement.classList.add("search");
}
if (input !== "") {
var results = find(input);
renderFeatures(results);
renderResultCount(results);
updateHash(input);
} else {
renderFeatures([]);
updateHash("");
renderResultCount([]);
}
}, true);
var hash = decodeURIComponent(location.hash.trim().replace('#', ''));
if (hash !== "") {
search.value = hash;
var results = find(hash);
renderFeatures(results);
renderResultCount(results);
document.documentElement.classList.add('search');
} else {
document.documentElement.classList.add('splash');
}
});
|
JavaScript
| 0 |
@@ -1765,16 +1765,547 @@
);%0A %7D%0A%0A
+ function onHashChange() %7B%0A var hash = decodeURIComponent(location.hash.replace('#', ''));%0A%0A if (!/%5Cs+/.test(hash) && hash.length !== 0) %7B%0A search.value = hash;%0A var results = find(hash.trim());%0A renderFeatures(results);%0A renderResultCount(results);%0A document.documentElement.classList.remove('splash');%0A document.documentElement.classList.add('search');%0A %7D else %7B%0A document.documentElement.classList.remove('search');%0A document.documentElement.classList.add('splash');%0A %7D%0A %7D%0A%0A
var up
@@ -2334,21 +2334,16 @@
nction (
-value
) %7B%0A
@@ -2383,21 +2383,35 @@
mponent(
-value
+search.value.trim()
);%0A %7D,
@@ -2418,17 +2418,16 @@
1000);%0A%0A
-%0A
search
@@ -2502,24 +2502,50 @@
ue.trim();%0A%0A
+ if (input !== %22%22) %7B%0A
if (docu
@@ -2595,32 +2595,34 @@
lash%22)) %7B%0A
+
document.documen
@@ -2654,24 +2654,26 @@
(%22splash%22);%0A
+
docume
@@ -2724,34 +2724,11 @@
-%7D%0A%0A if (input !== %22%22) %7B
+ %7D
%0A
@@ -2831,41 +2831,210 @@
- updateHash(input);%0A %7D else %7B
+%7D else %7B%0A if (document.documentElement.classList.contains(%22search%22)) %7B%0A document.documentElement.classList.remove(%22search%22);%0A document.documentElement.classList.add(%22splash%22);%0A %7D
%0A
@@ -3060,30 +3060,8 @@
%5D);%0A
- updateHash(%22%22);%0A
@@ -3097,351 +3097,93 @@
%7D%0A
-%7D, true);%0A%0A var hash = decodeURIComponent(location.hash.trim().replace('#', ''));%0A%0A if (hash !== %22%22) %7B%0A search.value = hash;%0A var results = find(hash);%0A renderFeatures(results);%0A renderResultCount(results);%0A document.documentElement.classList.add('search');%0A %7D else %7B%0A document.documentElement.classList.add('splash');%0A %7D
+ updateHash();%0A %7D, true);%0A%0A onHashChange();%0A%0A window.onhashchange = onHashChange;
%0A%7D);
|
b7641fd39af0a4d35ee8077f0660cc96fd7ae687
|
use correct name for controller
|
client/index.js
|
client/index.js
|
/*
* Copyright 2015 CareerBuilder, LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
"use strict";
var app = angular.module('cloudseed', ['ngRoute', 'ngCookies', 'toastr']);
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$routeProvider.when('/login', {
controller: 'LoginCtrl',
templateUrl: 'views/login.html'
})
.when('/signup', {
controller: 'SignupCtrl',
templateUrl: 'views/signup.html'
})
.when('/config', {
controller: 'ConfigCtrl',
templateUrl: 'views/config.html',
resolve:{
auth: ["authservice", function(authservice) {return authservice.hasAccess();}]
}
})
.when('/', {
controller: 'PartCtrl',
templateUrl: 'views/parts.html',
resolve:{
auth: ["authservice", function(authservice) {return authservice.hasAccess();}]
}
})
.otherwise({redirectTo: '/'});
$httpProvider.interceptors.push('httpRequestInterceptor');
}]);
app.controller('PageController', function($http, $scope, $location, toastr, authservice){
$scope.auth = authservice;
$scope.loggedin = function(){
if(authservice.authid()){
return true;
}
return false;
}
$scope.logOut=function(){
$scope.user={};
authservice.clearAuth();
$location.path('/login');
}
});
app.directive('partsSidebar', function() {
return {
restrict: 'E',
controller: 'PartsCtrl',
templateUrl: 'views/sidebar.html'
}
});
app.factory('httpRequestInterceptor', function ($cookieStore) {
return {
request: function(config){
var auth_token = $cookieStore.get('c_s66d') || "";
config.headers['Authorization'] = auth_token;
return config;
}
};
});
app.run(["$rootScope", "$location", "toastr", function($rootScope, $location, toastr) {
$rootScope.$on("$routeChangeError", function(event, current, previous, eventObj) {
if (eventObj.authenticated === false) {
toastr.error('Please Log in First');
$location.path("/login");
}
});
}]);
|
JavaScript
| 0.000021 |
@@ -1894,17 +1894,16 @@
r: 'Part
-s
Ctrl',%0D%0A
|
0d93e43560bc4574ab0d11b5c65e46720c55d7d3
|
Fix usage of notifier-client
|
lib/signup-api/lib/signup.js
|
lib/signup-api/lib/signup.js
|
/**
* Module dependencies.
*/
var log = require('debug')('democracyos:signup');
var utils = require('lib/utils');
var mongoose = require('mongoose');
var api = require('lib/db-api');
var mailer = require('lib/mailer').mandrillMailer;
var jade = require('jade');
var fs = require('fs');
var t = require('t-component');
var config = require('lib/config');
var url = require('url');
var notifier = require('notifier-client')(config.notifications);
/**
* Citizen Model
*/
var Citizen = mongoose.model('Citizen');
var path = require('path');
var resolve = path.resolve;
var rawJade = fs.readFileSync(resolve(__dirname, '../mail.jade'));
var template = jade.compile(rawJade);
/**
* Signups a citizen
*
* @param {Object} profile object with local signup data
* @param {Obehect} meta user's ip, user-agent, etc
* @param {Function} callback Callback accepting `err` and `citizen`
* @api public
*/
exports.doSignUp = function doSignUp (profile, meta, callback) {
var citizen = new Citizen(profile);
log('new citizen [%s] from Local signup [%s]', citizen.id, profile.email);
citizen.avatar = 'http://gravatar.com/avatar/'.concat(utils.md5(citizen.email)).concat('?d=mm&size=200');
citizen.firstName = profile.firstName;
citizen.lastName = profile.lastName;
citizen.reference = profile.reference;
if (config('env') == 'development') citizen.emailValidated = true;
Citizen.register(citizen, profile.password, function(err, citizen) {
if (err) return callback(err);
log('Saved citizen [%s]', citizen.id);
sendValidationEmail(citizen, 'signup', meta, callback);
});
}
/**
* Validates user email if a valid token is provided
*
* @param {Object} formData contains token
* @param {Function} callback Callback accepting `err` and `citizen`
* @api public
*/
exports.emailValidate = function emailValidate (formData, callback) {
log('email validate requested. token : [%s]', formData.token);
var tokenId = formData.token;
api.token.get(tokenId, function (err, token){
log('Token.findById result err : [%j] token : [%j]', err, token);
if (err) return callback(err);
if (!token) {
return callback(new Error("No token for id " + tokenId));
}
log('email validate requested. token : [%s]. token verified', formData.token);
api.citizen.get(token.user, function (err, citizen){
if (err) return callback(err);
log('about email validate. citizen : [%s].', citizen.id);
citizen.emailValidated = true;
citizen.save(function (err) {
if (err) return callback(err);
log('Saved citizen [%s]', citizen.id);
token.remove(function (err) {
if (err) return callback(err);
log('Token removed [%j]', token);
return callback(err, citizen);
});
});
});
});
}
/**
* Sends a new validation email to a citizen
*
* @param {Object} profile object with the email address
* @param {Obehect} meta user's ip, user-agent, etc
* @param {Function} callback Callback accepting `err` and `citizen`
* @api public
*/
exports.resendValidationEmail = function resendValidationEmail (profile, meta, callback) {
log('Resend validation email to [%s] requested', profile.email);
api.citizen.getByEmail(profile.email, function(err, citizen) {
if (err) return callback(err);
if (!citizen) return callback(new Error(t('No citizen found with that email address')));
log('Resend validation email to citizen [%j] requested', citizen);
sendValidationEmail(citizen, 'resend-validation', meta, callback);
});
}
/**
* Creates a token and sends a validation email to a citizen
*
* @param {Object} citizen to send the email to
* @param {Obehect} meta user's ip, user-agent, etc
* @param {Function} callback Callback accepting `err` and `citizen`
*/
function sendValidationEmail(citizen, event, meta, callback) {
api.token.createEmailValidationToken(citizen, meta, function (err, token) {
if (err) return callback(err);
log('email validation token created %j', token);
// var subject = t('DemocracyOS - Welcome!');
var validateUrl = url.format({
protocol: config('protocol')
, hostname: config('host')
, port: config('publicPort')
, pathname: '/signup/validate/' + token.id
, query: (citizen.reference ? { reference: citizen.reference } : null)
});
// var htmlBody = template({
// citizenName: citizen.fullName,
// validateUrl: validateUrl,
// t: t
// });
var payload = {
user: citizen.email,
event: event,
validateUrl: validateUrl
}
notifier.notify(event)
.to(citizen.email)
.withData(validateUrl)
.send(function (err, data) {
log('Error when sending notification for event %s to user %j', event, citizen);
if (err) return callback(err);
return callback(null, data);
})
// mailer.send(citizen, subject, htmlBody, { tags: [token.scope] }, function (err) {
// if (err) return callback(err);
// log('email validation mail sent to %s', citizen.email);
// return callback(err, citizen);
// });
});
}
|
JavaScript
| 0.000016 |
@@ -4662,16 +4662,19 @@
ithData(
+ %7B
validate
@@ -4676,16 +4676,32 @@
idateUrl
+: validateUrl %7D
)%0A
@@ -4725,24 +4725,45 @@
rr, data) %7B%0A
+ if (err) %7B%0A
log(
@@ -4842,32 +4842,25 @@
n);%0A
-if (err)
+
return call
@@ -4869,16 +4869,26 @@
ck(err);
+%0A %7D
%0A%0A
|
284d554a67664e81c843f72d20e091522b8f9968
|
fix (loader): fix the transition out when the application has loaded
|
client/index.js
|
client/index.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import Router from './router';
import { Config } from "./model/";
import './assets/css/reset.scss';
window.addEventListener("DOMContentLoaded", () => {
const className = 'ontouchstart' in window ? 'touch-yes' : 'touch-no';
document.body.classList.add(className);
const $loader = document.querySelector("#nyan_loader");
function render(){
ReactDOM.render(<Router/>, document.getElementById("main"));
return Promise.resolve();
};
function waitFor(n){
return new Promise((done) => {
window.setTimeout(() => {
window.requestAnimationFrame(() => done());
}, n);
});
}
function removeLoaderWithAnimation(){
if(!$loader) return Promise.resolve();
$loader.classList.add("done");
return new Promise((done) => {
window.setTimeout(() => requestAnimationFrame(done), 500);
});
}
function removeLoader(){
if($loader) $loader.remove();
return Promise.resolve();
}
Config.refresh().then(() => {
const timeSinceBoot = new Date() - window.initTime;
if(timeSinceBoot >= 1500){
const timeoutToAvoidFlickering = timeSinceBoot > 2500 ? 0 : 500;
return waitFor(timeoutToAvoidFlickering)
.then(removeLoaderWithAnimation)
.then(render);
}
return removeLoader().then(render);
});
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/assets/worker/cache.js').catch(function(error) {
console.log('ServiceWorker registration failed:', error);
});
}
});
|
JavaScript
| 0.000001 |
@@ -380,15 +380,10 @@
(%22#n
-yan_loa
+-l
der%22
|
c26db41711193ef946aebb4b8e8ed4634d57fb6a
|
extend draggable view
|
app/components/DraggableView/index.js
|
app/components/DraggableView/index.js
|
import React, { Component, PropTypes } from 'react';
import { Animated, PanResponder } from 'react-native';
const SWIPE_THRESHOLD = 80;
export default class DraggableView extends Component {
constructor (props) {
super(props);
this.state = {
pan: new Animated.ValueXY(), // inits to zero
};
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: Animated.event([null, {
dx: props.allowX ? this.state.pan.x : 0, // x,y are Animated.Value
dy: props.allowY ? this.state.pan.y : 0,
}]),
onPanResponderRelease: (e, { vx, vy }) => {
this.state.pan.flattenOffset();
if (Math.abs(this.state.pan.y._value) > SWIPE_THRESHOLD) {
this.props.onRelease();
Animated.decay(this.state.pan, {
velocity: { x: vx, y: vy },
deceleration: 0.98,
}).start();
} else {
Animated.spring(this.state.pan, {
toValue: { x: 0, y: 0 },
friction: 8,
tension: 80,
}).start();
}
},
});
}
render () {
return (
<Animated.View
{...this._panResponder.panHandlers}
style={[this.props.style, this.state.pan.getLayout()]}>
{this.props.children}
</Animated.View>
);
}
};
DraggableView.propTypes = {
allowX: PropTypes.bool,
allowY: PropTypes.bool,
onRelease: PropTypes.func,
};
DraggableView.defaultProps = {
allowX: true,
allowY: true,
style: {},
};
|
JavaScript
| 0 |
@@ -411,16 +411,107 @@
erMove:
+(e, gestureState) =%3E %7B%0A%09%09%09%09if (this.props.onMove) this.props.onMove(e, gestureState);%0A%0A%09%09%09%09
Animated
@@ -522,24 +522,25 @@
nt(%5Bnull, %7B%0A
+%09
%09%09%09%09dx: prop
@@ -602,16 +602,17 @@
lue%0A%09%09%09%09
+%09
dy: prop
@@ -651,11 +651,35 @@
%0A%09%09%09
+%09
%7D%5D)
+(e, gestureState);%0A%09%09%09%7D
,%0A%09%09
@@ -756,24 +756,25 @@
nOffset();%0A%0A
+%0A
%09%09%09%09if (Math
@@ -825,24 +825,50 @@
OLD) %7B%0A%09%09%09%09%09
+if (this.props.onRelease)
this.props.o
@@ -876,16 +876,29 @@
Release(
+e, %7B vx, vy %7D
);%0A%09%09%09%09%09
@@ -951,22 +951,81 @@
y: %7B
- x: vx, y: vy
+%0A%09%09%09%09%09%09%09x: props.allowX ? vx : 0,%0A%09%09%09%09%09%09%09y: props.allowY ? vy : 0,%0A%09%09%09%09%09%09
%7D,%0A%09
@@ -1503,16 +1503,41 @@
s.bool,%0A
+%09onMove: PropTypes.func,%0A
%09onRelea
|
c71372eb8ff1b6ae9e118ea4c3c38926c21e781c
|
Remove Autoinitialization
|
src/main.js
|
src/main.js
|
/*! AtFramework | Andrey Tkachenko | MIT License | github.com/andreytkachenko/atframework */
var ATF = {
runindex: 0,
dependencies: {},
invoke: function (deps, func) {
return func.apply(null, this.resolve(deps));
},
resolve: function (deps) {
var dependencies = this.dependencies;
return deps.map(function (i) {
return dependencies[i].func();
});
},
register: function (name, deps, func, type) {
if (this.dependencies[name]) {
throw Error(name + ' is already registered!');
}
this.dependencies[name] = {
func: func(),
name: name,
deps: deps,
type: type,
resolving: false,
resolved: false
};
},
controller: function (name, deps, func) {
var self = this;
this.register(name, deps, function () {
var called;
return function () {
if (!called) {
var resolved = self.resolve(deps);
func.apply(null, resolved);
called = true;
}
return {
scope: resolved[deps.indexOf('$scope')]
}
}
}, 'controller');
},
factory: function (name, deps, func) {
var self = this;
this.register(name, deps, function () {
return function () {
return func.apply(null, self.resolve(deps));
}
}, 'factory');
},
service: function (name, deps, func) {
var self = this;
this.register(name, deps, function () {
var instance;
return function () {
if (!instance) {
var resolved = self.resolve(deps);
instance = func.apply(null, resolved);
}
return instance
}
}, 'service');
},
view: function (name, deps, func) {
var self = this;
this.register(name, deps, function () {
return function () {
return func.apply(null, self.resolve(deps));
}
}, 'view');
return this;
},
config: function (name, value) {
this.register(name, null, function () {
return function () {
return value;
}
}, 'config');
return this;
},
run: function (deps, func) {
var self = this;
this.register('run' + this.runindex, deps, function () {
return function () {
return func.apply(null, self.resolve(deps));
}
}, 'run');
},
init: function () {
var runnable = [];
var dependencies = this.dependencies;
var resolve = function (name) {
var item;
if (!dependencies[name]) {
throw Error('Unknown dependency '+name);
}
item = dependencies[name];
if (item.resolving)
throw Error('Recursive dependency');
if (item.resolved) {
return;
}
item.resolving = true;
if (item.deps) {
for (var i = 0; i < item.deps.length; i++) {
resolve(item.deps[i]);
}
}
item.resolving = false;
item.resolved = true;
};
for (var i in this.dependencies) {
if (this.dependencies.hasOwnProperty(i)) {
if (this.dependencies[i].resolved) continue;
if (this.dependencies[i].resolving) throw Error('Recursive dependency');
resolve(i);
if (this.dependencies[i].type === 'run') {
runnable.push(this.dependencies[i].func);
}
}
}
for (var i=0; i<runnable.length; i++) {
runnable[i]();
}
}
};
ATF.factory('$hash', [], function () {
return {
map: {},
objMap: {},
objKeys: {},
index: 0,
gen: function (prefix) {
return prefix + (this.index++);
},
hash: function (obj, recursive) {
var _h;
switch (typeof obj) {
case 'string':
this.map[obj] = this.map[obj] || this.gen('s');
return this.map[obj];
case 'number':
this.map[obj] = this.map[obj] || this.gen('n');
return this.map[obj];
case 'function':
obj.$$hash = obj.$$hash || this.gen('f');
return obj.$$hash;
case 'object':
if (recursive) {
_h = '';
for (var key in obj) {
if (obj.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
this.objKeys[key] = this.objKeys[key] || this.gen('k');
_h += '|' + this.objKeys[key] + ':' + this.hash(obj[key], true);
}
}
this.objMap[_h] = this.objMap[_h] || this.gen('o');
obj.$$hash = obj.$$hash === this.objMap[_h] ? obj.$$hash: this.objMap[_h];
} else {
obj.$$hash = obj.$$hash || this.gen('o');
}
return obj.$$hash;
}
}
};
});
ATF.config('jQuery', jQuery);
$(document).ready(function () {
ATF.init();
});
|
JavaScript
| 0.000001 |
@@ -5580,88 +5580,4 @@
%0A%7D);
-%0A%0AATF.config('jQuery', jQuery);%0A%0A$(document).ready(function () %7B%0A ATF.init();%0A%7D);
|
c8070118fee7d4d32c1725aed83a16c07904025a
|
Fix replacements in wrong files
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp');
var bower = require('main-bower-files');
var browserify = require('browserify');
var concat = require('gulp-concat');
var minifyCss = require('gulp-minify-css');
var minifyHtml = require('gulp-minify-html');
var reactify = require('reactify');
var rev = require('gulp-rev');
var rimraf = require('rimraf');
var useref = require('gulp-useref');
var filter = require('gulp-filter');
var revReplace = require('gulp-rev-replace');
var runSequence = require('run-sequence');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
gulp.task('clean', function(cb) {
rimraf('dist/', cb);
});
gulp.task('browserify', ['clean'], function() {
var b = browserify();
b.transform(reactify); // use the reactify transform
b.add('./client/scripts/app.jsx');
return b.bundle()
.pipe(source('app.js'))
.pipe(gulp.dest('dist/'));
});
gulp.task('styles', ['clean'], function() {
gulp.src(['bower_components/bootstrap/dist/css/bootstrap.css', 'client/css/*'])
.pipe(concat('style.css'))
.pipe(gulp.dest('dist/'));
});
gulp.task('copy', ['clean'], function() {
gulp.src(['public/*'])
.pipe(gulp.dest('dist/'));
});
gulp.task('default', ['browserify', 'styles', 'copy'], function() {});
gulp.task('dist', ['default'], function(cb) {
var jsFilter = filter("**/*.js");
var cssFilter = filter("**/*.css");
var assets = useref.assets();
return gulp.src('dist/index.html')
.pipe(assets)
.pipe(jsFilter)
.pipe(uglify()) // Minify any javascript sources
.pipe(jsFilter.restore())
.pipe(cssFilter)
.pipe(minifyCss()) // Minify any CSS sources
.pipe(cssFilter.restore())
.pipe(rev()) // Rename the concatenated files
.pipe(assets.restore())
.pipe(useref())
.pipe(revReplace()) // Substitute in new filenames
.pipe(gulp.dest('dist/'));
});
gulp.task('watch', ['default'], function() {
gulp.watch('client/**/*', ['default']);
});
|
JavaScript
| 0.000013 |
@@ -1519,41 +1519,8 @@
y())
- // Minify any javascript sources
%0A
@@ -1593,34 +1593,8 @@
s())
- // Minify any CSS sources
%0A
@@ -1641,41 +1641,8 @@
v())
- // Rename the concatenated files
%0A
@@ -1711,41 +1711,54 @@
ace(
-)) // Substitute in new filenames
+%7B%0A replaceInExtensions: %5B'.html'%5D%0A %7D))
%0A
|
4a8a000fd42b597994a01d7c0843407080cbad29
|
Resolve with no classes if classPathAdditions are not defined
|
src/services/ldap/strategies/general.js
|
src/services/ldap/strategies/general.js
|
const AbstractLDAPStrategy = require('./interface.js');
/**
* General LDAP functionality
* @implements {AbstractLDAPStrategy}
*/
class GeneralLDAPStrategy extends AbstractLDAPStrategy {
/**
* @public
* @see AbstractLDAPStrategy#getSchoolsQuery
* @returns {Array} Array of Objects containing ldapOu (ldap Organization Path), displayName
* @memberof GeneralLDAPStrategy
*/
getSchools() {
return Promise.resolve([{
displayName: this.config.providerOptions.schoolName,
ldapOu: this.config.rootPath,
}]);
}
/**
* @public
* @see AbstractLDAPStrategy#getUsers
* @returns {Array} Array of Objects containing email, firstName, lastName, ldapDn, ldapUUID, ldapUID,
* (Array) roles = ['teacher', 'student', 'administrator']
* @memberof GeneralLDAPStrategy
*/
getUsers() {
const {
userAttributeNameMapping,
userPathAdditions,
roleType,
roleAttributeNameMapping,
} = this.config.providerOptions;
const options = {
filter: 'objectClass=person',
scope: 'sub',
attributes: [
userAttributeNameMapping.givenName,
userAttributeNameMapping.sn,
userAttributeNameMapping.dn,
userAttributeNameMapping.uuid,
userAttributeNameMapping.uid,
userAttributeNameMapping.mail,
(roleType === 'group') ? 'memberOf' : userAttributeNameMapping.role,
],
};
const rawAttributes = [userAttributeNameMapping.uuid];
const searchArray = userPathAdditions.split(';;');
searchArray.forEach((searchString, index) => {
searchArray[index] = (searchString === '')
? this.config.rootPath
: `${searchString},${this.config.rootPath}`;
});
const promises = searchArray.map((searchPath) => (
this.app.service('ldap').searchCollection(this.config, searchPath, options, rawAttributes)
));
return Promise.all(promises)
.then((results) => results.reduce((all, result) => all.concat(result)), [])
.then((data) => {
const results = [];
data.forEach((obj) => {
const roles = [];
if (roleType === 'group') {
if (!Array.isArray(obj.memberOf)) {
obj.memberOf = [obj.memberOf];
}
if (obj.memberOf.includes(roleAttributeNameMapping.roleStudent)) {
roles.push('student');
}
if (obj.memberOf.includes(roleAttributeNameMapping.roleTeacher)) {
roles.push('teacher');
}
if (obj.memberOf.includes(roleAttributeNameMapping.roleAdmin)) {
roles.push('administrator');
}
if (obj.memberOf.includes(roleAttributeNameMapping.roleNoSc)) {
return;
}
} else {
if (obj[userAttributeNameMapping.role]
=== roleAttributeNameMapping.roleStudent) {
roles.push('student');
}
if (obj[userAttributeNameMapping.role]
=== roleAttributeNameMapping.roleTeacher) {
roles.push('teacher');
}
if (obj[userAttributeNameMapping.role]
=== roleAttributeNameMapping.roleAdmin) {
roles.push('administrator');
}
if (obj[userAttributeNameMapping.role]
=== roleAttributeNameMapping.roleNoSc) {
return;
}
}
if (roles.length === 0) {
return;
}
let firstName = obj[userAttributeNameMapping.givenName];
if (!firstName) {
if (roles.includes('administrator')) {
firstName = 'Admin';
} else if (roles.includes('teacher')) {
firstName = 'Lehrkraft';
} else {
firstName = 'Schüler:in';
}
}
results.push({
email: obj[userAttributeNameMapping.mail],
firstName,
lastName: obj[userAttributeNameMapping.sn],
roles,
ldapDn: obj[userAttributeNameMapping.dn],
ldapUUID: obj[userAttributeNameMapping.uuid],
ldapUID: obj[userAttributeNameMapping.uid],
});
});
return results;
});
}
/**
* @public
* @see AbstractLDAPStrategy#getClasses
* @returns {Array} Array of Objects containing className, ldapDn, uniqueMember
* @memberof GeneralLDAPStrategy
*/
getClasses() {
const {
classAttributeNameMapping,
classPathAdditions,
} = this.config.providerOptions;
if (classPathAdditions !== '') {
const options = {
filter: `${classAttributeNameMapping.description}=*`,
scope: 'sub',
attributes: [
classAttributeNameMapping.dn,
classAttributeNameMapping.description,
classAttributeNameMapping.uniqueMember,
],
};
const searchString = `${classPathAdditions},${this.config.rootPath}`;
return this.app.service('ldap').searchCollection(this.config, searchString, options)
.then((data) => data.map((obj) => ({
className: obj[classAttributeNameMapping.description],
ldapDn: obj[classAttributeNameMapping.dn],
uniqueMembers: obj[classAttributeNameMapping.uniqueMember],
})));
}
}
}
module.exports = GeneralLDAPStrategy;
|
JavaScript
| 0 |
@@ -4862,16 +4862,46 @@
));%0A%09%09%7D%0A
+%09%09return Promise.resolve(%5B%5D);%0A
%09%7D%0A%7D%0A%0Amo
|
8e44f61c1d4b822415ea665e32d4feac00537a84
|
fix semver logic
|
src/main.js
|
src/main.js
|
/*
* Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/* global _spaces */
define(function (require, exports) {
"use strict";
var Promise = require("bluebird");
/**
* The minimum-compatible plugin version number.
*
* @const
* @type {{major: number=, minor: number=, patch: number=}}
*/
var COMPATIBLE_PLUGIN_VERSION = {
major: 1,
minor: 0,
patch: 13
};
/**
* Determine whether v1 is less than or equal to v2.
*
* @private
* @param {{major: number=, minor: number=, patch: number=}} v1
* @param {{major: number=, minor: number=, patch: number=}} v2
* @return {boolean}
*/
var _versionLessThanOrEqualTo = function (v1, v2) {
if (v1.hasOwnProperty("major") && v1.major > v2.major) {
return false;
}
if (v1.hasOwnProperty("minor") && v1.minor > v2.minor) {
return false;
}
if (v1.hasOwnProperty("patch") && v1.patch > v2.patch) {
return false;
}
return true;
};
/**
* Format a version object a string.
*
* @private
* @param {{major: number=, minor: number=, patch: number=}} version
* @return {string}
*/
var _formatVersion = function (version) {
return [version.major, version.minor, version.patch].join(".");
};
/**
* Assert that the current plugin version is compatible with the specified
* minimum-compatible plugin version.
*
* @throws {Error} If the current plugin version is incompatible with the
* minimum compatible plugin version.
*/
var _assertPluginVersionIsCompatible = function () {
var pluginVersion = _spaces.version;
if (!_versionLessThanOrEqualTo(COMPATIBLE_PLUGIN_VERSION, pluginVersion)) {
var message = "Plugin version " + _formatVersion(pluginVersion) +
" is incompatible with the minimum required version, " +
_formatVersion(COMPATIBLE_PLUGIN_VERSION);
throw new Error(message);
}
};
// Assert plugin compatibility at load time
_assertPluginVersionIsCompatible();
/**
* Promisified version of _spaces.
*/
var _main = Promise.promisifyAll(_spaces);
Object.defineProperties(exports, {
/**
* Version of the Spaces adapter plugin API.
* Follows Semver 2.0.0 conventions: http://semver.org/spec/v2.0.0.html
*
* @const
* @type {string}
*/
"version": {
enumerable: true,
value: _spaces.version
},
/**
* Abort the current application and return control to Classic Photoshop.
* If a message is supplied, Classic Photoshop may display it to the user,
* e.g., in a dialog.
*
* @param {{message: string=}}
* @return {Promise}
*/
"abort": {
enumerable: true,
value: _main.abortAsync
}
});
var getPropertyValue = function (name) {
return _main.getPropertyValueAsync(name, {});
};
var setPropertyValue = function (name, value) {
return _main.setPropertyValueAsync(name, value, {});
};
/**
* Opens the given URL in the user's default browser.
*
* @param {string} url The URL to open in the user's default browser.
* @return {Promise}
*/
var openURLInDefaultBrowser = function (url) {
return _main.openURLInDefaultBrowserAsync(url);
};
exports.openURLInDefaultBrowser = openURLInDefaultBrowser;
exports.getPropertyValue = getPropertyValue;
exports.setPropertyValue = setPropertyValue;
});
|
JavaScript
| 0.000002 |
@@ -1581,26 +1581,18 @@
is
-less than or equal
+compatible
to
@@ -1804,33 +1804,26 @@
_version
-LessThanOrEqualTo
+Compatible
= funct
@@ -1888,17 +1888,19 @@
1.major
-%3E
+!==
v2.majo
@@ -2047,110 +2047,8 @@
%7D%0A%0A
- if (v1.hasOwnProperty(%22patch%22) && v1.patch %3E v2.patch) %7B%0A return false;%0A %7D%0A%0A
@@ -2770,25 +2770,18 @@
sion
-LessThanOrEqualTo
+Compatible
(COM
|
9a1a8e9c899a13d8d6d120d33f73ecf08af6543e
|
Refactor internals - don't replace object, just copy properties over to maintain references across application
|
codebrag-ui/app/scripts/licence/licenceService.js
|
codebrag-ui/app/scripts/licence/licenceService.js
|
angular.module('codebrag.licence')
.service('licenceService', function($http, $q, $rootScope, events, $timeout, $modal) {
var warningDays = 14,
licenceData = {},
ready = $q.defer(),
checkTimer,
checkInterval = 6 * 3600 * 1000; // 6 hours (in millis)
function scheduleLicenceCheck() {
return loadLicenceData().then(scheduleNextCheck).then(fireEvents).then(function() {
ready.resolve(licenceData);
});
function scheduleNextCheck() {
checkTimer && $timeout.cancel(checkTimer);
checkTimer = $timeout(function() {
loadLicenceData().then(scheduleNextCheck).then(fireEvents)
}, checkInterval);
}
}
function loadLicenceData() {
return $http.get('rest/licence').then(function(response) {
licenceData = response.data;
return licenceData;
});
}
function serviceReady() {
return ready.promise;
}
function getLicenceData() {
return licenceData;
}
function fireEvents() {
var daysToWarning = licenceData.daysLeft - warningDays;
if(licenceData.valid && daysToWarning < 0) {
$rootScope.$broadcast(events.licence.licenceAboutToExpire);
}
if(!licenceData.valid && !fireEvents.initialExpirationEvent) {
$rootScope.$broadcast(events.licence.licenceExpired);
fireEvents.initialExpirationEvent = true
}
}
function initialize() {
$rootScope.$on(events.loggedIn, scheduleLicenceCheck);
$rootScope.$on(events.licence.openPopup, licencePopup);
$rootScope.$on(events.licence.licenceExpired, licencePopup);
$rootScope.$on(events.licence.licenceKeyRegistered, scheduleLicenceCheck);
}
function licencePopup(once) {
if(licencePopup.displayed) return;
var repoStatusModalConfig = {
backdrop: false,
keyboard: true,
controller: 'LicenceInfoCtrl',
resolve: {
licenceData: loadLicenceData
},
templateUrl: 'views/popups/licenceInfo.html'
};
licencePopup.displayed = true;
$modal.open(repoStatusModalConfig).result.then(function() {
licencePopup.displayed = false;
}, function() {
licencePopup.displayed = false;
})
}
return {
ready: serviceReady,
getLicenceData: getLicenceData,
loadLicenceData: loadLicenceData,
licencePopup: licencePopup,
initialize: initialize
};
});
|
JavaScript
| 0 |
@@ -924,35 +924,48 @@
-licenceData = response.d
+angular.copy(response.data, licenceD
ata
+)
;%0A
|
466b2f1dda0b7eb0bcd96ba3b6619c5c6243b73d
|
heroku task
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp'),
mainBowerFiles = require('main-bower-files'),
minifyCss = require('gulp-minify-css'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
addsrc = require('gulp-add-src'),
sass = require('gulp-sass'),
exec = require('gulp-exec'),
ngAnnotate = require('gulp-ng-annotate'),
sourcemaps = require('gulp-sourcemaps'),
browserSync = require('browser-sync').create(),
watch = require('gulp-watch'),
plumber = require('gulp-plumber'),
jshint = require('gulp-jshint'),
notify = require('gulp-notify'),
templateCache = require('gulp-angular-templatecache'),
spawn = require('child_process').spawn,
node;
//****************************************************************
//JavaScripts section
gulp.task('scripts', function() {
return gulp.src([
'app/angular/**/*.js',
'app/scripts/**/*.js'])
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(ngAnnotate())
.pipe(jshint())
// .pipe(jshint.reporter('default'))
.pipe(concat('application.min.js'))
.pipe(sourcemaps.write('maps'))
.pipe(gulp.dest('public/js'))
.pipe(notify({ message: 'Script task complete' }));;
});
gulp.task('vendor-js', function() {
return gulp.src(mainBowerFiles('**/*.js'))
.pipe(plumber())
.pipe(concat('vendors.min.js'))
.pipe(gulp.dest('public/js'));
});
//****************************************************************
//CSS section
//External styles
gulp.task('normalize', function() {
return gulp.src(mainBowerFiles('**/*.css'))
.pipe(minifyCss({compatibility: 'ie8'}))
.pipe(gulp.dest('public/css'));
});
gulp.task('vendor-css', ['normalize'], function(){
});
//Custom styles
gulp.task('styles', function() {
return gulp.src([
'app/styles/**/*.scss',
'app/styles/**/*.css'])
.pipe(sass().on('error', sass.logError))
.pipe(concat('application.min.css'))
.pipe(minifyCss({compatibility: 'ie8'}))
.pipe(gulp.dest('public/css'))
.pipe(notify({ message: 'Styles task complete' }));
});
//****************************************************************
//General section
// Vendors scripts and styles
gulp.task('vendors', ['vendor-css', 'vendor-js'], function () {
});
//****************************************************************
// watching scss/js/html files
gulp.task('watch', ['vendors', 'scripts', 'styles', 'template', 'server'], function() {
gulp.watch('app/styles/**/*.css', ['styles']);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch([
'app/scripts/**/*.js',
'app/angular/**/*.js'
], ['scripts']);
gulp.watch('app/angular/**/*.html', ['template']);
gulp.watch([
'config/*.js',
'routes/*.js',
'views/*.ejs',
'app.js',
'app/models/*.js'
], ['server']);
});
//****************************************************************
// Angular templates
gulp.task('template', function() {
return gulp.src('app/angular/**/*.html')
.pipe(templateCache('templates.js', {standalone:true}))
.pipe(gulp.dest('app/angular'))
.pipe(notify({ message: 'Template task complete' }));
});
//****************************************************************
// Run server
// gulp.task('server', function() {
// var options = {
// continueOnError: false, // default = false, true means don't emit error event
// pipeStdout: false // default = false, true means stdout is written to file.contents
// };
// var reportOptions = {
// err: true, // default = true, false means don't write err
// stderr: true, // default = true, false means don't write stderr
// stdout: true // default = true, false means don't write stdout
// }
// gulp.src('./bin/www')
// .pipe(exec('node <%= file.path %>', options))
// .pipe(exec.reporter(reportOptions))
// .pipe(notify({ message: 'Server is started' }));
// });
/**
* $ gulp server
* description: launch the server. If there's a server already running, kill it.
*/
gulp.task('server', function() {
if (node) node.kill()
node = spawn('node', ['./bin/www'], {stdio: 'inherit'})
node.on('close', function (code) {
if (code === 8) {
gulp.log('Error detected, waiting for changes...');
}
});
})
// clean up if an error goes unhandled.
process.on('exit', function() {
if (node) node.kill()
})
//Default task
gulp.task('default', ['watch'], function() {
});
/ heroku task
gulp.task('heroku:test', ['vendors', 'scripts', 'styles', 'template']);
|
JavaScript
| 0.99999 |
@@ -4620,16 +4620,17 @@
%7B%0A%7D);%0A%0A
+/
/ heroku
|
39d78650c87af8c24819bff68cbd0e2bb3690dc2
|
Fix gulp
|
gulpfile.js
|
gulpfile.js
|
const gulp = require('gulp');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const plumber = require('gulp-plumber');
const manifest = require('./bolg/config/webpack.manifest.json');
const writefile = require('./bolg/helpers').writefile;
const browserSync = require('browser-sync');
function sync(done) {
return browserSync.init({
proxy: 'localhost:3000',
open: true,
logFileChanges: false,
}, done);
}
function compileSass() {
return gulp.src('src/styles/post-index.scss')
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(sass({
includePaths: ['node_modules'],
}))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
}))
.pipe(sourcemaps.write('/', {
sourceMappingURLPrefix: '/css',
}))
.pipe(gulp.dest('public/css'))
.pipe(browserSync.stream({ match: '**/*.css' }))
.on('end', () => {
manifest['/bolg.css'] = '/css/post-index.css';
writefile('bolg/config/webpack.manifest.json', JSON.stringify(manifest));
});
}
const watch = (done) => {
gulp.watch('src/styles/**/*.scss', compileSass);
sync(done);
};
gulp.task('default', watch);
gulp.task('sass', compileSass);
gulp.task('watch', watch);
gulp.task('server', sync);
|
JavaScript
| 0.000002 |
@@ -225,20 +225,22 @@
uire('./
-bolg
+public
/config/
|
e2af94c5ef4340bc593686272b4dc6f88230e106
|
refactor filter test
|
src/image/filter/__tests__/invert.js
|
src/image/filter/__tests__/invert.js
|
import { Image } from 'test/common';
describe('invert', function () {
it('should invert colors of 3 components of RGBA, not alpha', function () {
let image = new Image(1, 2, [230, 83, 120, 255, 100, 140, 13, 240]);
let inverted = [25, 172, 135, 255, 155, 115, 242, 240];
image.invert();
expect(image.data).toEqual(inverted);
});
it('should invert grey of GREY image', function () {
let image = new Image(2, 2, [1, 2, 3, 4],
{ kind: 'GREY' });
let inverted = [254, 253, 252, 251];
image.invert();
expect(image.data).toEqual(inverted);
});
it('should invert grey 16 bits of GREY image', function () {
let image = new Image(2, 2, [1, 2, 3, 4],
{ kind: 'GREY', bitDepth: 16 });
let inverted = [65534, 65533, 65532, 65531];
image.invert();
expect(image.data).toEqual(inverted);
});
it('should invert data if BINARY image', function () {
let data = new Uint8Array(1);
data[0] = 85;
let image = new Image(2, 4, data,
{ kind: 'BINARY' });
let inverted = new Uint8Array(1);
inverted[0] = [170];
image.invert();
expect(image.data).toEqual(inverted);
});
});
|
JavaScript
| 0.00001 |
@@ -216,37 +216,37 @@
240%5D);%0A%0A let
-inver
+expec
ted = %5B25, 172,
@@ -272,32 +272,49 @@
242, 240%5D;%0A%0A
+ const inverted =
image.invert();
@@ -322,34 +322,83 @@
expect(i
-mage
+nverted).toBe(image);%0A expect(Array.from(inverted
.data)
+)
.toEqual(inv
@@ -386,37 +386,37 @@
.data)).toEqual(
-inver
+expec
ted);%0A %7D);%0A%0A i
@@ -504,38 +504,32 @@
2, %5B1, 2, 3, 4%5D,
-%0A
%7B kind: 'GREY'
@@ -537,29 +537,29 @@
);%0A%0A let
-inver
+expec
ted = %5B254,
@@ -570,32 +570,49 @@
252, 251%5D;%0A%0A
+ const inverted =
image.invert();
@@ -620,34 +620,83 @@
expect(i
-mage
+nverted).toBe(image);%0A expect(Array.from(inverted
.data)
+)
.toEqual(inv
@@ -684,37 +684,37 @@
.data)).toEqual(
-inver
+expec
ted);%0A %7D);%0A%0A i
@@ -818,22 +818,16 @@
, 3, 4%5D,
-%0A
%7B kind:
@@ -857,29 +857,29 @@
);%0A%0A let
-inver
+expec
ted = %5B65534
@@ -902,24 +902,41 @@
65531%5D;%0A%0A
+ const inverted =
image.inver
@@ -948,34 +948,83 @@
expect(i
-mage
+nverted).toBe(image);%0A expect(Array.from(inverted
.data)
+)
.toEqual(inv
@@ -1012,37 +1012,37 @@
.data)).toEqual(
-inver
+expec
ted);%0A %7D);%0A%0A i
@@ -1109,20 +1109,16 @@
t data =
- new
Uint8Ar
@@ -1124,31 +1124,16 @@
rray
-(1);%0A data%5B0%5D = 85;%0A
+.of(85);
%0A
@@ -1170,14 +1170,8 @@
ata,
-%0A
%7B k
@@ -1201,22 +1201,18 @@
let
-inver
+expec
ted =
- new
Uin
@@ -1222,25 +1222,37 @@
rray
-(1
+.of(170
);%0A
+%0A
+const
inverted
%5B0%5D
@@ -1251,25 +1251,10 @@
rted
-%5B0%5D = %5B170%5D;%0A%0A
+=
ima
@@ -1278,20 +1278,57 @@
expect(i
-mage
+nverted).toBe(image);%0A expect(inverted
.data).t
@@ -1334,21 +1334,21 @@
toEqual(
-inver
+expec
ted);%0A
|
b65d8187328ba11171ac7a125847d8056760bffb
|
remove gulp font task from build runsequence
|
gulpfile.js
|
gulpfile.js
|
// ##### Gulp Tasks #####
// ***** Inspired by https://css-tricks.com/gulp-for-beginners/ ***** //
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var browserSync = require('browser-sync');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var minifyCSS = require('gulp-minify-css');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var modernizr = require('gulp-modernizr');
var runSequence = require('run-sequence');
var validateHTML = require('gulp-w3cjs');
var scsslint = require('gulp-scss-lint');
var jshint = require('gulp-jshint');
var lbInclude = require('gulp-lb-include');
var ssi = require('browsersync-ssi');
var sftp = require('gulp-sftp');
var svgmin = require('gulp-svgmin');
var path = require('path');
var postcss = require('gulp-postcss');
var assets = require('postcss-assets');
// Check that gulp is working by running "gulp hello" at the command line:
gulp.task('hello', function() {
console.log('Hello there!');
});
// Run the dev process by running "gulp" at the command line:
gulp.task('default', function (callback) {
runSequence(['sass', 'browserSync', 'watch'],
callback
)
})
// Run the build process by running "gulp build" at the command line:
gulp.task('build', function (callback) {
runSequence('clean',
['fonts', 'scss-lint', 'js-lint', 'sass', 'useref', 'images' ],
callback
)
})
// Run "gulp modernizr" at the command line to build a custom modernizr file based off of classes found in CSS:
gulp.task('modernizr', function() {
gulp.src('app/css/main.css') // where modernizr will look for classes
.pipe(modernizr({
options: ['setClasses'],
dest: 'app/js/modernizr-custombuild.js'
}))
});
// Process sass to css, add sourcemaps, inline font & image files into css, and reload browser:
gulp.task('sass', function() {
return gulp.src('app/scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass.sync().on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(postcss([assets({
loadPaths: ['fonts/', 'images/']
})]))
.pipe(sourcemaps.write('sourcemaps'))
.pipe(gulp.dest('app/css'))
.pipe(browserSync.reload({
stream: true
}));
})
// Watch sass, html, and js and reload browser if any changes:
gulp.task('watch', ['browserSync', 'sass', 'scss-lint', 'js-lint'], function (){
gulp.watch('app/scss/**/*.scss', ['sass']);
gulp.watch('app/scss/**/*.scss', ['scss-lint']);
gulp.watch('app/js/**/*.js', ['js-lint']);
gulp.watch('app/**/*.html', browserSync.reload);
gulp.watch('app/js/**/*.js', browserSync.reload);
});
// Spin up a local browser with the index.html page at http://localhost:3000/
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: 'app',
middleware: ssi({
baseDir: __dirname + '/app',
ext: '.html',
version: '1.4.0'
})
},
})
})
// Minify CSS, uglify JS, and concatenate files from paths within HTML comment tags; include files:
gulp.task('useref', function(){
return gulp.src(['app/**/*.html', '!app/includes/*'])
.pipe(gulpIf('*.css', minifyCSS()))
.pipe(gulpIf('*.js', uglify()))
.pipe(useref())
.pipe(lbInclude()) // Process <!--#include file="" --> statements
.pipe(gulp.dest('dist'))
});
// Compress images:
gulp.task('images', function(){
return gulp.src('app/images/**/*.+(png|jpg|jpeg|gif|svg)')
.pipe(cache(imagemin({ // Caching images that ran through imagemin
interlaced: true
})))
.pipe(gulp.dest('dist/images'))
});
// Delete "dist" directory at start of build process:
gulp.task('clean', function(callback) {
del('dist');
return cache.clearAll(callback);
})
// Validate build HTML:
gulp.task('validateHTML', function () {
gulp.src('dist/**/*.html')
.pipe(validateHTML())
});
// Lint Sass:
gulp.task('scss-lint', function() {
return gulp.src(['app/scss/**/*.scss', '!app/scss/vendor/**/*.scss'])
.pipe(scsslint({
'config': 'scss-lint-config.yml'
}));
});
// Lint JavaScript:
gulp.task('js-lint', function() {
return gulp.src(['app/js/**/*.js', '!app/js/modernizr-custombuild.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'))
});
// Deploy a build via SFTP to a web server:
gulp.task('deploy', function () {
return gulp.src('dist/**')
.pipe(sftp({
host: 'webprod.cdlib.org',
remotePath: '/apps/webprod/apache/htdocs/dash/',
authFile: 'gulp-sftp-key.json', // keep this file out of public repos by listing it within .gitignore, .hgignore, etc.
auth: 'keyMain'
}));
});
|
JavaScript
| 0.000004 |
@@ -1476,17 +1476,8 @@
%5B
-'fonts',
'scs
|
41f656d4ee292f57e5a04283453fdcb207fd7a5b
|
remove quotes
|
gulpfile.js
|
gulpfile.js
|
/*!
* @author: Divio AG
* @copyright: http://www.divio.ch
*/
'use strict';
// #############################################################################
// #IMPORTS#
var autoprefixer = require('gulp-autoprefixer');
var gulp = require('gulp');
var gutil = require('gulp-util');
var karma = require('karma').server;
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var minifyCss = require('gulp-minify-css');
var protractor = require('gulp-protractor').protractor;
var webdriverUpdate = require('gulp-protractor').webdriver_update;
// #############################################################################
// #SETTINGS#
var PROJECT_ROOT = __dirname;
var PROJECT_PATH = {
'sass': PROJECT_ROOT + '/private/sass',
'css': PROJECT_ROOT + '/static/css',
'tests': PROJECT_ROOT + '/tests'
};
var PROJECT_PATTERNS = {
'sass': [
PROJECT_PATH.sass + '/**/*.{scss,sass}'
]
};
// #############################################################################
// #TASKS#
gulp.task('sass', function () {
gulp.src(PROJECT_PATTERNS.sass)
.pipe(sourcemaps.init())
.pipe(sass())
.on('error', function (error) {
gutil.log(gutil.colors.red('Error (' + error.plugin + '): ' + error.messageFormatted));
})
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(minifyCss())
.pipe(sourcemaps.write())
.pipe(gulp.dest(PROJECT_PATH.css));
});
// #######################################
// #TESTS#
gulp.task('tests', ['tests:unit', 'tests:integration']);
gulp.task('tests:unit', function (done) {
// run javascript tests
karma.start({
'configFile': PROJECT_PATH.tests + '/karma.conf.js',
'singleRun': true
}, done);
});
gulp.task('tests:webdriver', webdriverUpdate);
gulp.task('tests:integration', ['tests:webdriver'], function () {
return gulp.src([PROJECT_PATH.tests + '/integration/*.js'])
.pipe(protractor({
'configFile': PROJECT_PATH.tests + '/protractor.conf.js',
'args': []
}))
.on('error', function (error) {
gutil.log(gutil.colors.red('Error (' + error.plugin + '): ' + error.message));
});
});
gulp.task('tests:watch', function () {
// run javascript tests
karma.start({
'configFile': PROJECT_PATH.tests + '/karma.conf.js'
});
});
// #############################################################################
// #COMMANDS#
gulp.task('watch', function () {
gulp.watch(PROJECT_PATTERNS.sass, ['sass']);
});
gulp.task('default', ['sass', 'watch']);
|
JavaScript
| 0.000001 |
@@ -1719,33 +1719,32 @@
start(%7B%0A
-'
configFile': PRO
@@ -1729,33 +1729,32 @@
configFile
-'
: PROJECT_PATH.t
@@ -1786,17 +1786,16 @@
-'
singleRu
@@ -1795,17 +1795,16 @@
ingleRun
-'
: true%0A
@@ -2029,33 +2029,32 @@
r(%7B%0A
-'
configFile': PRO
@@ -2039,33 +2039,32 @@
configFile
-'
: PROJECT_PATH.t
@@ -2109,14 +2109,12 @@
-'
args
-'
: %5B%5D
@@ -2367,17 +2367,16 @@
-'
configFi
@@ -2377,17 +2377,16 @@
nfigFile
-'
: PROJEC
|
94197b4497d03d69ca0e80ee5291dd1f0ddc74c1
|
Remove console.log call
|
src/main.js
|
src/main.js
|
define(function (require) {
"use strict";
// Dependencies
var CommandManager = brackets.getModule("command/CommandManager");
var Commands = brackets.getModule("command/Commands");
var Dialogs = require("Dialogs");
var EditorManager = brackets.getModule("editor/EditorManager");
var FileSystem = brackets.getModule("filesystem/FileSystem");
var FileUtils = brackets.getModule("file/FileUtils");
var Menus = brackets.getModule("command/Menus");
var Nls = require("i18n!nls/strings");
var PDFDocument = require("PDFDocument");
var StringUtils = brackets.getModule("utils/StringUtils");
/**
* @const
* @privte
* @type {string}
*/
var _COMMAND_ID = "pdfexport.export";
/**
* @private
* return {boolean}
*/
function _isSupportedDocument(doc) {
return doc.language.getId() !== "binary";
}
/**
* @param {{fontSize: number, pathname: string, text: string}} options
*/
function _savePDFFile(options) {
PDFDocument.create(options)
.fail(function _handleError() {
/**
* @TODO Use error codes in order to simplify displaying of error dialogs
*/
});
}
/**
* @TODO Refactor this function to use more abstractions
*/
function exportAsPdf() {
var editor = EditorManager.getActiveEditor();
var doc, inputFile;
/**
* @TODO Implement error dialog for nullified editor
*/
if (!editor) {
return;
}
doc = editor.document;
inputFile = doc.file.fullPath;
if (!_isSupportedDocument(doc)) {
Dialogs.showErrorDialog(
Nls.ERROR_UNSUPPORTED_FILE_TITLE,
Nls.ERROR_UNSUPPORTED_FILE_MSG,
inputFile
);
}
Dialogs.showExportDialog(inputFile).then(function _callback(options) {
if (!options) {
return;
}
console.log(options.fontSize);
FileSystem.showSaveDialog(
StringUtils.format(Nls.DIALOG_TITLE, FileUtils.getBaseName(inputFile)),
FileUtils.getDirectoryPath(inputFile),
FileUtils.getBaseName(inputFile) + ".pdf",
function _saveDialogCallback(err, pathname) {
_savePDFFile({
fontSize: options.fontSize,
inputFile: inputFile,
pathname: pathname,
text: doc.getText()
});
}
);
});
}
CommandManager.register(Nls.CMD_EXPORT_PDF, _COMMAND_ID, exportAsPdf);
Menus.getMenu(Menus.AppMenuBar.FILE_MENU)
.addMenuItem(
_COMMAND_ID,
null,
Menus.AFTER,
Commands.FILE_SAVE_AS
);
});
|
JavaScript
| 0.000003 |
@@ -2029,52 +2029,8 @@
%7D%0A%0A
- console.log(options.fontSize);%0A%0A
|
2eb954b3269b08e56895a32b03000446e18ead41
|
fix deploy bug
|
gulpfile.js
|
gulpfile.js
|
'use strict';
const P = require('path');
const F = require('fs');
const D = require('del');
const merge = require('merge2');
const glob = require('glob');
const $ = require('gulp');
const $changed = require('gulp-changed');
const $concat = require('gulp-concat');
const $flatmap = require('gulp-flatmap');
const $if = require('gulp-if');
const $order = require('gulp-order');
const $ignore = require('gulp-ignore');
const $htmlmin = require('gulp-htmlmin');
const $mustache = require('gulp-mustache');
const $plumber = require('gulp-plumber');
const $postcss = require('gulp-postcss');
const $rename = require('gulp-rename');
const $rsync = require('gulp-rsync');
const $sass = require('gulp-sass');
const $uglify = require('gulp-uglify');
const cssnano = require('cssnano');
const browsersync = require('browser-sync').create();
const reload = (done) => {browsersync.reload(); done();};
const cfg = {
des: './build/dslab'
};
$.task('default', $.series(
() => D(['./build/dslab']), $.parallel(sync, watch)));
function watch() {
$.watch('./src/pages/**/*', {ignoreInitial: false },
$.series(pages, reload));
$.watch('./src/assets/css/*', {ignoreInitial: false },
$.series(styles, reload));
$.watch('./src/assets/js/*', {ignoreInitial: false },
$.series(scripts, reload));
$.watch(['./src/assets/img/*', './src/assets/fonts/*'],
{ignoreInitial: false }, $.series(misc, reload));
}
// -------------------------------------------------------------------
// browser-sync
// -------------------------------------------------------------------
function sync() {
browsersync.init({
server: './build',
port: 4000
});
}
// -------------------------------------------------------------------
// Render pages with mustache
// -------------------------------------------------------------------
function pages() {
var cond = (
() => {
const cur = new Date();
var i, ret = {};
var deps = glob.sync('./src/pages/partials/*.mustache');
var t0 = null;
for (i = 0; i < deps.length; ++i)
t0 = Math.max(t0, F.statSync(deps[i]).mtime);
t0 = new Date(t0);
try {
var fd = F.openSync('./build', 'r');
} catch (e) {
fd = null;
}
var files = glob.sync('./src/pages/*.mustache');
for (i = 0; i < files.length; ++i) {
var k = P.basename(files[i], '.mustache');
var t1 = F.statSync(P.join('./src/pages', k + '.json')).mtime;
ret[k] = null === fd || cur - t0 < 1000 || cur - t1 < 1000;
}
return ret;
})();
return $.src('./src/pages/*.mustache')
.pipe($if((file) => !cond[P.basename(file.path, '.mustache')],
$changed(cfg.des)))
.pipe($flatmap(function(stream, file) {
var dirname = P.dirname(file.path);
var stem = P.basename(file.path, P.extname(file.path));
return stream
.pipe($mustache(P.join(dirname, stem + '.json')))
.pipe($rename({
dirname: ('index' == stem ? '' : stem),
basename: 'index',
extname: '.html'}))
.pipe($htmlmin({
removeComments: true,
collapseWhitespace: true,
removeEmptyAttributes: true,
minifyJS: true,
minifyCSS: true}));}))
.pipe($.dest(cfg.des));
}
// -------------------------------------------------------------------
// Make assets
// -------------------------------------------------------------------
function styles() {
var processors = [
cssnano({autoprefixer: {browsers: ['last 2 version'], add: true},
discardComments: {removeAll: true}})
];
return $.src('./src/assets/css/*')
.pipe($order([
"src/assets/css/*.css",
"src/assets/css/*.scss"]))
.pipe($changed('./build/dslab/css'))
.pipe($if(file => P.extname(file.path) === '.scss', $sass()))
.pipe($concat('style.css'))
.pipe($postcss(processors))
.pipe($.dest('./build/dslab/css'));
}
function scripts() {
return $.src(['./src/assets/js/jquery.min.js',
'./src/assets/js/bootstrap.min.js'])
.pipe($changed('./build/dslab/js'))
.pipe($concat('script.js'))
.pipe($.dest('./build/dslab/js'));
}
function misc() {
var s0 = $.src(['./src/assets/**/*',
'!./src/assets/css/*', '!./src/assets/js/*'])
.pipe($.dest(cfg.des));
var s1 = $.src('./src/pages/*.bib')
.pipe($changed('./build/dslab/publication'))
.pipe($.dest('./build/dslab/publication'));
return merge([s0, s1]);
};
// --------------------------------------------------------------------
// copy and deploy
// --------------------------------------------------------------------
$.task('copy', $.series(
() => D(['docs'], {force: true}),
() => $.src('build/dslab/**/*').pipe($.dest('docs'))));
$.task('deploy', function() {
$.src('docs')
.pipe($rsync({
root: 'docs',
hostname: 'mallard',
destination: '/export/vol2/httpd/htdocs/academic/engineering/dslab',
incremental: true,
progress: true,
compress: true,
recursive: true,
update: true,
exclude: ['.git', '.gitignore', 'old']
}));
});
|
JavaScript
| 0.000001 |
@@ -4835,16 +4835,20 @@
unction(
+done
) %7B%0A $.
@@ -5096,28 +5096,8 @@
ue,%0A
- update: true,%0A
@@ -5146,12 +5146,22 @@
%7D));%0A
+ done();%0A
%7D);%0A
|
b5812638c700b250ffa6ca0d8d070f14c6840a4e
|
Update scripts.js
|
js/scripts.js
|
js/scripts.js
|
var processing = false;
// JavaScript source code
$(document).ready(function () {
$('form').submit(function (evt) {
evt.preventDefault();
var searchTerm = $('#input').val();
// AJAX Starts
var flickrAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
var animal = searchTerm;
var flickrOptions = {
tags: animal,
format: "json",
};
function displayPhotos(data) {
var photoHTML = '<ul>';
$.each(data.items, function(i,photo) {
photoHTML += '<li class="grid">';
photoHTML += '<a href="' + photo.link + '" class="image">';
photoHTML += '<img src="' + photo.media.m + '"></a></li>';
});
photoHTML += '</ul>';
$('#photos').html(photoHTML);
}
$.getJSON(flickrAPI, flickrOptions, displayPhotos);
}) //end submit
// Fire AJAX every time page reaches 70% of height
$(document).scroll(function(e){
if (processing) {
return false;
}
if ( $(document).scrollTop() >= ($(document).height() - $(window).height())) {
console.log('reached');
processing = true;
$.getJSON(flickrAPI, flickrOptions, displayPhotos);
processing = false;
}
});
}); // end ready
|
JavaScript
| 0.000002 |
@@ -798,17 +798,16 @@
submit%0D%0A
-%09
%0D%0A// Fir
@@ -850,16 +850,59 @@
f height
+ ##########################################
%0D%0A $(
@@ -1253,17 +1253,110 @@
%7D);%0D%0A
-%09
+//############################################################################################
%0D%0A%09%0D%0A%7D);
|
ced340885289b0efb811451e24c83237179ec791
|
Reformat gulpfile
|
gulpfile.js
|
gulpfile.js
|
/**
* Created by joan on 29/04/17.
*/
const gulp = require('gulp');
const gutil = require('gulp-util');
const pump = require('pump');
const commandLineArgs = require('command-line-args');
const clean = require('gulp-clean');
const sourcemaps = require('gulp-sourcemaps');
const buffer = require('vinyl-buffer');
const runSequence = require('run-sequence');
const babelify = require('babelify');
const uglify = require('gulp-uglify');
const changed = require("gulp-changed");
const imagemin = require('gulp-imagemin');
const Browserify = require('browserify-gulp').default;
const browserSync = require('browser-sync').create();
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const watchify = require('watchify');
const errorify = require('errorify');
const optionDefinitions = [
{ name: 'type', alias: 't', defaultValue: "release" },
];
const options = commandLineArgs(optionDefinitions, { partial: true });
const debug = options["type"] === "debug";
let b = watchify(browserify({
entries : ["./public/pigs_book/js/pigs_book.js"],
debug : true,
insertGlobals: true,
cache : {},
packageCache : {},
transform : [
[babelify,
{
// Use all of the ES2015 spec
presets : ["es2015"],
compact : true,
sourceMaps: true,
}],
]
}));
b.on('log', gutil.log);
gulp.task("js", done => {
return pump([
b.bundle().on('error', err => {
done(err.stack);
}),
source('main.js'),
buffer(),
sourcemaps.init({ loadMaps: true }),
uglify(),
sourcemaps.write("./"),
gulp.dest("build/pigs_book/js"),
]);
});
gulp.task("html", function () {
return pump([
gulp.src('public/**/*.html'),
changed("build"),
gulp.dest('build')
]);
});
gulp.task("css", function () {
return pump([
gulp.src('public/**/*.css'),
changed("build"),
gulp.dest('build')
]);
});
gulp.task("fonts", function () {
return pump([
gulp.src('public/**/*.ttf'),
changed("build"),
gulp.dest('build')
]);
});
gulp.task("img", function () {
return pump([
gulp.src(['public/**/rendered/*.png', 'public/**/game/*.png']),
changed("build"),
imagemin({ verbose: true }),
gulp.dest('build')
]);
});
gulp.task('browser-sync', ['watcher'], () => {
return browserSync.init({
proxy: "localhost/5book/pigs_book/pigs_book.html"
})
});
gulp.task('watcher', ['all'], function () {
gulp.watch('public/**/*.html').on('change', () => runSequence('html', browserSync.reload));
gulp.watch('public/**/*.ttf').on('change', () => runSequence('fonts', browserSync.reload));
gulp.watch('public/**/*.css').on('change', () => runSequence('css', browserSync.reload));
gulp.watch('public/**/*.png').on('change', () => runSequence('img', browserSync.reload));
gulp.watch('public/**/*.js').on('change', () => runSequence('js', browserSync.reload));
});
gulp.task('all', ['js', 'html', 'img', 'css', 'fonts']);
gulp.task('default', () => {
gutil.log(gutil.colors.green(`Building in ${options["type"]} mode`));
return runSequence('browser-sync');
});
gulp.task('rebuild', () => {
return runSequence('clean', 'default');
});
gulp.task('clean', () => {
return pump([
gulp.src('build', { read: false }),
clean()
]);
});
|
JavaScript
| 0.000001 |
@@ -885,16 +885,23 @@
rrorify
+
= requir
|
51af0938e7b0f90cefb2e16d77e95ab38193ab0a
|
Fix typo in gulpfile.js
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var newfile = require('gulp-file');
var concat = require('gulp-concat');
gulp.task('scripts', function (done) {
jsSources = [
'node_modules/jquery/dist/jquery.min.js',
'node_modules/bootstrap/dist/js/bootstrap.bundle.min.js',
'node_modules/gijgo/js/gijgo.min.js',
'node_modules/bootstrap-list-filter/bootstrap-list-filter.min.js',
'node_modules/sortablejs/Sortable.min.js',
'node_modules/clipboard/dist/clipboard.min.js',
'node_modules/file-saver/filesaver.min.js',
'node_modules/keymaster/keymaster.js',
'node_modules/fontawesome-iconpicker/dist/js/fontawesome-iconpicker.min.js',
'node_modules/bootstrap-fileinput/js/fileinput.min.js',
'node_modules/@fortawesome/fontawesome-pro/js/all.min.js'
];
cssSources = [
'node_modules/bootstrap/dist/css/bootstrap.min.css',
'node_modules/gijgo/css/gijgo.min.css',
'node_modules/fontawesome-iconpicker/dist/css/fontawesome-iconpicker.min.css',
'node_modules/bootstrap-fileinput/css/fileinput.min.css'
];
gulp.src(jsSources)
.pipe(concat('bundle.js'))
.pipe(gulp.dest('dist/js'));
gulp.src(cssSources)
.pipe(concat('bundle.css'))
.pipe(gulp.dest('dist/css'));
done();
});
gulp.task('copy', function (done) {
gulp.src('css/*').pipe(gulp.dest('dist/css'));
gulp.src('js/*').pipe(gulp.dest('dist/js'));
gulp.src('favicon.ico').pipe(gulp.dest('dist'));
gulp.src('index.html').pipe(gulp.dest('dist'));
done();
});
gulp.task('generateFA', function(done) {
let targetJSON = {
icons: []
};
sourceJSON = require('./icons.json');
Object.keys(sourceJSON).forEach(function(key) {
let ele = sourceJSON[key];
let icon = 'fa-' + key;
ele.styles.forEach(function(style) {
style = style.toLowerCase();
if (style.startsWith('brand')) {
targetJSON.icons.push({
title: 'fab ' + icon,
searchTerms: ele.search.terms
});
} else if (style.startsWith('solid')) {
targetJSON.icons.push({
title: 'fas ' + icon,
searchTerms: ele.search.terms
});
} else if (style.startsWith('regular')) {
targetJSON.icons.push({
title: 'far ' + icon,
searchTerms: ele.search.terms
});
} else if (style.startsWith('light')) {
targetJSON.icons.push({
title: 'fal ' + icon,
searchTerms: ele.search.terms
});
}
});
});
newfile('faIcons.js', 'var faIcons = ' + JSON.stringify(targetJSON.icons)).pipe(gulp.dest('dist/js'));
done();
});
gulp.task('build',
gulp.parallel('scripts', 'copy', 'generateFA')
);
|
JavaScript
| 0.997618 |
@@ -505,13 +505,13 @@
ver/
-files
+FileS
aver
|
5a6fa8f54fac1903458fb3a61168f92bb6354978
|
Use of redux store
|
src/main.js
|
src/main.js
|
// import React from 'react'
import ReactDOM from 'react-dom';
import expect from 'expect';
const MOUNT_NODE = document.getElementById('root');
// Rendering a React APP
// let render = () => {
// const App = require('./components/App').default;
//
// ReactDOM.render(
// <App />,
// MOUNT_NODE
// )
// };
// let runTests = () => {
// expect(
// counter(0, { type : 'INCREMENT' })
// ).toEqual(1);
//
// expect(
// counter(1, { type : 'INCREMENT' })
// ).toEqual(2);
//
// expect(
// counter(2, { type : 'DECREMENT' })
// ).toEqual(1);
//
// expect(
// counter(1, { type : 'DECREMENT' })
// ).toEqual(0);
//
// expect(
// counter(undefined, {})
// ).toEqual(0);
// console.log("All Tests Passed!! Hurray !! ");
// };
//
const counter = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT': return state + 1;
case 'DECREMENT' : return state - 1;
default : return state;
}
};
// Rendering via Vanilla JS without react.
let render = () => {
let h1div = document.createElement('h1');
h1div.appendChild(document.createTextNode('Hello from Vanilla JS' ));
MOUNT_NODE.appendChild(h1div);
};
// Development Tools
// ------------------------------------
if (__DEV__) {
if (module.hot) {
const renderApp = render;
const renderError = (error) => {
const RedBox = require('redbox-react').default;
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE);
};
render = () => {
try {
renderApp()
} catch (e) {
console.error(e);
renderError(e);
}
};
// Setup hot module replacement
module.hot.accept([
'./components/App',
// './routes/index',
], () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE);
render();
})
)
}
}
// Let's Go!
// ------------------------------------
if (!__TEST__) render();
|
JavaScript
| 0 |
@@ -86,16 +86,55 @@
pect';%0A%0A
+import %7B createStore %7D from 'redux';%0A%0A%0A
const MO
@@ -995,16 +995,111 @@
%7D%0A%7D;%0A%0A
+const store = createStore(counter);%0A%0Aconsole.log(%22store initial state: %22, store.getState());%0A%0A%0A
// Rende
@@ -1118,16 +1118,34 @@
illa JS
+using Redux store
without
@@ -1172,16 +1172,17 @@
() =%3E %7B%0A
+%0A
let h1
@@ -1266,31 +1266,26 @@
de('
-Hello from Vanilla JS'
+Click anywhere !!'
));%0A
@@ -1319,16 +1319,185 @@
1div);%0A%0A
+ store.subscribe(() =%3E %7B%0A h1div.innerText = store.getState();%0A %7D) ;%0A%0A document.addEventListener('click', () =%3E %7B%0A store.dispatch(%7B type : 'INCREMENT'%7D )%0A %7D);%0A%0A
%7D;%0A%0A%0A//
|
c371696e0e5180fe708fdd3b3bbf2bbd6a3ab5b0
|
remove the height attribute when copying styles.
|
src/main.js
|
src/main.js
|
function getLabelForXAxis(series, options) {
if (series.xaxis.options.axisLabel) {
return series.xaxis.options.axisLabel;
}
return options.datatable.xaxis.label;
}
function getLabelForYAxis(series, options, suffix) {
if (series.label !== undefined && series.label !== null) {
return series.label;
}
if (series.yaxis.options.axisLabel) {
return series.yaxis.options.axisLabel;
}
return options.datatable.yaxis.label + suffix;
}
function createTable(allSeries, options, useRawValues) {
var identity = function(e) { return e;},
xformat = useRawValues ? identity : options.datatable.xaxis.format,
yformat = useRawValues ? identity : options.datatable.yaxis.format;
var T = '<tr><th align="left">' + getLabelForXAxis(allSeries[0], options) + '</th>',
t = '',
i, j, N, M;
for (j = 0, N = allSeries.length; j < N; j++) {
if (allSeries[j].nodatatable) {
continue;
}
T += '<th align="left">' + getLabelForYAxis(allSeries[j], options, j) + '</th>';
}
T += '</tr>';
for (i = 0, N = allSeries[0].data.length; i < N; i++) { // for each x
t = '<tr><td nowrap>' + xformat(allSeries[0].data[i][0]) + '</td>'; // 1st colunm, x-value
for (j = 0, M = allSeries.length; j < M; j++) { // for each series
if (allSeries[j].nodatatable) {
continue;
}
t += '<td nowrap>' + yformat(allSeries[j].data[i][1]) + '</td>'; // add y-data
}
t += '</tr>';
T += t;
}
return T;
}
function init(plot) {
// Add the styles
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".flot-datatable-tab { display: inline; border: 1px solid black; border-bottom: 0; padding: 2px 5px 2px 5px; margin-left: 3px; border-radius: 4px 4px 0 0; cursor: pointer; } .flot-datatable-tab:hover { background-color: #DDDDDD; }";
document.head.insertBefore(css, document.head.firstChild);
plot.hooks.drawOverlay.push(function (plot) {
var placeholder = plot.getPlaceholder();
// Only render the tabs on the first call
if (placeholder.parent().find("#dataTab").length > 0) {
return;
}
var tabs = $('<div class="flot-datatable-tabs" align="right"><div class="flot-datatable-tab" id="graphTab">Graph</div><div class="flot-datatable-tab" id="dataTab">Data</div></div>');
var panel = $('<div title="Doubleclick to copy" class="flot-datatable-data" style="width: ' + placeholder[0].clientWidth + 'px; height: ' + placeholder[0].clientHeight + 'px; padding: 0px; position: relative; overflow: scroll; background: white; z-index: 10; display: none; text-align: left;">' +
'<input type="checkbox" name="raw" value="raw">Raw values<br>' +
'<table style="width: 100%"></table>' +
'</div>');
// Wrap the placeholder in an outer div and prepend the tabs
placeholder.wrap("<div></div>")
.before(tabs)
.append(panel);
// Copy the placeholder's style and classes to our newly created wrapper
placeholder.parent()
.attr('class', placeholder.attr('class'))
.attr('style', placeholder.attr('style'));
var checkbox = panel.find(":checkbox");
var table = panel.find("table");
var redrawTable = function() {
table.html(createTable(plot.getData(), plot.getOptions(), checkbox.is(':checked')));
};
redrawTable();
bindTabs(tabs, panel);
bindCheckbox(checkbox, redrawTable);
bindTable(table);
});
function bindTabs(tabs, table) {
tabs.click(function (e) {
switch (e.target.id) {
case 'graphTab':
table.hide();
break;
case 'dataTab':
table.show();
break;
}
});
}
function bindCheckbox(checkbox, redrawTable) {
checkbox.change(function() {
redrawTable();
});
}
function bindTable(table) {
table.bind('dblclick', function () {
highlightTableRows(table);
});
}
function highlightTableRows(table) {
var selection = window.getSelection(),
range = document.createRange();
range.selectNode(table.get()[0]);
selection.removeAllRanges();
selection.addRange(range);
}
}
|
JavaScript
| 0 |
@@ -3319,16 +3319,90 @@
style'))
+%0A // Remove the height attribute%0A .css(%22height%22, %22%22)
;%0A%0A
|
f35913b31534ad37a848b0121f48230da18d9a64
|
Remove jquery.ns-autogrow import
|
src/main.js
|
src/main.js
|
import Vue from 'vue'
import VueFire from 'vuefire'
import App from './App'
import db from './firebaseDatabase'
import 'jquery-ui/jquery-ui.min.js'
import 'jquery.ns-autogrow'
import imagesLoaded from 'imagesloaded'
imagesLoaded.makeJQueryPlugin($)
import 'semantic-ui-css/semantic.js'
import 'semantic-ui-css/semantic.css'
// import marked from 'marked'
import 'jquery-shapeshift'
Vue.use(VueFire)
console.log('NEWT!')
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App },
data: {
db: db
}
})
|
JavaScript
| 0 |
@@ -147,37 +147,8 @@
s'%0A%0A
-import 'jquery.ns-autogrow'%0A%0A
impo
|
94cae465b1f9b37b484f0fda8e06cb416446c9e6
|
clear notification object when user signsout/logsin/destroy
|
app/directives/users/notifications.js
|
app/directives/users/notifications.js
|
define(['text!./notifications.html','app','lodash','utilities/km-user-notification-service',
'utilities/km-utilities','filters/moment','ionsound'], function(template,app,_) {
app.directive('userNotifications', function() {
return {
restrict: 'EAC',
replace: true,
template: template,
controller: ['$scope', '$rootScope', 'IUserNotificationService', '$timeout', '$filter','authentication',
function($scope, $rootScope, userNotificationService, $timeout, $filter, authentication) {
var pageNumber = 0;
var pageLength = 5;
//============================================================
//
//
//============================================================
$scope.timePassed = function(createdOn) {
return $filter("fromNow")(createdOn);
}
var notificationTimer;
//============================================================
//
//
//============================================================
function getNotification() {
if ($rootScope.user && $rootScope.user.isAuthenticated) {
// if (canQuery) {
var queryMyNotifications;
// canQuery = false;
queryMyNotifications = {$or:[{'state': 'read'},{'state': 'unread'}]};
if ($scope.notifications) {
var notification = _.first($scope.notifications);
if (notification)
queryMyNotifications = {
$and: [{
"createdOn": {
"$gt": new Date(notification.createdOn).toISOString()
},
$or:[{'state': 'read'},{'state': 'unread'}]
}]
};
}
var continueNotification = true;
userNotificationService.query(queryMyNotifications, pageNumber, pageLength)
.then(function(data) {
if (!data || data.length === 0)
return;
var localNotifications;
if ($scope.notifications) {
localNotifications = _.clone($scope.notifications);
_.each(data, function(message) {
localNotifications.push(message);
});
if(ion)
ion.sound.play("bell_ring");
} else {
localNotifications = data;
}
$scope.notifications = [];
$scope.notifications = $filter("orderBy")(localNotifications, 'createdOn', true);
})
.catch(function(error){
if(error.data.statusCode==401){
continueNotification = false;
}
})
.finally(function() {
if(continueNotification)
notificationTimer = $timeout(function() { getNotification();}, 10000);
});
//}
}
};
//============================================================
//
//
//============================================================
$scope.updateStatus = function(notification,status, $event) {
userNotificationService.update(notification.id, {
'state': status
})
.then(function() {
notification.state = status;
});
if($event)
$event.stopPropagation();
};
//============================================================
//
//
//============================================================
$scope.isUnread = function(notification) {
return notification && notification.state == 'unread';
};
$scope.$on('$destroy', function(evt){
$timeout.cancel(notificationTimer);
});
// $scope.$on('signIn', function(evt,user){
// $timeout(function(){
// console.log('notification after signin')
// getNotification();
// },5000);
// });
$scope.$on('signOut', function(evt,user){
$timeout.cancel(notificationTimer);
});
getNotification();
$rootScope.$watch('user', function(newVla,oldVal){
if(newVla && newVla!=oldVal){
$timeout.cancel(notificationTimer);
getNotification();
}
});
$scope.getURL = function(notification){
if(notification.type=='documentNotification')
return '/management/requests/' + notification.data.workflowId + '/publishRecord';
else
return '#';//'/mailbox/' + notification.id;
}
ion.sound({
sounds: [
{
name: "bell_ring"
}
],
volume: 0.5,
path: "/app/libs/ionsound/sounds/",
preload: true
});
}
]
};
});
});
|
JavaScript
| 0 |
@@ -5323,16 +5323,74 @@
n(evt)%7B%0A
+ $scope.notifications = undefined;%0A
@@ -5815,24 +5815,81 @@
(evt,user)%7B%0A
+ $scope.notifications = undefined;%0A
@@ -6117,32 +6117,94 @@
ewVla!=oldVal)%7B%0A
+ $scope.notifications = undefined;%0A
|
ba81e21f5918bd8382d6bc70a933b7792b1b13cd
|
Improve Expect middleware
|
src/lib/command/middleware/Expect.js
|
src/lib/command/middleware/Expect.js
|
'use babel';
'use strict';
import { User, GuildMember, TextChannel, Role } from 'discord.js';
export default function expect(argTypes)
{
return function(message, args)
{
const names = Object.keys(argTypes);
const types = names.map(a => argTypes[a]);
for (const [index, arg] of args.entries())
{
if (index > types.length - 1) break;
const name = names[index];
const type = types[index];
if (type === 'String')
{
if (typeof arg !== 'string')
throw new Error(`in arg \`${name}\`: \`String\` expected, got \`${arg.constructor.name}\``);
}
else if (type === 'Number')
{
if (!(isNaN(arg) && isFinite(arg)))
throw new Error(`in arg \`${name}\`: \`Number\` expected, got \`${arg.constructor.name}\``);
}
else if (type === 'User')
{
if (!(arg instanceof User))
throw new Error(`in arg \`${name}\`: \`User\` expected, got \`${arg.constructor.name}\``);
}
else if (type === 'Member')
{
if (!(arg instanceof GuildMember))
throw new Error(`in arg \`${name}\`: \`GuildMember\` expected, got \`${arg.constructor.name}\``);
}
else if (type === 'Channel')
{
if (!(arg instanceof TextChannel))
throw new Error(`in arg \`${name}\`: \`TextChannel\` expected, got \`${arg.constructor.name}\``);
}
else if (type === 'Role')
{
if (!(arg instanceof Role))
throw new Error(`in arg \`${name}\`: \`Role\` expected, got \`${arg.constructor.name}\``);
}
else
{
throw new Error(`in arg \`${name}\`: Type \`${type}\` is not a valid argument type.`);
}
}
return [message, args];
};
}
|
JavaScript
| 0.000002 |
@@ -252,16 +252,150 @@
s%5Ba%5D);%0A%0A
+%09%09const prefix = message.guild.storage.getSetting('prefix');%0A%09%09const usage = %60Usage: %5C%60$%7Bthis.usage.replace('%3Cprefix%3E', prefix)%7D%5C%60%60;%0A%0A
%09%09for (c
@@ -411,19 +411,21 @@
ex,
-arg
+name
%5D of
-arg
+name
s.en
@@ -444,105 +444,230 @@
%0A%09%09%09
-if (index %3E types.length - 1) break;%0A%0A%09%09%09const name = names%5Bindex%5D;%0A%09%09%09const type = types%5Bindex%5D;
+const arg = args%5Bindex%5D;%0A%09%09%09const type = types%5Bindex%5D;%0A%0A%09%09%09if (typeof args%5Bindex%5D === 'undefined' %7C%7C args%5Bindex%5D === null)%0A%09%09%09%09throw new Error(%60Missing or null value for arg: %5C%60$%7Bname%7D%5C%60, expected %5C%60$%7Btype%7D%5C%60%5Cn$%7Busage%7D%60);%0A
%0A%09%09%09
@@ -875,17 +875,16 @@
%09%09%09if (!
-(
isNaN(ar
@@ -889,16 +889,17 @@
arg) &&
+!
isFinite
@@ -904,17 +904,16 @@
te(arg))
-)
%0A%09%09%09%09%09th
@@ -968,32 +968,69 @@
pected, got %5C%60$%7B
+%0A%09%09%09%09%09%09arg === Infinity ? Infinity :
arg.constructor.
|
748bea0179a6d9c77cb41c4cd2ffd7720b2076e0
|
Change template path to a const; Add proxy option and comments.
|
tasks/settings.js
|
tasks/settings.js
|
module.exports = {
"browsersync": {
"files": [
"./app/assets/_compiled/styles.css",
"./app/assets/_compiled/*.js",
"./app/templates/**/*.html"
],
"server": "app",
"notify": false,
"open": false
},
"templatePath": "/*.html" // Relative to the app directory
}
|
JavaScript
| 0 |
@@ -1,8 +1,54 @@
+const templatePath = %22/templates/**/*.html%22;%0A%0A
module.e
@@ -184,25 +184,28 @@
%22./app
-/
+%22 +
template
s/**/*.h
@@ -200,31 +200,106 @@
late
-s/**/*.html%22%0A %5D,
+Path%0A %5D,%0A %22proxy%22: %22%22, // use this if it's NOT a static site, ex: app.trendyminds.dev
%0A
+ //
%22se
@@ -310,17 +310,51 @@
%22: %22app%22
-,
+ // use this if it IS a static site
%0A %22no
@@ -379,20 +379,19 @@
%22open%22:
-fals
+tru
e%0A %7D,%0A
@@ -411,17 +411,20 @@
h%22:
-%22/*.html%22
+templatePath
//
|
dc8dc673b63da146cbae148cf4ad8a4915a9544c
|
fix dashboard reload
|
Resources/home/home.js
|
Resources/home/home.js
|
Ti.include('../controls/control_table_pulldown.js');
var win = Titanium.UI.currentWindow;
//
// Create main Table View
//
var tvDashboard = Titanium.UI.createTableView({ style:Titanium.UI.iPhone.TableViewStyle.GROUPED });
tvDashboard.addEventListener('click', function(e)
{
if (e.rowData.subWindowURL) // just to exlude imcomplete windows
{
var win = Ti.UI.createWindow( {
title : e.rowData.subWindowTitle,
url: e.rowData.subWindowURL,
_parent: Titanium.UI.currentWindow,
navGroup : Titanium.UI.currentWindow.navGroup,
rootWindow : Titanium.UI.currentWindow.rootWindow
});
Titanium.UI.currentWindow.navGroup.open(win, {animated:true});
}
});
// Pull down section init
mbl_addTablePullDownHeader(tvDashboard, function () { tvDashboard.data = [ ]; }, loadDashboard );
win.add(tvDashboard);
//
// Nav Bar Init
//
var navSignOut = Ti.UI.createButton({title:'Sign Out'});
navSignOut.addEventListener('click', function(e)
{
Ti.App.Properties.setString('mblUserPwd', '');
win.navGroup.close(win);
});
win.leftNavButton = navSignOut;
//
// Fill Main Dashboard TableView
//
var data = [
//General section
{title:'Accounts', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
{title:'Locations', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
{title:'Tickets', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
{title:'Projects', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
// Active link
{title:'Tickets', hasChild:true, subWindow:'../tickets/ticket_list.js', subWindowURL:'../tickets/ticket_list.js', header: 'Test Tickets', leftImage: '../images/MAIL.PNG'},
// Tickets section
{title:'New Messages', hasChild:true, subWindow:'../tickets/ticket_list.js', header: 'Ticket Summary', leftImage: '../images/MAIL.PNG'},
{title:'Open Tickets', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
{title:'Open as End User', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
{title:'On Hold', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
{title:'Waiting On Parts', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
{title:'Follow-Up Dates', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
{title:'Unconfirmed', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
// Queues
{title:'Future Consideration', hasChild:true, subWindow:'../tickets/ticket.js', header: 'Queues', leftImage: '../images/MAIL.PNG'},
{title:'MC3 Upgrade', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
{title:'Pre-Development', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'},
{title:'Website fixes', hasChild:true, subWindow:'../tickets/ticket_list.js', leftImage: '../images/MAIL.PNG'}
];
var tableData = [];
function loadDashboard()
{
for(var i=0,ilen=data.length; i<ilen; i++)
{
var thisObj = data[i];
var row = Ti.UI.createTableViewRow({
className: 'home_row',
leftImage: thisObj.leftImage,
hasChild: thisObj.hasChild
});
var rowName = Titanium.UI.createLabel({
text:thisObj.title,
font:{fontSize:16,fontWeight:'bold'},
width:'auto',
textAlign:'left',
left:40,
height:18
});
if (!thisObj.subWindowURL)
rowName.color = '#999999';
row.add(rowName);
var k = i;
if (k > 10)
k = k - 11;
var rowStatus = Titanium.UI.createLabel({
text: k + 1,
backgroundColor: '#999999',
color:'#ffffff',
width:14,
height: 18,
textAlign:'center',
right:10
});
if (i > 4 && i !== 9)
row.add(rowStatus);
if (thisObj.header)
row.header = thisObj.header;
row.subWindow = thisObj.subWindow;
row.subWindowURL = thisObj.subWindowURL;
row.subWindowTitle = thisObj.title;
tableData.push(row);
}
tvDashboard.setData(tableData);
}
loadDashboard();
|
JavaScript
| 0.000001 |
@@ -790,18 +790,19 @@
ard.
-data = %5B %5D
+setData(%5B%5D)
; %7D,
@@ -3107,29 +3107,8 @@
%5D;%0A%0A
-var tableData = %5B%5D;%0A%0A
func
@@ -3130,16 +3130,37 @@
ard()%0A%7B%0A
+%09var tableData = %5B%5D;%0A
%09for(var
|
2a70ae23fa2d65195eed0f99e224a3fd8e57aad8
|
Add proptype update
|
src/widgets/StepperInputs/DateEditor.js
|
src/widgets/StepperInputs/DateEditor.js
|
/* eslint-disable react/jsx-wrap-multilines */
/* eslint-disable react/forbid-prop-types */
import React from 'react';
import PropTypes from 'prop-types';
import { Pressable, TextInput } from 'react-native';
import moment from 'moment';
import DateTimePicker from '@react-native-community/datetimepicker';
import { Incrementor } from './Incrementor';
import { useOptimisticUpdating, useDatePicker } from '../../hooks';
import { generalStrings } from '../../localization';
import { APP_FONT_FAMILY, DARKER_GREY } from '../../globalStyles';
export const DateEditor = ({
label,
date,
onPress,
textInputStyle,
stepAmount,
stepUnit,
minimumDate,
maximumDate,
}) => {
const adjustValue = (toUpdate, addend) => moment(toUpdate).add(addend, stepUnit).toDate();
const formatter = toFormat => moment(toFormat).format('DD/MM/YYYY');
const wrappedDatePicker = timestamp => onPress(new Date(timestamp));
const [datePickerIsOpen, openDatePicker, onPickDate] = useDatePicker(wrappedDatePicker);
const [textInputRef, newValue, newOnChange] = useOptimisticUpdating(
date,
onPress,
adjustValue,
formatter
);
return (
<>
<Incrementor
onIncrement={() => newOnChange(stepAmount)}
onDecrement={() => newOnChange(-stepAmount)}
label={label}
Content={
<Pressable onPress={openDatePicker}>
<TextInput
ref={textInputRef}
editable={false}
style={textInputStyle}
value={newValue}
/>
</Pressable>
}
/>
{datePickerIsOpen && (
<DateTimePicker
minimumDate={minimumDate}
maximumDate={maximumDate}
value={date}
mode="date"
display="spinner"
onChange={onPickDate}
/>
)}
</>
);
};
DateEditor.defaultProps = {
label: generalStrings.date,
textInputStyle: { color: DARKER_GREY, fontFamily: APP_FONT_FAMILY, width: 90 },
stepAmount: 1,
stepUnit: 'day',
maximumDate: null,
minimumDate: null,
};
DateEditor.propTypes = {
label: PropTypes.string,
date: PropTypes.object.isRequired,
onPress: PropTypes.func.isRequired,
textInputStyle: PropTypes.object,
stepAmount: PropTypes.number,
stepUnit: PropTypes.string,
maximumDate: PropTypes.oneOfType([PropTypes.instanceOf(Date), PropTypes.instanceOf(moment)]),
minimumDate: PropTypes.oneOfType([PropTypes.instanceOf(Date), PropTypes.instanceOf(moment)]),
};
|
JavaScript
| 0 |
@@ -2059,16 +2059,36 @@
: null,%0A
+ date: new Date(),%0A
%7D;%0A%0ADate
@@ -2159,27 +2159,16 @@
s.object
-.isRequired
,%0A onPr
|
7d0f0432156daea7d0e5fb70fdf5df4625288492
|
Update index.js
|
js/index.js
|
js/index.js
|
/*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library 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
* Lesser General Public License for more details.
*
*/
function getopts(args, opts)
{
var result = opts.default || {};
args.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { result[$1] = $3; });
return result;
};
var args = getopts(location.search,
{
default:
{
ws_uri: 'wss://219.251.4.177:30001/kurento',
ice_servers: undefined
}
});
if (args.ice_servers) {
console.log("Use ICE servers: " + args.ice_servers);
kurentoUtils.WebRtcPeer.prototype.server.iceServers = JSON.parse(args.ice_servers);
} else {
console.log("Use freeice")
}
window.addEventListener('load', function(){
console = new Console('console', console);
var videoOutput = document.getElementById('videoOutput');
var address = document.getElementById('address');
address.value = 'rtsp://192.168.10.156/avc';
var pipeline;
var webRtcPeer;
startButton = document.getElementById('start');
startButton.addEventListener('click', start);
stopButton = document.getElementById('stop');
stopButton.addEventListener('click', stop);
function start() {
if(!address.value){
window.alert("You must set the video source URL first");
return;
}
address.disabled = true;
showSpinner(videoOutput);
var options = {
remoteVideo : videoOutput
};
webRtcPeer = kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options,
function(error){
if(error){
return console.error(error);
}
webRtcPeer.generateOffer(onOffer);
webRtcPeer.peerConnection.addEventListener('iceconnectionstatechange', function(event){
if(webRtcPeer && webRtcPeer.peerConnection){
console.log("oniceconnectionstatechange -> " + webRtcPeer.peerConnection.iceConnectionState);
console.log('icegatheringstate -> ' + webRtcPeer.peerConnection.iceGatheringState);
}
});
});
}
function onOffer(error, sdpOffer){
if(error) return onError(error);
kurentoClient(args.ws_uri, function(error, kurentoClient) {
if(error) return onError(error);
kurentoClient.create("MediaPipeline", function(error, p) {
if(error) return onError(error);
pipeline = p;
pipeline.create("PlayerEndpoint", {uri: address.value}, function(error, player){
if(error) return onError(error);
pipeline.create("WebRtcEndpoint", function(error, webRtcEndpoint){
if(error) return onError(error);
setIceCandidateCallbacks(webRtcEndpoint, webRtcPeer, onError);
webRtcEndpoint.processOffer(sdpOffer, function(error, sdpAnswer){
if(error) return onError(error);
webRtcEndpoint.gatherCandidates(onError);
webRtcPeer.processAnswer(sdpAnswer);
});
player.connect(webRtcEndpoint, function(error){
if(error) return onError(error);
console.log("PlayerEndpoint-->WebRtcEndpoint connection established");
player.play(function(error){
if(error) return onError(error);
console.log("Player playing ...");
});
});
});
});
});
});
}
function stop() {
address.disabled = false;
if (webRtcPeer) {
webRtcPeer.dispose();
webRtcPeer = null;
}
if(pipeline){
pipeline.release();
pipeline = null;
}
hideSpinner(videoOutput);
}
});
function setIceCandidateCallbacks(webRtcEndpoint, webRtcPeer, onError){
webRtcPeer.on('icecandidate', function(candidate){
console.log("Local icecandidate " + JSON.stringify(candidate));
candidate = kurentoClient.register.complexTypes.IceCandidate(candidate);
webRtcEndpoint.addIceCandidate(candidate, onError);
});
webRtcEndpoint.on('OnIceCandidate', function(event){
var candidate = event.candidate;
console.log("Remote icecandidate " + JSON.stringify(candidate));
webRtcPeer.addIceCandidate(candidate, onError);
});
}
function onError(error) {
if(error)
{
console.error(error);
stop();
}
}
function showSpinner() {
for (var i = 0; i < arguments.length; i++) {
arguments[i].poster = 'img/transparent-1px.png';
arguments[i].style.background = "center transparent url('img/spinner.gif') no-repeat";
}
}
function hideSpinner() {
for (var i = 0; i < arguments.length; i++) {
arguments[i].src = '';
arguments[i].poster = 'img/webrtc.png';
arguments[i].style.background = '';
}
}
/**
* Lightbox utility (to display media pipeline image in a modal dialog)
*/
$(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
|
JavaScript
| 0.000002 |
@@ -867,13 +867,12 @@
177:
-30001
+8443
/kur
|
dc2c4e02f11038ec101f4bb621c6060431535291
|
set user modes
|
lib/user.js
|
lib/user.js
|
//On user join channel
module.exports = class USER{
constructor(nick, chan, perm, joined) {
var _this = this;
this.perm = perm || '';
this.nick = nick;
this.chan = chan;
this.is_chan_owner = false;
this.is_discord_user = false;
this.log.info('> Weaponizing', nick, chan, perm, joined);
if(chan !== 'PM') this.set_user_modes();
if(joined){
if(chan !== 'PM'){
this.say_tagline();
b.users.update_last_seen(nick, chan, 'join');
} else {
b.users.update_last_seen(nick, chan, 'pm');
}
}
}
get where(){
if(this.chan !== 'PM'){
return b.channels[this.chan];
} else {
return b.pm;
}
}
get log(){
return this.where.log
}
get t(){
if(this.where.t){
return this.where.t;
} else {
return new Theme(config.chan_default.theme, config.chan_default.disable_colors);
}
}
get config(){
if(this.where.config){
return this.where.config;
} else {
return config.chan_default;
}
}
get is_owner(){
for(var who in b.users.on_server){
if(b.users.on_server[who].nick === this.nick){
return b.users.on_server[who].is_owner
break;
}
}
return false;
}
get nick_org(){
for(var who in b.users.on_server){
if(b.users.on_server[who].nick === this.nick){
return b.users.on_server[who].nick_org;
break;
}
}
return null;
}
get who(){
for(var who in b.users.on_server){
if(b.users.on_server[who].nick === this.nick){
return who;
break;
}
}
return null;
}
get who_org(){
for(var who in b.users.on_server){
if(b.users.on_server[who].nick === this.nick){
return b.users.on_server[who].who_org;
break;
}
}
return null;
}
//chan only
set_user_modes(){
var _this = this;
if(this.chan !== 'PM'){
b.users.user_data_from_who(_this.config.chan_owner, true, function(chan_owner_regex){
if(_this.who.match(chan_owner_regex) !== null){
_this.log.info(_this.who, 'make chan owner');
_this.is_chan_owner = true;
if(b.is_op){
if(_this.config.make_owner_chan_owner && _this.perm !== '~'){
bot.send('samode', _this.chan, '+q', _this.nick);
_this.log.info(_this.who, 'chan owner +q');
_this.perm = '~';
}
} else {
_this.log.trace(bot.nick, 'is not opper, cannot samode +q');
}
} else {
if(b.is_op && _this.perm === '' && _this.config.voice_users_on_join){
bot.send('samode', _this.chan, '+v', _this.nick);
_this.perm = '+';
} else {
_this.log.trace(bot.nick, 'is not opper, cannot samode +v');
}
}
});
}
}
nick_change(new_nick){
this.log.warn('USER nick_change', this.nick, '->', new_nick);
try {
this.where.users[new_nick] = this.where.users[this.nick];
delete this.where.users[this.nick];
this.nick = new_nick;
} catch(e) {
this.log.error('Unable to change nick', this.nick, '->', new_nick, 'in', this.chan);
}
}
//chan only
say_tagline(){
var _this = this;
if(this.chan !== 'PM'){
var _this = this;
b.users.get_user_data(_this, {
col: 'tags',
ignore_err: true,
skip_say: true,
use_nick_org: false
}, function(tags){
var enter_msg = '';
if(_this.config.discord_relay_channel){
enter_msg += '→ ' + x.no_highlight(_this.nick) + ' joined';
} else {
if(tags !== false && tags.length && tags.length > 0){
enter_msg += x.no_highlight(_this.nick) + ' says';
}
}
if(tags !== false && tags.length && tags.length > 0){
if(enter_msg !== '') enter_msg += ': ';
enter_msg += tags[x.rand_number_between(0, tags.length - 1)];
}
if(enter_msg !== ''){
_this.where.say(enter_msg, 1, {skip_verify: true, ignore_bot_speak: true, skip_buffer: true});
}
});
}
}
}
|
JavaScript
| 0.000001 |
@@ -2244,32 +2244,87 @@
r _this = this;%0A
+ _this.log.debug('SET USER MODES', _this.nick);%0A
if(this.
@@ -2437,16 +2437,78 @@
regex)%7B%0A
+ _this.log.debug(chan_owner_regex, _this.who);%0A
|
eb86fe40451f8e7406929975b5ef8df7e6d02386
|
Change the JSON representation of marks
|
src/mark.js
|
src/mark.js
|
const {compareDeep} = require("./comparedeep")
// ::- A mark is a piece of information that can be attached to a node,
// such as it being emphasized, in code font, or a link. It has a type
// and optionally a set of attributes that provide further information
// (such as the target of the link). Marks are created through a
// `Schema`, which controls which types exist and which
// attributes they have.
class Mark {
constructor(type, attrs) {
// :: MarkType
// The type of this mark.
this.type = type
// :: Object
// The attributes associated with this mark.
this.attrs = attrs
}
// :: ([Mark]) → [Mark]
// Given a set of marks, create a new set which contains this one as
// well, in the right position. If this mark is already in the set,
// the set itself is returned. If a mark of this type with different
// attributes is already in the set, a set in which it is replaced
// by this one is returned.
addToSet(set) {
for (var i = 0; i < set.length; i++) {
var other = set[i]
if (other.type == this.type) {
if (this.eq(other)) return set
let copy = set.slice()
copy[i] = this
return copy
}
if (other.type.rank > this.type.rank)
return set.slice(0, i).concat(this).concat(set.slice(i))
}
return set.concat(this)
}
// :: ([Mark]) → [Mark]
// Remove this mark from the given set, returning a new set. If this
// mark is not in the set, the set itself is returned.
removeFromSet(set) {
for (var i = 0; i < set.length; i++)
if (this.eq(set[i]))
return set.slice(0, i).concat(set.slice(i + 1))
return set
}
// :: ([Mark]) → bool
// Test whether this mark is in the given set of marks.
isInSet(set) {
for (let i = 0; i < set.length; i++)
if (this.eq(set[i])) return true
return false
}
// :: (Mark) → bool
// Test whether this mark has the same type and attributes as
// another mark.
eq(other) {
if (this == other) return true
if (this.type != other.type) return false
if (!compareDeep(other.attrs, this.attrs)) return false
return true
}
// :: () → Object
// Convert this mark to a JSON-serializeable representation.
toJSON() {
let obj = {_: this.type.name}
for (let attr in this.attrs) obj[attr] = this.attrs[attr]
return obj
}
// :: (Schema, Object) → Mark
static fromJSON(schema, json) {
let type = schema.marks[json._]
let attrs = null
for (let prop in json) if (prop != "_") {
if (!attrs) attrs = Object.create(null)
attrs[prop] = json[prop]
}
return attrs ? type.create(attrs) : type.instance
}
// :: ([Mark], [Mark]) → bool
// Test whether two sets of marks are identical.
static sameSet(a, b) {
if (a == b) return true
if (a.length != b.length) return false
for (let i = 0; i < a.length; i++)
if (!a[i].eq(b[i])) return false
return true
}
// :: (?union<Mark, [Mark]>) → [Mark]
// Create a properly sorted mark set from null, a single mark, or an
// unsorted array of marks.
static setFrom(marks) {
if (!marks || marks.length == 0) return Mark.none
if (marks instanceof Mark) return [marks]
var copy = marks.slice()
copy.sort((a, b) => a.type.rank - b.type.rank)
return copy
}
}
exports.Mark = Mark
// :: [Mark] The empty set of marks.
Mark.none = []
|
JavaScript
| 0.000078 |
@@ -2250,17 +2250,20 @@
obj = %7B
-_
+type
: this.t
@@ -2308,18 +2308,26 @@
trs)
+ %7B%0A
obj
-%5B
+.
attr
-%5D
+s
= t
@@ -2339,14 +2339,26 @@
ttrs
-%5Battr%5D
+%0A break%0A %7D
%0A
@@ -2448,18 +2448,14 @@
-let type =
+return
sch
@@ -2473,214 +2473,32 @@
son.
-_%5D%0A let attrs = null%0A for (let prop in json) if (prop != %22_%22) %7B%0A if (!attrs) attrs = Object.create(null)%0A attrs%5Bprop%5D = json%5Bprop%5D%0A %7D%0A return attrs ? type.create(attrs) : type.instance
+type%5D.create(json.attrs)
%0A %7D
|
d0d5b0c18a795d822f4faae0b2c6cf1c41918ff8
|
Update lib/xrds.js
|
lib/xrds.js
|
lib/xrds.js
|
/* A simple XRDS and Yadis parser written for OpenID for node.js
*
* http://ox.no/software/node-openid
* http://github.com/havard/node-openid
*
* Copyright (C) 2010 by Håvard Stranden
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*
* -*- Mode: JS; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set sw=2 ts=2 et tw=80 :
*/
exports.parse = function(data)
{
data = data.replace(/\r|\n/g, '');
services = [];
var serviceMatches = data.match(/<Service\s*(priority="\d+")?\s*?>(.*?)<\/Service>/g);
if(!serviceMatches)
{
return services;
}
for(var s = 0, len = serviceMatches.length; s < len; ++s)
{
var service = serviceMatches[s];
var svcs = [];
var priorityMatch = /<Service\s*priority="(.*)"\s*?>/g.exec(service);
var priority = 0;
if(priorityMatch)
{
priority = parseInt(priorityMatch[1], 10);
}
var typeMatch = null;
var typeRegex = new RegExp('<Type(\\s+.*?)?>(.*?)<\\/Type\\s*?>', 'g');
while(typeMatch = typeRegex.exec(service))
{
svcs.push({ priority: priority, type: typeMatch[2] });
}
if(svcs.length == 0)
{
continue;
}
var idMatch = /<(Local|Canonical)ID\s*?>(.*?)<\/\1ID\s*?>/g.exec(service);
if(idMatch)
{
for(var i = 0; i < svcs.length; i++)
{
var svc = svcs[i];
svc.id = idMatch[2];
}
}
var uriMatch = /<URI(\s+.*?)?>(.*?)<\/URI\s*?>/g.exec(service);
if(!uriMatch)
{
continue;
}
for(var i = 0; i < svcs.length; i++)
{
var svc = svcs[i];
svc.uri = uriMatch[2];
}
var delegateMatch = /<(.*?Delegate)\s*?>(.*)<\/\1\s*?>/g.exec(service);
if(delegateMatch)
{
svc.delegate = delegateMatch[2];
}
services.push.apply(services, svcs);
}
services.sort(function(a, b)
{
return a.priority < b.priority
? -1
: (a.priority == b.priority ? 0 : 1);
});
return services;
}
|
JavaScript
| 0 |
@@ -1434,16 +1434,20 @@
'');%0A
+var
services
|
065a2a39ae5106ba986a5cbb6de468fbd99ac03c
|
Enable tabs again.
|
src/zeit/find/browser/resources/find.js
|
src/zeit/find/browser/resources/find.js
|
zeit.find = {};
zeit.find.Tabs = gocept.Class.extend({
// Knows about all tabs
construct: function() {
log("initializing tabs");
var self = this;
self.container = $('cp-forms');
var div = self.container.appendChild(
DIV({'class': 'context-views'}))
self.tabs = [];
self.tabs_element = div.appendChild(UL());
MochiKit.Signal.connect(
self.tabs_element, 'onclick', self, self.switch_tab);
},
add: function(tab) {
// Create a tab inside $('cp-forms')
var self = this;
tab.tab_element = self.tabs_element.appendChild(
LI({},
A({href: tab.id}, tab.title)))
tab.container = self.container.appendChild(DIV({id: tab.id}));
MochiKit.DOM.hideElement(tab.container);
self.tabs.push(tab);
if (self.tabs.length == 1) {
self.activate(tab.id);
}
},
switch_tab: function(event) {
var self = this;
var target = event.target();
var id = target.getAttribute('href');
self.activate(id);
event.stop();
},
activate: function(id) {
var self = this;
forEach(self.tabs, function(tab) {
if (tab.id == id) {
MochiKit.DOM.showElement(tab.container);
MochiKit.DOM.addElementClass(tab.tab_element, 'selected');
} else {
MochiKit.DOM.hideElement(tab.container);
MochiKit.DOM.removeElementClass(tab.tab_element, 'selected');
}
});
},
});
zeit.find.Tab = gocept.Class.extend({
construct: function(id, title) {
var self = this;
self.id = id;
self.title = title;
self.selected = false;
},
});
zeit.find.View = gocept.Class.extend({
construct: function(json_url, expansion_id, get_query_string) {
var self = this;
self.json_url = json_url;
self.expansion_id = expansion_id
self.get_query_string = get_query_string;
self.template = null;
},
render: function() {
var self = this;
// XXX dependency on application_url...
var url = application_url + '/' + self.json_url;
if (!isUndefinedOrNull(self.get_query_string)) {
url += "?" + self.get_query_string();
}
var d = MochiKit.Async.loadJSONDoc(url);
// XXX have to wrap in function to retain reference to self
// otherwise this gets messed up
d.addCallback(function(json) { self.callback_json(json) });
d.addErrback(zeit.find.log_error);
},
callback_json: function(json) {
var self = this;
var template_url = json['template_url'];
var template = self.template;
if (!isUndefinedOrNull(template)) {
self.expand_template(json);
return;
}
self.load_template(template_url, json);
},
load_template: function(template_url, json) {
var self = this;
var d = MochiKit.Async.doSimpleXMLHttpRequest(template_url);
d.addCallback(function(result) {
var t = jsontemplate.Template(result.responseText);
self.template = t;
self.expand_template(json);
});
d.addErrback(zeit.find.log_error);
return d;
},
expand_template: function(json) {
var self = this;
var s = self.template.expand(json);
MochiKit.Signal.signal(self, 'before-load')
$(self.expansion_id).innerHTML = s;
log('template expanded successfully');
MochiKit.Signal.signal(self, 'load')
},
});
zeit.find.log_error = function(err) {
/* the error can be either a normal error or wrapped
by MochiKit in a GenericError in which case the message
is the real error. We check whether the message is the real
error first by checking whether its information is undefined.
If it is undefined, we fall back on the outer error and display
information about that */
var real_error = err.message;
if (isUndefinedOrNull(real_error.message)) {
real_error = err;
}
console.error(real_error.name + ': ' + real_error.message);
};
(function() {
var init_search_form = function() {
MochiKit.Signal.connect('search_button', 'onclick', function(e) {
search_result.render();
});
MochiKit.Signal.connect('extended_search_button', 'onclick', function(e) {
if ($('extended_search')) {
$('extended_search_form').innerHTML = '';
} else {
extended_search_form.render();
}
});
MochiKit.Signal.connect('result_filters_button', 'onclick', function(e) {
if ($('filter_Zeit')) {
$('result_filters').innerHTML = '';
} else {
result_filters.render();
}
});
};
var draggables = [];
var connect_draggables = function() {
var results = MochiKit.DOM.getElementsByTagAndClassName(
'div', 'search_entry', $('search_result'));
forEach(results, function(result) {
draggables.push(new MochiKit.DragAndDrop.Draggable(result, {
starteffect: null,
endeffect: null}));
});
}
var disconnect_draggables = function() {
while(draggables.length > 0) {
draggables.pop().destroy();
}
}
var init = function() {
// zeit.find.tabs = new zeit.find.Tabs();
// zeit.find.tabs.add(new zeit.find.Tab('search_form', 'Suche'));
// zeit.find.tabs.add(new zeit.find.Tab('favorites', 'Favoriten'));
// zeit.find.tabs.add(new zeit.find.Tab('for-this-page', 'Für diese Seite'));
search_form.render();
};
search_form = new zeit.find.View(
'search_form', 'search_form');
search_result = new zeit.find.View(
'search_result', 'search_result',
function() {
return 'fulltext=' + $('fulltext').value;
});
extended_search_form = new zeit.find.View(
'extended_search_form', 'extended_search_form');
result_filters = new zeit.find.View(
'result_filters', 'result_filters')
MochiKit.Signal.connect(window, 'onload', init);
MochiKit.Signal.connect(search_form, 'load', init_search_form);
MochiKit.Signal.connect(search_result, 'before-load',
disconnect_draggables);
MochiKit.Signal.connect(search_result, 'load',
connect_draggables);
})();
|
JavaScript
| 0 |
@@ -5527,18 +5527,16 @@
ion() %7B%0A
-//
@@ -5574,18 +5574,16 @@
Tabs();%0A
-//
@@ -5641,26 +5641,24 @@
'Suche'));%0A
-//
zeit
@@ -5718,18 +5718,17 @@
ten'));%0A
-//
+
z
|
5bad461ec5ca28a5355f0300113593c4c98bc397
|
Fix slider value in screenshots
|
src/mmw/js/src/main_water_balance.js
|
src/mmw/js/src/main_water_balance.js
|
"use strict";
var $ = require('jquery'),
_ = require('underscore'),
R = require('retina.js'),
shutterbug = require('../shim/shutterbug'),
modificationConfig = require('./core/modificationConfig.json'),
wbm = require('./water_balance/models');
// Global jQuery needed for Bootstrap plugins.
window.jQuery = window.$ = $;
require('bootstrap');
require('bootstrap-select');
var initialize = function(model) {
// Used to convert slider values into data keys
var precipKey = ['1', '3', '5', '8', '21'];
// Cache references to DOM elements so as not to query them each time
var $etColumn = $('#column-et'),
$rColumn = $('#column-r'),
$iColumn = $('#column-i'),
$etArrow = $('#effect-evapo svg'),
$rArrow = $('#effect-runoff svg'),
$iArrow = $('#effect-infiltration svg'),
$thumbsLand = $('#thumbs-land'),
$thumbsSoil = $('#thumbs-soil'),
$precipSlider = $('#precip-slider'),
$precipText = $('#well-precip > h1'),
$etText = $('#well-evapo > h1'),
$rText = $('#well-runoff > h1'),
$iText = $('#well-infil > h1'),
$runOffAlert = $('#alert');
var getType = function($el) {
// Return thumb type, after the 'thumb-' part of id
return $el.attr('id').substring(6);
};
// The following two magic methods have been replicated from the old flash app
var percentToScale = function(percent) {
var s = Math.pow(percent, 1/3) + 0.2;
return ((s - 0.9) / 2.1) * 1.7 + 0.5;
};
var scaleArrow = function($arrow, result) {
var scale = 0;
if (result) {
scale = Math.min(percentToScale(result), 3.2);
scale = Math.max(scale, 0.2);
}
$arrow.css('height', (100 * scale) + '%');
};
var showRunoffAlert = function() {
$runOffAlert.show();
};
var hideRunoffAlert = function() {
$runOffAlert.hide();
};
var recalculate = function() {
hideRunoffAlert();
var soil = getType($thumbsSoil.children('.active')),
land = getType($thumbsLand.children('.active')),
precip = precipKey[$precipSlider.val()],
result = model[soil][land][precip];
$precipText.text(tenthsPlace(precip) + ' cm');
$etText.text(tenthsPlace(result.et) + ' cm');
$rText.text(tenthsPlace(result.r) + ' cm');
$iText.text(tenthsPlace(result.i) + ' cm');
var total = parseFloat(result.et) + parseFloat(result.r) + parseFloat(result.i);
$etColumn.css('height', (100 * result.et / total) + '%');
$rColumn.css('height', (100 * result.r / total) + '%');
$iColumn.css('height', (100 * result.i / total) + '%');
scaleArrow($etArrow, result.et);
scaleArrow($rArrow, result.r);
scaleArrow($iArrow, result.i);
// Set border radius for middle Runoff div
// which has rounded borders whenever it is on the edge
// but not when it is in the middle
var topRadius = (parseFloat(result.et) === 0) ? '0.3rem' : '0',
bottomRadius = (parseFloat(result.i) === 0) ? '0.3rem' : '0';
if(result.r >= 2) {
showRunoffAlert();
}
$rColumn.css({
'border-top-left-radius': topRadius,
'border-top-right-radius': topRadius,
'border-bottom-left-radius': bottomRadius,
'border-bottom-right-radius': bottomRadius
});
};
function tenthsPlace(x) {
return parseFloat(x).toFixed(1);
}
// Wire up events
$precipSlider.on('input', recalculate);
$('a[data-toggle="tab"]').on('shown.bs.tab', recalculate);
// Trigger the first time page loads
recalculate();
};
var initBootstrap = function() {
$('[data-toggle="tooltip"]').tooltip();
$('[data-toggle="popover"]').each(function(i, popover) {
var $popover = $(popover),
nlcd = $popover.data('nlcd') || 'default',
template = '<div class="popover" role="tooltip">' +
'<div class="arrow"></div>' +
'<h3 class="popover-title ' + ' ' + nlcd + '"></h3>' +
'<div class="popover-content"></div></div>',
entry = modificationConfig[$popover.data('name')],
options = {
content: entry.summary,
template: template,
title: entry.name
};
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
$popover.popover(_.extend(options, {triggger:'click'}));
$popover.click(function() {
$('[data-toggle="popover"]').not(this).popover('hide'); //all but this
});
} else {
$popover.popover(_.extend(options, {trigger: 'hover'}));
}
});
};
$(function() {
R.Retina.init(window);
initBootstrap();
$.ajax({
type: 'GET',
url: '/static/data/water_balance/model.csv',
dataType: 'text',
success: function(data) {
var model = wbm.WaterBalanceModel.populateModel(data);
initialize(model);
}
});
// Enable screenshot functionality
shutterbug.enable('body');
});
|
JavaScript
| 0 |
@@ -3487,24 +3487,137 @@
%0A %7D);
+%0A%0A // Set slider value attribute for screenshots%0A $precipSlider.attr('value', $precipSlider.val());
%0A %7D;%0A%0A
|
eec5574c4c9eb0b2a337c92d6e0fdec305ccb5a5
|
handle case where category is not found
|
static/javascript/directives/cfyMenu.js
|
static/javascript/directives/cfyMenu.js
|
angular.module('getcloudify').directive('cfyMenu', function( $http, $log, CfyVersion, $rootScope, $location ){
return {
restrict: 'A',
scope:{},
templateUrl: '/views/directives/menu.html',
link: function( $scope/*, element*/ ){
var articles = null;
$scope.find = '';
// todo, need to do this per version!
var categoriesOrder = [
{ 'id': 'none', 'icon': null},
{ 'id' : 'a quick tutorial', icon: 'fa fa-bicycle'},
{ 'id' : 'what is cloudify?', icon: 'fa fa-cloud'},
{ 'id': 'Getting Started', 'icon': 'fa fa-road'},
{ 'id': 'Product Overview', 'icon' : 'fa fa-eye'},
{ 'id' : 'Command-Line Interface', 'icon' : 'fa fa-terminal' },
{ 'id' : 'Web Interface', 'icon' : 'fa fa-globe' },
{ 'id' : 'Manager Blueprints', 'icon' : 'fa fa-inbox' },
{ 'id' : 'Blueprints', 'icon' : 'fa fa-map' },
{ 'id' : 'Blueprints DSL', 'icon' : 'fa fa-language' },
{ 'id' : 'Workflows', 'icon' : 'fa fa-random' },
{ 'id' : 'Plugins', 'icon' : 'fa fa-plug' },
{ 'id' : 'Official Plugins', 'icon' : 'fa fa-diamond' },
{ 'id' : 'Contributed Plugins', 'icon' : 'fa fa-gift' },
{ 'id' : 'Policies', 'icon' : 'fa fa-map-signs' },
{ 'id' : 'Agents', 'icon' : 'fa fa-suitcase' },
{ 'id' : 'Installation', 'icon' : 'fa fa-download' },
{ 'id' : 'Guides', 'icon' : 'fa fa-book' },
{ 'id' : 'Reference', 'icon' : 'fa fa-graduation-cap' },
{ 'id' : 'APIs', 'icon' : 'fa fa-cubes' },
{ 'id' : 'Troubleshooting','icon' : 'fa fa-life-ring' }
];
// use lower case to overcome mistakes. Product overview and Product Overview should be treated the same.
// keep reference to camel case representation using a map.
var categoriesMap = {};
_.each(categoriesOrder, function(x){
categoriesMap[x.id.toLowerCase()] = x ;
});
var categories = {};
var currentCategory;
var currentVersion = CfyVersion.getVersion();
$http.get('/'+currentVersion+'/articles.json').then(function(result){
// convert to list. friendlier for the following algorithm
articles = _.map( result.data , function(v,k){v.path=k; return v;});
//$log.info('all in all articles',articles.length);
// remove unpublished artickes
articles = _.filter(articles, function(i){ return i.publish && i.category; });
// sort by page order
articles = articles.sort(function(a, b){return a.pageord- b.pageord});
//$log.info('published articles', articles.length);
// turn to a tree like structure. (assuming 1 level..)
_.each(articles, function(a){
var cat = a.category.replace(' root', '').toLowerCase(); // silly convention for nodes in tree with children
if ( !categories[cat]){
categories[cat] = { links: [], displayed: true };
}
if (a.category.indexOf(' root') > 0 ){
var me = categories[cat];
me.href= a.path + '.html';
}else {
var item = {
'href': a.path + '.html',
'name' : a.title, // used for top level items
'title': a.title,
'displayed': true,
'current': document.location.href.indexOf(a.path + '.html') > 0
};
categories[cat].links.push(item);
if (document.location.pathname.indexOf(a.path + '.html') > 0) {
currentCategory = cat;
item.active = true;
}
}
});
$scope.items = _.map(categories, function(v,k){
v.name= categoriesMap[k].id;
return v;
}).sort(function(a,b){
var indexA = categoriesOrder.indexOf(categoriesMap[a.name.toLowerCase()]);
var indexB = categoriesOrder.indexOf(categoriesMap[b.name.toLowerCase()]);
if ( indexA < 0 ){
$log.error(a.name, ' cannot find category');
}
return indexA - indexB;
});
// remove cateogry 'none' and make items be at top level
var noneCategory = $scope.items.splice(0,1)[0];
_.each(noneCategory.links, function(link){
$scope.items.unshift(link);
});
_.each($scope.items, function(v){
v.isOpen = document.location.href.indexOf(v.href) > 0 || ( !!currentCategory && v.name.toLowerCase() === currentCategory.toLowerCase() ) ;
try {
v.icon = categoriesMap[v.name.toLowerCase()].icon;
}catch(e){}
});
});
$scope.$watch('find', function(){
var patt = new RegExp($scope.find,'i');
_.each($scope.items, function( item ){
var hasOneDisplayed = false;
_.each(item.links, function(link){
link.displayed = patt.test(link.title);
if (link.displayed ){
hasOneDisplayed = true;
}
});
item.displayed = hasOneDisplayed || patt.test(item.name);
})
});
$scope.groupClicked = function(item){
$log.info('group clicked',item);
if ( !!item.href ){
document.location.href = item.href;
}
}
}
}
});
|
JavaScript
| 0.000005 |
@@ -3268,32 +3268,39 @@
+if ( !!
categories%5Bcat%5D
@@ -3297,47 +3297,310 @@
ries
+Map
%5Bcat%5D
-= %7B links: %5B%5D, displayed: true %7D;
+) %7B%0A categories%5Bcat%5D = %7Blinks: %5B%5D, displayed: true%7D;%0A %7Delse%7B%0A $log.error('category ', cat , ' found in frontmatter but not declared.. will hide content');%0A return;%0A %7D
%0A
|
9896bb1e8085a28d704b0d3cf8c148f5e5c1d683
|
use iframe to send request to webview
|
TGJSBridge/TGJSBridge/TGJSBridge.js
|
TGJSBridge/TGJSBridge/TGJSBridge.js
|
//
// TGJSBridge.js
// TGJSBridge
//
// Created by Chao Shen on 12-3-1.
// Copyright (c) 2012年 Hangzhou Jiuyan Technology Co., Ltd. All rights reserved.
//
(function(context){
function JSBridge()
{
this.callbackDict = {};
this.notificationIdCount = 0;
this.notificationDict = {};
context.document.addEventListener('DOMContentLoaded',function(){
window.location.href= 'jsbridge://NotificationReady';
},false);
}
JSBridge.prototype = {
constructor: JSBridge,
//js向oc发送消息
postNotification: function(name, userInfo){
this.notificationIdCount++;
this.notificationDict[this.notificationIdCount] = {name:name, userInfo:userInfo};
window.location.href= 'jsbridge://PostNotificationWithId-' + this.notificationIdCount;
},
//oc获取消息数据
popNotificationObject: function(notificationId){
var result = JSON.stringify(this.notificationDict[notificationId]);
delete this.notificationDict[notificationId];
return result;
},
//oc向js发送消息
trigger: function(name, userInfo) {
if(this.callbackDict[name]){
var callList = this.callbackDict[name];
for(var i=0,len=callList.length;i<len;i++){
callList[i](userInfo);
}
}
},
//绑定消息
bind: function(name, callback){
if(!this.callbackDict[name]){
//创建对应数组
this.callbackDict[name] = [];
}
this.callbackDict[name].push(callback);
},
//解除绑定
unbind: function(name, callback){
//如果只提供消息名,则删除整个对应的数组
if(arguments.length == 1){
delete this.callbackDict[name];
} else if(arguments.length > 1) {
//搜索相应的callback,并删除
if(this.callbackDict[name]){
var callList = this.callbackDict[name];
for(var i=0,len=callList.length;i<len;i++){
if(callList[i] == callback){
callList.splice(i,1);
break;
}
}
}
//如果数组为空,则删除
if(this.callbackDict[name].length == 0){
delete this.callbackDict[name];
}
}
}
};
context.jsBridge = new JSBridge();
})(window);
|
JavaScript
| 0 |
@@ -174,17 +174,420 @@
ntext)%7B%0A
+ function bridgeCall(src,callback) %7B%0A%09%09iframe = document.createElement(%22iframe%22);%0A%09%09iframe.style.display = %22none%22;%0A%09%09iframe.src = src;%0A%09%09var cleanFn = function(state)%7B%0A%09%09 console.log(state) %0A%09%09 try %7B%0A%09%09 iframe.parentNode.removeChild(iframe);%0A%09%09 %7D catch (error) %7B%7D%0A%09%09 if(callback) callback();%0A%09%09%7D;%0A iframe.onload = cleanFn;%0A%09%09document.documentElement.appendChild(iframe);%0A%09%7D%0A%09
%0A
-
func
@@ -715,32 +715,57 @@
= %7B%7D;%0A %0A
+ var that = this;%0A
context.
@@ -833,38 +833,27 @@
-window.location.href=
+bridgeCall(
'jsbridg
@@ -874,16 +874,50 @@
onReady'
+,that.trigger('jsBridgeReady',%7B%7D))
;%0A
@@ -1229,30 +1229,19 @@
-window.location.href=
+bridgeCall(
'jsb
@@ -1299,16 +1299,17 @@
nIdCount
+)
;%0A
|
f1ca2c7434477dd771b47ae8760825beee7929a5
|
use named function
|
src/modules/Dropdown/DropdownItem.js
|
src/modules/Dropdown/DropdownItem.js
|
import React, { PropTypes } from 'react'
import cx from 'classnames'
import Icon from '../../elements/Icon/Icon'
import { someChildType } from '../../utils/childrenUtils'
import { useKeyOnly } from '../../utils/propUtils'
import META from '../../utils/Meta'
const DropdownItem = (props) => {
const {
active,
children,
className,
description,
icon,
onClick,
selected,
text,
value,
...rest,
} = props
const handleClick = (e) => {
onClick(e, value)
}
const classes = cx(
'sd-dropdown-item',
useKeyOnly(active, 'active'),
useKeyOnly(selected, 'selected'),
'item',
className,
)
// add default dropdown icon if item contains another menu
const iconName = icon || someChildType(children, 'DropdownMenu') && 'dropdown'
const iconClasses = cx('sd-dropdown-item-icon', iconName, 'icon')
return (
<div {...rest} className={classes} onClick={handleClick}>
{description && <span className='description'>{description}</span>}
{iconName && <Icon className={iconClasses} />}
{text}
{children}
</div>
)
}
DropdownItem._meta = {
library: META.library.semanticUI,
name: 'DropdownItem',
parent: 'Dropdown',
type: META.type.module,
}
DropdownItem.propTypes = {
// TODO: filter private methods out of docs or support @private tags
__onClick: PropTypes.func,
/** Style as the currently chosen item. */
active: PropTypes.bool,
/** Additional className. */
children: PropTypes.node,
/** Additional className. */
className: PropTypes.string,
/** Additional text with less emphasis. */
description: PropTypes.string,
/** Add an icon to the item. */
icon: PropTypes.string,
/**
* The item currently selected by keyboard shortcut.
* This is not the active item.
*/
selected: PropTypes.bool,
/** Display text. */
text: PropTypes.string,
/** Stored value */
value: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
/** Called on click with (event, value, text). */
onClick: PropTypes.func,
}
export default DropdownItem
|
JavaScript
| 0.000009 |
@@ -253,21 +253,24 @@
/Meta'%0A%0A
-const
+function
Dropdow
@@ -278,21 +278,15 @@
Item
- =
(props)
- =%3E
%7B%0A
|
dcf59b6e15aea801eba3e20aa4c0f3d85024636d
|
add comments
|
src/nake.js
|
src/nake.js
|
#!/usr/bin/jjs -scripting
var global = this;
(function() {
var File = Java.type("java.io.File");
var fatalError = function (message) {
print(message);
exit(1);
};
global.path = $ENV['PWD'];
var findClosestNakefile = function (path) {
var nakefile = new File(path + "/Nakefile");
if (nakefile.exists()) {
return nakefile;
}
var parent = new File(path).getParentFile();
if (!parent) {
return undefined;
}
return findClosestNakefile(parent.getAbsolutePath());
};
var nakefile = findClosestNakefile(global.path);
if (!nakefile) {
fatalError("no Nakefile found for directory: ${global.path}");
}
var tasks = {};
var task = function(name, description, action) {
tasks[name] = {
name: name,
description: description,
action: action
};
};
global.task = task;
var run = function (name, options) {
var currentTask = tasks[name];
if (!currentTask) {
fatalError("no such task: ${taskName}\nuse 'nake' to list all available tasks");
}
try {
currentTask.action.call(global, options);
}
catch (e) {
fatalError("execution of task ${currentTask.name} failed: ${e}");
}
};
global.run = run;
var printTasks = function() {
print("Tasks defined in ${global.path}/Nakefile\n");
var length = 0;
for (var taskName in tasks) {
if (taskName.length() > length) {
length = taskName.length();
}
}
for each (var task in tasks) {
var name = task.name;
while (name.length() < length) {
name += " ";
}
var line = " ${name} ${task.description}";
print(line);
}
print("\nuse 'nake -- taskName' to run a specific task");
};
// evaluate Nakefile
load(nakefile.getAbsolutePath());
var args = $ARG;
if (args.length == 0) {
printTasks();
exit(0);
}
var taskName = args[0];
var options = [];
if (args.length > 1) {
options = args.slice(1);
}
var currentTask = tasks[taskName];
if (!currentTask) {
fatalError("no such task: ${taskName}\nuse 'nake' to list all available tasks");
}
try {
currentTask.action.call(global, options);
}
catch (e) {
fatalError("execution of task ${currentTask.name} failed: ${e}");
}
})();
|
JavaScript
| 0 |
@@ -24,27 +24,105 @@
ng%0A%0A
-var global = this;%0A
+%0A// tasks will be run in this context%0Avar global = this;%0A%0A%0A// local scope for nake internal stuff
%0A(fu
@@ -244,32 +244,33 @@
exit(1);%0A %7D;%0A%0A
+%0A
global.path =
@@ -283,16 +283,65 @@
PWD'%5D;%0A%0A
+ // find nearest Nakefile for current directory%0A
var fi
@@ -782,32 +782,33 @@
l.path%7D%22);%0A %7D%0A%0A
+%0A
var tasks = %7B%7D
@@ -806,24 +806,53 @@
asks = %7B%7D;%0A%0A
+ // register a task by name%0A
var task =
@@ -1014,24 +1014,57 @@
k = task;%0A%0A%0A
+ // run a specific task by name%0A
var run =
@@ -1079,22 +1079,23 @@
(name,
-option
+taskArg
s) %7B%0A
@@ -1287,30 +1287,31 @@
all(global,
-option
+taskArg
s);%0A %7D%0A
@@ -1429,16 +1429,17 @@
= run;%0A%0A
+%0A
var pr
@@ -2044,16 +2044,17 @@
ength ==
+=
0) %7B%0A
@@ -2119,22 +2119,23 @@
;%0A var
-option
+taskArg
s = %5B%5D;%0A
@@ -2163,22 +2163,23 @@
) %7B%0A
-option
+taskArg
s = args
@@ -2342,16 +2342,51 @@
);%0A %7D%0A%0A
+ // call task with global context%0A
try %7B%0A
@@ -2425,14 +2425,15 @@
al,
-option
+taskArg
s);%0A
|
02a055819bd7362e378cd5d9d306e06fc4e8cc0f
|
Clean up
|
src/nano.js
|
src/nano.js
|
(function (root) {
'use strict';
function nano(selector) {
return new dom(selector);
}
/**
* Selector method
* @returns: A collection of nodes
*/
var dom = function (selector) {
if (!selector) {
return this;
}
this.length = 0;
this.nodes = [];
if (selector instanceof HTMLElement || selector instanceof NodeList) {
this.nodes = (selector.length > 1) ? [].slice.call(selector) : [selector];
} else if (typeof selector === 'string') {
if (selector[0] === '<' && selector[selector.length - 1] === '>') {
this.nodes = [nano.createNode(selector)];
} else {
this.nodes = [].slice.call(document.querySelectorAll(selector));
}
}
if (this.nodes.length) {
this.length = this.nodes.length;
for (var i = 0; i < this.nodes.length; i++) {
this[i] = this.nodes[i];
}
}
return this;
};
nano.createNode = function (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.firstChild;
}
nano.each = function (collection, callback) {
var l = collection.length;
for (var i = 0; i < l; i++) {
callback.call(collection[i], collection, i);
}
}
/**
* DOM manipulation methods
*/
nano.fn = dom.prototype = {
/**
* Iterates through a collection and calls the callback method on each
*/
each: function (callback) {
nano.each(this, callback);
},
/**
* Returns first element in array
*/
first: function () {
return nano(this[0]);
},
/**
* Returns last element in array
*/
last: function () {
return nano(this[this.length - 1]);
},
/**
* Show elements in DOM
*/
show: function () {
var l = this.length;
while (l--) {
this[l].style.display = 'block';
}
return this;
},
/**
* Hide elements from DOM
*/
hide: function () {
var l = this.length;
while (l--) {
this[l].style.display = 'none';
}
return this;
},
/**
* Check if element has class
*/
hasClass: function (className) {
if (document.documentElement.classList) {
return this[0].classList.contains(className);
} else {
return new RegExp('(^|\\s)' + className + '(\\s|$)').test(this[0].className);
}
},
/**
* Add class to elements
*/
addClass: function (className) {
if (!this.hasClass(className)) {
if (document.documentElement.classList) {
return this.each(function () {
this.classList.add(className);
});
} else {
return this.each(function () {
this.className += ' ' + className;
});
}
}
},
/**
* Remove class from elements
*/
removeClass: function (className) {
if (this.hasClass(className)) {
if (document.documentElement.classList) {
return this.each(function () {
this.classList.remove(className);
});
} else {
return this.each(function () {
this.className = this.className.replace(new RegExp('(^|\\s)*' + className + '(\\s|$)*', 'g'), '');
});
}
}
},
// /**
// * Toggle class on elements
// */
toggleClass: function (className) {
if (document.documentElement.classList) {
return this.each(function () {
this.classList.toggle(className);
});
} else {
return this.each(function () {
if (this.hasClass(className)) {
this.removeClass(className);
} else {
this.addClass(className);
}
});
}
},
/**
* Callback method on DOMContentLoaded
* TODO: Add this[0] instead of document to function
*/
ready: function (callback) {
document.addEventListener("DOMContentLoaded", callback);
},
/**
* Add event
*/
on: function (type, callback) {
if (document.addEventListener) {
return this.each(function () {
this.addEventListener(type, callback, false);
});
} else if (document.attachEvent) {
return this.each(function () {
this.attachEvent('on' + type, callback);
});
}
},
/**
* Remove event
*/
off: function () {
if (document.removeEventListener) {
return this.each(function () {
this.removeEventListener(type, callback, false);
});
} else if (document.detachEvent) {
return this.each(function () {
this.detachEvent('on' + type, callback);
});
}
}
}
root.nano = root.$ = nano;
})(this);
|
JavaScript
| 0.000002 |
@@ -138,47 +138,8 @@
hod%0A
- * @returns: A collection of nodes%0A
@@ -3914,19 +3914,16 @@
%0A
- //
/**%0A
@@ -3926,19 +3926,16 @@
%0A
- //
* Togg
@@ -3966,11 +3966,8 @@
- //
*/
|
258a4eadcdc01e67effc0bfd9ad7676087ea4dd9
|
Update _TabPageApi.js
|
static/sqleditor/widgets/_TabPageApi.js
|
static/sqleditor/widgets/_TabPageApi.js
|
define([
'dojo/_base/declare',
'sqleditor/widgets/TabPage'
], function (declare, TabPage){
return declare(null, {
buttonSaveClick: function () {
},
comboboxOnChange: function () {
},
buttonRunClick: function () {
},
buttonNewClick: function () {
}
});
});
|
JavaScript
| 0 |
@@ -176,60 +176,8 @@
%7D,%0A%0A
- comboboxOnChange: function () %7B%0A %7D,%0A%0A
@@ -269,16 +269,139 @@
%7D
+,%0A %0A buttonLogoutClick: function () %7B%0A %7D,%0A %0A comboboxSystemsOnChange: function () %7B%0A %7D,
%0A%0A %7D)
@@ -405,8 +405,9 @@
%7D);%0A%7D);
+%0A
|
3e6dbd5d4740da2bfa77dd34a294406661686220
|
fix name
|
src/nest.js
|
src/nest.js
|
import compose from './compose'
const curried = (key, convert) => {
return (payloadCreator) => (...input) => {
return convert(key, payloadCreator, ...input)
}
}
export const nest = (convert) => {
return (...keys) => {
const nestFuncs = keys.map(
(key) => curried(key, convert)
)
return compose(...nestFuncs)
}
}
export default nest
|
JavaScript
| 0.999457 |
@@ -32,23 +32,23 @@
%0A%0Aconst
-curried
+resolve
= (key,
@@ -274,15 +274,15 @@
=%3E
-curried
+resolve
(key
|
f6379fdf40ff75e93bd672218a7171697e5e95ec
|
allow options in datepicker via df.options
|
frappe/public/js/frappe/form/controls/date.js
|
frappe/public/js/frappe/form/controls/date.js
|
frappe.ui.form.ControlDate = class ControlDate extends frappe.ui.form.ControlData {
static trigger_change_on_input_event = false
make_input() {
super.make_input();
this.make_picker();
}
make_picker() {
this.set_date_options();
this.set_datepicker();
this.set_t_for_today();
}
set_formatted_input(value) {
super.set_formatted_input(value);
if (this.timepicker_only) return;
if (!this.datepicker) return;
if (!value) {
this.datepicker.clear();
return;
} else if (value === "Today") {
value = this.get_now_date();
}
let should_refresh = this.last_value && this.last_value !== value;
if (!should_refresh) {
if(this.datepicker.selectedDates.length > 0) {
// if date is selected but different from value, refresh
const selected_date =
moment(this.datepicker.selectedDates[0])
.format(this.date_format);
should_refresh = selected_date !== value;
} else {
// if datepicker has no selected date, refresh
should_refresh = true;
}
}
if(should_refresh) {
this.datepicker.selectDate(frappe.datetime.str_to_obj(value));
}
}
set_date_options() {
// webformTODO:
let sysdefaults = frappe.boot.sysdefaults;
let lang = 'en';
frappe.boot.user && (lang = frappe.boot.user.language);
if(!$.fn.datepicker.language[lang]) {
lang = 'en';
}
let date_format = sysdefaults && sysdefaults.date_format
? sysdefaults.date_format : 'yyyy-mm-dd';
let now_date = new Date();
this.today_text = __("Today");
this.date_format = frappe.defaultDateFormat;
this.datepicker_options = {
language: lang,
autoClose: true,
todayButton: true,
dateFormat: date_format,
startDate: now_date,
keyboardNav: false,
onSelect: () => {
this.$input.trigger('change');
},
onShow: () => {
this.datepicker.$datepicker
.find('.datepicker--button:visible')
.text(this.today_text);
this.update_datepicker_position();
}
};
}
set_datepicker() {
this.$input.datepicker(this.datepicker_options);
this.datepicker = this.$input.data('datepicker');
// today button didn't work as expected,
// so explicitly bind the event
this.datepicker.$datepicker
.find('[data-action="today"]')
.click(() => {
this.datepicker.selectDate(this.get_now_date());
});
}
update_datepicker_position() {
if(!this.frm) return;
// show datepicker above or below the input
// based on scroll position
// We have to bodge around the timepicker getting its position
// wrong by 42px when opening upwards.
const $header = $('.page-head');
const header_bottom = $header.position().top + $header.outerHeight();
const picker_height = this.datepicker.$datepicker.outerHeight() + 12;
const picker_top = this.$input.offset().top - $(window).scrollTop() - picker_height;
var position = 'top left';
// 12 is the default datepicker.opts[offset]
if (picker_top <= header_bottom) {
position = 'bottom left';
if (this.timepicker_only) this.datepicker.opts['offset'] = 12;
} else {
// To account for 42px incorrect positioning
if (this.timepicker_only) this.datepicker.opts['offset'] = -30;
}
this.datepicker.update('position', position);
}
get_now_date() {
return frappe.datetime.now_date(true);
}
set_t_for_today() {
var me = this;
this.$input.on("keydown", function(e) {
if(e.which===84) { // 84 === t
if(me.df.fieldtype=='Date') {
me.set_value(frappe.datetime.nowdate());
} if(me.df.fieldtype=='Datetime') {
me.set_value(frappe.datetime.now_datetime());
} if(me.df.fieldtype=='Time') {
me.set_value(frappe.datetime.now_time());
}
return false;
}
});
}
parse(value) {
if(value) {
return frappe.datetime.user_to_str(value);
}
}
format_for_input(value) {
if(value) {
return frappe.datetime.str_to_user(value);
}
return "";
}
validate(value) {
if(value && !frappe.datetime.validate(value)) {
let sysdefaults = frappe.sys_defaults;
let date_format = sysdefaults && sysdefaults.date_format
? sysdefaults.date_format : 'yyyy-mm-dd';
frappe.msgprint(__("Date {0} must be in format: {1}", [value, date_format]));
return '';
}
return value;
}
};
|
JavaScript
| 0.000001 |
@@ -1927,24 +1927,55 @@
tion();%0A%09%09%09%7D
+,%0A%09%09%09...(this.get_df_options())
%0A%09%09%7D;%0A%09%7D%0A%09se
@@ -4205,11 +4205,376 @@
lue;%0A%09%7D%0A
+%09get_df_options() %7B%0A%09%09let options = %7B%7D;%0A%09%09let df_options = this.df.options %7C%7C '';%0A%09%09if (typeof df_options === 'string') %7B%0A%09%09%09try %7B%0A%09%09%09%09options = JSON.parse(df_options);%0A%09%09%09%7D catch (error) %7B%0A%09%09%09%09console.warn(%60Invalid JSON in options of %22$%7Bthis.df.fieldname%7D%22%60);%0A%09%09%09%7D%0A%09%09%7D%0A%09%09else if (typeof df_options === 'object') %7B%0A%09%09%09options = df_options;%0A%09%09%7D%0A%09%09return options;%0A%09%7D%0A
%7D;%0A
|
1c6a339d6d925eea6ec6a3242d1cea0c7ba4bbbf
|
Fix bug in date parsing function
|
step-capstone/src/scripts/Suggestion.js
|
step-capstone/src/scripts/Suggestion.js
|
import queryPlaces from './PlacesQuery';
import categories from './Categories';
const getDateString = (dateObject) => {
return dateObject.getFullYear() + "-" + dateObject.getMonth() + "-" + dateObject.getDate();
}
const contains = (startTime, endTime, timePoint) => {
// return whether timeRange from startTime to endTime contains timePoint
return startTime < timePoint && timePoint < endTime;
}
const overlaps = (openingTime, closingTime, startTime, endTime) => {
/**
* Case 1:
* opening-closing: |----------|
* start-end : |----------|
*
* Case 2:
* opening-closing: |----------|
* start-end : |----------|
*
* Case 3:
* opening-closing: |----------|
* start-end : |------|
*
* Case 4:
* opening-closing: |----|
* start-end : |----------|
*
*/
if (contains(openingTime, closingTime, startTime) && !contains(openingTime, closingTime, endTime)) {
return millisToMinutes(closingTime - startTime);
}
else if (contains(startTime, endTime, openingTime) && !contains(startTime, endTime, closingTime)) {
return millisToMinutes(endTime - openingTime);
}
else if (contains(openingTime, closingTime, startTime) && contains(openingTime, closingTime, endTime)) {
return millisToMinutes(endTime - startTime);
}
else if (contains(startTime, endTime, openingTime) && !contains(startTime, endTime, closingTime)) {
return millisToMinutes(closingTime - openingTime);
}
else {
return 0;
}
}
const millisToMinutes = (millis) => {
var minutes = Math.floor(millis / 60000);
return minutes;
}
const filterByTimeRange = (results, timeRange) => {
results.filter((result) => {
if (result.hasOwnProperty("opening_hours")) {
let day = timeRange[0].getDay();
let openHoursMinutes = result.opening_hour.period[day].open.time;
let closeHoursMinutes = (result.opening_hour.period[day].close !== undefined)?
result.opening_hour.period[day].close.time
: "2359";
let date = getDateString(timeRange[0]);
let openingTime = new Date(date + "T" + openHoursMinutes.slice(0, 2) + ":" + openHoursMinutes.splice(2) +":00");
let closingTime = new Date(date + "T" + closeHoursMinutes.slice(0, 2) + ":" + closeHoursMinutes.splice(2) + ":00");
return overlaps(openingTime, closingTime, timeRange[0], timeRange[1]) >= 45;
}
return true;
})
}
const query = (coordinates, service) => {
// return results: a map with key : place_id, value: PlaceObject
let places = queryPlaces(coordinates, radius, service, ["tourist_attraction", "natural_feature"])
places.then(results => {
return results;
})
}
const countCat = (placeObject, userCat) => {
// Count the number of categories a place fits into
let cats = 0;
userCat.forEach(catString => {
placeObject.place.types.forEach(type => {
if (categories.get(catString).has(type)) {
cats += 1;
break;
}
})
})
return cats;
}
const getScore = (placeCat, userCat, prominence, placePrice, userBudget, rating) => {
// return the score for a PlaceObject
var catScore = 0;
if (cat !== 0) {
catScore = 60 + 40/userCat * placeCat;
}
var prominenceScore = (prominence.total - prominence.index)**2/(prominence.total)**2 * 100;
var budgetScore = 0;
if (placePrice === null) {
budgetScore = 50;
} else if (userBudget < placePrice) {
budgetScore = 0;
} else {
budgetScore = 100;
}
var ratingScore = rating* 20;
return catScore * 0.65 + prominenceScore * 0.15 + budgetScore * 0.1 + ratingScore * 0.1;
}
const rank = (results, config) => {
// return a list of placeObjects with score calculated
let placeObjects = []
results.forEach(placeObject => {
let placeCat = countCat(placeObject, config.userCat);
let score = getScore(placeCat, config.userCat.length, placeObject.prominence,
placeObject.place.price_level, config.userBudget, placeObject.place.rating);
placeObject.score = score;
placeObjects.push(placeObject);
})
return placeObjects;
}
const placeObjectsComparator = (placeObjectA, placeObjectB) => {
return placeObjectA.score - placeObjectB.score;
}
export default function handleSuggestions(service, config) {
let results = query(config.coordinates, config.radius, service);
let placeObjects = rank(results, config);
placeObjects.sort(placeObjectsComparator);
return placeObjects;
}
|
JavaScript
| 0.00001 |
@@ -80,24 +80,31 @@
%0A%0Aconst getD
+isplayD
ateString =
@@ -109,19 +109,19 @@
= (d
-ateObject)
+isplayDate)
=%3E
@@ -130,101 +130,307 @@
-return dateObject.getFullYear() + %22-
+let year = displayDate.getFullYear().toString();%0A let month = (displayDate.getMonth() %3C10)? %220
%22 + d
-ateObject.getMonth() + %22-
+isplayDate.getMonth() : displayDate.getMonth();%0A let date = (displayDate.getDate() %3C 10)? %220
%22 + d
-ateObject.getDate();%0A%7D
+isplayDate.getDate() : displayDate.getDate();;%0A return year + %22-%22 + month + %22-%22 + date;%0A %7D;
%0A%0Aco
|
27492fe1a5e27ad5560805baa6f33b555300955d
|
Remove RHOC as accessable token
|
frontend/packages/dapple/package-post-init.js
|
frontend/packages/dapple/package-post-init.js
|
const config = require('./config.json');
const ENVs = {
'test': 'kovan',
'main': 'live',
'private': 'default',
};
Dapple.init = function init(env) {
var predefinedEnv = ENVs[env];
if (!predefinedEnv) {
predefinedEnv = env;
}
Dapple.env = predefinedEnv;
Dapple['maker-otc']['environments'][Dapple.env].otc.value = config.market[Dapple.env].address;
Dapple['maker-otc']['environments'][Dapple.env].otc.blockNumber = config.market[Dapple.env].blockNumber;
Dapple['maker-otc'].class(web3Obj, Dapple['maker-otc'].environments[Dapple.env]);
Dapple['ds-eth-token'].class(web3Obj, Dapple['ds-eth-token'].environments[Dapple.env]);
Dapple['token-wrapper'].class(web3Obj, Dapple['token-wrapper'].environments[Dapple.env]);
if (env) {
// Check if contract exists on new environment
const contractAddress = Dapple['maker-otc'].environments[Dapple.env].otc.value;
web3Obj.eth.getCode(contractAddress, (error, code) => {
Session.set('contractExists', !error && typeof code === 'string' && code !== '' && code !== '0x');
});
}
};
const tokens = config.tokens;
// http://numeraljs.com/ for formats
const tokenSpecs = {
'OW-ETH': { precision: 18, format: '0,0.00[0000000000000000]' },
'W-ETH': { precision: 18, format: '0,0.00[0000000000000000]' },
DAI: { precision: 18, format: '0,0.00[0000000000000000]' },
SAI: { precision: 18, format: '0,0.00[0000000000000000]' },
MKR: { precision: 18, format: '0,0.00[0000000000000000]' },
DGD: { precision: 9, format: '0,0.00[0000000]' },
GNT: { precision: 18, format: '0,0.00[0000000000000000]' },
'W-GNT': { precision: 18, format: '0,0.00[0000000000000000]' },
REP: { precision: 18, format: '0,0.00[0000000000000000]' },
ICN: { precision: 18, format: '0,0.00[0000000000000000]' },
'1ST': { precision: 18, format: '0,0.00[0000000000000000]' },
SNGLS: { precision: 0, format: '0,0' },
VSL: { precision: 18, format: '0,0.00[0000000000000000]' },
PLU: { precision: 18, format: '0,0.00[0000000000000000]' },
MLN: { precision: 18, format: '0,0.00[0000000000000000]' },
RHOC: { precision: 8, format: '0,0.00[000000]' },
TIME: { precision: 8, format: '0,0.00[000000]' },
GUP: { precision: 3, format: '0,0.00[0]' },
BAT: { precision: 18, format: '0,0.00[0000000000000000]' },
NMR: { precision: 18, format: '0,0.00[0000000000000000]' },
};
Dapple.getQuoteTokens = () => ['W-ETH'];
Dapple.getBaseTokens = () => ['W-GNT', 'DGD', 'REP', 'ICN', '1ST', 'SNGLS', 'VSL', 'PLU', 'MLN', 'RHOC', 'TIME', 'GUP', 'BAT', 'NMR'];
Dapple.getTokens = () => ['W-ETH', 'MKR', 'DGD', 'GNT', 'W-GNT', 'REP', 'ICN', '1ST', 'SNGLS', 'VSL', 'PLU', 'MLN', 'RHOC', 'TIME', 'GUP', 'BAT', 'NMR', 'SAI'];
Dapple.generatePairs = () => {
const TradingPairs = [
{
base: 'MKR',
quote: 'W-ETH',
priority: 10,
},
{
base: 'W-ETH',
quote: 'SAI',
priority: 9,
},
{
base: 'MKR',
quote: 'SAI',
priority: 8,
},
];
Dapple.getBaseTokens().forEach((base) => {
Dapple.getQuoteTokens().forEach((quote) => {
TradingPairs.push({
base,
quote,
priority: 0,
});
});
});
return TradingPairs;
};
Dapple.getTokenSpecs = (symbol) => {
if (typeof (tokenSpecs[symbol]) !== 'undefined') {
return tokenSpecs[symbol];
}
return tokenSpecs['W-ETH'];
};
Dapple.getTokenAddress = (symbol) => tokens[Dapple.env][symbol];
Dapple.getTokenByAddress = (address) => _.invert(tokens[Dapple.env])[address];
Dapple.getToken = (symbol, callback) => {
if (!(Dapple.env in tokens)) {
callback('Unknown environment', null);
return;
}
if (!(symbol in tokens[Dapple.env])) {
callback(`Unknown token "${symbol}"`, null);
return;
}
const address = Dapple.getTokenAddress(symbol);
let tokenClass = 'DSTokenBase';
let that = Dapple['ds-eth-token'];
if (symbol === 'W-ETH' || symbol === 'OW-ETH') {
tokenClass = 'DSEthToken';
} else if (symbol === 'W-GNT') {
tokenClass = 'TokenWrapper';
that = Dapple['token-wrapper'];
}
try {
that.classes[tokenClass].at(address, (error, token) => {
if (!error) {
token.abi = that.classes[tokenClass].abi;
callback(false, token);
} else {
callback(error, token);
}
});
} catch (e) {
callback(e, null);
}
};
|
JavaScript
| 0 |
@@ -2483,32 +2483,24 @@
PLU', 'MLN',
- 'RHOC',
'TIME', 'GU
@@ -2638,16 +2638,8 @@
LN',
- 'RHOC',
'TI
|
053fe39a00914c8b18116873f7c6563b19062300
|
Fix exclude filter (#40)
|
src/ping.js
|
src/ping.js
|
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var orm = require('../lib/orm');
var parser = require('../lib/parser');
var pings = {
check: async (function(vendor) {
var maxTimeDiff, stores;
if(typeof vendor !== 'undefined') {
maxTimeDiff = 1500;
stores = await (orm.getStores('exclude', [901, 902, 903], vendor));
} else {
maxTimeDiff = 16200;
stores = await (orm.getStores('exclude', [1, 5, 6, 11, 901, 902, 903]));
}
stores.forEach(function(store) {
var ping = await (orm.getLastPing(store.store_id));
console.log('Last ping for store: ' + store);
console.log(ping);
var down = false;
var now = new Date();
console.log('Now date: ' + now);
var parsedNow = parser.parseNow(now);
console.log('Parsed now: ' + parsedNow);
if(ping.length > 0) {
var diff = parser.getTimeDifference(now, ping[0].created_at);
console.log('Diff: ' + diff);
if(diff > maxTimeDiff) {
down = true;
}
}
if(down) {
await (orm.insertError(store.store_id, 901, parsedNow));
console.log('Error agregado a la máquina ' + store.store_id);
}
await (orm.cleanPings(store.store_id));
console.log('Pings antiguos han sido eliminados.');
});
process.exit();
})
};
pings.check(process.argv[2]);
|
JavaScript
| 0 |
@@ -340,16 +340,29 @@
lude', %5B
+1, 5, 6, 11,
901, 902
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.