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 |
|---|---|---|---|---|---|---|---|
437b2bfc6483746d00dc87572390243950058f23 | Move `title` attribute of buttons from `<span>` to `<a>` | src/node/utils/toolbar.js | src/node/utils/toolbar.js | /**
* The Toolbar Module creates and renders the toolbars and buttons
*/
var _ = require("underscore")
, tagAttributes
, tag
, defaultButtons
, Button
, ButtonsGroup
, Separator
, defaultButtonAttributes;
defaultButtonAttributes = function (name, overrides) {
return {
command: name,
localizationId: "pad.toolbar." + name + ".title",
class: "buttonicon buttonicon-" + name
};
};
tag = function (name, attributes, contents) {
var aStr = tagAttributes(attributes);
if (_.isString(contents) && contents.length > 0) {
return '<' + name + aStr + '>' + contents + '</' + name + '>';
}
else {
return '<' + name + aStr + '></' + name + '>';
}
};
tagAttributes = function (attributes) {
attributes = _.reduce(attributes || {}, function (o, val, name) {
if (!_.isUndefined(val)) {
o[name] = val;
}
return o;
}, {});
return " " + _.map(attributes, function (val, name) {
return "" + name + '="' + _.escape(val) + '"';
}).join(" ");
};
ButtonsGroup = function () {
this.buttons = [];
};
ButtonsGroup.fromArray = function (array) {
var btnGroup = new this;
_.each(array, function (btnName) {
btnGroup.addButton(Button.load(btnName));
});
return btnGroup;
};
ButtonsGroup.prototype.addButton = function (button) {
this.buttons.push(button);
return this;
};
ButtonsGroup.prototype.render = function () {
if (this.buttons.length == 1) {
this.buttons[0].grouping = "";
}
else {
_.first(this.buttons).grouping = "grouped-left";
_.last(this.buttons).grouping = "grouped-right";
_.each(this.buttons.slice(1, -1), function (btn) {
btn.grouping = "grouped-middle"
});
}
return _.map(this.buttons, function (btn) {
return btn.render();
}).join("\n");
};
Button = function (attributes) {
this.attributes = attributes;
};
Button.load = function (btnName) {
var button = module.exports.availableButtons[btnName];
if (button.constructor === Button || button.constructor === SelectButton) {
return button;
}
else {
return new Button(button);
}
};
_.extend(Button.prototype, {
grouping: "",
render: function () {
var liAttributes = {
"data-type": "button",
"data-key": this.attributes.command,
};
return tag("li", liAttributes,
tag("a", { "class": this.grouping },
tag("span", { "class": " "+ this.attributes.class, "data-l10n-id": this.attributes.localizationId })
)
);
}
});
SelectButton = function (attributes) {
this.attributes = attributes;
this.options = [];
};
_.extend(SelectButton.prototype, Button.prototype, {
addOption: function (value, text, attributes) {
this.options.push({
value: value,
text: text,
attributes: attributes
});
return this;
},
select: function (attributes) {
var self = this
, options = [];
_.each(this.options, function (opt) {
var a = _.extend({
value: opt.value
}, opt.attributes);
options.push( tag("option", a, opt.text) );
});
return tag("select", attributes, options.join(""));
},
render: function () {
var attributes = {
id: this.attributes.id,
"data-key": this.attributes.command,
"data-type": "select"
};
return tag("li", attributes,
this.select({ id: this.attributes.selectId })
);
}
});
Separator = function () {};
Separator.prototype.render = function () {
return tag("li", { "class": "separator" });
};
module.exports = {
availableButtons: {
bold: defaultButtonAttributes("bold"),
italic: defaultButtonAttributes("italic"),
underline: defaultButtonAttributes("underline"),
strikethrough: defaultButtonAttributes("strikethrough"),
orderedlist: {
command: "insertorderedlist",
localizationId: "pad.toolbar.ol.title",
class: "buttonicon buttonicon-insertorderedlist"
},
unorderedlist: {
command: "insertunorderedlist",
localizationId: "pad.toolbar.ul.title",
class: "buttonicon buttonicon-insertunorderedlist"
},
indent: defaultButtonAttributes("indent"),
outdent: {
command: "outdent",
localizationId: "pad.toolbar.unindent.title",
class: "buttonicon buttonicon-outdent"
},
undo: defaultButtonAttributes("undo"),
redo: defaultButtonAttributes("redo"),
clearauthorship: {
command: "clearauthorship",
localizationId: "pad.toolbar.clearAuthorship.title",
class: "buttonicon buttonicon-clearauthorship"
},
importexport: {
command: "import_export",
localizationId: "pad.toolbar.import_export.title",
class: "buttonicon buttonicon-import_export"
},
timeslider: {
command: "showTimeSlider",
localizationId: "pad.toolbar.timeslider.title",
class: "buttonicon buttonicon-history"
},
savedrevision: defaultButtonAttributes("savedRevision"),
settings: defaultButtonAttributes("settings"),
embed: defaultButtonAttributes("embed"),
showusers: defaultButtonAttributes("showusers"),
timeslider_export: {
command: "import_export",
localizationId: "timeslider.toolbar.exportlink.title",
class: "buttonicon buttonicon-import_export"
},
timeslider_returnToPad: {
command: "timeslider_returnToPad",
localizationId: "timeslider.toolbar.returnbutton",
class: "buttontext"
}
},
registerButton: function (buttonName, buttonInfo) {
this.availableButtons[buttonName] = buttonInfo;
},
button: function (attributes) {
return new Button(attributes);
},
separator: function () {
return (new Separator).render();
},
selectButton: function (attributes) {
return new SelectButton(attributes);
},
menu: function (buttons) {
var groups = _.map(buttons, function (group) {
return ButtonsGroup.fromArray(group).render();
});
return groups.join(this.separator());
}
};
| JavaScript | 0 | @@ -2333,16 +2333,64 @@
grouping
+, %22data-l10n-id%22: this.attributes.localizationId
%7D,%0A
@@ -2446,56 +2446,8 @@
lass
-, %22data-l10n-id%22: this.attributes.localizationId
%7D)%0A
@@ -5057,20 +5057,16 @@
sers%22),%0A
-
%0A tim
@@ -5234,20 +5234,16 @@
%0A %7D,%0A
-
%0A tim
|
06bb56eff20182522d6d1620483d7e200314c156 | Fix typecasts in ol.layer.TileLayer | src/ol/layer/tilelayer.js | src/ol/layer/tilelayer.js | goog.provide('ol.layer.TileLayer');
goog.require('ol.layer.Layer');
goog.require('ol.source.TileSource');
/**
* @constructor
* @extends {ol.layer.Layer}
* @param {ol.layer.LayerOptions} layerOptions Layer options.
*/
ol.layer.TileLayer = function(layerOptions) {
goog.base(this, layerOptions);
};
goog.inherits(ol.layer.TileLayer, ol.layer.Layer);
/**
* @return {ol.source.TileSource} Source.
*/
ol.layer.TileLayer.prototype.getTileSource = function() {
return /** @type {ol.source.TileSource} */ this.getSource();
};
| JavaScript | 0.000003 | @@ -506,16 +506,17 @@
rce%7D */
+(
this.get
@@ -523,13 +523,14 @@
Source()
+)
;%0A%7D;%0A
|
6259caf634ab74f247b278cd27ecb29270a1701a | Consistently return a function or undefined | src/ol/proj/transforms.js | src/ol/proj/transforms.js | goog.provide('ol.proj.transforms');
goog.require('ol');
goog.require('ol.obj');
/**
* @private
* @type {Object.<string, Object.<string, ol.TransformFunction>>}
*/
ol.proj.transforms.cache_ = {};
/**
* Clear the transform cache.
*/
ol.proj.transforms.clear = function() {
ol.proj.transforms.cache_ = {};
};
/**
* Registers a conversion function to convert coordinates from the source
* projection to the destination projection.
*
* @param {ol.proj.Projection} source Source.
* @param {ol.proj.Projection} destination Destination.
* @param {ol.TransformFunction} transformFn Transform.
*/
ol.proj.transforms.add = function(source, destination, transformFn) {
var sourceCode = source.getCode();
var destinationCode = destination.getCode();
var transforms = ol.proj.transforms.cache_;
if (!(sourceCode in transforms)) {
transforms[sourceCode] = {};
}
transforms[sourceCode][destinationCode] = transformFn;
};
/**
* Unregisters the conversion function to convert coordinates from the source
* projection to the destination projection. This method is used to clean up
* cached transforms during testing.
*
* @param {ol.proj.Projection} source Source projection.
* @param {ol.proj.Projection} destination Destination projection.
* @return {ol.TransformFunction} transformFn The unregistered transform.
*/
ol.proj.transforms.remove = function(source, destination) {
var sourceCode = source.getCode();
var destinationCode = destination.getCode();
var transforms = ol.proj.transforms.cache_;
ol.DEBUG && console.assert(sourceCode in transforms,
'sourceCode should be in transforms');
ol.DEBUG && console.assert(destinationCode in transforms[sourceCode],
'destinationCode should be in transforms of sourceCode');
var transform = transforms[sourceCode][destinationCode];
delete transforms[sourceCode][destinationCode];
if (ol.obj.isEmpty(transforms[sourceCode])) {
delete transforms[sourceCode];
}
return transform;
};
/**
* Get a transform given a source code and a destination code.
* @param {string} sourceCode The code for the source projection.
* @param {string} destinationCode The code for the destination projection.
* @return {?ol.TransformFunction} The transform function (if found).
*/
ol.proj.transforms.get = function(sourceCode, destinationCode) {
var transform = null;
var transforms = ol.proj.transforms.cache_;
if (sourceCode in transforms && destinationCode in transforms[sourceCode]) {
transform = transforms[sourceCode][destinationCode];
}
return transform;
};
| JavaScript | 0.998496 | @@ -2211,9 +2211,8 @@
rn %7B
-?
ol.T
@@ -2227,16 +2227,26 @@
Function
+%7Cundefined
%7D The tr
@@ -2362,15 +2362,8 @@
form
- = null
;%0A
|
d8c84cbf9766c172f10844eda70380107c50d9b1 | Add back button to episodes list | src/pages/series.js | src/pages/series.js | // npm packages
import _ from 'lodash';
import React from 'react';
import {Observable} from 'rxjs';
// our packages
import db from '../db';
import {Crunchyroll} from '../api';
// our components
import Episode from '../components/episode';
export default class Series extends React.Component {
constructor(props) {
super(props);
this.state = {
episodes: [],
};
// trigger episodes loading
const {location} = props;
Crunchyroll.getEpisodes(location.state);
}
componentDidMount() {
this.sub = Observable.fromEvent(
db.episodes.changes({
since: 0,
live: true,
include_docs: true,
}),
'change'
)
.filter(change => !change.deleted)
.map(change => change.doc)
.scan((acc, doc) => acc.concat([doc]), [])
.debounceTime(1000)
.subscribe(episodes => {
console.log(episodes);
this.setState({episodes});
});
}
componentWillUnmount() {
this.sub.unsubscribe();
}
render() {
const {episodes} = this.state;
return (
<div>
{_.chunk(episodes, 4).map((chunk, i) => (
<div key={`chunk_${i}`} className="columns">
{chunk.map(ep => <Episode key={ep._id} episode={ep} />)}
</div>
))}
</div>
);
}
}
| JavaScript | 0 | @@ -93,16 +93,55 @@
'rxjs';%0A
+import %7BLink%7D from 'react-router-dom';%0A
// our p
@@ -894,49 +894,8 @@
s =%3E
- %7B%0A console.log(episodes);%0A
thi
@@ -920,17 +920,8 @@
es%7D)
-;%0A %7D
);%0A
@@ -1046,16 +1046,16 @@
eturn (%0A
-
%3Cd
@@ -1054,24 +1054,412 @@
%3Cdiv%3E%0A
+ %3Cnav className=%22nav%22%3E%0A %3Cdiv className=%22nav-left nav-menu%22%3E%0A %3Cdiv className=%22nav-item%22%3E%0A %3CLink to=%22/%22 className=%22 button%22%3E%0A %3Cspan className=%22icon%22%3E%0A %3Ci className=%22fa fa-arrow-left%22 /%3E%0A %3C/span%3E%0A %3Cspan%3EBack%3C/span%3E%0A %3C/Link%3E%0A %3C/div%3E%0A %3C/div%3E%0A %3C/nav%3E%0A%0A
%7B_.c
|
4cf60a0951ddec160d94fe00b3ddb57be01e9c63 | Clean up code redundancy for interactions and fix bug with nonexistent keys | src/pages/Interactions.js | src/pages/Interactions.js | import React, { Component, } from 'react';
import {
Col,
Grid,
ListGroupItem,
Media,
Row,
} from 'react-bootstrap';
import { renderResults, } from '../components/renderResults';
import { renderTextArea, } from '../components/renderTextArea';
import { filterByText, } from '../util/filters';
import { imagePath, } from '../util/imagePath';
import { resolve, } from '../util/resolve';
import { parseURL, updateURL, } from '../util/url';
const heroData = require('../Decrypted/filtered_character_visual.json');
const skinData = require('../Decrypted/filtered_costume.json');
const interactionData = require('../Decrypted/get_hero_easteregg.json').heroeasteregg;
const data = interactionData.map(i => {
const dialogues = [];
for (let j of Object.keys(i.eatereggherotext)) {
let d;
if (j.startsWith('CHA')) {
const hero = heroData[heroData.findIndex(k => k.id === j)];
d = {
name: resolve(hero.name),
dialogue: resolve(i.eatereggherotext[j]),
image: imagePath('cq-assets', `heroes/${hero.face_tex}.png`),
};
} else {
const hero = skinData[skinData.findIndex(k => k.costume_name === `TEXT_${j}${k.costume_name.endsWith('_NAME') ? '_NAME' : ''}`)];
d = {
name: resolve(hero.costume_name),
dialogue: resolve(i.eatereggherotext[j]),
image: imagePath('cq-assets', `skins/${hero.face_tex}.png`),
};
}
dialogues.push(d);
}
return {
dialogues: dialogues,
name: dialogues.map(j => j.name).join(' '),
};
});
// console.log(data);
export default class Interactions extends Component {
state = {
textFilter: '',
render: [],
}
componentWillMount = () => {
this.timer = null;
const [textFilter,] = parseURL({});
const processed = filterByText(data, textFilter);
const render = processed.map(this.renderListGroupItem);
this.setState({textFilter, render,});
}
componentWillReceiveProps = () => {
this.componentWillMount();
}
renderListGroupItem = (interactions, index) => {
return (
<ListGroupItem key={index}>
<Media>
<Grid fluid>
{interactions.dialogues.map(this.renderItem)}
</Grid>
</Media>
</ListGroupItem>
);
}
renderItem = (interaction, index) => {
return (
<Row key={index}>
<Col style={{padding: 0,}} lg={3} md={3} sm={4} xs={5}>
<Media.Left style={{display: 'flex', justifyContent: 'center',}}>
<img alt='' src={interaction.image} />
</Media.Left>
</Col>
<Col style={{padding: 0,}} lg={9} md={9} sm={8} xs={7}>
<Media.Body>
<Media.Heading>{interaction.name}</Media.Heading>
<p>{interaction.dialogue}</p>
</Media.Body>
</Col>
</Row>
);
}
update = () => {
updateURL(this.state.textFilter, {});
const processed = filterByText(data, this.state.textFilter);
this.setState({ render: processed.map(this.renderListGroupItem), });
}
handleTextChange = (e) => {
if (e.target.value.includes('\n')) { return; }
clearTimeout(this.timer);
this.setState({ textFilter: e.target.value, }, () => {
this.timer = setTimeout(() => this.update(), 300);
});
}
render = () => {
return (
<Row>
{renderTextArea(this.handleTextChange, this.state.textFilter, [12, 12, 12, 12])}
{renderResults('Interactions', this.state.render)}
</Row>
);
}
}
| JavaScript | 0 | @@ -797,20 +797,29 @@
d;%0A%0A
-if (
+const flag =
j.starts
@@ -833,18 +833,14 @@
HA')
-) %7B%0A
+;%0A
-
cons
@@ -847,16 +847,29 @@
t hero =
+ flag%0A ?
heroDat
@@ -910,216 +910,16 @@
j)%5D
-;
%0A
-d = %7B%0A name: resolve(hero.name),%0A dialogue: resolve(i.eatereggherotext%5Bj%5D),%0A image: imagePath('cq-assets', %60heroes/$%7Bhero.face_tex%7D.png%60),%0A %7D;%0A %7D else %7B%0A const hero =
+:
ski
@@ -1032,18 +1032,95 @@
''%7D%60)%5D;%0A
-
+%0A if (hero == null) %7B%0A // console.log(j, hero);%0A continue;%0A %7D%0A%0A
d =
@@ -1127,18 +1127,16 @@
%7B%0A
-
-
name: re
@@ -1141,16 +1141,35 @@
resolve(
+flag ? hero.name :
hero.cos
@@ -1180,18 +1180,16 @@
_name),%0A
-
di
@@ -1234,18 +1234,16 @@
,%0A
-
-
image: i
@@ -1269,13 +1269,36 @@
', %60
+$%7Bflag ? 'heroes' : '
skins
+'%7D
/$%7Bh
@@ -1322,17 +1322,8 @@
%60),%0A
- %7D;%0A
|
3e5c38f7919d5cdb6ee4e26377720ec9c6c67dce | add audit fields for photo object | src/schema/photo.js | src/schema/photo.js | import mongoose from 'mongoose';
import URLSlugs from 'mongoose-url-slugs';
let photoSchema = new mongoose.Schema({
originalFilename: { type: String },
filename: { type: String },
name: { type: String },
contentType: { type: String },
size: { type: Number },
tags: [],
// ability to publis photos and/or albums
published: { type: Boolean, required: true, default: false },
page: { type: mongoose.Schema.Types.ObjectId, ref: 'Page' }
});
photoSchema.set('autoIndex', (process.env.NODE_ENV === 'development'));
photoSchema.plugin(URLSlugs('name', { field: 'nameslug' }));
mongoose.model('Photo', photoSchema);
| JavaScript | 0 | @@ -444,16 +444,132 @@
: 'Page'
+ %7D,%0A createdOn: %7B type: Date, default: Date.now %7D,%0A createdBy: %7B type: mongoose.Schema.Types.ObjectId, ref: 'User'
%7D%0A%7D);%0Ap
|
318e4862ba38fbe3daf884f71967360221ec3317 | Clear messages on logging out | src/screens/chat.js | src/screens/chat.js | /*
* copyright (c) 2015 Susisu
*/
"use strict";
function ChatScreen(chat) {
var chatScreen = window.document.getElementById("chat-screen");
var chatMembers = window.document.getElementById("chat-members");
var chatExit = window.document.getElementById("chat-logout");
chatExit.addEventListener("click", function () {
chat.logout();
});
var chatMessageInput = window.document.getElementById("chat-message-input");
chatMessageInput.addEventListener("keypress", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
var message = chatMessageInput.value;
if (message !== "") {
chat.sendMessage(message);
chatMessageInput.value = "";
}
}
});
var chatMessageSend = window.document.getElementById("chat-message-send");
chatMessageSend.addEventListener("click", function () {
var message = chatMessageInput.value;
chat.sendMessage(message);
chatMessageInput.value = "";
});
var chatMessages = window.document.getElementById("chat-messages");
var memberElems = [];
function updateMembers() {
while (chatMembers.firstChild) {
chatMembers.removeChild(chatMembers.firstChild);
}
for (var i = 0; i < memberElems.length; i++) {
chatMembers.appendChild(memberElems[i]["elem"]);
}
}
function updateMessages(data) {
var name = window.document.createElement("p");
name.className = "chat-message-name";
name.innerText = data["screen_name"];
var text = window.document.createElement("p");
text.className = "chat-message-text";
text.innerText = data["message"];
var date = window.document.createElement("p");
date.className = "chat-message-date";
date.innerText = new Date(data["date"]).toLocaleString();
var messageElem = window.document.createElement("li");
messageElem.className = "chat-message";
messageElem.appendChild(name);
messageElem.appendChild(text);
messageElem.appendChild(date);
chatMessages.appendChild(messageElem);
}
chat.on("userConnected", function (data) {
var elem = window.document.createElement("li");
elem.innerText = data["screen_name"];
memberElems.push({
"user_id": data["user_id"],
"elem" : elem
});
updateMembers();
});
chat.on("userDisconnected", function (data) {
for (var i = 0; i < memberElems.length; i++) {
if (memberElems[i]["user_id"] === data["user_id"]) {
memberElems.splice(i, 1);
break;
}
}
updateMembers();
});
chat.on("serverMessage", function (data) {
updateMessages(data);
});
chat.on("message", function (data) {
updateMessages(data);
});
return chatScreen;
}
module.exports = ChatScreen;
| JavaScript | 0 | @@ -351,24 +351,49 @@
t.logout();%0A
+ clearMessages();%0A
%7D);%0A%0A
@@ -1452,24 +1452,177 @@
%7D%0A %7D%0A%0A
+ function clearMessages() %7B%0A while (chatMessages.firstChild) %7B%0A chatMessages.removeChild(chatMessages.firstChild);%0A %7D%0A %7D%0A%0A
function
|
b5304a18cc2c66bcb724f1771684ac84cad10859 | Update gpa | src/pages/resume/index.js | src/pages/resume/index.js | import React from "react"
import Helmet from "react-helmet"
import Link from "gatsby-link"
import css from "./index.module.css"
const H1 = ({children}) =>
<h1 className={css.H1}>{children}</h1>
const H2 = ({children}) =>
<h2 className={css.H2}>{children}</h2>
const Defn = ({children}) =>
<div className={css.Defn}>{children}</div>
const Term = ({children}) =>
<div className={css.Term}>{children}</div>
const mlWebapp =
<a href="https://github.com/jerryyu8/tartanhacks-2017">
machine learning webapp
</a>
const cvPosterSim =
<a href="https://github.com/mrama/Hack-CMU-2016">
computer vision poster simulator
</a>
const frontendDev =
<a href="https://scottylabs.org/wdw/frontend">
frontend development
</a>
const InfoA = ({children, href, print}) =>
<span className={css.SepAfter}>
<a className={css.Print} data-print={print} href={href}>
{children}
</a>
</span>
const InfoLink = ({children, to, print}) =>
<span className={css.SepAfter}>
<Link className={css.Print} data-print={print} to={to}>
{children}
</Link>
</span>
export default ({data: {site}}) => <div>
<Helmet title={`Resume - ${site.siteMetadata.title}`}/>
<H1>Ariel Davis</H1>
<div>
<InfoA
href="mailto:ariel.z.davis@icloud.com"
print="ariel.z.davis@icloud.com"
>
Email
</InfoA>
<InfoA
print="1-908-514-1006"
href="tel:1-908-514-1006"
>
Phone
</InfoA>
<InfoLink
print="azdavis.xyz"
to="/"
>
Website
</InfoLink>
<InfoA
print="github.com/azdavis"
href="https://github.com/azdavis"
>
GitHub
</InfoA>
</div>
<H2>Education</H2>
<Term>May 2020</Term>
<Defn>
<div>Carnegie Mellon University - Pittsburgh, PA</div>
<div>B.S in Computer Science, Minor in Japanese Studies</div>
<div>GPA 4.0</div>
</Defn>
<Term>June 2016</Term>
<Defn>
<div>Summit High School - Summit, NJ</div>
<div>Summa Cum Laude</div>
</Defn>
<H2>Selected Coursework</H2>
<Term>Spring 2018</Term>
<Defn>
<div>
15-210: Parallel and Sequential Data Structures and Algorithms
</div>
<div>15-418: Parallel Computer Architecture and Programming</div>
<div>82-272: Intermediate Japanese II</div>
</Defn>
<Term>Fall 2017</Term>
<Defn>
<div>15-213: Introduction to Computer Systems</div>
<div>82-271: Intermediate Japanese I</div>
<div>82-273: Introduction to Japanese Language and Culture</div>
</Defn>
<Term>Summer 2017</Term>
<Defn>82-172: Elementary Japanese II</Defn>
<Term>Spring 2017</Term>
<Defn>
<div>15-251: Great Theoretical Ideas in Computer Science</div>
<div>82-171: Elementary Japanese I</div>
</Defn>
<Term>Fall 2016</Term>
<Defn>
<div>15-131: Great Practical Ideas in Computer Science</div>
<div>15-150: Principles of Functional Programming</div>
</Defn>
<Term>Summer 2015</Term>
<Defn>
<div>15-122: Principles of Imperative Computation</div>
<div>21-127: Concepts of Mathematics</div>
</Defn>
<H2>Activities</H2>
<Term>Spring 2018</Term>
<Defn>TA: 15-150</Defn>
<Term>Fall 2017</Term>
<Defn>TA: 15-131, 15-150</Defn>
<Term>Summer 2017</Term>
<Defn>TA: 15-150</Defn>
<Term>Spring 2017</Term>
<Defn>
TartanHacks: helped to create a {mlWebapp}
</Defn>
<Term>Fall 2016</Term>
<Defn>
<div>HackCMU: helped to create a {cvPosterSim}</div>
<div>ScottyLabs: gave a talk on basic {frontendDev}</div>
</Defn>
<Term>Summer 2015</Term>
<Defn>
Carnegie Mellon University Pre-College: took compressed-form CMU
classes
</Defn>
<Term>Summer 2014</Term>
<Defn>
Northwestern University Center for Talent Development: learned
HTML, CSS
</Defn>
<H2>Skills</H2>
<Term>Languages</Term>
<Defn>JavaScript, Haskell, Standard ML, Idris, Ruby, C</Defn>
<Term>Markup</Term>
<Defn>HTML, CSS, LaTeX, Markdown</Defn>
<Term>Tools</Term>
<Defn>Git, GitHub, Make, Shell, POSIX</Defn>
</div>
export const pageQuery = graphql`
query Resume {
site {
siteMetadata {
title
}
}
}
`
| JavaScript | 0 | @@ -2076,11 +2076,12 @@
GPA
-4.0
+~3.9
%3C/di
|
59e263d433ffc48d8de1941a14204904564a431a | fix hover in menu | src/scripts/menu.js | src/scripts/menu.js | const overlayNav = $('.cd-overlay-nav');
const overlayContent = $('.cd-overlay-content');
const navigation = $('.cd-primary-nav');
const toggleNav = $('.header__menu-button');
const closeMenuBtn = $('.menu__close');
layerInit();
$(window).on('resize', () => {
window.requestAnimationFrame(layerInit);
});
closeMenuBtn.on('click', () => {
overlayContent.children('span').velocity({
translateZ: 0,
scaleX: 1,
scaleY: 1,
}, 500, 'easeInCubic', () => {
navigation.removeClass('fade-in');
overlayNav.children('span').velocity(
{
translateZ: 0,
scaleX: 0,
scaleY: 0,
},
0,
);
overlayContent
.addClass('is-hidden')
.one(
'webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',
() => {
overlayContent.children('span').velocity({
translateZ: 0,
scaleX: 0,
scaleY: 0,
}, 0, () => {
overlayContent.removeClass('is-hidden');
});
},
);
if ($('html').hasClass('no-csstransitions')) {
overlayContent.children('span').velocity({
translateZ: 0,
scaleX: 0,
scaleY: 0,
}, 0, () => {
overlayContent.removeClass('is-hidden');
});
}
});
});
toggleNav.on('click', () => {
overlayNav.children('span').velocity({
translateZ: 0,
scaleX: 1,
scaleY: 1,
}, 500, 'easeInCubic', () => {
navigation.addClass('fade-in');
});
});
function layerInit() {
var diameterValue =
Math.sqrt(
Math.pow($(window).height(), 2) + Math.pow($(window).width(), 2),
) * 2;
overlayNav
.children('span')
.velocity(
{
scaleX: 0,
scaleY: 0,
translateZ: 0,
},
50,
)
.velocity(
{
height: diameterValue + 'px',
width: diameterValue + 'px',
top: -(diameterValue / 2) + 'px',
left: -(diameterValue / 2) + 'px',
},
0,
);
overlayContent
.children('span')
.velocity(
{
scaleX: 0,
scaleY: 0,
translateZ: 0,
},
50,
)
.velocity(
{
height: diameterValue + 'px',
width: diameterValue + 'px',
top: -(diameterValue / 2) + 'px',
left: -(diameterValue / 2) + 'px',
},
0,
);
}
$('.menu__list-link').hover((event) => {
let color = $(event.target).data('color');
if (!color) color = '#000';
$('#menu-icon').velocity("stop").velocity({ fill: color }, 500);
});
| JavaScript | 0.000001 | @@ -2502,14 +2502,14 @@
ity(
-%22
+'
stop
-%22
+'
).ve
@@ -2538,12 +2538,91 @@
, 500);%0A
+%7D, () =%3E %7B%0A $('#menu-icon').velocity('stop').velocity(%7B fill: '#000' %7D, 500);%0A
%7D);%0A
|
ef4b598fb4bc36efba7c08360866d0205fdcf5a6 | Fix tooltip implementation for button drawer | examples/playground/src/pages/components/global/ButtonDrawer/components/Details.js | examples/playground/src/pages/components/global/ButtonDrawer/components/Details.js | // External Requirements
var React = require('react');
var Router = require('react-router');
var MortarJS = require('../../../../../app-container').MortarJS;
// Bricks
var Br = MortarJS.require('components', 'Row', 'Column', 'Form', 'ButtonDrawer', 'Tooltip');
var icomoonConfig = require('json!../../../../../../../../lib/styles/fonts/icomoon/selection.json');
// Stores
var FormStore = MortarJS.Stores.FormStore;
// Mixins
var ResourceComponentMixin = MortarJS.Mixins.ResourceComponentMixin;
/**
* Text Input
*
* @type {*|Function}
*/
var Details = React.createClass({
mixins: [ResourceComponentMixin, Router.Navigation],
getInitialState: function () {
return {
workingResource: {
mod: 'primary'
},
formIsValid: true
};
},
pageConfig: function() {
return {
stores: [
{
store: FormStore,
changeListener: this.bindResource
}
]
};
},
formKey: 'modForm',
componentDidMount: function() {
this._componentDidMount();
},
componentWillUnmount: function() {
this._componentWillUnmount();
},
handleAction: function(action, resource) {
},
bindResource: function() {
this.setState({
workingResource: FormStore.getResource(this.formKey)
});
},
buildIcomoonButtonExamples: function() {
return icomoonConfig.icons.map((icon, index) => {
let name = icon.properties.name;
if (name.includes(',')) {
name = name.slice(0, name.indexOf(","));
}
let width = name.length > 15 ? name.length * 10 : name.length * 15;
return (
<Br.Tooltip key={index} text={name} width={width} orientation="top">
<a style={ {"margin": "0 5px"} } className={`btn btn-${this.state.workingResource.mod} btn-fab btn-raised icon icon-${name}`} />
</Br.Tooltip>
);
});
},
modOptions: [
{label: 'Default', value: 'default'},
{label: 'Primary', value: 'primary'},
{label: 'Success', value: 'success'},
{label: 'Info', value: 'info'},
{label: 'Warning', value: 'warning'},
{label: 'Danger', value: 'danger'},
{label: 'Link', value: 'link'}
],
render: function() {
let drawer1 = [
{
action : 'test',
handleAction : this.handleAction,
icon : 'table',
mods : ['info']
},
{
action : 'test',
handleAction : this.handleAction,
icon : 'paint-brush',
mods : 'default'
}
];
return (
<div id="page-wrapper">
<div id="page-content">
<div id="content">
<Br.Row>
<Br.Column grid="lg" size="9">
<h2>Overview</h2>
<p>The ButtonDrawer component is useful for adding multiple actionable events to a page without taking up a lot of valuable screen space. Hover the fab button in the buttom right to see what it looks like in action.</p>
<p>Please note that the hidden button elements are shown by hovering the button drawer. Since there are no hover events on mobile, tapping the drawer will show all buttons, and tapping outside the drawer will hide them.</p>
<h2>Customizing</h2>
<p>The ButtonDrawer is built with icon fonts in mind. We've made it compatible with any css-based icon font by adding the <code>iconClass</code> property to the component. For example, to use the ButtonDrawer with <a href="http://fontawesome.io">Font Awesome</a>, you would set the ButtonDrawer's <code>ButtonDrawer iconClass="fa"</code></p>
<p>This allows for quick integration with your current workflow and styling choices.</p>
<p>We've included a few <a href="http://icomoon.io">icomoon</a> icons in Mortar that you can reference by default, which you can see below.</p>
<br />
{this.buildIcomoonButtonExamples()}
</Br.Column>
<Br.Column grid="lg" size="3">
<Br.Form key="modForm" formKey={this.formKey} bindResource={this.state.workingResource}>
<Br.Form.RadioButtons fieldKey='mod'
options={this.modOptions}
label='Select a Mod' />
</Br.Form>
</Br.Column>
</Br.Row>
</div>
</div>
<Br.ButtonDrawer handleAction={this.handleAction} icon="info-circle" mods={this.state.workingResource.mod} buttons={drawer1} />
</div>
);
}
});
module.exports = Details;
| JavaScript | 0 | @@ -1648,16 +1648,23 @@
h=%7Bwidth
+ + 'px'
%7D orient
|
b9af1199d381c35035df0b559c6a06e6c127eb41 | Extract the className out of the props | components/toast/Toast.js | components/toast/Toast.js | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import ActivableRenderer from '../hoc/ActivableRenderer';
import { Button, IconButton } from '../button';
import Portal from '../hoc/Portal';
import { IconCloseMediumOutline } from '@teamleader/ui-icons';
import theme from './theme.css';
const factory = (Button, IconButton) => {
class Toast extends PureComponent {
static propTypes = {
action: PropTypes.string,
active: PropTypes.bool,
children: PropTypes.node,
className: PropTypes.string,
label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
onClick: PropTypes.func,
onTimeout: PropTypes.func,
timeout: PropTypes.number,
type: PropTypes.oneOf(['accept', 'cancel', 'warning']),
};
componentDidMount() {
if (this.props.active && this.props.timeout) {
this._scheduleTimeout(this.props);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.active && nextProps.timeout) {
this._scheduleTimeout(nextProps);
}
}
componentWillUnmount() {
clearTimeout(this.currentTimeout);
}
_scheduleTimeout = props => {
const { onTimeout, timeout } = props;
if (this.currentTimeout) {
clearTimeout(this.currentTimeout);
}
this.currentTimeout = setTimeout(() => {
if (onTimeout) {
onTimeout();
}
this.currentTimeout = null;
}, timeout);
};
render() {
const { action, active, children, label, onClick, type } = this.props;
const classNames = cx(
[theme.toast, theme[type]],
{
[theme.active]: active,
},
this.props.className,
);
return (
<Portal>
<div data-teamleader-ui="toast" className={classNames}>
<span className={theme.label}>
{label}
{children}
</span>
{onClick ? (
action ? (
<Button className={theme.button} label={action} level="outline" onClick={onClick} size="small" />
) : (
<IconButton className={theme.iconButton} icon={<IconCloseMediumOutline />} inverse onClick={onClick} />
)
) : null}
</div>
</Portal>
);
}
}
return ActivableRenderer()(Toast);
};
const Toast = factory(Button, IconButton);
export default Toast;
export { factory as toastFactory, Toast };
| JavaScript | 0.999926 | @@ -1569,16 +1569,27 @@
hildren,
+ className,
label,
@@ -1747,27 +1747,16 @@
-this.props.
classNam
|
5e466c9a2b1348423e45afd6c95b252204cfad56 | Use a LinkButton instead of Link & drop it's wrapper because it's not needed to wrap | components/toast/Toast.js | components/toast/Toast.js | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Transition from 'react-transition-group/Transition';
import cx from 'classnames';
import { IconButton } from '../button';
import { TextSmall } from '../typography';
import Link from '../link';
import LoadingSpinner from '../loadingSpinner';
import { createPortal } from 'react-dom';
import { IconCloseMediumOutline } from '@teamleader/ui-icons';
import theme from './theme.css';
const factory = (Link, IconButton) => {
class Toast extends PureComponent {
static propTypes = {
action: PropTypes.string,
active: PropTypes.bool,
children: PropTypes.node,
className: PropTypes.string,
label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
onClose: PropTypes.func,
onTimeout: PropTypes.func,
processing: PropTypes.bool,
timeout: PropTypes.number,
};
constructor() {
super(...arguments);
this.toastRoot = document.createElement('div');
this.toastRoot.id = 'toast-root';
}
componentDidMount() {
document.body.appendChild(this.toastRoot);
if (this.props.active && this.props.timeout) {
this.scheduleTimeout(this.props);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.active && nextProps.timeout) {
this.scheduleTimeout(nextProps);
}
}
componentWillUnmount() {
clearTimeout(this.currentTimeout);
document.body.removeChild(this.toastRoot);
}
scheduleTimeout = props => {
const { onTimeout, timeout } = props;
if (this.currentTimeout) {
clearTimeout(this.currentTimeout);
}
this.currentTimeout = setTimeout(() => {
if (onTimeout) {
onTimeout();
}
this.currentTimeout = null;
}, timeout);
};
render() {
const { action, active, children, className, label, onClose, processing } = this.props;
const toast = (
<Transition in={active} timeout={{ enter: 0, exit: 1000 }}>
{state => {
if (state === 'exited') {
return null;
}
const classNames = cx(
theme['toast'],
{
[theme['is-entering']]: state === 'entering',
[theme['is-entered']]: state === 'entered',
[theme['is-exiting']]: state === 'exiting',
},
className,
);
return (
<div data-teamleader-ui="toast" className={classNames}>
{processing && <LoadingSpinner className={theme['spinner']} color="white" />}
<TextSmall className={theme['label']} color="white" soft>
{label}
{children}
</TextSmall>
{onClose ? (
action ? (
<TextSmall className={theme['action-link']} color="white">
<Link onClick={onClose}>{action}</Link>
</TextSmall>
) : (
<IconButton
className={theme['action-button']}
icon={<IconCloseMediumOutline />}
color="white"
onClick={onClose}
/>
)
) : null}
</div>
);
}}
</Transition>
);
return createPortal(toast, this.toastRoot);
}
}
return Toast;
};
const Toast = factory(Link, IconButton);
export default Toast;
export { factory as toastFactory, Toast };
| JavaScript | 0 | @@ -183,16 +183,28 @@
onButton
+, LinkButton
%7D from
@@ -263,36 +263,8 @@
y';%0A
-import Link from '../link';%0A
impo
@@ -463,24 +463,30 @@
tory = (Link
+Button
, IconButton
@@ -2718,13 +2718,8 @@
ite%22
- soft
%3E%0A
@@ -2875,33 +2875,34 @@
%3C
-TextSmall
+LinkButton
className=%7B
@@ -2927,116 +2927,54 @@
'%5D%7D
-color=%22white%22%3E%0A %3CLink onClick=%7BonClose%7D%3E%7Baction%7D%3C/Link%3E%0A %3C/TextSmall
+inverse onClick=%7BonClose%7D%3E%7Baction%7D%3C/LinkButton
%3E%0A
@@ -3473,16 +3473,22 @@
ory(Link
+Button
, IconBu
|
21cc4397e960b5e5140bbba7ca29bc11a73b28ad | Remove duplication by using Universe class. | test/works.js | test/works.js | import assert from 'assert';
describe('test setup works?', function() {
it('i hope', function() {
assert.equal(1, 1);
});
});
function tick() {
return { positions:[] };
}
function newUniverseWithOneCellFrom(universe, position) {
return {positions: [universe.positions[position]]};
}
describe('universe', function() {
describe('next generation', function() {
it('of empty universe is empty', function() {
let universe = {
positions: []
};
let nextGeneration = tick();
assert.deepEqual(nextGeneration, { positions:[] });
});
it('of one cell is empty', function() {
let universe = {
positions: [{}]
};
let nextGeneration = tick();
assert.deepEqual(nextGeneration, { positions:[] } );
});
// first step to think of universe as single cell because only one cell
// survives and we place other cells accordingly.
it('of three diagonal cells contains middle cell', function() {
class Universe {
static withPositions(positions) {
const universe = new Universe();
universe.positions = positions;
return universe;
}
indexOf({x, y}) {
return this.positions
.map((position, index) => position.x == x && position.y == y ? index : -1)
.filter(index => index > -1)
[0];
}
}
let universe = Universe.withPositions([
{ x:51, y:51 }, // TODO the position is duplicated many times, extract
{ x:50, y:50 },
{ x:52, y:52 }
]);
let surviverIndex = universe.indexOf({x: 51, y: 51});
let nextGeneration = newUniverseWithOneCellFrom(universe, surviverIndex);
assert.deepEqual(nextGeneration, {positions: [{x: 51, y: 51}]});
});
it('of three diagonal cells (in different order) contains middle cell', function() {
let universe = {
positions: [
{ x:0, y:0 },
{ x:1, y:1 },
{ x:2, y:2 }
]
};
universe.indexOf = function({x, y}) {
return this.positions
.map((position, index) => position.x == x && position.y == y ? index : -1)
.filter(index => index > -1)
[0];
};
let xToFind = 1;
let yToFind = 1;
let surviverIndex = universe.indexOf({x: xToFind, y: yToFind});
// universe.positions[surviverIndex] = {x:1, y:1};
// TODO we need to determine 1 from the universe somehow. this is the
// rule for survival. then we can extract 49 and 66 into new tick method
// and combine with existing one. maybe <- ;-)
let positionIndex = surviverIndex;
let nextGeneration = newUniverseWithOneCellFrom(universe, positionIndex);
assert.deepEqual(nextGeneration, {positions: [{x: 1, y: 1}]});
});
});
}); | JavaScript | 0.000001 | @@ -129,16 +129,346 @@
);%0A%7D);%0A%0A
+class Universe %7B%0A static withPositions(positions) %7B%0A const universe = new Universe();%0A universe.positions = positions;%0A return universe;%0A %7D%0A indexOf(%7Bx, y%7D) %7B%0A return this.positions%0A .map((position, index) =%3E position.x == x && position.y == y ? index : -1)%0A .filter(index =%3E index %3E -1)%0A %5B0%5D;%0A %7D%0A%7D%0A
function
@@ -1336,416 +1336,8 @@
) %7B%0A
- class Universe %7B%0A static withPositions(positions) %7B%0A const universe = new Universe();%0A universe.positions = positions;%0A return universe;%0A %7D%0A indexOf(%7Bx, y%7D) %7B%0A return this.positions%0A .map((position, index) =%3E position.x == x && position.y == y ? index : -1)%0A .filter(index =%3E index %3E -1)%0A %5B0%5D;%0A %7D%0A %7D%0A
@@ -1853,35 +1853,38 @@
verse =
-%7B%0A p
+Universe.withP
ositions
: %5B%0A
@@ -1879,14 +1879,11 @@
ions
-: %5B%0A
+(%5B%0A
@@ -1904,26 +1904,24 @@
%7D,%0A
-
%7B x:1, y:1 %7D
@@ -1918,26 +1918,24 @@
x:1, y:1 %7D,%0A
-
%7B x:
@@ -1953,242 +1953,10 @@
- %5D %0A %7D;%0A universe.indexOf = function(%7Bx, y%7D) %7B%0A return this.positions%0A .map((position, index) =%3E position.x == x && position.y == y ? index : -1)%0A .filter(index =%3E index %3E -1)%0A %5B0%5D;%0A %7D
+%5D)
;%0A%0A
@@ -2340,49 +2340,8 @@
;-)%0A
- let positionIndex = surviverIndex;%0A
@@ -2400,24 +2400,24 @@
iverse,
-position
+surviver
Index);%0A
|
28711ab2a155be2d6db9ca1caea7754795f1fb30 | Eliminate a duplicate test def | packages/react-server-integration-tests/src/__tests__/containers/ContainersSpec.js | packages/react-server-integration-tests/src/__tests__/containers/ContainersSpec.js | var helper = require("../../specRuntime/testHelper");
var _ = require('lodash');
describe("A page's root elements", () => {
var pages = [];
var seen = {};
// Verify that we get our attributes set where they need to go.
_.forEach({
'RootElement' : "[data-react-server-root-id]",
'RootContainer' : "[data-react-server-container]",
}, (query, root) => {
_.forEach({
'id' : 'foo',
'class' : 'bar',
'style' : 'baz',
}, (value, attr) => desc(
`can have "${attr}" attribute on ${root}`,
'/attributesOn'+root,
element => expect(element).toBeTruthy() && expect(element.getAttribute(attr)).toBe(value),
query
));
});
// Single elements of various types.
// All should resolve to a single `<div>foo</div>`.
_.forEach({
"/singleDivNoArray" : "div with no array",
"/singleDivInArray" : "div in an array",
"/singlePromiseNoArray" : "promise with no array",
"/singlePromiseInArray" : "promise in an array",
"/singleRootElementNoArray" : "RootElement with no array",
"/singleRootElementInArray" : "RootElement in an array",
"/singleRootElementInArray" : "RootElement in an array",
"/singleRootContainerNoArray" : "RootContainer with no array",
"/singleRootContainerInArray" : "RootContainer in an array",
"/singleRootElementInRootContainer" : "RootElement in a RootContainer",
}, makeSingleDesc('can be a single'));
// Get props to root elements in various ways.
_.forEach({
"/propsFromEmitterRootElement" : "RootElement listen",
"/propsFromEmitterRootContainer" : "RootContainer listen",
}, makeSingleDesc('can get props from'));
// Some machinery to factor out commonality.
//
// Note that with the default query this just grabs the first root
// element. Won't always be index zero, since containers burn slots
// (but they don't have `data-react-server-root-id`).
function desc(txt, url, fn, query="[data-react-server-root-id]") {
describe(txt, () => helper.testWithElement(url, query, fn));
var page = `./pages/${url[0]+url[1].toUpperCase()+url.slice(2)}`;
if (!seen[page]){
seen[page] = true;
pages.push(page);
}
};
// Expect the contents of the first root element to be 'foo'.
function makeSingleDesc(prefix) {
return (txt, url) => desc(`${prefix} ${txt}`, url,
element => expect(element).toBeTruthy() && expect(element.innerHTML).toMatch('foo')
)
}
helper.startServerBeforeAll(__filename, pages);
helper.stopServerAfterAll();
})
| JavaScript | 0.999999 | @@ -1138,75 +1138,8 @@
y%22,%0A
-%09%09%22/singleRootElementInArray%22 : %22RootElement in an array%22,%0A
%09%09%22/
|
f983f121d4dd680c1fbfd7e99863888ea9237896 | Add docs for PlayAnimation | src/actions/PlayAnimation.js | src/actions/PlayAnimation.js | /**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* [description]
*
* @function Phaser.Actions.PlayAnimation
* @since 3.0.0
*
* @generic {Phaser.GameObjects.GameObject[]} G - [items,$return]
*
* @param {(array|Phaser.GameObjects.GameObject[])} items - An array of Game Objects. The contents of this array are updated by this Action.
* @param {string} key - The name of the animation to play
* @param {(string|integer)} [startFrame] - The starting frame of the animation with the given key
*
* @return {(array|Phaser.GameObjects.GameObject[])} The array of Game Objects that was passed to this Action.
*/
var PlayAnimation = function (items, key, startFrame)
{
for (var i = 0; i < items.length; i++)
{
items[i].anims.play(key, startFrame);
}
return items;
};
module.exports = PlayAnimation;
| JavaScript | 0 | @@ -206,21 +206,107 @@
%0A *
-%5Bdescription%5D
+Play an animation with the given key, starting at the given startFrame on all Game Objects in items
%0A *%0A
|
d55c4daec8ee50ddd9164ab4c335614e4a002a9b | Add a notification zero state | src/actions/notifications.js | src/actions/notifications.js | import * as ACTION_TYPES from '../constants/action_types'
import * as MAPPING_TYPES from '../constants/mapping_types'
import * as api from '../networking/api'
import * as StreamFilters from '../components/streams/StreamFilters'
import * as StreamRenderables from '../components/streams/StreamRenderables'
export function loadNotifications(params = {}) {
return {
type: ACTION_TYPES.LOAD_STREAM,
payload: { endpoint: api.notifications(params), vo: {} },
meta: {
mappingType: MAPPING_TYPES.ACTIVITIES,
renderStream: {
asList: StreamRenderables.notificationList,
asGrid: StreamRenderables.notificationList,
},
resultFilter: StreamFilters.notificationsFromActivities,
},
}
}
| JavaScript | 0.000004 | @@ -1,20 +1,46 @@
+import React from 'react'%0A
import * as ACTION_T
@@ -69,32 +69,32 @@
s/action_types'%0A
-
import * as MAPP
@@ -323,16 +323,70 @@
erables'
+%0Aimport %7B ZeroState %7D from '../components/zeros/Zeros'
%0A%0Aexport
@@ -664,24 +664,24 @@
cationList,%0A
-
asGr
@@ -716,24 +716,95 @@
cationList,%0A
+ asZero: %3CZeroState%3ESorry, no notifications found.%3C/ZeroState%3E,%0A
%7D,%0A
|
65d9a3cbe047d31e6f7135a7ba12b9ec2b6879a1 | Fix BlockContact receive | lib/receive/operation/BlockContact.js | lib/receive/operation/BlockContact.js | var OpType = require('../../constants/OpType');
var Operation = require('../Operation');
var BlockContact = function(config, result) {
this.config = config;
this.result = result;
};
BlockContact.prototype = new Operation();
BlockContact.prototype.constructor = BlockContact;
BlockContact.prototype.isBlockContact = function() {
return true;
};
BlockContact.prototype.getContentType = function() {
return ContentType.BLOCKED;
};
module.exports = BlockContact;
| JavaScript | 0 | @@ -372,23 +372,25 @@
type.get
-Content
+Operation
Type = f
@@ -414,15 +414,10 @@
urn
-Content
+Op
Type
|
58f6be5839773ff34ad7e0eb732228fc1e16c57c | Add Alias to Segment.io | src/angulartics-segmentio.js | src/angulartics-segmentio.js | /**
* @license Angulartics v0.17.2
* (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
* License: MIT
*/
(function(angular) {
'use strict';
/**
* @ngdoc overview
* @name angulartics.segment.io
* Enables analytics support for Segment.io (http://segment.io)
*/
angular.module('angulartics.segment.io', ['angulartics'])
.config(['$analyticsProvider', function ($analyticsProvider) {
// https://segment.com/docs/libraries/analytics.js/#page
// analytics.page([category], [name], [properties], [options], [callback]);
// TODO : Support optional parameters where the parameter order and type changes their meaning
// e.g.
// (string) is (name)
// (string, string) is (category, name)
// (string, object) is (name, properties)
$analyticsProvider.registerPageTrack(function (path) {
try {
analytics.page(path);
} catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
});
// https://segment.com/docs/libraries/analytics.js/#track
// analytics.track(event, [properties], [options], [callback]);
$analyticsProvider.registerEventTrack(function (event, properties, options, callback) {
try {
analytics.track(event, properties, options, callback);
} catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
});
// Segment Identify Method
// https://segment.com/docs/libraries/analytics.js/#identify
// analytics.identify([userId], [traits], [options], [callback]);
$analyticsProvider.registerSetUserProperties(function (userId, traits, options, callback) {
try {
analytics.identify(userId, traits, options, callback);
} catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
});
// Segment Identify Method
// https://segment.com/docs/libraries/analytics.js/#identify
// analytics.identify([userId], [traits], [options], [callback]);
$analyticsProvider.registerSetUserPropertiesOnce(function (userId, traits, options, callback) {
try {
analytics.identify(userId, traits, options, callback);
} catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
});
}]);
})(angular);
| JavaScript | 0 | @@ -2402,24 +2402,469 @@
%7D%0A %7D);
+%0A %0A // Segment Alias Method%0A // https://segment.com/docs/libraries/analytics.js/#alias%0A // analytics.alias(%5BuserId%5D, %5Bcallback%5D);%0A $analyticsProvider.registerSetAlias(function (userId, previousId, options, callback) %7B%0A try %7B%0A analytics.alias(userId, previousId, options, callback);%0A %7D catch (e) %7B%0A if (!(e instanceof ReferenceError)) %7B%0A throw e;%0A %7D%0A %7D%0A %7D);
%0A%0A %7D%5D);%0A%7D
|
1d1a6bf1a7da2e34a8b14c8c39a328026cfef0b4 | Make textual output CSV friendly | benchmarks/benchmark-runner.js | benchmarks/benchmark-runner.js | /** @babel */
import Chart from 'chart.js'
import glob from 'glob'
import fs from 'fs-plus'
import path from 'path'
export default async function ({test, benchmarkPaths}) {
document.body.style.backgroundColor = '#ffffff'
document.body.style.overflow = 'auto'
let paths = []
for (const benchmarkPath of benchmarkPaths) {
if (fs.isDirectorySync(benchmarkPath)) {
paths = paths.concat(glob.sync(path.join(benchmarkPath, '**', '*.bench.js')))
} else {
paths.push(benchmarkPath)
}
}
while (paths.length > 0) {
const benchmark = require(paths.shift())({test})
let results
if (benchmark instanceof Promise) {
results = await benchmark
} else {
results = benchmark
}
const dataByBenchmarkName = {}
for (const {name, duration, x} of results) {
dataByBenchmarkName[name] = dataByBenchmarkName[name] || {points: []}
dataByBenchmarkName[name].points.push({x, y: duration})
}
const benchmarkContainer = document.createElement('div')
document.body.appendChild(benchmarkContainer)
for (const key in dataByBenchmarkName) {
const data = dataByBenchmarkName[key]
if (data.points.length > 1) {
const canvas = document.createElement('canvas')
benchmarkContainer.appendChild(canvas)
const chart = new Chart(canvas, {
type: 'line',
data: {
labels: data.points.map((p) => p.x),
datasets: [{label: key, fill: false, data: data.points}]
}
})
const textualOutput = `${key}:\n` + data.points.map((p) => ` (${p.x}, ${p.y})`).join('\n')
console.log(textualOutput)
} else {
const title = document.createElement('h2')
title.textContent = key
benchmarkContainer.appendChild(title)
const duration = document.createElement('p')
duration.textContent = `${data.points[0].y}ms`
benchmarkContainer.appendChild(duration)
const textualOutput = `${key}: ${data.points[0].y}`
console.log(textualOutput)
}
global.atom.reset()
}
}
return 0
}
| JavaScript | 0.995504 | @@ -1593,24 +1593,21 @@
%60
-(
$%7Bp.x%7D
-,
+;
$%7Bp.y%7D
-)
%60).j
|
05510f5d49a0b0452fec20853b2b9de4b64728b1 | Fix server client | lib/runner/challenge_server_client.js | lib/runner/challenge_server_client.js | 'use strict';
var Promise = require('promise');
var unirest = require('unirest');
function ChallengeServerClient(hostname, port, journeyId, useColours){
this.hostname = hostname;
this.port = port;
this.journeyId = journeyId;
this.acceptHeader = useColours ? "text/coloured" : "text/not-coloured";
}
//~~~~~~~ GET ~~~~~~~~
ChallengeServerClient.prototype.getJourneyProgress = function () {
return this.get("journeyProgress");
};
ChallengeServerClient.prototype.getAvailableActions = function () {
return this.get("availableActions");
};
ChallengeServerClient.prototype.getRoundDescription = function () {
return this.get("roundDescription");
};
ChallengeServerClient.prototype.get = function (name) {
var client = this;
return new Promise(function (fulfill, reject) {
unirest
.get('http://' + client.hostname + ':' + client.port + '/' + actionName + '/' + client.journeyId)
.header("Accept", client.acceptHeader)
.header("Accept-Charset", "UTF-8")
.end(function (response) {
ifStatusOk(response, fulfill, reject)
});
});
};
//~~~~~~~ POST ~~~~~~~~
ChallengeServerClient.prototype.sendAction = function (name) {
var client = this;
return new Promise(function (fulfill, reject){
unirest
.post('http://' + client.hostname + ':' + client.port + '/action/' + actionName + '/' + client.journeyId)
.header("Accept", client.acceptHeader)
.header("Accept-Charset", "UTF-8")
.end(function (response) {
ifStatusOk(response, fulfill, reject)
});
});
};
//~~~~~~~ Error handling ~~~~~~~~~
function ifStatusOk(response, fulfill, reject) {
var responseCode = response.code;
if (isClientError(responseCode)) {
reject({name : "ClientErrorException", message : response.body});
} else if (isServerError(responseCode)) {
reject({name : "ServerErrorException", message : response.error});
} else if (isOtherErrorResponse(responseCode)) {
reject({name : "OtherCommunicationException", message : response.error});
} else {
fulfill(response.body)
}
}
function isClientError(responseStatus) {
return responseStatus >= 400 && responseStatus < 500;
}
function isServerError(responseStatus) {
return responseStatus >= 500 && responseStatus < 600;
}
function isOtherErrorResponse(responseStatus) {
return responseStatus < 200 || responseStatus > 300;
}
module.exports = ChallengeServerClient;
| JavaScript | 0.000001 | @@ -837,28 +837,26 @@
.get(
-'
+%60
http://
-' +
+$%7B
client.h
@@ -858,33 +858,28 @@
ent.hostname
- + ':' +
+%7D:$%7B
client.port
@@ -881,36 +881,20 @@
port
- + '/' + actionName + '/' +
+%7D/$%7Bname%7D/$%7B
clie
@@ -897,32 +897,34 @@
client.journeyId
+%7D%60
)%0A .h
@@ -1329,20 +1329,18 @@
ost(
-'
+%60
http://
-' +
+$%7B
clie
@@ -1354,17 +1354,12 @@
name
- + ':' +
+%7D:$%7B
clie
@@ -1369,20 +1369,17 @@
port
- + '
+%7D
/action/
' +
@@ -1378,31 +1378,18 @@
ion/
-' + actionName + '/' +
+$%7Bname%7D/$%7B
clie
@@ -1400,16 +1400,18 @@
ourneyId
+%7D%60
)%0A
|
8fd832d057701d26b16e3600fb8cf89f8e2e97d1 | fix no more forums | lib/site/home-multiforum/component.js | lib/site/home-multiforum/component.js | import React, {Component} from 'react'
import { Link } from 'react-router'
import user from 'lib/user/user'
import t from 't-component'
import debug from 'debug'
import forumStore from '../../stores/forum-store/forum-store'
import ForumCard from './forum-card/component'
const log = debug('democracyos:home-multiforum')
export default class HomeMultiForum extends Component {
constructor (props) {
super(props)
this.state = {
forums: [],
userForums: [],
page: 0,
loading: false,
loadingUserForms: false,
noMore: null
}
this.loadMore = this.loadMore.bind(this)
this.getUserForums = this.getUserForums.bind(this)
}
componentWillMount () {
user.on('loaded', this.getUserForums)
user.on('unloaded', this.getUserForums)
// Get all forums
console.log('loading true c w m')
this.setState({loading: true})
forumStore.findAll({
page: this.state.page
})
.then((forums) => {
this.setState({
loading: false,
noMore: forums.length === 0,
forums: this.state.forums.concat(forums),
page: this.state.page + 1
})
})
.catch(err => {
log('Forum home fetch error: ', err)
this.setState({
loading: false,
noMore: true
})
})
// Get user forums for permissions checking
this.getUserForums()
}
componentWillUnmount () {
forumStore.clear()
user.off('loaded', this.getUserForums)
user.off('unloaded', this.getUserForums)
}
loadMore () {
if (this.state.loading) return
console.log('loading true l m')
this.setState({loading: true})
forumStore.findAll({
page: this.state.page
}).then((forums) => {
let nextState = {
loading: false,
page: this.state.page + 1
}
if (forums.length === 0) {
nextState.noMore = true
} else {
nextState.forums = this.state.forums.concat(forums)
}
this.setState(nextState)
}).catch((err) => {
log('Found error %s', err)
this.setState({loading: false, noMore: true})
})
}
getUserForums () {
if (user.logged()) {
this.setState({loadingUserForms: true})
forumStore.findAll({
'privileges.canChangeTopics': true
})
.then(forums => {
this.setState({
userForums: forums,
loadingUserForms: false
})
})
}
}
render () {
console.log(this.state.loading)
if (this.state.loadingUserForms) {
return null
}
let info
if (user && user.logged()) {
if (
this.state.userForums &&
this.state.userForums.length > 0 &&
user.privileges &&
user.privileges.canManage
) {
info =
(
<div className='forum-info'>
<a href='/settings/forums' className='admin'>
{t('newsfeed.call-to-action.manage-forums')}
<span className='icon-arrow-right'></span>
</a>
</div>
)
} else if (
user.privileges &&
user.privileges.canCreate
) {
info =
(
<div className='forum-info cover'>
<div className='content'>
<h1>{t('newsfeed.welcome.title')}</h1>
<p>{t('newsfeed.welcome.body')}</p>
<a href='/forums/new' className='btn btn-default'>
{t('newsfeed.call-to-action.start-a-forum')}
<span className='icon-arrow-right'></span>
</a>
</div>
</div>
)
}
} else {
info = (
<div className='forum-info cover'>
<div className='content'>
<h1>{t('newsfeed.welcome.title')}</h1>
<p>{t('newsfeed.welcome.body')}</p>
<Link to='/signup' className='btn btn-default'>
{t('newsfeed.welcome.join')}
<span className='icon-arrow-right'></span>
</Link>
</div>
</div>
)
}
return (
<div id='home-multiforum' className='center-container'>
{info}
<div id='forum-list'>
<div className='title'>
<h2>{t('newsfeed.title')}</h2>
</div>
<section>
{
this.state.forums.map((forum, key) => {
return <ForumCard forum={forum} key={key} />
})
}
{
this.state.noMore &&
!this.state.loading &&
(
<p className='msg-empty'>
{t('newsfeed.nothing-to-show')}
</p>
)
}
</section>
<div className={!this.state.noMore ? 'load-more' : 'hide'}>
<button
onClick={this.loadMore}
className={!this.state.loading ? 'btn btn-block' : 'hide'}>
{t('newsfeed.button.load-more')}
</button>
<button
className={this.state.loading ? 'loader-btn btn btn-block' : 'hide'}>
<div className='loader'></div>
{t('newsfeed.button.load-more')}
</button>
</div>
</div>
</div>
)
}
}
| JavaScript | 0 | @@ -4441,22 +4441,35 @@
s.state.
-noMore
+forums.length === 0
&&%0A
|
98a07e6f0c8c6ce64108006ff675f126ac1803fc | make CheckedInt instance print nicely | src/arithmetic/checkedInt.js | src/arithmetic/checkedInt.js | var checkedInt = function checkedInt(longInt) {
'use strict';
var CheckedInt = "__CheckedInt__";
var make = function make(n) {
return {
type : CheckedInt,
value: n
};
};
var toJS = function toJS(n) {
return n.value;
};
var promote = function promote(n) {
if (longInt.shouldPromote(n))
return longInt.promote(n);
else
return make(n);
};
var toString = function toString(n) {
return '' + n.value;
};
var negative = function negative(n) {
return make(-n.value);
};
var abs = function abs(n) {
return make(Math.abs(n.value));
};
var sgn = function sgn(n) {
return (n.value > 0) - (n.value < 0);
};
var isEven = function isEven(n) {
return n.value % 2 == 0;
};
var cmp = function cmp(a, b) {
return a.value - b.value;
};
var plus = function plus(a, b) {
return promote(a.value + b.value);
};
var minus = function minus(a, b) {
return promote(a.value - b.value);
};
var times = function times(a, b) {
var product = a.value * b.value;
if (longInt.shouldPromote(product))
return longInt.times(longInt.promote(a.value), longInt.promote(b.value));
else
return make(product);
};
var idiv = function idiv(a, b) {
return make(Math.floor(a.value / b.value));
};
var mod = function mod(a, b) {
return make(a.value % b.value);
};
return {
type : CheckedInt,
promote : promote,
toString: toString,
toJS : toJS,
negative: negative,
abs : abs,
sgn : sgn,
isEven : isEven,
cmp : cmp,
plus : plus,
minus : minus,
times : times,
idiv : idiv,
mod : mod
};
};
module.exports = checkedInt(require('./longInt'));
module.exports.custom = checkedInt;
if (require.main == module) {
with(module.exports.custom(require('./longInt').custom(4))) {
'use strict';
var show = function(n) {
console.log(toString(n));
};
show(promote(-1234));
console.log(promote(-1234));
console.log(promote(-12345));
console.log(promote(-1234567890));
console.log();
show(plus(promote(1234), promote(8765)));
console.log(plus(promote(1234), promote(8766)));
show(minus(promote(1234), promote(1234)));
show(minus(promote(1234), promote(1230)));
show(plus(promote(1234), promote(-1234)));
console.log();
show(abs(promote(-1234)));
console.log(sgn(promote(1)));
console.log(sgn(promote(1234)));
console.log(sgn(promote(0)));
console.log(sgn(promote(-0)));
console.log(sgn(promote(-45)));
console.log(sgn(promote(-1234)));
console.log(isEven(promote(0)));
console.log(isEven(promote(-123)));
console.log(isEven(promote(1234)));
console.log();
console.log(times(promote(123), promote(1001)));
show(times(promote(1111), promote(9)));
console.log(times(promote(1235), promote(9)));
show(idiv(promote(111), promote(37)));
show(idiv(promote(111), promote(3)));
show(idiv(promote(9998), promote(4999)));
show(idiv(promote(2001), promote(1001)));
show(idiv(promote(9999), promote(99)));
console.log();
show(mod(promote(111), promote(37)));
show(mod(promote(112), promote(37)));
}
}
| JavaScript | 0 | @@ -1,12 +1,43 @@
+var I = require('immutable');%0A%0A
var checkedI
@@ -112,24 +112,145 @@
t =
-%22__CheckedInt__%22
+I.Record(%7B%0A type : undefined,%0A value: undefined%0A %7D);%0A%0A CheckedInt.prototype.toString = function() %7B%0A return ''+this.value;%0A %7D
;%0A%0A%0A
@@ -296,21 +296,29 @@
urn
-%7B%0A
+new CheckedInt(%7B
type
-
: Ch
@@ -326,22 +326,16 @@
ckedInt,
-%0A
value:
@@ -335,22 +335,19 @@
value: n
-%0A
%7D
+)
;%0A %7D;%0A%0A
|
9a8322ea9957c288d4056dd84a8a487bcc78d95c | install preprocessors as devDependencies | lib/tasks/install-npm-dependencies.js | lib/tasks/install-npm-dependencies.js | var runCommand = require('../utils/run-command');
var dependencies = [
'broccoli-coffee',
'broccoli-sass'
];
module.exports = function(config) {
var command = 'cd ' + config.get('projectPath') + '/ember; '
+ 'npm install --save ' + dependencies.join(' ');
return runCommand(command, "Installing npm dependencies...");
}
| JavaScript | 0 | @@ -250,13 +250,9 @@
ll -
--save
+D
' +
|
c63cd5fd35b6d985fd25b54d44cb3e0efdb45cf0 | Add a guard clause for svg attribute presence | lib/tests/modules/graph/components.js | lib/tests/modules/graph/components.js | var _ = require('underscore');
module.exports = {
line: function (browser, selector, index) {
var lineInGroup = _.isNumber(index) ? '.group' + index : '';
return function () {
return browser
.$(selector + ' svg .line' + lineInGroup)
.should.eventually.exist;
};
},
stack: function (browser, selector, index) {
var lineInGroup = _.isNumber(index) ? '.group' + index : '';
return function () {
var linePath;
return browser
.$(selector + ' svg .line' + lineInGroup)
.should.eventually.exist
.getAttribute('d').then(function (d) {
linePath = d.split('M')[1];
})
.$(selector + ' svg .stack' + lineInGroup)
.should.eventually.exist
.getAttribute('d').then(function (d) {
// the line follows the top of the stack, so the line path should be a
// substring of the stack path
d.should.contain(linePath);
});
};
}
}; | JavaScript | 0 | @@ -605,32 +605,64 @@
(function (d) %7B%0A
+ if (d !== null) %7B%0A
line
@@ -685,16 +685,30 @@
M')%5B1%5D;%0A
+ %7D%0A
@@ -973,16 +973,48 @@
ck path%0A
+ if (d !== null) %7B%0A
@@ -1045,16 +1045,30 @@
ePath);%0A
+ %7D%0A
@@ -1087,8 +1087,9 @@
%0A %7D%0A%0A%7D;
+%0A
|
872f701c921922c605064cc8914e03be3ac3f6ff | Use reset() instead of clear() | js/energy-systems/model/EnergySystemElement.js | js/energy-systems/model/EnergySystemElement.js | // Copyright 2016, University of Colorado Boulder
/**
* Base class for energy sources, converters, and users.
*
* @author Andrew Adare
* @author Jesse Greenberg
*/
define( function( require ) {
'use strict';
var inherit = require( 'PHET_CORE/inherit' );
// var PropertySet = require( 'AXON/PropertySet' );
var ObservableArray = require( 'AXON/ObservableArray' );
var PositionableFadableModelElement = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/model/PositionableFadableModelElement' );
var Vector2 = require( 'DOT/Vector2' );
/**
* Energy system element
*
* @param {Image} iconImage
* @constructor
*/
function EnergySystemElement( iconImage ) {
PositionableFadableModelElement.call( this, new Vector2( 0, 0 ), 1.0 );
// @public
this.iconImage = iconImage;
this.energyChunkList = new ObservableArray();
this.addProperty( 'active', false );
var thisElement = this;
// At initialization, oldPosition is null, so skip that case with lazyLink
this.positionProperty.lazyLink( function( newPosition, oldPosition ) {
var deltaPosition = newPosition.minus( oldPosition );
thisElement.energyChunkList.forEach( function( chunk ) {
chunk.translate( deltaPosition );
} );
} );
}
return inherit( PositionableFadableModelElement, EnergySystemElement, {
/**
* Activate this element
*
*/
activate: function() {
this.activeProperty.set( true );
},
/**
* Deactivate this element. All energy chunks are removed.
*
*/
deactivate: function() {
this.activeProperty.set( false );
this.clearEnergyChunks();
},
/**
* Clear daughter energy chunks
*
*/
clearEnergyChunks: function() {
this.energyChunkList.clear();
}
} );
} );
| JavaScript | 0.000007 | @@ -1792,21 +1792,21 @@
unkList.
-clear
+reset
();%0A
|
fa0c5bfa2b6b5921a1b1500e3a674f66aa29d44e | Remove unnecessary check | lib/Accordion/headers/FilterAccordionHeader.js | lib/Accordion/headers/FilterAccordionHeader.js | import React from 'react';
import { injectIntl } from 'react-intl';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from '../../Icon';
import Headline from '../../Headline';
import IconButton from '../../IconButton';
import css from '../Accordion.css';
class FilterAccordionHeader extends React.Component {
static propTypes = {
autoFocus: PropTypes.bool,
contentId: PropTypes.string,
disabled: PropTypes.bool,
displayClearButton: PropTypes.bool,
displayWhenClosed: PropTypes.element,
displayWhenOpen: PropTypes.element,
headingLevel: PropTypes.oneOf([1, 2, 3, 4, 5, 6]),
id: PropTypes.string,
intl: PropTypes.object,
label: PropTypes.oneOfType([PropTypes.element, PropTypes.string]).isRequired,
name: PropTypes.string,
onClearFilter: PropTypes.func,
onToggle: PropTypes.func,
open: PropTypes.bool,
toggleRef: PropTypes.func,
};
static defaultProps = {
displayClearButton: true,
headingLevel: 3
};
handleHeaderClick = (e) => {
e.preventDefault();
e.stopPropagation();
const { id, label } = this.props;
this.props.onToggle({ id, label });
}
handleClearButtonClick = () => {
this.props.onClearFilter(this.props.name);
}
handleKeyPress = (e) => {
e.preventDefault();
if (e.charCode === 13) { // 13 = enter
const { id, label } = this.props;
this.props.onToggle({ id, label });
}
}
render() {
const {
label,
open,
disabled,
displayWhenOpen,
displayWhenClosed,
displayClearButton,
onClearFilter,
contentId,
headingLevel,
intl: {
formatMessage
},
} = this.props;
const clearButtonVisible = displayClearButton && typeof onClearFilter === 'function';
const labelPropsId = label?.props?.id ?? '';
const labelText = labelPropsId ? formatMessage({ id: labelPropsId }) : '-';
return (
<div className={css.headerWrapper}>
<Headline size="small" tag={`h${headingLevel}`} block={!clearButtonVisible}>
<button
type="button"
tabIndex="0"
onClick={this.handleHeaderClick}
onKeyPress={this.handleKeyPress}
aria-label={`${labelText} filter list`}
aria-controls={contentId}
aria-expanded={open}
disabled={disabled}
className={classNames(css.filterSetHeader, { [css.clearButtonVisible]: clearButtonVisible })}
autoFocus={this.props.autoFocus}
ref={this.props.toggleRef}
id={`accordion-toggle-button-${this.props.id}`}
>
{
disabled ? null :
<Icon
iconClassName={css.filterSetHeaderIcon}
size="small"
icon={`caret-${open ? 'up' : 'down'}`}
/>
}
<div className={css.labelArea}>
<div className={css.filterSetLabel}>{label}</div>
</div>
</button>
</Headline>
{ clearButtonVisible ?
<IconButton
data-test-clear-button
size="small"
iconSize="small"
icon="times-circle-solid"
aria-label={`Clear selected filters for "${label}"`}
onClick={this.handleClearButtonClick}
/> : null
}
{open ? displayWhenOpen : displayWhenClosed}
</div>
);
}
}
export default injectIntl(FilterAccordionHeader);
| JavaScript | 0 | @@ -1842,14 +1842,8 @@
?.id
- ?? ''
;%0A
|
b2e4ab201f53b9609509ef24e0be2a8de617c31b | change child doctype name | frappe/custom/doctype/package_publish_tool/package_publish_tool.js | frappe/custom/doctype/package_publish_tool/package_publish_tool.js | // Copyright (c) 2020, Frappe Technologies and contributors
// For license information, please see license.txt
frappe.ui.form.on('Package Publish Tool', {
refresh: function(frm) {
frm.set_query("document_type", "package_details", function () {
return {
filters: {
"istable": 0,
}
};
});
frappe.realtime.on("package", (data) => {
frm.dashboard.show_progress(data.prefix, data.progress / data.total * 100, __("{0}", [data.message]));
if ((data.progress+1) != data.total) {
frm.dashboard.show_progress(data.prefix, data.progress / data.total * 100, __("{0}", [data.message]));
} else {
frm.dashboard.hide_progress();
}
});
frm.trigger("show_instructions");
frm.trigger("last_deployed_on");
frm.trigger("set_dirty_trigger");
frm.trigger("set_deploy_primary_action");
},
last_deployed_on: function(frm) {
if (frm.doc.last_deployed_on) {
frm.trigger("show_indicator");
}
},
show_indicator: function(frm) {
let pretty_date = frappe.datetime.prettyDate(frm.doc.last_deployed_on);
frm.page.set_indicator(__("Last deployed {0}", [pretty_date]), "blue");
},
set_dirty_trigger: function(frm) {
$(frm.wrapper).on("dirty", function() {
frm.page.set_primary_action(__('Save'), () => frm.save());
});
},
set_deploy_primary_action: function(frm) {
if (frm.doc.package_details.length && frm.doc.instances.length) {
frm.page.set_primary_action(__("Deploy"), function () {
frappe.show_alert({
message: __("Deploying Package"),
indicator: "green"
});
frappe.call({
method: "frappe.custom.doctype.package_publish_tool.package_publish_tool.deploy_package",
callback: function() {
frappe.msgprint(__("Package has been published."));
}
});
});
}
},
show_instructions: function(frm) {
let field = frm.get_field("html_info");
field.html(`
<p class="text-muted small">
- Create a Package by selecting the Documents and filters in the Package table.<br>
- Add the Remote Instance's URL, Username and Password to the Instances table.<br>
- Once the above details are filled, Deploy button will be visible and the Package will be deployed on click.<br>
</p>
`);
}
});
frappe.ui.form.on('Package Detail', {
form_render: function (frm, cdt, cdn) {
function _show_filters(filters, table) {
table.find('tbody').empty();
if (filters.length > 0) {
filters.forEach(filter => {
const filter_row =
$(`<tr>
<td>${filter[1]}</td>
<td>${filter[2] || ""}</td>
<td>${filter[3]}</td>
</tr>`);
table.find('tbody').append(filter_row);
});
} else {
const filter_row = $(`<tr><td colspan="3" class="text-muted text-center">
${__("Click to Set Filters")}</td></tr>`);
table.find('tbody').append(filter_row);
}
}
let row = frappe.get_doc(cdt, cdn);
let wrapper = $(`[data-fieldname="filters_json"]`).empty();
let table = $(`<table class="table table-bordered" style="cursor:pointer; margin:0px;">
<thead>
<tr>
<th style="width: 33%">${__('Filter')}</th>
<th style="width: 33%">${__('Condition')}</th>
<th>${__('Value')}</th>
</tr>
</thead>
<tbody>
</tbody>
</table>`).appendTo(wrapper);
$(`<p class="text-muted small">${__("Click table to edit")}</p>`).appendTo(wrapper);
let filters = JSON.parse(row.filters_json || '[]');
_show_filters(filters, table);
table.on('click', () => {
if (!row.document_type) {
frappe.msgprint(__("Select Document Type."));
return;
}
frappe.model.with_doctype(row.document_type, function() {
let dialog = new frappe.ui.Dialog({
title: __('Set Filters'),
fields: [
{
fieldtype: 'HTML',
label: 'Filters',
fieldname: 'filter_area',
}
],
primary_action: function() {
let values = filter_group.get_filters();
let flt = [];
if (values) {
values.forEach(function(value) {
flt.push([value[0], value[1], value[2], value[3]]);
});
}
row.filters_json = JSON.stringify(flt);
_show_filters(flt, table);
dialog.hide();
},
primary_action_label: "Set"
});
let filter_group = new frappe.ui.FilterGroup({
parent: dialog.get_field('filter_area').$wrapper,
doctype: row.document_type,
on_change: () => {},
});
filter_group.add_filters_to_filter_group(filters);
dialog.show();
});
});
},
}); | JavaScript | 0.000082 | @@ -2229,21 +2229,28 @@
ackage D
-etail
+ocument Type
', %7B%0A%09fo
|
cf3c243af27e111fcad4f6f58885cf9e9ff3c5db | Set default values for user preferences | frontend/delta/js/Clipperz/PM/DataModel/User.Header.Preferences.js | frontend/delta/js/Clipperz/PM/DataModel/User.Header.Preferences.js | /*
Copyright 2008-2015 Clipperz Srl
This file is part of Clipperz, the online password manager.
For further information about its features and functionalities please
refer to http://www.clipperz.com.
* Clipperz is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
* Clipperz 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public
License along with Clipperz. If not, see http://www.gnu.org/licenses/.
*/
try { if (typeof(Clipperz.PM.DataModel.User) == 'undefined') { throw ""; }} catch (e) {
throw "Clipperz.PM.DataModel.User.Header.Preferences depends on Clipperz.PM.DataModel.User!";
}
if (typeof(Clipperz.PM.DataModel.User.Header) == 'undefined') { Clipperz.PM.DataModel.User.Header = {}; }
Clipperz.PM.DataModel.User.Header.Preferences = function(args) {
Clipperz.PM.DataModel.User.Header.Preferences.superclass.constructor.apply(this, arguments);
return this;
}
Clipperz.Base.extend(Clipperz.PM.DataModel.User.Header.Preferences, Clipperz.PM.DataModel.EncryptedRemoteObject, {
'toString': function() {
return "Clipperz.PM.DataModel.User.Header.Preferences";
},
//-------------------------------------------------------------------------
'mergeDefaultPreferences': function(somePreferences) {
var result;
result = new Clipperz.KeyValueObjectStore();
result.setValues(MochiKit.Base.updatetree(
Clipperz.Base.deepClone(Clipperz.PM.DataModel.User.Header.Preferences.defaultPreferences),
somePreferences
));
return result;
},
'getPreferences': function() {
return Clipperz.Async.callbacks("User.Header.Preferences.getPreferences", [
MochiKit.Base.method(this, 'values'),
MochiKit.Base.method(this, 'mergeDefaultPreferences')
], {trace:false});
},
'getPreference': function(aKey) {
return Clipperz.Async.callbacks("User.Header.Preferences.getPreference", [
MochiKit.Base.method(this, 'getPreferences'),
MochiKit.Base.methodcaller('getValue', aKey)
], {trace:false});
},
//=========================================================================
__syntaxFix__: "syntax fix"
});
Clipperz.PM.DataModel.User.Header.Preferences.defaultPreferences = {
'lock': {
'timeoutInMinutes': 10
},
'shouldShowDonationPanel': true
}; | JavaScript | 0.000001 | @@ -2564,16 +2564,36 @@
ock': %7B%0A
+%09%09'enabled': false,%0A
%09%09'timeo
@@ -2608,21 +2608,232 @@
tes': 10
+,
%0A%09%7D,%0A
+%09'passwordGenerator': %7B%0A%09%09'length': 24,%0A%09%09'characters': %7B%0A%09%09%09'A-Z': true,%0A%09%09%09'a-z': true,%0A%09%09%09'0-9': true,%0A%09%09%09'space': false,%0A%09%09%09'!#?': true,%0A%09%09%7D,%0A%09%7D,%0A%0A%09//%09legacy preferences%0A%09'preferredLanguage': 'en',%0A
%09'should
@@ -2856,11 +2856,12 @@
l': true
+,
%0A%7D;
|
db62953588cd8d377c199c12a61e401f891d1e25 | Use foo loop instead of underscore 3rd-party lib | src/client/script-manager.js | src/client/script-manager.js | 'use strict';
import * as _ from '../external/underscore.js';
function functionFromString(funcOrString) {
if (typeof funcOrString === 'function') {
return funcOrString;
}
// lets trick babel to allow the usage of 'this' in outermost context
var innerWrap = '(function() { return (' + funcOrString + ').apply(this, args)}).call(temp)',
transpiled = (babel.transform(innerWrap).code
.replace(/^\s*('|")use strict('|");/, '"use strict"; return (') + ')')
.replace(/;\s*\)$/, ')'),
outerWrap = `(function() {
var args = arguments;
return (function(temp) {` +
transpiled +
`})(this);
})`;
// this makes sure we always create a function
try {
// this fails if it has no `function ()` header
return eval('(' + outerWrap.toString() + ')');
} catch(err) {
// this works with just a block of code (for lively4script)
return new Function(outerWrap.toString());
}
}
function isLively4Script(object) {
return object.tagName.toLocaleLowerCase() == "script" &&
object.type == 'lively4script';
}
function persistToDOM(object, funcString, data={}) {
var DOMScript = $('<script>', _.extend(data, {
type: 'lively4script',
text: funcString
}));
$(object).append(DOMScript);
}
function removeFromDOM(object, name) {
var children = $(object).children('script[type="lively4script"][data-name="' + name + '"]');
if (children.size() != 1) {
throw 'multiple children detected ' + children;
}
children.remove();
}
function asCollection(object) {
if (object instanceof jQuery) {
return object;
}
return [object];
}
function prepareFunction(funcOrString, options) {
var func = functionFromString(funcOrString);
if (typeof func !== 'function') {
throw 'no valid function provided!';
}
var name = func.name || options.name;
if (!name) {
throw 'cannot update script without name!';
}
return {
executable: func,
name: name
};
}
function bindFunctionToObject(object, func, options) {
object[func.name] = func.executable.bind(object);
object[func.name].isScript = true;
}
function initializeScriptsMap(object) {
if (typeof object.__scripts__ === 'undefined') {
object.__scripts__ = {};
}
}
function scriptExists(object, name) {
return typeof object.__scripts__ !== 'undefined' &&
typeof object.__scripts__[name] !== 'undefined';
}
function addFunctionToScriptsMap(object, name, funcOrString) {
object.__scripts__[name] = funcOrString.toString();
}
function persistScript(object, name, funcOrString, options) {
if (!options.hasOwnProperty("persist") || options.persist == true) {
persistToDOM(object, funcOrString.toString(), {"data-name": name});
}
}
export default class ScriptManager {
static findLively4Script(parent, shadow) {
// if shadow is set, look for the scripts in the shadow root
var children = shadow ? parent.shadowRoot.children : parent.children;
_.each(children, (child) => {
if (isLively4Script(child)) {
try {
var scriptName = child.dataset.name;
this.addScript(parent, child.textContent, {
name: scriptName,
persist: false
});
} catch(e) {
debugger
lively.notify('Error adding function: ' + scriptName + ' to object: ' + parent,
""+e , 20, () => lively.openWorkspace("" + e + "Source: " + child.textContent));
console.error('Error while adding function ' + scriptName + ' to object:');
console.error($(parent));
console.error(e);
}
} else {
this.findLively4Script(child, false);
}
});
// dont do it here...
// if(parent.initialize) parent.initialize() // initialize only after all scripts are there.
}
static load() {
this.loadScriptsFromDOM();
}
static loadScriptsFromDOM() {
this.findLively4Script(document);
}
static attachScriptsFromShadowDOM(root) {
this.findLively4Script(root, true);
}
static updateScript(object, funcOrString, options={}) {
var objects = asCollection(object);
_.each(objects, (object) => {
var func = prepareFunction(funcOrString, options);
this.removeScript(object, func.name);
this.addScript(object, func.executable, options);
});
}
static addScript(object, funcOrString, options={}) {
var objects = asCollection(object);
_.each(objects, function(object) {
var func = prepareFunction(funcOrString, options);
initializeScriptsMap(object);
if(scriptExists(object, func.name)) {
throw 'script name "' + func.name + '" is already reserved!';
}
bindFunctionToObject(object, func, options);
addFunctionToScriptsMap(object, func.name, funcOrString);
persistScript(object, func.name, funcOrString, options);
});
}
static removeScript(object, name) {
var objects = asCollection(object);
_.each(objects, function(object) {
if(!scriptExists(object, name)) {
throw 'script name "' + name + '" does not exist!';
}
delete object.__scripts__[name];
delete object[name];
removeFromDOM(object, name);
});
}
static callScript(object, name) {
var optionalArgs = [].splice.call(arguments, 2);
var objects = asCollection(object);
_.each(objects, function(object) {
if(!scriptExists(object, name)) {
throw 'unknown script "' + name +'"!';
}
var returnValue = object[name].apply(object, optionalArgs);
});
return returnValue;
}
}
ScriptManager.load()
| JavaScript | 0.00041 | @@ -3088,35 +3088,34 @@
-_.each(children, (
+for(let child of
child
-) =%3E
+ren)
%7B%0A
@@ -3880,26 +3880,24 @@
%7D%0A %7D
-);
%0A%0A // don
|
d056c2e7f046be643aa48887ed87418e90340432 | Add missing import | lib/queryBuilder/operations/InsertOperation.js | lib/queryBuilder/operations/InsertOperation.js | 'use strict';
const { QueryBuilderOperation } = require('./QueryBuilderOperation');
const { StaticHookArguments } = require('../StaticHookArguments');
const { after, mapAfterAllReturn } = require('../../utils/promiseUtils');
const { isPostgres, isSqlite, isMySql } = require('../../utils/knexUtils');
const { isObject } = require('../../utils/objectUtils');
// Base class for all insert operations.
class InsertOperation extends QueryBuilderOperation {
constructor(name, opt) {
super(name, opt);
this.models = null;
this.isArray = false;
this.modelOptions = Object.assign({}, this.opt.modelOptions || {});
}
onAdd(builder, args) {
const json = args[0];
const modelClass = builder.modelClass();
this.isArray = Array.isArray(json);
this.models = modelClass.ensureModelArray(json, this.modelOptions);
return true;
}
async onBefore2(builder, result) {
if (this.models.length > 1 && (!isPostgres(builder.knex()) || !isSqlServer(builder.knex()))) {
throw new Error('batch insert only works with Postgresql and SQL Server');
} else {
await callBeforeInsert(builder, this.models);
return result;
}
}
onBuildKnex(knexBuilder, builder) {
if (!isSqlite(builder.knex()) && !isMySql(builder.knex()) && !builder.has(/returning/)) {
// If the user hasn't specified a `returning` clause, we make sure
// that at least the identifier is returned.
knexBuilder.returning(builder.modelClass().getIdColumn());
}
knexBuilder.insert(this.models.map(model => model.$toDatabaseJson(builder)));
}
onAfter1(_, ret) {
if (!Array.isArray(ret) || !ret.length || ret === this.models) {
// Early exit if there is nothing to do.
return this.models;
}
if (isObject(ret[0])) {
// If the user specified a `returning` clause the result may be an array of objects.
// Merge all values of the objects to our models.
for (let i = 0, l = this.models.length; i < l; ++i) {
this.models[i].$set(ret[i]);
}
} else {
// If the return value is not an array of objects, we assume it is an array of identifiers.
for (let i = 0, l = this.models.length; i < l; ++i) {
const model = this.models[i];
// Don't set the id if the model already has one. MySQL and Sqlite don't return the correct
// primary key value if the id is not generated in db, but given explicitly.
if (!model.$id()) {
model.$id(ret[i]);
}
}
}
return this.models;
}
onAfter2(builder, models) {
const result = this.isArray ? models : models[0] || null;
return callAfterInsert(builder, this.models, result);
}
clone() {
const clone = super.clone();
clone.models = this.models;
clone.isArray = this.isArray;
return clone;
}
}
function callBeforeInsert(builder, models) {
const maybePromise = callInstanceBeforeInsert(builder, models);
return after(maybePromise, () => callStaticBeforeInsert(builder));
}
function callInstanceBeforeInsert(builder, models) {
return mapAfterAllReturn(models, model => model.$beforeInsert(builder.context()), models);
}
function callStaticBeforeInsert(builder) {
const args = StaticHookArguments.create({ builder });
return builder.modelClass().beforeInsert(args);
}
function callAfterInsert(builder, models, result) {
const maybePromise = callInstanceAfterInsert(builder, models);
return after(maybePromise, () => callStaticAfterInsert(builder, result));
}
function callInstanceAfterInsert(builder, models) {
return mapAfterAllReturn(models, model => model.$afterInsert(builder.context()), models);
}
function callStaticAfterInsert(builder, result) {
const args = StaticHookArguments.create({ builder, result });
const maybePromise = builder.modelClass().afterInsert(args);
return after(maybePromise, maybeResult => {
if (maybeResult === undefined) {
return result;
} else {
return maybeResult;
}
});
}
module.exports = {
InsertOperation
};
| JavaScript | 0.000466 | @@ -256,16 +256,29 @@
isMySql
+, isSqlServer
%7D = req
|
7f5e8cac014c5e1bc0996b0bb27fa1b7999767c6 | Add hints | libs/spider-queen.js | libs/spider-queen.js | 'use strict';
const cache = require('../config/cache.js');
const crawlers = require('./crawlers');
const spiders = require('./spiders');
const util = require('./util.js');
function findCrawlers (selector) {
let result = [];
for (var name in crawlers) {
let crawler = crawlers[name];
if (selector(crawler)) {
result.push(crawler);
}
}
return result;
}
function firstCrawler (selector) {
let result = findCrawlers(selector);
if (result.length > 0) {
return result[0];
} else {
return null;
}
}
function findSpiders (selector) {
let result = [];
for (var name in spiders) {
let spider = spiders[name];
if (selector(spider)) {
result.push(spider);
}
}
return result;
}
function firstSpider (selector) {
let result = findSpiders(selector);
if (result.length > 0) {
return result[0];
} else {
return null;
}
}
function summon (options) {
let target = options.target || '';
let qtext = options.qtext || '';
if (options.assign) {
let assign = options.assign;
let spider = firstSpider(v => v.name() == assign &&
v.target() == target);
if (spider) {
return [spider, qtext];
}
let crawler = firstCrawler(v => v.name() == assign);
if (crawler) {
return [crawler, qtext];
}
}
if (target == "human") {
return [
firstSpider(v => v.name() == "minnano-av"),
qtext
];
}
if (target == "movie") {
let movid = '';
if (qtext.indexOf(' ') > 0) {
let pos = qtext.indexOf(' ');
let name = qtext.substring(0, pos).trim();
let spider = firstSpider(
v =>
v.name().indexOf(name) > -1 &&
v.target() == target);
if (spider) {
movid = qtext.substring(pos).trim();
return [ spider, movid ];
}
let crawler = firstCrawler(v => v.name() == name);
if (crawler) {
movid = qtext.substring(pos).trim();
return [ crawler, movid ];
}
movid = qtext;
return [ null, movid ];
} else {
movid = qtext;
return [ null, movid ];
}
}
return [];
}
const HINTS_LIST = [
{ crawler: 'r18', regex: /^asw-\d{3}$/ },
{ crawler: 'r18', regex: /^ght-\d{3}$/ },
{ crawler: 'caribbeancom', regex: /^(carib|caribbean) \d{6}-\d{3}$/ },
{ crawler: 'caribbeancompr', regex: /^(caribpr|caribbeanpr) \d{6}_\d{3}$/ },
{ crawler: 'dmm', regex: /.*/ },
];
function findHintsList (movid) {
var qtext = (movid || '').toLowerCase();
if (!qtext) {
return [];
}
for (var hint of HINTS_LIST) {
if (hint.regex.test(qtext)) {
let id = qtext;
if (qtext.indexOf(' ') > 0) {
let pos = qtext.indexOf(' ');
id = qtext.substring(pos).trim();
}
return [ hint.crawler, id ];
}
}
return [];
}
function crawl (queryText, options) {
let qtext = (queryText || '').toLowerCase();
let opt = options || {};
if (qtext == '') {
return null;
}
let target = opt.target || '';
let type = opt.type || '';
if (!target || !type) {
throw new Error("Invalid Arguments");
}
let [ crawler, id ] = summon({
target: target,
qtext: qtext,
assign: options.assign,
});
if (!crawler) {
let [crawlerName, movid] = findHintsList(id);
if (crawlerName) {
crawler = summon({
assign: crawlerName,
target: target,
})[0];
}
if (movid) {
id = movid;
}
}
if (!crawler) {
return Promise.reject('Crawler not found');
}
let data_cached = cache.get('data', id);
if (data_cached) {
return Promise.resolve(data_cached);
} else {
let options = {
"type": type,
"qtext": id,
};
console.log(
'Crawler: ' + crawler.name() + ' ' +
JSON.stringify(options)
);
return crawler.crawl(options).then(data => {
switch (type) {
case "search":
cache.set('data', id, data, 1800); // 30 minutes
break;
case "id":
cache.set('data', id, data, 3600); // 1 hour
break;
}
return data;
});
}
}
module.exports.crawl = crawl;
| JavaScript | 0 | @@ -2764,32 +2764,86 @@
d%7B6%7D_%5Cd%7B3%7D$/ %7D,%0A
+ %7B crawler: 'tokyo-hot', regex: /%5Etokyohot .*$/ %7D,%0A
%7B crawler: '
|
4db4fb1f3c0579c15f27d8ba18e108f71f6cb902 | Update index.js | demo/src/index.js | demo/src/index.js | import VirtualizedList from '../../src';
const ROW_HEIGHT_POSSIBILITIES = [70, 110, 140, 70, 90, 70];
const CONTAINER_STYLE = 'width: 400px; height: 600px; overflow-y: auto; border: 1px solid #DDD; margin: 50px auto;';
const ELEMENT_STYLE = `border-bottom: 1px solid #DDD; box-sizing: border-box; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 18px; font-family: sans-serif; color: #333;';`;
// Here, we're generating an array of 1000 numbers [0, 1, 2, 3, 4, ...] to use as our dataset
const data = Array.from(Array(1000).keys());
function getRandomHeight() {
return ROW_HEIGHT_POSSIBILITIES[Math.floor(Math.random()*ROW_HEIGHT_POSSIBILITIES.length)];
}
const rowHeights = data.map(getRandomHeight);
(function() {
// Make sure you have a container to render into
const container = document.createElement('div');
container.setAttribute('style', CONTAINER_STYLE);
document.body.append(container);
// Initialize our VirtualizedList
var virtualizedList = new VirtualizedList(container, {
data,
rowHeight: rowHeights,
renderRow: (row, index) => {
const element = document.createElement('div');
element.setAttribute('style', `height: ${rowHeights[index]}px; ${ELEMENT_STYLE}`);
element.innerHTML = row;
return element;
},
onMount: () => {
// We can set the initial index in the onMount callback
virtualizedList.scrollToIndex(15);
}
});
})();
| JavaScript | 0.000002 | @@ -1077,16 +1077,45 @@
eights,%0A
+ estimatedRowHeight: 100,%0A
rend
|
0bd88611fa0e52d55875b4ba8bc9161f0ee99576 | Remove {0} from the value if there's no existing tag to update. | lib/transforms/addContentVersionMetaElement.js | lib/transforms/addContentVersionMetaElement.js | var _ = require('underscore');
module.exports = function (queryObj, version, updateExisting) {
if (typeof version === 'undefined') {
throw new Error("transforms.addContentVersionMetaTag: The 'version' parameter is mandatory.");
}
return function addContentVersionMetaElement(assetGraph) {
assetGraph.findAssets(_.extend({type: 'Html'}, queryObj)).forEach(function (htmlAsset) {
var document = htmlAsset.parseTree;
if (updateExisting) {
var metaTags = document.getElementsByTagName('meta');
for (var i = 0 ; i < metaTags.length ; i += 1) {
var metaTag = metaTags[i];
if (metaTag.getAttribute('http-equiv').toLowerCase() === 'content-version') {
metaTag.setAttribute('content', version.replace(/\{0\}/g, metaTag.getAttribute('content') || ''));
return;
}
}
}
if (document.head) {
var contentVersionMetaElement = document.createElement('meta');
contentVersionMetaElement.setAttribute('http-equiv', 'Content-Version');
contentVersionMetaElement.setAttribute('content', version);
var lastExistingMetaElement;
for (var i = 0 ; i < document.head.childNodes.length ; i += 1) {
if (document.head.childNodes[i].nodeName.toLowerCase() === 'meta') {
lastExistingMetaElement = document.head.childNodes[i];
}
}
// element.insertBefore(newElement, null) works as element.appendChild(newElement) if there is no nextSibling:
if (lastExistingMetaElement) {
document.head.insertBefore(contentVersionMetaElement, lastExistingMetaElement.nextSibling);
} else {
document.head.insertBefore(contentVersionMetaElement, document.head.firstChild);
}
document.head.appendChild(contentVersionMetaElement);
htmlAsset.markDirty();
}
});
};
};
| JavaScript | 0 | @@ -1246,16 +1246,38 @@
version
+.replace(/%5C%7B0%5C%7D/g, '')
);%0A
|
616b63c534c20a129275a0482bc03c347e58770c | Fix search content field fallback | app/reducers/search.js | app/reducers/search.js | // @flow
import { createSelector } from 'reselect';
import { get } from 'lodash';
import { Search } from '../actions/ActionTypes';
import moment from 'moment-timezone';
import { resolveGroupLink } from 'app/reducers/groups';
import { categoryOptions } from 'app/reducers/pages';
export type SearchResult = {
label: string,
color: string,
picture: string,
path: string,
value: string,
link: string,
content: string,
icon: string
};
const initialState = {
results: [],
autocomplete: [],
query: '',
searching: false,
open: false
};
const searchMapping = {
'users.user': {
label: user => `${user.fullName} (${user.username})`,
title: 'fullName',
type: 'Bruker',
color: '#A1C34A',
value: 'id',
username: 'username',
link: user => `/users/${user.username}`,
id: 'id',
profilePicture: 'profilePicture'
},
'articles.article': {
icon: 'book',
label: 'title',
title: 'title',
type: 'Artikkel',
picture: 'cover',
color: '#52B0EC',
path: '/articles/',
value: 'id',
content: 'description'
},
'events.event': {
label: event =>
`${event.title} (${moment(event.startTime).format('YYYY-MM-DD')})`,
title: 'title',
type: 'Arrangement',
date: 'startTime',
icon: 'calendar',
color: '#E8953A',
picture: 'cover',
path: '/events/',
value: 'id',
content: 'description'
},
'flatpages.page': {
icon: 'paper-outline',
label: 'title',
title: 'title',
type: page =>
'Infoside - ' +
get(categoryOptions.find(val => val.value === page.category), 'label'),
color: '#E8953A',
link: page => `/pages/${page.category}/${page.slug}`,
value: 'slug',
content: 'content'
},
'gallery.gallery': {
label: 'title',
title: 'title',
type: 'Galleri',
color: '#F8953A',
icon: 'photos',
path: '/photos/',
value: 'id',
content: 'text'
},
'companies.company': {
icon: 'briefcase',
label: 'name',
title: 'name',
type: 'Bedrift',
color: '#E8953A',
path: '/companies/',
value: 'id',
content: 'description'
},
'tags.tag': {
label: 'id',
title: 'id',
type: 'Tag',
path: '/tags/',
icon: 'pricetags',
value: 'tag',
color: '#000000'
},
'users.abakusgroup': {
label: 'name',
title: 'name',
link: resolveGroupLink,
value: 'id',
profilePicture: 'logo',
id: 'id',
type: 'type',
icon: group => (group.profilePicture ? null : 'people'),
color: '#000000'
}
};
type State = typeof initialState;
export default function search(state: State = initialState, action: any) {
switch (action.type) {
case Search.SEARCH.BEGIN:
return {
...state,
query: action.meta.query,
searching: true
};
case Search.AUTOCOMPLETE.BEGIN:
return {
...state,
query: action.meta.query,
searching: true
};
case Search.SEARCH.SUCCESS:
if (action.meta.query !== state.query) {
return state;
}
return {
...state,
results: action.payload,
searching: false
};
case Search.AUTOCOMPLETE.SUCCESS:
if (action.meta.query !== state.query) {
return state;
}
return {
...state,
autocomplete: action.payload,
searching: false
};
case Search.SEARCH.FAILURE:
return {
...state,
searching: false
};
case Search.AUTOCOMPLETE.FAILURE:
return {
...state,
searching: false
};
case Search.TOGGLE_OPEN:
return {
...state,
autocomplete: [],
open: !state.open
};
default:
return state;
}
}
/*
* This transfors the search results (both search and autocomplete) from the backend.
* If the element has no valid url, it will be returned as null. You should therefore
* always filter out null values:
*
* const mapped = results.map(transformResult).filter(Boolean)
*/
const transformResult = result => {
const fields = searchMapping[result.contentType];
const item = {};
Object.keys(fields).forEach(field => {
const value = fields[field];
if (typeof value === 'function') {
item[field] = value(result);
} else {
item[field] = result[value] || value;
}
});
item.link = fields.link ? item.link : item.path + item.value;
return item;
};
export const selectAutocomplete = (autocomplete: Array<any>) =>
autocomplete.map(transformResult).filter(Boolean);
export const selectAutocompleteRedux = createSelector(
state => state.search.autocomplete,
autocomplete => autocomplete.map(transformResult).filter(Boolean)
);
export const selectResult = createSelector(
state => state.search.results,
results => results.map(transformResult).filter(Boolean)
);
| JavaScript | 0.000005 | @@ -1055,32 +1055,45 @@
',%0A content:
+item =%3E item%5B
'description'%0A
@@ -1081,32 +1081,33 @@
em%5B'description'
+%5D
%0A %7D,%0A 'events.
@@ -1388,32 +1388,45 @@
',%0A content:
+item =%3E item%5B
'description'%0A
@@ -1414,32 +1414,33 @@
em%5B'description'
+%5D
%0A %7D,%0A 'flatpag
@@ -1748,16 +1748,29 @@
ontent:
+item =%3E item%5B
'content
@@ -1770,16 +1770,17 @@
content'
+%5D
%0A %7D,%0A
@@ -1959,14 +1959,28 @@
nt:
+item =%3E item%5B
'text'
+%5D
%0A %7D
@@ -2165,16 +2165,29 @@
ontent:
+item =%3E item%5B
'descrip
@@ -2191,16 +2191,17 @@
ription'
+%5D
%0A %7D,%0A
|
301e947611604c959686bff8d2b06746e856af54 | Update dashboard-controller.js | www/dashboard/dashboard-controller.js | www/dashboard/dashboard-controller.js | 'use strict';
angular.module('MyApp.controllers')
.controller('DashboardCtrl', function($firebase, $scope, Auth) {
var noticeRef = new Firebase('https://noticeapp.firebaseio.com/notifications');
var textMessages = $firebase(noticeRef);
$scope.email = Auth.currentUser.email;
$scope.message = "";
$scope.postNotification = function(message) {
// textMessages.$add({message: message, createdBy: email, tag: tag});
textMessages.$add({message: message});
message = "";
};
});
| JavaScript | 0.000001 | @@ -464,24 +464,49 @@
message
+, createdBy: $scope.email
%7D);%0A %09%09
message
@@ -497,16 +497,23 @@
%7D);%0A %09%09
+$scope.
message
|
93e0b455adcd37ff4e995b4d9ad300a15c9ae283 | add modal close click event and pass data to form | app/assets/scripts/components/modal.js | app/assets/scripts/components/modal.js | import React,{Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {folderAdd} from "../actions/index";
import FormNewFolder from "./form-new-folder";
import FormNewFolderItem from "./form-new-folder-item";
import FormRequestEditor from "./form-request-editor";
class Modal extends Component {
constructor(props){
super(props);
this.state = {
show:false
};
this.componentWillReceiveProps = this.componentWillReceiveProps.bind(this);
this.addKeyboardEvents = this.addKeyboardEvents.bind(this);
this.onComplete = this.onComplete.bind(this);
this.addKeyboardEvents();
}
componentWillReceiveProps(nextProps) {
this.forceUpdate();
this.setState({show:true})
}
addKeyboardEvents(){
document.addEventListener("keyup",(e) => {
if (e.keyCode == 27) {
this.onComplete();
}
})
}
onComplete(){
const modal = document.querySelector(".component-modal");
const form = modal.querySelector("form");
this.setState({show:false});
if (form.length > 0) form.reset();
}
render() {
var type = ("type" in this.props.modal) ? this.props.modal.type : "";
var showClass = (this.state.show)? "-open": "";
return (
<div className={`component-modal ${showClass}`}>
<div className="panel">
{(type == "newFolder") ? <FormNewFolder onComplete={this.onComplete} /> : null}
{(type == "newFolderItem") ? <FormNewFolderItem onComplete={this.onComplete} /> : null}
{(type == "form-request-editor") ? <FormRequestEditor onComplete={this.onComplete} /> : null}
</div>
</div>
);
}
}
function mapStateToProps({modal}){
return {modal};
}
function mapDispatchToProps(dispatch){
return bindActionCreators({folderAdd},dispatch);
}
export default connect (mapStateToProps,mapDispatchToProps)(Modal);
| JavaScript | 0 | @@ -651,32 +651,90 @@
ete.bind(this);%0A
+ this.onClickClose = this.onClickClose.bind(this);%0A
this.add
@@ -1278,151 +1278,412 @@
-render() %7B%0A var type = (%22type%22 in this.props.modal) ? this.props.modal.type : %22%22;%0A var showClass = (this.state.show)? %22-open%22: %22%22
+onClickClose(e)%7B%0A var hasClass = e.target.classList.contains(%22component-modal%22)%0A if (hasClass) this.setState(%7Bshow:false%7D)%0A %7D%0A%0A render() %7B%0A var showClass = (this.state.show)? %22-open%22: %22%22;%0A var type = (%22type%22 in this.props.modal) ? this.props.modal.type : %22%22;%0A var data = (%22data%22 in this.props.modal)? this.props.modal.data : %7B%7D;%0A%0A console.log(%22modal%22,type)
;%0A%0A
@@ -1757,16 +1757,44 @@
Class%7D%60%7D
+ onClick=%7Bthis.onClickClose%7D
%3E%0A
@@ -1886,16 +1886,28 @@
ewFolder
+ data=%7Bdata%7D
onCompl
@@ -2006,16 +2006,28 @@
lderItem
+ data=%7Bdata%7D
onCompl
@@ -2090,34 +2090,32 @@
ype == %22form
--r
+R
equest
--e
+E
ditor%22) ? %3CF
@@ -2130,16 +2130,28 @@
stEditor
+ data=%7Bdata%7D
onCompl
|
26927a256c7484ef4f0d220b39f356001308caaf | Remove useless test | gulpfile.js/tests/changelog.test.js | gulpfile.js/tests/changelog.test.js | 'use strict'
const endOfLine = require('os').EOL
const test = require('tape')
const changelog = require('../tasks/changelog')
test('changelog - runCommand', (t) => {
t.plan(3)
changelog
.runCommand()
.catch(function (err) {
t.ok(err instanceof Error, 'returns an Error if the command fails')
t.ok(err.message.includes('No command specified'), 'returns exec\'s error message')
})
changelog
.runCommand('echo test')
.then(function (stdout) {
t.equal(stdout, 'test' + endOfLine, 'should return a Promise if given a command to run')
})
})
test('changelog - getGitDiffs', (t) => {
t.plan(1)
t.ok(changelog.getGitDiffs().then(), 'returns a promise')
})
test('changelog - isMerged', (t) => {
t.plan(1)
t.ok(changelog.isMerged().then(), 'returns a promise')
})
test('changelog - filterFiles', (t) => {
t.plan(3)
t.equal(changelog.filterFiles(['README.md', 'another.md']).length, 1, 'returns 1 as only README has filtered')
t.equal(changelog.filterFiles(['README.md', 'README.md', 'README.md', 'README.md', 'another.md']).length, 1, 'returns 1 as only README has filtered')
t.equal(changelog.filterFiles(['README.md', 'another.md'])[0], 'another.md', 'returns a string representing the only item')
})
test('changelog - verifyGitDiffs', (t) => {
t.plan(9)
changelog
.verifyGitDiffs()
.catch(function (err) {
t.ok(err instanceof Error, 'returns an Error if the command fails')
t.ok(err.message.includes('CHANGELOG.md was not updated'), 'returns an error message')
})
changelog
.verifyGitDiffs('file1\nfile2\nfile')
.catch(function (err) {
t.ok(err instanceof Error, 'returns an Error if the command fails')
t.ok(err.message.includes('CHANGELOG.md was not updated'), 'returns an error message')
})
changelog
.verifyGitDiffs('file1\nREADME.md\nfolder1/README.md')
.catch(function (err) {
t.ok(err instanceof Error, 'returns an Error if the command fails')
t.ok(err.message.includes('CHANGELOG.md was not updated'), 'returns an error message')
})
t.ok(changelog.verifyGitDiffs('string').then(), 'returns a promise')
changelog
.verifyGitDiffs('file1\nCHANGELOG.md\nfile')
.then((res) => {
t.ok(res, 'returns true as CHANGELOG.md is in the list')
})
changelog
.verifyGitDiffs('README.md\nfolder1/README.md\nfolder2/README.md')
.then((res) => {
t.ok(res, 'returns true as CHANGELOG.md should not be changed')
})
})
| JavaScript | 0 | @@ -1315,9 +1315,9 @@
lan(
-9
+8
)%0A%0A
@@ -2087,80 +2087,8 @@
%7D)%0A%0A
- t.ok(changelog.verifyGitDiffs('string').then(), 'returns a promise')%0A%0A
ch
|
cad8c4068b1d6b44785e825f7e54be39426a4563 | handle edge case in watch | packages/gluestick-cli/watch.js | packages/gluestick-cli/watch.js | const path = require('path');
const chalk = require('chalk');
const chokidar = require('chokidar');
const fs = require('fs-extra');
module.exports = (exitWithError) => {
const packagePath = path.join(process.cwd(), 'package.json');
let packageContent = null;
try {
packageContent = require(packagePath);
} catch (error) {
exitWithError(`Cannot find package.json in ${packagePath}`);
}
try {
if (/\d\.\d\.\d.*/.test(packageContent.dependencies.gluestick)) {
exitWithError('Gluestick dependency does not contain valid path');
}
} catch (error) {
exitWithError('Invalid package.json');
}
let gsDeps = null;
let gsPackages = [];
gsDeps = require(path.join(process.cwd(), 'package.json')).dependencies;
gsPackages = Object.keys(gsDeps).filter(
(e => /^gluestick/.test(e) && !/\d+\.\d+\.\d+.*/.test(gsDeps[e])),
);
const gsDependenciesPath = gsPackages.map(e => {
const newPath = gsDeps[e].replace('file://', '').replace('file:', '');
return newPath[0] !== '/'
? path.join(
process.cwd(),
newPath,
)
: newPath;
});
gsDependenciesPath.forEach((e, i) => {
const packageName = gsPackages[i];
const convertFilePath = filePath => {
const split = filePath.split(packageName);
return path.join(
process.cwd(),
'node_modules',
packageName,
split[split.length - 1],
);
};
const watcher = chokidar.watch(`${e}/**/*`, {
ignored: [
/(^|[/\\])\../,
/.*node_modules.*/,
],
persistent: true,
});
watcher
.on('ready', () => {
const copy = (filePath, type, typeColorFactory) => {
const destPath = convertFilePath(filePath);
fs.copy(filePath, destPath, (err) => {
if (err) {
console.error(chalk.red(err));
} else {
console.log(`${chalk.gray(`${filePath} -> ${destPath}`)} ${typeColorFactory(`[${type}]`)}`);
}
});
};
const remove = (filePath, type, typeColorFactory) => {
const destPath = convertFilePath(filePath);
fs.remove(destPath, (err) => {
if (err) {
console.error(chalk.red(err));
} else {
console.log(`${chalk.gray(destPath)} ${typeColorFactory(`[${type}]`)}`);
}
});
};
console.log(chalk.blue(`Watching for changes in ${packageName}...`));
watcher.on('add', filePath => copy(filePath, 'added', chalk.green));
watcher.on('change', filePath => copy(filePath, 'changed', chalk.yellow));
watcher.on('unlink', filePath => remove(filePath, 'removed', chalk.red));
watcher.on('unlinkDir', filePath => remove(filePath, 'removed dir', chalk.magenta));
watcher.on('addDir', filePath => {
const destPath = convertFilePath(filePath);
fs.ensureDir(destPath, (err) => {
if (err) {
console.error(chalk.red(err));
} else {
console.log(`${chalk.gray(destPath)} ${chalk.cyan('[added dir]')}`);
}
});
});
});
});
};
| JavaScript | 0 | @@ -1239,57 +1239,8 @@
%3E %7B%0A
- const split = filePath.split(packageName);%0A
@@ -1339,29 +1339,53 @@
-split%5Bsplit.length -
+/packages%5C/%5Ba-zA-Z-_%5D*%5C/(.*)/.exec(filePath)%5B
1%5D,%0A
|
a37adb6695f9e68251bc152c311a081308123982 | Add platform availability info | tools/parse-language-reports/index.js | tools/parse-language-reports/index.js | var fs = require('fs'),
parse = require('./parse'),
path = require('path'),
yaml = require('js-yaml');
function isVersionLess(a, b) {
a = a.split('.').map(Number);
b = b.split('.').map(Number);
for (var i = 0; i < 4; i++) {
if (a[i] != b[i]) {
return a[i] < b[i];
}
}
return false;
}
function addPlatform(value, platform, version) {
if (!value.platforms) {
value.platforms = {};
}
if (value.platforms[platform]) {
if (isVersionLess(version, value.platforms[platform])) {
value.platforms[platform] = version;
}
} else {
value.platforms[platform] = version;
}
}
function getPlatform(reportPath, platformNames) {
var platform = path.basename(reportPath).match(/Language\.(.+)\.txt$/)[1];
if (!platformNames[platform]) {
throw new Error('Unknown platform: ' + platform);
}
return platformNames[platform];
}
function parseLanguageReports(languageReports, platformNames) {
var combinedReport = {
types: {},
properties: {},
platforms: {}
};
fs.readdirSync(languageReports).forEach(function(version) {
var versionPath = path.join(languageReports, version);
fs.readdirSync(versionPath).forEach(function(reportFile) {
var reportPath = path.join(versionPath, reportFile);
var platform = getPlatform(reportPath, platformNames);
console.error(version + ' - ' + platform);
addPlatform(combinedReport, platform, version);
var report = parse(fs.readFileSync(reportPath));
Object.keys(report.types).forEach(function(key) {
if (!combinedReport.types[key]) {
combinedReport.types[key] = report.types[key];
}
addPlatform(combinedReport.types[key], platform, version);
});
Object.keys(report.properties).forEach(function(key) {
if (!combinedReport.properties[key]) {
combinedReport.properties[key] = report.properties[key];
}
addPlatform(combinedReport.properties[key], platform, version);
});
});
});
return combinedReport;
}
function getPlatformNames() {
var platformToTargets =
yaml.safeLoad(fs.readFileSync(path.join(__dirname, 'platforms.yml')));
var targetToPlatform = {};
Object.keys(platformToTargets).forEach(function(name) {
platformToTargets[name].forEach(function(target) {
targetToPlatform[target] = name;
})
});
return targetToPlatform;
}
function main() {
if (process.argv.length !== 3) {
console.error('usage: parse-language-reports <folder>');
return process.exit(1);
}
var platformNames = getPlatformNames();
var language = parseLanguageReports(process.argv[2], platformNames);
console.log(JSON.stringify(language));
}
if (require.main === module) {
main();
}
module.exports = parseLanguageReports;
| JavaScript | 0 | @@ -617,24 +617,378 @@
ion;%0A %7D%0A%7D%0A%0A
+function convertPlatformsToAvailability(value) %7B%0A value.availability = %7B%7D;%0A%0A Object.keys(value.platforms).forEach(function(platform) %7B%0A var version = value.platforms%5Bplatform%5D;%0A%0A if (!value.availability%5Bversion%5D) %7B%0A value.availability%5Bversion%5D = %5B%5D;%0A %7D%0A%0A value.availability%5Bversion%5D.push(platform);%0A %7D);%0A%0A delete value.platforms;%0A%7D%0A%0A
function get
@@ -1021,24 +1021,24 @@
ormNames) %7B%0A
-
var platfo
@@ -1356,27 +1356,8 @@
ies:
- %7B%7D,%0A platforms:
%7B%7D%0A
@@ -1722,63 +1722,8 @@
);%0A%0A
- addPlatform(combinedReport, platform, version);%0A%0A
@@ -2293,32 +2293,302 @@
%0A %7D);%0A %7D);%0A%0A
+ Object.keys(combinedReport.types).forEach(function(key) %7B%0A convertPlatformsToAvailability(combinedReport.types%5Bkey%5D);%0A %7D);%0A%0A Object.keys(combinedReport.properties).forEach(function(key) %7B%0A convertPlatformsToAvailability(combinedReport.properties%5Bkey%5D);%0A %7D);%0A%0A
return combine
@@ -3108,51 +3108,8 @@
%7D%0A%0A
- var platformNames = getPlatformNames();%0A%0A
va
@@ -3159,17 +3159,20 @@
rgv%5B2%5D,
-p
+getP
latformN
@@ -3175,20 +3175,21 @@
ormNames
+()
);%0A
-%0A
consol
|
272d8df5373677ee5edb43724db0f0ca67f99c5b | add optional margin for text position | Sources/Widgets/Widgets3D/ShapeWidget/Constants.js | Sources/Widgets/Widgets3D/ShapeWidget/Constants.js | export const BehaviorCategory = {
POINTS: 'POINTS',
PLACEMENT: 'PLACEMENT',
RATIO: 'RATIO',
};
export const ShapeBehavior = {
[BehaviorCategory.POINTS]: {
CORNER_TO_CORNER: 0,
CENTER_TO_CORNER: 1,
RADIUS: 2,
DIAMETER: 3,
},
[BehaviorCategory.PLACEMENT]: {
CLICK: 0,
DRAG: 1,
CLICK_AND_DRAG: 2,
},
[BehaviorCategory.RATIO]: {
FIXED: 0,
FREE: 1,
},
};
export const HorizontalTextPosition = {
OUTSIDE_LEFT: 'OUSIDE_LEFT',
INSIDE_LEFT: 'INSIDE_LEFT',
OUTSIDE_RIGHT: 'OUSIDE_RIGHT',
INSIDE_RIGHT: 'INSIDE_RIGHT',
MIDDLE: 'MIDDLE',
};
export const VerticalTextPosition = {
OUTSIDE_TOP: 'OUSIDE_TOP',
INSIDE_TOP: 'INSIDE_TOP',
OUTSIDE_BOTTOM: 'OUSIDE_BOTTOM',
INSIDE_BOTTOM: 'INSIDE_BOTTOM',
MIDDLE: 'MIDDLE',
};
export function computeTextPosition(
bounds,
horizontalPosition,
verticalPosition,
textWidth,
textHeight
) {
let x = 0;
switch (horizontalPosition) {
case HorizontalTextPosition.OUTSIDE_LEFT:
x = bounds[0] - textWidth;
break;
case HorizontalTextPosition.INSIDE_LEFT:
x = bounds[0];
break;
case HorizontalTextPosition.MIDDLE:
x = 0.5 * (bounds[0] + bounds[1] - textWidth);
break;
case HorizontalTextPosition.INSIDE_RIGHT:
x = bounds[1] - textWidth;
break;
case HorizontalTextPosition.OUTSIDE_RIGHT:
x = bounds[1];
break;
default:
break;
}
let y = 0;
switch (verticalPosition) {
case VerticalTextPosition.OUTSIDE_TOP:
y = bounds[3] + textHeight;
break;
case VerticalTextPosition.INSIDE_TOP:
y = bounds[3];
break;
case VerticalTextPosition.MIDDLE:
y = 0.5 * (bounds[2] + bounds[3] + textWidth);
break;
case VerticalTextPosition.INSIDE_BOTTOM:
y = bounds[2] + textHeight;
break;
case VerticalTextPosition.OUTSIDE_BOTTOM:
y = bounds[2];
break;
default:
break;
}
return [x, y, 0];
}
export default ShapeBehavior;
| JavaScript | 0.000001 | @@ -891,17 +891,31 @@
xtHeight
+,%0A margin = 0
%0A
-
) %7B%0A le
@@ -1024,32 +1024,41 @@
s%5B0%5D - textWidth
+ - margin
;%0A break;%0A
@@ -1120,16 +1120,25 @@
ounds%5B0%5D
+ + margin
;%0A
@@ -1327,16 +1327,25 @@
extWidth
+ - margin
;%0A
@@ -1417,16 +1417,25 @@
ounds%5B1%5D
+ + margin
;%0A
@@ -1582,32 +1582,41 @@
%5B3%5D + textHeight
+ + margin
;%0A break;%0A
@@ -1675,16 +1675,25 @@
ounds%5B3%5D
+ - margin
;%0A
@@ -1880,16 +1880,25 @@
xtHeight
+ + margin
;%0A
@@ -1942,32 +1942,32 @@
OUTSIDE_BOTTOM:%0A
-
y = bounds
@@ -1969,16 +1969,25 @@
ounds%5B2%5D
+ - margin
;%0A
|
43f50dbe6ee27fb45857cc210f4236d9706261a7 | Change marks for CC logging. | extension/modules/require-debug.js | extension/modules/require-debug.js | /*Software License Agreement (BSD License)
Copyright (c) 2007, Parakey Inc.
All rights reserved.
Redistribution and use of this software in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of Parakey Inc. nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of Parakey Inc.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// johnjbarton@johnjbarton.com May 2011 IBM Corp.
// Extend require.js to add debugging information
// Include this file immediately after require.js
// ********************************************************************************************* //
/*
* Override this function to write output from the debug support for require.
* @param see Firebug console.log
*/
require.log = function()
{
try
{
FBTrace.sysout.apply(FBTrace, arguments);
}
catch(exc)
{
if (window.console)
console.log.apply(console, arguments);
else
alert.apply(null, arguments);
}
}
/*
* Called by require for each completed module
* @param fullName module name
* @param deps array of module names that fullName depends upon
*/
require.onDebugDAG = function(fullName, deps, url)
{
if (!require.depsNamesByName)
{
require.depsNamesByName = {};
require.urlByFullName = {};
}
var arr = [];
for (var p in deps)
arr.push(p);
require.depsNamesByName[fullName] = arr;
require.urlByFullName[fullName] = url;
}
require.originalExecCb = require.execCb;
require.execCbOFF = function (name)
{
var ret = require.originalExecCb.apply(require, arguments);
try
{
if (ret)
{
var basename = "requirejs("+name+")";
for (var prop in ret)
{
try
{
if (ret.hasOwnProperty(prop))
{
var value = ret[prop];
if (value !== null &&
(typeof value == "function" || typeof value == "object"))
{
value.displayName = basename+"/"+prop;
}
}
}
catch (e)
{
require.log("Could not displayName module "+name+" prop "+prop+": "+
e.toString(), [ret, prop, value]);
}
}
ret.displayName = basename;
}
}
catch(e)
{
require.log("Could not displayName module "+name+": "+e.toString());
}
return ret;
};
/* Calls require.log to record dependency analysis.
* Call this function from your main require.js callback function
* @param none
*
*/
require.analyzeDependencyTree = function()
{
require.log("Firebug module list: ", require.depsNamesByName);
// For each deps item create an object referencing dependencies
function linkArrayItems(id, depNamesByName, path)
{
var deps = depNamesByName[id];
var result = {};
for (var i = 0; i < deps.length; i++)
{
var depID = deps[i];
if (path.indexOf(":"+depID+":") == -1) // Then depId is not already an dependent
result[depID] = linkArrayItems(depID, depNamesByName, path+":"+depID+":");
else
require.log("Circular dependency: "+path+":"+depID+":");
}
return result;
}
var linkedDependencies = {};
var dependents = {}; // reversed list, dependents by name
var depNamesByName = require.depsNamesByName;
for (var name in depNamesByName)
{
var depArray = depNamesByName[name];
if (name === "undefined")
{
linkedDependencies["__main__"] = linkArrayItems(name, depNamesByName, "");
name = "__main__";
}
for (var i = 0; i < depArray.length; i++)
{
var dependent = depArray[i];
if (!dependents[dependent])
dependents[dependent] = [];
dependents[dependent].push(name);
}
}
var minimal = [];
var mainDeps = depNamesByName["undefined"];
for (var i = 0; i < mainDeps.length; i++)
{
var dependencyOfMain = mainDeps[i];
var dependentsOfDependencyOfMain = dependents[dependencyOfMain];
if (dependentsOfDependencyOfMain.length === 1)
minimal.push(dependencyOfMain);
}
require.log("Firebug module dependency tree: ", linkedDependencies);
require.log("Firebug dependents: ", dependents);
require.log("Firebug minimal modules list: ", minimal);
require.log("Firebug URLs: ", require.urlByFullName);
}
/*
* Calls require.log for warning and debug of require.js.
* Called by require.js diagnostic branch
*/
require.onDebug = function()
{
try
{
require.log.apply(null,arguments);
}
catch(exc)
{
var msg = "";
for (var i = 0; i < arguments.length; i++)
msg += arguments[i]+", ";
window.alert("Loader; onDebug:"+msg+"\n");
}
}
/*
* Calls require.log for errors, then throws exception
* Called by require.js
*/
require.onError = function(exc)
{
require.onDebug.apply(require, arguments);
throw exc;
} | JavaScript | 0 | @@ -3210,16 +3210,18 @@
unction%22
+/*
%7C%7C type
@@ -3240,16 +3240,18 @@
%22object%22
+*/
))%0A
@@ -3292,23 +3292,478 @@
+
-
+var funcName = name + %22_%22 + prop;%0A funcName = funcName.replace(%22/%22, %22_%22, %22g%22);%0A funcName = funcName.replace(%22-%22, %22_%22, %22g%22);%0A var namedFunction = eval(%22(function()%7B return function %22 + funcName +%0A %22()%7Breturn true;%7D %7D)()%22);%0A value.displayName = namedFunction;%0A //
value.di
|
975c077270144879dcbb8f0adb94335663e5f6e3 | fix typo | libs/phantomRunner.js | libs/phantomRunner.js | /*global current:true, window, QUnit, document, require:true */
var phantomHelper = require('./helper.js');
var logger = require('chip')();
require('colors');
var prefixes = logger.getPrefixes();
prefixes.log = "";
prefixes.trace = "";
logger.setPrefixes(prefixes);
module.exports = function(testOpt, done, coverage){
'use strict';
var suiteResults = { files: 0, success: 0, failure: 0 },
verbose = false, cwd = process.cwd();
return function(e, phantom){
function handleResults(file, result, queue){
suiteResults.success += result.success;
suiteResults.failure += result.failure;
coverage(file, result.__coverage__);
if (verbose) {
logger.log('');
}
if (result.failure === 0) {
logger.info(file);
} else {
logger.error(file);
}
if (queue.length){
loadSuite(queue.shift(), queue);
} else {
if (!verbose){
logger.warn('Files: ' + (suiteResults.files) + ' Tests: ' + (suiteResults.success + suiteResults.failure) + ' Success: ' + suiteResults.success + ' Failed: ' + suiteResults.failure);
logger.log('');
}
phantom.exit();
done(suiteResults.failure? false : true);
}
}
function initRequire(page, test){
phantomHelper.evaluate(page, function(requireConf, paths, test) {
if (requireConf) {
require = requireConf;
}
if (require.baseUrl) {
require.baseUrl = 'file://' + paths.cwd + '/' + require.baseUrl;
}
if (require.paths) {
for (var prop in require.paths) {
if (require.paths.hasOwnProperty(prop)) {
require.paths[prop] = 'file://'+ paths.cwd + '/' + require.paths[prop];
}
}
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'utf-8';
script.setAttribute('data-main', 'file://'+ paths.cwd + '/'+ test);
script.src = 'file://'+ paths.lib + '/../node_modules/requirejs/require.js';
document.head.appendChild(script);
}, testOpt.require, {cwd: cwd, lib: __dirname}, test);
}
function injectDependency(page, dependencies, callback) {
var dep = dependencies.shift();
page.injectJs(dep, function(){
if (dependencies.length) {
injectDependency(page, dependencies, callback);
} else {
callback();
}
});
}
function exectuteTests(file, queue) {
return phantom.createPage(function(e, page) {
page.onConsoleMessage = function(text){
if (text.indexOf('logger.')===0 && verbose){
/* jshint evil: true */
eval(text);
/* jshint evil: false */
} else {
if (verbose){
logger.log(text);
}
}
};
page.onError = function(e){
logger.log(JSON.stringify(e, null, 4));
done(false);
};
var testRunning = false;
page.open(__dirname +'/empty.html', function(){
if (testRunning) {
return;
}
testRunning = true;
var dependencies = [__dirname + '/helper.js', __dirname +'/../node_modules/qunitjs/qunit/qunit.js'];
if (testOpt.include) {
dependencies = dependencies.concat(testOpt.include.map(function(f){ return cwd + '/' + f; }));
}
injectDependency(page, dependencies, function(){
page.evaluate(function(){
var testRunning;
current = {
success: 0,
failure: 0
};
window.onerror = function(){
current.failure++;
};
QUnit.init();
QUnit.config.blocking = false;
QUnit.config.requireExpects = true;
QUnit.config.autorun = false;
QUnit.testStart = function(obj){
testRunning = obj.name;
console.log('logger.trace("'+ obj.name.replace(/\"/g, '\\"') +'".bold)');
};
QUnit.log = function(testResult){
var result = testResult.result;
current[(result)?'success':'failure']++;
var expected = testResult.expected,
actual = testResult.actual,
message = testResult.message,
makeCliFriendly = function (input) {
// Return the string 'isNaN' if that is the case
if (input.toString() === 'isNaN' && typeof input !== 'string') {
return 'isNaN';
// Return the string undefined if input is undefined
} else if (typeof input === 'undefined') {
return 'undefined';
// Return indication for JSON.parse to run and the stringified content
} else {
return JSON.stringify(input);
}
}
if (result) {
console.log('logger.info("'+ (message || 'test successful').replace(/\"/g, '\\"') +'")');
} else {
console.log('logger.error("'+ (message || 'test failed').replace(/\n/g, '\\n').replace(/\"/g, '\\"') +'")');
if (typeof expected!== 'undefined') {
console.log('logger.error(" expected: '+ makeCliFriendly(expected).replace(/\"/g, '\\"') +'")');
}
if (typeof actual!== 'undefined') {
console.log('logger.error(" actual: '+ makeCliFriendly(actual).replace(/\"/g, '\\"') + '")');
}
}
};
}, function(){
initRequire(page, file);
phantomHelper.waitFor(page, function(){
return !QUnit.config.queue.length;
}, function(){
if (page) {
page.evaluate(function(){
if (window.__coverage__){
current.__coverage__ = window.__coverage__;
}
return current;
}, function(e, result) {
page = null;
handleResults(file, result, queue);
});
}
}, function(){
logger.error('script timeout');
done(false);
}, 10000);
});
});
});
});
}
function loadSuite(file, queue){
if (verbose) {
logger.log('');
logger.warn('TESTING:' + file);
logger.log('');
}
exectuteTests(file, queue);
}
function initialize(files){
suiteResults.files = files.length;
if (suiteResults.files === 0) {
logger.error('no test to be run');
done(false);
}
verbose = (suiteResults.files === 1 || testOpt.verbose);
return files;
}
var queue = initialize(testOpt.tests);
loadSuite(queue.shift(), queue);
};
};
| JavaScript | 0.999991 | @@ -2282,25 +2282,24 @@
unction exec
-t
uteTests(fil
@@ -5800,17 +5800,16 @@
%0A%09%09%09exec
-t
uteTests
|
80bcd503160fea3cf948303ca6c079ede159f7ae | Add a shortcut for isMoment | addon/services/moment.js | addon/services/moment.js | import Ember from 'ember';
import moment from 'moment';
const { computed, Logger:logger } = Ember;
export default Ember.Service.extend({
_timeZone: null,
locale: null,
defaultFormat: null,
init() {
this._super(...arguments);
if (!this.get('defaultFormat')) {
this.set('defaultFormat', 'LLLL');
}
},
timeZone: computed('_timeZone', {
get() {
return this.get('_timeZone');
},
set(propertyKey, timeZone) {
if (!moment.tz) {
logger.warn('[ember-moment] attempted to set timezone, but moment-timezone unavailable.');
return;
}
this.set('_timeZone', timeZone);
return timeZone;
}
}),
changeLocale(locale) {
this.set('locale', locale);
},
changeTimeZone(timeZone) {
this.set('timeZone', timeZone);
},
moment() {
let time = moment(...arguments);
const locale = this.get('locale');
const timeZone = this.get('timeZone');
if (locale) {
time = time.locale(locale);
}
if (timeZone && time.tz) {
time = time.tz(timeZone);
}
return time;
}
});
| JavaScript | 0.000061 | @@ -803,24 +803,83 @@
eZone);%0A %7D,
+%0A %0A isMoment(obj) %7B%0A return moment.isMoment(obj);%0A %7D,
%0A%0A moment()
|
ca6ae474578ed30933dbe64b0fe4d098b041130f | fix build | src/service/generator/game_generator.test.js | src/service/generator/game_generator.test.js | import { generateGame } from "./";
import PlayerModel from "../../model/player_model";
describe(`generator:: Game`, () => {
describe(`::generate`, () => {
[0, 1, 2, 10].forEach((v) => {
it(`expected ${v} battlefields`, () => {
const model = generateGame(v, 0);
expect(model.getBattlefields().length).toBe(v);
});
});
[1, 2, 10].forEach(v => {
it(`expected last player of ${v} to be market as Human Controlled`, () => {
const model = generateGame(v, 0);
model.getBattlefields().forEach((bf, index) => {
const expectedSeq = index === (v - 1) ? PlayerModel.getHumanFlag() : 0;
expect(bf.getPlayer().byte_sequence).toBe(expectedSeq);
});
});
});
[0, 1, 2, 10].forEach(size => {
const expectedCellAmount = size ** 2;
it(`expected 2 battlefields with size ${size} attached [expected ${expectedCellAmount} cells]`, () => {
const model = generateGame(2, size);
/** @param {BattlefieldModel} battlefieldModel */
for (const battlefieldModel of model.getBattlefields()) {
const cells = battlefieldModel.getCellsIndexedByCoordinate();
expect(Object.keys(cells).length).toBe(expectedCellAmount);
}
});
});
});
});
| JavaScript | 0.000001 | @@ -770,17 +770,11 @@
byte
-_sequence
+Seq
).to
|
69dedb2f06accaca9bfee2c6dd634e485d367e9c | Fix annotation | src/main/author/units/unit/topics/topics-controller.js | src/main/author/units/unit/topics/topics-controller.js | import _ from 'lodash';
import removeModal from '../../remove-modal';
export default /*@ngInject*/class TopicsCtrl{
constructor(topics,$state,$scope, $uibModal, $http){
this.$http = $http;
this.topics = topics.data;
this.$state = $state;
this.$uibModal = $uibModal;
this.removeModal = removeModal($scope);
this.$scope = $scope;
this.selected = null;
this.collapse = false;
this.init();
this.fields = [{
key: 'title',
type: 'horizontalInput',
templateOptions: {
type: 'text',
required: true,
label: 'Titel',
placeholder: 'Titel des Subkapitels'
},
modelOptions: $scope.units.modelOptions
},
{
key: 'subtitle',
type: 'horizontalInput',
templateOptions: {
type: 'text',
label: 'Untertitel',
placeholder: 'Untertitel des Subkapitels'
},
modelOptions: $scope.units.modelOptions
},
{
key: 'body',
type: 'horizontalMarkdownArea',
templateOptions: {
required: true,
label: 'Text',
placeholder: 'Hier Text des Subkapitels eingeben'
},
modelOptions: $scope.units.modelOptions
}];
}
init(){
if(!this.$state.params.topic){return;}
this.selected = _.find(this.topics,{_id: this.$state.params.topic});
return this.selected;
}
select(){
if(this.selected){
this.$state.go(
'main.author.units.unit.topics.topic.basics',
{topic: this.selected._id}
);
}
else{
this.$state.go('main.author.units.unit.topics.new');
}
}
remove(){
if(!this.selected){return;}
return this.$uibModal.open(this.removeModal)
.result
.then(() => {
return this.$http.delete(`api/units/${this.$state.params.unit}/topics/${this.selected._id}`);
})
.then(
() => {
_.remove(this.topics, {_id: this.selected._id});
this.selected = null;
this.select();
},
(e) => {
this.error = e;
}
);
}
move(dir){
return this.$http.patch(`api/units/${this.$state.params.unit}/topics`,{
action: 'move',
dir,
topic: this.selected._id
})
.then(
(res) => {
this.topics = res.data;
this.$scope.$broadcast('topic moved', {updatedAt: res.headers('last-modified')});
this.$scope.unit.unit.updatedAt = res.headers('x-updated-unit');
},
(e) => {
this.error = e;
}
);
}
}
| JavaScript | 0.000077 | @@ -82,21 +82,8 @@
ult
-/*@ngInject*/
clas
@@ -2466,8 +2466,83 @@
;%0A %7D%0A%7D%0A
+TopicsCtrl.$inject = %5B'topics', '$state', '$scope', '$uibModal', '$http'%5D;%0A
|
e5d6ea15543809fff90e239e3178e38b85ca5c78 | update etl for dim category | src/etl/dim-category-etl-manager.js | src/etl/dim-category-etl-manager.js | 'use strict'
// external deps
var ObjectId = require("mongodb").ObjectId;
var BaseManager = require('module-toolkit').BaseManager;
var moment = require("moment");
// internal deps
require('mongodb-toolkit');
var CategoryManager = require('../managers/master/category-manager');
module.exports = class DimCategoryEtlManager extends BaseManager {
constructor(db, user, sql) {
super(db, user);
this.sql = sql;
this.categoryManager = new CategoryManager(db, user);
this.migrationLog = this.db.collection("migration-log");
}
run() {
var startedDate = new Date();
this.migrationLog.insert({
description: "Dim Category from MongoDB to Azure DWH",
start: startedDate,
})
return this.getTimestamp()
.then((time) => this.extract(time))
.then((data) => this.transform(data))
.then((data) => this.load(data))
.then(() => {
var finishedDate = new Date();
var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes");
var updateLog = {
description: "Dim Category from MongoDB to Azure DWH",
start: startedDate,
finish: finishedDate,
executionTime: spentTime + " minutes",
status: "Successful"
};
this.migrationLog.updateOne({ start: startedDate }, updateLog);
}).catch((err) => {
var finishedDate = new Date();
var spentTime = moment(finishedDate).diff(moment(startedDate), "minutes");
var updateLog = {
description: "Dim Category from MongoDB to Azure DWH",
start: startedDate,
finish: finishedDate,
executionTime: spentTime + " minutes",
status: err
};
this.migrationLog.updateOne({ start: startedDate }, updateLog);
})
}
getTimestamp() {
return this.migrationLog.find({
status: "Successful",
description: "Dim Category from MongoDB to Azure DWH"
}).sort({ finish: -1 }).limit(1).toArray();
}
extract(time) {
var timestamp = new Date(time[0].finish);
return this.categoryManager.collection.find({
_updatedDate: {
"$gt": timestamp
},
_deleted: false
}).toArray();
}
transform(data) {
var result = data.map((item) => {
return {
categoryCode: item.code ? `'${item.code}'` : null,
categoryName: item.name ? `'${item.name}'` : null,
categoryType: item.name ? `'${item.name.toLowerCase() == 'bahan baku' ? 'BAHAN BAKU' : 'NON BAHAN BAKU'}'` : null
};
});
return Promise.resolve([].concat.apply([], result));
}
insertQuery(sql, query) {
return new Promise((resolve, reject) => {
sql.query(query, function (err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
})
})
}
load(data) {
return new Promise((resolve, reject) => {
this.sql.startConnection()
.then(() => {
var transaction = this.sql.transaction();
transaction.begin((err) => {
var request = this.sql.transactionRequest(transaction);
var command = [];
var sqlQuery = '';
var count = 1;
for (var item of data) {
if (item) {
var queryString = `insert into DL_Dim_Kategori_Temp(ID_Dim_Kategori, Kode_Kategori, Nama_Kategori, Jenis_Kategori) values(${count}, ${item.categoryCode}, ${item.categoryName}, ${item.categoryType});\n`;
sqlQuery = sqlQuery.concat(queryString);
if (count % 1000 == 0) {
command.push(this.insertQuery(request, sqlQuery));
sqlQuery = "";
}
console.log(`add data to query : ${count}`);
count++;
}
}
if (sqlQuery !== "")
command.push(this.insertQuery(request, `${sqlQuery}`));
this.sql.multiple = true;
return Promise.all(command)
.then((results) => {
request.execute("DL_UPSERT_DIM_KATEGORI").then((execResult) => {
request.execute("DL_INSERT_DIMTIME").then((execResult) => {
transaction.commit((err) => {
if (err)
reject(err);
else
resolve(results);
});
}).catch((error) => {
transaction.rollback((err) => {
console.log("rollback")
if (err)
reject(err)
else
reject(error);
});
})
}).catch((error) => {
transaction.rollback((err) => {
console.log("rollback")
if (err)
reject(err)
else
reject(error);
});
})
})
.catch((error) => {
transaction.rollback((err) => {
console.log("rollback");
if (err)
reject(err)
else
reject(error);
});
});
})
})
.catch((err) => {
reject(err);
})
})
.catch((err) => {
reject(err);
})
}
}
| JavaScript | 0 | @@ -2341,22 +2341,21 @@
time%5B0%5D.
-finish
+start
);%0A
|
11b8e781d058c2088b967cbf1c99a574da64230a | Test for capital letters in descriptions | tests/docs.js | tests/docs.js | 'use strict';
var docs = require('../docs/src/js/docs');
var expect = require('chai').expect;
var sinon = require('sinon');
var stub = sinon.stub;
var utils = require('./helpers/utils');
var each = utils.each;
var any = utils.any;
var getContextStub = require('./helpers/get-context-stub');
var Canvas = require('../lib/index.js');
describe('docs', function () {
var element = document.createElement('canvas');
stub(element, 'getContext', getContextStub);
var canvas = new Canvas(element);
it('is a list of groups', function () {
expect(docs.length).to.be.above(1);
each(docs, function (value) {
expect(value.name).to.exist;
expect(value.methods).to.exist;
});
});
it('should contain all of the canvasimo methods and aliases', function () {
each(canvas, function (value, key) {
var anyGroupContainsTheMethod = any(docs, function (group) {
return any(group.methods, function (method) {
return method.name === key || method.alias === key;
});
});
expect(anyGroupContainsTheMethod).to.be.true;
});
});
it('should have descriptions for every group', function () {
var totalGroups = 0;
var documentedGroups = 0;
var firstUndocumentedGroup;
each(docs, function (group) {
totalGroups += 1;
if (group.description) {
documentedGroups += 1;
} else if (!firstUndocumentedGroup) {
firstUndocumentedGroup = group.name;
}
});
console.log(documentedGroups + ' of ' + totalGroups + ' groups have descriptions');
if (firstUndocumentedGroup) {
throw new Error(firstUndocumentedGroup + ' group has no description');
}
});
it('should have descriptions for every method', function () {
var totalMethods = 0;
var documentedMethods = 0;
var firstUndocumentedMethod;
each(docs, function (group) {
each(group.methods, function (method) {
totalMethods += 1;
if (method.description) {
documentedMethods += 1;
} else if (!firstUndocumentedMethod) {
firstUndocumentedMethod = method.name;
}
});
});
console.log(documentedMethods + ' of ' + totalMethods + ' methods have descriptions');
if (firstUndocumentedMethod) {
throw new Error(firstUndocumentedMethod + ' method has no description');
}
});
it('descriptions should have a full stop', function () {
each(docs, function (group) {
if (group.description.lastIndexOf('.') < 0) {
throw new Error(group.name + ' group\'s description should have a full stop');
}
each(group.methods, function (method) {
if (method.description.lastIndexOf('.') < 0) {
throw new Error(method.name + ' method\'s description should have a full stop');
}
});
});
});
it('should have arguments or returns for every method', function () {
var exceptions = [
'clearCanvas',
'beginPath',
'closePath',
'save',
'restore',
'resetTransform'
];
var totalMethods = 0;
var documentedMethods = 0;
var firstUndocumentedMethod;
each(docs, function (group) {
each(group.methods, function (method) {
totalMethods += 1;
if (exceptions.indexOf(method.name) >= 0) {
return;
}
if (method.arguments || method.returns) {
documentedMethods += 1;
} else if (!firstUndocumentedMethod) {
firstUndocumentedMethod = method.name;
}
});
});
console.log(documentedMethods + ' of ' + totalMethods + ' methods have arguments or returns');
if (firstUndocumentedMethod) {
throw new Error(firstUndocumentedMethod + ' method has no arguments or returns');
}
});
});
| JavaScript | 0.00003 | @@ -2374,38 +2374,576 @@
riptions should
-have a
+begin with a capital letter', function () %7B%0A var beginsWithCapital = /%5E%5BA-Z%5D/;%0A%0A each(docs, function (group) %7B%0A if (!beginsWithCapital.test(group.description)) %7B%0A throw new Error(group.name + ' group%5C's description should have a capital letter');%0A %7D%0A%0A each(group.methods, function (method) %7B%0A if (!beginsWithCapital.test(method.description)) %7B%0A throw new Error(method.name + ' method%5C's description should have a capital letter');%0A %7D%0A %7D);%0A %7D);%0A %7D);%0A%0A it('descriptions should end with
full stop', fun
|
89f1c658d42fead785ba97be9d2e011410938f26 | Add missing multiple newline comments test | tests/test.js | tests/test.js | 'use strict';
const fs = require('fs');
const path = require('path');
const tape = require('tape');
const postcss = require('postcss');
const plugin = require('../src/');
const name = require('../package.json').name;
const processCss = function (css, options) {
return postcss(plugin(options)).process(css);
};
const testCssFixtures = function (testMessage, tests) {
tape(testMessage, function (t) {
// Set amount of assertions by setting two assertions per sort order test
t.plan(tests.length * 2);
tests.forEach(function (test) {
const options = test.options || {};
processCss(test.fixture, options).then(function (result) {
t.equal(result.css, test.expected, test.message);
t.equal(result.warnings().length, 0);
});
});
});
};
const sortOrderTests = [
{
message: 'Keep same order for identical properties.',
fixture: 'a{flex: 0;flex: 2;}',
expected: 'a{flex: 0;flex: 2;}'
},
{
message: 'Sort alphabetically with no order defined.',
fixture: 'a{flex: 0;border: 0;}',
expected: 'a{border: 0;flex: 0;}'
},
{
message: 'Sort alphabetically with a defined order.',
fixture: 'a{flex: 0;border: 0;}',
expected: 'a{border: 0;flex: 0;}',
options: { order: 'alphabetically' }
},
{
message: 'Sort according to custom order.',
fixture: 'a{border: 0;z-index: 0;}',
expected: 'a{z-index: 0;border: 0;}',
options: { customOrder: 'tests/custom-order.json' }
},
{
message: 'Sort according to SMACSS.',
fixture: 'a{border: 0;flex: 0;}',
expected: 'a{flex: 0;border: 0;}',
options: { order: 'smacss' }
},
{
message: 'Sort according to Concentric CSS.',
fixture: 'a{border: 0;flex: 0;}',
expected: 'a{flex: 0;border: 0;}',
options: { order: 'concentric-css' }
}
];
const commentOrderTests = [
{
message: 'Keep comment intact.',
fixture: 'a{flex: 0;/*flex*/}',
expected: 'a{flex: 0;/*flex*/}'
},
{
message: 'Keep dangling comment intact.',
fixture: 'a{flex: 0;\n/*end*/}',
expected: 'a{flex: 0;\n/*end*/}'
},
{
message: 'Keep multiple comments intact.',
fixture: 'a{flex: 0;\n/*flex*/\n/*flex 2*/}',
expected: 'a{flex: 0;\n/*flex*/\n/*flex 2*/}'
},
{
message: 'Keep newline comment above declaration.',
fixture: 'a{flex: 0;\n/*border*/\nborder: 0;}',
expected: 'a{\n/*border*/\nborder: 0;flex: 0;}'
},
{
message: 'Keep inline comment beside declaration.',
fixture: 'a{flex: 0;\nborder: 0; /*border*/}',
expected: 'a{\nborder: 0; /*border*/flex: 0;}'
}
];
const nestedDeclarationTests = [
{
message: 'Sort nested declarations.',
fixture: 'a{a{flex: 0;border: 0;}}',
expected: 'a{a{border: 0;flex: 0;}}',
},
{
message: 'Sort nested at-rule declarations.',
fixture: 'a{@media(){flex: 0;border: 0;}}',
expected: 'a{@media(){border: 0;flex: 0;}}'
}
];
testCssFixtures('Should order CSS declarations.', sortOrderTests);
testCssFixtures('Should retain comments.', commentOrderTests);
testCssFixtures('Should order nested CSS declarations.', nestedDeclarationTests);
tape('Should use the PostCSS plugin API.', function (t) {
t.plan(2);
t.ok(plugin().postcssVersion, 'Able to access version.');
t.equal(plugin().postcssPlugin, name, 'Able to access name.');
});
tape('CSS properties are up-to-date.', function (t) {
const cssOrdersDir = './orders/';
fs.readdir(cssOrdersDir, function (error, files) {
const sourceProperties = JSON.parse(
// eslint-disable-next-line no-sync
fs.readFileSync(path.join(cssOrdersDir, 'source.json'))
);
files
.filter(function (fileName) {
return fileName !== 'source.json';
})
// Pair filenames and amount of properties from each CSS order file
.map(function (fileName) {
return {
'fileName': fileName,
'properties': JSON.parse(
// eslint-disable-next-line no-sync
fs.readFileSync(path.join(cssOrdersDir, fileName))
)
};
})
.forEach(function (customOrderFile) {
t.deepLooseEqual(
customOrderFile.properties.sort(), sourceProperties.sort(),
customOrderFile.fileName + ' ' + 'has the same properties as source.'
);
});
t.end();
});
});
| JavaScript | 0.000001 | @@ -2412,32 +2412,227 @@
: 0;%7D'%0A %7D,%0A %7B%0A
+ message: 'Handle multiple newline comments.',%0A fixture: 'a%7Bflex: 0;%5Cn/*border a*/%5Cn/*border b*/%5Cnborder: 0;%7D',%0A expected: 'a%7B%5Cn/*border a*/%5Cn/*border b*/%5Cnborder: 0;flex: 0;%7D'%0A %7D,%0A %7B%0A
message: 'Ke
|
b13840926172eee6064b2aac8b9bc575dc506e28 | add more tests | tests/test.js | tests/test.js | var expect = require('chai').expect
var Subject = require('../lib/Subject')
var ResultEntry = require('../lib/ResultEntry')
var identBuilder = require('../lib/tools/identBuilder')
var splitter = require('../lib/tools/splitter')
var prepareTerm = require('../lib/tools/prepareTerm')
var dedupeStream = require('../lib/streams/dedupeStream')
var cutStream = require('../lib/tools/cutstream')
describe('models', () => {
describe('subject', () => {
var s;
before(() => {
s = new Subject('term #foo')
s.addChunk('fooChunk')
s.addChunk('barChunk')
})
it('should return the term', () => expect(s.getTerm()).to.equal('term #foo'))
it('should return the prepared term', () => expect(s.getTermPrepared()).to.equal('term foo'))
it('should return the prepared term ident', () => expect(s.getTermPreparedIdent()).to.equal('foo term'))
it('should return the chunks', () => expect(s.getChunks()).to.deep.equal(['fooChunk', 'barChunk']))
})
describe('resultentry', () => {
var s, e;
before(() => {
s = new Subject('fooTerm')
e = new ResultEntry(s, 2, 4)
})
it('should return the subject', () => expect(e.getSubject()).to.equal(s))
it('should return the number of matches chunks', () => expect(e.getCountMatchedChunks()).to.equal(2))
it('should return the relation of matched to contained chunks', () => expect(e.getMatchRelation()).to.equal(0.5))
})
})
describe('tools', () => {
describe('splitter', () => {
it('should split with a default chunk size of 2 and default whitespace treatment', () => {
var splitted = splitter('foo bar', {})
expect(splitted).to.deep.equal(['fo', 'oo', 'ob', 'ba', 'ar'])
})
it('should split with a custom chunk size of 3', () => {
var splitted = splitter('foo bar', {size: 3})
expect(splitted).to.deep.equal(['foo', 'oob', 'oba', 'bar'])
})
it('should split with a custom chunk size of 3 and should respect whitespaces', () => {
var splitted = splitter('meinl byzance crash', {size: 3, whitespaces: splitter.WHITESPACES_RESPECT})
expect(splitted).to.deep.equal(['mei', 'ein', 'inl', 'byz', 'yza', 'zan', 'anc', 'nce', 'cra', 'ras', 'ash'])
})
it('should return a chunk even if its smaller than size', () => {
var splitted = splitter('paiste 18 crash', {size: 3, whitespaces: splitter.WHITESPACES_RESPECT})
expect(splitted).to.deep.equal(['pai', 'ais', 'ist', 'ste', '18', 'cra', 'ras', 'ash'])
})
})
describe('prepareTerm', () => {
it('should prepare', () => expect(prepareTerm('foo bar-bax; # 123')).to.equal('foo bar-bax 123'))
})
describe('identBuilder', () => {
it('should create an ident', () => expect(identBuilder('foo-bar-bär-büx " , - + bax/baz')).to.equal('baxbaz foobarbaerbuex'))
})
})
describe('streams', () => {
describe('dedupe', () => {
var stream
var collection = []
before((done) => {
stream = dedupeStream('foo', 'bar')
stream.on('data', (data) => collection.push(data))
stream.on('end', done)
stream.write({foo: 'a bb', bar: 1})
stream.write({foo: 'bb a', bar: 3})
stream.write({foo: 'b+b a', bar: 44})
stream.write({foo: 'b-b a', bar: 33})
stream.write({foo: 'one', bar: 1})
stream.end()
})
it('should split with a default chunk size of 2', () => expect(collection).to.deep.equal([
{ foo: 'b+b a', bar: 81 },
{ foo: 'one', bar: 1 }
]))
})
describe('cutstream', () => {
var stream
var collection = []
before((done) => {
stream = cutStream(4)
stream.on('data', (data) => collection.push(data))
stream.on('end', done)
for(var i = 0; i < 10; i++) stream.write(i)
stream.end()
})
it('should cut', () => expect(collection).to.deep.equal([0, 1, 2]))
})
}) | JavaScript | 0 | @@ -2820,179 +2820,794 @@
-%7D)%0A%0A describe('identBuilder', () =%3E %7B%0A it('should create an ident', () =%3E expect(identBuilder('foo-bar-b%C3%A4r-b%C3%BCx %22 , - + bax/baz')).to.equal('baxbaz foobarbaerbuex
+ it('should prepare', () =%3E expect(prepareTerm('Paiste 2002 18%22 crash')).to.equal('paiste 2002 18%22 crash'))%0A it('should prepare', () =%3E expect(prepareTerm('Gallien Kr%C3%BCger NEO12-II-8')).to.equal('gallien kr%C3%BCger neo12-ii-8'))%0A %7D)%0A%0A describe('identBuilder', () =%3E %7B%0A it('should create an ident', () =%3E expect(identBuilder('foo-bar-b%C3%A4r-b%C3%BCx %22 , - + bax/baz')).to.equal('baxbaz foobarbaerbuex'))%0A it('should create an ident', () =%3E expect(identBuilder('Paiste 2002 18%22 crash')).to.equal('18 2002 crash paiste'))%0A it('should create an ident', () =%3E expect(identBuilder('Paiste 18%22 crash 2002')).to.equal('18 2002 crash paiste'))%0A it('should create an ident', () =%3E expect(identBuilder('Gallien Kr%C3%BCger NEO12-II-8')).to.equal('gallien krueger neo12ii8
'))%0A
|
7c63af81819147bd4c0b24b98a809395be437c67 | Add test that will probably never pass. | tests/test.js | tests/test.js | "use strict";
var util = require("util");
var fleece = require("../lib/fleece");
function test_url(url, expected) {
fleece.describe_url(url, function (err, result) {
if (err) {
console.error("URL %s error: %s", url, err);
throw new Error(err);
}
if (result.match(expected) === null) {
throw new Error(util.format("Expected %s but got %s", expected, result));
}
if (!result) {
console.log("URL %s: No result", url);
return;
}
console.log(url, "\n", result);
});
}
test_url(
"https://github.com/Floobits/floobits-sublime",
"^floobits-sublime \\(\\d+ stars \\d+ forks\\) .*$"
);
test_url(
"https://www.youtube.com/watch?v=taaEzHI9xyY#t=26m50s",
"^Crockford on JavaScript - Section 8: Programming Style & Your Brain \\d:\\d\\d:\\d\\d [\\d,]+ views \\d+% like$"
);
test_url(
"https://twitter.com/SpaceX/status/556131313905070081",
"^<@SpaceX> Close, but no cigar. This time. https://vine.co/v/OjqeYWWpVWK[\\s]+\\([\\d,]+ retweets, [\\d,]+ favorites\\)"
);
// TODO: this test is rather brittle. Any small change to whitespace on HN could break it.
test_url(
"https://news.ycombinator.com/item?id=6577671",
"Accidentally Turing-Complete \\(http:\\/\\/beza1e1\\.tuxen\\.de\\/articles\\/accidentally_turing_complete\\.html\\)[\\s]+\\d+ points by ggreer \\d+ days ago[\\s]+\\| \\d+ comments"
);
| JavaScript | 0 | @@ -522,16 +522,230 @@
%7D);%0A%7D%0A%0A
+// test_url(%0A// %22https://twitter.com/ggreer/status/588220411529297921%22,%0A// %22%3C@ggreer%3E An emoji haiku titled, Drinking on a School Night %F0%9F%93%9D%F0%9F%95%99%F0%9F%98%90%F0%9F%8D%BA%F0%9F%98%8A %F0%9F%98%8F%F0%9F%8D%BB%F0%9F%98%9C%F0%9F%8D%BB%E2%9C%A8%F0%9F%98%B4%F0%9F%92%A4 %F0%9F%8C%84%E2%8F%B0%F0%9F%98%A9%F0%9F%95%98%F0%9F%98%B1%5B%5Cs%5D+%5C%5C(%5B%5C%5Cd,%5D+ retweets, %5B%5C%5Cd,%5D+ favorites%5C%5C)%22%0A// );%0A%0A
test_url
|
64b5373b9dbb4349229002c443e800dc75e37a90 | Add error management | src/geo/geocoder/mapbox-geocoder.js | src/geo/geocoder/mapbox-geocoder.js | var ENDPOINT = 'https://api.mapbox.com/geocoding/v5/mapbox.places/{{address}}.json?access_token={{access_token}}';
var TYPES = {
country: 'country',
region: 'region',
postcode: 'postal-area',
district: 'localadmin',
place: 'venue',
locality: 'locality',
neighborhood: 'neighbourhood',
address: 'address',
poi: 'venue',
'poi.landmark': 'venue'
};
function MapboxGeocoder () { }
MapboxGeocoder.geocode = function (address, token) {
return fetch(ENDPOINT.replace('{{address}}', address).replace('{{access_token}}', token))
.then(function (response) {
return response.json();
})
.then(function (response) {
return _formatResponse(response);
});
};
/**
* Transform a mapbox geocoder response on a object friendly with our search widget.
* @param {object} rawMapboxResponse - The raw mapbox geocoding response, {@see https://www.mapbox.com/api-documentation/?language=JavaScript#response-object}
*/
function _formatResponse (rawMapboxResponse) {
if (!rawMapboxResponse.features.length) {
return [];
}
var center = _getCenter(rawMapboxResponse.features[0]);
return [{
center: center,
lat: center.lat,
lon: center.lon,
bbox: _getBoundingBox(rawMapboxResponse.features[0]),
type: _getType(rawMapboxResponse.features[0])
}];
}
/**
* Transform a lat, lon array into an object.
*/
function _getCenter (feature) {
return {
lon: feature.center[0],
lat: feature.center[1]
};
}
/**
* Transform the feature type into a well known enum.
*/
function _getType (feature) {
if (TYPES[feature.place_type[0]]) {
return TYPES[feature.place_type[0]];
}
return 'default';
}
/**
* Transform the feature bbox into a carto.js well known format.
*/
function _getBoundingBox (feature) {
if (!feature.bbox) {
return;
}
return {
south: feature.bbox[0],
west: feature.bbox[1],
north: feature.bbox[2],
east: feature.bbox[3]
};
}
module.exports = MapboxGeocoder;
| JavaScript | 0.000001 | @@ -442,24 +442,211 @@
s, token) %7B%0A
+ if (!address) %7B%0A throw new Error('MapboxGeocoder.geocode called with no address');%0A %7D%0A if (!token) %7B%0A throw new Error('MapboxGeocoder.geocode called with no access_token');%0A %7D%0A
return fet
|
732e47f54a0e38f1d5c33588d9c2c87da923a19b | remove cherry-pick debris | packages/api/src/create-subscription.js | packages/api/src/create-subscription.js | const Path = require("path");
const ARSON = require("arson");
const { validate } = require("@patternplate/validate-config");
const WebSocket = require("ws");
const loadConfig = require("@patternplate/load-config");
const createCompiler = require("./compiler");
const { PluginApi } = require("./plugin-api");
const debug = require("util").debuglog("PATTERNPLATE");
module.exports.createSubscription = function createSubscription(context) {
const { queues, config, cwd, wss, server, watcher } = context;
return handler => {
debug("subscribing to webpack and fs events");
// Prevent client errors (frequently caused by Chrome disconnecting on reload)
// from bubbling up and making the server fail, ref: https://github.com/websockets/ws/issues/1256
wss.on("connection", ws => {
ws.on("error", err => {
if (err.errno === "ECONNRESET") {
return;
}
console.error(err);
});
ws.on("message", async envelope => {
const message = ARSON.parse(envelope);
switch (message.type) {
case "plugin": {
const plugins = Array.isArray(config.plugins)
? await loadPlugins(config.plugins, { cwd, validate: true })
: [];
const target = plugins.find(p => p.id === message.payload.plugin);
if (!target) {
console.log(
`Received message for unknown plugin: ${message.payload.id}`
);
return;
}
const { plugin } = target;
if (!plugin.commands.hasOwnProperty(message.payload.command)) {
console.log(
`Received unknown command: ${
message.payload.command
} for plugin ${target.id}. Available commands: ${Object.keys(
target.plugin.commands || {}
).join(", ")}`
);
return;
}
const command = plugin.commands[message.payload.command];
if (typeof command.command !== "function") {
console.log(
`Command: ${message.payload.command} for plugin ${
target.id
} is malformed.`
);
return;
}
const address = server.address();
command.command(PluginApi.from(message.state, { config, cwd, address }));
return;
}
default:
console.log(`Received unknown message from client: ${message.type}`);
}
});
});
const send = getSender(wss, handler);
queues.client.subscribe(queue => {
const [message] = queue;
send({ type: message.type, payload: message.payload });
});
queues.client.subscribe(queue => {
const [message] = queue;
send({ type: message.type, payload: message.payload });
});
let configError = false;
watcher.subscribe(message => {
if (
message.type === "change" &&
message.payload.contentType === "config"
) {
(async () => {
const { config, filepath } = await loadConfig({ cwd });
const [error, valid] = validate({ target: config, name: filepath });
if (error) {
configError = true;
send({ type: "error", payload: error });
}
if (configError) {
console.log(`Resolved config error, applying ${filepath}`);
configError = false;
}
queues.client.stop();
queues.server.stop();
const [clientQueue, serverQueue] = await Promise.all([
createCompiler({ cwd, target: "web" }),
createCompiler({ cwd, target: "node" })
]);
queues.client = clientQueue;
queues.server = serverQueue;
})().catch(err => {
configError = true;
send({ type: "error", payload: err });
});
}
send(message);
});
};
};
function getSender(wss, handler) {
return message => {
if (typeof handler === "function") {
handler(message);
}
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(ARSON.stringify(message));
}
});
};
}
| JavaScript | 0.00103 | @@ -243,16 +243,23 @@
uire(%22./
+create-
compiler
@@ -265,55 +265,8 @@
r%22);
-%0Aconst %7B PluginApi %7D = require(%22./plugin-api%22);
%0A%0Aco
@@ -845,32 +845,32 @@
turn;%0A %7D%0A
+
console.
@@ -894,1640 +894,8 @@
%7D);
-%0A%0A ws.on(%22message%22, async envelope =%3E %7B%0A const message = ARSON.parse(envelope);%0A switch (message.type) %7B%0A case %22plugin%22: %7B%0A const plugins = Array.isArray(config.plugins)%0A ? await loadPlugins(config.plugins, %7B cwd, validate: true %7D)%0A : %5B%5D;%0A%0A const target = plugins.find(p =%3E p.id === message.payload.plugin);%0A%0A if (!target) %7B%0A console.log(%0A %60Received message for unknown plugin: $%7Bmessage.payload.id%7D%60%0A );%0A return;%0A %7D%0A%0A const %7B plugin %7D = target;%0A%0A if (!plugin.commands.hasOwnProperty(message.payload.command)) %7B%0A console.log(%0A %60Received unknown command: $%7B%0A message.payload.command%0A %7D for plugin $%7Btarget.id%7D. Available commands: $%7BObject.keys(%0A target.plugin.commands %7C%7C %7B%7D%0A ).join(%22, %22)%7D%60%0A );%0A return;%0A %7D%0A%0A const command = plugin.commands%5Bmessage.payload.command%5D;%0A%0A if (typeof command.command !== %22function%22) %7B%0A console.log(%0A %60Command: $%7Bmessage.payload.command%7D for plugin $%7B%0A target.id%0A %7D is malformed.%60%0A );%0A return;%0A %7D%0A%0A const address = server.address();%0A command.command(PluginApi.from(message.state, %7B config, cwd, address %7D));%0A return;%0A %7D%0A default:%0A console.log(%60Received unknown message from client: $%7Bmessage.type%7D%60);%0A %7D%0A %7D);
%0A
|
7617e6cc3068f550cf435600611470c5dcaddd8b | replace custom media query by alias | packages/cf-component-form/src/FormFieldset.js | packages/cf-component-form/src/FormFieldset.js | import React from 'react';
import PropTypes from 'prop-types';
import { createComponentStyles } from 'cf-style-container';
import { clearFix } from 'polished';
const mainStyles = ({ theme }) => ({
margin: theme.main.margin,
padding: theme.main.padding,
borderTop: theme.main.borderTop,
borderLeft: theme.main.borderLeft,
borderRight: theme.main.borderRight,
borderBottom: theme.main.borderBottom,
...clearFix()
});
const legendStyles = ({ theme, layout }) => ({
padding: theme.legend.padding,
marginBottom: theme.legend.marginBottom,
borderBottom: theme.legend.borderBottom,
'@media (min-width: 720px)': layout === 'horizontal'
? {
width: '30%',
float: 'left',
padding: '1.7em 1rem',
color: theme.colorGrayDark,
textAlign: 'right'
}
: {}
});
const contentStyles = ({ theme, layout }) => ({
padding: theme.content.padding,
border: theme.content.border,
borderTopWidth: theme.content.borderTopWidth,
background: theme.content.background,
'@media (min-width: 720px)': layout === 'horizontal'
? {
width: '70%',
float: 'left',
borderTopWidth: 0,
borderLeftWidth: 0
}
: {}
});
class FormFieldset extends React.Component {
render() {
const { legend, children, styles } = this.props;
return (
<fieldset className={styles.mainStyles}>
<legend className={styles.legendStyles}>
{legend}
</legend>
<div className={styles.contentStyles}>
{children}
</div>
</fieldset>
);
}
}
FormFieldset.propTypes = {
layout: PropTypes.oneOf(['horizontal', 'vertical']).isRequired,
styles: PropTypes.object.isRequired,
legend: PropTypes.string.isRequired,
children: PropTypes.node
};
export default createComponentStyles(
{ mainStyles, legendStyles, contentStyles },
FormFieldset
);
| JavaScript | 0.000002 | @@ -596,35 +596,14 @@
,%0A
-'@media (min-width: 720px)'
+tablet
: la
@@ -1001,35 +1001,14 @@
,%0A
-'@media (min-width: 720px)'
+tablet
: la
|
a3c6141ab7f53122d6672d1fe3c7c0674e4b86e9 | Update docs for Mibew.Views.LeaveMessageFrom.submitError | src/messenger/webim/js/source/chat/model_views/leave_message/leave_message_form.js | src/messenger/webim/js/source/chat/model_views/leave_message/leave_message_form.js | /**
* @preserve This file is part of Mibew Messenger project.
* http://mibew.org
*
* Copyright (c) 2005-2011 Mibew Messenger Community
* License: http://mibew.org/license.php
*/
(function(Mibew, Handlebars, _){
// Create shortcut for base view
var BaseView = Mibew.Views.BaseSurveyForm;
/**
* @class Represents leave message form view
*/
Mibew.Views.LeaveMessageForm = BaseView.extend(
/** @lends Mibew.Views.LeaveMessageForm.prototype */
{
/**
* Template function
* @type Function
*/
template: Handlebars.templates.leave_message_form,
/**
* Map ui events to view methods.
* The view inherits events from
* {@link Mibew.Views.BaseSurveyForm.prototype.events}.
* @type Object
*/
events: _.extend(
{},
BaseView.prototype.events,
{
'click #send-message': 'submitForm'
}
),
/**
* Shortcuts for ui elements.
* The view inherits ui elements from
* {@link Mibew.Views.BaseSurveyForm.prototype.ui}.
* @type Object
*/
ui: _.extend(
{},
BaseView.prototype.ui,
{
captcha: 'input[name="captcha"]',
captchaImg: '#captcha-img'
}
),
modelEvents: _.extend(
{},
BaseView.prototype.modelEvents,
{
'submit:error': 'showError submitError'
}
),
/**
* Update model fields and call model.submit() method.
*/
submitForm: function() {
// Update model fields
var values = {};
// Update group id
if (this.model.get('groups')) {
values.groupId = this.ui.groupSelect.val()
}
// Update name
values.name = this.ui.name.val() || '';
// Update email
values.email = this.ui.email.val() || '';
// Update message
values.message = this.ui.message.val() || '';
if (this.model.get('showCaptcha')) {
values.captcha = this.ui.captcha.val() || '';
}
// Update model fields
this.model.set(values, {validate: true});
// Submit form
this.model.submit();
},
submitError: function(model, error) {
if (error.code == model.ERROR_WRONG_CAPTCHA && model.get('showCaptcha')) {
var src = this.ui.captchaImg.attr('src');
src = src.replace(/\?d\=[0-9]+/, '');
this.ui.captchaImg.attr(
'src',
src + '?d=' + (new Date()).getTime()
);
}
}
}
);
})(Mibew, Handlebars, _); | JavaScript | 0 | @@ -2704,16 +2704,368 @@
%7D,%0A%0A
+ /**%0A * Handler function for model 'submitError' event.%0A * Update captcha img if captcha field has wrong value.%0A *%0A * @param %7BMibew.Models.LeaveMessageForm%7D model Form model%0A * @param %7BObject%7D error Error object, contains 'code' and 'message'%0A * fields%0A */%0A
|
3b0002e4c5c8e5ca785703d1883f77c8af5835d5 | simplify logic in main.js | app/templates/_main.js | app/templates/_main.js | require([<% if (useZepto) { %>
'zepto',<% } else { %>
'jquery',<% } %>
'backbone',
'<% if (includeCoffeeScript) { %>cs!<% } %>views/root',<% if (starterApp === 'Hello World') { %>
'<% if (includeCoffeeScript) { %>cs!<% } %>routers/hello-world',<% } else if (starterApp === 'Todo List') { %>
'<% if (includeCoffeeScript) { %>cs!<% } %>routers/todo-list',<% } %>
'<% if (includeCoffeeScript) { %>cs!<% } %>helpers'
], function ($, Backbone, RootView<% if (starterApp === 'Hello World') { %>, HelloWorldRouter<% } else if (starterApp === 'Todo List') { %>, TodoListRouter <% } %>) {
initialize(function(next) {
// Load any data that your app requires to boot
// and initialize all routers here, the callback
// `next` is provided in case the operations
// needed are aysynchronous
<% if (starterApp === 'Hello World') { %>new HelloWorldRouter();<% } else if (starterApp === 'Todo List') { %>new TodoListRouter();<% } %>
next();
});
function initialize(complete) {
$(function() {
Backbone.history.start({
pushState: false,
root: '/',
silent: true
});
// RootView may use link or url helpers which
// depend on Backbone history being setup
// so need to wait to loadUrl() (which will)
// actually execute the route
RootView.getInstance(document.body);
complete(function() {
Backbone.history.loadUrl();
});
});
}
});
| JavaScript | 0.000074 | @@ -591,424 +591,8 @@
) %7B%0A
-%0A initialize(function(next) %7B%0A // Load any data that your app requires to boot%0A // and initialize all routers here, the callback%0A // %60next%60 is provided in case the operations%0A // needed are aysynchronous%0A %3C%25 if (starterApp === 'Hello World') %7B %25%3Enew HelloWorldRouter();%3C%25 %7D else if (starterApp === 'Todo List') %7B %25%3Enew TodoListRouter();%3C%25 %7D %25%3E%0A%0A next();%0A %7D);%0A%0A function initialize(complete) %7B%0A
$(
@@ -600,26 +600,24 @@
unction() %7B%0A
-
Backbone
@@ -639,18 +639,16 @@
%7B%0A
-
pushStat
@@ -663,18 +663,16 @@
,%0A
-
-
root: '/
@@ -674,18 +674,16 @@
t: '/',%0A
-
si
@@ -693,18 +693,16 @@
t: true%0A
-
%7D);%0A
@@ -706,18 +706,16 @@
);%0A%0A
-
// RootV
@@ -756,18 +756,16 @@
ich%0A
-
// depen
@@ -802,18 +802,16 @@
tup%0A
-
-
// so ne
@@ -851,18 +851,16 @@
ll)%0A
-
// actua
@@ -881,18 +881,16 @@
e route%0A
-
Root
@@ -931,36 +931,231 @@
- complete(function() %7B%0A
+// Initialize your routers here%0A %3C%25 if (starterApp === 'Hello World') %7B %25%3Enew HelloWorldRouter();%3C%25 %7D else if (starterApp === 'Todo List') %7B %25%3Enew TodoListRouter();%3C%25 %7D %25%3E%0A%0A // This will trigger your routers to start%0A
@@ -1188,29 +1188,11 @@
;%0A
- %7D);%0A %7D);%0A %7D%0A%0A
%7D);%0A
+%7D);
|
1b32d3843ab26b2aac5fbe36531649d6fcdf8e63 | fix unit tests | app/test/unit/queue.js | app/test/unit/queue.js | // Run with mocha by installing dev deps: npm install --dev
// more docs on writing tests with mocha can be found here:
// http://visionmedia.github.com/mocha/
/*global describe:true, it:true */
"use strict";
var assert = require('assert')
, appium = require('../../appium')
, path = require('path')
, UUID = require('uuid-js')
, ios = require('../../ios');
describe('IOS', function() {
// we'd like to test ios.proxy; mock instruments
var inst = ios({});
inst.instruments = {};
inst.instruments.sendCommand = function(cmd, cb) {
// let's pretend we've got some latency here.
var to = Math.round(Math.random()*10);
setTimeout(function() { cb([cmd, to]); }, to);
};
describe('#proxy()', function() {
return it('should execute one command at a time keeping the seq right', function(done) {
var intercept = []
, iterations = 100
, check = function(err, result) {
intercept.push(result);
if (intercept.length >= iterations) {
for (var x=0; x < iterations; x++) {
assert.equal(intercept[x][0], x);
}
done();
}
};
for (var i=0; i < iterations; i++) {
inst.proxy(i, check);
}
});
});
});
describe('Appium', function() {
var intercept = []
, logPath = path.resolve(__dirname, "../../../appium.log")
, inst = appium({app: "/path/to/fake.app", log: logPath});
var start = function(cb) {
cb(null, {});
}
, stop = function(cb) {
cb(null);
}
, mock = function(cb) {
// mock
inst.deviceType = 'ios';
inst.devices[inst.deviceType] = {};
inst.devices[inst.deviceType].start = start;
inst.devices[inst.deviceType].stop = stop;
inst.device = inst.devices[inst.deviceType];
cb();
};
describe('#start', function() {
return it('should queue up subsequent calls and execute them sequentially', function(done) {
var doneYet = function(num) {
intercept.push(num);
if (intercept.length > 9) {
for (var i=0; i < intercept.length; i++) {
assert.equal(intercept[i], i);
}
done();
}
};
var loop = function(num) {
if (num > 9)
return;
mock(function() {
inst.start({}, function() {
var n = num;
setTimeout(function() {
inst.stop(function() { doneYet(n); });
}, Math.round(Math.random()*100));
loop(++num);
});
});
};
loop(0);
});
});
});
| JavaScript | 0.000001 | @@ -1455,16 +1455,53 @@
ath%7D);%0A%0A
+ inst.registerConfig(%7Bios: true%7D);%0A%0A
var st
|
0bd20f5fea72d622620dc50a864860d0a879bf8d | Add ;;; | js/FavoriteHandler.js | js/FavoriteHandler.js | var Storage = require('FuseJS/Storage');
var data = 'favorites';
/* ...
-----------------------------------------------------------------------------*/
var addFavorite
, deleteFavorite
, getFavorites;
/* Functions
-----------------------------------------------------------------------------*/
addFavorite = function(id) {
var favorite = getFavorites();
if (favorite[id]) {
return;
}
favorite[id] = { name: 'woop' };
Storage.writeSync(data, JSON.stringify(favorite));
}
deleteFavorite = function(id) {
var favorite = getFavorites();
if (favorite[id]) {
delete favorite[id];
Storage.writeSync(data, JSON.stringify(favorite));
}
}
getFavorites = function() {
var favorites = JSON.parse(Storage.readSync(data));
if (favorites === null) {
favorites = {};
Storage.write(data, JSON.stringify(favorites));
}
return favorites;
}
/* Exports
-----------------------------------------------------------------------------*/
module.exports = {
addFavorite: addFavorite,
deleteFavorite: deleteFavorite,
getFavorites: getFavorites
};
| JavaScript | 0.000016 | @@ -484,17 +484,18 @@
ite));%0A%7D
+;
%0A
-
%0AdeleteF
@@ -660,16 +660,17 @@
);%0A %7D%0A%7D
+;
%0A%0AgetFav
@@ -745,16 +745,17 @@
data));%0A
+%0A
if (fa
@@ -794,17 +794,16 @@
s = %7B%7D;%0A
-%0A
Stor
@@ -871,17 +871,18 @@
orites;%0A
-
%7D
+;
%0A%0A%0A/* Ex
|
31699e816c692156e1388bc9836c278d10dc5c4e | remove trailing slash for individual applications | troposphere/static/js/models/application.js | troposphere/static/js/models/application.js | define(['underscore', 'models/base', 'models/machine', 'collections/machines'],
function(_, Base, Machine, Machines) {
var Application = Base.extend({
defaults: { 'model_name': 'application' },
parse: function(response) {
var attributes = response;
attributes.id = response.uuid;
attributes.rating = Math.floor(Math.random() * 6);
attributes.favorite = response.is_bookmarked;
var machines = _.map(attributes.machines, function(attrs) {
return new Machine(Machine.prototype.parse(attrs));
});
attributes.machines = new Machines(machines);
return attributes;
},
url: function(){
var url = this.urlRoot
+ '/' + this.defaults.model_name + '/';
if (typeof this.get('id') != 'undefined') {
url += this.get('id') + '/';
}
return url;
},
computed: {
name_or_id: function() {
return this.get('name') || this.get('id');
}
}
});
_.extend(Application.defaults, Base.defaults);
return Application;
});
| JavaScript | 0 | @@ -917,22 +917,16 @@
et('id')
- + '/'
;%0A
|
e62023e879584c6a9938718d4342ef06c751cbe1 | remove unused CustomMenu | src/components/CustomMenu.js | src/components/CustomMenu.js | import React from 'react';
import ReactDOM from 'react-dom';
export class CustomToggle extends React.Component {
constructor(props, context) {
super(props, context);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
this.props.onClick(e);
}
render() {
return (
<a href="" onClick={this.handleClick}>
{this.props.children}
</a>
);
}
}
export class CustomMenu extends React.Component {
constructor(props, context) {
super(props, context);
this.handleChange = this.handleChange.bind(this);
this.state = {
value: ''
};
}
handleChange(e) {
this.setState({ value: e.target.value });
}
focusNext() {
const input = ReactDOM.findDOMNode(this.input);
if (input) {
input.focus();
}
}
render() {
const { children } = this.props;
const { value } = this.state;
return (
<div className="dropdown-menu" style={{ padding: '5px', width: '140px', 'fontSize': '11px', 'margin-right': '100px'}}>
<ul className="list-unstyled">
{React.Children.toArray(children).filter(
child => !value.trim() || child.props.children.indexOf(value) !== -1
)}
</ul>
</div>
);
}
}
| JavaScript | 0.000001 | @@ -23,42 +23,8 @@
ct';
-%0Aimport ReactDOM from 'react-dom';
%0A%0Aex
@@ -394,854 +394,4 @@
%7D%0A%7D%0A
-%0Aexport class CustomMenu extends React.Component %7B%0A constructor(props, context) %7B%0A super(props, context);%0A%0A this.handleChange = this.handleChange.bind(this);%0A%0A this.state = %7B%0A value: ''%0A %7D;%0A %7D%0A%0A handleChange(e) %7B%0A this.setState(%7B value: e.target.value %7D);%0A %7D%0A%0A focusNext() %7B%0A const input = ReactDOM.findDOMNode(this.input);%0A%0A if (input) %7B%0A input.focus();%0A %7D%0A %7D%0A%0A render() %7B%0A const %7B children %7D = this.props;%0A const %7B value %7D = this.state;%0A%0A return (%0A %3Cdiv className=%22dropdown-menu%22 style=%7B%7B padding: '5px', width: '140px', 'fontSize': '11px', 'margin-right': '100px'%7D%7D%3E%0A %3Cul className=%22list-unstyled%22%3E%0A %7BReact.Children.toArray(children).filter(%0A child =%3E !value.trim() %7C%7C child.props.children.indexOf(value) !== -1%0A )%7D%0A %3C/ul%3E%0A %3C/div%3E%0A );%0A %7D%0A%7D%0A
|
b23a52bff38b2a6c5a7f1556cd8bb36a9630d243 | Update button.min.js UIkit 2.26.2 | js/core/button.min.js | js/core/button.min.js | /*! UIkit 2.24.3 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(t){"use strict";t.component("buttonRadio",{defaults:{activeClass:"uk-active",target:".uk-button"},boot:function(){t.$html.on("click.buttonradio.uikit","[data-uk-button-radio]",function(i){var a=t.$(this);if(!a.data("buttonRadio")){var e=t.buttonRadio(a,t.Utils.options(a.attr("data-uk-button-radio"))),o=t.$(i.target);o.is(e.options.target)&&o.trigger("click")}})},init:function(){var i=this;this.find(i.options.target).attr("aria-checked","false").filter("."+i.options.activeClass).attr("aria-checked","true"),this.on("click",this.options.target,function(a){var e=t.$(this);e.is('a[href="#"]')&&a.preventDefault(),i.find(i.options.target).not(e).removeClass(i.options.activeClass).blur(),e.addClass(i.options.activeClass),i.find(i.options.target).not(e).attr("aria-checked","false"),e.attr("aria-checked","true"),i.trigger("change.uk.button",[e])})},getSelected:function(){return this.find("."+this.options.activeClass)}}),t.component("buttonCheckbox",{defaults:{activeClass:"uk-active",target:".uk-button"},boot:function(){t.$html.on("click.buttoncheckbox.uikit","[data-uk-button-checkbox]",function(i){var a=t.$(this);if(!a.data("buttonCheckbox")){var e=t.buttonCheckbox(a,t.Utils.options(a.attr("data-uk-button-checkbox"))),o=t.$(i.target);o.is(e.options.target)&&o.trigger("click")}})},init:function(){var i=this;this.find(i.options.target).attr("aria-checked","false").filter("."+i.options.activeClass).attr("aria-checked","true"),this.on("click",this.options.target,function(a){var e=t.$(this);e.is('a[href="#"]')&&a.preventDefault(),e.toggleClass(i.options.activeClass).blur(),e.attr("aria-checked",e.hasClass(i.options.activeClass)),i.trigger("change.uk.button",[e])})},getSelected:function(){return this.find("."+this.options.activeClass)}}),t.component("button",{defaults:{},boot:function(){t.$html.on("click.button.uikit","[data-uk-button]",function(){var i=t.$(this);if(!i.data("button")){{t.button(i,t.Utils.options(i.attr("data-uk-button")))}i.trigger("click")}})},init:function(){var t=this;this.element.attr("aria-pressed",this.element.hasClass("uk-active")),this.on("click",function(i){t.element.is('a[href="#"]')&&i.preventDefault(),t.toggle(),t.trigger("change.uk.button",[t.element.blur().hasClass("uk-active")])})},toggle:function(){this.element.toggleClass("uk-active"),this.element.attr("aria-pressed",this.element.hasClass("uk-active"))}})}(UIkit); | JavaScript | 0.000001 | @@ -10,11 +10,11 @@
2.2
-4.3
+6.2
%7C h
@@ -2456,8 +2456,9 @@
(UIkit);
+%0A
|
7ff2d2aea62be274ee35ea497ee7cbb35f23dc19 | Fix tab context menu item size checks (#7420) | src/components/Editor/Tab.js | src/components/Editor/Tab.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
import React, { PureComponent } from "react";
import { connect } from "react-redux";
import { showMenu, buildMenu } from "devtools-contextmenu";
import SourceIcon from "../shared/SourceIcon";
import { CloseButton } from "../shared/Button";
import type { List } from "immutable";
import type { Source } from "../../types";
import actions from "../../actions";
import {
getFileURL,
getRawSourceURL,
getTruncatedFileName,
getDisplayPath,
isPretty,
getSourceQueryString
} from "../../utils/source";
import { copyToTheClipboard } from "../../utils/clipboard";
import { getTabMenuItems } from "../../utils/tabs";
import {
getSelectedSource,
getActiveSearch,
getSourcesForTabs,
getHasSiblingOfSameName
} from "../../selectors";
import classnames from "classnames";
type SourcesList = List<Source>;
type Props = {
tabSources: SourcesList,
selectedSource: Source,
source: Source,
activeSearch: string,
selectSource: string => void,
closeTab: Source => void,
closeTabs: (List<string>) => void,
togglePrettyPrint: string => void,
showSource: string => void,
hasSiblingOfSameName: boolean
};
class Tab extends PureComponent<Props> {
onTabContextMenu = (event, tab: string) => {
event.preventDefault();
this.showContextMenu(event, tab);
};
showContextMenu(e, tab: string) {
const {
closeTab,
closeTabs,
tabSources,
showSource,
togglePrettyPrint,
selectedSource
} = this.props;
const otherTabs = tabSources.filter(t => t.id !== tab);
const sourceTab = tabSources.find(t => t.id == tab);
const tabURLs = tabSources.map(t => t.url);
const otherTabURLs = otherTabs.map(t => t.url);
if (!sourceTab) {
return;
}
const isPrettySource = isPretty(sourceTab);
const tabMenuItems = getTabMenuItems();
const items = [
{
item: {
...tabMenuItems.closeTab,
click: () => closeTab(sourceTab)
}
},
{
item: {
...tabMenuItems.closeOtherTabs,
click: () => closeTabs(otherTabURLs)
},
hidden: () => tabSources.size === 1
},
{
item: {
...tabMenuItems.closeTabsToEnd,
click: () => {
const tabIndex = tabSources.findIndex(t => t.id == tab);
closeTabs(tabURLs.filter((t, i) => i > tabIndex));
}
},
hidden: () =>
tabSources.size === 1 ||
tabSources.some((t, i) => t === tab && tabSources.size - 1 === i)
},
{
item: { ...tabMenuItems.closeAllTabs, click: () => closeTabs(tabURLs) }
},
{ item: { type: "separator" } },
{
item: {
...tabMenuItems.copyToClipboard,
disabled: selectedSource.id !== tab,
click: () => copyToTheClipboard(sourceTab.text)
}
},
{
item: {
...tabMenuItems.copySourceUri2,
disabled: !selectedSource.url,
click: () => copyToTheClipboard(getRawSourceURL(sourceTab.url))
}
},
{
item: {
...tabMenuItems.showSource,
disabled: !selectedSource.url,
click: () => showSource(tab)
}
}
];
if (!isPrettySource) {
items.push({
item: {
...tabMenuItems.prettyPrint,
click: () => togglePrettyPrint(tab)
}
});
}
showMenu(e, buildMenu(items));
}
isProjectSearchEnabled() {
return this.props.activeSearch === "project";
}
isSourceSearchEnabled() {
return this.props.activeSearch === "source";
}
render() {
const {
selectedSource,
selectSource,
closeTab,
source,
tabSources,
hasSiblingOfSameName
} = this.props;
const sourceId = source.id;
const active =
selectedSource &&
sourceId == selectedSource.id &&
(!this.isProjectSearchEnabled() && !this.isSourceSearchEnabled());
const isPrettyCode = isPretty(source);
function onClickClose(e) {
e.stopPropagation();
closeTab(source);
}
function handleTabClick(e) {
e.preventDefault();
e.stopPropagation();
return selectSource(sourceId);
}
const className = classnames("source-tab", {
active,
pretty: isPrettyCode
});
const path = getDisplayPath(source, tabSources);
const query = hasSiblingOfSameName ? getSourceQueryString(source) : "";
return (
<div
className={className}
key={sourceId}
onClick={handleTabClick}
// Accommodate middle click to close tab
onMouseUp={e => e.button === 1 && closeTab(source)}
onContextMenu={e => this.onTabContextMenu(e, sourceId)}
title={getFileURL(source, false)}
>
<SourceIcon
source={source}
shouldHide={icon => ["file", "javascript"].includes(icon)}
/>
<div className="filename">
{getTruncatedFileName(source, query)}
{path && <span>{`../${path}/..`}</span>}
</div>
<CloseButton
handleClick={onClickClose}
tooltip={L10N.getStr("sourceTabs.closeTabButtonTooltip")}
/>
</div>
);
}
}
const mapStateToProps = (state, { source }) => {
const selectedSource = getSelectedSource(state);
return {
tabSources: getSourcesForTabs(state),
selectedSource: selectedSource,
activeSearch: getActiveSearch(state),
hasSiblingOfSameName: getHasSiblingOfSameName(state, source)
};
};
export default connect(
mapStateToProps,
{
selectSource: actions.selectSource,
closeTab: actions.closeTab,
closeTabs: actions.closeTabs,
togglePrettyPrint: actions.togglePrettyPrint,
showSource: actions.showSource
}
)(Tab);
| JavaScript | 0 | @@ -1685,16 +1685,56 @@
props;%0A%0A
+ const tabCount = tabSources.length;%0A
cons
@@ -2332,16 +2332,17 @@
TabURLs)
+,
%0A
@@ -2342,33 +2342,26 @@
-%7D,%0A hidden
+ disabled
: () =%3E
@@ -2363,34 +2363,37 @@
) =%3E tab
-Sources.size === 1
+Count === 1%0A %7D
%0A %7D
@@ -2624,24 +2624,25 @@
%0A %7D
+,
%0A %7D,%0A
@@ -2642,25 +2642,18 @@
-%7D,%0A hidden
+ disabled
: ()
@@ -2666,31 +2666,26 @@
+
tab
-Sources.size
+Count
=== 1 %7C
@@ -2686,16 +2686,18 @@
== 1 %7C%7C%0A
+
@@ -2744,20 +2744,13 @@
tab
-Sources.size
+Count
- 1
@@ -2757,16 +2757,26 @@
=== i)%0A
+ %7D%0A
%7D,
|
08860698e00843ac8fa1e0c9b50eb4326cf8789e | remove obnoxious text | src/components/Home/index.js | src/components/Home/index.js | import React from 'react';
export default function Home() {
return (
<div>
<p>
HELLO
</p>
<p>
welcome.
</p>
<p>
front end developer, artist, queer, multiracial. I put some things I make here; feel
free to poke around.
</p>
<p>
all sentences and phrases here begin with lowercase letters unless it begins with a proper
noun. "I" and "I'm" are also exceptions.
</p>
<p>
I apologize for the hash appended in the url. a caveat for using github pages.
</p>
</div>
);
}
| JavaScript | 0.999994 | @@ -369,333 +369,8 @@
/p%3E%0A
- %3Cp%3E%0A all sentences and phrases here begin with lowercase letters unless it begins with a proper%0A noun. %22I%22 and %22I'm%22 are also exceptions.%0A %3C/p%3E%0A %3Cp%3E%0A I apologize for the hash appended in the url. a caveat for using github pages.%0A %3C/p%3E%0A
|
335ee9efeb290aa14f3dee3a9c8d2bea40c215eb | improve LinkButton | src/components/LinkButton.js | src/components/LinkButton.js | import React, { PropTypes } from 'react'
import _ from 'lodash'
class LinkButton extends React.Component {
constructor (props) {
super(props)
this.state = {
}
this.handleClick = (e) => {
this.context.router.push(this.props.to)
}
}
render () {
let { to, className } = this.props
const { router } = this.context
className = _.isString(className)
? className
: ''
className += router.isActive(to) ? ' active' : ''
return (
<button
onClick={this.handleClick}
{..._.omit(this.props, ['active', 'className'])}
className={className}
/>
)
}
}
LinkButton.propTypes = {
}
LinkButton.contextTypes = {
router: PropTypes.shape({
push: PropTypes.func
})
}
export default LinkButton
| JavaScript | 0 | @@ -258,16 +258,61 @@
%7D%0A %7D%0A%0A
+ focus () %7B%0A this.refs.root.focus()%0A %7D%0A%0A
render
@@ -541,16 +541,35 @@
%3Cbutton%0A
+ ref='root'%0A
@@ -607,43 +607,19 @@
-%7B..._.omit(this.props, %5B'active', '
+className=%7B
clas
@@ -627,11 +627,8 @@
Name
-'%5D)
%7D%0A
@@ -634,35 +634,93 @@
c
-lassName=%7BclassName
+hildren=%7Bthis.props.children%7D%0A onContextMenu=%7Bthis.props.onContextMenu
%7D%0A
|
b6896890ae0c1c8a95477cbefa304ab438c061fb | Disable fetching if there's nothing to fetch | js/infinite-jekyll.js | js/infinite-jekyll.js | $(function() {
var postURLs,
isFetchingPosts = false,
shouldFetchPosts = true,
postsToLoad = $(".posts").children().length,
loadNewPostsThreshold = 3000;
// Load the JSON file containing all URLs
$.getJSON('/all-posts.json', function(data) {
postURLs = data["posts"];
});
// If there's no spinner, it's not a page where posts should be fetched
if ($(".infinite-spinner").length < 1)
shouldFetchPosts = false;
// Are we close to the end of the page? If we are, load more posts
$(window).scroll(function(e){
if (!shouldFetchPosts || isFetchingPosts) return;
var windowHeight = $(window).height();
var windowScrollPosition = $(window).scrollTop();
var bottomScrollPosition = windowHeight + windowScrollPosition;
var documentHeight = $(document).height();
// If we've scrolled past the loadNewPostsThreshold, fetch posts
if ((documentHeight - loadNewPostsThreshold) < bottomScrollPosition) {
fetchPosts();
}
});
// Fetch a chunk of posts
function fetchPosts() {
// Exit if postURLs haven't been loaded
if (!postURLs) return;
isFetchingPosts = true;
// Load as many posts as there were present on the page when it loaded
// After successfully loading a post, load the next one
var loadedPosts = 0,
postCount = $(".posts").children().length,
callback = function() {
loadedPosts++;
var postIndex = postCount + loadedPosts;
if (postIndex > postURLs.length-1) {
disableFetching();
return;
}
if (loadedPosts < postsToLoad) {
fetchPostWithIndex(postIndex, callback);
} else {
isFetchingPosts = false;
}
};
fetchPostWithIndex(postCount + loadedPosts, callback);
}
function fetchPostWithIndex(index, callback) {
var postURL = postURLs[index];
$.get(postURL, function(data) {
$(data).find(".post").appendTo(".blog-posts");
callback();
});
}
function disableFetching() {
shouldFetchPosts = false;
isFetchingPosts = false;
$(".infinite-spinner").fadeOut();
}
});
| JavaScript | 0.000007 | @@ -301,16 +301,181 @@
osts%22%5D;%0A
+ %0A // If there aren't any more posts available to load than already visible, disable fetching%0A if (postURLs.length %3C= postsToLoad)%0A disableFetching();%0A
%7D);%0A%09%0A
|
b2c52e3ecc069bcaa9a92f6f9b86c7e712012b90 | Create example 2 with state and Starting Value in input | src/components/search_bar.js | src/components/search_bar.js | import React, { Component } from 'react';
class SearchBar extends Component{
constructor(props){
super(props);
this.state = { term : ''}; //оголошує обєкт
console.log(this.state);
}
render(){
//this.setState({term: event.target.value})
//те ж саме що, але так не правильно this.state.term = event.target.value
return (
<div>
<input onChange = { event => this.setState({term: event.target.value})} />;
//змінює значення обєкта і присвоює йому значення інпута
value of input : {this.state.term}
// виводить на екран обєкт стейт
</div>
);
}
}
export default SearchBar; | JavaScript | 0 | @@ -151,16 +151,30 @@
term : '
+Starting Value
'%7D; //%D0%BE%D0%B3
@@ -186,16 +186,16 @@
%D1%94 %D0%BE%D0%B1%D1%94%D0%BA%D1%82%0A
-
@@ -418,173 +418,50 @@
div%3E
-%0A %3Cinput onChange = %7B event =%3E
+%7B
this.s
-etS
tate
-(%7B
+.
term
-: event.target.value%7D)%7D /%3E;%0A //%D0%B7%D0%BC%D1%96%D0%BD%D1%8E%D1%94 %D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%BD%D1%8F %D0%BE%D0%B1%D1%94%D0%BA%D1%82%D0%B0 %D1%96 %D0%BF%D1%80%D0%B8%D1%81%D0%B2%D0%BE%D1%8E%D1%94 %D0%B9%D0%BE%D0%BC%D1%83 %D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%BD%D1%8F %D1%96%D0%BD%D0%BF%D1%83%D1%82%D0%B0
+%7D%0A %3Cinput
%0A
@@ -482,20 +482,9 @@
alue
- of input :
+=
%7Bthi
@@ -488,32 +488,33 @@
this.state.term%7D
+
%0A
@@ -518,40 +518,75 @@
-// %D0%B2%D0%B8%D0%B2%D0%BE%D0%B4%D0%B8%D1%82%D1%8C %D0%BD%D0%B0 %D0%B5%D0%BA%D1%80%D0%B0%D0%BD %D0%BE%D0%B1%D1%94%D0%BA%D1%82 %D1%81%D1%82%D0%B5%D0%B9%D1%82
+onChange = %7B event =%3E this.setState(%7Bterm: event.target.value%7D)%7D /%3E
%0A
|
a41fc842e4e25cd4bfc02bb1c51b36cc0f33e7e2 | Fix handlebars adapter asset references | vendor/assets/javascripts/backbone.js | vendor/assets/javascripts/backbone.js | //= require jquery
//= require handlebars.runtime
//= require underscore/underscore
//= require backbone/backbone
//= require backbone/backbone.handlebars.adapter
//= require marionette/backbone.babysitter
//= require marionette/backbone.radio
//= require marionette/backbone.marionette
//= require marionette/backbone.radio.adapter
//= require_self
| JavaScript | 0 | @@ -111,57 +111,8 @@
one%0A
-//= require backbone/backbone.handlebars.adapter%0A
//=
@@ -273,24 +273,75 @@
dio.adapter%0A
+//= require marionette/backbone.handlebars.adapter%0A
//= require_
|
71f4bd4966412d07b7377b1021efb9d60096f406 | Replace function expression | lib/node_modules/@stdlib/math/base/random/box-muller/lib/_randn.js | lib/node_modules/@stdlib/math/base/random/box-muller/lib/_randn.js | 'use strict';
// MODULES //
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var ln = require( '@stdlib/math/base/special/ln' );
var sin = require( '@stdlib/math/base/special/sin' );
var cos = require( '@stdlib/math/base/special/cos' );
var TWO_PI = require( '@stdlib/math/constants/float64-two-pi' );
// MAIN //
/**
* Returns a function for generating standard normally distributed pseudorandom numbers using the Box-Muller algorithm.
*
* @private
* @param {Function} rand - PRNG which returns standard uniformly distributed numbers
* @returns {Function} PRNG
*/
function randn( rand ) {
var flg;
var r;
// Flag indicating whether to generate new normal random variates or return a cached normal random variate:
flg = true;
/**
* Generates a standard normally distributed pseudorandom number.
*
* @private
* @returns {number} pseudorandom number
*
* @example
* var r = randn();
* // returns <number>
*/
return function randn() {
var u1;
var u2;
var a;
var b;
if ( flg ) {
// Note: if `u1` is `0`, the natural log blows up, so we keep trying until we get a non-zero rand. Rarely should we need more than one iteration.
do {
u1 = rand();
u2 = rand();
} while (
u1 === 0.0
);
a = sqrt( -2.0 * ln(u1) );
b = TWO_PI * u2;
r = a * cos( b ); // cache for next call
flg = false;
return a * sin( b );
}
flg = true;
return r;
}; // end FUNCTION randn()
} // end FUNCTION randn()
// EXPORTS //
module.exports = randn;
| JavaScript | 0.998318 | @@ -578,21 +578,20 @@
unction
+w
ra
-ndn
+p
( rand )
@@ -735,16 +735,32 @@
true;%0A%0A
+%09return randn;%0A%0A
%09/**%0A%09*
@@ -941,23 +941,16 @@
r%3E%0A%09*/%0A%09
-return
function
@@ -1404,17 +1404,16 @@
rn r;%0A%09%7D
-;
// end
@@ -1447,21 +1447,20 @@
UNCTION
+w
ra
-ndn
+p
()%0A%0A%0A//
@@ -1488,15 +1488,14 @@
ports =
+w
ra
-ndn
+p
;%0A
|
ee2a53f185f82ab3a5c660022a9ece3df9bfe5b9 | remove test highlight conditions in browser settings (#369) | src/sites/iva/conf/opencga-variant-browser.settings.js | src/sites/iva/conf/opencga-variant-browser.settings.js | const OPENCGA_VARIANT_BROWSER_SETTINGS = {
menu: {
// merge criterium: internal sections and filters are used to hydrates the external filters list for each section (which is a list of string). Sections and filter order is respected.
sections: [
{
title: "Study and Cohorts",
filters: ["study", "cohort"]
},
{
title: "Genomic",
collapsed: true,
filters: ["region", "feature", "biotype", "type"]
},
{
title: "Consequence Type",
collapsed: true,
filters: ["consequence-type"]
},
{
title: "Population Frequency",
collapsed: true,
filters: ["populationFrequency"]
},
{
title: "Clinical",
collapsed: true,
filters: ["diseasePanels", "clinical-annotation", "fullTextSearch"]
},
{
title: "Phenotype",
collapsed: true,
filters: ["go", "hpo"]
},
{
title: "Deleteriousness",
collapsed: true,
filters: ["proteinSubstitutionScore", "cadd"]
},
{
title: "Conservation",
collapsed: true,
filters: ["conservation"]
}
],
// merge criterium: full outer join like. it adds objects presents in internal array only and in external array only. In case of objects with same id, the external values overwrite the internal.
examples: [
{
id: "Intellectual disability2",
active: false,
query: {
disorder: "Intellectual disability"
}
}
]
},
table: {
// merge criterium: spread operator
toolbar: {
showColumns: true,
showExport: true,
showDownload: false
// columns list for the dropdown will be added in grid components based on settings.table.columns
},
highlights: [
{
id: "highlight1",
name: "Test highlight 1",
description: "",
// condition: (variant, index) => index % 2 === 1,
condition: () => true,
style: {
rowBackgroundColor: "#cfe2ff",
rowOpacity: 0.5,
icon: "circle",
iconColor: "blue",
},
},
{
id: "highlight2",
name: "Test highlight 2",
description: "",
condition: (variant, index) => index % 2 === 0,
style: {
rowBackgroundColor: "#f8d7da",
icon: "exclamation",
iconColor: "red",
},
},
],
activeHighlights: ["highlight2"],
// merge criterium: uses this array as filter for internal 1D/2D array. It handles row/col span.
// It is supported either columns[] or hiddenColumns[].
columns: ["id", "gene", "type", "consequenceType", "deleteriousness", "conservation", "samples", "cohorts", "popfreq", "clinicalInfo"]
// hiddenColumns: ["id", "gene", "type"]
},
// merge criterium: uses this array as filter for internal 1D array.
// It is supported either details[] or hiddenDetails[].
details: ["annotationSummary", "annotationConsType", "annotationPropFreq", "annotationClinical", "cohortStats", "samples", "beacon", "json-view"]
// hiddenDetails: ["json-view"]
};
| JavaScript | 0 | @@ -2228,16 +2228,71 @@
%0A
+ // Highlight conditions for Variant Browser%0A //
highlig
@@ -2297,32 +2297,35 @@
ights: %5B%0A
+ //
%7B%0A
@@ -2314,32 +2314,35 @@
// %7B%0A
+ //
id: %22hi
@@ -2351,32 +2351,35 @@
light1%22,%0A
+ //
name: %22
@@ -2396,32 +2396,35 @@
ight 1%22,%0A
+ //
descrip
@@ -2445,74 +2445,10 @@
- // condition: (variant, index) =%3E index %25 2 === 1,%0A
+//
@@ -2479,32 +2479,34 @@
ue,%0A
+//
style: %7B%0A
@@ -2485,32 +2485,33 @@
//
+
style: %7B%0A
@@ -2502,32 +2502,35 @@
style: %7B%0A
+ //
row
@@ -2556,32 +2556,35 @@
cfe2ff%22,%0A
+ //
row
@@ -2597,32 +2597,34 @@
y: 0.5,%0A
+//
icon
@@ -2615,24 +2615,25 @@
+
icon: %22circl
@@ -2635,32 +2635,35 @@
circle%22,%0A
+ //
ico
@@ -2682,38 +2682,26 @@
e%22,%0A
- %7D,%0A
+//
%7D,%0A
@@ -2712,353 +2712,10 @@
-
-%7B%0A id: %22highlight2%22,%0A name: %22Test highlight 2%22,%0A description: %22%22,%0A condition: (variant, index) =%3E index %25 2 === 0,%0A style: %7B%0A rowBackgroundColor: %22#f8d7da%22,%0A icon: %22exclamation%22,%0A iconColor: %22red%22,%0A
+//
@@ -2718,37 +2718,36 @@
%7D,%0A
- %7D
+// %5D
,%0A %5D,%0A
@@ -2740,26 +2740,18 @@
-%5D,%0A
+//
activeH
@@ -2772,17 +2772,17 @@
ighlight
-2
+1
%22%5D,%0A
|
82d96273990ed36d8d50aec456bf1e12122e4b16 | Use string utility | lib/node_modules/@stdlib/string/starts-with/benchmark/benchmark.js | lib/node_modules/@stdlib/string/starts-with/benchmark/benchmark.js | 'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var pkg = require( './../package.json' ).name;
var startsWith = require( './../lib' );
// MAIN //
bench( pkg, function benchmark( b ) {
var bool;
var str;
var i;
str = 'To be, or not to be, that is the question.';
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
bool = startsWith( str, String.fromCharCode( i%126 ) );
if ( !isBoolean( bool ) ) {
b.fail( 'should return a boolean' );
}
}
b.toc();
if ( !isBoolean( bool ) ) {
b.fail( 'should return a boolean' );
}
b.pass( 'benchmark finished' );
b.end();
});
bench( pkg+'::search', function benchmark( b ) {
var bool;
var str;
var i;
str = 'To be, or not to be, that is the question.';
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
bool = startsWith( str, 'to be', i%42 );
if ( !isBoolean( bool ) ) {
b.fail( 'should return a boolean' );
}
}
b.toc();
if ( !isBoolean( bool ) ) {
b.fail( 'should return a boolean' );
}
b.pass( 'benchmark finished' );
b.end();
});
| JavaScript | 0.000028 | @@ -131,16 +131,81 @@
mitive;%0A
+var fromCodePoint = require( '@stdlib/string/from-code-point' );%0A
var pkg
@@ -499,27 +499,21 @@
tr,
-String.fromCharCode
+fromCodePoint
( i%25
|
cfb10f162dd3b6cf9a5ad33502f78070220bdf34 | add htdocsDir setting | node_modules/bh/lib/context.js | node_modules/bh/lib/context.js | function Context() {
return this;
}
Context.prototype.handle = function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}
module.exports = Context;
// vim:set ts=8 sts=4 sw=4 tw=0 et:
| JavaScript | 0 | @@ -11,24 +11,58 @@
ontext() %7B%0D%0A
+ this.htdocsDir = './htdocs';%0D%0A
return t
|
64078024cb2b9e4e6bb513477ed6072b0192f4ca | Add unit test to snapshot index route | api/tests/unit/application/snapshots/index_test.js | api/tests/unit/application/snapshots/index_test.js | JavaScript | 0.000001 | @@ -0,0 +1,917 @@
+const %7B describe, it, before, after, beforeEach, expect, sinon %7D = require('../../../test-helper');%0Aconst Hapi = require('hapi');%0A%0Aconst snapshotController = require('../../../../lib/application/snapshots/snapshot-controller');%0A%0Adescribe('Unit %7C Router %7C snapshot-router', () =%3E %7B%0A%0A let server;%0A%0A beforeEach(() =%3E %7B%0A server = new Hapi.Server();%0A server.connection(%7B port: null %7D);%0A server.register(%7B register: require('../../../../lib/application/snapshots') %7D);%0A %7D);%0A%0A describe('POST /api/snapshots', _ =%3E %7B%0A%0A before(() =%3E %7B%0A sinon.stub(snapshotController, 'create').callsFake((request, reply) =%3E reply('ok'));%0A %7D);%0A%0A after(() =%3E %7B%0A snapshotController.create.restore();%0A %7D);%0A%0A it('should exist', (done) =%3E %7B%0A return server.inject(%7B method: 'POST', url: '/api/snapshots' %7D, res =%3E %7B%0A expect(res.statusCode).to.equal(200);%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%0A%7D);%0A
| |
54bf96eda2c949af2f6e1b6d37f250091745185b | fix adding of days | app/controllers/delayed_musters/delayed_musters.js | app/controllers/delayed_musters/delayed_musters.js | 'use strict';
const Queries = require('../../helpers/queries');
exports.show = {
description: 'Delayed musters tables',
auth: {
mode: 'optional'
},
plugins: {
'hapi-auth-cookie': {
redirectTo: false // '/login' if set redirects to ./login.
}
},
handler: function (request, reply) {
const pachayat_code = request.query.pc
var sequelize = request.server.plugins.sequelize.db.sequelize;
var queryString = Queries.panchayat_delayed_musters(pachayat_code);
console.log(queryString)
sequelize
.query(queryString, {
type: sequelize.QueryTypes.SELECT
})
.then(function (rows) {
if (rows.length == 0) {
return reply.view('delayed_musters/delayed_musters', {error: 'No delayed musters found'});
}
const today = new Date()
const tomorrow = new Date()
tomorrow.setDate(today.getDate() + 1)
const delayed_muster_rows = rows.map(function (d) {
const end_date = new Date(d.end_date)
const date_t8 = new Date()
date_t8.setDate(end_date.getDate() + 8)
let days_delayed = -1
let delay_step = ''
switch (d.step) {
case "ds_t2":
delay_step = 'T + 2'
const date_t2 = new Date()
date_t2.setDate(end_date.getDate() + 2)
days_delayed = datediff(date_t2, today)
break;
case "ds_t5":
delay_step = 'T + 5'
const date_t5 = new Date()
date_t5.setDate(end_date.getDate() + 5)
days_delayed = datediff(date_t5, today)
break;
case "ds_t6":
delay_step = 'T + 6'
const date_t6 = new Date()
date_t6.setDate(end_date.getDate() + 6)
days_delayed = datediff(date_t6, today)
break;
case "ds_t7":
delay_step = 'T + 7'
const date_t7 = new Date()
date_t7.setDate(end_date.getDate() + 7)
days_delayed = datediff(date_t7, today)
break;
case "ds_t8":
delay_step = 'T + 8'
days_delayed = datediff(date_t8, today)
break;
}
return {
msr_no: d.msr_no,
work_name: d.work_name,
work_code: d.work_code,
end_date: d.end_date,
delay_step: delay_step,
days_delayed: days_delayed,
date_t8: date_t8
};
})
const actionable_musters = delayed_muster_rows.filter(function (a) {
const days_since_t8 = datediff(a.date_t8, today)
return days_since_t8 < 1
}).sort(function (a, b) {
if (a.days_delayed > b.days_delayed) return -1
if (a.days_delayed < b.days_delayed) return 1
return 0
}).map(function (d, i) {
return {
"S. No.": i + 1,
"Work code": d.work_code,
"Muster Roll no.": d.msr_no,
"Delay step": d.delay_step,
"No. of days delayed at step": d.days_delayed,
"End date": d.end_date.toISOString().slice(0, 10),
"T + 8 day": d.date_t8.toISOString().slice(0, 10)
};
})
const other_musters = delayed_muster_rows.filter(function (a) {
const days_since_t8 = datediff(a.date_t8, today)
return days_since_t8 >= 1
}).sort(function (a, b) {
if (a.days_delayed > b.days_delayed) return -1
if (a.days_delayed < b.days_delayed) return 1
return 0
}).map(function (d, i) {
return {
"S. No.": i + 1,
"Work code": d.work_code,
"Muster Roll no.": d.msr_no,
"Delay step": d.delay_step,
"No. of days delayed at step": d.days_delayed,
"End date": d.end_date.toISOString().slice(0, 10),
"T + 8 day": d.date_t8.toISOString().slice(0, 10)
};
})
return reply.view('delayed_musters/delayed_musters', {
actionable_musters: actionable_musters,
other_musters: other_musters,
panchayat_name: rows[0].panchayat_name
});
});
}
};
function datediff(first, second) {
return Math.round((second - first) / (1000 * 60 * 60 * 24));
}
| JavaScript | 0.000766 | @@ -936,107 +936,8 @@
()%0A%0A
- const tomorrow = new Date()%0A tomorrow.setDate(today.getDate() + 1)%0A%0A
@@ -1100,75 +1100,25 @@
8 =
-new Date()%0A date_t8.setDate(end_date.getDate() +
+addDays(end_date,
8)%0A
@@ -1374,83 +1374,25 @@
2 =
-new Date()%0A date_t2.setDate(end_date.getDate() +
+addDays(end_date,
2)%0A
@@ -1629,83 +1629,25 @@
5 =
-new Date()%0A date_t5.setDate(end_date.getDate() +
+addDays(end_date,
5)%0A
@@ -1884,83 +1884,25 @@
6 =
-new Date()%0A date_t6.setDate(end_date.getDate() +
+addDays(end_date,
6)%0A
@@ -2139,83 +2139,25 @@
7 =
-new Date()%0A date_t7.setDate(end_date.getDate() +
+addDays(end_date,
7)%0A
@@ -5017,16 +5017,147 @@
%7D%0A%7D;%0A%0A
+function addDays(date, days) %7B%0A var result = new Date(date);%0A result.setDate(result.getDate() + days);%0A return result;%0A%7D%0A%0A
function
|
2ee6a6a22b18568cb437cb48d106115dbaac644d | use id on the tag if there | app/frontend/app/controllers/modals/program-nfc.js | app/frontend/app/controllers/modals/program-nfc.js | import modal from '../../utils/modal';
import { later as runLater } from '@ember/runloop';
import capabilities from '../../utils/capabilities';
import CoughDrop from '../../app';
export default modal.ModalController.extend({
opening: function() {
// check if NFC is available
// if so, check if it's programmable
// if so, ask if they want to save data to the NFC tag if possible
// text box for the label/vocalization, otherwise button render
// program button at the bottom that starts listening
var button = this.get('model.button');
var tag = this.store.createRecord('tag');
var _this = this;
_this.set('status', {loading: true});
_this.set('label', null);
_this.set('button', null);
_this.set('update_tag_id', null);
capabilities.nfc.available().then(function(res) {
if(res.can_write) {
_this.set('can_write', true);
_this.set('write_tag', true);
_this.set('public', false);
}
if(button) {
var btn = button.raw();
btn.image_url = button.get('image_url');
tag.set('button', btn);
_this.set('label', btn.vocalization || btn.label);
} else {
_this.set('label', _this.get('model.label') || "");
}
if(_this.get('model.listen')) {
_this.send('program');
}
tag.save().then(function() {
if(!_this.get('model.listen')) {
_this.set('status', null);
}
_this.set('tag', tag);
}, function() {
_this.set('status', {error: true});
});
}, function() {
_this.set('status', {no_nfc: true});
});
},
not_programmable: function() {
return !!(this.get('status.loading') || this.get('status.error') || this.get('status.no_nfc') || this.get('status.saving') || this.get('status.programming')) || this.get('status.saved');
}.property('status.loading', 'status.error', 'status.no_nfc', 'status.saving', 'status.programming', 'status.saved'),
save_tag: function(tag_id) {
var _this = this;
var tag_object = _this.get('tag');
tag_object.set('tag_id', tag_id);
tag_object.set('public', !!_this.get('public'));
_this.set('status', {saving: true});
tag_object.save().then(function() {
_this.set('status', {saved: true});
runLater(function() {
modal.close();
}, 3000);
}, function() {
_this.set('status', {error_saving: true});
});
},
listening_without_tag_id: function() {
return this.get('model.listen') && !this.get('update_tag_id');
}.property('model.listen', 'update_tag_id'),
actions: {
save: function() {
var _this = this;
if(_this.get('label')) {
_this.set('tag.label', _this.get('label'));
_this.save_tag(_this.get('update_tag_id'));
}
},
program: function() {
var _this = this;
_this.set('status', {programming: true});
var tag_object = _this.get('tag');
capabilities.nfc.prompt().then(function() {
var close_tag = function() {
capabilities.nfc.stop_listening('programming');
capabilities.nfc.end_prompt();
};
var handled = false;
capabilities.nfc.listen('programming', function(tag) {
if(handled) { return; }
handled = true;
if(!_this.get('label') && _this.get('model.listen')) {
CoughDrop.store.findRecord('tag', JSON.stringify(tag.id)).then(function(tag_object) {
if(tag_object.get('label') || tag_object.get('button')) {
// save tag to user and close
var tag_ids = [].concact(_this.get('model.user.preferences.tag_ids') || []);
tag_ids.push(tag_object.get('id'));
_this.set('model.user.preferences.tag_ids', tag_ids);
_this.get('model.user').save();
_this.set('status', {saved: true});
} else {
_this.set('tag', tag_object);
_this.set('update_tag_id', JSON.stringify(tag.id));
_this.set('status', null);
}
}, function() {
_this.set('update_tag_id', JSON.stringify(tag.id));
_this.set('status', null);
// prompt for label and save
});
close_tag();
// ajax lookup
} else {
var finish_tag = function() {
_this.save_tag(JSON.stringify(tag.id));
close_tag();
};
if(tag.writeable && _this.get('write_tag') && (_this.get('label') || _this.get('button'))) {
var opts = {
uri: "cough://tag/" + tag_object.get('id')
};
if(tag.size) {
// Program in the label as well if there's room
if(opts.uri.length + (_this.get('label') || '').length < tag.size * 0.85) {
opts.text = _this.get('label');
}
}
capabilities.nfc.write(opts).then(function() {
finish_tag();
}, function() {
_this.set('status', {error_writing: true});
});
} else {
finish_tag();
}
}
});
runLater(function() {
if(handled) { return; }
handled = true;
capabilities.nfc.stop_listening('programming');
capabilities.nfc.end_prompt();
_this.set('status', {read_timeout: true});
}, 10000);
});
}
}
});
| JavaScript | 0.000001 | @@ -3332,32 +3332,261 @@
del.listen')) %7B%0A
+ var tag_id = JSON.stringify(tag.id);%0A if(tag.uri) %7B%0A var tag_uri_id = (tag.uri.match(/%5Ecough:%5C/%5C/tag%5C/(%5B%5E%5C/%5D+)$/) %7C%7C %5B%5D)%5B1%5D;%0A if(tag_uri_id) %7B tag_id = tag_uri_id; %7D%0A %7D%0A
Coug
@@ -3615,39 +3615,23 @@
('tag',
-JSON.stringify(
tag
-.
+_
id)
-)
.then(fu
@@ -4196,39 +4196,23 @@
ag_id',
-JSON.stringify(
tag
-.
+_
id)
-)
;%0A
@@ -4333,39 +4333,23 @@
ag_id',
-JSON.stringify(
tag
-.
+_
id)
-)
;%0A
|
1a9abe535d12e8d975e0b2548aa2978c1f76ec90 | delete unused property | src/directives/directives.js | src/directives/directives.js | /**
* @file rewrite指令
* @author zdying
*/
var fs = require('fs');
var path = require('path');
var setHeader = require('./setHeader');
module.exports = {
// proxy request config
'proxy_set_header': function (key, value) {
log.debug('proxy_set_header -', key, value);
var headers = this.request.headers;
var oldValue = headers[key];
if (Array.isArray(oldValue)) {
oldValue.push(value);
} else {
headers[key] = value;
}
},
'proxy_hide_header': function (key, value) {
log.debug('proxy_hide_header -', key, value);
delete this.request.headers[key.toLowerCase()];
},
'proxy_set_cookie': function (key, value) {
log.debug('proxy_set_cookie -', key, value);
var str = key + '=' + value;
var headers = this.request.headers;
var cookie = headers.cookie || '';
headers.cookie = cookie + '; ' + str;
},
'proxy_hide_cookie': function (key) {
log.debug('proxy_hide_cookie -', key);
var headers = this.request.headers;
var cookie = headers.cookie || '';
headers.cookie = cookie.replace(new RegExp('(;.*)?' + key + ' *= *([^;]*) *'), '');
},
'proxy_method': function (key) {
log.debug('proxy_method -', key);
this.request.method = key.toUpperCase();
},
'proxy_set_body': function (body) {
log.debug('proxy_set_body -', body);
this.request.body = body;
},
'proxy_replace_body': function (oldValue, newValue) {
log.debug('proxy_replace_body -', oldValue, newValue);
var body = this.request.body || '';
// TODO 正则表达式
this.request.body = body.replace(oldValue, newValue);
},
'proxy_append_body': function (body) {
log.debug('proxy_append_body -', body);
var _body = this.request.body || '';
this.request.body = _body + body;
},
// response config
'hide_cookie': function (key) {
log.debug('hide_cookie -', key);
setHeader(this.response, 'Set-Cookie', key + '=; Expires=' + new Date(1).toGMTString());
},
'hide_header': function (key, value) {
log.debug('hide_header -', key, value);
delete this.response.headers[key.toLowerCase()];
this.response.removeHeader(key);
},
'set_header': function (key, value) {
log.debug('set_header -', key, value);
setHeader(this.response, key, value);
},
'set_cookie': function (key, value) {
log.debug('set_cookie -', key, value);
setHeader(this.response, 'Set-Cookie', key + '=' + value);
},
'echo': function () {
this.response.write([].join.call(arguments, ' '));
},
'send_file': function (value) {
var filePath = '';
var self = this;
if (path.isAbsolute(value)) {
// absolute path
filePath = value;
} else {
// relative path
var currentFilePath = this.rewriteRule.extends.filePath;
var dirname = path.dirname(currentFilePath);
filePath = path.join(dirname, value);
}
return new Promise(function (resolve, reject) {
fs.readFile(filePath, 'utf-8', function (err, data) {
if (err) {
data = 'File send error: <br/>' + err.stack;
self.response.writeHead(err.code === 'ENOENT' ? 404 : 500, {
'Content-Type': 'text/html'
});
}
self.response.end(data);
resolve(data);
});
});
},
/**
* Set the response status code and status message.
*
* @param {Number} code The status code.
* @param {String} [message] A optional human-readable status message.
*/
'status': function (code, message) {
this.response.customStatus = true;
this.response.statusCode = code;
this.response.statusMessage = message;
},
// location commands
'proxy_pass': function (value) {
this.variables['proxy_pass'] = value;
},
'alias': function (value) {
this.variables.alias = true;
if (path.isAbsolute(value)) {
// absolute path
this.variables.proxy_pass = value;
} else {
// relative path
var currentFilePath = this.extends.filePath;
var dirname = path.dirname(currentFilePath);
this.variables.proxy_pass = path.join(dirname, value);
}
},
'root': function (value) {
this.variables.default = value;
},
// domain commands
'ssl_certificate': function (value) {
var filePath = '';
if (path.isAbsolute(value)) {
// absolute path
filePath = value;
} else {
// relative path
var rewriteFilePath = this.extends.filePath;
var dirname = path.dirname(rewriteFilePath);
filePath = path.join(dirname, value);
}
this.variables.ssl_certificate = filePath;
},
'ssl_certificate_key': function (value) {
var filePath = '';
if (path.isAbsolute(value)) {
// absolute path
filePath = value;
} else {
// relative path
var rewriteFilePath = this.extends.filePath;
var dirname = path.dirname(rewriteFilePath);
filePath = path.join(dirname, value);
}
this.variables.ssl_certificate_key = filePath;
}
};
| JavaScript | 0.000001 | @@ -3512,47 +3512,8 @@
) %7B%0A
- this.response.customStatus = true;%0A
|
f01212d6928a75817d07a5e930643cc6eec03d89 | Fix user notification settings fetch | app/routes/users/UserSettingsNotificationsRoute.js | app/routes/users/UserSettingsNotificationsRoute.js | // @flow
import { compose } from 'redux';
import { connect } from 'react-redux';
import { dispatched } from '@webkom/react-prepare';
import UserSettingsNotifications from './components/UserSettingsNotifications';
import {
fetchNotificationAlternatives,
fetchNotificationSettings,
updateNotificationSetting
} from 'app/actions/NotificationSettingsActions';
import {
selectNotificationSettingsAlternatives,
selectNotificationSettings
} from 'app/reducers/notificationSettings';
const loadData = (props, dispatch) => {
return Promise.all([
dispatch(fetchNotificationAlternatives()),
dispatch(fetchNotificationSettings())
]);
};
const mapStateToProps = state => {
return {
alternatives: selectNotificationSettingsAlternatives(state),
settings: selectNotificationSettings(state)
};
};
const mapDispatchToProps = { updateNotificationSetting };
export default compose(
dispatched(loadData),
connect(mapStateToProps, mapDispatchToProps)
)(UserSettingsNotifications);
| JavaScript | 0.000001 | @@ -916,16 +916,60 @@
loadData
+, %7B%0A componentWillReceiveProps: false%0A %7D
),%0A con
|
5fdfc80f24d31de16f075c1048e729062e99d017 | Use foam.LIB and be a bit lazier. | src/foam/core/AxiomCloner.js | src/foam/core/AxiomCloner.js | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.core',
name: 'AxiomCloner',
documentation: 'An axiom that clones an axiom from another model.',
properties: [
{
class: 'Class',
name: 'from'
},
{
class: 'String',
name: 'axiom'
},
{
class: 'String',
name: 'name',
transient: true,
expression: function(axiom) {
return axiom + '_cloner';
}
},
{
class: 'Map',
name: 'config'
}
],
methods: [
function installInClass(cls) {
var axiom = this.from.getAxiomByName(this.axiom);
if ( ! axiom ) {
throw `Cannot find ${this.axiom} on ${this.from.id}`;
}
axiom = axiom.clone().copyFrom(this.config);
cls.installAxiom(axiom);
}
]
});
foam.SCRIPT({
package: 'foam.core',
name: 'AxiomClonerConvenienceMethod',
code: function() {
foam.axiomCloner = function(from, axiom, config) {
return foam.core.AxiomCloner.create({
from: from,
axiom: axiom,
config: config
});
};
}
});
| JavaScript | 0 | @@ -891,133 +891,67 @@
oam.
-SCRIPT(%7B%0A package: 'foam.core',%0A name: 'AxiomClonerConvenienceMethod',%0A code: function() %7B%0A foam.axiomCloner = function
+LIB(%7B%0A name: 'foam',%0A methods: %5B%0A function axiomCloner
(fro
@@ -983,16 +983,34 @@
return
+%7B%0A class: '
foam.cor
@@ -1026,17 +1026,10 @@
oner
-.create(%7B
+',
%0A
@@ -1101,22 +1101,19 @@
%7D
-)
;%0A %7D
-;
%0A
-%7D
+%5D
%0A%7D);
-%0A
|
27668cd573cb675d1627056ac3ab61685407874e | Set tableColumns for Group. | src/foam/nanos/auth/Group.js | src/foam/nanos/auth/Group.js | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.auth',
name: 'Group',
implements: [
'foam.nanos.auth.EnabledAware'
],
documentation: 'A Group of Users.',
properties: [
{
class: 'String',
name: 'id',
documentation: 'Unique name of the Group.'
},
{
class: 'String',
name: 'description',
documentation: 'Description of the Group.'
},
{
class: 'String',
name: 'parent',
documentation: 'Parent group to inherit permissions from.'
},
{
class: 'FObjectArray',
of: 'foam.nanos.auth.Permission',
name: 'permissions'
}
/*
FUTURE
{
class: 'FObjectProperty',
of: 'AuthConfig',
documentation: 'Custom authentication settings for this group.'
}
*/
],
methods: [
{
name: 'implies',
javaReturns: 'Boolean',
args: [
{
name: 'permission',
javaType: 'java.security.Permission'
}
],
javaCode:
`if ( getPermissions() == null ) return false;
for ( int i = 0 ; i < permissions_.length ; i++ ) {
if ( new javax.security.auth.AuthPermission(permissions_[i].getId()).implies(permission) ) {
return true;
}
}
return false;`
}
]
});
| JavaScript | 0 | @@ -274,16 +274,58 @@
ers.',%0A%0A
+ tableColumns: %5B 'id', 'description' %5D,%0A%0A
proper
@@ -948,18 +948,16 @@
*/%0A %5D,%0A
-
%0A metho
|
6403f7e508a73ee7c2ca9ba5cb080db63ec17986 | Use getUser() helper | src/game-logic/utils/disk.js | src/game-logic/utils/disk.js | import TrackedData from './tracked-data';
export default class Disk extends TrackedData {
constructor(position = 0) {
super({
position: position,
user: '',
lastUser: '',
targetSpeed: 0,
// Used for auto-moveTo (shuffle, lock). false if no auto position is set
// Note: false since we need a real value to make the streaming client transport this value
autoPosition: false,
locked: false, // disk is locked (implies master-controlled)
});
}
setTargetSpeed(speed, props) {
return this.set('targetSpeed', speed, props);
}
getTargetSpeed() {
return this.get('targetSpeed');
}
setPosition(position, props) {
this.set('position', position, props);
}
getPosition() {
return this.get('position');
}
setUser(user, props) {
const lastUser = this.getUser();
if (lastUser !== '') this.set('lastUser', lastUser, props);
return this.set('user', user, props);
}
getUser() {
return this.get('user');
}
hasUser() {
return this.get('user') !== '';
}
getLastUser() {
return this.get('lastUser');
}
// Set to undefined to remove target positioning
setAutoPosition(autoPosition, props) {
return this.set('autoPosition', autoPosition, props);
}
hasAutoPosition() {
return this.get('autoPosition') !== false;
}
getAutoPosition() {
return this.get('autoPosition');
}
setLocked(locked, props) {
return this.set('locked', locked, props);
}
getLocked() {
return this.get('locked');
}
stop() {
this.setTargetSpeed(0);
this.setAutoPosition(false);
}
}
| JavaScript | 0.000003 | @@ -1038,23 +1038,21 @@
this.get
-('user'
+User(
) !== ''
|
d96478c6960c4bbc5511bbb1b58dafc256fa21d3 | fix #749 enable VisualFocusTest in IE8 | test/aria/templates/visualFocus/VisualFocusTestCase.js | test/aria/templates/visualFocus/VisualFocusTestCase.js | /*
* Copyright 2013 Amadeus s.a.s.
* 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.
*/
/**
* Testcase for focus handling
*/
Aria.classDefinition({
$classpath : "test.aria.templates.visualFocus.VisualFocusTestCase",
$dependencies : ["aria.core.Browser", "aria.utils.Dom"],
$extends : "aria.jsunit.TemplateTestCase",
$constructor : function () {
this.$TemplateTestCase.constructor.call(this);
this._visualFocusTestCaseEnv = {
template : "test.aria.templates.visualFocus.VisualFocusTemplate"
};
this.setTestEnv(this._visualFocusTestCaseEnv);
},
$prototype : {
runTemplateTest : function () {
// set the outline configuration property of the application
aria.core.AppEnvironment.setEnvironment({
appOutlineStyle : "2px dashed red"
}, null, true);
if (aria.utils.VisualFocus) {
this.executeActions();
} else {
aria.core.ClassMgr.$on({
"classComplete" : function (evt) {
if (evt.refClasspath && evt.refClasspath == "aria.utils.VisualFocus") {
this.executeActions();
}
},
scope : this
});
}
},
executeActions : function () {
try {
this.visualFocusTestvar = {};
var curOutline;
var myDom = aria.utils.Dom;
var link = this.getElementById("myLink");
var secondLink = this.getElementById("mySecondLink");
// on button the outline is added directly on the button element
var button = this.getWidgetInstance("myButton").getDom().childNodes[0];
// on fields it's added on the span containing the input
var field = this.getWidgetInstance("myField").getDom().getElementsByTagName("input")[0].parentNode;
var template = this.templateCtxt._tpl;
curOutline = [link.style.outlineColor, link.style.outlineStyle, link.style.outlineWidth];
this.visualFocusTestvar.var1 = curOutline.join(" ");
template.$focus("myLink");
curOutline = [link.style.outlineColor, link.style.outlineStyle, link.style.outlineWidth];
this.visualFocusTestvar.var2 = curOutline.join(" ");
template.$focus("myButton");
curOutline = [link.style.outlineColor, link.style.outlineStyle, link.style.outlineWidth];
this.visualFocusTestvar.var3 = curOutline.join(" ");
curOutline = [button.style.outlineColor, button.style.outlineStyle, button.style.outlineWidth];
this.visualFocusTestvar.var4 = curOutline.join(" ");
template.$focus("myField");
curOutline = [button.style.outlineColor, button.style.outlineStyle, button.style.outlineWidth];
this.visualFocusTestvar.var5 = curOutline.join(" ");
curOutline = [field.style.outlineColor, field.style.outlineStyle, field.style.outlineWidth];
this.visualFocusTestvar.var6 = curOutline.join(" ");
curOutline = [myDom.getStyle(secondLink, "outlineStyle")];
this.visualFocusTestvar.var7 = curOutline.join(" ");
template.$focus("mySecondLink");
curOutline = [field.style.outlineStyle, field.style.outlineWidth];
this.visualFocusTestvar.var8 = curOutline.join(" ");
curOutline = [myDom.getStyle(secondLink, "outlineStyle"), myDom.getStyle(secondLink, "outlineWidth")];
this.visualFocusTestvar.var9 = curOutline.join(" ");
template.$focus("myField");
curOutline = [myDom.getStyle(secondLink, "outlineStyle")];
this.visualFocusTestvar.var10 = curOutline.join(" ");
aria.core.AppEnvironment.setEnvironment({
appOutlineStyle : null
}, null, true);
this.myVisualFocusTest();
} catch (ex) {
try {
this.fail("Exception in executeActions " + ex.message);
} catch (expt) {}
this.finishTest();
}
},
myVisualFocusTest : (aria.core.Browser.isIE6 || aria.core.Browser.isIE7 || aria.core.Browser.isIE8)
? function () {
this.finishTest();
}
: function () {
var testVar;
var outlines = {
1 : "green solid 3px",
2 : "red dashed 2px",
3 : "green solid 3px",
4 : "red dashed 2px",
5 : " ",
6 : "red dashed 2px",
7 : "double",
8 : " ",
9 : "dashed 2px",
10 : "double"
};
for (var i = 1; i <= 10; i++) {
testVar = this.visualFocusTestvar["var" + i];
var expected = outlines[i].toLowerCase();
var got = testVar.toLowerCase();
this.assertEquals(got, expected, "got '" + got + "' expected '" + expected + "' on var" + i);
}
this.finishTest();
},
/**
* Finalize the test, in this case, nothing special to do
*/
finishTest : function () {
this.notifyTemplateTestEnd();
}
}
}); | JavaScript | 0 | @@ -4950,63 +4950,9 @@
isIE
-6 %7C%7C aria.core.Browser.isIE7 %7C%7C aria.core.Browser.isIE8
+7
)%0A
@@ -6211,8 +6211,9 @@
%7D%0A%7D);
+%0A
|
d48642acf5856b5ab7c1342516496155b57d668c | test was failing in travis because of show ACL for 3rd link. 4 show in not travis environment, 3 in travis environment | test/e2e/specs/all-features/navbar/base-config.spec.js | test/e2e/specs/all-features/navbar/base-config.spec.js | var chaisePage = require('../../../utils/chaise.page.js');
describe('Navbar ', function() {
var navbar, menu, chaiseConfig, EC = protractor.ExpectedConditions;
beforeAll(function () {
browser.ignoreSynchronization=true;
browser.get(browser.params.url + "/recordset/#" + browser.params.catalogId + "/product-navbar:accommodation");
navbar = element(by.id('mainnav'));
menu = element(by.id('navbar-menu'));
browser.executeScript('return chaiseConfig;').then(function(config) {
chaiseConfig = config;
browser.wait(EC.presenceOf(navbar), browser.params.defaultTimeout);
});
});
it('should be visible', function() {
expect(navbar.isDisplayed()).toBeTruthy();
});
it('should display the right title from chaiseConfig', function() {
var actualTitle = element(by.id('brand-text'));
var expectedTitle = chaiseConfig.navbarBrandText;
expect(actualTitle.getText()).toEqual(expectedTitle);
});
it('should use the brand image/logo specified in chaiseConfig', function() {
var actualLogo = element(by.id('brand-image'));
var expectedLogo = chaiseConfig.navbarBrandImage;
expect(actualLogo.isDisplayed()).toBeTruthy();
expect(actualLogo.getAttribute('src')).toMatch(expectedLogo);
});
it('for the menu, should generate the correct # of list items based on acls to show/hide specific options', function() {
var nodesInDOM = menu.all(by.tagName('li'));
// Count the number of nodes that are being shown (top level and submenus)
// - Local: config has 13 but 1 is hidden by ACLs
// - Travis: config has 13 but 7 are hidden based on ACLs
var counter = (!process.env.TRAVIS ? 12 : 6); // counted from chaise config doc rather than having code count
nodesInDOM.count().then(function(count) {
expect(count).toEqual(counter, "number of nodes present does not match what's defined in chaise-config");
});
});
it('should prefer markdownName over name when both are defined', function () {
// option #2 has both name and markdownName defined
expect(element.all(by.css('#navbar-menu > li.dropdown')).get(1).getText()).toBe("Test Recordsets", "name was used instead of markdownName");
});
it('should render a markdown pattern using proper HTML', function () {
// option #4 has only markdownName defined
element.all(by.css('#navbar-menu > li.dropdown')).get(3).element(by.css("a")).getAttribute('innerHTML').then(function (aInnerHTML) {
expect(aInnerHTML.indexOf("<strong>")).toBeGreaterThan(-1, "name was used instead of markdownName");
});
});
if (!process.env.TRAVIS) {
var menuDropdowns, disabledSubMenuOptions;
it('should have a disabled "Records" link.', function () {
menuDropdowns = element.all(by.css('#navbar-menu > li.dropdown'));
expect(menuDropdowns.count()).toBe(4, "number of top level dropdown menus is wrong");
// get index 2 (3rd item)
expect(menuDropdowns.get(2).element(by.css("a.disable-link")).getText()).toBe("Records", "text is incorrect, may include caret");
});
it('should have a header and a disabled "Edit Existing Record" submenu link (no children).', function () {
var editMenu = menuDropdowns.get(3);
// need to open menu so it renders and has a value
editMenu.click().then(function () {
subMenuHeader = editMenu.all(by.css("span.chaise-dropdown-header"));
expect(subMenuHeader.get(0).getText()).toBe("For Mutating Data", "Sub menu header is incorrect or not showing");
return editMenu.all(by.css("a.disable-link"));
}).then(function (options) {
disabledSubMenuOptions = options;
expect(options.length).toBe(4, "some options are not shown properly");
expect(disabledSubMenuOptions[0].getText()).toBe("Edit Existing Record", "the wrong link is disabled or none were selected");
});
});
it('should have disabled "Edit Records" submenu link (has children)', function () {
//menu should still be open from previous test case
expect(disabledSubMenuOptions[1].getText()).toBe("Edit Records", "the wrong link is disabled or caret is still visible");
});
}
it('should show the "Full Name" of the logged in user in the top right', function () {
var name = (!process.env.TRAVIS ? browser.params.client.full_name : browser.params.client.display_name);
expect(element(by.css('login .username-display')).getText()).toBe(name, "user's displayed name is incorrect");
});
it('should open the profile card on click of My Profile link', function(done) {
var link = element(by.css('login .dropdown-toggle'));
browser.wait(EC.elementToBeClickable(link), browser.params.defaultTimeout);
chaisePage.clickButton(link).then(function() {
var profileLink = element(by.id('profile-link'));
browser.wait(EC.elementToBeClickable(profileLink), browser.params.defaultTimeout);
chaisePage.clickButton(profileLink).then(function() {
var modalContent = element(by.css('.modal-content'));
chaisePage.waitForElement(modalContent);
expect(modalContent.isDisplayed()).toBeTruthy();
done();
}).catch(function (err) {
done.fail();
console.log(err);
});
});
});
it('should close the profile card on click of X on the modal window', function(done) {
var closeLink = element(by.css('.modal-close'));
var modalContent = element(by.css('.modal-content'));
browser.wait(EC.elementToBeClickable(closeLink), browser.params.defaultTimeout);
chaisePage.clickButton(closeLink).then(function(){
browser.wait(EC.not(EC.presenceOf(modalContent)), browser.params.defaultTimeout);
expect(modalContent.isPresent()).toEqual(false);
done();
}).catch(function (err) {
console.log(err);
done.fail();
});
});
// TODO: These tests are xit'd because we don't handle tests logging in via Globus/other services just yet
// e.g. On Travis, the user is logged in. On local machines, you must log in manually, which changes the desired order of specs.
xit('should have a "Log In" link', function() {
var actualLink = element(by.id('login-link'));
browser.wait(EC.elementToBeClickable(actualLink), browser.params.defaultTimeout).then(function() {
expect(actualLink.isDisplayed()).toBeTruthy();
});
}).pend("Pending until we handle tests logging in via Globus/other services");
xit('should have a "Sign Up" link with the right href from chaiseConfig', function(done) {
var actualLink = element(by.id('signup-link'));
browser.wait(EC.elementToBeClickable(actualLink), browser.params.defaultTimeout).then(function() {
expect(actualLink.isDisplayed()).toBeTruthy();
expect(actualLink.getAttribute('href')).toMatch(chaiseConfig.signUpURL);
done();
});
}).pend("Pending until we handle tests logging in via Globus/other services");
xit('should display a "Log Out" link', function(done) {
var logOutLink = element(by.id('logout-link'));
browser.wait(EC.elementToBeClickable(logOutLink), browser.params.defaultTimeout).then(function() {
browser.ignoreSynchronization = true;
expect(logOutLink.isDisplayed()).toBeTruthy();
done();
});
}).pend("Pending until we handle tests logging in via Globus/other services");
});
| JavaScript | 0.000369 | @@ -2406,32 +2406,187 @@
, function () %7B%0A
+ // in travis we don't have the same globus groups so the %22show%22 ACL hides the 3rd link (%22Records%22)%0A var idx = (!process.env.TRAVIS ? 3 : 2)%0A
// optio
|
dfa02a7cf34f54e25d698cea83d33904a16753de | Remove stray console.log | architecture-examples/backbone/js/views/appView.js | architecture-examples/backbone/js/views/appView.js | $(function( $ ) {
'use strict';
// The Application
// ---------------
// Our overall **AppView** is the top-level piece of UI.
window.app.AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: $("#todoapp"),
// Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template($('#stats-template').html()),
// Delegated events for creating new items, and clearing completed ones.
events: {
"keypress #new-todo": "createOnEnter",
"click #clear-completed": "clearCompleted",
"click #toggle-all": "toggleAllComplete"
},
// At initialization we bind to the relevant events on the `Todos`
// collection, when items are added or changed. Kick things off by
// loading any preexisting todos that might be saved in *localStorage*.
initialize: function() {
this.input = this.$("#new-todo");
this.allCheckbox = this.$("#toggle-all")[0];
window.app.Todos.on('add', this.addOne, this);
window.app.Todos.on('reset', this.addAll, this);
window.app.Todos.on('all', this.render, this);
this.$footer = $('#footer');
this.$main = $('#main');
window.app.Todos.fetch();
},
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function() {
var completed = window.app.Todos.completed().length;
var remaining = window.app.Todos.remaining().length;
if (window.app.Todos.length) {
this.$main.show();
this.$footer.show();
this.$footer.html(this.statsTemplate({
completed: completed,
remaining: remaining
}));
this.$('#filters li a')
.removeClass('selected')
.filter("[href='#/" + window.app.TodoFilter + "']")
.addClass('selected');
} else {
this.$main.hide();
this.$footer.hide();
}
this.allCheckbox.checked = !remaining;
},
// Add a single todo item to the list by creating a view for it, and
// appending its element to the `<ul>`.
addOne: function(todo) {
var view = new window.app.TodoView({model: todo});
$("#todo-list").append(view.render().el);
},
// Add all items in the **Todos** collection at once.
addAll: function() {
console.log('addall', window.app.TodoFilter);
this.$("#todo-list").html('');
switch(window.app.TodoFilter){
case "active":
_.each(window.app.Todos.remaining(), this.addOne);
break;
case "completed":
_.each(window.app.Todos.completed(), this.addOne);
break;
default:
window.app.Todos.each(this.addOne, this);
break;
}
},
// Generate the attributes for a new Todo item.
newAttributes: function() {
return {
title: this.input.val().trim(),
order: window.app.Todos.nextOrder(),
completed: false
};
},
// If you hit return in the main input field, create new **Todo** model,
// persisting it to *localStorage*.
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!this.input.val().trim()) return;
window.app.Todos.create(this.newAttributes());
this.input.val('');
},
// Clear all completed todo items, destroying their models.
clearCompleted: function() {
_.each(window.app.Todos.completed(), function(todo){ todo.clear(); });
return false;
},
toggleAllComplete: function () {
var completed = this.allCheckbox.checked;
window.app.Todos.each(function (todo) { todo.save({'completed': completed}); });
}
});
}); | JavaScript | 0.000002 | @@ -2277,58 +2277,8 @@
%7B%0A%0A
-%09%09%09console.log('addall', window.app.TodoFilter);%0A%0A
%09%09%09t
|
ed4304ac79b3e7bcc6608f60d6490ea7e31c9ac4 | FIX Linter errors | test/unit/client/client-information-management-test.js | test/unit/client/client-information-management-test.js | /*
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of iotagent-lwm2m-lib
*
* iotagent-lwm2m-lib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* iotagent-lwm2m-lib 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with iotagent-lwm2m-lib.
* If not, seehttp://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::[contacto@tid.es]
*/
'use strict';
var should = require('should'),
async = require('async'),
apply = async.apply,
lwm2mServer = require('../../../').server,
lwm2mClient = require('../../../').client,
config = require('../../../config'),
testInfo = {};
function emptyHandler(data) {
}
describe('Client-side information management', function() {
var deviceInformation,
deviceId;
beforeEach(function(done) {
lwm2mServer.start(config.server, function (error, srvInfo) {
testInfo.serverInfo = srvInfo;
lwm2mClient.register('localhost', config.server.port, null, 'testEndpoint', function (error, result) {
deviceInformation = result;
deviceId = deviceInformation.location.split('/')[2];
lwm2mClient.registry.create('/3/6', done);
});
});
});
afterEach(function(done) {
async.series([
apply(lwm2mClient.registry.remove, '/3/6'),
apply(lwm2mClient.unregister, deviceInformation),
apply(lwm2mServer.stop, testInfo.serverInfo)
], function() {
lwm2mClient.registry.bus.removeAllListeners();
done();
});
});
describe.only('When a Read requests arrives to the client with the Observe Option for value changes', function () {
var obj = {
type: '3',
id: '6',
resource: '2',
value: 'ValueToBeRead',
uri: '/3/6'
};
beforeEach(function(done) {
lwm2mClient.registry.setAttribute(obj.uri, obj.resource, obj.value, done);
});
afterEach(function(done) {
lwm2mClient.registry.unsetAttribute(obj.uri, obj.resource, done);
});
it('should call the read handler once with the original value', function(done) {
var handlerCalls = 0;
lwm2mClient.setHandler(deviceInformation.serverInfo, 'read',
function (objectType, objectId, resourceId, resourceValue, callback) {
should.exist(objectType);
should.exist(objectId);
should.exist(resourceId);
objectType.should.equal(obj.type);
objectId.should.equal(obj.id);
resourceId.should.equal(obj.resource);
handlerCalls++;
callback(null, resourceValue);
});
lwm2mServer.observe(deviceId, obj.type, obj.id, obj.resource, emptyHandler, function(error, result) {
should.not.exist(error);
should.exist(result);
result.should.equal(obj.value);
handlerCalls.should.equal(1);
done();
});
});
it('should return the current value of the selected object', function(done) {
lwm2mClient.setHandler(deviceInformation.serverInfo, 'read',
function (objectType, objectId, resourceId, resourceValue, callback) {
callback(null, resourceValue);
});
lwm2mServer.observe(deviceId, obj.type, obj.id, obj.resource, emptyHandler, function(error, result) {
should.not.exist(error);
should.exist(result);
result.should.equal(obj.value);
done();
});
});
it('should update the value each time there is a new value', function(done) {
var serverHandlerCalls = 0;
lwm2mClient.setHandler(deviceInformation.serverInfo, 'read',
function (objectType, objectId, resourceId, resourceValue, callback) {
callback(null, resourceValue);
});
function serverHandler() {
serverHandlerCalls++;
if (serverHandlerCalls === 3) {
done();
}
}
lwm2mServer.observe(deviceId, obj.type, obj.id, obj.resource, serverHandler, function(error, result) {
should.not.exist(error);
async.series([
async.apply(lwm2mClient.registry.setAttribute, obj.uri, obj.resource, 21),
async.apply(lwm2mClient.registry.setAttribute, obj.uri, obj.resource, 89),
async.apply(lwm2mClient.registry.setAttribute, obj.uri, obj.resource, 7)
], function (error) {
should.not.exist(error);
})
});
});
it('should appear in the list of observed values');
});
describe('When the client cancels an observed value', function() {
it('should cease sending messages to the remote server');
});
}); | JavaScript | 0 | @@ -2149,13 +2149,8 @@
ribe
-.only
('Wh
@@ -5435,16 +5435,17 @@
%7D)
+;
%0A
|
383fbd50e06780c46d1e0be1c993c9cd0f4ca380 | Use actual id attribute for pageElementId | assets/src/components/editor-carousel/reorderer.js | assets/src/components/editor-carousel/reorderer.js | /**
* WordPress dependencies
*/
import { Fragment } from '@wordpress/element';
import { withState } from '@wordpress/compose';
import { Draggable, DropZoneProvider, DropZone } from '@wordpress/components';
/**
* Internal dependencies
*/
import BlockPreview from './block-preview';
const Reorderer = ( { pages, dragging, hasDropped, setState } ) => {
return (
<DropZoneProvider>
{ hasDropped ? 'Dropped!' : 'Drop something here' }
<div className="amp-story-reorderer">
{ pages.map( ( page, index ) => {
const { clientId } = page;
const pageElementId = `page-${ clientId }`;
const transferData = {
type: 'block',
srcIndex: index,
srcRootClientId: '',
srcClientId: clientId,
};
return (
<div
key={ pageElementId }
className="amp-story-reorderer-item"
>
<Draggable
className={ dragging ? 'is-dragging' : undefined }
elementId={ pageElementId }
transferData={ transferData }
onDragStart={ () => {
setState( { dragging: true } );
} }
onDragEnd={ () => {
setState( { dragging: false } );
} }
>
{
( { onDraggableStart, onDraggableEnd } ) => (
<Fragment>
<DropZone
onDrop={ () => setState( { hasDropped: true } ) }
/>
<div
className="amp-story-page-preview"
onDragStart={ onDraggableStart }
onDragEnd={ onDraggableEnd }
draggable
>
<BlockPreview { ...page } />
</div>
</Fragment>
)
}
</Draggable>
</div>
);
} ) }
</div>
</DropZoneProvider>
);
};
export default withState( {
dragging: false,
hasDropped: false,
} )( Reorderer );
| JavaScript | 0.000001 | @@ -200,16 +200,54 @@
onents';
+%0Aimport %7B __ %7D from '@wordpress/i18n';
%0A%0A/**%0A *
@@ -612,16 +612,24 @@
ntId = %60
+reorder-
page-$%7B
@@ -816,31 +816,38 @@
%09%09key=%7B
+%60
page
-Elem
+-$%7B cli
entId %7D
+%60 %7D
%0A%09%09%09%09%09%09%09
@@ -1323,16 +1323,75 @@
ropZone%0A
+%09%09%09%09%09%09%09%09%09%09%09%09label=%7B __( 'Drop page to re-order', 'amp' ) %7D%0A
%09%09%09%09%09%09%09%09
@@ -1469,25 +1469,65 @@
%09%09%09%09%09%09%09%09%3Cdiv
-%0A
+ id=%7B pageElementId %7D%3E%0A%09%09%09%09%09%09%09%09%09%09%09%09%3Cdiv%0A%09
%09%09%09%09%09%09%09%09%09%09%09%09
@@ -1565,32 +1565,33 @@
ew%22%0A%09%09%09%09%09%09%09%09%09%09%09%09
+%09
onDragStart=%7B on
@@ -1607,16 +1607,17 @@
Start %7D%0A
+%09
%09%09%09%09%09%09%09%09
@@ -1661,16 +1661,17 @@
%09%09%09%09%09%09%09%09
+%09
draggabl
@@ -1664,32 +1664,33 @@
%09%09%09%09%09%09draggable%0A
+%09
%09%09%09%09%09%09%09%09%09%09%09%3E%0A%09%09%09
@@ -1698,16 +1698,17 @@
%09%09%09%09%09%09%09%09
+%09
%3CBlockPr
@@ -1728,16 +1728,35 @@
ge %7D /%3E%0A
+%09%09%09%09%09%09%09%09%09%09%09%09%3C/div%3E%0A
%09%09%09%09%09%09%09%09
|
5145f75bf6aa698178e2a0728752b3c8f09c140b | remove null coalescing operator (#2069) | src/instanceMethods/close.js | src/instanceMethods/close.js | import { undoScrollbar } from '../utils/scrollbarFix.js'
import { undoIOSfix } from '../utils/iosFix.js'
import { undoIEfix } from '../utils/ieFix.js'
import { unsetAriaHidden } from '../utils/aria.js'
import * as dom from '../utils/dom/index.js'
import { swalClasses } from '../utils/classes.js'
import globalState, { restoreActiveElement } from '../globalState.js'
import privateProps from '../privateProps.js'
import privateMethods from '../privateMethods.js'
/*
* Instance method to close sweetAlert
*/
function removePopupAndResetState (instance, container, isToast, didClose) {
if (isToast) {
triggerDidCloseAndDispose(instance, didClose)
} else {
restoreActiveElement().then(() => triggerDidCloseAndDispose(instance, didClose))
globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, { capture: globalState.keydownListenerCapture })
globalState.keydownHandlerAdded = false
}
if (container.parentNode && !document.body.getAttribute('data-swal2-queue-step')) {
container.parentNode.removeChild(container)
}
if (dom.isModal()) {
undoScrollbar()
undoIOSfix()
undoIEfix()
unsetAriaHidden()
}
removeBodyClasses()
}
function removeBodyClasses () {
dom.removeClass(
[document.documentElement, document.body],
[
swalClasses.shown,
swalClasses['height-auto'],
swalClasses['no-backdrop'],
swalClasses['toast-shown'],
swalClasses['toast-column']
]
)
}
export function close (resolveValue) {
const popup = dom.getPopup()
if (!popup) {
return
}
resolveValue = prepareResolveValue(resolveValue)
const innerParams = privateProps.innerParams.get(this)
if (!innerParams || dom.hasClass(popup, innerParams.hideClass.popup)) {
return
}
const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this)
dom.removeClass(popup, innerParams.showClass.popup)
dom.addClass(popup, innerParams.hideClass.popup)
const backdrop = dom.getContainer()
dom.removeClass(backdrop, innerParams.showClass.backdrop)
dom.addClass(backdrop, innerParams.hideClass.backdrop)
handlePopupAnimation(this, popup, innerParams)
// Resolve Swal promise
swalPromiseResolve(resolveValue)
}
const prepareResolveValue = (resolveValue) => {
// When user calls Swal.close()
if (typeof resolveValue === 'undefined') {
return {
isConfirmed: false,
isDenied: false,
isDismissed: true,
}
}
return Object.assign({
isConfirmed: false,
isDenied: false,
isDismissed: false,
}, resolveValue)
}
const handlePopupAnimation = (instance, popup, innerParams) => {
const container = dom.getContainer()
// If animation is supported, animate
const animationIsSupported = dom.animationEndEvent && dom.hasCssAnimation(popup)
const {
onClose, onAfterClose, // @deprecated
willClose, didClose
} = innerParams
runDidClose(popup, willClose, onClose)
if (animationIsSupported) {
animatePopup(instance, popup, container, didClose ?? onAfterClose)
} else {
// Otherwise, remove immediately
removePopupAndResetState(instance, container, dom.isToast(), didClose ?? onAfterClose)
}
}
const runDidClose = (popup, willClose, onClose) => {
if (willClose !== null && typeof willClose === 'function') {
willClose(popup)
} else if (onClose !== null && typeof onClose === 'function') {
onClose(popup) // @deprecated
}
}
const animatePopup = (instance, popup, container, didClose) => {
globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, dom.isToast(), didClose)
popup.addEventListener(dom.animationEndEvent, function (e) {
if (e.target === popup) {
globalState.swalCloseEventFinishedCallback()
delete globalState.swalCloseEventFinishedCallback
}
})
}
const triggerDidCloseAndDispose = (instance, didClose) => {
setTimeout(() => {
if (typeof didClose === 'function') {
didClose()
}
instance._destroy()
})
}
export {
close as closePopup,
close as closeModal,
close as closeToast
}
| JavaScript | 0 | @@ -3009,34 +3009,34 @@
ainer, didClose
-??
+%7C%7C
onAfterClose)%0A
@@ -3160,10 +3160,10 @@
ose
-??
+%7C%7C
onA
|
f99c3ad3b3072a4f64f261e79fc048ecc8260bf0 | Use internal logger instead of console.error | src/instrumentation/trace.js | src/instrumentation/trace.js | var Promise = require('es6-promise').Promise
var logger = require('../lib/logger')
var frames = require('../exceptions/frames')
var traceCache = require('./traceCache')
var Trace = module.exports = function (transaction, signature, type) {
this.transaction = transaction
this.signature = signature
this.type = type
this.ended = false
this._parent = null
// Start timers
this._start = window.performance.now()
this._startStamp = new Date()
this._isFinish = new Promise(function (resolve, reject) {
this._markFinishedFunc = resolve
}.bind(this))
this.getTraceStackFrames(function (frames) {
if (frames) {
this.frames = frames.reverse() // Reverse frames to make Opbeat happy
}
this._markFinishedFunc() // Mark the trace as finished
}.bind(this))
logger.log('%c -- opbeat.instrumentation.trace.start', 'color: #9a6bcb', this.signature, this._start)
}
Trace.prototype.end = function () {
this._diff = window.performance.now() - this._start
this.ended = true
logger.log('%c -- opbeat.instrumentation.trace.end', 'color: #9a6bcb', this.signature, this._diff)
this._isFinish.then(function () {
this.transaction._onTraceEnd(this)
}.bind(this))
}
Trace.prototype.duration = function () {
if (!this.ended) {
console.error('Trying to call trace.duration() on un-ended Trace!')
return null
}
return parseFloat(this._diff)
}
Trace.prototype.startTime = function () {
if (!this.ended || !this.transaction.ended) {
logger.error('Trying to call trace.startTime() for un-ended Trace/Transaction!')
return null
}
return this._start
}
Trace.prototype.ancestors = function () {
var parent = this.parent()
if (!parent) {
return []
} else {
return [parent.signature]
}
}
Trace.prototype.parent = function () {
return this._parent
}
Trace.prototype.setParent = function (val) {
this._parent = val
}
Trace.prototype.getFingerprint = function () {
var key = [this.transaction.name, this.signature, this.type]
// Iterate over parents
var prev = this._parent
while (prev) {
key.push(prev.signature)
prev = prev._parent
}
return key.join('-')
}
Trace.prototype.getTraceStackFrames = function (callback) {
// Use callbacks instead of Promises to keep the stack
var key = this.getFingerprint()
var traceFrames = traceCache.get(key)
if (traceFrames) {
callback(traceFrames)
} else {
frames.getFramesForCurrent().then(function (traceFrames) {
traceCache.set(key, traceFrames)
callback(traceFrames)
})['catch'](function () {
callback(null)
})
}
}
module.exports = Trace
| JavaScript | 0.000004 | @@ -1272,38 +1272,49 @@
-console.error('Trying to call
+logger.log('%25c -- opbeat.instrumentation.
trac
@@ -1327,22 +1327,23 @@
tion
-() on
+.error.
un-ended
Tra
@@ -1342,16 +1342,62 @@
nded
- T
+.t
race!'
+, 'color: #ff0000', this.signature, this._diff
)%0A
@@ -1555,30 +1555,42 @@
ger.
-error('Trying to call
+log('%25c -- opbeat.instrumentation.
trac
@@ -1604,23 +1604,23 @@
Time
-() for
+.error.
un-ended
Tra
@@ -1619,28 +1619,62 @@
nded
- T
+.t
race
-/Transaction!'
+!', 'color: #ff0000', this.signature, this._diff
)%0A
|
305df1f9ca96807285f1c1b47a4545c9c1e9e7f8 | Allow IndexHistory legend position to be set | src/js/components/History.js | src/js/components/History.js | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component, PropTypes } from 'react';
import Chart from 'grommet/components/Chart';
export default class IndexHistory extends Component {
constructor (props) {
super(props);
this.state = this._stateFromProps(props);
}
componentWillReceiveProps (nextProps) {
this.setState(this._stateFromProps(nextProps));
}
_stateFromProps (props) {
let series = [];
let xAxis = [];
if (props.series) {
series = props.series.map((item, index) => {
const values = item.intervals.map(interval => {
let date = interval.start;
if (typeof interval.start === 'string') {
date = new Date(Date.parse(interval.start));
}
if (0 === index) {
xAxis.push({
label: (date.getMonth() + 1) + '/' + date.getDate(),
value: date
});
}
return [date, interval.count];
});
let colorIndex = `graph-${index + 1}`;
if ('status' === props.name) {
colorIndex = item.value.toLowerCase();
}
return {
label: (item.label || item.value),
values: values,
colorIndex: colorIndex
};
});
}
return { series: series, xAxis: xAxis };
}
render () {
return (
<Chart series={this.state.series || []}
xAxis={this.state.xAxis || []}
legend={{position: 'after'}}
legendTotal={true}
size={this.props.size}
smooth={this.props.smooth}
points={this.props.points}
type={this.props.type}
threshold={this.props.threshold}
a11yTitleId={this.props.a11yTitleId}
a11yDescId={this.props.a11yTitleId} />
);
}
}
IndexHistory.propTypes = {
a11yTitleId: PropTypes.string,
a11yDescId: PropTypes.string,
name: PropTypes.string.isRequired,
points: PropTypes.bool,
series: PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.string,
value: PropTypes.string.isRequired,
intervals: PropTypes.arrayOf(PropTypes.shape({
count: PropTypes.number,
start: PropTypes.oneOfType([
PropTypes.object,
PropTypes.string
]),
stop: PropTypes.oneOfType([
PropTypes.object,
PropTypes.string
])
})).isRequired
})),
size: PropTypes.oneOf(['small', 'medium', 'large']),
smooth: PropTypes.bool,
threshold: PropTypes.number,
type: PropTypes.oneOf(['bar', 'area', 'line'])
};
| JavaScript | 0 | @@ -1473,27 +1473,25 @@
nd=%7B
-%7Bposition: 'after'%7D
+this.props.legend
%7D%0A
@@ -1887,16 +1887,129 @@
string,%0A
+ legend: PropTypes.shape(%7B%0A position: PropTypes.oneOf(%5B'overlay', 'after'%5D),%0A total: PropTypes.bool%0A %7D),%0A
name:
@@ -2640,8 +2640,72 @@
e'%5D)%0A%7D;%0A
+%0AIndexHistory.defaultProps = %7B%0A legend: %7Bposition: 'after'%7D%0A%7D;%0A
|
612ff20df168c667bd0cc1c5d8cac313333e762a | set backup done flag if wallet is created from a specified phrase | src/js/controllers/create.js | src/js/controllers/create.js | 'use strict';
angular.module('copayApp.controllers').controller('createController',
function($scope, $rootScope, $timeout, $log, lodash, go, profileService, configService, gettext, ledger, trezor, platformInfo, derivationPathHelper, ongoingProcess) {
var isChromeApp = platformInfo.isChromeApp;
var isCordova = platformInfo.isCordova;
var isDevel = platformInfo.isDevel;
var self = this;
var defaults = configService.getDefaults();
this.isWindowsPhoneApp = platformInfo.isWP && isCordova;
$scope.account = 1;
/* For compressed keys, m*73 + n*34 <= 496 */
var COPAYER_PAIR_LIMITS = {
1: 1,
2: 2,
3: 3,
4: 4,
5: 4,
6: 4,
7: 3,
8: 3,
9: 2,
10: 2,
11: 1,
12: 1,
};
var defaults = configService.getDefaults();
$scope.bwsurl = defaults.bws.url;
$scope.derivationPath = derivationPathHelper.default;
// ng-repeat defined number of times instead of repeating over array?
this.getNumber = function(num) {
return new Array(num);
}
var updateRCSelect = function(n) {
$scope.totalCopayers = n;
var maxReq = COPAYER_PAIR_LIMITS[n];
self.RCValues = lodash.range(1, maxReq + 1);
$scope.requiredCopayers = Math.min(parseInt(n / 2 + 1), maxReq);
};
var updateSeedSourceSelect = function(n) {
self.seedOptions = [{
id: 'new',
label: gettext('New Random Recovery Phrase'),
}, {
id: 'set',
label: gettext('Specify Recovery Phrase...'),
}];
$scope.seedSource = self.seedOptions[0];
if (n > 1 && isChromeApp)
self.seedOptions.push({
id: 'ledger',
label: 'Ledger',
});
if (isChromeApp || isDevel) {
self.seedOptions.push({
id: 'trezor',
label: 'Trezor',
});
}
};
this.TCValues = lodash.range(2, defaults.limits.totalCopayers + 1);
$scope.totalCopayers = defaults.wallet.totalCopayers;
this.setTotalCopayers = function(tc) {
updateRCSelect(tc);
updateSeedSourceSelect(tc);
self.seedSourceId = $scope.seedSource.id;
};
this.setSeedSource = function(src) {
self.seedSourceId = $scope.seedSource.id;
$timeout(function() {
$rootScope.$apply();
});
};
this.create = function(form) {
if (form && form.$invalid) {
this.error = gettext('Please enter the required fields');
return;
}
var opts = {
m: $scope.requiredCopayers,
n: $scope.totalCopayers,
name: $scope.walletName,
myName: $scope.totalCopayers > 1 ? $scope.myName : null,
networkName: $scope.testnetEnabled ? 'testnet' : 'livenet',
bwsurl: $scope.bwsurl,
singleAddress: $scope.singleAddressEnabled,
walletPrivKey: $scope._walletPrivKey, // Only for testing
};
var setSeed = self.seedSourceId == 'set';
if (setSeed) {
var words = $scope.privateKey || '';
if (words.indexOf(' ') == -1 && words.indexOf('prv') == 1 && words.length > 108) {
opts.extendedPrivateKey = words;
} else {
opts.mnemonic = words;
}
opts.passphrase = $scope.passphrase;
var pathData = derivationPathHelper.parse($scope.derivationPath);
if (!pathData) {
this.error = gettext('Invalid derivation path');
return;
}
opts.account = pathData.account;
opts.networkName = pathData.networkName;
opts.derivationStrategy = pathData.derivationStrategy;
} else {
opts.passphrase = $scope.createPassphrase;
}
if (setSeed && !opts.mnemonic && !opts.extendedPrivateKey) {
this.error = gettext('Please enter the wallet recovery phrase');
return;
}
if (self.seedSourceId == 'ledger' || self.seedSourceId == 'trezor') {
var account = $scope.account;
if (!account || account < 1) {
this.error = gettext('Invalid account number');
return;
}
if (self.seedSourceId == 'trezor')
account = account - 1;
opts.account = account;
ongoingProcess.set('connecting' + self.seedSourceId, true);
var src = self.seedSourceId == 'ledger' ? ledger : trezor;
src.getInfoForNewWallet(opts.n > 1, account, function(err, lopts) {
ongoingProcess.set('connecting' + self.seedSourceId, false);
if (err) {
self.error = err;
$scope.$apply();
return;
}
opts = lodash.assign(lopts, opts);
self._create(opts);
});
} else {
self._create(opts);
}
};
this._create = function(opts) {
ongoingProcess.set('creatingWallet', true);
$timeout(function() {
profileService.createWallet(opts, function(err) {
ongoingProcess.set('creatingWallet', false);
if (err) {
$log.warn(err);
self.error = err;
$timeout(function() {
$rootScope.$apply();
});
return;
}
go.walletHome();
});
}, 100);
}
this.formFocus = function(what) {
if (!this.isWindowsPhoneApp) return
if (what && what == 'my-name') {
this.hideWalletName = true;
this.hideTabs = true;
} else if (what && what == 'wallet-name') {
this.hideTabs = true;
} else {
this.hideWalletName = false;
this.hideTabs = false;
}
$timeout(function() {
$rootScope.$digest();
}, 1);
};
$scope.$on("$destroy", function() {
$rootScope.hideWalletNavigation = false;
});
updateSeedSourceSelect(1);
self.setSeedSource();
});
| JavaScript | 0.000004 | @@ -5146,32 +5146,193 @@
rn;%0A %7D%0A
+ if (self.seedSourceId == 'set') %7B%0A $timeout(function() %7B%0A $rootScope.$emit('Local/BackupDone');%0A %7D, 1);%0A %7D%0A
go.wal
|
1eeb869714fe5412a5fe5a8f2d0a53693067fe0e | Use Sentry/Raven context to include user info | troposphere/static/js/components/SplashScreen.react.js | troposphere/static/js/components/SplashScreen.react.js | import $ from "jquery";
import React from "react";
import ReactDOM from "react-dom";
import context from "context";
import stores from "stores";
import Router from "../Router";
import routes from "../AppRoutes.react";
export default React.createClass({
displayName: "SplashScreen",
//
// Mounting & State
// ----------------
//
getInitialState: function() {
return {
profile: stores.ProfileStore.get(),
instances: stores.InstanceStore.getAll(),
volumes: stores.VolumeStore.getAll()
};
},
updateState: function() {
var profile = stores.ProfileStore.get(),
instances = stores.InstanceStore.getAll(),
volumes = stores.VolumeStore.getAll(),
isEmulatedUser;
if (profile && instances && volumes) {
// set user context
context.profile = profile;
//context.nullProject = nullProject;
// if the emulator token exists, the user is being emulated by staff
// in that case, this doesn't count as a real session, so don't report
// it to Intercom.
isEmulatedUser = !!window.emulator_token;
if (!isEmulatedUser) {
window.Intercom("boot", {
app_id: window.intercom_app_id,
name: profile.get("username"),
username: profile.get("username"),
email: profile.get("email"),
company: {
id: window.intercom_company_id,
name: window.intercom_company_name
}
// TODO: The current logged in user's sign-up date as a Unix timestamp.
//created_at: 1234567890
});
}
this.startApplication();
}
},
componentDidMount: function() {
stores.ProfileStore.addChangeListener(this.updateState);
stores.InstanceStore.addChangeListener(this.updateState);
stores.VolumeStore.addChangeListener(this.updateState);
},
componentWillUnmount: function() {
stores.ProfileStore.removeChangeListener(this.updateState);
stores.InstanceStore.removeChangeListener(this.updateState);
stores.VolumeStore.removeChangeListener(this.updateState);
},
startApplication: function() {
$("body").removeClass("splash-screen");
// Start the application router
Router.getInstance(routes).run(function(Handler, state) {
// you might want to push the state of the router to a store for whatever reason
// RouterActions.routeChange({routerState: state});
// Update intercom so users get any messages sent to them
window.Intercom("update");
// whenever the url changes, this callback is called again
ReactDOM.render(<Handler/>, document.getElementById("application"));
});
},
render: function() {
return null;
}
});
| JavaScript | 0 | @@ -212,16 +212,47 @@
eact%22;%0A%0A
+import Raven from %22raven-js%22;%0A%0A
export d
@@ -1845,16 +1845,332 @@
%7D%0A%0A
+ if (Raven && Raven.isSetup())%7B%0A Raven.setUserContext(%7B%0A id: profile.get(%22user%22),%0A name: profile.get(%22username%22),%0A email: profile.get(%22email%22),%0A username: profile.get(%22username%22)%0A %7D);%0A %7D%0A%0A
|
d09c3e12cb680e25010acb8d09e69a97ad5649d5 | Fix allowed strings | src/languages/applescript.js | src/languages/applescript.js | /*
Language: AppleScript
Authors: Nathan Grigg <nathan@nathanamy.org>
Dr. Drang <drdrang@gmail.com>
*/
function(hljs) {
var STRINGS = [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE
];
var TITLE = {
className: 'title', begin: hljs.UNDERSCORE_IDENT_RE
};
var PARAMS = {
className: 'params',
begin: '\\(', end: '\\)',
contains: ['self', hljs.C_NUMBER_MODE].concat(STRINGS)
};
return {
defaultMode: {
keywords: {
keyword:
'about above after against and around as at back before beginning ' +
'behind below beneath beside between but by considering contain ' +
'contain contains continue copy div does eighth else end equal ' +
'equals error every exit fifth first for fourth from front ' +
'get given global if ignoring in into is it its last local ' +
'middle mod ninth not of on onto or over prop property put ref ' +
'reference repeat return returning script second set seventh since ' +
'since sixth some tell tenth that the then third through thru ' +
'timeout times to transaction try until where while whose with ' +
'without',
built_in:
'true false me my'
},
contains: [
hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: ''}),
hljs.HASH_COMMENT_MODE,
{
className: 'comment',
begin: '--', end: '$'
},
{
className: 'comment',
begin: '\\(\\*', end: '\\*\\)'
},
hljs.C_NUMBER_MODE,
{
className: 'function_start',
beginWithKeyword: true,
keywords: 'on',
illegal: '[${=;\\n]',
contains: [TITLE, PARAMS]
},
{
className: 'unix',
begin: 'do shell script|quoted form|POSIX path',
},
{
className: 'ui',
begin: 'display dialog|display alert|choose from list|' +
'choose file|choose folder|choose color',
}
]
}
};
}
| JavaScript | 0 | @@ -154,30 +154,16 @@
ljs.
-APOS_STRING_MODE,%0A
+inherit(
hljs
@@ -180,16 +180,32 @@
ING_MODE
+, %7Billegal: ''%7D)
%0A %5D;%0A
@@ -1272,69 +1272,8 @@
: %5B%0A
- hljs.inherit(hljs.QUOTE_STRING_MODE, %7Billegal: ''%7D),%0A
@@ -1985,16 +1985,32 @@
%0A %5D
+.concat(STRINGS)
%0A %7D%0A
|
641c67da264466fbe2013edf091c6701c53b127b | fix get element message through class | client/js/app/controllers/NegotiationController.js | client/js/app/controllers/NegotiationController.js | class NegotiationController {
constructor() {
const $ = document.querySelector.bind(document);
// avoid traversing the DOM many times
this._amount = $('#amount')
this._date = $('#date')
this._value = $('#value')
this._negotiationsList = new NegotiationList();
this._negotiatioView = new NegotiationView();
this._message = new Message();
this._messageView = new MessageView('#message');
}
add(event) {
event.preventDefault();
const negotiation = this._createNegotiation();
this._negotiationsList.add(negotiation);
this._negotiatioView.update(negotiation)
this._message.text = 'Negotiation saves successfully';
this._messageView.update(this._message);
this._cleanForm();
}
_cleanForm() {
this._amount.value = 1;
this._date.value = '';
this._value.value = 0.0
this._date.focus();
}
_createNegotiation() {
return new Negotiation(
DateHelper.stringToDate(this._date.value),
this._amount.value,
this._value.value
);
}
}
| JavaScript | 0.000001 | @@ -407,18 +407,20 @@
ageView(
-'#
+$('.
message'
@@ -420,16 +420,17 @@
essage')
+)
;%0A %7D%0A%0A
|
3c9e3c2f67f8223f6252d33de62906cd289f9f56 | Make eslint happy | client/tests/end2end/protractor-coverage.config.js | client/tests/end2end/protractor-coverage.config.js | var fs = require('fs');
var specs = JSON.parse(fs.readFileSync('tests/end2end/specs.json'));
var tmp = [];
for (var i=0; i<specs.length; i++) {
tmp.push('tests/end2end/' + specs[i]);
}
specs = tmp;
console.log(specs);
var q = require("q");
var FirefoxProfile = require("firefox-profile");
var makeFirefoxProfile = function(preferenceMap) {
var deferred = q.defer();
var firefoxProfile = new FirefoxProfile();
for (var key in preferenceMap) {
if (preferenceMap.hasOwnProperty(key)) {
firefoxProfile.setPreference(key, preferenceMap[key]);
}
}
firefoxProfile.encoded(function (encodedProfile) {
var capabilities = {
browserName: 'firefox',
firefox_profile: encodedProfile,
};
deferred.resolve(capabilities);
});
return deferred.promise;
};
// The test directory for downloaded files
var tmpDir = '/tmp/';
exports.config = {
framework: 'jasmine',
baseUrl: 'http://127.0.0.1:8082/',
troubleshoot: true,
directConnect: true,
params: {
'testFileDownload': true,
'tmpDir': tmpDir
},
specs: specs,
getMultiCapabilities: function() {
return q.all([
makeFirefoxProfile({
"browser.download.folderList": 2,
// One of these does the job
"browser.download.dir": tmpDir,
"browser.download.defaultFolder": tmpDir,
"browser.download.downloadDir": tmpDir,
"browser.helperApps.neverAsk.saveToDisk": "application/octet-stream"
})
]);
},
jasmineNodeOpts: {
isVerbose: true,
includeStackTrace: true,
defaultTimeoutInterval: 180000
}
};
| JavaScript | 0.000034 | @@ -200,29 +200,8 @@
p;%0A%0A
-console.log(specs);%0A%0A
var
|
93db013f447ea4fb3655ec2b0c06902ab2d582af | define variables with const | src/post/postsReducers.js | src/post/postsReducers.js | import * as feedTypes from '../feed/feedActions';
import * as bookmarksActions from '../bookmarks/bookmarksActions';
import * as postsActions from './postActions';
const postItem = (state = {}, action) => {
switch (action.type) {
case postsActions.LIKE_POST_START:
let optimisticActiveVotes = [];
let optimisticNetVotes = 0;
optimisticActiveVotes = [
...state.active_votes.filter(vote => vote.voter !== action.meta.voter),
{
voter: action.meta.voter,
percent: action.meta.weight,
},
];
optimisticNetVotes = action.meta.weight > 0
? parseInt(state.net_votes) + 1
: parseInt(state.net_votes) - 1;
return {
...state,
active_votes: optimisticActiveVotes,
net_votes: optimisticNetVotes,
};
default:
return state;
}
};
const posts = (state = {}, action) => {
switch (action.type) {
case feedTypes.GET_FEED_CONTENT_SUCCESS:
case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
case bookmarksActions.GET_BOOKMARKS_SUCCESS:
const posts = {};
action.payload.postsData.forEach(post => posts[post.id] = post);
return {
...state,
...posts,
};
case postsActions.GET_CONTENT_SUCCESS:
return {
...state,
[action.payload.id]: {
...state[action.payload.id],
...action.payload,
},
};
case postsActions.LIKE_POST_START:
return {
...state,
[action.meta.postId]: postItem(state[action.meta.postId], action),
};
default:
return state;
}
};
export default posts;
| JavaScript | 0.000006 | @@ -275,80 +275,13 @@
-let optimisticActiveVotes = %5B%5D;%0A let optimisticNetVotes = 0;%0A%0A
+const
opt
@@ -494,16 +494,22 @@
;%0A
+const
optimist
|
d943891ae0ba6ecd42626e5210634b591dbcc61f | handle porn | extension/httpd/app.js | extension/httpd/app.js | 'use strict';
const express = require('express');
const https = require('https');
const forge = require('node-forge');
const port = 8000;
const httpsPort = 443;
const app = express();
const enableHttps = false;
const enableRedis = false;
/*
if (enableRedis) {
const promise = require('bluebird');
const redis = require('redis');
const client = redis.createClient();
promise.promisifyAll(redis.RedisClient.prototype);
}
*/
const viewsPath = 'firewalla_views';
app.engine('pug', require('pug').__express);
app.set('views', './firewalla_views');
app.set('view engine', 'pug');
function isMalware(dn) {
return true;
}
function isPorn(dn) {
return true;
}
let router = express.Router();
router.all('/porn', (req, res) => {
console.info("Got a request in porn views");
let message = `Porn Blocked by Firewalla: ${req.ip} => ${req.method}: ${req.hostname}${req.originalUrl}`;
res.render('green', {message});
})
app.use(`/${viewsPath}`, router);
app.use('*', (req, res) => {
console.info("Got a request in *");
if (!req.originalUrl.includes(viewsPath)) {
if (isPorn(req.hostname)) {
res.status(303).location(`/${viewsPath}/porn?url=${req.originalUrl}`).send().end();
return;
}
}
if (enableRedis) {
client.hincrbyAsync('block:stats', 'adblock', 1).then(value => {
console.log(`${txt}, Total blocked: ${value}`);
});
}
});
app.listen(port, () => console.log(`Httpd listening on port ${port}!`));
if (enableHttps) {
const httpsOptions = genHttpsOptions();
https.createServer(httpsOptions, app).listen(httpsPort, () => console.log(`Httpd listening on port ${httpsPort}!`));
}
function genHttpsOptions() {
// generate a keypair and create an X.509v3 certificate
const pki = forge.pki;
console.log('Generating 1024-bit key-pair...');
const keys = pki.rsa.generateKeyPair(1024);
console.log('Key-pair created.');
console.log('Creating self-signed certificate...');
const cert = pki.createCertificate();
cert.publicKey = keys.publicKey;
cert.serialNumber = '01';
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
let attrs = [{
name: 'commonName',
value: 'blackhole.firewalla.com'
}, {
name: 'countryName',
value: 'US'
}, {
shortName: 'ST',
value: 'New York'
}, {
name: 'localityName',
value: 'Brooklyn'
}, {
name: 'organizationName',
value: 'BLACKHOLE'
}, {
shortName: 'OU',
value: 'BLACKHOLE'
}];
cert.setSubject(attrs);
cert.setIssuer(attrs);
cert.setExtensions([{
name: 'basicConstraints',
cA: true/*,
pathLenConstraint: 4*/
}, {
name: 'keyUsage',
keyCertSign: true,
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true
}, {
name: 'extKeyUsage',
serverAuth: true,
clientAuth: true,
codeSigning: true,
emailProtection: true,
timeStamping: true
}, {
name: 'nsCertType',
client: true,
server: true,
email: true,
objsign: true,
sslCA: true,
emailCA: true,
objCA: true
}]);
cert.sign(keys.privateKey);
console.log('Certificate created.');
return {
key: pki.privateKeyToPem(keys.privateKey),
cert: pki.certificateToPem(cert)
};
} | JavaScript | 0 | @@ -112,16 +112,88 @@
forge');
+%0Aconst qs = require('querystring');%0Aconst intel = require('./intel.js');
%0A%0Aconst
@@ -201,18 +201,16 @@
ort = 80
-00
;%0Aconst
@@ -655,91 +655,8 @@
);%0A%0A
-function isMalware(dn) %7B%0A return true;%0A%7D%0A%0Afunction isPorn(dn) %7B%0A return true;%0A%7D%0A%0A
let
@@ -696,19 +696,20 @@
r.all('/
-por
+gree
n', (req
@@ -730,187 +730,224 @@
cons
-ole.info(%22Got a request in porn views%22);%0A let message = %60Porn Blocked by Firewalla: $%7Breq.ip%7D =%3E $%7Breq.method%7D: $%7Breq.hostname%7D$%7Breq.originalUrl%7D%60;%0A res.render('green', %7Bmessage
+t hostname = req.hostname;%0A const url = qs.unescape(req.query.url);%0A const ip = req.ip;%0A const method = req.method;%0A%0A console.info(%22Got a request in porn views%22);%0A%0A res.render('green', %7Bhostname, url, ip, method
%7D);%0A
@@ -1107,36 +1107,85 @@
-if (isPorn(req.hostname)) %7B%0A
+let cat = intel.check(req.hostname);%0A%0A switch(cat) %7B%0A case 'porn':%0A
@@ -1230,19 +1230,35 @@
th%7D/
-porn?url=$%7B
+green?$%7Bqs.stringify(%7Burl:
req.
@@ -1269,16 +1269,18 @@
inalUrl%7D
+)%7D
%60).send(
@@ -1294,22 +1294,279 @@
;%0A
+
-return
+ break;%0A case 'ad':%0A if (enableRedis) %7B%0A client.hincrbyAsync('block:stats', 'adblock', 1).then(value =%3E %7B%0A console.log(%60$%7Btxt%7D, Total blocked: $%7Bvalue%7D%60);%0A %7D);%0A %7D%0A default:%0A res.status(200).send().end()
;%0A %7D%0A
@@ -3688,8 +3688,9 @@
)%0A %7D;%0A%7D
+%0A
|
1aec000ce35ca8d5f1becc4c9f7f25438d2ea857 | Switch from for-in to forEach in WADO-RS loadImage because it was iterating over other Array properties | src/imageLoader/wadors/loadImage.js | src/imageLoader/wadors/loadImage.js | import metaDataManager from './metaDataManager.js';
import getPixelData from './getPixelData.js';
import createImage from '../createImage.js';
/**
* Helper method to extract the transfer-syntax from the response of the server.
* @param {string} contentType The value of the content-type header as returned by the WADO-RS server.
* @return The transfer-syntax as announced by the server, or Implicit Little Endian by default.
*/
export function getTransferSyntaxForContentType (contentType) {
let transferSyntax = '1.2.840.10008.1.2'; // Default is Implicit Little Endian.
if (contentType) {
// Browse through the content type parameters
const parameters = contentType.split(';');
for (const parameterIndex in parameters) {
const parameter = parameters[parameterIndex];
// Look for a transfer-syntax=XXXX pair
const parameterValues = parameter.split('=');
if (parameterValues.length !== 2) {
continue;
}
if (parameterValues[0].trim() === 'transfer-syntax') {
transferSyntax = parameterValues[1].trim() || transferSyntax;
}
}
}
return transferSyntax;
}
function loadImage (imageId, options) {
const start = new Date().getTime();
const uri = imageId.substring(7);
const promise = new Promise((resolve, reject) => {
// check to make sure we have metadata for this imageId
const metaData = metaDataManager.get(imageId);
if (metaData === undefined) {
const error = new Error(`no metadata for imageId ${imageId}`);
return reject(error);
}
// TODO: load bulk data items that we might need
const mediaType = 'multipart/related; type="application/octet-stream"'; // 'image/dicom+jp2';
// get the pixel data from the server
getPixelData(uri, imageId, mediaType).then((result) => {
const transferSyntax = getTransferSyntaxForContentType(result.contentType);
const pixelData = result.imageFrame.pixelData;
const imagePromise = createImage(imageId, pixelData, transferSyntax, options);
imagePromise.then((image) => {
// add the loadTimeInMS property
const end = new Date().getTime();
image.loadTimeInMS = end - start;
resolve(image);
}, reject);
}, reject);
});
return {
promise,
cancelFn: undefined
};
}
export default loadImage;
| JavaScript | 0 | @@ -700,103 +700,41 @@
-for (const parameterIndex in parameters) %7B%0A const parameter = parameters%5BparameterIndex%5D;%0A
+parameters.forEach(parameter =%3E %7B
%0A
@@ -883,16 +883,14 @@
-continue
+return
;%0A
@@ -1035,21 +1035,23 @@
%7D%0A
-
%7D
+);
%0A %7D%0A%0A
|
c4ec316c36efd2586694ff9e7b1feb6bf8b4a656 | Add documentation. | graphql/database/users/rewardReferringUser.js | graphql/database/users/rewardReferringUser.js |
import UserModel from './UserModel'
import {
USER_REFERRAL_VC_REWARD
} from '../constants'
import {
getPermissionsOverride
} from '../../utils/authorization-helpers'
const rewardReferringUser = async (referringUserId) => {
const permissionsOverride = getPermissionsOverride()
await UserModel.addVc(permissionsOverride, referringUserId,
USER_REFERRAL_VC_REWARD)
}
export default rewardReferringUser
| JavaScript | 0 | @@ -165,16 +165,216 @@
lpers'%0A%0A
+/**%0A * Reward a referring user by increasing their VC.%0A * @param %7Bstring%7D referringUserId - The ID of the referring user.%0A * @return %7BPromise%3CUser%3E%7D A promise that resolves into a User instance.%0A */%0A
const re
|
e952564d5d1ad46b6e93b52e588cb7f2e4b7b5ca | Update to title filter | tipple-1.0.js | tipple-1.0.js | /**
*
* _||_
* | |
* | |
* | | Tipple
* |~~~~|
* |_--_| =]
*
*
* Tipple is a simple JS templating solution.
*
*
* @author Devin Ivy
* @email devin@bigroomstudios.com
* @website http://devinivy.com
*
* @dependency jQuery 1.7+
* @version 1.0
*
* @license MIT
* @enjoy
*
*/
(function ($) {
$.extend({tplFilters: {
html: function (content) {
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
return String(content).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
},
attr: function (content) {
var entityMap = {
'"': '"',
"'": ''',
};
return String(content).replace(/["']/g, function (s) {
return entityMap[s];
});
},
url: function (content) {
content = String(content);
return encodeURI(content);
},
nl2br: function (content) {
return String(content).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');
},
currency : function (content) {
content = Number(content).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
return (content == 'NaN') ? '' : content;
},
upper: function (content) {
return String(content).toUpperCase();
},
lower: function (content) {
return String(content).toLowerCase();
},
title: function (content) {
content = String(content).replace(/[^-'\s]+/g, function(word) {
return word.replace(/^./, function(first) {
return first.toUpperCase();
});
});
return content;
}
}});
$.fn.tipple = function (replacements, justReturn) {
// when sent null, current active tipples matching the selector are cleared
if (replacements === null) {
this.each(function(i, item){
var tmpspawn;
var spawn = $(item).prev('[tpl-a]');
while (spawn.length) {
tmpspawn = $(spawn).prev('[tpl-a]');
spawn.remove();
spawn = tmpspawn;
}
});
return this;
// otherwise, we create some active tipples with the replacements
} else {
justReturn = justReturn || false;
var regex, matches;
var origs = this.filter('[tpl], [tpl-each]');
var clone = origs.first().clone().removeAttr('tpl tpl-each');
var attribs = ['src'];
// making the proper replacements
var newHTML = clone.html() || '';
var content;
for (var name in replacements) {
// allow content to be passed as a jQuery object
content = replacements[name];
if (content instanceof jQuery) {
if (content.length) {
content = content[0].outerHTML;
} else {
content = '';
}
}
regex = new RegExp('{[\\s]*(' +
name.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') +
')[\\s]*(|[^}:]+)?(:[^}]+)?}', 'g');
// apply filters
newHTML = newHTML.replace(regex, function(m, n, filters, dfault) {
if (dfault) {
dfault = String(dfault).substring(1).trim();
} else {
dfault = '';
}
if (filters) {
filters = filters.substring(1).split('|');
var filter;
var tmpContent = content;
for (var i = 0; i < filters.length; i++) {
filter = String(filters[i]).trim();
tmpContent = $.tplFilters[filter](tmpContent);
}
return tmpContent ? tmpContent : dfault;
} else {
return content ? content : dfault;
}
});
}
clone.html(newHTML);
// set special attributes, like tpl-src to src. this prevents unwanted requests.
var attrib;
for (var j = 0; j < attribs.length; j++) {
attrib = attribs[j];
clone.find('[tpl-' + attrib + ']').each(function (i, subtpl) {
subtpl = $(subtpl);
subtpl.attr(attrib, subtpl.attr('tpl-' + attrib)).removeAttr('tpl-' + attrib);
});
}
// if you dont just want the tipple clone returned, insert it.
if (!justReturn) {
origs.each(function (i, orig) {
if ($(orig).is('[tpl]')) {
$(orig).tipple(null);
}
clone.attr('tpl-a','').insertBefore(orig);
});
}
return clone;
}
}
})(jQuery);
| JavaScript | 0 | @@ -2224,17 +2224,16 @@
ace(/%5B%5E-
-'
%5Cs%5D+/g,
|
a124fa4dcd2174a7f877ac341257b029a7ba1df8 | remove unnecessary typeof method | fluff/_design/views/generic/map.js | fluff/_design/views/generic/map.js | function (doc) {
function typeOf(value) {
// from Crockford himself: http://javascript.crockford.com/remedial.html
var s = typeof value;
if (s === 'object') {
if (value) {
if (Object.prototype.toString.call(value) == '[object Array]') {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
}
var excludes = ['group_by_type_map'];
if (doc.base_doc === 'IndicatorDocument') {
var key = [doc.doc_type], i;
for (i = 0; i < doc.group_by.length; i++) {
key.push(doc[doc.group_by[i]]);
}
for (var calcName in doc) {
if (excludes.indexOf(calcName) === -1 && doc.hasOwnProperty(calcName)) {
// isObject(doc[calcName])
if (Object.prototype.toString.call(doc[calcName]) === '[object Object]') {
for (var emitterName in doc[calcName]) {
if (doc[calcName].hasOwnProperty(emitterName)) {
for (i = 0; i < doc[calcName][emitterName].length; i++) {
var value = doc[calcName][emitterName][i];
if (typeOf(value) === 'object') {
var custom_key = value['group_by'];
key = custom_key === null ? key : custom_key;
emit(key.concat([calcName, emitterName, value['date']]), value['value']);
} else {
emit(key.concat([calcName, emitterName, value[0]]), value[1]);
}
}
}
}
}
}
}
}
}
| JavaScript | 0.011711 | @@ -14,433 +14,8 @@
) %7B%0A
- function typeOf(value) %7B%0A // from Crockford himself: http://javascript.crockford.com/remedial.html%0A var s = typeof value;%0A if (s === 'object') %7B%0A if (value) %7B%0A if (Object.prototype.toString.call(value) == '%5Bobject Array%5D') %7B%0A s = 'array';%0A %7D%0A %7D else %7B%0A s = 'null';%0A %7D%0A %7D%0A return s;%0A %7D%0A%0A
@@ -833,14 +833,38 @@
if (
-typeOf
+Object.prototype.toString.call
(val
@@ -872,22 +872,31 @@
e) === '
+%5B
object
+ Object%5D
') %7B%0A
|
d4102ccf676e9dc7b6576b910384f39b5ec549f7 | Add TODOs. | tools/dist.js | tools/dist.js | #!/usr/bin/env node
/*!
* Chameleon
*
* Copyright 2014 ghostwords.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
var moment = require('moment'),
shell = require('shelljs');
var package_name = [
'chameleon',
require('../chrome/manifest.json').version,
moment().format('YYYY-MM-DD')
].join('_');
// copy chrome/** to dist/
shell.cp('-R', 'chrome/**', 'dist/' + package_name);
// create the package
shell.exit(shell.exec(
'cd dist && ../tools/crxmake.sh ' + package_name + ' ~/.ssh/chameleon.pem'
).code);
| JavaScript | 0 | @@ -559,16 +559,46 @@
ate the
+drag-and-drop installable CRX
package%0A
@@ -701,12 +701,500 @@
m'%0A).code);%0A
+%0A// TODO create the zip for uploading to Chrome Web Store%0A// TODO make this is the %22release%22 task (also tags, ...)%0A// https://developer.chrome.com/extensions/packaging%0A// 1. Rename the private key that was generated when you created the .crx file to key.pem.%0A// 2. Put key.pem in the top directory of your extension.%0A// 3. Compress that directory into a ZIP file.%0A// 4. Upload the ZIP file using the Chrome Developer Dashboard.%0A// TODO No need to do the key.pem thing for updates, right?%0A
|
f2e9dad09b45dc33a1e4ad6e276ca6a574b09936 | Add a guid to drawn annotations | web_client/views/imageViewerWidget/geojs.js | web_client/views/imageViewerWidget/geojs.js | import _ from 'underscore';
import Backbone from 'backbone';
import { staticRoot } from 'girder/rest';
import events from 'girder/events';
import ImageViewerWidget from './base';
import convertAnnotation from '../../annotations/geojs/convert';
var GeojsImageViewerWidget = ImageViewerWidget.extend({
initialize: function (settings) {
ImageViewerWidget.prototype.initialize.call(this, settings);
this._layers = {};
this.listenTo(events, 's:widgetDrawRegion', this.drawRegion);
this.listenTo(events, 'g:startDrawMode', this.startDrawMode);
$.getScript(
staticRoot + '/built/plugins/large_image/extra/geojs.js',
() => this.render()
);
},
render: function () {
// If script or metadata isn't loaded, then abort
if (!window.geo || !this.tileWidth || !this.tileHeight) {
return;
}
this._destroyViewer();
var geo = window.geo; // this makes the style checker happy
var w = this.sizeX, h = this.sizeY;
var params = geo.util.pixelCoordinateParams(
this.el, w, h, this.tileWidth, this.tileHeight);
params.layer.useCredentials = true;
params.layer.url = this._getTileUrl('{z}', '{x}', '{y}');
this.viewer = geo.map(params.map);
this.viewer.createLayer('osm', params.layer);
this.trigger('g:imageRendered', this);
return this;
},
destroy: function () {
this._destroyViewer();
if (window.geo) {
delete window.geo;
}
ImageViewerWidget.prototype.destroy.call(this);
},
_destroyViewer: function () {
if (this.viewer) {
this.viewer.exit();
this.viewer = null;
}
},
/**
* Render an annotation model on the image. Currently,
* this is limited to annotation types that can be directly
* converted into geojson primatives.
*
* Internally, this generates a new feature layer for the
* annotation that is referenced by the annotation id.
* All "elements" contained inside this annotations are
* drawn in the referenced layer.
*
* @param {AnnotationModel} annotation
*/
drawAnnotation: function (annotation) {
var geojson = annotation.geojson();
var layer = this.viewer.createLayer('feature', {
features: ['point', 'line', 'polygon']
});
this._layers[annotation.id] = layer;
window.geo.createFileReader('jsonReader', {layer})
.read(geojson, () => this.viewer.draw());
},
/**
* Remove an annotation from the image. This simply
* finds a layer with the given id and removes it because
* each annotation is contained in its own layer. If
* the annotation is not drawn, this is a noop.
*/
removeAnnotation: function (annotation) {
var layer = this._layers[annotation.id];
if (layer) {
this.viewer.deleteLayer(layer);
}
},
/**
* Set the image interaction mode to region drawing mode. This
* method takes an optional `model` argument where the region will
* be stored when created by the user. In any case, this method
* returns a promise that resolves to an array defining the region:
* [ left, top, width, height ]
*
* @param {Backbone.Model} [model] A model to set the region to
* @returns {Promise}
*/
drawRegion: function (model) {
model = model || new Backbone.Model();
return this.startDrawMode('rectangle', {trigger: false}).then((elements) => {
/*
* Strictly speaking, the rectangle drawn here could be rotated, but
* for simplicity we will set the region model assuming it is not.
* To be more precise, we could expand the region to contain the
* whole rotated rectangle. A better solution would be to add
* a draw parameter to geojs that draws a rectangle aligned with
* the image coordinates.
*/
var element = elements[0];
var width = Math.round(element.width);
var height = Math.round(element.height);
var left = Math.round(element.center[0] - element.width / 2);
var top = Math.round(element.center[1] - element.height / 2);
model.set('value', [
left, top, width, height
], {trigger: true});
return model.get('value');
});
},
/**
* Set the image interaction mode to draw the given type of annotation.
*
* @param {string} type An annotation type
* @param {object} [options]
* @param {boolean} [options.trigger=true]
* Trigger a global event after creating each annotation element.
* @returns {Promise}
* Resolves to an array of generated annotation elements.
*/
startDrawMode: function (type, options) {
var layer;
var elements = [];
var annotations = [];
return new Promise((resolve) => {
var element;
options = _.defaults(options || {}, {trigger: true});
layer = this.viewer.createLayer('annotation');
layer.geoOn(
window.geo.event.annotation.state,
(evt) => {
element = convertAnnotation(evt.annotation);
elements.push(element);
annotations.push(evt.annotation);
if (options.trigger) {
events.trigger('g:annotationCreated', element, evt.annotation);
}
resolve(elements, annotations);
// defer deleting the layer because geojs calls draw on it
// after triggering this event
window.setTimeout(() => this.viewer.deleteLayer(layer), 10);
}
);
layer.mode(type);
});
}
});
export default GeojsImageViewerWidget;
| JavaScript | 0 | @@ -240,16 +240,271 @@
vert';%0A%0A
+function guid() %7B%0A function s4() %7B%0A return Math.floor((1 + Math.random()) * 0x10000)%0A .toString(16)%0A .substring(1);%0A %7D%0A return s4() + s4() + '-' + s4() + '-' + s4() + '-' +%0A s4() + '-' + s4() + s4() + s4();%0A%7D%0A%0A
var Geoj
@@ -5669,32 +5669,138 @@
vt.annotation);%0A
+ if (!element.id) %7B%0A element.id = guid();%0A %7D%0A
|
83bbe0dae4d33c009959eaece2c304dcca26a780 | load jquery before plugins | webapps/client/scripts/cockpit-bootstrap.js | webapps/client/scripts/cockpit-bootstrap.js | (function(document, window, require) {
'use strict';
var baseUrl = document.getElementsByTagName('base')[0].getAttribute('app-root') +'/';
var APP_NAME = 'cam.cockpit';
baseUrl += 'app/cockpit/';
var pluginPackages = window.PLUGIN_PACKAGES || [];
require({
baseUrl: baseUrl + 'assets/vendor', // for dojo
packages: pluginPackages
});
var pluginDependencies = window.PLUGIN_DEPENDENCIES || [];
var dependencies = [
'angular',
'angular-resource',
'angular-sanitize',
'angular-ui',
'ngDefine',
'jquery-ui/ui/jquery.ui.draggable']
.concat(pluginDependencies.map(function(plugin) {
return plugin.requirePackageName;
}));
require(dependencies, function(angular) {
require([
'camunda-cockpit-ui',
'domReady!'
], function() {
angular.bootstrap(document, [ APP_NAME ]);
var html = document.getElementsByTagName('html')[0];
html.setAttribute('ng-app', APP_NAME);
if (html.dataset) {
html.dataset.ngApp = APP_NAME;
}
if (top !== window) {
window.parent.postMessage({ type: 'loadamd' }, '*');
}
});
});
})(document, window || this, require);
| JavaScript | 0.000013 | @@ -550,24 +550,40 @@
'ngDefine',%0A
+ 'jquery',%0A
'jquer
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.