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 |
|---|---|---|---|---|---|---|---|
e1ba5f4d38f559bb4fb50eac371e2edb3615c276 | Add varaibles | src/config/theme.js | src/config/theme.js | module.exports = module.exports.default = {
primary: '#e44a49',
primaryLight: '#e44a49',
primaryDark: '#e44a49',
primaryDarkest: '#e44a49',
textPrimary: 'rgba(255,255,255, 1)',
textSecondary: 'rgba(255,255,255, 0.7)',
textDisabled: 'rgba(255,255,255, 0.5)',
divider: 'rgba(255,255,255, 0.12)',
// Board
board: 'hsl(0, 0%, 16%)',
}
| JavaScript | 0 | @@ -48,26 +48,34 @@
primary
-: '#e44a49
+Lightest: '#eca8a7
',%0A p
@@ -86,16 +86,40 @@
ryLight:
+ '#e77a79',%0A primary:
'#e44a4
@@ -138,29 +138,29 @@
aryDark: '#e
-44a49
+01b1a
',%0A prima
@@ -172,23 +172,169 @@
kest: '#
-e44a49'
+b71110',%0A%0A greyLightest: %22#45403e%22,%0A greyLight: %22#35302e%22,%0A grey: %22#2e2927%22,%0A greyDark: %22#26211f%22,%0A greyDarkest: %22#1f1a18%22
,%0A%0A t
@@ -507,45 +507,614 @@
-// Board%0A board: 'hsl(0, 0%25, 16%25)',%0A%7D
+board: '#2e2927', // hsl(0, 0%25, 16%25) warm-tint%0A boardSearchbar: '#3e3636',%0A boardPostBackground: '#26211f', // hsl(0, 0%25, 13%25) warm-tint%0A boardPostShadow: '#312d2b', // HOOK%0A%0A threadPostBackground: '#2e2927', // hsl(0, 0%25, 16%25) warm-tint%0A%0A postHighlight: '#402c2a', // mix($primary, grey(7), 10%25)%0A%0A textSelectionBackground: '#e44a49', // $primary%0A textSelectionColor: '#f4b6b6', // lighten($primary, 60%25)%0A%0A contentBorder: '#2e2927', // hsl(0, 0%25, 16%25) warm-tint%0A%7D%0A%0A%0A// warm-tint: adjust-color($color, $red: +5, $blue: -2);%0A// cold-tint: adjust-color($color, $red: -2, $blue: +5);
%0A
|
2d8b5dc24fdc677d634edb9ae24f35cdcc8d9aa6 | Revert "Count filtered r/all as a fake subreddit" | src/lib/isFakeSubreddit.es6.js | src/lib/isFakeSubreddit.es6.js | const randomSubs = ['random', 'randnsfw', 'myrandom'];
const fakeSubs = ['all', 'mod', 'friends'].concat(randomSubs);
export { fakeSubs, randomSubs };
export default function isFakeSubreddit(subredditName) {
return !!subredditName && (
subredditName.indexOf('+') > -1 ||
subredditName.indexOf('-') > -1 ||
fakeSubs.includes(subredditName)
);
}
| JavaScript | 0 | @@ -232,21 +232,16 @@
ame && (
-%0A
subreddi
@@ -270,51 +270,8 @@
1 %7C%7C
-%0A subredditName.indexOf('-') %3E -1 %7C%7C%0A
fak
@@ -299,16 +299,13 @@
ditName)
-%0A
);%0A%7D%0A
|
e41d9c5a7872772369cf455ba29a84ad8bb5c646 | Improve doc warning | src/lib/shadowtree/function.js | src/lib/shadowtree/function.js | import Declaration from "./declaration"
import Parameter from "./parameter"
import Block from "./block"
import Identifier from "./identifier"
import {Context, ContextTypes, Doc, ParserStateOption} from "./node"
import {PHPSimpleType, PHPFunctionType, PHPTypeUnion, WrongType} from "../phptype"
import * as PHPError from "../php-error"
import DocParser from "../doc-parser"
const USE_INTERNAL_DOC_PARSER = true
export default class _Function extends Declaration {
/** @type {Parameter[]} */
get arguments() {
return this.cacheNodeArray("arguments")
}
/** @type {?Block} */
get body() {
return this.cacheNode("body")
}
/** @type {boolean} */
get byref() {
return this.node.byref
}
/** @type {boolean} */
get nullable() {
return this.node.nullable
}
/** @type {Identifier} */
get type() {
return this.node.type
}
/**
* Checks that syntax seems ok
* @param {Context} context
* @param {Set<ParserStateOption.Base>} [parser_state]
* @param {?Doc} [doc]
* @returns {?ContextTypes} The set of types applicable to this value
*/
check(context, parser_state = new Set(), doc = null) {
super.check(context, parser_state, doc)
if(!doc) {
this.throw(new PHPError.NoDoc(), context)
}
let doc_function_type
if(doc) {
let doc_structure
if(USE_INTERNAL_DOC_PARSER) {
doc_structure = new DocParser(doc.lines).top.children
} else {
doc_structure = doc.structure
}
if(doc_structure.some(c => c.kind.match(/^(var|param|return)$/))) {
let structure_arg_types = []
let structure_arg_names = []
let structure_return = null
doc_structure.forEach(
c => {
/**
* @param {string} t
* @returns {string}
*/
let resolve_name = t => {
let md = t.match(/^(.*?)(\[.*)?$/)
let [stem, tail] = [md[1], md[2] || ""]
try {
if(stem.match(/^[A-Z0-9]/)) {
return (
context.fileContext.resolveAliasName(stem) ||
"\\" + stem
) + tail
} else {
return context.resolveName(stem, "uqn") + tail
}
} catch(e) {
if(e instanceof WrongType) {
this.throw(new PHPError.BadDoc(e.message), context, doc.loc)
} else {
throw e
}
}
}
switch(c.kind) {
case "param":
let type = PHPTypeUnion.empty
c.type.name.split(/\|/).forEach(
t => {
type = type.addTypesFrom(
PHPSimpleType.named(resolve_name(t))
)
}
)
structure_arg_types.push(type)
structure_arg_names.push(c.name)
break
case "return":
let rtype = PHPTypeUnion.empty
if(c.what.name) {
c.what.name.split(/\|/).forEach(
t => {
rtype = rtype.addTypesFrom(
PHPSimpleType.named(
resolve_name(t)
)
)
}
)
}
structure_return = rtype
break
case "api":
case "deprecated":
case "example":
case "internal":
case "link":
case "see":
case "throws":
break
default:
console.log(`Skipping ${c.kind}`)
}
}
)
doc_function_type =
new PHPFunctionType(structure_arg_types, structure_return)
}
}
var inner_context = context.childContext()
let arg_types = []
let pass_by_reference_positions = {}
this.arguments.forEach(
(node, index) => {
arg_types.push(node.check(inner_context, parser_state, null).expressionType)
if(node.byref) {
pass_by_reference_positions[index] = true
}
}
)
if(context.findName("$this")) {
inner_context.setThis()
}
let signature_type
if(this.type) {
signature_type = PHPSimpleType.named(context.resolveName(this.type.name, this.type.resolution))
if(this.nullable) {
signature_type = signature_type.addTypesFrom(PHPSimpleType.coreTypes.null)
}
}
let return_type
if(this.body) {
return_type = this.body.check(inner_context, new Set(), null).returnType
if(signature_type && !return_type.compatibleWith(signature_type)) {
this.throw(new PHPError.ReturnTypeMismatch(
`Practical return type ${return_type} does not match signature ${signature_type}`
), context)
}
} else if(signature_type) {
return_type = signature_type
} else {
return_type = PHPSimpleType.coreTypes.mixed
}
let function_type = new PHPFunctionType(
arg_types,
return_type,
pass_by_reference_positions
)
if(
doc_function_type &&
!function_type.compatibleWith(doc_function_type)
) {
this.throw(
new PHPError.BadDoc(
`Documented type ${doc_function_type} does not match actual ${function_type} for ${this.name}`
),
context
)
}
if(context.classContext && context.classContext.name == "\\Slim\\App") {
switch(this.name) {
case "group":
function_type.callbackPositions[1] = PHPSimpleType.named("\\Slim\\App")
break
default:
}
}
let types = function_type.union
if(this.constructor === _Function) {
context.addName(this.name, types)
}
return new ContextTypes(types) // Special case
}
}
| JavaScript | 0 | @@ -4966,16 +4966,41 @@
kipping
+unrecognised PHPDoc tag @
$%7Bc.kind
|
b5dc588e2336a8eaf5313129676b3533d399f985 | remove unused property | ui/js/component/common.js | ui/js/component/common.js | import React from "react";
import { formatCredits, formatFullPrice } from "util/formatCredits";
import lbry from "../lbry.js";
//component/icon.js
export class Icon extends React.PureComponent {
static propTypes = {
icon: React.PropTypes.string.isRequired,
className: React.PropTypes.string,
fixed: React.PropTypes.bool,
};
render() {
const { fixed, className } = this.props;
const spanClassName =
"icon " +
("fixed" in this.props ? "icon-fixed-width " : "") +
this.props.icon +
" " +
(this.props.className || "");
return <span className={spanClassName} />;
}
}
export class TruncatedText extends React.PureComponent {
static propTypes = {
lines: React.PropTypes.number,
};
static defaultProps = {
lines: null,
};
render() {
return (
<span
className="truncated-text"
style={{ WebkitLineClamp: this.props.lines }}
>
{this.props.children}
</span>
);
}
}
export class BusyMessage extends React.PureComponent {
static propTypes = {
message: React.PropTypes.string,
};
render() {
return (
<span>{this.props.message} <span className="busy-indicator" /></span>
);
}
}
export class CurrencySymbol extends React.PureComponent {
render() {
return <span>LBC</span>;
}
}
export class CreditAmount extends React.PureComponent {
static propTypes = {
amount: React.PropTypes.number.isRequired,
precision: React.PropTypes.number,
isEstimate: React.PropTypes.bool,
label: React.PropTypes.bool,
showFree: React.PropTypes.bool,
showFullPrice: React.PropTypes.bool,
showPlus: React.PropTypes.bool,
look: React.PropTypes.oneOf(["indicator", "plain", "fee"]),
fee: React.PropTypes.bool,
};
static defaultProps = {
precision: 2,
label: true,
showFree: false,
look: "indicator",
showFullPrice: false,
showPlus: false,
fee: false,
};
render() {
const minimumRenderableAmount = Math.pow(10, -1 * this.props.precision);
const { amount, precision, showFullPrice } = this.props;
let formattedAmount;
let fullPrice = formatFullPrice(amount, 2);
if (showFullPrice) {
formattedAmount = fullPrice;
} else {
formattedAmount = amount > 0 && amount < minimumRenderableAmount
? "<" + minimumRenderableAmount
: formatCredits(amount, precision);
}
let amountText;
if (this.props.showFree && parseFloat(this.props.amount) === 0) {
amountText = __("free");
} else {
if (this.props.label) {
amountText =
formattedAmount +
" " +
(parseFloat(amount) == 1 ? __("credit") : __("credits"));
} else {
amountText = formattedAmount;
}
if (this.props.showPlus && amount > 0) {
amountText = "+" + amountText;
}
}
return (
<span
className={`credit-amount credit-amount--${this.props.look}`}
title={fullPrice}
>
<span>
{amountText}
</span>
{this.props.isEstimate
? <span
className="credit-amount__estimate"
title={__("This is an estimate and does not include data fees")}
>
*
</span>
: null}
</span>
);
}
}
let addressStyle = {
fontFamily:
'"Consolas", "Lucida Console", "Adobe Source Code Pro", monospace',
};
export class Address extends React.PureComponent {
static propTypes = {
address: React.PropTypes.string,
};
constructor(props) {
super(props);
this._inputElem = null;
}
render() {
return (
<input
className="input-copyable"
type="text"
ref={input => {
this._inputElem = input;
}}
onFocus={() => {
this._inputElem.select();
}}
style={addressStyle}
readOnly="readonly"
value={this.props.address || ""}
/>
);
}
}
export class Thumbnail extends React.PureComponent {
static propTypes = {
src: React.PropTypes.string,
};
handleError() {
if (this.state.imageUrl != this._defaultImageUri) {
this.setState({
imageUri: this._defaultImageUri,
});
}
}
constructor(props) {
super(props);
this._defaultImageUri = lbry.imagePath("default-thumb.svg");
this._maxLoadTime = 10000;
this._isMounted = false;
this.state = {
imageUri: this.props.src || this._defaultImageUri,
};
}
componentDidMount() {
this._isMounted = true;
setTimeout(() => {
if (this._isMounted && !this.refs.img.complete) {
this.setState({
imageUri: this._defaultImageUri,
});
}
}, this._maxLoadTime);
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
const className = this.props.className ? this.props.className : "",
otherProps = Object.assign({}, this.props);
delete otherProps.className;
return (
<img
ref="img"
onError={() => {
this.handleError();
}}
{...otherProps}
className={className}
src={this.state.imageUri}
/>
);
}
}
| JavaScript | 0.000001 | @@ -1744,39 +1744,8 @@
%5D),%0A
- fee: React.PropTypes.bool,%0A
%7D;
@@ -1902,24 +1902,8 @@
se,%0A
- fee: false,%0A
%7D;
|
a27c8c3cc9967944416e8752f54ba64adcfc614b | change rs count | ui/js/controllers/jobs.js | ui/js/controllers/jobs.js | "use strict";
treeherder.controller('JobsCtrl',
function JobsCtrl($scope, $http, $rootScope, $routeParams, $log, $cookies,
localStorageService, thUrl, thRepos, thSocket,
thResultSetModelManager) {
// set the default repo to mozilla-inbound if not specified
if ($routeParams.hasOwnProperty("repo") &&
$routeParams.repo !== "") {
$rootScope.repoName = $routeParams.repo;
} else {
$rootScope.repoName = "mozilla-inbound";
}
// handle the most recent used repos
$rootScope.update_mru_repos = function(repo){
var max_mru_repos_length = 6;
var curr_repo_index = $scope.mru_repos.indexOf($rootScope.repoName);
if( curr_repo_index !== -1){
$scope.mru_repos.splice(curr_repo_index, 1);
}
$scope.mru_repos.unshift($rootScope.repoName);
if($scope.mru_repos.length > max_mru_repos_length){
var old_branch= $scope.mru_repos.pop();
thSocket.emit('subscribe', old_branch+'.job_failure');
$log.debug("subscribing to "+old_branch+'.job_failure');
}
localStorageService.set("mru_repos", $scope.mru_repos);
};
// the primary data model
thResultSetModelManager.init(60000, $scope.repoName);
$scope.result_sets = thResultSetModelManager.getResultSetsArray();
$rootScope.update_mru_repos($rootScope.repoName);
// stop receiving new failures for the current branch
if($rootScope.new_failures.hasOwnProperty($rootScope.repoName)){
delete $rootScope.new_failures[$rootScope.repoName];
}
thRepos.load($scope.repoName);
$scope.isLoadingRsBatch = thResultSetModelManager.loadingStatus;
// load our initial set of resultsets
// scope needs this function so it can be called directly by the user, too.
$scope.fetchResultSets = function(count) {
thResultSetModelManager.fetchResultSets(count);
};
$scope.fetchResultSets(2);
$scope.repo_has_failures = function(repo_name){
if($rootScope.new_failures.hasOwnProperty(repo_name) &&
$rootScope.new_failures[repo_name].length > 0){
return true;
}else{
return false;
}
};
}
);
treeherder.controller('ResultSetCtrl',
function ResultSetCtrl($scope, $rootScope, $http, $log,
thUrl, thServiceDomain, thResultStatusInfo) {
// determine the greatest severity this resultset contains
// so that the UI can depict that
var getMostSevereResultStatus = function(result_types) {
var status = "pending",
rsInfo = thResultStatusInfo(status);
for (var i = 0; i < result_types.length; i++) {
var res = thResultStatusInfo(result_types[i]);
if (res.severity < rsInfo.severity) {
status = result_types[i];
rsInfo = res;
}
}
return {status: status, isCollapsedResults: rsInfo.isCollapsedResults};
};
var severeResultStatus = getMostSevereResultStatus($scope.resultset.result_types);
$scope.$watch('resultset.result_types', function(newVal) {
severeResultStatus = getMostSevereResultStatus($scope.resultset.result_types);
if ($scope.resultSeverity !== severeResultStatus.status) {
$log.debug("updating resultSeverity from " + $scope.resultSeverity + " to " + severeResultStatus.status);
}
$scope.resultSeverity = severeResultStatus.status;
}, true);
$scope.resultSeverity = severeResultStatus.status;
$scope.isCollapsedResults = severeResultStatus.isCollapsedResults;
// whether or not revision list for a resultset is collapsed
$scope.isCollapsedRevisions = true;
$scope.viewJob = function(job) {
// set the selected job
$rootScope.selectedJob = job;
};
$scope.viewLog = function(job_uri) {
// open the logviewer for this job in a new window
// currently, invoked by right-clicking a job.
$http.get(thServiceDomain + job_uri).
success(function(data) {
if (data.hasOwnProperty("artifacts")) {
data.artifacts.forEach(function(artifact) {
if (artifact.name === "Structured Log") {
window.open(thUrl.getLogViewerUrl(artifact.id));
}
});
} else {
$log.warn("Job had no artifacts: " + job_uri);
}
});
};
}
);
| JavaScript | 0.000006 | @@ -2131,9 +2131,10 @@
ets(
-2
+10
);%0A%0A
|
0dbfa012c579569d1c9040de52b8e013354839a8 | fix vat field in transaction form | validators/transaction.js | validators/transaction.js | import Joi from 'joi';
import pluck from 'lodash/collection/pluck';
import dates from '../lib/dates';
import validate from '../lib/validate';
import paymentMethods from '../ui/payment_methods';
/**
* New transaction schema
*/
const schema = Joi.object().keys({
link: Joi.string().uri()
.label('Photo'),
description: Joi.string().required()
.label('Title'),
amount: Joi.number().precision(2).min(0).required()
.label('Amount'),
vat: Joi.number().precision(2).min(0)
.label('VAT'),
createdAt: Joi.date().max(dates().tomorrow).required()
.raw() // doesn't convert date into Date object
.label('Date'),
approvedAt: Joi.date().max(dates().tomorrow)
.raw() // doesn't convert date into Date object
.label('Date'),
tags: Joi.array().items(Joi.string()).required()
.label('Category'),
approved: Joi.boolean(),
paymentMethod: Joi.string().valid(pluck(paymentMethods, 'value'))
.label('Payment method'),
comment: Joi.string()
.label('Comment'),
});
export default (obj) => validate(obj, schema);
| JavaScript | 0 | @@ -482,16 +482,28 @@
).min(0)
+.allow(null)
%0A .la
|
46d1d6065a01defcdf30d3b6b6b9473a1de57b38 | correct terminology | sample-simple/src/RealtimeDatabase.js | sample-simple/src/RealtimeDatabase.js | import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import React, { Suspense, useState } from 'react';
import { useDatabaseList, useDatabaseObject, useUser } from 'reactfire';
const Counter = props => {
const ref = firebase.database().ref('counter');
const increment = amountToIncrement => {
ref.transaction(counterVal => {
return counterVal + amountToIncrement;
});
};
const { snapshot } = useDatabaseObject(ref);
const counterValue = snapshot.val();
return (
<>
<button onClick={() => increment(-1)}>-</button>
<span> {counterValue} </span>
<button onClick={() => increment(1)}>+</button>
</>
);
};
const AnimalEntry = ({ saveAnimal }) => {
const [text, setText] = useState('');
const [disabled, setDisabled] = useState(false);
const onSave = () => {
setDisabled(true);
saveAnimal(text).then(() => {
setText('');
setDisabled(false);
});
};
return (
<>
<input
value={text}
disabled={disabled}
placeholder="Iguana"
onChange={({ target }) => setText(target.value)}
/>
<button onClick={onSave} disabled={disabled || text.length < 3}>
Add new animal
</button>
</>
);
};
const List = props => {
const ref = firebase.database().ref('animals');
const changes = useDatabaseList(ref);
const addNewAnimal = commonName => {
const newAnimalRef = ref.push();
return newAnimalRef.set({
commonName
});
};
const removeAnimal = id => ref.child(id).remove();
return (
<>
<AnimalEntry saveAnimal={addNewAnimal} />
<ul>
{changes.map(({ snapshot }) => (
<li key={snapshot.key}>
{snapshot.val().commonName}{' '}
<button onClick={() => removeAnimal(snapshot.key)}>X</button>
</li>
))}
</ul>
</>
);
};
const AuthCheck = props => {
const user = useUser(firebase.auth());
// TODO: check props.requiredClaims
if (!user) {
return props.fallback;
} else {
return props.children;
}
};
const SuspenseWrapper = props => {
return (
<Suspense fallback="loading...">
<AuthCheck
fallback="sign in to use Realtime Database"
requiredClaims={[]}
>
<h3>Sample Doc Listener</h3>
<Suspense fallback="connecting to Realtime Database...">
<Counter />
</Suspense>
<h3>Sample Collection Listener</h3>
<Suspense fallback="connecting to Realtime Database...">
<List />
</Suspense>
</AuthCheck>
</Suspense>
);
};
export default SuspenseWrapper;
| JavaScript | 0.99913 | @@ -2310,11 +2310,14 @@
ple
-Doc
+Object
Lis
@@ -2457,18 +2457,12 @@
ple
-Collection
+List
Lis
|
39206913539b2b28bdcd65db6a156743906cd9db | use the server side hasTrait function as it works better | client/deck-validator.js | client/deck-validator.js | import _ from 'underscore';
function getDeckCount(deck) {
var count = 0;
_.each(deck, function(card) {
count += card.count;
});
return count;
}
function hasTrait(card, trait) {
var traits = card.card.traits;
var split = traits.split('.');
return _.any(split, function(t) {
return t.toLowerCase() === trait.toLowerCase();
});
}
function isBannerCard(bannerCode, faction) {
switch(bannerCode) {
// Banner of the stag
case '01198':
return faction === 'baratheon';
// Banner of the kraken
case '01199':
return faction === 'greyjoy';
// Banner of the lion
case '01200':
return faction === 'lannister';
// Banner of the sun
case '01201':
return faction === 'martell';
// Banner of the watch
case '01202':
return faction === 'thenightswatch';
// Banner of the wolf
case '01203':
return faction === 'stark';
// Banner of the dragon
case '01204':
return faction === 'targaryen';
// Banner of the rose
case '01205':
return faction === 'tyrell';
}
return false;
}
export function validateDeck(deck) {
var plotCount = getDeckCount(deck.plotCards);
var drawCount = getDeckCount(deck.drawCards);
var status = 'Valid';
var requiredPlots = 7;
var isRains = false;
var extendedStatus = [];
// "The Rains of Castamere"
if(deck.agenda && deck.agenda.code === '05045') {
isRains = true;
requiredPlots = 12;
}
if(drawCount < 60) {
status = 'Invalid';
extendedStatus.push('Too few draw cards');
}
if(plotCount < requiredPlots) {
status = 'Invalid';
extendedStatus.push('Too few plot cards');
}
var combined = _.union(deck.plotCards, deck.drawCards);
if(_.any(combined, function(card) {
if(card.count > card.card.deck_limit) {
extendedStatus.push(card.card.label + ' has limit ' + card.card.deck_limit);
return true;
}
return false;
})) {
status = 'Invalid';
}
if(plotCount > requiredPlots) {
extendedStatus.push('Too many plots');
status = 'Invalid';
}
if(isRains) {
var schemePlots = _.filter(deck.plotCards, plot => {
return hasTrait(plot, 'Scheme');
});
var groupedSchemes = _.groupBy(schemePlots, plot => {
return plot.card.code;
});
if(_.size(groupedSchemes) !== 5 && !_.all(groupedSchemes, plot => {
return plot.count === 1;
})) {
extendedStatus.push('Rains requires 5 different scheme plots');
status = 'Invalid';
}
}
// Kings of summer
if(deck.agenda && deck.agenda.code === '04037' && _.any(deck.plotCards, card => {
return hasTrait(card, 'winter');
})) {
extendedStatus.push('Kings of Summer cannot include Winter plots');
status = 'Invalid';
}
// Kings of winter
if(deck.agenda && deck.agenda.code === '04038' && _.any(deck.plotCards, card => {
return hasTrait(card, 'summer');
})) {
extendedStatus.push('Kings of Winter cannot include Summer plots');
status = 'Invalid';
}
var bannerCount = 0;
if(!_.all(combined, card => {
var faction = card.card.faction_code.toLowerCase();
var bannerCard = false;
if(deck.agenda && isBannerCard(deck.agenda.code, faction) && !card.card.is_loyal) {
bannerCount += card.count;
bannerCard = true;
}
return bannerCard || faction === deck.faction.value.toLowerCase() || faction === 'neutral';
})) {
extendedStatus.push('Too many out of faction cards');
status = 'Invalid';
}
if(bannerCount > 0 && bannerCount < 12) {
extendedStatus.push('Not enough banner faction cards');
status = 'Invalid';
}
return { status: status, plotCount: plotCount, drawCount: drawCount, extendedStatus: extendedStatus };
}
| JavaScript | 0 | @@ -206,20 +206,14 @@
-var traits =
+return
car
@@ -229,100 +229,28 @@
aits
-;%0A var split = traits.split('.');%0A%0A return _.any(split, function(t) %7B%0A return t
+ && card.card.traits
.toL
@@ -259,21 +259,25 @@
erCase()
- ===
+.indexOf(
trait.to
@@ -287,24 +287,30 @@
erCase()
-;%0A %7D)
+ + '.') !== -1
;%0A%7D%0A%0Afun
|
1b1319815780dfd7c3c78b9abbd914cea03e045b | use epic editor autogrow feature | client/helpers/config.js | client/helpers/config.js | Accounts.ui.config({
passwordSignupFields: 'USERNAME_AND_EMAIL'
});
EpicEditorOptions={
container: 'editor',
basePath: '/editor',
clientSideStorage: false,
theme: {
base:'/themes/base/epiceditor.css',
preview:'/themes/preview/github.css',
editor:'/themes/editor/epic-light.css'
}
};
SharrreOptions={
share: {
googlePlus: true,
// facebook: true,
twitter: true,
},
buttons: {
googlePlus: {size: 'tall', annotation:'bubble'},
// facebook: {layout: 'box_count'},
twitter: {
count: 'vertical',
via: 'TelescopeApp'
}
},
enableHover: false,
enableCounter: false,
enableTracking: true
};
Statuses={
pending: 1,
approved: 2,
rejected: 3
};
| JavaScript | 0 | @@ -158,16 +158,33 @@
false,%0A
+%09autogrow: true,%0A
%09theme:
|
64906365802ed41ba0529f98c8c6d63d0728e98b | Replace sourceMappingURL. | lib/transform-chain.js | lib/transform-chain.js | 'use strict';
const fs = require('fs');
const path = require('path');
const async = require('async');
const merge = require('merge');
const sorcery = require('sorcery');
const FileReader = require('./file-reader');
class TransformChain {
constructor(transforms, cacheChain) {
this.transforms = transforms;
this.cacheChain = cacheChain;
}
_buildChain(localFilename, remoteFilename) {
var result = [];
// We're going to mutate array - so we copy it using concat.
var transforms = this.transforms.concat();
var getDstFilename = function() {
return {
local: ((result[result.length - 1] || {}).srcFilename || {}).local || localFilename,
remote: ((result[result.length - 1] || {}).srcFilename || {}).remote || remoteFilename
};
};
// Loop until no more transforms are found.
do {
var found = false;
for (var idx in transforms) {
var transform = transforms[idx];
var dstFilename = getDstFilename();
if (transform.canTransform(dstFilename.local)) {
result.push({
srcFilename: {
local: transform.map(dstFilename.local),
remote: transform.map(dstFilename.remote)
},
dstFilename: dstFilename,
transform: transform
});
transforms.splice(idx, 1);
found = true;
break;
}
}
if (!found) break;
} while (true);
result.push({
srcFilename: getDstFilename(),
dstFilename: getDstFilename(),
transform: new FileReader()
});
return result.reverse();
}
render(localFilename, remoteFilename, ctx) {
return new Promise((resolved, rejected) => {
this.cacheChain.get(localFilename).then((result) => {
if (result) return resolved(merge(result, { cached: true }));
var renderChain = this._buildChain(localFilename, remoteFilename);
async.forEachOfSeries(renderChain, (item, idx, next) => {
var lastResult = (renderChain[idx - 1] || {}).result || {};
item.transform.compile(item.srcFilename.local, lastResult.data, lastResult.map, ctx).then((itemResult) => {
if (!itemResult) return resolved();
async.reduce(itemResult.files || [], [], (files, file, next) => {
fs.access(file, (err) => {
next(null, files.concat([file]));
});
}, (err, files) => {
if (err) return rejected(err);
item.result = merge(itemResult, {
files: files.map((filename) => {
return path.relative(path.dirname(localFilename), filename);
}),
modificationDate: new Date()
});
next();
});
}, next);
}, (err) => {
if (err) return rejected(err);
var lastResult = renderChain[renderChain.length - 1].result;
var files = renderChain.reduce((files, item) => {
return (files || []).concat(item.result.files || []);
}, []);
var uniqueFiles = [];
files.forEach((file) => {
if (uniqueFiles.indexOf(file) == -1) uniqueFiles.push(file);
});
lastResult = merge(lastResult, {
filename: localFilename,
files: uniqueFiles
});
if (lastResult.map) {
lastResult.data = new Buffer(lastResult.data.toString().replace(/sourceMappingURL=[.*?][ $]/, 'sourceMappingURL=' + path.basename(remoteFilename) + '.min'));
}
this.cacheChain.set(localFilename, lastResult).then(() => {
resolved(merge(lastResult, { cached: false }));
}, rejected);
});
}, rejected);
});
}
}
module.exports = exports = TransformChain;
| JavaScript | 0 | @@ -3127,16 +3127,18 @@
=%5B.*?%5D%5B
+%5C*
$%5D/, 'so
|
e1db0ec174395860967df134c26561db55478bc1 | Fix lint | client/js/chart/index.js | client/js/chart/index.js | import {SVG_NS} from '../util.js';
/**
* Creates an SVG chart inside of `container` with the given data.
*
* @param {HTMLElement} container The container element for this chart.
* @param {Map<string, number[]>} histories The ranking history for each
* track.
* @param {Date[]} dates The date of each history entry.
*/
export function createChart(container, histories, dates) {
const svg = document.createElementNS(SVG_NS, 'svg');
svg.setAttribute('class', 'chart');
svg.append(createDefs());
const seriesContainer = document.createElementNS(SVG_NS, 'g');
seriesContainer.setAttribute('class', 'series-container');
svg.append(seriesContainer);
let index = 0;
const colors = ['blue', 'red', 'green', 'purple', 'orange'];
// get only the first 7 tracks for now
for (const history of [...histories.values()].slice(0, 7)) {
const color = colors[index % colors.length];
const series = createSeries(history, color);
seriesContainer.append(series);
index++;
}
container.append(svg);
}
const RUN_SCALE_X = 30;
const RUN_SCALE_Y = 30;
/**
* Creates a new series (set of lines on the chart for a specific song).
*
* @param {number[]} history The historical positions of this track on the
* leaderboard.
* @param {string} color The color of this series.
* @returns {SVGGElement} A group containing the series.
*/
function createSeries(history, color) {
const series = document.createElementNS(SVG_NS, 'g');
series.setAttribute('class', 'series');
series.style.setProperty('--run-color', color);
let start = 0;
let end = 0;
// find segments of history that don't contain null and create a 'run' for
// each one
while (end < history.length) {
// go until we find a non-null point
while (start < history.length && history[start] === null) {
start++;
}
end = start + 1;
// go until we find a null point
while (end < history.length && history[end] !== null) {
end++;
}
// all of the points between start and end are non-null, create run
series.append(createRun(history, start, end));
start = end;
}
return series;
}
/**
* Creates a new run (continuous group of points within a series).
*
* @param {number[]} history The historical positions of this track on the
* leaderboard.
* @param {number} start The index of the first entry in this run.
* @param {number} end The index of the last entry in this run.
* @returns {SVGGElement} The elements that compose this run.
*/
function createRun(history, start, end) {
const runContainer = document.createElementNS(SVG_NS, 'g');
const points = history
.slice(start, end)
.map((val, idx) => ({
x: (idx + start) * RUN_SCALE_X,
y: val * RUN_SCALE_Y
}));
const pointsStr = points
.map(({x, y}) => `${x},${y}`)
.join(' ');
// line that is displayed
const line = document.createElementNS(SVG_NS, 'polyline');
line.setAttribute('class', 'series-run');
line.setAttribute('points', pointsStr);
// secondary (wider) invisible line to make it easier to hit the line with the
// mouse
const touchTarget = document.createElementNS(SVG_NS, 'polyline');
touchTarget.setAttribute('class', 'series-run-touch-target');
touchTarget.setAttribute('points', pointsStr);
const startCap = document.createElementNS(SVG_NS, 'circle');
const endCap = document.createElementNS(SVG_NS, 'circle');
startCap.setAttribute('class', 'series-run-cap');
endCap.setAttribute('class', 'series-run-cap');
startCap.setAttribute('r', '5');
startCap.setAttribute('cx', points[0].x + 'px');
startCap.setAttribute('cy', points[0].y + 'px');
endCap.setAttribute('r', '5');
endCap.setAttribute('cx', points[points.length - 1].x + 'px');
endCap.setAttribute('cy', points[points.length - 1].y + 'px');
runContainer.append(startCap, line, touchTarget, endCap);
return runContainer;
}
/**
* Creates SVG <defs> to use for things such as filters.
*
* @returns {SVGDefsElement} Defs
*/
function createDefs() {
const defs = document.createElementNS(SVG_NS, 'defs');
// need to create SVG brightness filter b/c CSS filters
// don't work on SVG elements in Chrome
const highlightFilter = document.createElementNS(SVG_NS, 'filter');
highlightFilter.id = 'filter-highlight';
highlightFilter.innerHTML = `
<feComponentTransfer>
<feFuncR type="linear" slope="0.5" />
<feFuncG type="linear" slope="0.5" />
<feFuncB type="linear" slope="0.5" />
</feComponentTransfer>
`;
defs.append(highlightFilter);
return defs;
}
| JavaScript | 0.000032 | @@ -1733,32 +1733,65 @@
a non-null point
+, which is the beginning of a run
%0A while (star
@@ -1918,16 +1918,43 @@
ll point
+, which is the end of a run
%0A whi
@@ -2775,17 +2775,16 @@
SCALE_X,
-
%0A
@@ -2804,16 +2804,17 @@
_SCALE_Y
+,
%0A %7D
@@ -2874,16 +2874,17 @@
%3E %60$%7Bx%7D,
+
$%7By%7D%60)%0A
|
eee4e7e4e0caca8ced397e16d4c80f2f738b522f | Fix cleanupPackageCache usage | lib/util/repository.js | lib/util/repository.js | /** @module env/repository */
'use strict';
const fs = require('fs');
const path = require('path');
const semver = require('semver');
const debug = require('debug')('yeoman:environment:repository');
const execa = require('execa');
const REPOSITORY_FOLDER = '.yo-repository';
module.exports = {
/**
* @private
* @property
* Repository absolute path (npm --prefix).
*/
repositoryPath: path.resolve(REPOSITORY_FOLDER),
/**
* @private
* @property nodeModulesPath
* Path to the repository's node_modules.
*/
get nodeModulesPath() {
if (!this._nodeModulesPath) {
this._nodeModulesPath = this.runPackageManager('root').stdout;
}
return this._nodeModulesPath;
},
/**
* @private
* @method
* Create the repositoryPath if it doesn't exists.
*/
createRepositoryFolder() {
if (!fs.existsSync(this.repositoryPath)) {
fs.mkdirSync(this.repositoryPath);
}
},
/**
* @private
* @method
* Resolve the package name module path inside the [repository path]{@link repository.repositoryPath}
* @param {String} packageName - Package name. If packageName is a absolute path then modulePath is joined to it.
* @param {String} [modulePath] - Path to a module inside the package path.
* @returns {String} Absolute module path.
*/
resolvePackagePath(packageName = '', modulePath = '') {
if (path.isAbsolute(packageName)) {
return path.join(packageName, modulePath);
}
return path.join(this.nodeModulesPath, packageName, modulePath);
},
/**
* @private
* @method
* Remove the package from node's cache, necessary for a reinstallation.
* Removes only package.json by default, it's used to version verification.
* Removes only cache of the repository's packages.
* @param {String} packageName - Package name.
* @param {Boolean} [force=false] - If true removes every cache the package.
* @throw Error if force === false and any file other the package.json is loaded.
*/
cleanupPackageCache(packageName, force = false) {
if (!packageName) {
throw new Error('You must provide a packageName');
}
debug('Cleaning cache of %s', packageName);
const packagePath = this.resolvePackagePath(packageName);
const toCleanup = Object.keys(require.cache).filter(cache => cache.startsWith(packagePath));
if (!force && toCleanup.find(cache => !cache.endsWith('package.json'))) {
throw new Error(`Package ${packageName} already loaded`);
}
toCleanup.forEach(cache => {
delete require.cache[cache];
});
},
/**
* @private
* @method
* Run the packageManager.
* @param {String} cmd - The command.
* @param {String[]} [args] - Additional arguments.
* @param {Object} [options] - Config to be passed to execa.
*/
runPackageManager(cmd, args, options) {
const allArgs = [cmd, '-g', '--prefix', this.repositoryPath];
if (args) {
allArgs.push(...args);
}
debug('Running npm with args %o', allArgs);
return execa.sync('npm', allArgs, options);
},
/**
* @private
* @method
* Install a package into the repository.
* @param {String} packageName - Package name.
* @param {String} version - Version of the package.
* @returns {String} Package path.
* @throws Error.
*/
installPackage(packageName, version) {
const packagePath = this.resolvePackagePath(packageName);
const installedVersion = this.getPackageVersion(packagePath);
// Installs the package if no version is installed or the version is provided and don't match the installed version.
if (installedVersion === undefined || (version && (!semver.validRange(version) || !semver.satisfies(installedVersion, version)))) {
debug(`Found ${packageName} version ${installedVersion} but requires version ${version}`);
this.cleanupPackageCache(packagePath, packageName);
const pkgs = {};
if (packageName === 'yeoman-environment' && version && (!semver.validRange(version) || semver.lt(semver.minVersion(version), '2.9.0'))) {
// Workaround buggy dependencies.
pkgs['rxjs-compat'] = '^6.0.0';
}
pkgs[packageName] = version;
const success = this.installPackages(pkgs) === true;
if (!success) {
throw new Error(`Error installing package ${packageName}, version ${version}.`);
}
debug(`Package ${packageName} sucessfully installed`);
} else {
debug(`Using ${packageName} installed version ${installedVersion}`);
}
return packagePath;
},
/**
* @private
* @method
* Install packages.
* @param {Object} packages - Packages to be installed.
* @returns {Boolean}
* @example
* repository.installPackages({ 'yeoman-environment': '2.3.0' });
*/
installPackages(packages) {
this.createRepositoryFolder();
debug('Installing packages %o', packages);
const packagesArgs = Object.entries(packages).map(([key, value]) => value ? (semver.validRange(value) ? `${key}@${value}` : value) : key);
const result = this.runPackageManager('install', [...packagesArgs], {stdio: 'inherit'});
return result.exitCode === 0;
},
/**
* @private
* @method
* Get the installed package version.
* @param {String} packageName - Package name.
* @returns {String|undefined} Package version or undefined.
*/
getPackageVersion(packageName) {
try {
const packageJson = this.resolvePackagePath(packageName, 'package.json');
return require(packageJson).version;
} catch (_) {
return undefined;
}
},
/**
* @private
* @method
* Require a module from the repository.
* @param {String} packageName - Package name.
* @param {String} version - Version of the package. Verify version and force installation.
* @param {String} modulePath - Package name.
* @returns {Object} Module.
* @throws Error.
*/
requireModule(packageName, version, modulePath = '') {
const packagePath = this.installPackage(packageName, version);
const absolutePath = this.resolvePackagePath(packagePath, modulePath);
debug('Loading module at %s', absolutePath);
return require(absolutePath);
}
};
| JavaScript | 0.000002 | @@ -3854,29 +3854,16 @@
geCache(
-packagePath,
packageN
|
12c8ceab21fe127105c5a1e4f63f68005f164598 | Fix and add additional tests. | test/test_container_token.js | test/test_container_token.js | /*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
describe('container token view', function() {
var Y, container, machine, models, utils, views, view, View;
before(function(done) {
Y = YUI(GlobalConfig).use(['container-token',
'juju-models',
'juju-views',
'juju-tests-utils',
'event-simulate',
'node-event-simulate',
'node'], function(Y) {
models = Y.namespace('juju.models');
utils = Y.namespace('juju-tests.utils');
views = Y.namespace('juju.views');
View = views.ContainerToken;
done();
});
});
beforeEach(function() {
container = utils.makeContainer(this, 'container-token');
machine = {
title: 'test title'
};
view = new View({
containerParent: container,
container: utils.makeContainer(this, 'container'),
machine: machine
}).render();
});
afterEach(function() {
view.destroy();
container.remove(true);
});
it('should apply the wrapping class to the container', function() {
assert.equal(view.get('container').hasClass('container-token'), true);
});
it('fires the delete event', function(done) {
view.on('deleteToken', function(e) {
assert.isObject(e);
done();
});
container.one('.delete').simulate('click');
});
it('can be marked as uncommitted', function() {
view.setUncommitted();
assert.equal(view.get('container').one('.token').hasClass('uncommitted'),
true);
assert.equal(view.get('committed'), false);
});
it('can be marked as committed', function() {
view.setUncommitted();
assert.equal(view.get('container').one('.token').hasClass('uncommitted'),
true);
assert.equal(view.get('committed'), false);
view.setCommitted();
assert.equal(view.get('container').one('.token').hasClass('uncommitted'),
false);
assert.equal(view.get('committed'), true);
});
it('mixes in the DropTargetViewExtension', function() {
assert.equal(typeof view._attachDragEvents, 'function');
});
it('attaches the drag events on init', function() {
var attachDragStub = utils.makeStubMethod(view, '_attachDragEvents');
this._cleanups.push(attachDragStub.reset);
view.init();
assert.equal(attachDragStub.calledOnce(), true);
});
it('can be set to the droppable state', function() {
view.setDroppable();
assert.equal(view.get('container').hasClass('droppable'), true);
});
it('can be set from the droppable state back to the default', function() {
var viewContainer = view.get('container');
view.setDroppable();
assert.equal(viewContainer.hasClass('droppable'), true);
view.setNotDroppable();
assert.equal(viewContainer.hasClass('droppable'), false);
});
});
| JavaScript | 0 | @@ -1587,16 +1587,43 @@
ine = %7B%0A
+ displayDelete: true,%0A
ti
@@ -2035,24 +2035,407 @@
ue);%0A %7D);%0A%0A
+ it('does not have a delete button if it is not supposed to', function() %7B%0A container = utils.makeContainer(this, 'container-token');%0A machine.displayDelete = false;%0A view = new View(%7B%0A containerParent: container,%0A container: utils.makeContainer(this, 'container'),%0A machine: machine%0A %7D).render();%0A assert.equal(container.one('.delete'), null);%0A %7D);%0A%0A
it('fires
|
89967b9f755121edc931c5713cbf460f27fb96c8 | Add logic for checking if other players are in room, add transaction function for giving an object to a player and removing it from other player's inventory. | commands/give.js | commands/give.js | var l10n_file = __dirname + '/../l10n/commands/give.yml';
var l10n = require('../src/l10n')(l10n_file);
var CommandUtil = require('../src/command_util').CommandUtil;
exports.command = function (rooms, items, players, npcs, Commands)
{
return function (args, player)
{
// syntax 'give [target player] [item]'
// No giving stuff in combat
if (player.isInCombat()) {
player.sayL10n(l10n, 'GIVE_COMBAT');
return;
}
var room = rooms.getAt(player.getLocation());
args = args.split(' ');
var item = CommandUtil.findItemInInventory(args[1], player, true);
if (!item) {
player.sayL10n(l10n, 'ITEM_NOT_FOUND');
return;
}
var target = players.eachIf(
//Find out if players are in the same room
,
//If they are, do all the stuff
)
item = items.get(item);
player.sayL10n(l10n, 'ITEM_PICKUP', item.getShortDesc(player.getLocale()));
item.setRoom(null);
item.setInventory(player.getName());
player.addItem(item);
room.removeItem(item.getUuid());
};
};
| JavaScript | 0 | @@ -229,12 +229,15 @@
nds)
-%0A%7B%0A%09
+ %7B%0A
retu
@@ -266,15 +266,19 @@
yer)
-%0A%09%7B%0A%0A%09%09
+ %7B%0A
// s
@@ -317,42 +317,16 @@
m%5D'%0A
-%09%09// No giving stuff in combat%0A%0A%09%09
+
if (
@@ -344,27 +344,36 @@
Combat()) %7B%0A
-%09%09%09
+
player.sayL1
@@ -397,34 +397,55 @@
MBAT');%0A
-%09%09%09return;%0A%09%09%7D%0A%0A%09%09
+ return;%0A %7D%0A%0A
var room
@@ -482,18 +482,25 @@
ion());%0A
-%09%09
+%0A
args = a
@@ -515,19 +515,24 @@
t(' ');%0A
-%0A%09%09
+
var item
@@ -590,18 +590,25 @@
true);%0A
-%09%09
+%0A
if (!ite
@@ -612,19 +612,28 @@
item) %7B%0A
-%09%09%09
+
player.s
@@ -668,150 +668,294 @@
');%0A
-%09%09%09return;%0A%09%09%7D%0A%0A%09%09var target = players.eachIf(%0A%09%09%09//Find out if players are in the same room%0A%09%09%09,%0A%0A%09%09%09//If they are, do all the stuff%0A%09%09%09)%0A%0A%09%09
+ return;%0A %7D%0A%0A var target = players.eachIf(function (p) %7B%0A otherPlayersInRoom(p)%0A %7D, function (p) %7B%0A giveItemToPlayer(player, p, item)%0A %7D);%0A%0A function giveItemToPlayer(playerGiving, playerReceiving, item) %7B%0A
item
@@ -975,24 +975,40 @@
item);%0A%0A
-%09%09player
+ playerGiving
.sayL10n
@@ -1024,14 +1024,13 @@
TEM_
-PICKUP
+GIVEN
', i
@@ -1072,32 +1072,173 @@
));%0A
-%09%09item.setRoom(null);%0A%09%09
+ playerReceiving.sayL10n(l10n, 'ITEM_RECEIVED', item.getShortDesc(player.getLocale()));%0A%0A playerGiving.removeItem(item.getUuid());%0A
item
@@ -1253,24 +1253,33 @@
ntory(player
+Receiving
.getName());
@@ -1283,70 +1283,241 @@
));%0A
-%09%09player.addItem(item);%0A%09%09room.removeItem(item.getUuid());%0A%09%7D;%0A
+ playerReceiving.addItem(item);%0A %7D%0A%0A function otherPlayersInRoom(p) %7B%0A if (p)%0A return (p.getName() !== player.getName() && p.getLocation() === player.getLocation());%0A %7D;%0A
%7D;%0A
+%7D;
|
2aee715fd5569ff51304edf5632ebf7c4e876e88 | use port 3001 for shell service | commands/init.js | commands/init.js | var fs = require('fs');
var path = require('path');
var child = require('child_process');
var _ = require('lodash');
var exists = require('is-there');
var util = require('heroku-cli-util');
var YAML = require('yamljs');
var camelcase = require('camelcase');
var docker = require('../lib/docker');
var safely = require('../lib/safely');
var directory = require('../lib/directory');
const ADDONS = {
'heroku-redis': {
image: 'redis',
env: { 'REDIS_URL': 'redis://herokuRedis:6379' }
},
'heroku-postgresql': {
image: 'postgres',
env: { 'DATABASE_URL': 'postgres://postgres:@herokuPostgresql:5432/postgres' }
}
};
module.exports = function(topic) {
return {
topic: topic,
command: 'init',
description: 'create Dockerfile and docker-compose.yml',
help: 'Creates a Dockerfile and docker-compose.yml for the app specified in app.json',
flags: [],
run: safely(init)
};
};
function init(context) {
var procfile = directory.readProcfile(context.cwd);
if (!procfile) throw new Error('Procfile required. Aborting');
createDockerfile(context.cwd);
createDockerCompose(context.cwd);
}
function createDockerfile(dir) {
var dockerfile = path.join(dir, docker.filename);
var appJSON = JSON.parse(fs.readFileSync(path.join(dir, 'app.json'), { encoding: 'utf8' }));
var contents = `FROM ${ appJSON.image }\n`;
try {
fs.statSync(dockerfile);
util.log(`Overwriting existing '${ docker.filename }'`);
}
catch (e) {}
fs.writeFileSync(dockerfile, contents, { encoding: 'utf8' });
util.log(`Wrote ${ docker.filename }`);
}
function createDockerCompose(dir) {
var composeFile = path.join(dir, docker.composeFilename);
var procfile = directory.readProcfile(dir);
try {
fs.statSync(composeFile);
util.log(`Overwriting existing '${ docker.composeFilename }'`);
}
catch (e) {}
// read app.json to get the app's specification
var appJSON = JSON.parse(fs.readFileSync(path.join(dir, 'app.json'), { encoding: 'utf8' }));
// compile a list of addon links
var links = _.map(appJSON.addons || [], camelcase);
// create environment variables to link the addons
var envs = _.reduce(appJSON.addons, addonsToEnv, {});
// compile a list of process services
var processes = _.mapValues(procfile, processToService(links, envs));
// build the 'shell' process for persistent changes, one-off tasks
processes.shell = _.extend(_.cloneDeep(processes.web), {
command: 'bash',
volumes: ['.:/app/user'],
ports: [ '3000:3001' ]
});
// compile a list of addon services
var addons = _.zipObject(links, _.map(appJSON.addons, addonToService));
// combine processes and addons into a list of all services
var services = _.extend({}, processes, addons);
// create a docker-compose file from the list of services
var composeContents = YAML.stringify(services, 4, 2);
fs.writeFileSync(composeFile, composeContents, { encoding: 'utf8' });
util.log(`Wrote ${ docker.composeFilename }`);
function addonsToEnv(env, addon) {
_.extend(env, ADDONS[addon].env);
return env;
}
function processToService(links, envs) {
return function(command, procName) {
var port = procName === 'web' ? '3000' : undefined;
return _.pick({
build: '.',
command: command,
dockerfile: undefined, // TODO: docker.filename (once docker-compose 1.3.0 is released)
environment: _.extend(port ? { PORT: port } : {}, envs),
ports: port ? [`${ port }:${ port }`] : undefined,
links: links.length ? links : undefined,
envFile: undefined // TODO: detect an envFile?
}, _.identity);
};
}
function addonToService(addon) {
return {
image: ADDONS[addon].image
};
}
}
| JavaScript | 0 | @@ -2509,17 +2509,17 @@
: %5B '300
-0
+1
:3001' %5D
@@ -2521,24 +2521,71 @@
01' %5D%0A %7D);%0A
+ processes.shell.environment.PORT = '3001';%0A
%0A // compil
|
5d11d5d8272d6e00782bec4eb8bf3df980fc1747 | Update mute.js | commands/mute.js | commands/mute.js | const Discord = require('discord.js');
const ms = require('ms');
exports.run = (client, message, args) => {
const reason = args.slice(1).join(' ');
const user = message.mentions.users.first();
const modlog = client.channels.find('name', 'mod-log');
const muteRole = client.guilds.get(message.guild.id).roles.find('name', 'SendMessage');
if (!modlog) return message.reply('I cannot find a mod-log channel').catch(console.error);
if (!muteRole) return message.reply('I cannot find a mute role').catch(console.error);
if (reason.length < 1) return message.reply('You must supply a reason for the mute.').catch(console.error);
if (message.mentions.users.size < 1) return message.reply('You must mention someone to mute them.').catch(console.error);
const embed = new Discord.RichEmbed()
.setTimestamp()
.setColor(0xff0000)
.setTitle("User Muted")
.setThumbnail(`${user.avatarURL}`)
.setDescription(`\n`)
.addField("Username:",`${user.username} (${user})`,true)
.addField("Moderator:",`${message.author.username} (${message.author})`, true)
.addField("Reason:",`${reason}`, false)
.setFooter(`User: ${user.username}`,`${user.avatarURL}`);
user.sendMessage({embed: {
color: 0xff0000,
title: "User muted warning",
description: (`\nYou have been muted!\n`),
fields: [{
name : "Username:",
value : `${user.username} (${user})`,
inline : true
},{
name : "Moderator:",
value :`${message.author.username} (${message.author})`,
inline : true
},{
name : "Mute reason:",
value : `${reason}`,
inline : false
},{
name : "If you believe that this was an error, please contact the moderator involved.",
value : `Please avoid interacting with the server for the time being. However, if you have not been unmuted after the stated time, please contact the moderator immediately.`,
inline : false
}]
}})
if (!message.guild.member(client.user).hasPermission('MANAGE_ROLES_OR_PERMISSIONS')) return message.reply('I do not have the correct permissions.').catch(console.error);
message.guild.member(user).removeRole(muteRole).then(() => {
client.channels.get(modlog.id).send({embed}).catch(console.error);
message.channel.send({embed}).catch(console.error);
});
}
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 2
};
exports.help = {
name: 'mute',
description: 'mutes a mentioned user',
usage: 'mute [mention] [reason]'
};
| JavaScript | 0.000001 | @@ -2012,16 +2012,74 @@
error);%0A
+ if (message.guild.member(user).roles.has(muteRole.id)) %7B
%0A mes
@@ -2277,16 +2277,17 @@
%7D);%0A %7D
+%7D
%0A%0Aexport
|
eecdf7d12a87de54701d475408433bd1b2676142 | Fix reaction buttons for team command. | commands/team.js | commands/team.js | const Discord = require('discord.js');
const app = require('../app');
const vex = require('../vex');
const client = app.client;
const addFooter = app.addFooter;
const getTeamId = vex.getTeamId;
const validTeamId = vex.validTeamId;
const getTeam = vex.getTeam;
const createTeamEmbed = vex.createTeamEmbed;
const pageSize = 10;
const previous = '🔺';
const next = '🔻';
module.exports = async (message, args) => {
const arg = args ? args.replace(/\s+/g, '') : '';
const teamId = getTeamId(message, arg);
if (validTeamId(teamId)) {
try {
const team = await getTeam(teamId);
if (team.length) {
let index = 0;
const embed = createTeamEmbed(team[index]);
try {
const reply = await message.channel.send({embed: embed});
const collector = reply.createReactionCollector((reaction, user) => {
return user.id !== client.user.id && (reaction.emoji.name === previous || reaction.emoji.name === next);
}, {time: 30000, dispose: true});
collector.on('collect', (reaction, user) => {
if (user.id === message.author.id) {
index += (reaction.emoji.name === next ? 1 : -1) * pageSize;
if (index >= team.length) {
index = 0;
} else if (index < 0) {
index = Math.max(team.length - pageSize, 0);
}
reply.edit({embed: createTeamEmbed(team[index])});
} else {
reaction.users.remove(user);
}
});
collector.on('remove', (reaction, user) => {
if (user.id === message.author.id) {
index += (reaction.emoji.name === next ? 1 : -1) * pageSize;
if (index >= team.length) {
index = 0;
} else if (index < 0) {
index = Math.max(team.length - pageSize, 0);
}
reply.edit({embed: createTeamEmbed(team[index])});
}
});
collector.on('end', (collected, reason) => {
let users = reply.reactions.get(next).users;
users.forEach(user => users.remove(user));
users = reply.reactions.get(previous).users;
users.forEach(user => users.remove(user));
addFooter(message, embed, reply);
});
await reply.react(previous);
await reply.react(next);
} catch (err) {
console.log(err);
}
} else {
message.reply('that team ID has never been registered.').catch(console.error);
}
} catch (err) {
console.error(err);
}
} else {
message.reply('please provide a valid team ID, such as **24B** or **BNS**.').catch(console.error);
}
};
| JavaScript | 0 | @@ -305,29 +305,8 @@
d;%0A%0A
-const pageSize = 10;%0A
cons
@@ -323,9 +323,14 @@
= '
-%F0%9F%94%BA
+%5Cu25C0
';%0Ac
@@ -346,9 +346,14 @@
= '
-%F0%9F%94%BB
+%5Cu25B6
';%0A%0A
@@ -1093,34 +1093,23 @@
next ?
+-
1 :
--
1)
- * pageSize
;%0A%09%09%09%09%09%09
@@ -1199,33 +1199,24 @@
%09%09%09%09index =
-Math.max(
team.length
@@ -1213,36 +1213,25 @@
am.length -
-pageSize, 0)
+1
;%0A%09%09%09%09%09%09%09%7D%0A%09
@@ -1500,26 +1500,15 @@
t ?
+-
1 :
--
1)
- * pageSize
;%0A%09%09
@@ -1610,17 +1610,8 @@
x =
-Math.max(
team
@@ -1624,20 +1624,9 @@
h -
-pageSize, 0)
+1
;%0A%09%09
@@ -1767,153 +1767,157 @@
%09%09%09%09
-let users = reply.reactions.get(next).users;%0A%09%09%09%09%09%09users.forEach(user =%3E users.remove(user));%0A%09%09%09%09%09%09users = reply.reactions.get(previous)
+%5Bprevious, next%5D.forEach(emoji =%3E %7B%0A%09%09%09%09%09%09%09const reaction = reply.reactions.get(emoji);%0A%09%09%09%09%09%09%09if (reaction) %7B%0A%09%09%09%09%09%09%09%09const users = reaction
.users;%0A
%09%09%09%09
@@ -1912,16 +1912,18 @@
.users;%0A
+%09%09
%09%09%09%09%09%09us
@@ -1963,16 +1963,35 @@
user));%0A
+%09%09%09%09%09%09%09%7D%0A%09%09%09%09%09%09%7D);%0A
%09%09%09%09%09%09ad
|
6a74d12cb068a31b80ee0cb8bd26078434c62845 | fix link thing | commands/wiki.js | commands/wiki.js | // const utils = require('../lib/utils.js')
const rp = require('request-promise-native');
const txtwiki = require('txtwiki');
const linkRegex = /\[(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)) (.*?)\]/g;
const linkNoTextRegex = /\[(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*))\]/g;
const otherLinkType = /{{(.*)\|(.*)\|url=(.*)}}/g;
exports.run = function (msg, args, usertype) {
rp('https://wiki.archlinux.org/api.php?action=parse&format=json&page=' + args.join(' ').toLowerCase() + '&redirects=1&prop=wikitext§ion=0§ionpreview=1&disabletoc=1&utf8=1')
.then(htmlString => {
try {
let text = JSON.parse(htmlString).parse.wikitext['*'].split('\n');
let title = JSON.parse(htmlString).parse.title;
text = text.filter(function (item) {
if (item.startsWith('[[') || item.startsWith('{{') || item === '') return false;
return true;
});
text.forEach(function (part, index, arr) {
if (part.startsWith(':')) arr[index] = ' ' + arr[index].substr(1);
else arr[index] = txtwiki.parseWikitext(arr[index]).replace(linkRegex, '[$4]($1)').replace(linkNoTextRegex, '[(link)]($1)').replace(otherLinkType, '[(link)]($3)');
});
msg.channel.send({
embed: {
color: 1545169,
description: `<:arch:305467628028428288> [**${title}**](https://wiki.archlinux.org/index.php/${title.replace(/ /g, '%20')})\n\n${text.join('\n\n')}`
}
});
} catch (e) {
msg.channel.send({
embed: {
color: 1545169,
description: '<:downarch:317522424012996608> **Article not found.**'
}
});
}
})
.catch(function (err) {
msg.channel.send({
embed: {
color: 1545169,
description: '<:downarch:317522424012996608> **An error occurred.**'
}
});
void err;
});
};
| JavaScript | 0 | @@ -1134,13 +1134,8 @@
-else
arr%5B
|
fddaf1f97e9ec359f320177b17ca771caaabe70c | change [read more] button color | buttons.js | buttons.js | /*
Date: 2016-01-05
*/
var configMenu = {isVisible:false};
var feedList = {isVisible:true};
var feedInput = {isVisible:false};
var feedContainter = {isVisible:true};
var story = {isVisible:false};
var xfunc = function() { $('#feedContainter').removeClass('hidden'); };
var ifBothFalseFunc = function ( first, second, func ) {
if ((first === false) && (second === false) ){
func();
}
};
//
// App Icon on the top left
//
$('#appIcon').on('click', function(event) {
console.log('#appIcon');
if (configMenu.isVisible) {
$('#configMenu').addClass('hidden'); // hide our config menu
configMenu.isVisible = false;
// show the feeds, if both menus
ifBothFalseFunc(configMenu.isVisible, feedList.isVisible, xfunc);
} else {
$('#feedContainter').addClass('hidden'); // hide the feeds
$('#configMenu').removeClass('hidden'); // show our config menu
configMenu.isVisible = true;
}
});
//
// Menu Icon on the top right corner
//
$('#menuIcon').on('click', function(event) {
console.log('#menuIcon');
if (feedList.isVisible) {
$('#RSSListContainter').addClass('hidden'); // hide our config menu
feedList.isVisible = false;
// show the feeds, if both menus
ifBothFalseFunc(configMenu.isVisible, feedList.isVisible, xfunc);
} else {
$('#feedContainter').addClass('hidden'); // hide the feeds
$('#RSSListContainter').removeClass('hidden'); // show our config menu
feedList.isVisible = true;
}
});
//
// Create list of headlines
//
$('#getData').on('click', function(event) {
console.log('#getData');
$('.feedStatus').html('#getData');
if (readerApp.needFeed) {
$('.feedStatus').html('getting Data');
var passingReference = {
// Reduce
draw : function (parm) {
$('#toggleStory').html(parm.title);
var s = '';
//now "shadow" draw the list
$.each(parm.entries, function(i, v) {
s += '<li id="' + i + '" class="contentLink button button-block">' + v.title + '</li>';
});
$("#linksList li").remove();
$("#linksList").append(s);
buttons.rebind();
},
// output of status
status: function (parm) { $('.feedStatus').html(parm); },
};
readerApp.getFeed(passingReference);
readerApp.needFeed = false;
}
});
//
// get a list of feeds from localStorage
//
$('#getFeeds').on('click', function(event) {
console.log('#getFeeds');
$('.feedStatus').html('#getData');
var s = '';
console.log("Num of Feeds: " + localStore.length());
$('.feedStatus').html(localStore.length() + ' Feed(s)');
//now "shadow" draw the list
for (i = 0; i < localStore.length(); i++ ) {
var k = localStore.key(i);
var v = localStore.get(k);
s += '<li id="' + k + '" class="feedLink button button-block">' + k + '</li>';
};
s += '<li id=addFeed class="xfeedLink button button-block">Add a Feed</li>';
console.log(s);
$("#RSSList li").remove(); // remove children of the DOM
$("#RSSList").append(s); // appeand our list of Feeds
buttons.dynamic2(); // bind the list to touching
addFeedBinding(); // bind our button to add more feeds
});
// Toggle the visibility of the "Story"
$('#toggleWrapper').on('click', function(event) {
console.log('#toggleWrapper');
if (story.isVisible) {
$('#linksList').removeClass('hidden'); // show list
$('#story').addClass('hidden'); // hide story
$('#backIcon').addClass('hidden'); // hide icon
story.isVisible = false;
} else {
var loadStory = function (parm) {
$('#story').html(
'<h2>' + parm.title + '</h2>' +
'<div>' + parm.description + '</div>' +
'<button id=readMore ' +
' class="button button-pill button-royal" ' +
'>Read More ..</button>'
);
buttons.readmore(parm.link); // create handler to open browser
};
readerApp.getStory(loadStory);
$('#backIcon').removeClass('hidden'); // show icon
$('#story').removeClass('hidden'); // show story
$('#linksList').addClass('hidden'); // hist list
story.isVisible = true;
}
});
addFeedBinding = function () {
$('#addFeed').on('click', function(event) {
console.log('#addFeed');
if (feedInput.isVisible) {
$('#feedInput').addClass('hidden');
feedInput.isVisible = false;
} else {
$('#feedInput').removeClass('hidden');
feedInput.isVisible = true;
}
});
};
addFeedBinding();
clearFeedFields = function() {
$('#RSSLabel').val(''); // clear the field
$('#RSSURL').val(''); // clear the field
}
$('#addBtn').on('click', function(event) {
console.log('#addBtn');
// Add the data to storage
if ($('#RSSLabel').val() && $('#RSSURL').val()) {
localStore.put($('#RSSLabel').val(), $('#RSSURL').val());
clearFeedFields();
// $('#RSSURL').val(''); // clear the field
$('#addFeed').trigger('click'); // trigger to close the AddFeed form
$('#getFeeds').trigger('click'); // trigger to recycle the list
} else {
alert('Both fields must have something.');
}
});
$('#cancelBtn').on('click', function(event) {
console.log('#cancelBtn');
clearFeedFields();
//$('#RSSLabel').val(''); // clear the field
//$('#RSSURL').val(''); // clear the field
$('#addFeed').trigger('click'); // trigger the toggle button
});
$('#codeURL').on('click', function(event) {
console.log('#codeURL');
window.open('https://github.com/jessemonroy650/3rdParty-RSS-Examples', '_system');
});
$('#testToast').on('click', function(event) {
console.log('#testToast');
show('Loading...', 'long', 'center');
});
/*
Since the list is dynamically created, the rebinding of buttons
has to be done everytime the list is created. These button
module deals with that.
*/
var buttons = {
listTag : null,
storyTag : null,
browserTag : null,
init : function (tag) {
buttons.listTag = tag.list;
buttons.storyTag = tag.story;
buttons.browserTag = tag.browser;
console.log("buttons.init");
buttons.dynamic();
},
dynamic : function () {
if (buttons.listTag && buttons.storyTag) {
$(buttons.listTag).on('click', function(event) {
$('.lastReadLink').html(event.target.id);
currentFeed.selectedStory = event.target.id;
$(buttons.storyTag).trigger('click');
});
} else {
alert('Cannot bind dynamic buttons');
}
},
dynamic2 : function () {
$('.feedLink').on('click', function(event) {
//$('.lastReadLink').html(event.target.id);
//currentFeed.selectedStory = event.target.id;
console.log('id:' + event.target.id);
console.log(localStore.get(event.target.id));
// reset the need for a feed.
readerApp.needFeed = true;
currentFeed.RSS = localStore.get(event.target.id);
$('#menuIcon').trigger('click');
$('#getData').trigger('click');
});
},
readmore : function (link, tag) {
if (! tag) {
tag = buttons.browserTag;
}
if (tag && link) {
$(tag).on('click', function(event) {
window.open(link, '_system');
});
} else {
alert('Cannot bind dynamic buttons #2');
}
},
rebind : function () {
buttons.dynamic();
}
}
| JavaScript | 0 | @@ -4119,13 +4119,14 @@
ton-
-royal
+action
%22 '
|
f2d412cac0f98e929ec80ef54d72b1ade2d1cd7e | fix public prefix if write to root | api/getPublicPrefix.js | api/getPublicPrefix.js | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
module.exports = "require.valueOf().modules.c"; | JavaScript | 0.000139 | @@ -111,16 +111,17 @@
orts = %22
+(
require.
@@ -139,10 +139,15 @@
odules.c
+%7C%7C'')
%22;
|
02e39b103f525dc742cb9649c04ce66136870133 | Tidy LocalStorage class. | source/Vibrato/storage/LocalStorage.js | source/Vibrato/storage/LocalStorage.js | // -------------------------------------------------------------------------- \\
// File: LocalStorage.js \\
// Module: Storage \\
// Requires: Core, Foundation \\
// Author: Neil Jenkins \\
// License: © 2010–2013 Opera Software ASA. All rights reserved. \\
// -------------------------------------------------------------------------- \\
/*global window */
"use strict";
( function ( NS, undefined ) {
/**
Module: Storage
The Storage module provides classes for persistant storage in the client.
*/
var dummyStorage = {
setItem: function () {},
getItem: function () {}
};
/**
Class: O.LocalStorage
Extends: O.Object
LocalStorage provides an observable object interface to the local/session
storage facilities provided by modern browsers. Essentially, you can treat
it as an instance of <O.Object> whose values persists between page reloads
(and between browser sessions if not set to session-only).
Since data is serialised to a string for storage, only native JS types
should be stored; class instances will not be restored correctly.
*/
var LocalStorage = NS.Class({
Extends: NS.Object,
/**
Constructor: O.LocalStorage
Parameters:
name - {String} The name of this storage set. Objects with
the same name will overwrite each others' values.
sessionOnly - {Boolean} (optional) Should the values only be
persisted for the session?
*/
init: function ( name, sessionOnly ) {
LocalStorage.parent.init.call( this );
this._name = name + '.';
this._store = window.location.protocol === 'file:' ? dummyStorage :
sessionOnly ? window.sessionStorage : window.localStorage;
},
set: function ( key, value ) {
// If we exceed the storage quota, an error will be thrown.
try {
this._store.setItem( this._name + key, JSON.stringify( value ) );
} catch ( error ) {}
LocalStorage.parent.set.call( this, key, value );
},
getUnknownProperty: function ( key ) {
var item;
// Firefox sometimes throws and error
try {
item = this._store.getItem( this._name + key );
} catch ( error ) {}
return item ? ( this[ key ] = JSON.parse( item ) ) : this[ key ];
}
});
NS.LocalStorage = LocalStorage;
}( this.O ) );
| JavaScript | 0 | @@ -570,22 +570,54 @@
*global
-window
+location, sessionStorage, localStorage
*/%0A%0A%22us
@@ -1904,23 +1904,16 @@
store =
-window.
location
@@ -1977,23 +1977,16 @@
nOnly ?
-window.
sessionS
@@ -1998,15 +1998,8 @@
e :
-window.
loca
|
1bf50fbae64bf7d14aa1805aa19a01a44aa37356 | remove unused dependency and update model | api/user/user.model.js | api/user/user.model.js | 'use strict';
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var md5 = require('MD5');
var userSchema = new mongoose.Schema({
email: {
type: String,
lowercase: true,
unique: true,
required: true,
match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Invalid E-Mail!'],
index: true
},
password: {
type: String,
required: true
},
firstname: String,
surname: String,
description: String,
birthdate: Date,
image: String,
reviews: [
{
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: false
},
naviRequest: {
type: mongoose.Schema.ObjectId,
ref: 'naviRequest',
required: false
},
stars: Number,
createdAt: { type: Date, default: Date.now },
comment: String
}
],
Car: {
capacity: Number,
color: String,
image: String,
year: Number,
brand: String,
model: String,
}
});
userSchema.methods.generateHash = function (password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
userSchema.methods.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};
userSchema.pre('save', function (next) {
console.log('hello.');
});
module.exports = mongoose.model('User', userSchema);
| JavaScript | 0 | @@ -87,32 +87,179 @@
');%0A
-var md5 = require('MD5')
+const emailRegex = /%5E((%5B%5E%3C%3E()%5C%5B%5C%5D%5C%5C.,;:%5Cs@%22%5D+(%5C.%5B%5E%3C%3E()%5C%5B%5C%5D%5C%5C.,;:%5Cs@%22%5D+)*)%7C(%22.+%22))@((%5C%5B%5B0-9%5D%7B1,3%7D%5C.%5B0-9%5D%7B1,3%7D%5C.%5B0-9%5D%7B1,3%7D%5C.%5B0-9%5D%7B1,3%7D%5D)%7C((%5Ba-zA-Z%5C-0-9%5D+%5C.)+%5Ba-zA-Z%5D%7B2,%7D))$/
;%0A%0Av
@@ -422,55 +422,18 @@
h: %5B
-/%5E%5Cw+(%5B%5C.-%5D?%5Cw+)*@%5Cw+(%5B%5C.-%5D?%5Cw+)*(%5C.%5Cw%7B2,3%7D)+$/
+emailRegex
, 'I
@@ -464,16 +464,36 @@
index:
+ true,%0A trim:
true%0A
@@ -584,35 +584,79 @@
me:
-String,%0A surname: String
+%7B type: String, trim: true %7D,%0A surname: %7B type: String, trim: true %7D
,%0A
@@ -1626,34 +1626,8 @@
) %7B%0A
- console.log('hello.');
%0A%7D);
|
7e5bb2069ac3f6a3f42773d52942e53c709b21d5 | Create layout for log in page | Users/Login.js | Users/Login.js | import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Container,
TextInput,
Label,
Text,
View,
Button,
} from 'react-native';
export default class LoginScreen extends Component {
static navigationOptions = {
title: 'Login below',
};
render() {
return (
<View>
<View>
<Label text="Email" />
<TextInput
style={styles.textInput}
/>
</View>
<View>
<Label text="Password" />
<TextInput
secureTextEntry={true}
style={styles.textInput}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
textInput: {
height: 80,
fontSize: 30,
backgroundColor: '#FFF',
},
});
| JavaScript | 0 | @@ -260,19 +260,20 @@
e: '
-Login below
+Welcome Back
',%0A
@@ -315,30 +315,16 @@
%3CView%3E%0A
- %3CView%3E
%0A
@@ -331,28 +331,24 @@
%3C
-Label text=%22
+Text%3E
Email
-%22 /
+%3C/Text
%3E%0A
@@ -420,39 +420,8 @@
/%3E%0A
- %3C/View%3E%0A%0A %3CView%3E
%0A
@@ -432,28 +432,21 @@
%3C
-Label text=%22
+Text%3E
Password
%22 /%3E
@@ -445,11 +445,14 @@
word
-%22 /
+%3C/Text
%3E%0A
@@ -555,16 +555,19 @@
/%3E%0A
+%0A
@@ -563,30 +563,102 @@
%0A %3C
-/View%3E
+Button%0A onPress=%7B() =%3E navigate('#')%7D%0A title=%22Login%22 /%3E%0A
%0A %3C/Vie
|
7395d1eedaebfcffb1d67f6936123b248e5c7b01 | Change playlist background to artwork colour | source/assets/js/modules/soundcloud.js | source/assets/js/modules/soundcloud.js | define([
'libs/bean',
'libs/bonzo',
'libs/qwery',
'utils/loadJSON',
'sc'
], function(
bean,
bonzo,
qwery,
loadJSON
) {
var sound;
return {
init: function() {
loadJSON('/soundcloud-keys.json', function(data) {
SC.initialize({
client_id: data.id
});
});
this.bindEvents();
},
bindEvents: function() {
bean.on(document.body, 'click', '.playlist__entry', function(e) {
this.playTrack(e.currentTarget.dataset.trackId);
}.bind(this));
bean.on(document.body, 'click', '.audio-controls', function(e) {
this.controlsPlay();
}.bind(this));
bean.on(document.body, 'click', '.controls__buttons__skip', function(e) {
this.controlsSkip();
}.bind(this));
},
controlsPlay: function() {
id = bonzo(qwery('.post')).attr('data-current-track');
if (id) {
this.playTrack(id);
} else {
this.playTrack(bonzo(qwery('.playlist__entry')).attr('data-track-id'))
}
},
controlsSkip: function() {
this.playTrack(bonzo(qwery('.is-playing')).next().attr('data-track-id'));
},
loadingState: function(target, state) {
if (state === true) {
target.addClass("is-loading");
} else {
target.removeClass("is-loading");
}
},
onPlay: function(target) {
target.addClass('is-playing');
bonzo(qwery('body')).attr('data-state', 'is-playing');
this.updateNowPlaying();
},
onStop: function(target) {
bonzo(qwery('body')).attr('data-state', 'is-stopped');
target.removeClass('is-playing');
},
getNowPlayingInfo: function() {
return {
"id" : bonzo(qwery('.is-playing')).attr('data-track-id'),
"color" : bonzo(qwery('.is-playing .playlist__entry__info')).attr('style'),
"contrast" : bonzo(qwery('.is-playing')).attr('data-track-contrast'),
"title" : qwery('.is-playing .playlist__entry__title')[0].textContent,
"artist": qwery('.is-playing .playlist__entry__artist')[0].textContent
}
},
updateNowPlaying: function() {
track = this.getNowPlayingInfo();
bonzo(qwery('.post')).attr('data-current-track', track['id']);
bonzo(qwery('.controls')).removeClass('is-dark is-light is-very-dark').addClass(track['contrast']).attr("style", track['color']);
bonzo(qwery('.controls .controls__title__track-artist')).text(track['artist']);
bonzo(qwery('.controls .controls__title__track-title')).text(track['title']);
},
playTrack: function(trackId) {
el = bonzo(qwery('#playlist__entry--' + trackId));
current = bonzo(qwery('.is-playing'));
// Set options for player
var myOptions = {
onload : function() {
// Debug onfinish with this
// sound.setPosition(this.duration - 3000);
},
onfinish : function(){
next = bonzo(qwery('.is-playing')).next().attr('data-track-id');
this.playTrack(next);
}.bind(this),
onbufferchange: function() {
this.loadingState(el, sound.playState);
}.bind(this),
onplay: function() {
this.loadingState(el, true);
}.bind(this)
}
if (sound) {
// Check if it's the same track
if (sound.url.split('/')[4] == trackId) {
if (el.hasClass('is-playing')) {
sound.pause();
this.onStop(el);
} else {
sound.play();
this.onPlay(el);
}
// If not, destroy old track and start again
} else {
sound.stop();
this.onStop(current);
sound = undefined;
this.playTrack(trackId);
}
// First time playing of new track
} else {
context = this;
SC.whenStreamingReady(function() {
var obj = SC.stream('/tracks/' + trackId, myOptions, function(obj){
obj.play();
sound = obj;
context.onPlay(el);
});
sound.load();
});
}
}
}
}); | JavaScript | 0 | @@ -2747,24 +2747,139 @@
%5B'color'%5D);%0A
+ bonzo(qwery('.playlist')).attr(%22style%22, track%5B'color'%5D.replace(')', ', 0.2)').replace('rgb', 'rgba'));%0A
|
0eca466e6016f5e65c5343c102db7f15bcbef3a3 | add method to set an arbitray value | cbuffer.js | cbuffer.js | (function( global ) {
function CBuffer() {
var i = 0;
// handle cases where "new" keyword wasn't used
if (!( this instanceof CBuffer )) {
if ( arguments.length > 1 || typeof arguments[0] !== 'number' ) {
return CBuffer.apply( new CBuffer(), arguments );
} else {
return new CBuffer( arguments[0] );
}
}
// this is the same in either scenario
this.size = this.start = 0;
// build CBuffer based on passed arguments
if ( arguments.length > 1 || typeof arguments[0] !== 'number' ) {
this.data = new Array( arguments.length );
this.end = ( this.length = arguments.length ) - 1;
this.push.apply( this, arguments );
} else {
this.data = new Array( arguments[0] );
// force preallocation of memory to each array slot, for quicker operation on buffer
for ( ; i < arguments[0]; i++ ) {
this.data[i] = undefined;
}
this.end = ( this.length = arguments[0] ) - 1;
}
return this;
}
CBuffer.prototype = {
// push item to the end
push : function() {
var i = 0;
// push items to the end, wrapping and erasing existing items
// using arguments variable directly to reduce gc footprint
for ( ; i < arguments.length; i++ ) {
this.data[( this.end + i + 1 ) % this.length ] = arguments[i];
}
// recalculate size
if ( this.size < this.length ) {
if ( this.size + i > this.length ) this.size = this.length;
else this.size += i;
}
// recalculate end
this.end = ( this.end + i ) % this.length;
// recalculate start
this.start = ( this.length + this.end - this.size + 1 ) % this.length;
// return number current number of items in CBuffer
return this.size;
},
// pop last item
pop : function() {
var item;
if ( this.size === 0 ) return;
item = this.data[ this.end ];
delete this.data[( this.size + this.start - 1 ) % this.length ];
this.size--;
this.end = ( this.end - 1 + this.length ) % this.length;
return item;
},
// remove and return first item
shift : function() {
var item;
// check if there are any items in CBuff
if ( this.size === 0 ) return;
// store first item for return
item = this.data[ this.start ];
// delete first item from memory
delete this.data[ this.start ];
// recalculate start of CBuff
this.start = ( this.start + 1 ) % this.length;
// decrement size
this.size--;
return item;
},
// loop through each item in buffer
forEach : function( callback, context ) {
var i = 0;
// check if context was passed
if ( context ) {
for (; i < this.size; i++ ) {
callback.call( context, this.idx( i ), i, this );
}
} else {
for (; i < this.size; i++ ) {
callback( this.idx( i ), i, this );
}
}
},
// return index of first matched element
indexOf : function( arg, idx ) {
if ( !idx ) idx = 0;
for ( ; idx < this.size; idx++ ) {
if ( this.idx( idx ) === arg ) return idx;
}
return -1;
},
// return first item in buffer
first : function() {
return this.data[ this.start ];
},
// return last item in buffer
last : function() {
return this.data[ this.end ];
},
// return specific index in buffer
idx : function( arg ) {
return this.data[( this.start + arg ) % this.length ];
}
};
global.CBuffer = CBuffer;
}( this ));
| JavaScript | 0 | @@ -3134,16 +3134,146 @@
ngth %5D;%0A
+%09%7D,%0A%09// set value at specified index%0A%09set : function( idx, arg ) %7B%0A%09%09return this.data%5B( this.start + idx ) %25 this.length %5D = arg;%0A
%09%7D%0A%7D;%0A%0Ag
|
52014671bf42df73fd8764de2c18c979cad47ff8 | Make Flow happy | src/devtools/views/Components/Element.js | src/devtools/views/Components/Element.js | // @flow
import React, {
Fragment,
useCallback,
useContext,
useLayoutEffect,
useMemo,
useRef,
} from 'react';
import { ElementTypeClass, ElementTypeFunction } from 'src/devtools/types';
import { createRegExp } from '../utils';
import { TreeContext } from './TreeContext';
import { BridgeContext, StoreContext } from '../context';
import type { Element } from './types';
import styles from './Element.css';
type Props = {
index: number,
style: Object,
// TODO: I can't get the correct type to work here:
data: Object,
};
export default function ElementView({ index, style, data }: Props) {
const {
baseDepth,
getElementAtIndex,
selectOwner,
selectedElementID,
selectElementByID,
} = useContext(TreeContext);
const bridge = useContext(BridgeContext);
const store = useContext(StoreContext);
const element = getElementAtIndex(index);
const id = element === null ? null : element.id;
const isSelected = selectedElementID === id;
const lastScrolledIDRef = data.lastScrolledIDRef;
const handleDoubleClick = useCallback(() => {
if (id !== null) {
selectOwner(id);
}
}, [id, selectOwner]);
const ref = useRef<HTMLSpanElement | null>(null);
// The tree above has its own autoscrolling, but it only works for rows.
// However, even when the row gets into the viewport, the component name
// might be too far left or right on the screen. Adjust it in this case.
useLayoutEffect(() => {
if (isSelected) {
// Don't select the same item twice.
// A row may appear and disappear just by scrolling:
// https://github.com/bvaughn/react-devtools-experimental/issues/67
// It doesn't necessarily indicate a user action.
// TODO: we might want to revamp the autoscroll logic
// to only happen explicitly for user-initiated events.
if (lastScrolledIDRef.current === id) {
return;
}
lastScrolledIDRef.current = id;
if (ref.current !== null) {
ref.current.scrollIntoView({
behavior: 'auto',
block: 'nearest',
inline: 'nearest',
});
}
}
}, [id, isSelected, lastScrolledIDRef]);
// TODO Add click and key handlers for toggling element open/close state.
const handleMouseDown = useCallback(
({ metaKey }) => {
if (id !== null) {
selectElementByID(metaKey ? null : id);
}
},
[id, selectElementByID]
);
const rendererID = store.getRendererIDForElement(element.id);
// Individual elements don't have a corresponding leave handler.
// Instead, it's implemented on the tree level.
const handleMouseEnter = useCallback(() => {
if (rendererID !== null) {
bridge.send('highlightElementInDOM', {
displayName: element.displayName,
hideAfterTimeout: false,
id: element.id,
rendererID,
scrollIntoView: false,
});
}
}, [bridge, element, rendererID]);
// Handle elements that are removed from the tree while an async render is in progress.
if (element == null) {
console.warn(`<ElementView> Could not find element at index ${index}`);
// This return needs to happen after hooks, since hooks can't be conditional.
return null;
}
const { depth, displayName, key, type } = ((element: any): Element);
const showDollarR =
isSelected && (type === ElementTypeClass || type === ElementTypeFunction);
// TODO styles.SelectedElement is 100% width but it doesn't take horizontal overflow into account.
return (
<div
className={isSelected ? styles.SelectedElement : styles.Element}
onMouseEnter={handleMouseEnter}
onMouseDown={handleMouseDown}
onDoubleClick={handleDoubleClick}
style={{
...style, // "style" comes from react-window
// Left padding presents the appearance of a nested tree structure.
paddingLeft: `${(depth - baseDepth) * 0.75 + 0.25}rem`,
// These style overrides enable the background color to fill the full visible width,
// when combined with the CSS tweaks in Tree.
// A lot of options were considered; this seemed the one that requires the least code.
// See https://github.com/bvaughn/react-devtools-experimental/issues/9
width: undefined,
minWidth: '100%',
position: 'relative',
marginBottom: `-${style.height}px`,
}}
>
<span className={styles.Component} ref={ref}>
<DisplayName displayName={displayName} id={((id: any): number)} />
{key && (
<Fragment>
<span className={styles.AttributeName}>key</span>=
<span className={styles.AttributeValue}>"{key}"</span>
</Fragment>
)}
</span>
{showDollarR && <span className={styles.DollarR}> == $r</span>}
</div>
);
}
type DisplayNameProps = {|
displayName: string | null,
id: number,
|};
function DisplayName({ displayName, id }: DisplayNameProps) {
const { searchIndex, searchResults, searchText } = useContext(TreeContext);
const isSearchResult = useMemo(() => {
return searchResults.includes(id);
}, [id, searchResults]);
const isCurrentResult =
searchIndex !== null && id === searchResults[searchIndex];
if (!isSearchResult || displayName === null) {
return displayName;
}
const match = createRegExp(searchText).exec(displayName);
if (match === null) {
return displayName;
}
const startIndex = match.index;
const stopIndex = startIndex + match[0].length;
const children = [];
if (startIndex > 0) {
children.push(<span key="begin">{displayName.slice(0, startIndex)}</span>);
}
children.push(
<mark
key="middle"
className={isCurrentResult ? styles.CurrentHighlight : styles.Highlight}
>
{displayName.slice(startIndex, stopIndex)}
</mark>
);
if (stopIndex < displayName.length) {
children.push(<span key="end">{displayName.slice(stopIndex)}</span>);
}
return children;
}
| JavaScript | 0.000001 | @@ -2454,16 +2454,30 @@
ererID =
+ id !== null ?
store.g
@@ -2503,19 +2503,18 @@
ent(
-element.id)
+id) : null
;%0A
@@ -2683,16 +2683,51 @@
if (
+element !== null && id !== null &&
renderer
@@ -2873,20 +2873,8 @@
-id: element.
id,%0A
@@ -2936,24 +2936,24 @@
%7D);%0A %7D%0A
-
%7D, %5Bbridge
@@ -2962,16 +2962,20 @@
element,
+ id,
rendere
|
bb53f05d05f357bca5d3a08a9c30319fef2c8905 | rework reports so they use the amount of traits rather than a string to decide things | reports/js/totals.js | reports/js/totals.js | var request = new XMLHttpRequest();
request.open('GET', 'totals.json', true);
request.responseType = 'text';
request.onload = function() {
try {
var data = request.response;
var json = JSON.parse(data);
loadData(json);
} catch(e) {
console.log('booo when loading data', e);
}
};
request.send();
function loadData(data) {
data.sort(makeSorter('total'));
var out = document.getElementById('out');
data.forEach(function(app) {
var traits = app.traits;
traits.sort(makeSorter('amount'));
// Title
var trTitle = out.insertRow(-1);
trTitle.className = 'title';
// Build up the title:
var title = app.info !== undefined ? app.info.title : app.name;
// If no HTML files are included, there's no way this is an HTML5
// app.
var hasHTML = false;
traits.forEach(function(trait) {
if (trait.reason === 'HTML files found in code') {
hasHTML = true;
}
});
// var tdTotal = trTitle.insertCell(-1);
// tdTotal.innerHTML = app.total;
var tdName = trTitle.insertCell(-1);
tdName.innerHTML = '<a href="#show-more" class="reveal-reasons">' + title + '</a>';
// Details
var trDetails = out.insertRow(-1);
trDetails.className = 'details';
var tdDetails = trDetails.insertCell(-1);
tdDetails.colSpan = 2;
if (app.total >= 21 && hasHTML) {
trTitle.className = trTitle.className + ' yes';
trDetails.className = trDetails.className + ' yes';
} else if (app.total >= 15 && hasHTML) {
trTitle.className = trTitle.className + ' maybe';
trDetails.className = trDetails.className + ' maybe';
} else if (!hasHTML) {
trTitle.className = trTitle.className + ' no';
trDetails.className = trDetails.className + ' no';
} else {
trTitle.className = trTitle.className + ' unlikely';
trDetails.className = trDetails.className + ' unlikely';
}
var traitsTable = document.createElement('table');
traitsTable.className = 'traits';
tdDetails.appendChild(traitsTable);
traits.forEach(function(trait) {
var traitRow = traitsTable.insertRow(-1);
var tdAmount = traitRow.insertCell(-1);
var tdDesc = traitRow.insertCell(-1);
tdAmount.innerHTML = trait.amount.toFixed(2);
tdDesc.innerHTML = trait.reason;
var hover = trait.files.join('\n');
traitRow.title = hover;
});
});
}
function makeSorter(propertyName) {
return function(a, b) {
var propA = Number(a[propertyName]);
var propB = Number(b[propertyName]);
var epsilon = propA - propB;
if(Math.abs(epsilon) < 0.0001) {
return 0;
} else {
return epsilon > 0 ? -1 : 1;
}
};
}
$(function() {
$('.reveal-reasons').on('click', function() {
var $details = $(this).parent().parent().next();
$details.toggle();
});
});
| JavaScript | 0 | @@ -770,291 +770,8 @@
//
- If no HTML files are included, there's no way this is an HTML5%0A // app.%0A var hasHTML = false;%0A traits.forEach(function(trait) %7B%0A if (trait.reason === 'HTML files found in code') %7B%0A hasHTML = true;%0A %7D%0A %7D);%0A%0A //
var
@@ -814,17 +814,16 @@
//
-
tdTotal.
@@ -1003,16 +1003,25 @@
Details%0A
+ %0A
@@ -1190,656 +1190,198 @@
-if (app.total %3E= 21 && hasHTML) %7B%0A trTitle.className = trTitle.className + ' yes';%0A trDetails.className = trDetails.className + ' yes';%0A %7D else if (app.total %3E= 15 && hasHTML) %7B%0A trTitle.className = trTitle.className + ' maybe';%0A trDetails.className = trDetails.className + ' maybe';%0A %7D else if (!hasHTML) %7B%0A trTitle.className = trTitle.className + ' no';%0A trDetails.className = trDetails.className + ' no';%0A %7D else %7B%0A trTitle.className = trTitle.className + ' unlikely';%0A trDetails.className = trDetails.className + ' unlikely';%0A %7D
+tdDetails.innerHTML = '%3Ch2%3E' + app.total + ' %3Ca href=%22https://play.google.com/store/apps/details?id=' + app.name + '%22 target=%22_blank%22 rel=%22noreferrer%22%3E' + app.name + '%3C/a%3E%3C/h2%3E' + '%3Cbr /%3E';
%0A%0A
@@ -1491,44 +1491,8 @@
-tdDetails.appendChild(traitsTable);%0A
%0A
@@ -1885,24 +1885,561 @@
%7D);%0A%0A
+ tdDetails.appendChild(traitsTable);%0A%0A%0A var total = app.total;%0A var className = 'no';%0A if(total %3E 50) %7B%0A className = 'yes';%0A %7D else if(total %3E 30) %7B%0A className = 'maybe';%0A %7D else if(total %3E 15) %7B%0A className = 'unlikely';%0A %7D%0A%0A trTitle.classList.add(className);%0A trDetails.classList.add(className);%0A%0A %7D);%0A%0A $('.reveal-reasons').on('click', function() %7B%0A var $details = $(this).parent().parent().next();%0A $details.toggle();%0A
%7D);%0A%7D%0A%0Af
@@ -2774,165 +2774,5 @@
%0A%7D%0A%0A
-$(function() %7B%0A $('.reveal-reasons').on('click', function() %7B%0A var $details = $(this).parent().parent().next();%0A $details.toggle();%0A %7D);%0A%7D);
%0A
|
14bb729bccbe95e14ff601c4aed94240be8b33e3 | Remove sticky menu for widths <500px | site/static/js/all.js | site/static/js/all.js | $(function() {
var share = new Share("#share-button-top", {
networks: {
facebook: {
app_id: "1604147083144211",
}
}
});
var winWidth = $(window).width();
var stickyHeader = function () {
winWidth = $(window).width();
if (winWidth >= 768) {
$('.navbar').attr('style', '').removeData('pin');
$('.navbar').pin();
}
}
stickyHeader();
// This is still buggy and just a band-aid
$(window).on('resize', stickyHeader());
var sortAscending = {title: true};
$(".projects").isotope({
layoutMode: "fitRows",
getSortData: {
stars: "[data-stars] parseInt",
forks: "[data-forks] parseInt",
issues: "[data-issues] parseInt",
language: "[data-language]",
title: "[data-title]"
}
});
$('.landing .card').matchHeight();
$("select[name='filter']").change(function(e) {
console.log("Filter by: %o", $(this).val());
$(".projects").isotope({filter: $(this).val().replace(/^\.lang-\./, '.lang-')});
});
$("select[name='sort']").change(function(e) {
var val = $(this).val();
$(".projects").isotope({sortBy: val, sortAscending: sortAscending[val] || false});
});
});
| JavaScript | 0 | @@ -150,145 +150,90 @@
);%0A%0A
-%0A
-var winWidth = $(window).width();%0A%0A var stickyHeader = function () %7B%0A winWidth = $(window).width();%0A%0A if (winWidth %3E= 768) %7B%0A
+// This is still buggy and just a band-aid%0A $(window).on('resize', function()%7B%0A
@@ -286,18 +286,16 @@
');%0A
-
$('.navb
@@ -307,125 +307,41 @@
pin(
-);
+%7B
%0A
-%7D%0A %7D%0A%0A stickyHeader();%0A%0A // This is still buggy and just a band-aid%0A $(window).on('resize', stickyHeader()
+ minWidth: 500%0A %7D);%0A %7D
);%0A%0A
|
85bad9bbffa3e45f862194e0f32af8d7ed124d65 | Add missing @license headers | js/com/google/drive/FileDAOTest.js | js/com/google/drive/FileDAOTest.js | CLASS({
package: 'com.google.drive',
name: 'FileDAOTest',
requires: [
'XHR',
'com.google.drive.FileDAO',
'foam.oauth2.AutoOAuth2',
'foam.demos.olympics.Medal'
],
tests: [
{
model_: 'UnitTest',
name: 'abc',
async: true,
code: function(ret) {
console.log("Testing");
var authX = this.AutoOAuth2.create().Y;
var agent = authX.lookup('foam.oauth2.EasyOAuth2').create({
scopes: [
'https://www.googleapis.com/auth/drive.appfolder'
],
clientId: '982012106580-juaqtmvoue69plra0v6dlqv4ttbggqi3.apps.googleusercontent.com',
clientSecret: '-uciG4ePPT5DXFccHn4kNHWq'
}, authX);
authX.registerModel(
this.XHR.xbind({
authAgent: agent,
}));
var dao = this.FileDAO.create({
model: this.Medal
}, authX);
dao.select(console.log.json);
}
}
]
});
| JavaScript | 0.000001 | @@ -1,8 +1,637 @@
+/**%0A * @license%0A * Copyright 2015 Google Inc. All Rights Reserved.%0A *%0A * Licensed under the Apache License, Version 2.0 (the %22License%22);%0A * you may not use this file except in compliance with the License.%0A * You may obtain a copy of the License at%0A *%0A * http://www.apache.org/licenses/LICENSE-2.0%0A *%0A * Unless required by applicable law or agreed to in writing, software%0A * distributed under the License is distributed on an %22AS IS%22 BASIS,%0A * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A * See the License for the specific language governing permissions and%0A * limitations under the License.%0A */%0A
CLASS(%7B%0A
|
1441eb95790d23a8aff0e341800ffa16b15734ca | Rename ctor param for clarity; fix PropertySet bugs | js/common/model/ElementFollower.js | js/common/model/ElementFollower.js | // Copyright 2016, University of Colorado Boulder
/**
* Convenience class for sticking to model elements.
*
* @author John Blanco
* @author Jesse Greenberg
* @author Andrew Adare
*/
define( function( require ) {
'use strict';
// modules
var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
var inherit = require( 'PHET_CORE/inherit' );
var Vector2 = require( 'DOT/Vector2' );
var PropertySet = require( 'AXON/PropertySet' );
/**
* Convenience class for sticking to model elements.
*
* @param {Vector2 || null} follower
* @constructor
*/
function ElementFollower( follower ) {
PropertySet.call( this, {
follower: follower === null ? new Vector2( 0, 0 ) : follower,
locationBeingFollowed: null
} );
this.offset = new Vector2( 0, 0 );
var thisThermometer = this;
// @private - function that gets linked/unlinked when the thermometer is following/unfollwing.
this.followerFunction = function( location ) {
thisThermometer.follower = location.plus( thisThermometer.offset );
};
}
energyFormsAndChanges.register( 'ElementFollower', ElementFollower );
return inherit( PropertySet, ElementFollower, {
follow: function( locationToFollowProperty ) {
var thisThermometer = this;
if ( this.locationBeingFollowed !== null ) {
this.locationBeingFollowed.unlink( thisThermometer.followerFunction );
}
this.offset = this.follower.minus( locationToFollowProperty.get() );
locationToFollowProperty.link( thisThermometer.followerFunction );
this.locationBeingFollowed = locationToFollowProperty.get();
},
stopFollowing: function() {
var thisThermometer = this;
if ( this.locationBeingFollowed !== null ) {
this.locationBeingFollowedProperty.unlink( thisThermometer.followerFunction );
this.locationBeingFollowed = null;
}
},
isFollowing: function() {
return this.locationBeingFollowed !== null;
}
} );
} );
| JavaScript | 0 | @@ -572,24 +572,38 @@
%7C null%7D
-follower
+initialPositionToTrack
%0A * @c
@@ -647,24 +647,38 @@
llower(
-follower
+initialPositionToTrack
) %7B%0A%0A
@@ -721,24 +721,38 @@
llower:
-follower
+initialPositionToTrack
=== nul
@@ -777,24 +777,38 @@
, 0 ) :
-follower
+initialPositionToTrack
,%0A
@@ -888,39 +888,28 @@
);%0A%0A var
-thisThermometer
+self
= this;%0A
@@ -1065,34 +1065,34 @@
-thisThermometer.follower =
+self.followerProperty.set(
loc
@@ -1107,30 +1107,21 @@
us(
-thisThermometer
+self
.offset
+ )
);%0A
@@ -1311,42 +1311,8 @@
) %7B%0A
- var thisThermometer = this;%0A
@@ -1336,32 +1336,46 @@
ionBeingFollowed
+Property.get()
!== null ) %7B%0A
@@ -1406,16 +1406,24 @@
Followed
+Property
.unlink(
@@ -1423,35 +1423,24 @@
unlink( this
-Thermometer
.followerFun
@@ -1489,16 +1489,30 @@
follower
+Property.get()
.minus(
@@ -1582,35 +1582,24 @@
y.link( this
-Thermometer
.followerFun
@@ -1639,18 +1639,29 @@
Followed
- =
+Property.set(
locatio
@@ -1683,16 +1683,18 @@
ty.get()
+ )
;%0A %7D,
@@ -1731,42 +1731,8 @@
) %7B%0A
- var thisThermometer = this;%0A
@@ -1837,19 +1837,8 @@
this
-Thermometer
.fol
|
77cf537ff4a38dee6fdeb4e84209fc4ea12b83e1 | fix small issues | js/services/booleanSearchEngine.js | js/services/booleanSearchEngine.js | define(
[
'underscore'
],
function(_) { "use strict";
/*
* Boolean search engine.
*/
var BooleanSearchEngine = function () {
var exTree;
var searchTextForExTree;
var andExpression = 'AND';
var orExpression = 'OR';
var nonePattern = 'NONE';
var patterns = ['TAG:', 'URL:', 'TITLE:'];
// Trims defined characters from begining and ending of the string. Defaults to whitespace characters.
var trim = function(input, characters){
if (!_.isString(input)) return input;
if (!characters) characters = '\\s';
return String(input).replace(new RegExp('^' + characters + '+|' + characters + '+$', 'g'), '');
};
// Checks if string is blank or not.
var isBlank = function(str){
if (_.isNull(str)) str = '';
return (/^\s*$/).test(str);
};
// Check that tag collection contains search.
var containsTag = function(tags, patternText){
var tag = _.find(tags, function(item){
return item.text.toUpperCase().indexOf(patternText) != -1;
});
return !_.isUndefined(tag);
};
// Check that title contains search.
var containsTitle = function(title, patternText){
return title.toUpperCase().indexOf(trim(patternText)) != -1;
};
// Check that url contains search.
var containsUrl = function(url, patternText){
return url.toUpperCase().indexOf(trim(patternText)) != -1;
};
// Check that bookmark fields contain search.
var containsField = function(bookmark, patternText){
// var filteredValue = _.find(_.values(_.pick(bookmark, 'title', 'url')), function(propertyValue){
var filteredValue = _.find([bookmark.title, bookmark.url], function(propertyValue){
return propertyValue.toString().toUpperCase().indexOf(trim(patternText)) != -1;
});
return !_.isUndefined(filteredValue);
};
// Check that bookmark could be reached by following expression.
var evaluateExpression = function(bookmark, node){
if(node.pattern === nonePattern && node.literals.length === 1){
var literal = node.literals[0];
return containsField(bookmark, literal.text);
}
var evaluateFunc = function(word){ return containsField(bookmark, word); };
if(node.pattern === 'TAG:'){
evaluateFunc = function(word){ return containsTag(bookmark.tag, word); };
}
else if(node.pattern === 'TITLE:'){
evaluateFunc = function(word){ return containsTitle(bookmark.title, word); };
}
else if(node.pattern === 'URL:'){
evaluateFunc = function(word){ return containsUrl(bookmark.url, word); };
}
if(node.literals.length === 1){
return evaluateFunc(node.literals[0].text);
}
var result = true;
var exp = andExpression;
_.each(node.literals, function(literal){
var literalResult = evaluateFunc(literal.text);
if(exp === andExpression)
{
result = result && literalResult;
}
else if(exp === orExpression){
result = result || literalResult;
}
exp = literal.expression;
});
return result;
};
// Generate expression tree by search text.
this.generateExpressionTree = function(searchText){
if(isBlank(searchText)) return exTree;
searchText = searchText.toUpperCase();
var searchWords = searchText.split(/(TAG:|TITLE:|URL:)/);
if(_.isEmpty(searchWords))
return exTree;
exTree = [];
var node = { pattern: nonePattern, literals:[] };
var literal = { text: '', expression: nonePattern};
_.each(searchWords, function(word){
if(isBlank(word)) return;
if(_.isEqual(word, andExpression)){
literal.expression = andExpression;
return;
}
var pattern = _.find(patterns, function(it){ return word.indexOf(it) != -1; });
if(!_.isUndefined(pattern)){
// flush node
if(node.literals.length !== 0) exTree.push(node);
// create a new node
node = {
pattern: pattern,
literals:[]
};
return;
}
var exps = word.split(/(AND|OR)/);
_.each(exps, function(item){
if(isBlank(word)) return;
if(item === andExpression){
if(isBlank(literal.text)) return;
literal.expression = andExpression;
node.literals.push(literal);
literal = null;
}
else if(item === orExpression){
if(isBlank(literal.text)) return;
literal.expression = orExpression;
node.literals.push(literal);
literal = null;
}
else{
literal = {
expression: nonePattern,
text: trim(item)
};
}
});
if(!isBlank(literal.text)) node.literals.push(literal);
});
exTree.push(node);
return exTree;
};
// Check that bookmark could be reached by following search text.
this.filterBookmark = function(bookmark, searchText){
if(!searchText) return true;
if(!_.isEqual(this.search, searchText)){
this.search = searchText;
this.generateExpressionTree(this.search);
}
if(exTree.length == 1){
return evaluateExpression(bookmark, exTree[0]);
}
if(exTree.length > 1){
var failureNode = _.find(exTree, function(node){
return !evaluateExpression(bookmark, node);
});
return _.isUndefined(failureNode);
}
return false;
};
};
/*
* Boolean search engine factory method.
*/
var BooleanSearchEngineFactory = function() {
return new BooleanSearchEngine();
};
return [
BooleanSearchEngineFactory
];
}); | JavaScript | 0.000212 | @@ -1548,19 +1548,16 @@
%0A
- //
var fil
@@ -1589,23 +1589,16 @@
ues(
-_.pick(
bookmark
, 't
@@ -1597,25 +1597,8 @@
mark
-, 'title', 'url')
), f
@@ -1625,100 +1625,8 @@
e)%7B%0A
- var filteredValue = _.find(%5Bbookmark.title, bookmark.url%5D, function(propertyValue)%7B%0A
@@ -1700,32 +1700,33 @@
patternText)) !=
+=
-1;%0A %7D);
@@ -5591,32 +5591,86 @@
ch);%0A %7D%0A%0A
+ // Improve performance for simple search case%0A
if(exTre
@@ -5680,16 +5680,17 @@
ength ==
+=
1)%7B%0A
|
24a85bb40594bda3fe30d401cdba639a0bccfc25 | Set highlightable to false on SVG components | src/dom_components/model/ComponentSvg.js | src/dom_components/model/ComponentSvg.js | var Component = require('./Component');
module.exports = Component.extend({
getName() {
let name = this.get('tagName');
let customName = this.get('custom-name');
name = name.charAt(0).toUpperCase() + name.slice(1);
return customName || name;
},
}, {
isComponent(el) {
if (SVGElement && el instanceof SVGElement) {
return {type: 'svg'};
}
},
});
| JavaScript | 0.000004 | @@ -71,16 +71,91 @@
tend(%7B%0A%0A
+ defaults: %7B ...Component.prototype.defaults,%0A highlightable: 0,%0A %7D,%0A%0A
getNam
|
b3b2ad18ab0586a0095b3e2df7dd20fc977a2743 | exclude build/* folder from presubmit checks | build-system/tasks/presubmit-checks.js | build-system/tasks/presubmit-checks.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* 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.
*/
var gulp = require('gulp');
var util = require('gulp-util');
// Directories to check for presubmit checks.
var srcGlobs = [
'**/*.{css,js,html,md}',
'!{node_modules,dist,dist.3p}/**/*.*',
'!build-system/tasks/presubmit-checks.js',
'!build/polyfills.js',
'!gulpfile.js'
];
var dedicatedCopyrightNoteSources = /(\.js|.css|\.md)$/;
// Terms that must not appear in our source files.
var forbiddenTerms = {
'DO NOT SUBMIT': '',
'describe\\.only': '',
'it\\.only': '',
'XXX': '',
'console\\.\\w+\\(': 'If you run against this, use console/*OK*/.log to ' +
'whitelist a legit case.',
'\\.innerHTML': '',
'\\.outerHTML': '',
'\\.postMessage': '',
'cookie': '',
'eval\\(': '',
'localStorage': '',
'sessionStorage': '',
'indexedDB': '',
'openDatabase': '',
'requestFileSystem': '',
'\\.scrollTop': '',
'webkitRequestFileSystem': '',
};
// Terms that must appear in a source file.
var requiredTerms = {
'Copyright 2015 The AMP HTML Authors\\.':
dedicatedCopyrightNoteSources,
'Licensed under the Apache License, Version 2\\.0':
dedicatedCopyrightNoteSources,
'http\\://www\\.apache\\.org/licenses/LICENSE-2\\.0':
dedicatedCopyrightNoteSources,
};
function hasAnyTerms(file) {
var content = file.contents.toString();
return Object.keys(forbiddenTerms).map(function(term) {
var fix;
// we can't optimize building the `RegExp` objects early unless we build
// another mapping of term -> regexp object to be able to get back to the
// original term to get the possible fix value. This is ok as the
// presubmit doesn't have to be blazing fast and this is most likely
// negligible.
var matches = content.match(new RegExp(term));
if (matches) {
util.log(util.colors.red('Found forbidden: "' + matches[0] +
'" in ' + file.path));
fix = forbiddenTerms[term];
if (fix) {
util.log(util.colors.blue(fix));
}
util.log(util.colors.blue('=========='));
return true;
}
return false;
}).some(function(hasAnyTerm) {
return hasAnyTerm;
});
}
function hasAllTerms(file) {
var content = file.contents.toString();
return Object.keys(requiredTerms).map(function(term) {
var filter = requiredTerms[term];
if (!filter.test(file.path)) {
return false;
}
var matches = content.match(new RegExp(term));
if (!matches) {
util.log(util.colors.red('Did not find required: "' + term +
'" in ' + file.path));
util.log(util.colors.blue('=========='));
return true;
}
return false;
}).some(function(hasAnyTerm) {
return hasAnyTerm;
});
}
function checkForbiddenAndRequiredTerms() {
var forbiddenFound = false;
var missingRequirements = false;
return gulp.src(srcGlobs)
.pipe(util.buffer(function(err, files) {
forbiddenFound = files.map(hasAnyTerms).some(function(errorFound) {
return errorFound;
});
missingRequirements = files.map(hasAllTerms).some(function(errorFound) {
return errorFound;
});
}))
.on('end', function() {
if (forbiddenFound) {
util.log(util.colors.blue(
'Please remove these usages or consult with the AMP team.'));
}
if (missingRequirements) {
util.log(util.colors.blue(
'Adding these terms (e.g. by adding a required LICENSE ' +
'to the file'));
}
if (forbiddenFound || missingRequirements) {
process.exit(1);
}
});
}
gulp.task('presubmit', checkForbiddenAndRequiredTerms);
| JavaScript | 0 | @@ -797,16 +797,22 @@
es,dist,
+build,
dist.3p%7D
|
ec39baa7eaecbf8e108574b47caba3f8e4b94eef | Use existsRecursive more for clarity | public/app/js/cbus-server-update.js | public/app/js/cbus-server-update.js | if (!cbus.hasOwnProperty("server")) { cbus.server = {} }
(function() {
const request = require("request");
const x2j = require("xml2js");
const path = require("path");
cbus.server.update = function(feeds, callback) {
console.log(feeds);
var feedContents = {};
var updatedCount;
function checkUpdatedCount() {
console.log(updatedCount + "/" + feeds.length);
if (updatedCount === feeds.length) {
callback(feedContents);
}
}
console.log("starting feeds update");
updatedCount = 0;
if (feeds.length > 0) {
feeds.forEach(function(feed) {
console.log("starting update of feed '" + feed.title + "'");
request({
url: feed.url,
headers: REQUEST_HEADERS,
timeout: 60 * 1000
}, function(err, result, body) {
if (!err && result.statusCode.toString()[0] === "2") {
x2j.parseString(body, function(err, result) {
if (!err && result) {
feedContents[feed.url] = { items: [] };
var feedContent = feedContents[feed.url];
var items = result.rss.channel[0].item;
items.forEach(function(item) {
var episodeInfo = {};
/* episode title */
episodeInfo.title = item.title;
/* episode audio url */
var episodeURL = null;
if (item["enclosure"] && item["enclosure"][0] &&
item["enclosure"][0].$ && item["enclosure"][0].$.url) {
episodeURL = item["enclosure"][0].$.url;
} else if (item["media:content"] && item["media:content"][0] &&
item["media:content"][0].$ && item["media:content"][0].$.url) {
episodeURL = item["media:content"][0].$.url;
}
if (episodeURL) {
episodeInfo.url = episodeURL;
episodeInfo.id = episodeURL;
}
/* episode description */
var description = null;
if (item["itunes:summary"] && item["itunes:summary"][0]) {
description = item["itunes:summary"][0];
} else if (item.description && item.description[0]) {
description = item.description[0];
}
if (description) { episodeInfo.description = description; }
/* episode publish date */
if (item.pubDate && item.pubDate[0]) {
episodeInfo.date = item.pubDate[0];
}
/* episode duration */
if (item["itunes:duration"] && item["itunes:duration"][0]) {
var length = 0;
var lengthStr = item["itunes:duration"][0];
var lengthArr = lengthStr.split(":")
.map(function(val) {
return Number(val);
})
.reverse(); // seconds, minutes, hours
for (var i = 0; i < lengthArr.length; i++) {
if (i === 0) length += lengthArr[i]; // seconds
if (i === 1) length += lengthArr[i] * 60 // minutes
if (i === 2) length += lengthArr[i] * 60 * 60 // hours
}
episodeInfo.length = length;
}
/* episode art */
var episodeArt = null;
if (item["itunes:image"] && item["itunes:image"] &&
item["itunes:image"][0].$ && item["itunes:image"][0].$.href) {
episodeArt = item["itunes:image"][0].$.href;
} else if (item["media:content"] && item["media:content"][0] &&
item["media:content"][0].$ && item["media:content"][0].$.url &&
item["media:content"][0].$.type && item["media:content"][0].$.type.indexOf("image/") === 0) {
episodeArt = item["media:content"][0].$.url;
}
if (episodeArt) { episodeInfo.episodeArt = episodeArt; }
/* episode chapters (podlove.org/simple-chapters) */
var episodeChapters = [];
if (existsRecursive(item, ["psc:chapters", 0, "psc:chapter", 0])) {
let chaptersRaw = item["psc:chapters"][0]["psc:chapter"];
for (let i = 0, l = chaptersRaw.length; i < l; i++) {
let timeStringSplit = chaptersRaw[i].$.start.split(":").reverse();
var time = 0;
for (let i = 0, l = Math.min(timeStringSplit.length - 1, 2); i <= l; i++) {
time += Number(timeStringSplit[i]) * (60 ** i);
}
episodeChapters.push({
title: chaptersRaw[i].$.title,
time: time
});
}
}
episodeInfo.chapters = episodeChapters;
feedContent.items.push(episodeInfo);
});
} else {
console.log("error updating feed '" + feed.title + "'");
console.log(err);
}
updatedCount += 1;
checkUpdatedCount();
});
} else {
console.log("error updating feed '" + feed.title + "'");
console.log(err || result.status);
updatedCount += 1;
checkUpdatedCount();
}
});
});
} else {
console.log("no feeds to update");
}
};
}());
| JavaScript | 0 | @@ -1487,33 +1487,30 @@
if (
-item%5B%22enclosure%22%5D &&
+existsRecursive(
item
+,
%5B%22en
@@ -1521,89 +1521,25 @@
ure%22
-%5D%5B0%5D &&%0D%0A item%5B%22enclosure%22%5D%5B0%5D.$ && item%5B%22enclosure%22%5D%5B0%5D.$.url
+, 0, %22$%22, %22url%22%5D)
) %7B%0D
@@ -1634,37 +1634,30 @@
if (
-item%5B%22media:content%22%5D &&
+existsRecursive(
item
+,
%5B%22me
@@ -1672,97 +1672,25 @@
ent%22
-%5D%5B0%5D &&%0D%0A item%5B%22media:content%22%5D%5B0%5D.$ && item%5B%22media:content%22%5D%5B0%5D.$.url
+, 0, %22$%22, %22url%22%5D)
) %7B%0D
@@ -3533,36 +3533,30 @@
if (
-item%5B%22itunes:image%22%5D &&
+existsRecursive(
item
+,
%5B%22it
@@ -3571,92 +3571,25 @@
ge%22%5D
- &&%0D%0A item%5B%22itunes:image%22%5D%5B0%5D.$ && item%5B%22itunes:image%22%5D%5B0%5D.$.
+, 0, %22$%22, %22
href
+%22)
) %7B%0D
|
7d650001018959a342fe94989929d52c8b4236fd | Improve stage confiration message when moving to the action items stage | web/static/js/configs/shared_stage_configs.js | web/static/js/configs/shared_stage_configs.js | import LobbyStage from "../components/lobby_stage"
import PrimeDirectiveStage from "../components/prime_directive_stage"
import GroupingStage from "../components/grouping_stage"
import GroupsContainer from "../components/groups_container"
import IdeationInterface from "../components/ideation_interface"
import StageChangeInfoPrimeDirective from "../components/stage_change_info_prime_directive"
import StageChangeInfoVoting from "../components/stage_change_info_voting"
import StageChangeInfoGrouping from "../components/stage_change_info_grouping"
import StageChangeInfoClosed from "../components/stage_change_info_closed"
import StageChangeInfoActionItems from "../components/stage_change_info_action_items"
import IdeasWithEphemeralGroupingIds from "../services/ideas_with_ephemeral_grouping_ids"
import { selectors } from "../redux/votes"
import STAGES from "./stages"
const {
LOBBY,
PRIME_DIRECTIVE,
IDEA_GENERATION,
GROUPING,
VOTING,
LABELING_PLUS_VOTING,
ACTION_ITEMS,
GROUPS_ACTION_ITEMS,
CLOSED,
GROUPS_CLOSED,
} = STAGES
const baseVotingConfig = {
arrivalAlert: {
headerText: "Stage Change: Voting!",
BodyComponent: StageChangeInfoVoting,
},
help: {
headerText: "Voting!",
BodyComponent: StageChangeInfoVoting,
},
uiComponent: IdeationInterface,
progressionButton: {
nextStage: ACTION_ITEMS,
copy: "Action Items",
iconClass: "arrow right",
confirmationMessage: "Has everyone had a chance to submit their votes?",
stateDependentTooltip: selectors.votingStageProgressionTooltip,
},
}
export default {
[LOBBY]: {
arrivalAlert: null,
help: null,
uiComponent: LobbyStage,
progressionButton: {
nextStage: PRIME_DIRECTIVE,
copy: "Begin Retro",
iconClass: "arrow right",
confirmationMessage: "Has your entire party arrived?",
},
},
[PRIME_DIRECTIVE]: {
arrivalAlert: {
headerText: "Stage Change: The Prime Directive!",
BodyComponent: StageChangeInfoPrimeDirective,
},
help: {
headerText: "The Prime Directive",
BodyComponent: StageChangeInfoPrimeDirective,
},
uiComponent: PrimeDirectiveStage,
progressionButton: {
nextStage: IDEA_GENERATION,
copy: "Idea Generation",
iconClass: "arrow right",
confirmationMessage: "Is everyone ready to begin?",
},
},
[GROUPING]: {
arrivalAlert: {
headerText: "Stage Change: Grouping!",
BodyComponent: StageChangeInfoGrouping,
},
help: {
headerText: "Grouping",
BodyComponent: StageChangeInfoGrouping,
},
uiComponent: GroupingStage,
progressionButton: {
nextStage: LABELING_PLUS_VOTING,
optionalParamsAugmenter: reduxState => ({
ideasWithEphemeralGroupingIds: IdeasWithEphemeralGroupingIds.buildFrom(reduxState.ideas),
}),
copy: "Labeling + Voting",
iconClass: "arrow right",
confirmationMessage: "Has your team finished grouping the ideas?",
},
},
[VOTING]: baseVotingConfig,
[LABELING_PLUS_VOTING]: {
...baseVotingConfig,
progressionButton: {
...baseVotingConfig.progressionButton,
nextStage: GROUPS_ACTION_ITEMS,
},
arrivalAlert: {
headerText: "Stage Change: Labeling + Voting!",
BodyComponent: StageChangeInfoVoting,
},
help: {
headerText: "Labeling + Voting!",
BodyComponent: StageChangeInfoVoting,
},
uiComponent: GroupsContainer,
},
[ACTION_ITEMS]: {
arrivalAlert: {
headerText: "Stage Change: Action-Item Generation!",
BodyComponent: StageChangeInfoActionItems,
},
help: {
headerText: "Action-Item Generation",
BodyComponent: StageChangeInfoActionItems,
},
uiComponent: IdeationInterface,
progressionButton: {
nextStage: CLOSED,
copy: "Send Action Items",
iconClass: "send",
confirmationMessage: "Are you sure you want to distribute this retrospective's action items? This will close the retro.",
},
},
[GROUPS_ACTION_ITEMS]: {
arrivalAlert: {
headerText: "Stage Change: Action-Item Generation!",
BodyComponent: StageChangeInfoActionItems,
},
help: {
headerText: "Action-Item Generation",
BodyComponent: StageChangeInfoActionItems,
},
uiComponent: GroupsContainer,
progressionButton: {
nextStage: GROUPS_CLOSED,
copy: "Send Action Items",
iconClass: "send",
confirmationMessage: "Are you sure you want to distribute this retrospective's action items? This will close the retro.",
},
},
[CLOSED]: {
arrivalAlert: {
headerText: "Retro: Closed!",
BodyComponent: StageChangeInfoClosed,
},
help: {
headerText: "Retro is Closed!",
BodyComponent: StageChangeInfoClosed,
},
uiComponent: IdeationInterface,
progressionButton: null,
},
[GROUPS_CLOSED]: {
arrivalAlert: {
headerText: "Retro: Closed!",
BodyComponent: StageChangeInfoClosed,
},
help: {
headerText: "Retro is Closed!",
BodyComponent: StageChangeInfoClosed,
},
uiComponent: GroupsContainer,
progressionButton: null,
},
}
| JavaScript | 0.000001 | @@ -1434,18 +1434,23 @@
ssage: %22
-Ha
+Wait! I
s everyo
@@ -1456,30 +1456,22 @@
one
-had a chance to subm
+satisfied w
it
+h
the
|
d0222c376ea75ccf927507b18473908e43ba11aa | Resolve absolute node_modules | webpack/common/modules.js | webpack/common/modules.js | const {resolve} = require('path');
module.exports = [
'node_modules',
resolve(resolve('.'), 'lib/assets/javascripts')
];
| JavaScript | 0.000004 | @@ -49,16 +49,38 @@
ts = %5B%0A
+ resolve(resolve('.'),
'node_m
@@ -86,16 +86,17 @@
modules'
+)
,%0A reso
|
0c8fd42464c4296973503e5c8ed8b45ce557b470 | add regex to resolve warnings on build | webpack/webpack.common.js | webpack/webpack.common.js | var webpack = require("webpack");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var helpers = require("./helpers");
module.exports = {
entry: {
"polyfills": helpers.root("src") + "/polyfills.ts",
"vendor": helpers.root("src") + "/vendor.ts",
"app": helpers.root("src") + "/main.ts",
"css": helpers.root("src") + "/app.css"
},
resolve: {
extensions: [".ts", ".js"]
},
module: {
rules: [
{
test: /\.(html|php)$/,
loader: "html-loader"
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: "url-loader?name=/assets/[name].[hash].[ext]"
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({ fallbackLoader: "style-loader", loader: "css-loader?minimize=true" })
},
{
test: /\.ts$/,
loaders: ["awesome-typescript-loader"]
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ["app", "vendor", "polyfills"]
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
Popper: ['popper.js', 'default']
}),
new HtmlWebpackPlugin({
inject: "head",
filename: helpers.root("public_html") + "/index.html",
template: helpers.root("webpack") + "/index.html"
})
]
}; | JavaScript | 0 | @@ -1126,24 +1126,116 @@
lt'%5D%0A%09%09%7D),%0A%0A
+%09%09new webpack.ContextReplacementPlugin(/@angular(%5C%5C%7C%5C/)core(%5C%5C%7C%5C/)/, helpers.root(%22src%22)),%0A%0A
%09%09new HtmlWe
|
ef728dcfec791be8691f9c2b3b6a022a382f3d2a | Include form id in error event. | website-guts/assets/js/utils/oform_globals.js | website-guts/assets/js/utils/oform_globals.js | ;(function(){
var w, d;
w = window;
d = document;
w.optly = w.optly || {};
w.optly.mrkt = w.optly.mrkt || {};
w.optly.mrkt.Oform = {};
w.optly.mrkt.Oform.before = function(){
d.getElementsByTagName('body')[0].classList.add('oform-processing');
return true;
};
w.optly.mrkt.Oform.validationError = function(element){
w.analytics.track(element.getAttribute('name') + ' error', {
category: 'form error',
label: w.location.pathname
}, {
Marketo: true
});
};
w.optly.mrkt.Oform.done = function(){
d.getElementsByTagName('body')[0].classList.remove('processing');
};
w.optly.mrkt.Oform.trackLead = function(data, XMLHttpRequest){
var propertyName,
reportingObject,
source,
response,
token;
source = w.optly.mrkt.source;
response = JSON.parse(XMLHttpRequest.target.responseText);
if(response.token){
token = response.token;
} else if(response.munchkin_token){
token = response.munchkin_token;
} else {
token = '';
}
reportingObject = {
utm_Campaign__c: source.utm.campaign,
utm_Content__c: source.utm.content,
utm_Medium__c: source.utm.medium,
utm_Source__c: source.utm.source,
utm_Keyword__c: source.utm.keyword,
otm_Campaign__c: source.otm.campaign,
otm_Content__c: source.otm.content,
otm_Medium__c: source.otm.medium,
otm_Source__c: source.otm.source,
otm_Keyword__c: source.otm.keyword,
GCLID__c: source.gclid,
Signup_Platform__c: source.signupPlatform,
Email: response.email,
FirstName: response.first_name,
LastName: response.last_name,
Phone: response.phone_number
};
$.cookie('sourceCookie',
source.utm.campaign + '|||' +
source.utm.content + '|||' +
source.utm.medium + '|||' +
source.utm.source + '|||' +
source.utm.keyword + '|||' +
source.otm.campaign + '|||' +
source.otm.content + '|||' +
source.otm.medium + '|||' +
source.otm.source + '|||' +
source.otm.keyword + '|||' +
source.signupPlatform + '|||'
);
for(propertyName in data){
reportingObject['propertyName'] = data['propertyName']; //jshint ignore:line
}
if(window.debug){
window.debugger;
}
w.Munchkin.munchkinFunction('associateLead', reportingObject, token);
w.analytics.identify(data.email, reportingObject, {
integrations: {
Marketo: true
}
});
/* legacy reporting - to be deprecated */
w.analytics.track('/account/create/success', {
category: 'account',
label: w.location.pathname
}, {
Marketo: true
});
w.Munchkin.munchkinFunction('visitWebPage', {
url: '/account/create/success'
});
w.analytics.track('/account/signin', {
category: 'account',
lable: w.location.pathname
}, {
Marketo: true
});
w.Munchkin.munchkinFunction('visitWebPage', {
url: '/account/signin'
});
/* new reporting */
w.analytics.track('account created', {
category: 'account',
label: w.location.pathname
}, {
Marketo: true
});
w.analytics.track('account signin', {
category: 'account',
lable: w.location.pathname
}, {
Marketo: true
});
};
w.optly.mrkt.Oform.initContactForm = function(arg){
new Oform({
selector: arg.selector
})
.on('validationerror', w.optly.mrkt.Oform.validationError)
.on('load', function(event){
if(event.target.status === 200){
//identify user
$('body').addClass('oform-success');
var response = JSON.parse(event.target.responseText),
email = d.querySelector('[name="email"]').value,
traffic = d.querySelector('#traffic');
w.analytics.identify(email, {
name: d.querySelector('[name="name"]').value,
email: email,
phone: d.querySelector('[name="phone"]').value || '',
company: d.querySelector('[name="company"]').value || '',
website: d.querySelector('[name="website"]').value || '',
utm_Medium__c: window.optly.mrkt.source.utm.medium,
otm_Medium__c: window.optly.mrkt.source.otm.medium,
Demo_Request_Monthly_Traffic__c: traffic.options[traffic.selectedIndex].value || '',
Inbound_Lead_Form_Type__c: d.querySelector('[name="inboundFormLeadType"]').value,
token: response.token
}, {
integrations: {
Marketo: true
}
});
//track the event
w.analytics.track('demo requested', {
category: 'contact form',
label: w.location.pathname
}, {
Marketo: true
});
}
});
};
})();
| JavaScript | 0 | @@ -369,16 +369,62 @@
s.track(
+$(element).closest('form').attr('id') + ' ' +
element.
@@ -495,32 +495,74 @@
,%0A%0A label:
+window.optly.mrkt.utils.trimTrailingSlash(
w.location.pathn
@@ -564,16 +564,17 @@
pathname
+)
%0A%0A %7D,
|
c15f1cfb59f77ca674fafd4d4eda2e2d772c12b0 | add Auth0 badge | website/pages/HomePage.js | website/pages/HomePage.js | view HomePage {
view.lock = new Auth0Lock('0cUJF1X5QmrXTsVKdL9CqorbW4SnjbZd', 'aria.auth0.com')
<Hexagon>
<heading>FormulaGrid</heading>
</Hexagon>
<input placeholder="Search" type="text" />
<buttons>
<button onClick={Motion.router.link('/explore')} class="ui button basic green">
Explore
</button>
<button onClick={() => view.lock.show()} class="ui button basic blue">
Login
</button>
</buttons>
$ = {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
width: '100%'
}
$input = {
width: '30%',
marginTop: 100,
textAlign: 'center'
}
$heading = {
fontSize: 24,
fontWeight: 300
}
$Hexagon = {
width: 200
}
}
| JavaScript | 0.000658 | @@ -152,16 +152,17 @@
exagon%3E%0A
+%0A
%3Cinput
@@ -198,16 +198,17 @@
ext%22 /%3E%0A
+%0A
%3Cbutto
@@ -438,16 +438,326 @@
ttons%3E%0A%0A
+ %3Ccredit%3E%0A %3Ch4%3EAuthentication Powered By:%3C/h4%3E%0A %3Ca href=%22https://auth0.com/%22 target=%22_blank%22 alt=%22Single Sign On & Token Based Authentication - Auth0%22%3E%0A %3Cimg width=%22150%22 height=%2250%22 alt=%22JWT Auth for open source projects%22 src=%22//cdn.auth0.com/oss/badges/a0-badge-light.png%22/%3E%0A %3C/a%3E%0A %3C/credit%3E%0A%0A
$ = %7B%0A
@@ -885,16 +885,109 @@
%25'%0A %7D%0A%0A
+ $Hexagon = %7B%0A width: 200%0A %7D%0A%0A $heading = %7B%0A fontSize: 24,%0A fontWeight: 300%0A %7D%0A%0A
$input
@@ -1053,39 +1053,33 @@
center'%0A %7D%0A%0A $
-heading
+a
= %7B%0A fontSiz
@@ -1075,41 +1075,38 @@
-fontSize: 24,%0A fontWeight: 300
+width: 150,%0A margin: 'auto'
%0A %7D
@@ -1102,39 +1102,38 @@
'auto'%0A %7D%0A%0A $
-Hexagon
+credit
= %7B%0A width:
@@ -1121,29 +1121,113 @@
dit = %7B%0A
-width: 200
+display: 'flex',%0A flexDirection: 'column',%0A marginTop: 100,%0A justifyContent: 'center'
%0A %7D%0A%7D%0A
|
2311a1706ab726013dacae18223f403b67651da8 | rename the community_resource tables and code #5578 | www/assets/cockpit/js/controllers.resource.js | www/assets/cockpit/js/controllers.resource.js | NGApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/community/resources', {
action: 'resources',
controller: 'CommunityResourcesCtrl',
templateUrl: 'assets/view/resources.html',
reloadOnSearch: false
})
.when('/community/resource/:id?', {
action: 'resources',
controller: 'CommunityResourceCtrl',
templateUrl: 'assets/view/resources-resource.html'
});
}]);
NGApp.controller('CommunityResourcesCtrl', function ($rootScope, $scope, ViewListService, ResourceService, CommunityService ) {
$rootScope.title = 'Resources';
CommunityService.listSimple( function( json ){
$scope.communities = [];
$scope.communities.push( { 'name': 'All', 'id_community': 'all' } );
angular.forEach( json, function( community, key ) {
this.push( { 'name': community.name, 'id_community': community.id_community } );
}, $scope.communities );
} );
angular.extend($scope, ViewListService);
$scope.view({
scope: $scope,
watch: {
search: '',
community: 'all'
},
update: function() {
ResourceService.list( $scope.query, function(d) {
$scope.resources = d.results;
$scope.complete(d);
});
}
});
} );
NGApp.controller( 'CommunityResourceCtrl', function ($scope, $routeParams, $rootScope, ResourceService, CommunityService ) {
$scope.resource = { communities: [] };
$scope.save = function(){
if( $scope.isUploading || $scope.isSaving ){
return;
}
if( $scope.form.$invalid ){
$scope.submitted = true;
App.alert( 'Please fill all the required fields!' );
return;
}
if( $scope.resource.temp_name == $scope.resource.file ){
save();
} else {
$rootScope.$broadcast( 'triggerStartUpload' );
$scope.isUploading = true;
}
}
var save = function(){
$scope.isSaving = true;
ResourceService.save( $scope.resource, function( json ){
$scope.isUploading = false;
$scope.isSaving = false;
if( json.error ){
App.alert( 'Error saving: ' + json.error );
} else {
if( $routeParams.id ){
App.alert( 'Resource saved!' );
}
load();
}
} );
}
var communities = function(){
if( $scope.communities ){
return;
}
CommunityService.listSimple( function( json ){
$scope.communities = [];
angular.forEach( json, function( community, key ) {
var ticked = ( $scope.resource.communities.indexOf( community.id_community ) >= 0 );
this.push( { 'name': community.name, 'id_community': community.id_community, 'ticked': ticked} );
}, $scope.communities );
$scope.ready = true;
} );
}
var load = function(){
ResourceService.get( $routeParams.id, function( json ){
$scope.resource = json;
$scope.resource.temp_name = $scope.resource.file;
communities();
} );
}
if( $routeParams.id ){
load();
} else {
$scope.resource = { 'all': false, 'page': true, 'side': true, 'order_page': true, 'active': true, 'communities': [] };
communities();
}
$rootScope.$on( 'triggerUploadFileAdded', function(e, file_name) {
$scope.resource.temp_name = file_name;
});
// this is a listener to upload error
$scope.$on( 'resourceUploadError', function(e, data) {
App.alert( 'Upload error, please try again or send us a message.' );
} );
$scope.$on( 'triggerUploadProgress', function(e, progress) {
console.log('progress',progress);
} );
// this is a listener to upload success
$scope.$on( 'resourceUpload', function(e, data) {
var id_driver_document = data.id_driver_document;
var response = data.response;
if( response.success ){
$scope.resource.file = response.success;
save();
} else {
App.alert( 'File not saved! ');
}
});
});
| JavaScript | 0.000024 | @@ -1261,16 +1261,27 @@
otScope,
+ $location,
Resourc
@@ -2061,21 +2061,101 @@
%09%09%09%09
-%7D%0A
+%09load();%0A%09%09%09%09%7D else %7B%0A%09
%09%09%09%09
+$
lo
-ad();
+cation.path( '/community/resource/' + json.id_resource );%0A%09%09%09%09%7D
%0A%09%09%09
|
c73bb73f674f854ab6b0ff9bfc30114882708fe4 | fix event assigning bug | www/js/controller/lecturesWeeklyController.js | www/js/controller/lecturesWeeklyController.js | "use strict";
angular.module("wuw.controllers")
.controller("LecturesWeeklyCtrl", function($scope, $ionicHistory, $state, $ionicPopup, $compile, $timeout, $filter, Lectures, Settings, uiCalendarConfig) {
$scope.events = [];
$scope.eventSource = [$scope.events];
/* config object */
$scope.uiConfig = {
calendar: {
allDaySlot: false,
weekends: false, //TODO: look if we have a lecture on saturday, then set it to corresponding value
minTime: "08:00:00",
height: "9000",
editable: false,
defaultView: "agendaWeek",
header: false,
dayClick: $scope.alertEventOnClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize
}
};
$scope.loadLectures = function() {
Lectures.lecturesThisWeek().then(function(lectures){
// this event assign works...
$scope.events.length = 0;
for (var i = 0; i < lectures.length; i++) {
$scope.events.push(lectures[i]);
}
// ... this not, WTF? Needs further investigation
// $scope.events = lectures;
//hide an eventually shown error message
$scope.$broadcast("czErrorMessage.hide");
}, function(error) {
if (error === "httpFailed") {
// show the error message with some delay to prevent flickering
$timeout(function() {
$scope.$broadcast("czErrorMessage.show");
}, 300);
}
}).finally(function () {
// remove the refresh spinner a little bit later to prevent flickering
$timeout(function() {
$scope.$broadcast("scroll.refreshComplete");
}, 400);
});
};
$scope.doRefresh = function() {
$scope.loadLectures();
};
$scope.switchToList = function() {
Settings.setSetting("lecturesView", "lecturesList");
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
$state.go("tab.lecturesList", {location: "replace"});
};
$scope.$on('$ionicView.enter', function(){
// get the number of selected lectures, if its zero, we display a message to select courses
$scope.selectedLectures = JSON.parse(Settings.getSetting("selectedLectures") || "[]").length;
// get lectures from cache, and if the cache is older then 10 seconds load from the API
$scope.lectures = Lectures.fromCache("weekly");
if (Lectures.secondsSinceCache("weekly") > 10) {
$scope.loadLectures();
}
});
});
| JavaScript | 0 | @@ -800,82 +800,103 @@
%7D;%0A
+
%0A $
-scope.loadLectures = function() %7B%0A Lectures.lecturesThisWeek(
+ionicPopover.fromTemplateUrl('templates/popover.html', %7B%0A scope: $scope,%0A %7D
).th
@@ -911,17 +911,17 @@
ion(
-lectures)
+popover)
%7B%0A
@@ -930,59 +930,166 @@
-
+$scope.popover = popover;%0A %7D);
%0A
+%0A
+/*%0A
-// this event assign works...%0A
+ used to assign events to the full calendar eventSource%0A */%0A var assignEvents = function(events) %7B%0A
@@ -1126,20 +1126,16 @@
-
for (var
@@ -1146,23 +1146,21 @@
0; i %3C
-lecture
+event
s.length
@@ -1164,28 +1164,24 @@
gth; i++) %7B%0A
-
@@ -1199,23 +1199,21 @@
ts.push(
-lecture
+event
s%5Bi%5D);%0A
@@ -1223,88 +1223,117 @@
-
-
%7D%0A
- %0A // ... this not, WTF? Needs further investigation
+%7D;%0A%0A $scope.loadLectures = function() %7B%0A Lectures.lecturesThisWeek().then(function(lectures)%7B
%0A
@@ -1345,35 +1345,29 @@
-// $scope.e
+assignE
vents
- =
+(
lectures
;%0A
@@ -1362,16 +1362,17 @@
lectures
+)
;%0A
@@ -2751,26 +2751,21 @@
-$scope.lectures =
+assignEvents(
Lect
@@ -2788,16 +2788,17 @@
weekly%22)
+)
;%0A
|
da68457850fc4401abd9b23487d15568a39c5a8c | fix sticky table header on responsive resize | src/encoded/static/libs/sticky_header.js | src/encoded/static/libs/sticky_header.js | (function($) {
// http://stackoverflow.com/a/6625189/199100
// http://css-tricks.com/persistent-headers/
function translate(element, x, y) {
var translation = "translate(" + x + "px," + y + "px)";
element.css({
"transform": translation,
"-ms-transform": translation,
"-webkit-transform": translation,
"-o-transform": translation,
"-moz-transform": translation
});
}
$(function() {
$(document).scroll(function() {
$(".sticky-header").each(function() {
var $header = $(this),
$table = $header.parents('.sticky-area:first'),
offsetTop = $table.offset().top,
scrollTop = $(window).scrollTop() + $('.navbar-fixed-top').height(),
delta = scrollTop - offsetTop;
if((scrollTop > offsetTop) && (scrollTop < (offsetTop + $table.height()))) {
translate($header, 0, delta - 3); // correction for borders
} else {
translate($header, 0, 0);
}
});
});
});
})(jQuery);
| JavaScript | 0 | @@ -674,16 +674,200 @@
+$nb = $('.navbar-fixed-top'),%0A nb_height = 0;%0A%0A if ($nb.css('position') == 'fixed') %7B%0A nb_height = $nb.height();%0A %7D%0A var
scrollTo
@@ -898,39 +898,17 @@
) +
-$('.navbar-fixed-top').
+nb_
height
-()
,%0A
|
8c2239838e82a4902c8ab9a20e2ce52e8eaa1bbe | Update addon/-task-group.js | addon/-task-group.js | addon/-task-group.js | import { or, bool } from '@ember/object/computed';
import EmberObject from '@ember/object';
import { objectAssign, _ComputedProperty } from './utils';
import TaskStateMixin from './-task-state-mixin';
import { propertyModifiers } from './-property-modifiers-mixin';
import { gte } from 'ember-compatibility-helpers';
export const TaskGroup = EmberObject.extend(TaskStateMixin, {
isTaskGroup: true,
toString() {
return `<TaskGroup:${this._propertyName}>`;
},
_numRunningOrNumQueued: or('numRunning', 'numQueued'),
isRunning: bool('_numRunningOrNumQueued'),
isQueued: false,
});
export let TaskGroupProperty;
if (gte('3.10.0')) {
TaskGroupProperty = class {};
} else {
TaskGroupProperty = class extends _ComputedProperty {};
}
objectAssign(TaskGroupProperty.prototype, propertyModifiers);
| JavaScript | 0 | @@ -636,16 +636,24 @@
('3.10.0
+-alpha.1
')) %7B%0A
|
af8136900033fa4de4fc2436df378cbd464faf91 | update response for destory game | server/controllers/gamesController.js | server/controllers/gamesController.js | const Game = require('../models').Game;
module.exports = {
/**
* Creates a new Game object on the server
*
* @route POST /games
*
* @param {*} req req.body.ATTRIBUTE
* @param {*} res res.status
*/
create(req, res) {
return Game
.create({
game_number: req.body.game_number,
sr_change: req.body.sr_change,
rank: req.body.rank,
streak: req.body.streak,
map: req.body.map,
score: req.body.score,
group_size: req.body.group_size,
heroes: req.body.heroes,
notes: req.body.notes
})
.then((game) => res.status(201).send({
status: 201,
message: 'Game created',
data: game,
}))
.catch((error) => res.status(500).send({
status: 500,
message: 'Internal server error',
errors: [error],
}));
},
/**
* Returns all entries from the server
* Note: Should be changed to a findById in future multi-user versions
*
* @route GET /games
*
* @param {*} req
* @param {*} res res.status
*/
findAll(req, res) {
return Game
.findAll()
.then(games => res.status(200).send({
status: 200,
message: 'Games found',
data: games,
}))
.catch(error => res.status(500).send({
status: 500,
message: 'Internal server error',
errors: [error],
}));
},
/**
* Updates the database with new data from a put request by gameId
*
* @route PUT /games/:gameId
*
* @param {*} req req.params.gameId from the URL
* @param {*} res
*/
update(req, res) {
return Game
.findById(req.params.gameId)
.then(game => {
if (!game) {
throw {
status: 404,
message: 'Game not found',
errors: ['Game not found'],
};
}
return game
.update({
game_number: req.body.game_number || game.game_number,
sr_change: req.body.sr_change || game.sr_change,
rank: req.body.rank || game.rank,
streak: req.body.streak || game.streak,
map: req.body.map || game.map,
score: req.body.score || game.score,
group_size: req.body.group_size || game.group_size,
heroes: req.body.heroes || game.heroes,
notes: req.body.notes || game.notes
});
})
.then((game) => res.status(200).send({
status: 200,
message: 'Game updated',
data: game,
}))
.catch((error) => {
if (error.status) {
res.status(error.status).send(error);
}
else {
res.status(500).send({
status: 500,
message: 'Internal server error',
errors: [error],
});
}
});
},
/**
* Destroy Game by gameId
*
* @route DELETE /games/:gameId
*
* @param {*} req
* @param {*} res
*/
destroy(req, res) {
return Game
.findById(req.params.gameId)
.then(game => {
if (!game) {
return res.status(400).send({
message: 'Game Not Found',
});
}
return game
.destroy()
.then(() => res.status(204).send())
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
}
};
| JavaScript | 0 | @@ -3088,75 +3088,118 @@
-return res.status(400).send(%7B%0A message: 'Game Not F
+throw %7B%0A status: 404,%0A message: 'Game not found',%0A errors: %5B'Game not f
ound'
+%5D
,%0A
@@ -3199,33 +3199,32 @@
d'%5D,%0A %7D
-)
;%0A %7D%0A
@@ -3211,32 +3211,33 @@
%7D;%0A %7D%0A
+%0A
return g
@@ -3231,32 +3231,42 @@
return game
+.destroy()
%0A .dest
@@ -3261,30 +3261,78 @@
.
-destroy()
+then(() =%3E new Promise((resolve) =%3E resolve(game)));
%0A
+ %7D)%0A
.t
@@ -3336,20 +3336,34 @@
.then((
+game
) =%3E
+ %7B%0A
res.sta
@@ -3372,23 +3372,121 @@
s(20
-4
+0
).send(
-))%0A
+%7B%0A status: 200,%0A message: 'Game destroyed',%0A data: game,%0A %7D);%0A
+%7D)%0A
@@ -3501,38 +3501,87 @@
((error) =%3E
-res.status(400
+%7B%0A if (error.status) %7B%0A res.status(error.status
).send(error
@@ -3581,25 +3581,24 @@
d(error)
-)
;%0A
%7D)%0A
@@ -3593,34 +3593,36 @@
+
%7D
-)
%0A
-.catch((error) =%3E
+ else %7B%0A
res
@@ -3629,17 +3629,17 @@
.status(
-4
+5
00).send
@@ -3639,22 +3639,149 @@
0).send(
-error)
+%7B%0A status: 500,%0A message: 'Internal server error',%0A errors: %5Berror%5D,%0A %7D);%0A %7D%0A %7D
);%0A %7D%0A%7D
|
1d72fef270a2f1d683929fa90f7ebd55d848580a | Update QMenu.js | quasar/src/components/menu/QMenu.js | quasar/src/components/menu/QMenu.js | import Vue from 'vue'
import AnchorMixin from '../../mixins/anchor.js'
import ModelToggleMixin from '../../mixins/model-toggle.js'
import PortalMixin from '../../mixins/portal.js'
import TransitionMixin from '../../mixins/transition.js'
import ClickOutside from './ClickOutside.js'
import uid from '../../utils/uid.js'
import { getScrollTarget } from '../../utils/scroll.js'
import { stop, position, listenOpts } from '../../utils/event.js'
import EscapeKey from '../../utils/escape-key.js'
import { MenuTreeMixin, closeRootMenu } from './menu-tree.js'
import slot from '../../utils/slot.js'
import {
validatePosition, validateOffset, setPosition, parsePosition
} from '../../utils/position-engine.js'
export default Vue.extend({
name: 'QMenu',
mixins: [ AnchorMixin, ModelToggleMixin, PortalMixin, MenuTreeMixin, TransitionMixin ],
directives: {
ClickOutside
},
props: {
persistent: Boolean,
autoClose: Boolean,
noParentEvent: Boolean,
noRefocus: Boolean,
noFocus: Boolean,
fit: Boolean,
cover: Boolean,
square: Boolean,
anchor: {
type: String,
validator: validatePosition
},
self: {
type: String,
validator: validatePosition
},
offset: {
type: Array,
validator: validateOffset
},
touchPosition: Boolean,
maxHeight: {
type: String,
default: null
},
maxWidth: {
type: String,
default: null
}
},
data () {
return {
menuId: uid()
}
},
computed: {
horizSide () {
return this.$q.lang.rtl ? 'right' : 'left'
},
anchorOrigin () {
return parsePosition(
this.anchor || (
this.cover === true ? `center middle` : `bottom ${this.horizSide}`
)
)
},
selfOrigin () {
return this.cover === true
? this.anchorOrigin
: parsePosition(this.self || `top ${this.horizSide}`)
},
menuClass () {
return this.square === true ? ' q-menu--square' : ''
}
},
watch: {
noParentEvent (val) {
if (this.anchorEl !== void 0) {
if (val === true) {
this.__unconfigureAnchorEl()
}
else {
this.__configureAnchorEl()
}
}
}
},
methods: {
focus () {
let node = this.__portal.$refs !== void 0 ? this.__portal.$refs.inner : void 0
if (node === void 0 || node.contains(document.activeElement) === true) {
return
}
node = node.querySelector('[autofocus]') || node
node.focus()
},
__show (evt) {
clearTimeout(this.timer)
this.__refocusTarget = this.noRefocus === false
? document.activeElement
: void 0
this.scrollTarget = getScrollTarget(this.anchorEl)
this.scrollTarget.addEventListener('scroll', this.updatePosition, listenOpts.passive)
if (this.scrollTarget !== window) {
window.addEventListener('scroll', this.updatePosition, listenOpts.passive)
}
EscapeKey.register(this, () => {
this.$emit('escape-key')
this.hide()
})
this.__showPortal()
this.__registerTree()
this.timer = setTimeout(() => {
const { top, left } = this.anchorEl.getBoundingClientRect()
if (this.touchPosition || this.contextMenu) {
const pos = position(evt)
this.absoluteOffset = { left: pos.left - left, top: pos.top - top }
}
else {
this.absoluteOffset = void 0
}
this.updatePosition()
if (this.unwatch === void 0) {
this.unwatch = this.$watch('$q.screen.width', this.updatePosition)
}
if (this.noFocus !== true) {
document.activeElement.blur()
this.$nextTick(() => {
this.focus()
})
}
this.timer = setTimeout(() => {
this.$emit('show', evt)
}, 300)
}, 0)
},
__hide (evt) {
this.__anchorCleanup(true)
this.timer = setTimeout(() => {
if (this.__refocusTarget !== void 0) {
this.__refocusTarget.focus()
}
this.__hidePortal()
this.$emit('hide', evt)
}, 300)
},
__anchorCleanup (hiding) {
clearTimeout(this.timer)
this.absoluteOffset = void 0
if (this.unwatch !== void 0) {
this.unwatch()
this.unwatch = void 0
}
if (hiding === true || this.showing === true) {
EscapeKey.pop(this)
this.__unregisterTree()
this.scrollTarget.removeEventListener('scroll', this.updatePosition, listenOpts.passive)
if (this.scrollTarget !== window) {
window.removeEventListener('scroll', this.updatePosition, listenOpts.passive)
}
}
},
__onAutoClose (e) {
closeRootMenu(this.menuId)
this.$emit('click', e)
},
updatePosition () {
const el = this.__portal.$el
if (el.nodeType === 8) { // IE replaces the comment with delay
setTimeout(() => {
this.__portal !== void 0 && this.__portal.showing === true && this.updatePosition()
}, 25)
return
}
setPosition({
el,
offset: this.offset,
anchorEl: this.anchorEl,
anchorOrigin: this.anchorOrigin,
selfOrigin: this.selfOrigin,
absoluteOffset: this.absoluteOffset,
fit: this.fit,
cover: this.cover,
maxHeight: this.maxHeight,
maxWidth: this.maxWidth
})
},
__render (h) {
const on = {
...this.$listeners,
input: stop
}
if (this.autoClose === true) {
on.click = this.__onAutoClose
}
return h('transition', {
props: { name: this.transition }
}, [
this.showing === true ? h('div', {
ref: 'inner',
staticClass: 'q-menu scroll' + this.menuClass,
class: this.contentClass,
style: this.contentStyle,
attrs: {
tabindex: -1,
...this.$attrs
},
on,
directives: this.persistent !== true ? [{
name: 'click-outside',
value: this.hide,
arg: [ this.anchorEl ]
}] : null
}, slot(this, 'default')) : null
])
},
__onPortalCreated (vm) {
vm.menuParentId = this.menuId
},
__onPortalClose () {
closeRootMenu(this.menuId)
}
}
})
| JavaScript | 0 | @@ -2386,17 +2386,17 @@
f (node
-=
+!
== void
@@ -2397,18 +2397,18 @@
void 0
-%7C%7C
+&&
node.co
@@ -2438,17 +2438,17 @@
lement)
-=
+!
== true)
@@ -2452,38 +2452,16 @@
ue) %7B%0A
- return%0A %7D%0A%0A
no
@@ -2509,24 +2509,26 @@
node%0A
+
node.focus()
@@ -2524,24 +2524,32 @@
ode.focus()%0A
+ %7D%0A
%7D,%0A%0A
|
7a917f2c19a616721bf818bf48673d4093380baa | Add getContents method to file model | addon/models/file.js | addon/models/file.js | import DS from 'ember-data';
import OsfModel from './osf-model';
import FileItemMixin from 'ember-osf/mixins/file-item';
import { authenticatedAJAX } from 'ember-osf/utils/ajax-helpers';
/**
* @module ember-osf
* @submodule models
*/
/**
* Model for OSF APIv2 files. This model may be used with one of several API endpoints. It may be queried directly,
* or (more commonly) accessed via relationship fields.
* This model is used for basic file metadata. To interact with file contents directly, see the `file-manager` service.
* For field and usage information, see:
* * https://api.osf.io/v2/docs/#!/v2/File_Detail_GET
* * https://api.osf.io/v2/docs/#!/v2/Node_Files_List_GET
* * https://api.osf.io/v2/docs/#!/v2/Node_File_Detail_GET
* * https://api.osf.io/v2/docs/#!/v2/Registration_Files_List_GET
* * https://api.osf.io/v2/docs/#!/v2/Registration_File_Detail_GET
* @class File
*/
export default OsfModel.extend(FileItemMixin, {
_isFileModel: true,
name: DS.attr('fixstring'),
kind: DS.attr('fixstring'),
guid: DS.attr('fixstring'),
path: DS.attr('string'),
size: DS.attr('number'),
currentVersion: DS.attr('number'),
provider: DS.attr('fixstring'),
materializedPath: DS.attr('string'),
lastTouched: DS.attr('date'),
dateModified: DS.attr('date'),
dateCreated: DS.attr('date'),
extra: DS.attr(),
tags: DS.attr(),
parentFolder: DS.belongsTo('file', { inverse: 'files' }),
// Folder attributes
files: DS.hasMany('file', { inverse: 'parentFolder' }),
// File attributes
versions: DS.hasMany('file-version'),
comments: DS.hasMany('comment'),
node: DS.belongsTo('node'), // TODO: In the future apiv2 may also need to support this pointing at nodes OR registrations
user: DS.belongsTo('user'),
checkout: DS.attr('fixstring'),
rename(newName, conflict = 'replace') {
return authenticatedAJAX({
url: this.get('links.upload'),
type: 'POST',
xhrFields: {
withCredentials: true
},
headers: {
'Content-Type': 'Application/json'
},
data: JSON.stringify({
action: 'rename',
rename: newName,
conflict: conflict
}),
}).done(response => {
this.set('name', response.data.attributes.name);
});
},
getGuid() {
return this.store.findRecord(
this.constructor.modelName,
this.id,
{
reload: true,
adapterOptions: {
query: {
create_guid: 1,
},
},
}
);
},
});
| JavaScript | 0 | @@ -2745,12 +2745,206 @@
%0A %7D,%0A
+ getContents() %7B%0A return authenticatedAJAX(%7B%0A url: this.get('links.download'),%0A type: 'GET',%0A xhrFields: %7B withCredentials: true %7D,%0A %7D);%0A %7D,%0A
%7D);%0A
|
c48136f91d182d849dca8dc891aa767468229652 | use routeTo for redirecting after login | client/modules/user/signals/loginFormSubmitted.js | client/modules/user/signals/loginFormSubmitted.js | import {state} from 'cerebral/tags'
import {set, when} from 'cerebral/operators'
import {isValidForm} from 'cerebral-provider-forms/operators'
import {httpPost} from 'cerebral-provider-http/operators'
import initUser from '../actions/initUser'
import setValidationError from '../factories/setValidationError'
export default [
isValidForm(state`user.signIn`), {
true: [
set(state`user.signIn.isLoading`, true),
httpPost('/login', {
email: state`user.signIn.email.value`,
password: state`user.signIn.password.value`
}), {
success: [
set(state`user.signIn.email.value`, ''),
set(state`user.signIn.password.value`, ''),
set(state`user.signIn.showErrors`, false),
set(state`user.signIn.validationError`, null),
initUser,
set(state`user.signIn.isLoading`, false),
when(state`app.lastVisited`), {
true: set(state`app.currentPage`, state`app.lastVisited`),
false: set(state`app.currentPage`, 'home')
}
],
error: [
set(state`user.signIn.password.value`, ''),
set(state`user.signIn.showErrors`, false),
setValidationError(
'user.signIn.validationError',
'Could not log-in!'
),
set(state`user.signIn.isLoading`, false)
]
}
],
false: set(state`user.signIn.showErrors`, true)
}
]
| JavaScript | 0.000001 | @@ -190,24 +190,77 @@
/operators'%0A
+import routeTo from '../../common/factories/routeTo'%0A
import initU
@@ -977,36 +977,16 @@
ue:
-set(state%60app.currentPage%60,
+routeTo(
stat
@@ -1029,36 +1029,16 @@
se:
-set(state%60app.currentPage%60,
+routeTo(
'hom
|
598b501d1d6118e6bf8036943751c5db99c3e4e8 | fix issue with scroll bar positioning (fix #3284) (#3854) | quasar/src/utils/position-engine.js | quasar/src/utils/position-engine.js | import { getScrollbarWidth } from './scroll.js'
export function validatePosition (pos) {
let parts = pos.split(' ')
if (parts.length !== 2) {
return false
}
if (!['top', 'center', 'bottom'].includes(parts[0])) {
console.error('Anchor/Self position must start with one of top/center/bottom')
return false
}
if (!['left', 'middle', 'right'].includes(parts[1])) {
console.error('Anchor/Self position must end with one of left/middle/right')
return false
}
return true
}
export function validateOffset (val) {
if (!val) { return true }
if (val.length !== 2) { return false }
if (typeof val[0] !== 'number' || typeof val[1] !== 'number') {
return false
}
return true
}
export function parsePosition (pos) {
let parts = pos.split(' ')
return { vertical: parts[0], horizontal: parts[1] }
}
export function validateCover (val) {
if (val === true || val === false) { return true }
return validatePosition(val)
}
export function getAnchorProps (el, offset) {
let { top, left, right, bottom, width, height } = el.getBoundingClientRect()
if (offset !== void 0) {
top -= offset[1]
left -= offset[0]
bottom += offset[1]
right += offset[0]
width += offset[0]
height += offset[1]
}
return {
top,
left,
right,
bottom,
width,
height,
middle: left + (right - left) / 2,
center: top + (bottom - top) / 2
}
}
export function getTargetProps (el) {
return {
top: 0,
center: el.offsetHeight / 2,
bottom: el.offsetHeight,
left: 0,
middle: el.offsetWidth / 2,
right: el.offsetWidth
}
}
export function setPosition ({ el, anchorEl, anchorOrigin, selfOrigin, offset, absoluteOffset, cover, fit }) {
let anchorProps
if (absoluteOffset === void 0) {
anchorProps = getAnchorProps(anchorEl, cover === true ? [0, 0] : offset)
}
else {
const
{ top: anchorTop, left: anchorLeft } = anchorEl.getBoundingClientRect(),
top = anchorTop + absoluteOffset.top,
left = anchorLeft + absoluteOffset.left
anchorProps = { top, left, width: 1, height: 1, right: left + 1, center: top, middle: left, bottom: top + 1 }
}
if (fit === true || cover === true) {
el.style.minWidth = anchorProps.width + 'px'
if (cover === true) {
el.style.minHeight = anchorProps.height + 'px'
}
}
const
targetProps = getTargetProps(el),
props = {
top: anchorProps[anchorOrigin.vertical] - targetProps[selfOrigin.vertical],
left: anchorProps[anchorOrigin.horizontal] - targetProps[selfOrigin.horizontal]
}
applyBoundaries(props, anchorProps, targetProps, anchorOrigin, selfOrigin)
el.style.top = Math.max(0, props.top) + 'px'
el.style.left = Math.max(0, props.left) + 'px'
if (props.maxHeight !== void 0) {
el.style.maxHeight = props.maxHeight + 'px'
}
if (props.maxWidth !== void 0) {
el.style.maxWidth = props.maxWidth + 'px'
}
}
function applyBoundaries (props, anchorProps, targetProps, anchorOrigin, selfOrigin) {
const margin = getScrollbarWidth()
let { innerHeight, innerWidth } = window
// don't go bellow scrollbars
innerHeight -= margin
innerWidth -= margin
if (props.top < 0 || props.top + targetProps.bottom > innerHeight) {
if (selfOrigin.vertical === 'center') {
props.top = anchorProps[selfOrigin.vertical] > innerHeight / 2
? innerHeight - targetProps.bottom
: 0
props.maxHeight = Math.min(targetProps.bottom, innerHeight)
}
else if (anchorProps[selfOrigin.vertical] > innerHeight / 2) {
const anchorY = Math.min(
innerHeight,
anchorOrigin.vertical === 'center'
? anchorProps.center
: (anchorOrigin.vertical === selfOrigin.vertical ? anchorProps.bottom : anchorProps.top)
)
props.maxHeight = Math.min(targetProps.bottom, anchorY)
props.top = Math.max(0, anchorY - props.maxHeight)
}
else {
props.top = anchorOrigin.vertical === 'center'
? anchorProps.center
: (anchorOrigin.vertical === selfOrigin.vertical ? anchorProps.top : anchorProps.bottom)
props.maxHeight = Math.min(targetProps.bottom, innerHeight - props.top)
}
}
if (props.left < 0 || props.left + targetProps.right > innerWidth) {
props.maxWidth = Math.min(targetProps.right, innerWidth)
if (selfOrigin.horizontal === 'middle') {
props.left = anchorProps[selfOrigin.horizontal] > innerWidth / 2 ? innerWidth - targetProps.right : 0
}
else if (anchorProps[selfOrigin.horizontal] > innerWidth / 2) {
const anchorX = Math.min(
innerWidth,
anchorOrigin.horizontal === 'middle'
? anchorProps.center
: (anchorOrigin.horizontal === selfOrigin.horizontal ? anchorProps.right : anchorProps.left)
)
props.maxWidth = Math.min(targetProps.right, anchorX)
props.left = Math.max(0, anchorX - props.maxWidth)
}
else {
props.left = anchorOrigin.horizontal === 'middle'
? anchorProps.center
: (anchorOrigin.horizontal === selfOrigin.horizontal ? anchorProps.left : anchorProps.right)
props.maxWidth = Math.min(targetProps.right, innerWidth - props.left)
}
}
}
| JavaScript | 0 | @@ -2686,24 +2686,35 @@
Math.max(0,
+Math.floor(
props.top) +
@@ -2711,16 +2711,17 @@
ops.top)
+)
+ 'px'%0A
@@ -2750,16 +2750,27 @@
.max(0,
+Math.floor(
props.le
@@ -2772,16 +2772,17 @@
ps.left)
+)
+ 'px'%0A
@@ -2843,16 +2843,27 @@
eight =
+Math.floor(
props.ma
@@ -2865,24 +2865,25 @@
ps.maxHeight
+)
+ 'px'%0A %7D%0A
@@ -2941,16 +2941,27 @@
Width =
+Math.floor(
props.ma
@@ -2962,24 +2962,25 @@
ops.maxWidth
+)
+ 'px'%0A %7D%0A
|
a51bcbf97caced01f38936c46df8b1f9162b8d29 | Replace javascript == with === | client/tests/end2end/test-admin-configure-node.js | client/tests/end2end/test-admin-configure-node.js | var utils = require('./utils.js');
describe('adming configure node', function() {
it('should configure node', function(done) {
browser.setLocation('admin/advanced_settings');
// simplify the configuration in order to simplfy initial tests
element(by.model('admin.node.disable_security_awareness_badge')).click();
// enable all receivers to postpone and delete tips
element(by.model('admin.node.can_postpone_expiration')).click();
element(by.model('admin.node.can_delete_submission')).click();
// temporary fix in order to disable the proof of work for testing IE9
// and generically test all the browsers that does not support workers
if (utils.isOldIE()) {
element(by.model('admin.node.enable_proof_of_work')).click();
}
// enable experimental featuress that by default are disabled
element(by.model('admin.node.enable_experimental_features')).click();
// grant tor2web permissions
element(by.cssContainingText("a", "HTTPS settings")).click();
element(by.model('admin.node.tor2web_whistleblower')).click();
// save settings
element(by.css('[data-ng-click="updateNode(admin.node)"]')).click().then(function() {
browser.waitForAngular();
done();
});
});
});
describe('verify navigation of admin sections', function() {
// Even if not performing real checks this test at least verify to be able to perform the
// navigation of the admin section without triggering any exception
it('should should navigate through admin sections', function(done) {
element(by.cssContainingText("a", "General settings")).click().then(function() {
browser.waitForAngular();
element(by.cssContainingText("a", "Main configuration")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Theme customization")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Translation customization")).click();
browser.waitForAngular();
});
element(by.cssContainingText("a", "User management")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Recipient configuration")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Context configuration")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Questionnaire configuration")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Notification settings")).click().then(function() {
browser.waitForAngular();
element(by.cssContainingText("a", "Main configuration")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Admin notification templates")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Recipient notification templates")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Exception notification")).click();
browser.waitForAngular();
});
element(by.cssContainingText("a", "URL shortener")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Advanced settings")).click().then(function() {
browser.waitForAngular();
element(by.cssContainingText("a", "Main configuration")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "HTTPS settings")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Anomaly detection thresholds")).click();
browser.waitForAngular();
});
element(by.cssContainingText("a", "Recent activities")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "System stats")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Anomalies")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "User overview")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "Submission overview")).click();
browser.waitForAngular();
element(by.cssContainingText("a", "File overview")).click();
browser.waitForAngular();
done();
});
});
describe('configure short urls', function() {
it('should should be able to configure short urls', function(done) {
var j = 3;
for (var i = 0; i < j; i++) {
element(by.cssContainingText("a", "URL shortener")).click().then(function() {
element(by.model('new_shorturl.shorturl')).sendKeys('shorturl');
element(by.model('new_shorturl.longurl')).sendKeys('longurl');
element(by.cssContainingText("button", "Add")).click().then(function() {
browser.waitForAngular();
element(by.cssContainingText("button", "Delete")).click().then(function() {
browser.waitForAngular();
j = j - 1;
if (j == 0) {
done();
}
});
});
});
}
});
});
| JavaScript | 0.999703 | @@ -4801,16 +4801,17 @@
if (j ==
+=
0) %7B%0A
|
4a06ebd6019ce85f0e018c356b7fe86da5647c32 | extend target cardCondition for Lionstar so that only characters with printed cost 4 or lower can be targeted (#2657) | server/game/cards/14-FotS/Lionstar.js | server/game/cards/14-FotS/Lionstar.js | const DrawCard = require('../../drawcard');
class Lionstar extends DrawCard {
setupCardAbilities(ability) {
this.action({
title: 'Put a character into play',
cost: ability.costs.kneelSelf(),
target: {
cardCondition: card => (
card.location === 'hand' &&
card.controller === this.controller &&
card.getType() === 'character' &&
card.isFaction('lannister') &&
this.controller.canPutIntoPlay(card)
)
},
message: '{player} kneels {source} to put {target} into play',
handler: context => {
context.player.putIntoPlay(context.target);
this.atEndOfPhase(ability => ({
match: context.target,
effect: ability.effects.discardIfStillInPlay()
}));
}
});
}
}
Lionstar.code = '14028';
module.exports = Lionstar;
| JavaScript | 0 | @@ -552,16 +552,66 @@
ay(card)
+ &&%0A card.getPrintedCost() %3C= 4
%0A
|
2badd65ca949b1704176a97d386b4741fd4468f0 | Update http-common.js | l2-frontend/src/api/http-common.js | l2-frontend/src/api/http-common.js | import axios from 'axios'
import * as Cookies from 'es-cookie'
import {merge, pick} from 'lodash/object'
export const HTTP = axios.create({
baseURL: window.location.origin + '/api',
headers: {
'X-CSRF-Token': Cookies.get('csrftoken')
},
params: {
_: Math.floor((new Date().getTime()) / 100000)
}
})
export const smartCall = async ({method = 'post', url, urlFmt = null, onReject = {}, ctx = null, moreData = {}, pickKeys}) => {
const data = ctx
? (pickKeys ? merge(pick(ctx, Array.isArray(pickKeys) ? pickKeys : [pickThis]), moreData) : ctx)
: moreData;
try {
let response
if (urlFmt) {
response = await HTTP.get(urlFmt.kwf(data))
} else {
response = await HTTP[method](url, data)
}
if (response.statusText === 'OK') {
return response.data
}
} catch (e) {
console.error(e)
}
return onReject
};
export const creator = ({method = 'post', url = null, urlFmt = null, onReject={}}, resultOnCatch = null) =>
(ctx = null, pickKeys = null, moreData = {}) =>
smartCall({
method,
url,
urlFmt,
onReject: resultOnCatch || onReject,
ctx,
moreData,
pickKeys,
})
export const generator = (points) => {
const apiPoints = {};
for (const k of Object.keys(points)) {
apiPoints[k] = creator(points[k]);
}
return apiPoints;
};
| JavaScript | 0.000001 | @@ -539,11 +539,11 @@
pick
-Thi
+Key
s%5D),
|
2e77988923eba585b8b41e9f81ad49b00a5387b3 | make background task name specific to app version | src/front/services/backgroundLocation.js | src/front/services/backgroundLocation.js | import * as Linking from 'expo-linking';
import * as Location from 'expo-location';
import { Alert, Platform } from 'react-native';
// got this idea from: https://forums.expo.dev/t/how-to-setstate-from-within-taskmanager/26630/5?u=agrc
function BackgroundLocationService() {
let subscriber;
return {
subscribe: (callback) => (subscriber = callback),
unsubscribe: () => {
subscriber = null;
},
notify: (location) => subscriber && subscriber(location),
taskName: 'wvcr-vehicle-tracking-background-task',
};
}
export default new BackgroundLocationService();
export async function verifyPermissions() {
console.log('verifyPermissions');
const existingPermissions = await Location.getBackgroundPermissionsAsync();
console.log('existingPermissions', existingPermissions);
if (!existingPermissions.granted) {
await new Promise((resolve) => {
let buttons = [{ text: 'OK', onPress: resolve }];
if (!existingPermissions.canAskAgain) {
buttons.push({ text: 'Go To Settings', onPress: () => Linking.openSettings() });
}
Alert.alert(
'Background Location Permissions',
[
'This app collects location data to enable the tracking of vehicle routes even when the app is closed or',
'not in use. Data is only collected when a tracking session is active. Data submitted to the server is only',
'used for billing purposes and is not shared with any third parties.',
`Please select the **${
Platform.OS === 'android' ? 'Allow all the time' : 'Always'
}** option in the location settings dialog`,
].join(' '),
buttons
);
});
const result = await Location.requestBackgroundPermissionsAsync();
if (!result.granted) {
return false;
}
}
const enabled = await Location.hasServicesEnabledAsync();
console.log('enabled', enabled);
if (!enabled) {
Alert.alert('Error', 'Location services are required to record vehicle routes.', [
{ text: 'OK', onPress: () => Linking.openSettings() },
]);
return false;
}
return true;
}
| JavaScript | 0.00001 | @@ -1,20 +1,70 @@
+import %7B applicationId %7D from 'expo-application';%0A
import * as Linking
@@ -540,13 +540,25 @@
me:
-'wvcr
+%60$%7BapplicationId%7D
-veh
@@ -586,17 +586,17 @@
und-task
-'
+%60
,%0A %7D;%0A%7D
|
4bc9cf2afb557a4d3d5d2dd573b36b5dff1c5715 | Change default hide method to mouseleave | inst/htmlwidgets/lib/cytoscape-qtip.js | inst/htmlwidgets/lib/cytoscape-qtip.js | ;(function( $, $$ ){ 'use strict';
function register( $$, $ ){
// use a single dummy dom ele as target for every qtip
var $qtipContainer = $('<div></div>');
var viewportDebounceRate = 250;
function generateOpts( target, passedOpts ){
var qtip = target.scratch().qtip;
var opts = $.extend( {}, passedOpts );
if( !opts.id ){
opts.id = 'cy-qtip-target-' + ( Date.now() + Math.round( Math.random() * 10000) );
}
if( !qtip.$domEle ){
qtip.$domEle = $qtipContainer;
}
// qtip should be positioned relative to cy dom container
opts.position = opts.position || {};
opts.position.container = opts.position.container || $( document.body );
opts.position.viewport = opts.position.viewport || $( document.body );
opts.position.target = [0, 0];
opts.position.my = opts.position.my || 'top center';
opts.position.at = opts.position.at || 'bottom center';
// adjust
var adjust = opts.position.adjust = opts.position.adjust || {};
adjust.method = adjust.method || 'flip';
adjust.mouse = false;
if( adjust.cyAdjustToEleBB === undefined ){
adjust.cyAdjustToEleBB = true;
}
// default show event
opts.show = opts.show || {};
if( !opts.show.event ){
opts.show.event = 'tap';
}
// default hide event
opts.hide = opts.hide || {};
opts.hide.cyViewport = opts.hide.cyViewport === undefined ? true : opts.hide.cyViewport;
if( !opts.hide.event ){
opts.hide.event = 'unfocus';
}
// so multiple qtips can exist at once (only works on recent qtip2 versions)
opts.overwrite = false;
var content;
if( opts.content ){
if( $$.is.fn(opts.content) ){
content = opts.content;
} else if( opts.content.text && $$.is.fn(opts.content.text) ){
content = opts.content.text;
}
if( content ){
opts.content = function(event, api){
return content.apply( target, [event, api] );
};
}
}
return opts;
}
$$('collection', 'qtip', function( passedOpts ){
var eles = this;
var cy = this.cy();
var container = cy.container();
if( passedOpts === 'api' ){
return this.scratch().qtip.api;
}
eles.each(function(i, ele){
var scratch = ele.scratch();
var qtip = scratch.qtip = scratch.qtip || {};
var opts = generateOpts( ele, passedOpts );
var adjNums = opts.position.adjust;
qtip.$domEle.qtip( opts );
var qtipApi = qtip.api = qtip.$domEle.qtip('api'); // save api ref
qtip.$domEle.removeData('qtip'); // remove qtip dom/api ref to be safe
var updatePosition = function(e){
var cOff = container.getBoundingClientRect();
var pos = ele.renderedPosition() || ( e ? e.cyRenderedPosition : undefined );
if( !pos || pos.x == null || isNaN(pos.x) ){ return; }
if( opts.position.adjust.cyAdjustToEleBB && ele.isNode() ){
var my = opts.position.my.toLowerCase();
var at = opts.position.at.toLowerCase();
var z = cy.zoom();
var w = ele.outerWidth() * z;
var h = ele.outerHeight() * z;
if( at.match('top') ){
pos.y -= h/2;
} else if( at.match('bottom') ){
pos.y += h/2;
}
if( at.match('left') ){
pos.x -= w/2;
} else if( at.match('right') ){
pos.x += w/2;
}
if( $$.is.number(adjNums.x) ){
pos.x += adjNums.x;
}
if( $$.is.number(adjNums.y) ){
pos.y += adjNums.y;
}
}
qtipApi.set('position.adjust.x', cOff.left + pos.x + window.pageXOffset);
qtipApi.set('position.adjust.y', cOff.top + pos.y + window.pageYOffset);
};
updatePosition();
ele.on( opts.show.event, function(e){
updatePosition(e);
qtipApi.show();
} );
ele.on( opts.hide.event, function(e){
qtipApi.hide();
} );
if( opts.hide.cyViewport ){
cy.on('viewport', $$.util.debounce(function(){
qtipApi.hide();
}, viewportDebounceRate, { leading: true }) );
}
if( opts.position.adjust.cyViewport ){
cy.on('pan zoom', $$.util.debounce(function(e){
updatePosition(e);
qtipApi.reposition();
}, viewportDebounceRate, { trailing: true }) );
}
});
return this; // chainability
});
$$('core', 'qtip', function( passedOpts ){
var cy = this;
var container = cy.container();
if( passedOpts === 'api' ){
return this.scratch().qtip.api;
}
var scratch = cy.scratch();
var qtip = scratch.qtip = scratch.qtip || {};
var opts = generateOpts( cy, passedOpts );
qtip.$domEle.qtip( opts );
var qtipApi = qtip.api = qtip.$domEle.qtip('api'); // save api ref
qtip.$domEle.removeData('qtip'); // remove qtip dom/api ref to be safe
var updatePosition = function(e){
var cOff = container.getBoundingClientRect();
var pos = e.cyRenderedPosition;
if( !pos || pos.x == null || isNaN(pos.x) ){ return; }
qtipApi.set('position.adjust.x', cOff.left + pos.x + window.pageXOffset);
qtipApi.set('position.adjust.y', cOff.top + pos.y + window.pageYOffset);
};
cy.on( opts.show.event, function(e){
if( !opts.show.cyBgOnly || (opts.show.cyBgOnly && e.cyTarget === cy) ){
updatePosition(e);
qtipApi.show();
}
} );
cy.on( opts.hide.event, function(e){
if( !opts.hide.cyBgOnly || (opts.hide.cyBgOnly && e.cyTarget === cy) ){
qtipApi.hide();
}
} );
if( opts.hide.cyViewport ){
cy.on('viewport', $$.util.debounce(function(){
qtipApi.hide();
}, viewportDebounceRate, { leading: true }) );
}
return this; // chainability
});
}
if( typeof module !== 'undefined' && module.exports ){ // expose as a commonjs module
module.exports = register;
}
if( typeof define !== 'undefined' && define.amd ){ // expose as an amd/requirejs module
define('cytoscape-qtip', function(){
return register;
});
}
if( $ && $$ ){
register( $$, $ );
}
})( jQuery, cytoscape );
| JavaScript | 0 | @@ -1569,15 +1569,18 @@
= '
-unfocus
+mouseleave
';%0A
|
6e6cdddc21530cccc64655eb92eb8245d70b4568 | update testing case | plugin/miHome/index.js | plugin/miHome/index.js | var miio = require('./lib');
// var vacuum = python.import('mirobot/protocol');
class MiHome {
constructor (name, ip, port, token, model) {
this.ip = ip;
this.port = port
this.token = token;
this.name = name
this.model = model
this.device = null;
}
load () {
var that = this;
return that.loading = new Promise(function(resolve, reject){
if (that.model == 'vacuum') {
that.device = miio.createDevice({
address: that.ip,
token: that.token,
model: 'rockrobo.vacuum.v1'
});
that.device.init()
.then(() => {
console.log(that.model + " init success");
resolve(that);
})
.catch(err => {
console.error(that.model + " init error: " + err);
reject(err);
});
}
else {
if (that.token == null) {
var para = { address: that.ip };
}
else {
var para = { address: that.ip, token: that.token };
};
miio.device(para)
.then(device => {
that.device = device;
console.log(that.name + " " + that.device.type + " init success");
resolve(that);
})
.catch(err => {
console.error(that.name + " init error: " + err);
reject(err);
});
}
});
}
exec(cmd) {
var that = this;
if (cmd == 'Stop') {
cmd = 'Charge';
}
switch (cmd) {
case 'Start':
if (this.device.type == 'vacuum') {
this.device.start()
.then(res => console.log(this.name + " start result : " + res))
.catch(err => console.error(this.name + " start error: " + err));
}
break;
case 'Charge':
if (this.device.type == 'vacuum') {
this.device.charge()
.then(res => console.log(this.name + " charge result : " + res))
.catch(err => console.error(this.name + " charge error: " + err));
}
break;
case 'Pause':
if (this.device.type == 'vacuum') {
this.device.pause()
.then(res => console.log(this.name + " pause result : " + res))
.catch(err => console.error(this.name + " pause error: " + err));
}
break;
case 'List':
if (this.device.type == 'gateway') {
this.list();
}
break;
case 'PowerOff':
if (this.device.type == 'light') {
this.device.setPower(false)
.then(res => console.log(this.name + " PowerOff result : " + res))
.catch(err => console.error(this.name + " PowerOff error: " + err));
}
else {
this.powerSet(false);
}
break;
case 'PowerOn':
if (this.device.type == 'light') {
this.device.setPower(true)
.then(res => console.log(this.name + " PowerOn result : " + res))
.catch(err => console.error(this.name + " PowerOn error: " + err));
}
else {
this.powerSet(true);
}
break;
case 'PowerStatus':
this.powerStatus();
break;
case 'LightStatus':
if (this.device.type == 'light') {
console.log(this.name + " Color Temp: " + this.device.colorTemperature);
}
break;
default:
console.log('Invalid type:' + cmd);
}
return;
}
powerOn() {
var that = this;
if(this.device.hasCapability('power')) {
this.device.setPower(true)
.then(console.log(this.name + ":Power On"))
.catch(console.error(this.name + "Failed to Power On"));
}
}
_deviecPowerSet(inputDevice, cmd) {
var that = this;
for (var i=0; i<inputDevice.powerChannels.length; i++) {
console.log("Chan " + i);
inputDevice.setPower(i, cmd)
.then(power => console.log(inputDevice.type + " Power " + power))
.catch(err => console.error(inputDevice.type + " Failed: " + err));
}
}
_deviecPowerStatus(inputDevice) {
var that = this;
for (var i=0; i<inputDevice.powerChannels.length; i++) {
console.log(inputDevice.type + " power " + inputDevice.power(JSON.stringify(i)));
}
}
powerSet(cmd) {
var that = this;
if(that.device.type == 'gateway') {
that.device.on('deviceAvailable', subDevice => {
if (subDevice.type == 'power-plug') {
that._deviecPowerSet(subDevice,cmd);
}
return;
});
}
else {
that._deviecPowerSet(that.device,cmd);
}
}
powerStatus() {
var that = this;
if(that.device.type == 'gateway') {
that.device.on('deviceAvailable', subDevice => {
if (subDevice.type == 'power-plug') {
that._deviecPowerStatus(subDevice);
}
return;
});
}
else {
that._deviecPowerStatus(that.device);
}
}
list() {
var that = this;
console.log('All SubDevice:');
that.device.on('deviceAvailable', subDevice => {
console.log('ID: ' + subDevice.id + ' Model:' + subDevice.model + ' Type:' + subDevice.type );
if (subDevice.type == 'controller') {
console.log('ID: ' + subDevice.id + ' Model:' + subDevice.model + ' Type:' + subDevice.type );
debugger;
subDevice.call('set_status', [ 'status','click' ])
.then(console.log("click ok"))
.catch(console.error("click failed"));
}
return;
});
if(that.device.devices) {
that.device.devices.forEach(function(item){
console.log('-' + item);
})
}
}
};
module.exports = MiHome; | JavaScript | 0 | @@ -5609,68 +5609,17 @@
og('
-ID: ' + subDevice.id + ' Model:' + subDevice.model + ' Type:
+Actions:
' +
@@ -5620,36 +5620,39 @@
: ' + subDevice.
-type
+actions
);%0D%0A d
|
17b508c2ebd28975018871f2684b15658fee2c94 | Add class names | src/js/WinJS/Controls/ToggleSwitchNew.js | src/js/WinJS/Controls/ToggleSwitchNew.js | // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
define([
'../Core/_Global',
'../Core/_Base',
'../Core/_BaseUtils',
'../Core/_Events',
'../Core/_Resources',
'../Utilities/_Control',
'../Utilities/_ElementUtilities',
'require-style!less/desktop/controls',
'require-style!less/phone/controls'
],
function toggleNewInit(_Global, _Base, _BaseUtils, _Events, _Resources, _Control, _ElementUtilities) {
"use strict";
_Base.Namespace.define("WinJS.UI", {
ToggleSwitchNew: _Base.Namespace._lazy(function() {
// Define the ToggleSwitch class
var Toggle = _Base.Class.define(function ToggleSwitchNew_ctor(element, options) {
// Constructor
// Set up DOM elements
// Main container
element = element || _Global.document.createElement('div');
this._domElement = element;
// Header/Title text
this._headerElement = _Global.document.createElement('div');
// Clickable region
this._clickElement = _Global.document.createElement('div');
// Slider track
this._trackElement = _Global.document.createElement('div');
// Lower portion of slider
this._fillLowerElement = _Global.document.createElement('div');
// Thumb element
this._thumbElement = _Global.document.createElement('div');
// Upper portion of slider
this._fillUpperElement = _Global.document.createElement('div');
// Current value label
this._valueElement = _Global.document.createElement('div');
// Description text
this._descriptionElement = _Global.document.createElement('div');
// Some initialization of main element
element.winControl = this;
_ElementUtilities.addClass(element, 'win-disposable');
}, {
// Properties
element: {
get: function() {return this._domElement;}
}
});
// addEventListener, removeEventListener, dispatchEvent
_Base.Class.mix(Toggle, _Control.DOMEventMixin);
return Toggle;
})
});
}
); | JavaScript | 0.000169 | @@ -701,16 +701,654 @@
on() %7B%0A%0A
+ // Store some class names%0A var classContainer = 'win-toggleswitch-new';%0A var classHeader = 'win-toggleswitch-header-new';%0A var classTrack = 'win-toggleswitch-track-new';%0A var classFill = 'win-toggleswitch-fill-new';%0A var classFillLower = 'win-toggleswitch-fill-lower-new';%0A var classFillUpper = 'win-toggleswitch-fill-upper-new';%0A var classThumb = 'win-toggleswitch-thumb-new';%0A var classValue = 'win-toggleswitch-value-new';%0A var classDescription = 'win-toggleswitch-description-new';%0A%0A
@@ -1731,16 +1731,98 @@
element;
+%0A _ElementUtilities.addClass(this._domElement, classContainer);
%0A%0A
@@ -1928,32 +1928,185 @@
eElement('div');
+%0A _ElementUtilities.addClass(this._headerElement, classHeader);%0A this._domElement.appendChild(this._headerElement);
%0A%0A
@@ -2202,32 +2202,102 @@
eElement('div');
+%0A this._domElement.appendChild(this._clickElement);
%0A%0A
@@ -2402,638 +2402,1756 @@
');%0A
-%0A // Lower portion of slider%0A this._fillLowerElement = _Global.document.createElement('div');%0A%0A // Thumb element%0A this._thumbElement = _Global.document.createElement('div');%0A%0A // Upper portion of slider%0A this._fillUpperElement = _Global.document.createElement('div');%0A%0A // Current value label%0A this._valueElement = _Global.document.createElement('div');%0A%0A // Description text%0A this._descriptionElement = _Global.document.createElement('div'
+ _ElementUtilities.addClass(this._trackElement, classTrack);%0A this._clickElement.appendChild(this._trackElement);%0A%0A // Lower portion of slider%0A this._fillLowerElement = _Global.document.createElement('div');%0A _ElementUtilities.addClass(this._fillLowerElement, classFill);%0A _ElementUtilities.addClass(this._fillLowerElement, classFillLower);%0A this._trackElement.appendChild(this._fillLowerElement);%0A%0A // Thumb element%0A this._thumbElement = _Global.document.createElement('div');%0A _ElementUtilities.addClass(this._thumbElement, classThumb);%0A this._trackElement.appendChild(this._thumbElement);%0A%0A // Upper portion of slider%0A this._fillUpperElement = _Global.document.createElement('div');%0A _ElementUtilities.addClass(this._fillUpperElement, classFill);%0A _ElementUtilities.addClass(this._fillUpperElement, classFillUpper);%0A this._trackElement.appendChild(this._fillUpperElement);%0A%0A // Current value label%0A this._valueElement = _Global.document.createElement('div');%0A _ElementUtilities.addClass(this._valueElement, classValue);%0A this._clickElement.appendChild(this._valueElement);%0A%0A // Description text%0A this._descriptionElement = _Global.document.createElement('div');%0A _ElementUtilities.addClass(this._descriptionElement, classDescription);%0A this._domElement.appendChild(this._descriptionElement
);%0A%0A
|
3125bc4c48731f49b2d17f1462e8c2b658c709d5 | Test Mark Repo as read store | src/js/__tests__/stores/notifications.js | src/js/__tests__/stores/notifications.js | /*global jest, describe, it, expect, spyOn, beforeEach */
'use strict';
jest.dontMock('reflux');
jest.dontMock('../../stores/notifications.js');
jest.dontMock('../../utils/api-requests.js');
jest.dontMock('../../actions/actions.js');
describe('Tests for NotificationsStore', function () {
var NotificationsStore, Actions, apiRequests;
beforeEach(function () {
// Mock Electron's window.require
window.require = function () {
return {
sendChannel: function () {
return;
}
};
};
// Mock localStorage
window.localStorage = {
item: false,
getItem: function () {
return this.item;
},
setItem: function (item) {
this.item = item;
}
};
// Mock Audio
window.Audio = function () {
return {
play: function () {}
};
};
// Mock Notifications
window.Notification = function () {
return {
onClick: function () {}
};
};
Actions = require('../../actions/actions.js');
apiRequests = require('../../utils/api-requests.js');
NotificationsStore = require('../../stores/notifications.js');
});
it('should get the notifications from the GitHub API', function () {
spyOn(NotificationsStore, 'trigger');
var response = [{
'id': '1',
'repository': {
'id': 1296269,
'owner': {
'login': 'octocat',
'id': 1,
'avatar_url': 'https://github.com/images/error/octocat_happy.gif',
'gravatar_id': '',
'url': 'https://api.github.com/users/octocat',
'html_url': 'https://github.com/octocat',
'followers_url': 'https://api.github.com/users/octocat/followers',
'following_url': 'https://api.github.com/users/octocat/following{/other_user}',
'gists_url': 'https://api.github.com/users/octocat/gists{/gist_id}',
'starred_url': 'https://api.github.com/users/octocat/starred{/owner}{/repo}',
'subscriptions_url': 'https://api.github.com/users/octocat/subscriptions',
'organizations_url': 'https://api.github.com/users/octocat/orgs',
'repos_url': 'https://api.github.com/users/octocat/repos',
'events_url': 'https://api.github.com/users/octocat/events{/privacy}',
'received_events_url': 'https://api.github.com/users/octocat/received_events',
'type': 'User',
'site_admin': false
},
'name': 'Hello-World',
'full_name': 'octocat/Hello-World',
'description': 'This your first repo!',
'private': false,
'fork': false,
'url': 'https://api.github.com/repos/octocat/Hello-World',
'html_url': 'https://github.com/octocat/Hello-World'
},
'subject': {
'title': 'Greetings',
'url': 'https://api.github.com/repos/octokit/octokit.rb/issues/123',
'latest_comment_url': 'https://api.github.com/repos/octokit/octokit.rb/issues/comments/123',
'type': 'Issue'
},
'reason': 'subscribed',
'unread': true,
'updated_at': '2014-11-07T22:01:45Z',
'last_read_at': '2014-11-07T22:01:45Z',
'url': 'https://api.github.com/notifications/threads/1'
}];
var superagent = require('superagent');
superagent.__setResponse(200, 'ok', response, false);
Actions.getNotifications();
jest.runAllTimers();
var repository = NotificationsStore._notifications[0].repository;
var subjectTitle = NotificationsStore._notifications[0].subject.title;
expect(repository.full_name).toBe('octocat/Hello-World');
expect(subjectTitle).toBe('Greetings');
expect(NotificationsStore.trigger).toHaveBeenCalled();
});
it('should get 0(zero) notifications from the GitHub API', function () {
spyOn(NotificationsStore, 'trigger');
var response = [];
var superagent = require('superagent');
superagent.__setResponse(200, 'ok', response, false);
Actions.getNotifications();
jest.runAllTimers();
expect(NotificationsStore._notifications.length).toBe(0);
expect(NotificationsStore.trigger).toHaveBeenCalled();
});
it('should FAIL to get the notifications from the GitHub API', function () {
spyOn(NotificationsStore, 'trigger');
spyOn(NotificationsStore, 'onGetNotificationsFailed');
var superagent = require('superagent');
superagent.__setResponse(400, false);
Actions.getNotifications();
jest.runAllTimers();
expect(NotificationsStore.trigger).toHaveBeenCalled();
});
});
| JavaScript | 0 | @@ -4541,12 +4541,764 @@
%0A %7D);%0A%0A
+ it('should mark a repo as read - remove notifications from store', function () %7B%0A%0A spyOn(NotificationsStore, 'trigger');%0A%0A NotificationsStore._notifications = %5B%0A %7B%0A 'id': '1',%0A 'repository': %7B%0A 'full_name': 'ekonstantinidis/gitify',%0A %7D,%0A 'unread': true%0A %7D,%0A %7B%0A 'id': '2',%0A 'repository': %7B%0A 'full_name': 'ekonstantinidis/gitify',%0A %7D,%0A 'reason': 'subscribed'%0A %7D%0A %5D;%0A%0A expect(NotificationsStore._notifications.length).toBe(2);%0A%0A Actions.removeRepoNotifications('ekonstantinidis/gitify');%0A%0A jest.runAllTimers();%0A%0A expect(NotificationsStore._notifications.length).toBe(0);%0A expect(NotificationsStore.trigger).toHaveBeenCalled();%0A%0A %7D);%0A%0A
%7D);%0A
|
c337a0c224426c0f5e5b9c360e1b5e3b8a2cd29a | add index for rate slider | src/js/containers/Market/RateSliderV2.js | src/js/containers/Market/RateSliderV2.js | import React from "react"
import { connect } from "react-redux"
// import Slider from "react-slick"
import { toT, roundingNumber } from "../../utils/converter"
import constants from "../../services/constants"
function getPriceToken(token) {
if (token.ETH.buyPrice == 0 || token.ETH.sellPrice == 0) {
return token.ETH.buyPrice + token.ETH.sellPrice
} else {
return (token.ETH.buyPrice + token.ETH.sellPrice) / 2
}
}
@connect((store) => {
// get array tokens
var tokens = store.market.tokens
var listTokens = []
Object.keys(tokens).forEach((key) => {
var price = getPriceToken(tokens[key])
if (price != 0) {
listTokens.push(tokens[key])
}
})
return {
listTokens
}
})
export default class RateSilderV2 extends React.Component {
constructor() {
super()
this.state = {
numDisplay: 7,
page: 0,
intervalUpdatePage: false,
intervalTime: 7000
}
}
componentDidMount = () => {
if(window.innerWidth < 992){
this.setState({
numDisplay: 5
})
}
this.intervalUpdatePage = setInterval(() => {
this.increasePage()
}, this.state.intervalTime)
}
componentWillUnmount = () => {
clearInterval(this.intervalUpdatePage)
this.intervalUpdatePage = false
}
clickIncreasePage = () => {
this.increasePage()
clearInterval(this.intervalUpdatePage)
this.intervalUpdatePage = setInterval(() => {
this.increasePage()
}, this.state.intervalTime)
}
increasePage = () => {
if (this.state.page >= this.props.listTokens.length / this.state.numDisplay - 1) {
this.setState({
page: 0
})
} else {
this.setState({
page: this.state.page + 1
})
}
}
// getPriceToken = (token) => {
// if (token.ETH.buyPrice == 0 || token.ETH.sellPrice == 0) {
// return token.ETH.buyPrice + token.ETH.sellPrice
// } else {
// return (token.ETH.buyPrice + token.ETH.sellPrice) / 2
// }
// }
getListDisplay = () => {
var currentPage = this.state.page
var listDisplay = []
var listTokens = this.props.listTokens
//console.log(listTokens)
for (var i = currentPage * this.state.numDisplay; i < (currentPage + 1) * this.state.numDisplay; i++) {
if (i < listTokens.length) {
if (listTokens[i]) listDisplay.push(listTokens[i])
} else {
if (listTokens[i - listTokens.length]) listDisplay.push(listTokens[i - listTokens.length])
}
}
return listDisplay
}
render() {
var listDisplay = this.getListDisplay()
//console.log(listDisplay)
var rateContent = listDisplay.map(value => {
var rateChange = value.ETH.change
var symbol = value.info.symbol
var price = getPriceToken(value)
return (
<div key={symbol}>
<div className="rate-item">
{rateChange > 0 && rateChange != -9999 && (
<div className="change-positive rate-item__percent-change"></div>
)}
{rateChange < 0 && rateChange != -9999 && (
<div className="change-negative rate-item__percent-change"></div>
)}
<div>
<div class="pair">{symbol}</div>
<div class="value up">
{roundingNumber(price)}
</div>
<div class="percent-change">{rateChange === -9999 ? "---" : Math.abs(rateChange)} %</div>
</div>
</div>
</div>
)
})
return (
<div id="rate-bar">
<div className="rate" onClick={this.clickIncreasePage}>
{rateContent}
</div>
</div>
)
}
}
| JavaScript | 0 | @@ -2976,21 +2976,30 @@
lay.map(
+(
value
+, index)
=%3E %7B%0A
@@ -3183,16 +3183,22 @@
=%7Bsymbol
++index
%7D%3E%0A
|
3582fd3ba979aba3bd241b5df1fb4ddba6504628 | Make flashing cursor behave like MSWord | src/mixins/itext_click_behavior.mixin.js | src/mixins/itext_click_behavior.mixin.js | fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
/**
* Initializes "dbclick" event handler
*/
initDoubleClickSimulation: function() {
// for double click
this.__lastClickTime = +new Date();
// for triple click
this.__lastLastClickTime = +new Date();
this.lastPointer = { };
this.on('mousedown', this.onMouseDown.bind(this));
},
onMouseDown: function(options) {
this.__newClickTime = +new Date();
var newPointer = this.canvas.getPointer(options.e);
if (this.isTripleClick(newPointer)) {
this.fire('tripleclick', options);
this._stopEvent(options.e);
}
else if (this.isDoubleClick(newPointer)) {
this.fire('dblclick', options);
this._stopEvent(options.e);
}
this.__lastLastClickTime = this.__lastClickTime;
this.__lastClickTime = this.__newClickTime;
this.__lastPointer = newPointer;
this.__lastEditing = this.isEditing;
},
isDoubleClick: function(newPointer) {
return this.__newClickTime - this.__lastClickTime < 500 &&
this.__lastPointer.x === newPointer.x &&
this.__lastPointer.y === newPointer.y && this.__lastEditing;
},
isTripleClick: function(newPointer) {
return this.__newClickTime - this.__lastClickTime < 500 &&
this.__lastClickTime - this.__lastLastClickTime < 500 &&
this.__lastPointer.x === newPointer.x &&
this.__lastPointer.y === newPointer.y;
},
/**
* @private
*/
_stopEvent: function(e) {
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
},
/**
* Initializes event handlers related to cursor or selection
*/
initCursorSelectionHandlers: function() {
this.initSelectedHandler();
this.initMousedownHandler();
this.initMousemoveHandler();
this.initMouseupHandler();
this.initClicks();
},
/**
* Initializes double and triple click event handlers
*/
initClicks: function() {
this.on('dblclick', function(options) {
this.selectWord(this.getSelectionStartFromPointer(options.e));
});
this.on('tripleclick', function(options) {
this.selectLine(this.getSelectionStartFromPointer(options.e));
});
},
/**
* Initializes "mousedown" event handler
*/
initMousedownHandler: function() {
this.on('mousedown', function(options) {
var pointer = this.canvas.getPointer(options.e);
this.__mousedownX = pointer.x;
this.__mousedownY = pointer.y;
this.__isMousedown = true;
if (this.hiddenTextarea && this.canvas) {
this.canvas.wrapperEl.appendChild(this.hiddenTextarea);
}
if (this.isEditing) {
this.setCursorByClick(options.e);
this.__selectionStartOnMouseDown = this.selectionStart;
}
});
},
/**
* Initializes "mousemove" event handler
*/
initMousemoveHandler: function() {
this.on('mousemove', function(options) {
if (!this.__isMousedown || !this.isEditing) return;
var newSelectionStart = this.getSelectionStartFromPointer(options.e);
if (newSelectionStart >= this.__selectionStartOnMouseDown) {
this.setSelectionStart(this.__selectionStartOnMouseDown);
this.setSelectionEnd(newSelectionStart);
}
else {
this.setSelectionStart(newSelectionStart);
this.setSelectionEnd(this.__selectionStartOnMouseDown);
}
});
},
/**
* @private
*/
_isObjectMoved: function(e) {
var pointer = this.canvas.getPointer(e);
return this.__mousedownX !== pointer.x ||
this.__mousedownY !== pointer.y;
},
/**
* Initializes "mouseup" event handler
*/
initMouseupHandler: function() {
this.on('mouseup', function(options) {
this.__isMousedown = false;
if (this._isObjectMoved(options.e)) return;
if (this.selected) {
this.enterEditing();
}
});
},
/**
* Changes cursor location in a text depending on passed pointer (x/y) object
* @param {Object} pointer Pointer object with x and y numeric properties
*/
setCursorByClick: function(e) {
var newSelectionStart = this.getSelectionStartFromPointer(e);
if (e.shiftKey) {
if (newSelectionStart < this.selectionStart) {
this.setSelectionEnd(this.selectionStart);
this.setSelectionStart(newSelectionStart);
}
else {
this.setSelectionEnd(newSelectionStart);
}
}
else {
this.setSelectionStart(newSelectionStart);
this.setSelectionEnd(newSelectionStart);
}
},
/**
* @private
* @param {Event} e Event object
* @param {Object} Object with x/y corresponding to local offset (according to object rotation)
*/
_getLocalRotatedPointer: function(e) {
var pointer = this.canvas.getPointer(e),
pClicked = new fabric.Point(pointer.x, pointer.y),
pLeftTop = new fabric.Point(this.left, this.top),
rotated = fabric.util.rotatePoint(
pClicked, pLeftTop, fabric.util.degreesToRadians(-this.angle));
return this.getLocalPointer(e, rotated);
},
/**
* Returns index of a character corresponding to where an object was clicked
* @param {Event} e Event object
* @return {Number} Index of a character
*/
getSelectionStartFromPointer: function(e) {
var mouseOffset = this._getLocalRotatedPointer(e),
textLines = this.text.split(this._reNewline),
prevWidth = 0,
width = 0,
height = 0,
charIndex = 0,
newSelectionStart;
for (var i = 0, len = textLines.length; i < len; i++) {
height += this._getHeightOfLine(this.ctx, i) * this.scaleY;
var widthOfLine = this._getWidthOfLine(this.ctx, i, textLines);
var lineLeftOffset = this._getLineLeftOffset(widthOfLine);
width = lineLeftOffset;
if (this.flipX) {
// when oject is horizontally flipped we reverse chars
textLines[i] = textLines[i].split('').reverse().join('');
}
for (var j = 0, jlen = textLines[i].length; j < jlen; j++) {
var _char = textLines[i][j];
prevWidth = width;
width += this._getWidthOfChar(this.ctx, _char, i, this.flipX ? jlen - j : j) *
this.scaleX;
if (height <= mouseOffset.y || width <= mouseOffset.x) {
charIndex++;
continue;
}
return this._getNewSelectionStartFromOffset(
mouseOffset, prevWidth, width, charIndex + i, jlen);
}
if(mouseOffset.y < height){
return this._getNewSelectionStartFromOffset(
mouseOffset, prevWidth, width, charIndex + i, jlen, j);
}
}
// clicked somewhere after all chars, so set at the end
if (typeof newSelectionStart === 'undefined') {
return this.text.length;
}
},
/**
* @private
*/
_getNewSelectionStartFromOffset: function(mouseOffset, prevWidth, width, index, jlen, j) {
var distanceBtwLastCharAndCursor = mouseOffset.x - prevWidth,
distanceBtwNextCharAndCursor = width - mouseOffset.x,
offset = distanceBtwNextCharAndCursor > distanceBtwLastCharAndCursor ? 0 : 1,
newSelectionStart = index + offset;
// if object is horizontally flipped, mirror cursor location from the end
if (this.flipX) {
newSelectionStart = jlen - newSelectionStart;
}
if (newSelectionStart > this.text.length) {
newSelectionStart = this.text.length;
}
if(j == jlen){
newSelectionStart--;
}
return newSelectionStart;
}
});
| JavaScript | 0.000038 | @@ -3899,24 +3899,62 @@
rEditing();%0A
+ this.initDelayedCursor(true);%0A
%7D%0A
|
eefe5f7a8064afd01aeb97e65eac70af7c0c7b33 | Fix - don't display licence badge when licence data not fetched from server yet | codebrag-ui/app/scripts/licence/licenceService.js | codebrag-ui/app/scripts/licence/licenceService.js | angular.module('codebrag.licence')
.service('licenceService', function($http, $q, $rootScope, events, $timeout, $modal) {
var warningDays = 14,
licenceData = {},
ready = $q.defer(),
checkTimer,
checkInterval = 6 * 3600 * 1000; // 6 hours (in millis)
function scheduleLicenceCheck() {
ready = $q.defer();
return loadLicenceData().then(scheduleNextCheck).then(fireEvents).then(function() {
ready.resolve();
});
function scheduleNextCheck() {
checkTimer && $timeout.cancel(checkTimer);
checkTimer = $timeout(function() {
loadLicenceData().then(scheduleNextCheck).then(fireEvents)
}, checkInterval);
}
}
function loadLicenceData() {
return $http.get('rest/licence').then(function(response) {
licenceData = response.data;
return licenceData;
});
}
function serviceReady() {
return ready.promise;
}
function getLicenceData() {
return licenceData;
}
function fireEvents() {
var daysToWarning = licenceData.daysLeft - warningDays;
if(licenceData.valid && daysToWarning < 0) {
$rootScope.$broadcast('codebrag:licenceAboutToExpire');
}
if(!licenceData.valid && !fireEvents.initialExpirationEvent) {
$rootScope.$broadcast('codebrag:licenceExpired');
fireEvents.initialExpirationEvent = true
}
}
function initialize() {
$rootScope.$on(events.loggedIn, scheduleLicenceCheck);
$rootScope.$on('codebrag:openLicencePopup', licencePopup);
$rootScope.$on('codebrag:licenceExpired',licencePopup);
}
function licencePopup(once) {
if(licencePopup.displayed) return;
var repoStatusModalConfig = {
backdrop: false,
keyboard: true,
controller: 'LicenceInfoCtrl',
resolve: {
licenceData: loadLicenceData
},
templateUrl: 'views/popups/licenceInfo.html'
};
licencePopup.displayed = true;
$modal.open(repoStatusModalConfig).result.then(function() {
licencePopup.displayed = false;
}, function() {
licencePopup.displayed = false;
})
}
return {
ready: serviceReady,
getLicenceData: getLicenceData,
loadLicenceData: loadLicenceData,
licencePopup: licencePopup,
initialize: initialize
};
}); | JavaScript | 0 | @@ -352,40 +352,8 @@
) %7B%0A
- ready = $q.defer();%0A
@@ -436,32 +436,73 @@
en(function() %7B%0A
+ console.log('resolved');%0A
@@ -1514,24 +1514,60 @@
ionEvent) %7B%0A
+ console.log('aaa');%0A
|
686252c08d65413de56fde49440b101a8b00b91e | Fix types for range | src/modules/store/ConnectTypes.js | src/modules/store/ConnectTypes.js | /* @flow */
export type Subscription = {
remove: () => void
}
export type SubscriptionSlice = {
type: string;
order: string;
filter?: Object;
}
export type SubscriptionRange = {
start?: number,
before?: number,
after?: number
}
export type Store = {
subscribe(
options: {
what?: string;
slice?: SubscriptionSlice;
range?: SubscriptionRange;
},
callback: Function
): Subscription;
[key: string]: Function;
}
export type MapSubscriptionToProps = {
[key: string]: string | {
key: string | {
type?: string;
slice?: SubscriptionSlice;
range?: SubscriptionRange;
};
transform?: Function;
}
};
export type MapSubscriptionToPropsCreator = (props: Object) => MapSubscriptionToProps;
export type MapActionsToProps = {
[key: string]: (props: Object, store: Store) => Function
};
| JavaScript | 0 | @@ -184,19 +184,19 @@
%7B%0A%09start
-?
:
+?
number,%0A
@@ -202,19 +202,19 @@
%0A%09before
-?
:
+?
number,%0A
@@ -219,19 +219,19 @@
,%0A%09after
-?
:
+?
number%0A%7D
|
9d8ce434a6869a6dfb458bf1f87fcd5d586ab038 | Fix task priority level | SingularityUI/app/components/requestForm/fields.es6 | SingularityUI/app/components/requestForm/fields.es6 | import Utils from '../../utils';
const QUARTZ_SCHEDULE_FIELD = {id: 'quartzSchedule', type: 'string', required: true};
const CRON_SCHEDULE_FIELD = {id: 'cronSchedule', type: 'string', required: true};
const INSTANCES_FIELD = {id: 'instances', type: 'number'};
const RACK_SENSITIVE_FIELD = {id: 'rackSensitive', type: 'bool'};
const HIDE_EVEN_NUMBERS_ACROSS_RACKS_HINT_FIELD = {id: 'hideEvenNumberAcrossRacksHint', type: 'bool'};
const EXECUTION_TIME_LIMIT_FIELD = {id: 'taskExecutionTimeLimitMillis', type: 'number'}
const RACK_AFFINITY_FIELD = {
id: 'rackAffinity',
type: {
typeName: 'array',
arrayType: 'string'
}
};
const KILL_OLD_NRL_FIELD = {id: 'killOldNonLongRunningTasksAfterMillis', type: 'number'};
const BOUNCE_AFTER_SCALE_FIELD = {id: 'bounceAfterScale', type: 'bool'};
export const FIELDS_BY_REQUEST_TYPE = {
ALL: [
{id: 'id', type: 'request-id', required: true},
{
id: 'owners',
type: {
typeName: 'array',
arrayType: 'string'
}
},
{id: 'requestType', type: { typeName: 'enum', enumType: Utils.enums.SingularityRequestTypes}, required: true},
{id: 'agentPlacement', type: 'string'},
{
id: 'requiredAgentAttributes',
type: {
typeName: 'map',
mapFrom: 'string',
mapTo: 'string'
}
},
{
id: 'allowedAgentAttributes',
type: {
typeName: 'map',
mapFrom: 'string',
mapTo: 'string'
}
},
{id: 'group', type: 'string'},
{id: 'maxTasksPerOffer', type: 'number'},
{id: 'taskLogErrorRegex', type: 'string'},
{id: 'taskLogErrorRegexCaseSensitive', type: 'bool'},
{
id: 'readOnlyGroups',
type: {
typeName: 'array',
arrayType: 'string'
}
},
{
id: 'readWriteGroups',
type: {
typeName: 'array',
arrayType: 'string'
}
},
{id: 'skipHealthchecks', type: 'bool'},
{
id: 'emailConfigurationOverrides',
type: {
typeName: 'map',
mapFrom: {
typeName: 'enum',
enumType: Utils.enums.SingularityEmailType
},
mapTo: {
typeName: 'array',
arrayType: {
typeName: 'enum',
enumType: Utils.enums.SingularityEmailDestination
}
}
}
}
],
SERVICE: [
INSTANCES_FIELD,
RACK_SENSITIVE_FIELD,
HIDE_EVEN_NUMBERS_ACROSS_RACKS_HINT_FIELD,
{id: 'loadBalanced', type: 'bool'},
{id: 'allowBounceToSameHost', type: 'bool'},
RACK_AFFINITY_FIELD,
BOUNCE_AFTER_SCALE_FIELD
],
WORKER: [
INSTANCES_FIELD,
RACK_SENSITIVE_FIELD,
HIDE_EVEN_NUMBERS_ACROSS_RACKS_HINT_FIELD,
{id: 'waitAtLeastMillisAfterTaskFinishesForReschedule', type: 'number'},
{id: 'allowBounceToSameHost', type: 'bool'},
RACK_AFFINITY_FIELD,
BOUNCE_AFTER_SCALE_FIELD
],
SCHEDULED: [
QUARTZ_SCHEDULE_FIELD,
CRON_SCHEDULE_FIELD,
{id: 'scheduleTimeZone', type: 'string'},
{id: 'scheduleType', type: 'string'},
{id: 'numRetriesOnFailure', type: 'number'},
KILL_OLD_NRL_FIELD,
{id: 'scheduledExpectedRuntimeMillis', type: 'number'},
EXECUTION_TIME_LIMIT_FIELD
],
ON_DEMAND: [
INSTANCES_FIELD,
{id: 'numRetriesOnFailure', type: 'number'},
KILL_OLD_NRL_FIELD,
EXECUTION_TIME_LIMIT_FIELD
],
RUN_ONCE: [KILL_OLD_NRL_FIELD, EXECUTION_TIME_LIMIT_FIELD]
};
function makeIndexedFields(fields) {
const indexedFields = {};
for (const field of fields) {
if (field.type === 'object') {
_.extend(indexedFields, makeIndexedFields(field.values));
} else {
indexedFields[field.id] = field;
}
}
return indexedFields;
}
export const INDEXED_FIELDS = _.extend(
{},
makeIndexedFields(FIELDS_BY_REQUEST_TYPE.ALL),
makeIndexedFields(FIELDS_BY_REQUEST_TYPE.SERVICE),
makeIndexedFields(FIELDS_BY_REQUEST_TYPE.WORKER),
makeIndexedFields(FIELDS_BY_REQUEST_TYPE.SCHEDULED),
makeIndexedFields(FIELDS_BY_REQUEST_TYPE.ON_DEMAND),
makeIndexedFields(FIELDS_BY_REQUEST_TYPE.RUN_ONCE)
);
| JavaScript | 0.998444 | @@ -1529,32 +1529,79 @@
ype: 'number'%7D,%0A
+ %7Bid: 'taskPriorityLevel', type: 'number'%7D,%0A
%7Bid: 'taskLo
|
54b299a6a8f04186187855c060cef793ff58c2b9 | fix image name being used as target name | chimera.js | chimera.js | #!/usr/bin/env node
var fs = require('fs');
var os = require('os');
var path = require('path');
var crypto = require('crypto');
var _ = require('underscore');
var Handlebars = require('handlebars');
var async = require('async');
var tar = require('tar-fs');
var Docker = require('dockerode');
var rimraf = require('rimraf');
var yaml = require('js-yaml');
var minimist = require('minimist');
var colors = require('colors');
var argv = (function(argv) {
return {
help: argv.h || argv.help,
version: argv.v || argv.version,
config: path.resolve(process.cwd(), argv.f || argv.file || '.chimera.yml'),
project: path.resolve(process.cwd(), argv.p || argv.project || './'),
target: argv.t || argv.target || process.env.CHIMERA_TARGET,
verbose: argv.V || argv.verbose,
_: argv._
};
}(minimist(process.argv.slice(2))));
var verbose = argv.verbose ?
function(arg) { console.log(arg); return arg;} :
function(arg) { return arg; };
var docker;
Handlebars.registerHelper('render', function(template, data) {
return new Handlebars.SafeString(Handlebars.compile(template)(data));
});
var dockerfile = Handlebars.compile([
'FROM {{name}}:{{tag}}',
'COPY project/ /project',
'WORKDIR /project',
'',
'ENV CHIMERA_TARGET={{name}}:{{tag}}',
'ENV CHIMERA_TARGET_NAME={{name}}',
'ENV CHIMERA_TARGET_TAG={{tag}}',
'{{#each env}}',
'ENV {{render this ../this}}',
'{{/each}}',
'',
'{{#each install}}',
'RUN {{render this ../this}}',
'{{/each}}',
'CMD {{script}}'
].join('\n'));
if (argv.help) {
console.log([
'',
'Usage: chimera [options]',
' chimera generate <ci-service>',
'',
'Easy multi-container testing with Docker',
'',
'Options:',
'',
' -h, --help output usage information',
' -v, --version output version',
' -c, --config <path> set configuration file',
' -p, --project <path> set project directory',
' -t, --target <image:tag> set target',
' -V, --verbose verbose mode'
].join('\n'));
process.exit(0);
}
if(argv.version) {
console.log('chimera version ' + require('./package.json').version);
process.exit(0);
}
fs.readFile(argv.config, 'utf8', function(err, raw) {
fail(err);
var config = yaml.safeLoad(raw);
docker = new Docker(config.docker);
targets(config, function(err, targets) {
fail(err);
switch (argv._[0]) {
case 'generate':
generate(targets);
break;
case 'run':
case undefined:
run(targets);
break;
default:
console.error('unknown command, see --help');
};
});
});
function generate(targets) {
switch (argv._[1]) {
case 'travis':
console.log(Handlebars.compile([
'language: node_js',
'sudo: required',
'services:',
' - docker',
'install:',
' - npm install -g chimera-cli',
'script:',
' - chimera',
'env:',
' matrix:',
'{{#each this}}',
' - CHIMERA_TARGET={{name}}:{{tag}}',
'{{/each}}'
].join('\n'))(targets));
break;
default:
console.error('unknown ci service, example: chimera generate travis');
};
};
function run(targets) {
async.eachSeries(targets, function(target, cb) {
console.log(('executing target ' + target.image).green);
async.applyEachSeries([bundle, build, test, clean], target, cb);
}, fail);
};
function targets(config, cb) {
cb(null, _.map(config.targets, function(target, name) {
return target.tags.map(function(tag) {
var id = crypto.randomBytes(5).toString('hex');
return {
name: target.image || name,
tag: tag,
id: id,
dir: path.join(os.tmpdir(), id),
tar: path.join(os.tmpdir(), id + '.tar'),
image: name + '-' + tag + '-' + id,
install: (target.install || []).concat(config.install || []),
env: (target.env || []).concat(config.env || []),
script: config.script.join(' && ') // TODO is this a good idea?
};
});
}).reduce(function(a, b) {
return a.concat(b);
}).filter(function(target) {
return !argv.target ||
target.name.indexOf(argv.target) === 0 ||
(target.name + ':' + target.tag).indexOf(argv.target) === 0;
}));
}
function bundle(target, cb) {
async.series([
fs.mkdir.bind(fs, target.dir),
fs.writeFile.bind(fs,
path.join(target.dir, 'Dockerfile'), verbose(dockerfile(target))),
fs.symlink.bind(fs, argv.project, path.join(target.dir, 'project')),
function(cb) {
tar.pack(target.dir, {dereference: true})
.pipe(fs.createWriteStream(target.tar))
.on('error', cb)
.on('finish', cb);
}
], cb);
}
function build(target, cb) {
docker.buildImage(target.tar, {t: target.image}, function(err, res) {
if(err) {
return cb(err);
}
res.on('data', function(data) {
var msg = JSON.parse(data);
if(msg.error) {
console.error(msg.error);
cb = cb.bind(null, new Error('failed to build image ' + target.image));
} else if(msg.stream || msg.status) {
verbose(msg.stream || msg.status);
}
});
res.on('end', cb);
});
}
function test(target, cb) {
docker.run(target.image, [], process.stdout, function(err, data, container) {
if(err) {
return cb(err);
}
if(data.StatusCode != 0) {
return cb(new Error('tests failed on ' + target.image));
}
target.container = container.id;
cb();
});
}
function clean(target, cb) {
var container = docker.getContainer(target.container);
var image = docker.getImage(target.image);
async.series([
rimraf.bind(rimraf, target.dir),
rimraf.bind(rimraf, target.tar),
container.remove.bind(container),
image.remove.bind(image)
], cb);
}
function fail(err) {
if(err) {
console.error(err.message.red);
process.exit(1);
}
}
| JavaScript | 0.000189 | @@ -1232,19 +1232,24 @@
'FROM %7B%7B
-nam
+baseImag
e%7D%7D:%7B%7Bta
@@ -3701,24 +3701,8 @@
ame:
- target.image %7C%7C
nam
@@ -3825,24 +3825,65 @@
+ '.tar'),%0A
+ baseImage: target.image %7C%7C name,%0A
imag
|
486d0867d9bf4e5cf3b7ed874d5d7ffd5560ac29 | Add attribute to viewdata to store total video time | api/models/ViewData.js | api/models/ViewData.js | /**
* ViewData.js
*
* @description :: This model represents the data for all the video statistics.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
coordinates: {
type: 'array',
required: true
},
width: {
type: 'float',
required: true
},
videoTime: {
type: 'float',
required: true
},
// Add a reference to ViewSession
sessionObj: {
model: 'ViewSession'
}
}
}
| JavaScript | 0 | @@ -359,16 +359,78 @@
e%0A%09%09%7D,%0A%0A
+%09%09videoTotalTime: %7B%0A%09%09%09type: 'float',%0A%09%09%09required: true%0A%09%09%7D,%0A%0A
%09%09// Add
|
b93c3dba7e073934d84695ae5e881880a8f3739f | update additional conditions form to accept undefined additionalConditions field | server/routes/additionalConditions.js | server/routes/additionalConditions.js | const express = require('express');
const asyncMiddleware = require('../utils/asyncMiddleware');
module.exports = function({logger, conditionsService, licenceService}) {
const router = express.Router();
router.use(function(req, res, next) {
if (typeof req.csrfToken === 'function') {
res.locals.csrfToken = req.csrfToken();
}
next();
});
router.get('/:nomisId', asyncMiddleware(async (req, res) => {
logger.debug('GET /additionalConditions');
const nomisId = req.params.nomisId;
const existingLicence = await licenceService.getLicence(req.params.nomisId);
const licence = existingLicence ? existingLicence.licence : null;
const conditions = await conditionsService.getAdditionalConditions(licence);
return res.render('additionalConditions/index', {nomisId, conditions});
}));
router.post('/:nomisId', asyncMiddleware(async (req, res) => {
logger.debug('POST /additionalConditions');
const nomisId = req.body.nomisId;
const validatedInput = await conditionsService.validateConditionInputs(req.body);
if (!validatedInput.validates) {
const conditions = await conditionsService.getAdditionalConditionsWithErrors(validatedInput);
return res.render('additionalConditions/index', {nomisId, conditions, submissionError: 'MISSING_INPUTS'});
}
await licenceService.updateLicenceConditions(req.body);
return res.redirect('/reporting/'+nomisId);
}));
router.get('/standard/:nomisId', asyncMiddleware(async (req, res) => {
logger.debug('GET /additionalConditions/standard');
const nomisId = req.params.nomisId;
const conditions = await conditionsService.getStandardConditions();
return res.render('additionalConditions/standard', {nomisId, conditions});
}));
return router;
};
| JavaScript | 0 | @@ -990,33 +990,32 @@
alConditions');%0A
-%0A
const no
@@ -1032,32 +1032,145 @@
q.body.nomisId;%0A
+%0A if(!req.body.additionalConditions) %7B%0A return res.redirect('/reporting/'+nomisId);%0A %7D%0A%0A
const va
@@ -1243,17 +1243,16 @@
.body);%0A
-%0A
|
b61b6ebe5907fd203d75e3db4dd6c7e9fa92ce7d | Fix broken tests. | test/controllers_static_content_spec.js | test/controllers_static_content_spec.js | /**
* Author: Daniel M. de Oliveira
*/
describe ('StaticContentController', function() {
var TEMPLATE_URL = "con10t/{LANG}/title.html";
var PROJECTS_JSON = 'con10t/content.json';
var scope = {};
var prepare = function (route,title,primaryLanguage,searchParam) {
module('arachne.controllers');
module('idai.components', function($provide) {
$provide.value('$location', {
search : function () {
return searchParam;
},
path : function () {
return route+'/'+title;
},
hash : function() {
return "";
}
});
$provide.constant('$stateParams', {
"title" : title
});
$provide.value('language', {
browserPrimaryLanguage: function () {
return primaryLanguage;
}
});
});
inject(function ($controller, _$httpBackend_) {
$httpBackend = _$httpBackend_;
$controller('StaticContentController', {'$scope': scope});
});
}
var setUpSimpleProjectJson = function(jsonFile,itemName,itemLang) {
$httpBackend.expectGET(jsonFile).respond(200,'{\
"id": "","children": [{\
"id": "'+itemName+'",\
"title": {\
"'+itemLang+'": "DAI - Objectdatabase"\
}}]}');
$httpBackend.flush();
}
it ('should provide a german templateUrl with search param lang=de',function(){
prepare('/project','title','de',{ "lang" : "de" });
expect(scope.templateUrl).toBe(TEMPLATE_URL.replace('{LANG}','de'));
});
it ('should provide an italian templateUrl (no search param) if project configured for italian',function(){
prepare('/project','title','it',{});
setUpSimpleProjectJson(PROJECTS_JSON,'title','it');
expect(scope.templateUrl).toBe(TEMPLATE_URL.replace('{LANG}','it'));
});
it ('should fallback to a german templateUrl (no search param) if no project configured',function(){
prepare('/project','title','it',{});
setUpSimpleProjectJson(PROJECTS_JSON,'title','de');
expect(scope.templateUrl).toBe(TEMPLATE_URL.replace('{LANG}','de'));
});
it ('should fallback to a german templateUrl (no search param) if project not configured for italian',function(){
prepare('/project','title','it',{});
setUpSimpleProjectJson(PROJECTS_JSON,'someOtherProject','it');
expect(scope.templateUrl).toBe(TEMPLATE_URL.replace('{LANG}','de'));
});
it ('should search for a matching project translation recursively',function(){
prepare('/project','title','it',{});
$httpBackend.expectGET(PROJECTS_JSON).respond(200,'{\
"id": "",\
"children": [\
{\
"id": "1",\
"children": [\
{\
"id": "fotorom",\
"children" : [ {\
"id" : "title", \
"title" : { \
"it" : "dede"\
}}]}]}]}');
$httpBackend.flush();
expect(scope.templateUrl).toBe(TEMPLATE_URL.replace('{LANG}','it'));
});
it ('should serve content from the static folder for the info route',function(){
prepare('/info','title','it',{});
setUpSimpleProjectJson('info/content.json','title','it');
expect(scope.templateUrl).toBe('info/it/title.html');
});
}); | JavaScript | 0.000004 | @@ -187,17 +187,156 @@
var
-scope = %7B
+callback = undefined;%0A%09var targetPage = undefined;%0A%09var scope = %7B%0A%09%09$on : function(p,cb) %7B%0A%09%09%09if (p===%22$includeContentError%22)%0A%09%09%09%09callback=cb;%0A%09%09%7D%0A%09
%7D;%0A%0A
@@ -590,35 +590,65 @@
ath : function (
-) %7B
+target) %7B%0A%09%09%09%09%09targetPage=target;
%0A%09%09%09%09%09return rou
@@ -914,11 +914,8 @@
);%0A%0A
-%09%09%0A
%09%09in
@@ -1064,16 +1064,17 @@
%09%09%7D);%0A%09%7D
+;
%0A%0A%09var s
@@ -1339,18 +1339,224 @@
lush();%0A
-
%09%7D
+;%0A%0A%09it ('should register a hook for redirect', function() %7B%0A%0A%09%09prepare('/project','title','de',%7B %22lang%22 : %22de%22 %7D);%0A%09%09if (callback === undefined) fail();%0A%09%09callback();%0A%09%09expect(targetPage).toBe('/404')%0A%09%7D);%0A
%0A%0A%09it ('
|
7ce644b3702fb5ea9c4c7f526c5480029e69c58e | Drop fallback props | config/common.js | config/common.js | 'use strict';
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var webpack = require('webpack');
module.exports = function(config) {
return new Promise(function(resolve, reject) {
var theme = config.theme;
if(!theme || !theme.name) {
return reject(new Error('Missing theme'));
}
var cwd = process.cwd();
var parent = path.join(__dirname, '..');
var themeConfig = config.themeConfig && config.themeConfig.common;
themeConfig = themeConfig || {};
var siteConfig = config.webpack && config.webpack.common;
siteConfig = siteConfig || {};
resolve({
resolve: {
fallback: path.join(cwd, 'antwar.config.js'),
root: path.join(parent, 'node_modules'),
alias: {
'underscore': 'lodash',
'pages': path.join(cwd, 'pages'),
'assets': path.join(cwd, 'assets'),
'customStyles': path.join(cwd, 'styles'), // Should be moved to theme specific config
'config': path.join(cwd, 'antwar.config.js'),
'antwar-core': path.join(parent, 'elements'),
'theme': getThemeName(theme.name),
},
extensions: _.uniq([
'',
'.webpack.js',
'.web.js',
'.js',
'.jsx',
'.coffee',
'.json',
].
concat(themeConfig.extensions || []).
concat(siteConfig.extensions || [])),
modulesDirectories: [
path.join(cwd, 'node_modules'),
getThemePath(theme.name),
'node_modules',
]
},
resolveLoader: {
fallback: path.join(cwd, 'antwar.config.js'),
modulesDirectories: [
path.join(parent, 'node_modules'),
getThemePath(theme.name),
'node_modules',
]
},
plugins: [
new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV)),
'process.env': {
'NODE_ENV': JSON.stringify(process.env.BUILD_DEV ? 'dev' : 'production')
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin()
],
jshint: {
bitwise: false,
boss: true,
curly: false,
eqnull: true,
expr: true,
newcap: false,
quotmark: false,
shadow: true,
strict: false,
sub: true,
undef: true,
unused: 'vars',
},
});
});
};
function getThemeName(name) {
// XXX: existsSync
if(fs.existsSync(name)) {
return path.join(process.cwd(), name);
}
return name;
}
function getThemePath(name) {
var cwd = process.cwd();
// XXX: existsSync
if(fs.existsSync(name)) {
return path.join(cwd, name);
}
return path.join(cwd, 'node_modules', name, 'node_modules');
}
| JavaScript | 0.000001 | @@ -644,62 +644,8 @@
: %7B%0A
- fallback: path.join(cwd, 'antwar.config.js'),%0A
@@ -1541,62 +1541,8 @@
: %7B%0A
- fallback: path.join(cwd, 'antwar.config.js'),%0A
|
8d8f90c47c07edbae23f83f613fc5b21d5a11b77 | Remove button handling | react-project/src/reducers/index.js | react-project/src/reducers/index.js | import * as types from '../types';
import db from '../products.json';
export const initialState = {
cart: {
products: {
/*"<product-id>": {
name: "string",
price: 1.00,
tax: 0.07 || 0.19
},*/
},
meta: {
/*"<product-id>": {
added: new Date(),
quantity: 0,
comment: "editable string"
}*/
}
}
};
function generateProductMeta () {
return {
added: Date.now(),
quantity: 0,
comment: ""
};
}
export function cartReducer(state = initialState, action) {
switch (action.type) {
case types.ADD_PRODUCT:
console.info('cartReducer: Add product', action);
// assumes product is not in cart already
// action.payload = "<product-id>"
const id = action.payload;
let cart = state.cart;
const products = Object.assign({}, cart.products, {[id]: db[id]});
const meta = Object.assign({}, cart.meta, {[id]: generateProductMeta()});
cart = Object.assign({}, cart, { products, meta });
return { cart };
case types.REMOVE_PRODUCT:
console.info('cartReducer: Remove product', action);
return state;
default:
return state;
}
}
const reducer = cartReducer // combineReducers({ });
export default reducer;
| JavaScript | 0.000001 | @@ -1,12 +1,37 @@
+import _ from 'lodash';%0A%0A
import * as
@@ -574,16 +574,99 @@
tion) %7B%0A
+ const id = action.payload;%0A let cart = state.cart;%0A let products;%0A let meta;%0A%0A
switch
@@ -859,82 +859,14 @@
d%3E%22%0A
+%0A
- const id = action.payload;%0A%0A let cart = state.cart;%0A const
pro
@@ -873,22 +873,17 @@
ducts =
-Object
+_
.assign(
@@ -928,27 +928,16 @@
-const
meta =
-Object
+_
.ass
@@ -1004,14 +1004,9 @@
t =
-Object
+_
.ass
@@ -1160,28 +1160,356 @@
;%0A
-return state
+// assumes product is in the cart%0A // action.payload = %22%3Cproduct-id%3E%22%0A%0A // create new object omitting product to be removed%0A products = _.omitBy(cart.products, (value, key) =%3E key === id);%0A meta = _.omitBy(cart.meta, (value, key) =%3E key === id);%0A cart = _.assign(%7B%7D, cart, %7B products, meta %7D);%0A return %7B cart %7D
;%0A%0A d
|
67ad72fa3c9beb5c2b1e32530b0b2c0b5e74883c | Add types to RCTSnapshotNativeComponent (#23111) | Libraries/RCTTest/RCTSnapshotNativeComponent.js | Libraries/RCTTest/RCTSnapshotNativeComponent.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
const requireNativeComponent = require('requireNativeComponent');
module.exports = requireNativeComponent('RCTSnapshot');
| JavaScript | 0.000001 | @@ -211,21 +211,8 @@
flow
- strict-local
%0A%09 *
@@ -229,16 +229,468 @@
rict';%0A%0A
+import type %7BSyntheticEvent%7D from 'CoreEventTypes';%0Aimport type %7BViewProps%7D from 'ViewPropTypes';%0Aimport type %7BNativeComponent%7D from 'ReactNative';%0A%0Atype SnapshotReadyEvent = SyntheticEvent%3C%0A $ReadOnly%3C%7B%0A testIdentifier: string,%0A %7D%3E,%0A%3E;%0A%0Atype NativeProps = $ReadOnly%3C%7B%7C%0A ...ViewProps,%0A onSnapshotReady?: ?(event: SnapshotReadyEvent) =%3E mixed,%0A testIdentifier?: ?string,%0A%7C%7D%3E;%0A%0Atype SnapshotViewNativeType = Class%3CNativeComponent%3CNativeProps%3E%3E;%0A%0A
const re
@@ -765,16 +765,18 @@
ports =
+((
requireN
@@ -804,10 +804,40 @@
apshot')
+:any): SnapshotViewNativeType)
;%0A
|
b1f93ade78c840ec01f85c159c8d978632b544b3 | Fix hyphen-separated css property names | ipywidgets/static/widgets/js/layout.js | ipywidgets/static/widgets/js/layout.js | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
// npm compatibility
if (typeof define !== 'function') { var define = require('./requirejs-shim')(module); }
// Use the CommonJS-like requirejs style.
define([
"./widget",
"underscore",
"backbone",
"jquery"
], function(widget, _, Backbone, $) {
/**
* Represents a group of CSS style attributes
*/
var LayoutView = widget.WidgetView.extend({
/**
* Public constructor
*/
constructor: function() {
LayoutView.__super__.constructor.apply(this, arguments);
// Register the traits that live on the Python side
this._traitNames = [];
this.initTraits();
},
/**
* Initialize the traits for this layout object
*/
initTraits: function() {
this.registerTraits(
'align_content',
'align_items',
'align_self',
'bottom',
'display',
'flex',
'flex_basis',
'flex_direction',
'flex_flow',
'flex_grow',
'flex_shrink',
'flex_wrap',
'height',
'justify_content',
'left',
'margin',
'padding',
'right',
'top',
'visibility',
'width'
);
},
/**
* Register CSS traits that are known by the model
* @param {...string[]} traits
*/
registerTraits: function() {
// Expand any args that are arrays
_.flatten(Array.prototype.slice.call(arguments))
// Call registerTrait on each trait
.forEach(_.bind(this.registerTrait, this));
},
/**
* Register a CSS trait that is known by the model
* @param {string} trait
*/
registerTrait: function(trait) {
this._traitNames.push(trait);
// Listen to changes, and set the value on change.
this.listenTo(this.model, 'change:' + this.modelize(trait), function (model, value) {
this.handleChange(trait, value);
}, this);
// Set the initial value on display.
this.displayed.then(_.bind(function() {
this.handleChange(trait, this.model.get(this.modelize(trait)));
}, this));
},
/**
* Get the the name of the trait as it appears in the model
* @param {string} trait - CSS trait name
* @return {string} model key name
*/
modelize: function(trait) {
return trait.replace('-', '_');
},
/**
* Handles when a trait value changes
* @param {string} trait
* @param {object} value
*/
handleChange: function(trait, value) {
this.displayed.then(_.bind(function(parent) {
if (parent) {
parent.el.style[trait] = value;
} else {
console.warn("Style not applied because a parent view doesn't exist");
}
}, this));
},
/**
* Remove the styling from the parent view.
*/
unlayout: function() {
this._traitNames.forEach(function(trait) {
this.displayed.then(_.bind(function(parent) {
if (parent) {
parent.el.style[trait] = '';
} else {
console.warn("Style not removed because a parent view doesn't exist");
}
}, this));
}, this);
}
});
return {LayoutView: LayoutView};
});
| JavaScript | 0.999887 | @@ -359,20 +359,16 @@
e, $) %7B%0A
-
%0A /**
@@ -474,24 +474,16 @@
xtend(%7B%0A
-
%0A
@@ -537,27 +537,26 @@
-constructor
+initialize
: functi
@@ -595,27 +595,26 @@
super__.
-constructor
+initialize
.apply(t
@@ -630,29 +630,16 @@
ments);%0A
- %0A
@@ -767,32 +767,24 @@
%0A %7D,%0A
-
%0A /**
@@ -1533,32 +1533,24 @@
%0A %7D,%0A
-
%0A /**
@@ -1927,32 +1927,24 @@
%0A %7D,%0A
-
%0A /**
@@ -2132,28 +2132,16 @@
trait);%0A
-
%0A
@@ -2246,36 +2246,21 @@
nge:' +
-this.modelize(
trait
-)
, functi
@@ -2278,17 +2278,16 @@
value) %7B
-
%0A
@@ -2512,30 +2512,15 @@
get(
-this.modelize(
trait))
-)
;%0A
@@ -2547,32 +2547,24 @@
%0A %7D,%0A
-
%0A /**
@@ -2603,40 +2603,43 @@
the
-trait as it appears in the model
+style attribute from the trait name
%0A
@@ -2667,25 +2667,23 @@
ng%7D
-trait - CSS trait
+model attribute
nam
@@ -2716,22 +2716,27 @@
ng%7D
-model key
+css attribute
name
+.
%0A
@@ -2756,15 +2756,15 @@
-modeliz
+css_nam
e: f
@@ -2818,14 +2818,14 @@
ce('
--
+_
', '
-_
+-
');%0A
@@ -2831,32 +2831,25 @@
%0A %7D,%0A
-
+%0A
%0A /**
@@ -3098,32 +3098,41 @@
if (parent
+ && value
) %7B%0A
@@ -3151,29 +3151,44 @@
nt.el.style%5B
+this.css_name(
trait
+)
%5D = value;%0A
@@ -3354,24 +3354,16 @@
%7D,%0A
-
%0A
@@ -3653,21 +3653,36 @@
l.style%5B
+this.css_name(
trait
+)
%5D = '';%0A
@@ -3894,20 +3894,16 @@
%7D);%0A
-
%0A ret
|
cf80ada65f3a85dc9223bd8203836d5935d8c4d8 | Remove resolutionHandler from DT | server/game/cards/01-Core/DuelistTraining.js | server/game/cards/01-Core/DuelistTraining.js | const DrawCard = require('../../drawcard.js');
const GameActions = require('../../GameActions/GameActions');
const { Players, CardTypes, AbilityTypes, DuelTypes } = require('../../Constants');
class DuelistTraining extends DrawCard {
setupCardAbilities(ability) {
this.whileAttached({
effect: ability.effects.gainAbility(AbilityTypes.Action, {
title: 'Initiate a duel to bow',
condition: context => context.source.isParticipating(),
printedAbility: false,
target: {
cardType: CardTypes.Character,
controller: Players.Opponent,
cardCondition: card => card.isParticipating(),
gameAction: ability.actions.duel(context => ({
type: DuelTypes.Military,
challenger: context.source,
gameAction: duel => ability.actions.bow({ target: duel.loser }),
costHandler: (context, prompt) => this.costHandler(context, prompt)
}))
}
})
});
}
resolutionHandler(context, winner, loser) {
if(loser) {
this.game.addMessage('{0} wins the duel, and bows {1}', winner, loser);
this.game.applyGameAction(context, { bow: loser });
}
}
costHandler(context, prompt) {
let lowBidder = this.game.getFirstPlayer();
let difference = lowBidder.honorBid - lowBidder.opponent.honorBid;
if(difference < 0) {
lowBidder = lowBidder.opponent;
difference = -difference;
} else if(difference === 0) {
return;
}
if(lowBidder.hand.size() < difference) {
prompt.transferHonorAfterBid(context);
return;
}
this.game.promptWithHandlerMenu(lowBidder, {
activePromptTite: 'Difference in bids: ' + difference.toString(),
source: this,
choices: ['Pay with honor', 'Pay with cards'],
handlers: [
() => prompt.transferHonorAfterBid(context),
() => GameActions.chosenDiscard({ amount: difference }).resolve(lowBidder, context)
]
});
}
}
DuelistTraining.id = 'duelist-training';
module.exports = DuelistTraining;
| JavaScript | 0.000001 | @@ -1146,241 +1146,8 @@
%7D%0A%0A
- resolutionHandler(context, winner, loser) %7B%0A if(loser) %7B%0A this.game.addMessage('%7B0%7D wins the duel, and bows %7B1%7D', winner, loser);%0A this.game.applyGameAction(context, %7B bow: loser %7D);%0A %7D%0A %7D%0A%0A
|
ee9d9cc4080c57a5b12f11b5c6ce71e971f44f4f | fix sideCI | server/routes/v000803/route.nation.js | server/routes/v000803/route.nation.js | /**
* Created by aleckim on 2017. 6. 21..
*/
var router = require('express').Router();
var async = require('async');
var req = require('request');
var config = require('../../config/config');
var ControllerTown24h = require('../../controllers/controllerTown24h');
var cTown = new ControllerTown24h();
router.use(function timestamp(req, res, next){
var printTime = new Date();
log.info('+ nation > request | Time[', printTime.toISOString(), ']');
next();
});
/**
*
* @param cityName
* @param version
* @param query
* @param lang
* @param callback
*/
function requestApi(cityName, version, query, lang, callback) {
var apiEndpoint = '/town';
if (version === 'v000901') {
apiEndpoint = '/kma/addr'
}
var url = config.push.serviceServer+"/"+version+apiEndpoint+"/"+encodeURIComponent(cityName);
if (query) {
var count = 0;
for (var key in query) {
url += count === 0? "?":"&";
url += key+'='+query[key];
count++;
}
}
/**
* 못 받으면 다음 요청에 받도록 timeout을 길게 함
*/
var options = {json: true, timeout: 9000, headers: {'Accept-Language' : lang}};
log.info({city: cityName, date: new Date(), url: url});
req(url, options, function(err, response, body) {
log.info('Finished '+cityName+' '+new Date());
if (err) {
return callback(err);
}
if ( response.statusCode >= 400) {
err = new Error("response.statusCode="+response.statusCode);
log.error(err);
return callback(err);
}
callback(undefined, body);
});
}
router.get('/:nation', [cTown.checkQueryValidation], function(req, res) {
//서울(서울경기), 춘천(강원도), 부산(경남), 대구(경북), 제주(제주), 광주(전남), 대전(충남), 청주(충북), 전주(전북), 강릉,
//수원, 인천, 안동, 울릉도/독도, 목표, 여수, 울산, 백령도, 창원
var cityArray = ["서울특별시", "강원도/춘천시", "부산광역시", "대구광역시", "제주특별자치도/제주시", "광주광역시", "대전광역시",
"충청북도/청주시", "전라북도/전주시", "강원도/강릉시", "인천광역시", "전라남도/목포시", "전라남도/여수시", "경상북도/안동시", "울산광역시"];
var acceptLanguage;
if (req.headers) {
if (req.headers.hasOwnProperty('accept-language')) {
acceptLanguage = req.headers['accept-language'];
}
if (req.headers.hasOwnProperty('Accept-Language')) {
acceptLanguage = req.headers['Accept-Language'];
}
}
async.map(cityArray,
function (city, callback) {
requestApi(city, req.version, req.query, acceptLanguage, function (err, weatherInfo) {
if (err) {
return callback(err);
}
callback(undefined, weatherInfo);
});
},
function (err, weatherList) {
if (err) {
log.error(err);
return res.status(500).send(err);
}
return res.send({nation:"SouthKorea", weather:weatherList});
});
});
module.exports = router;
| JavaScript | 0.000001 | @@ -41,16 +41,31 @@
..%0A */%0A%0A
+%22use strict%22;%0A%0A
var rout
@@ -743,16 +743,17 @@
ma/addr'
+;
%0A %7D%0A
|
2bba64bf352c3897cc21157e9af41fb903e68f51 | Use var for compatibility with Android 4.x | www/LocalStorageHandle.js | www/LocalStorageHandle.js | var NativeStorageError = require('./NativeStorageError');
// args = [reference, variable]
function LocalStorageHandle(success, error, intent, operation, args) {
var reference = args[0];
var variable = args[1];
if (operation.startsWith('put') || operation.startsWith('set')) {
try {
var varAsString = JSON.stringify(variable);
if (reference === null) {
error(new NativeStorageError(NativeStorageError.NULL_REFERENCE, "JS", ""));
return;
}
localStorage.setItem(reference, varAsString);
success(variable);
} catch (err) {
error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err));
}
} else if (operation.startsWith('get')) {
var item = {};
item = localStorage.getItem(reference);
if (item === null) {
error(new NativeStorageError(NativeStorageError.ITEM_NOT_FOUND,"JS",""));
return;
}
try {
var obj = JSON.parse(item);
//console.log("LocalStorage Reading: "+obj);
success(obj);
} catch (err) {
error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err));
}
} else if(operation === 'keys') {
const keys = [];
let key = localStorage.key(0);
if(!key) {
return success(keys);
}
let i = 0;
while(key) {
keys.push(key);
i++;
key = localStorage.key(i);
}
success(keys);
}
}
module.exports = LocalStorageHandle;
| JavaScript | 0 | @@ -1260,16 +1260,17 @@
else if
+
(operati
@@ -1296,13 +1296,11 @@
-const
+var
key
@@ -1313,19 +1313,19 @@
;%0A
-let
+var
key = l
@@ -1409,11 +1409,11 @@
-let
+var
i =
|
4213db17221f837b27aff072cdff7693854eacb3 | fix missing angular | tests/wrappers/label-spec.js | tests/wrappers/label-spec.js | import testUtils from './../test-utils';
describe('formlyMaterial - label wrapper', () => {
//
// vars
//
let $compile;
let $rootScope;
let $scope;
let element;
let field;
const color = 'rgb(117, 117, 117)';
//
// helpers
//
function compile(options) {
$scope = $rootScope.$new();
$scope.fields = [angular.merge({}, {
key: 'testField',
type: 'checkbox',
wrapper: ['label'],
templateOptions: {
label: 'test field'
}
}, options)];
const form = $compile(testUtils.getFormTemplate())($scope);
$scope.$digest();
element = form.find('label');
field = $scope.fields[0];
}
//
// tests
//
beforeEach(() => {
window.module('formlyMaterial');
inject((_$compile_, _$rootScope_) => {
$compile = _$compile_;
$rootScope = _$rootScope_;
});
});
it('should exist', () => {
compile();
expect(element.length).toBe(1);
});
it('should have proper value', () => {
compile();
expect(element.html()).toContain(field.templateOptions.label);
});
it('should be before the field', () => {
compile();
expect(element.find('md-checkbox').length).toBe(0);
expect(element.next().children()[0].nodeName).toBe('MD-CHECKBOX');
});
it('should have styles added', () => {
compile();
expect(element.css('color')).toBe(color);
});
it('should not have styles added when used with input', () => {
compile({
type: 'input'
});
expect(element.css('color')).not.toBe(color);
});
it('should not have styles added when used with select', () => {
compile({
type: 'select',
templateOptions: {
options: [{
name: 'foo',
value: 'bar'
}]
}
});
expect(element.css('color')).not.toBe(color);
});
it('should not have styles added when used with textarea', () => {
compile({
type: 'textarea'
});
expect(element.css('color')).not.toBe(color);
});
});
| JavaScript | 0.001526 | @@ -33,16 +33,47 @@
-utils';
+%0Aimport angular from 'angular';
%0A%0Adescri
|
bd25eaa5fcebaedc9a94f763d94f660bc64f02e4 | Fix tests | spec/javascripts/unit/AnalyticsSpec.js | spec/javascripts/unit/AnalyticsSpec.js | describe("GOVUK.Analytics", function () {
var analytics;
beforeEach(function () {
window.ga = function() {};
spyOn(window, 'ga');
});
describe('when initialised', function () {
it('should initialise pageviews, events and virtual pageviews', function () {
spyOn(window.GOVUK.GDM.analytics, 'register');
spyOn(window.GOVUK.GDM.analytics.pageViews, 'init');
spyOn(window.GOVUK.GDM.analytics, 'virtualPageViews');
spyOn(window.GOVUK.GDM.analytics.events, 'init');
window.GOVUK.GDM.analytics.init();
expect(window.GOVUK.GDM.analytics.register).toHaveBeenCalled();
expect(window.GOVUK.GDM.analytics.pageViews.init).toHaveBeenCalled();
expect(window.GOVUK.GDM.analytics.virtualPageViews).toHaveBeenCalled();
expect(window.GOVUK.GDM.analytics.events.init).toHaveBeenCalled();
});
});
describe('when registered', function() {
var universalSetupArguments;
beforeEach(function() {
GOVUK.GDM.analytics.init();
universalSetupArguments = window.ga.calls.allArgs();
});
it('configures a universal tracker', function() {
var trackerId = 'UA-49258698-1';
expect(universalSetupArguments[0]).toEqual(['create', trackerId, {
'cookieDomain': document.domain
}]);
});
});
describe('pageViews', function () {
beforeEach(function () {
window.ga.calls.reset();
});
it('should register a pageview when initialised', function () {
spyOn(window.GOVUK.GDM.analytics.pageViews, 'init').and.callThrough();
window.GOVUK.GDM.analytics.pageViews.init();
expect(window.ga.calls.argsFor(0)).toEqual(['send', 'pageview']);
});
});
describe('link tracking', function () {
var mockLink;
beforeEach(function () {
mockLink = document.createElement('a');
window.ga.calls.reset();
});
it('sends the right event when an internal link is clicked', function() {
mockLink.appendChild(document.createTextNode('Suppliers guide'));
mockLink.href = window.location.hostname + '/suppliers/frameworks/g-cloud-7/download-supplier-pack';
GOVUK.GDM.analytics.events.registerLinkClick({ 'target': mockLink });
expect(window.ga.calls.first().args).toEqual(['send', {
'hitType': 'event',
'eventCategory': 'internal-link',
'eventAction': 'Suppliers guide'
}]);
});
it('sends the right event when an external link is clicked', function() {
mockLink.appendChild(document.createTextNode('Open Government Licence v3.0'));
mockLink.href = 'https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/';
GOVUK.GDM.analytics.events.registerLinkClick({ 'target': mockLink });
expect(window.ga.calls.first().args).toEqual(['send', {
'hitType': 'event',
'eventCategory': 'external-link',
'eventAction': 'Open Government Licence v3.0'
}]);
});
it('sends the right event when a download link is clicked', function() {
mockLink.appendChild(document.createTextNode('Download guidance and legal documentation (.zip)'));
mockLink.href = window.location.hostname + '/suppliers/frameworks/g-cloud-7/g-cloud-7-supplier-pack.zip';
GOVUK.GDM.analytics.events.registerLinkClick({ 'target': mockLink });
expect(window.ga.calls.first().args).toEqual(['send', {
'hitType': 'event',
'eventCategory': 'download',
'eventAction': 'Download guidance and legal documentation (.zip)'
}]);
});
});
describe('button tracking', function () {
var mockButton;
beforeEach(function () {
mockButton = document.createElement('input');
mockButton.setAttribute('type', 'submit');
window.ga.calls.reset();
});
it('sends the right event when a submit button is clicked', function() {
mockButton.setAttribute('value', 'Save and continue');
document.title = 'Features and benefits';
GOVUK.GDM.analytics.events.registerSubmitButtonClick.call(mockButton);
expect(window.ga.calls.first().args).toEqual(['send', {
'hitType': 'event',
'eventCategory': 'button',
'eventAction': 'Save and continue',
'eventLabel': 'Features and benefits'
}
]);
});
it('knows if the user is on a service page', function () {
expect(
GOVUK.GDM.analytics.isQuestionPage("http://example.com/suppliers/submission/services/7478/edit/service_name")
).toEqual(true);
expect(
GOVUK.GDM.analytics.isQuestionPage("http://example.com/suppliers/submission/services/7478")
).toEqual(false);
expect(
GOVUK.GDM.analytics.isQuestionPage("http://example.com/suppliers/frameworks/g-cloud-7/services")
).toEqual(false);
expect(
GOVUK.GDM.analytics.isQuestionPage("file:///Users/Jo/gds/suppliers/spec.html")
).toEqual(false);
});
});
describe("Virtual Page Views", function () {
beforeEach(function () {
window.ga.calls.reset();
});
describe("When called", function () {
var $analyticsString;
afterEach(function () {
$analyticsString.remove();
});
it("Should not call google analytics without a url", function () {
$analyticsString = $("<div data-analytics='trackPageView'/>");
$(document.body).append($analyticsString);
window.GOVUK.GDM.analytics.virtualPageViews();
expect(window.ga.calls.any()).toEqual(false);
});
it("Should call google analytics if url exists", function () {
$analyticsString = $("<div data-analytics='trackPageView' data-url='http://example.com'/>");
$(document.body).append($analyticsString);
window.GOVUK.GDM.analytics.virtualPageViews();
expect(window.ga.calls.first().args).toEqual([ 'send', 'pageview', { page: 'http://example.com' } ]);
expect(window.ga.calls.count()).toEqual(1);
});
});
describe("When the clarification question for an opportunity page is loaded", function () {
var $form,
$content;
beforeEach(function () {
$content = $('<div id="content" />');
$form = $('<form />');
$content.append($form);
$(document.body).append($content);
});
afterEach(function () {
$content.remove();
});
it("Should not send a pageview if question not sent", function () {
$form.attr('data-message-sent', 'false');
spyOn(GOVUK.GDM.analytics.location, "pathname")
.and
.callFake(function () {
return "/suppliers/opportunities/1/ask-a-question";
});
window.GOVUK.GDM.analytics.virtualPageViews();
expect(window.ga.calls.any()).toEqual(false);
});
it("Should send a pageview with a query string if question sent", function () {
$form.attr('data-message-sent', 'true');
spyOn(GOVUK.GDM.analytics.location, "pathname")
.and
.callFake(function () {
return "/suppliers/opportunities/1/ask-a-question";
});
spyOn(GOVUK.GDM.analytics.location, "href")
.and
.callFake(function () {
return "https://www.digitalmarketplace.service.gov.uk/suppliers/opportunities/1/ask-a-question";
});
window.GOVUK.GDM.analytics.virtualPageViews();
expect(window.ga.calls.first().args).toEqual([ 'send', 'pageview', { page: "https://www.digitalmarketplace.service.gov.uk/suppliers/opportunities/1/ask-a-question?submitted=true" } ]);
});
});
});
});
| JavaScript | 0.000003 | @@ -7465,53 +7465,8 @@
e: %22
-https://www.digitalmarketplace.service.gov.uk
/sup
|
2a2419a6e0f5458fff0f1ece9ff8a70bde0ee421 | Update DatePicker.js | www/android/DatePicker.js | www/android/DatePicker.js | /**
* Phonegap DatePicker Plugin Copyright (c) Greg Allen 2011 MIT Licensed
* Reused and ported to Android plugin by Daniel van 't Oever
*/
/**
* Constructor
*/
function DatePicker() {
//this._callback;
}
/**
* show - true to show the ad, false to hide the ad
*/
DatePicker.prototype.show = function(options, cb) {
if (options.date) {
options.date = (options.date.getMonth() + 1) + "/" +
(options.date.getDate()) + "/" +
(options.date.getFullYear()) + "/" +
(options.date.getHours()) + "/" +
(options.date.getMinutes());
}
var defaults = {
mode : 'date',
date : '',
minDate: 0,
maxDate: 0,
doneButtonLabel: "Done",
cancelButtonLabel: "Cancel",
clearButtonLabel: "Clear",
clearButton: false,
cancelButton: true,
windowTitle: "[default]"
};
for (var key in defaults) {
if (typeof options[key] !== "undefined") {
defaults[key] = options[key];
}
}
//this._callback = cb;
var callback = function(message) {
if ( message == "clear" || message == "cancel" ) {
cb(message);
} else {
cb(new Date(message));
}
}
cordova.exec(callback,
null,
"DatePickerPlugin",
defaults.mode,
[defaults]
);
};
var datePicker = new DatePicker();
module.exports = datePicker;
// Make plugin work under window.plugins
if (!window.plugins) {
window.plugins = {};
}
if (!window.plugins.datePicker) {
window.plugins.datePicker = datePicker;
}
| JavaScript | 0 | @@ -773,19 +773,20 @@
Button:
-tru
+fals
e,%0A%09%09win
|
4f69da24b7f67054369003f0ff9e9322ed0827e5 | Add moment | app/components/Home.js | app/components/Home.js | import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './Home.module.css';
const { TextField,Snackbar } = require('material-ui');
const GitHubApi = require("github-api");
import pinyin from "pinyin";
export default class Home extends Component {
constructor() {
super();
this.state = {
autoHideDuration: 0,
sending: 0,
title: "",
link: "",
date: "",
message: ""
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleTitleChange = this.handleTitleChange.bind(this);
this.handleAuthorChange = this.handleAuthorChange.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
}
handleSubmit() {
var that = this;
this.setState({
sending: 1
});
if (localStorage.getItem('token') === null || localStorage.getItem('repo') === null) {
that.setState({message: "跳转到设置中..."});
that.refs.snackbar.show();
return;
}
var token = localStorage.getItem('token');
var username = localStorage.getItem('repo').split("/")[0];
var reponame = localStorage.getItem('repo').split("/")[1];
var github = new GitHubApi({
token: token,
auth: "oauth"
});
var repo = github.getRepo(username, reponame);
repo.read('master', 'README.md', function (err, data) {
that.setState({message: "上传成功" + data});
that.refs.snackbar.show();
that.setState({
sending: 0
});
});
};
handleTitleChange(e) {
var linkName = pinyin(e.target.value, {
style: pinyin.STYLE_NORMAL // 设置拼音风格
}).toString();
linkName = linkName.replace(/,/g, '-');
console.log(linkName);
this.setState({
title: e.target.value,
link: linkName
});
};
handleAuthorChange(e) {
this.setState({
author: e.target.value
});
};
handleDateChange(e) {
this.setState({
date: e.target.value
});
};
static getStyles() {
return {
link: {
marginLeft: "2em"
},
author: {
marginLeft: "2em",
width: "4em"
}
};
};
render() {
var inlineStyles = Home.getStyles();
var Message = this.state.message;
return (
<div>
<div className={styles.article}>
<div className={styles.titleLine}>
<div className={styles.headLine}>
<i className="fa fa-fw fa-edit mode"></i>
<TextField
defaultValue={this.state.title}
onChange={this.handleTitleChange}
floatingLabelText="标题"
hintText="标题"/>
<TextField
style={inlineStyles.author}
defaultValue={this.state.author}
onChange={this.handleAuthorChange}
floatingLabelText="作者"
hintText="白米粥"/>
<TextField
style={inlineStyles.link}
value={this.state.link}
defaultValue={this.state.link}
floatingLabelText="链接名"
hintText="biaoti-2014"/>
<TextField
style={inlineStyles.link}
defaultValue={this.state.date}
onChange={this.handleDateChange}
type="date"
floatingLabelText="日期" />
</div>
<div className={styles.publish}>
<button type="submit" className="fa fa-fw fa-paper-plane-o mode" onClick={this.handleSubmit}
disabled={this.sending}/>
</div>
</div>
<div id="editor" className={styles.editor}>
说说你的故事...
</div>
</div>
<Snackbar
ref="snackbar"
message={Message}
autoHideDuration={this.state.autoHideDuration}/>
</div>
);
}
}
| JavaScript | 0.000009 | @@ -236,16 +236,48 @@
pinyin%22;
+%0Avar moment = require('moment');
%0A%0Aexport
@@ -460,35 +460,130 @@
te:
-%22%22,%0A message: %22%22%0A %7D
+moment(Date.now()).format('YYYY-MM-DD'),%0A message: %22%22%0A %7D;%0A console.log(moment(Date.now()).format('YYYY-MM-DD'))
;%0A
@@ -2224,24 +2224,96 @@
idth: %224em%22%0A
+ %7D,%0A date: %7B%0A marginLeft: %222em%22,%0A width: %2210em%22%0A
%7D%0A
@@ -3351,36 +3351,36 @@
e=%7BinlineStyles.
-link
+date
%7D%0A
|
b314642586814bca0fa90846175cf4b90c94d8f5 | Rollback to setImmediate | test/functional/util/webdriverio-ext.js | test/functional/util/webdriverio-ext.js | var artifacts = require("../../artifacts");
var fs = require("fs");
var path = require("path");
browser.timeoutsAsyncScript(20*1000);
browser.timeoutsImplicitWait(20*1000);
var SCREENSHOTS_PATH = artifacts.pathSync("/screenshots");
/**
* Sometimes chrome driver can result in the wrong text.
*
* See <https://github.com/webdriverio/webdriverio/issues/1886>
*/
try {
browser.addCommand('setValueSafe', function(selector, text) {
for(var i=0; i<10; i++) {
browser.waitForVisible(selector);
var elements = browser.elements(selector);
if(elements.length > 1) {
throw "Too many elements found";
}
browser.setValue(selector, text);
var browserText = browser.getValue(selector);
if(browserText == text) {
return;
}
else {
console.error("Warning: setValue failed, trying again");
}
}
// Wait for change events to fire and state updated
browser.flushReactUpdates();
})
browser.addCommand('takeScreenShot', function(filepath) {
var data = browser.screenshot();
fs.writeFileSync(path.join(SCREENSHOTS_PATH, filepath), data.value, 'base64');
});
browser.addCommand('flushReactUpdates', function() {
browser.executeAsync(function(done) {
// For any events to propogate
process.nextTick(function() {
// For the DOM to be updated.
process.nextTick(done);
})
})
})
} catch(err) {
console.error(">>> Ignored error: "+err);
}
| JavaScript | 0 | @@ -1309,32 +1309,28 @@
e%0A
-process.nextTick
+setImmediate
(functio
@@ -1385,24 +1385,20 @@
-process.nextTick
+setImmediate
(don
|
6ab93f6281f5a079f35f00ecd35472047467bc5e | Remove increment prop. | source/ProgressBar.js | source/ProgressBar.js | /**
_moon.ProgressBar_ is a control that shows the current progress of a
process in a horizontal bar.
{kind: "moon.ProgressBar", progress: 10}
To animate progress changes, call the _animateProgressTo()_ method:
this.$.progressBar.animateProgressTo(50);
You may customize the color of the bar by applying a style via the
_barClasses_ property, e.g.:
{kind: "moon.ProgressBar", barClasses: "class-name"}
For more information, see the documentation on [Progress
Indicators](https://github.com/enyojs/moonstone/wiki/Progress-Indicators) in
the Enyo Developer Guide.
*/
enyo.kind({
name: "moon.ProgressBar",
//* @protected
classes: "moon-progress-bar",
//* @public
published: {
//* Current position of progress bar
progress: 0,
//* Minimum progress value (i.e., no progress made)
min: 0,
//* Maximum progress value (i.e., process complete)
max: 100,
//* CSS classes to apply to progress bar
barClasses: "moon-progress-bar-bar",
//* CSS classes to apply to bg progress bar
bgBarClasses: "moon-progress-bg-bar",
//* Sliders may "snap" to multiples of this value in either direction
increment: 0,
//* Completion percentage for background process
bgProgress: 0
},
events: {
//* Fires when progress bar finishes animating to a position.
onAnimateProgressFinish: ""
},
//* @protected
components: [
{name: "progressAnimator", kind: "Animator", onStep: "progressAnimatorStep", onEnd: "progressAnimatorComplete"},
{name: "bgbar"},
{name: "bar"}
],
create: function() {
this.inherited(arguments);
this.addRemoveClass("moon-progress-bar-rtl", this.rtl);
this.progressChanged();
this.barClassesChanged();
this.bgBarClassesChanged();
this.bgProgressChanged();
},
barClassesChanged: function(inOld) {
this.$.bar.removeClass(inOld);
this.$.bar.addClass(this.barClasses);
},
bgBarClassesChanged: function(inOld) {
this.$.bgbar.removeClass(inOld);
this.$.bgbar.addClass(this.bgBarClasses);
},
bgProgressChanged: function() {
this.bgProgress = this.clampValue(this.min, this.max, this.bgProgress);
var p = this.calcPercent(this.bgProgress);
this.updateBgBarPosition(p);
},
progressChanged: function() {
this.progress = this.clampValue(this.min, this.max, this.progress);
var p = this.calcPercent(this.progress);
this.updateBarPosition(p);
},
calcIncrement: function(inValue) {
return (Math.round(inValue / this.increment) * this.increment);
},
clampValue: function(inMin, inMax, inValue) {
return Math.max(inMin, Math.min(inValue, inMax));
},
calcRatio: function(inValue) {
return (inValue - this.min) / (this.max - this.min);
},
calcPercent: function(inValue) {
return this.calcRatio(inValue) * 100;
},
updateBarPosition: function(inPercent) {
this.$.bar.applyStyle("width", inPercent + "%");
},
updateBgBarPosition: function(inPercent) {
this.$.bgbar.applyStyle("width", inPercent + "%");
},
//* @public
//* Animates progress to the passed-in value.
animateProgressTo: function(inValue) {
this.$.progressAnimator.play({
startValue: this.progress,
endValue: inValue,
node: this.hasNode()
});
},
//* @protected
progressAnimatorStep: function(inSender) {
this.setProgress(inSender.value);
return true;
},
progressAnimatorComplete: function(inSender) {
this.doAnimateProgressFinish(inSender);
return true;
}
});
| JavaScript | 0 | @@ -1048,96 +1048,8 @@
r%22,%0A
-%09%09//* Sliders may %22snap%22 to multiples of this value in either direction%0A%09%09increment: 0,%0A
%09%09//
@@ -2240,114 +2240,8 @@
%09%7D,%0A
-%09calcIncrement: function(inValue) %7B%0A%09%09return (Math.round(inValue / this.increment) * this.increment);%0A%09%7D,%0A
%09cla
|
4cc0ab59dc5e82e173fa990579f08b293d9a9946 | Fix another bug due to Ohm API change. | src/editorErrors.js | src/editorErrors.js | /* global document */
'use strict';
var cmUtil = require('./cmUtil');
var domUtil = require('./domUtil');
var ohmEditor = require('./ohmEditor');
var errorMarks = {
grammar: null,
input: null
};
function hideError(category, editor) {
var errInfo = errorMarks[category];
if (errInfo) {
errInfo.mark.clear();
clearTimeout(errInfo.timeout);
if (errInfo.widget) {
errInfo.widget.clear();
}
errorMarks[category] = null;
}
}
function setError(category, editor, interval, messageOrNode) {
hideError(category, editor);
errorMarks[category] = {
mark: cmUtil.markInterval(editor, interval, 'error-interval', false),
timeout: setTimeout(showError.bind(null, category, editor, interval, messageOrNode), 1500),
widget: null
};
}
function showError(category, editor, interval, messageOrNode) {
var errorEl = domUtil.createElement('.error');
if (typeof messageOrNode === 'string') {
errorEl.textContent = messageOrNode;
} else {
errorEl.appendChild(messageOrNode);
}
var line = editor.posFromIndex(interval.endIdx).line;
errorMarks[category].widget = editor.addLineWidget(line, errorEl, {insertAt: 0});
}
function createErrorEl(result, pos) {
var el = domUtil.createElement('span', 'Expected ');
var failures = result._failures;
var sep = ', ';
var lastSep = failures.length >= 3 ? ', or ' : ' or '; // Oxford comma.
failures.forEach(function(f, i) {
var prefix = '';
if (i > 0) {
prefix = i === failures.length - 1 ? lastSep : sep;
}
el.appendChild(document.createTextNode(prefix));
var link = el.appendChild(domUtil.createElement('span.link', f.toString()));
link.onclick = function() { ohmEditor.emit('goto:failure', f); };
link.onmouseenter = function() { ohmEditor.emit('peek:failure', f); };
link.onmouseout = function() { ohmEditor.emit('unpeek:failure'); };
});
return el;
}
// Hide errors in the editors as soon as the user starts typing again.
ohmEditor.addListener('change:grammarEditor', function(cm) {
hideError('grammar', cm);
});
ohmEditor.addListener('change:inputEditor', function(cm) {
hideError('input', cm);
});
// Hide the input error when the grammar is about to be reparsed.
ohmEditor.addListener('change:grammar', function(source) {
hideError('input', ohmEditor.ui.inputEditor);
});
ohmEditor.addListener('parse:grammar', function(matchResult, grammar, err) {
if (err) {
var editor = ohmEditor.ui.grammarEditor;
setError('grammar', editor, err.interval, err.shortMessage || err.message);
}
});
ohmEditor.addListener('parse:input', function(matchResult, trace) {
if (trace.result.failed()) {
var editor = ohmEditor.ui.inputEditor;
// Intervals with start == end won't show up in CodeMirror.
var interval = trace.result.getInterval();
interval.endIdx += 1;
setError('input', editor, interval, createErrorEl(trace.result));
}
});
| JavaScript | 0 | @@ -1287,17 +1287,30 @@
ult.
-_f
+getRightmostF
ailures
+()
;%0A
|
cd806bc61529c59bf63e38bc7f64c2a911905f6a | Change logo size | app/components/Logo.js | app/components/Logo.js | import React from 'react';
import Icon from './Icon';
const Logo = () => (
<Icon
name="logo"
width={98}
height={24}
/>
);
export default Logo;
| JavaScript | 0 | @@ -110,9 +110,9 @@
h=%7B9
-8
+0
%7D%0A
@@ -126,9 +126,9 @@
t=%7B2
-4
+2
%7D%0A
|
609ebe2160ca038175ace81bd1cfa4237ed0f5f3 | update passport.js | app/config/passport.js | app/config/passport.js |
var TwitterStrategy = require('passport-twitter').Strategy,
configTwitter = require('./configTwitter'),
UserModel = require('../models/UserModel');
module.exports = function (passport) {
// serialize user
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// deserialize user
passport.deserializeUser(function(id, done) {
UserModel.findById(id, function(err, user) {
done(err, user);
});
});
// Twitter Autenticate
passport.use(new TwitterStrategy({
consumerKey : configTwitter.consumerKey,
consumerSecret : configTwitter.consumerSecret,
callbackURL : configTwitter.callbackURL
},
function(token, tokenSecret, profile, done) {
// make the code asynchronous
// User.findOne won't fire until we have all our data back from Twitter
process.nextTick(function() {
UserModel.findOne({ _id : profile.id }, function(err, user) {
// if there is an error, stop everything and return that
// ie an error connecting to the database
if (err) return done(err);
// if the user is found then log them in
if (user) {
return done(null, user); // user found, return that user
} else {
// if there is no user, create them
var newUser = new UserModel({
_id : profile.id,
token : token,
username : profile.username,
displayName : profile.displayName
});
// save our user into the database
newUser.save(function(err) {
if (err) throw err;
return done(null, newUser);
});
}
});
});
}));
};
| JavaScript | 0.000001 | @@ -928,17 +928,16 @@
ne(%7B _id
-
: profil
@@ -1643,16 +1643,79 @@
playName
+,%0A avatar : profile.photos%5B0%5D.value
%0A
|
1c9e5b3200ddd17e2cbd1f2f4a7240d036ea5e4a | Add todo about views | src/entity-store.js | src/entity-store.js | /* A data structure that is aware of views and entities.
* 1. If a value exist both in a view and entity, the newest value is preferred.
* 2. If a view or entity is removed, the connected views and entities are also removed.
* 3. If a new view value is added, it will be merged into the entity value if such exist.
* otherwise a new view value will be added.
*
* Note that a view will always return at least what constitutes the view.
* It can return the full entity too. This means the client code needs to take this into account
* by not depending on only a certain set of values being there.
* This is done to save memory and to simplify data synchronization.
* Of course, this also requiers the view to truly be a subset of the entity.
*/
import {merge} from './merger';
import {curry, reduce, map_, clone, noop} from './fp';
import {removeId} from './id-helper';
// Value -> StoreValue
const toStoreValue = v => ({value: v, timestamp: Date.now()});
// EntityStore -> String -> Value
const read = ([_, s], k) => (s[k] ? {...s[k], value: clone(s[k].value)} : s[k]);
// EntityStore -> String -> Value -> ()
const set = ([eMap, s], k, v) => { s[k] = toStoreValue(clone(v)); };
// EntityStore -> String -> ()
const rm = curry(([_, s], k) => delete s[k]);
// Entity -> String
const getEntityType = e => e.viewOf || e.name;
// EntityStore -> Entity -> ()
const rmViews = ([eMap, s], e) => {
const entityType = getEntityType(e);
const toRemove = [...eMap[entityType]];
map_(rm([eMap, s]), toRemove);
};
// Entity -> Value -> String
const createEntityKey = (e, v) => {
return getEntityType(e) + v.__ladda__id;
};
// Entity -> Value -> String
const createViewKey = (e, v) => {
return e.name + v.__ladda__id;
};
// Entity -> Bool
const isView = e => !!e.viewOf;
// EntityStore -> Hook
const getHook = (es) => es[2];
// EntityStore -> Type -> [Entity] -> ()
const triggerHook = curry((es, e, type, xs) => getHook(es)({
type,
entity: getEntityType(e),
entities: removeId(xs)
}));
// Function -> Function -> EntityStore -> Entity -> Value -> a
const handle = curry((viewHandler, entityHandler, s, e, v) => {
if (isView(e)) {
return viewHandler(s, e, v);
}
return entityHandler(s, e, v);
});
// EntityStore -> Entity -> Value -> Bool
const entityValueExist = (s, e, v) => !!read(s, createEntityKey(e, v));
// EntityStore -> Entity -> Value -> ()
const setEntityValue = (s, e, v) => {
if (!v.__ladda__id) {
throw new Error(`Value is missing id, tried to add to entity ${e.name}`);
}
const k = createEntityKey(e, v);
set(s, k, v);
return v;
};
// EntityStore -> Entity -> Value -> ()
const setViewValue = (s, e, v) => {
if (!v.__ladda__id) {
throw new Error(`Value is missing id, tried to add to view ${e.name}`);
}
if (entityValueExist(s, e, v)) {
const eValue = read(s, createEntityKey(e, v)).value;
setEntityValue(s, e, merge(v, eValue));
rmViews(s, e); // all views will prefer entity cache since it is newer
} else {
const k = createViewKey(e, v);
set(s, k, v);
}
return v;
};
// EntityStore -> Entity -> [Value] -> ()
export const mPut = curry((es, e, xs) => {
map_(handle(setViewValue, setEntityValue)(es, e))(xs);
triggerHook(es, e, 'UPDATE', xs);
});
// EntityStore -> Entity -> Value -> ()
export const put = curry((es, e, x) => mPut(es, e, [x]));
// EntityStore -> Entity -> String -> Value
const getEntityValue = (s, e, id) => {
const k = createEntityKey(e, {__ladda__id: id});
return read(s, k);
};
// EntityStore -> Entity -> String -> Value
const getViewValue = (s, e, id) => {
const entityValue = read(s, createEntityKey(e, {__ladda__id: id}));
const viewValue = read(s, createViewKey(e, {__ladda__id: id}));
const onlyViewValueExist = viewValue && !entityValue;
if (onlyViewValueExist) {
return viewValue;
}
return entityValue;
};
// EntityStore -> Entity -> String -> ()
export const get = handle(getViewValue, getEntityValue);
// EntityStore -> Entity -> String -> ()
export const remove = (es, e, id) => {
const x = get(es, e, id);
rm(es, createEntityKey(e, {__ladda__id: id}));
rmViews(es, e);
if (x) {
triggerHook(es, e, 'DELETE', [x.value]);
}
};
// EntityStore -> Entity -> String -> Bool
export const contains = (es, e, id) => !!handle(getViewValue, getEntityValue)(es, e, id);
// EntityStore -> Entity -> EntityStore
const registerView = ([eMap, ...other], e) => {
if (!eMap[e.viewOf]) {
eMap[e.viewOf] = [];
}
eMap[e.viewOf].push(e.name);
return [eMap, ...other];
};
// EntityStore -> Entity -> EntityStore
const registerEntity = ([eMap, ...other], e) => {
if (!eMap[e.name]) {
eMap[e.name] = [];
}
return [eMap, ...other];
};
// EntityStore -> Entity -> EntityStore
const updateIndex = (m, e) => { return isView(e) ? registerView(m, e) : registerEntity(m, e); };
// [Entity] -> EntityStore
export const createEntityStore = (c, hook = noop) => reduce(updateIndex, [{}, {}, hook], c);
| JavaScript | 0 | @@ -1836,16 +1836,80 @@
es%5B2%5D;%0A%0A
+// TODO All hook code needs to be able to deal with views also!%0A
// Entit
|
60ca445a2c14736ba051d646c6e7bed56cc4c19c | Update console.js | app/console/console.js | app/console/console.js | angular.module('uiRouterSample.console', [
'ui.router'
])
.config(
[ '$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider
/////////////////
// Home Screen //
/////////////////
.state('console', {
url: '/console',
views: {
'': {
templateUrl: 'app/console/console.html',
controller: ['$scope', '$state', '$rootScope', '$http',
function ( $scope, $state, $rootScope, $http) {
$rootScope.enableConfiguration = "disabled";
alert("console-17");
// $http.get("assets/data/console-data.txt")
// .success(function(data) {
// //$scope.consolegrid.data = data;
// alert("http complete" + data);
// });
$scope.consolegrid.data = [
{
"name": "Ethel Price",
"country": "Scotland",
"gender": "female",
"dependant": "spouse",
"offer": "EMPLOYER",
"offerStatus": "OK",
"englishScore": "92",
"englishScoreStatus": "HIGH",
"daysRemaining": "183",
"applicantStatus": "APPROVED"
}
];
$scope.consolegrid = { enableRowSelection: true, enableRowHeaderSelection: false };
$scope.consolegrid.columnDefs = [
{ name: 'Applicant Name', field: 'name', width: "18%" },
{ name: 'Gender', field: 'gender', width: "10%" },
{ name: 'Dependants', field: 'dependant', width: "10%" },
{ name: 'Entry Offer', field: 'offer', width: "13%", enableFiltering: false,
cellClass: function(grid, row, col, rowRenderIndex, colRenderIndex)
{
if(row.entity.offerStatus === 'OK') { return 'status-ok'; }
else if(row.entity.offerStatus === 'Inactive') { return 'status-inactive'; }
else if(row.entity.offerStatus === 'Rejected') { return 'status-error'; }
}
},
{ name: 'Resident Country', field: 'country', width: "13%" },
{ name: 'English Score', field: 'englishScore', width: "13%", enableFiltering: false,
cellClass: function(grid, row, col, rowRenderIndex, colRenderIndex)
{
if(row.entity.englishScoreStatus === 'HIGH') { return 'status-ok'; }
else if(row.entity.englishScoreStatus === 'MEDIUM') { return 'status-inactive'; }
else if(row.entity.englishScoreStatus === 'LOW') { return 'status-error'; }
}
},
{ name: 'Days Remaining', field: 'daysRemaining', width: "12%", cellClass: "console-text-center" },
{ name: 'Status', field: 'applicantStatus', width: "11%", enableFiltering: false,
cellClass: function(grid, row, col, rowRenderIndex, colRenderIndex)
{
if(row.entity.applicantStatus === 'APPROVED') { return 'status-ok'; }
else if(row.entity.applicantStatus === 'ON-HOLD') { return 'status-hold'; }
else if(row.entity.applicantStatus === 'REJECTED') { return 'status-error'; }
}
}
];
$scope.consolegrid.multiSelect = false;
$scope.consolegrid.modifierKeysToMultiSelect = false;
$scope.consolegrid.noUnselect = false;
$scope.consolegrid.onRegisterApi = function ( gridApi) {
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope, function(row){
if(row.isSelected)
{
if(row.entity && row.entity.name)
{
//Save the selected application into singleton
//singleton.setConsoleRow(row);
$rootScope.enableConfiguration = "enabled";
}
}
});
};
$scope.toggleRowSelection = function() {
$scope.gridApi.selection.clearSelectedRows();
$scope.consolegrid.enableRowSelection = !$scope.consolegrid.enableRowSelection;
$scope.gridApi.core.notifyDataChange( uiGridConstants.dataChange.OPTIONS);
};
}]
},
'navigation-bar@': {
templateUrl: 'app/navbar/console-navbar.html'
}
}
})
;
}
]
);
| JavaScript | 0.000002 | @@ -598,32 +598,34 @@
+//
$rootScope.enabl
@@ -709,10 +709,10 @@
ole-
-17
+20
%22);%0A
@@ -999,361 +999,8 @@
%0A
- $scope.consolegrid.data = %5B%0A %7B%0A %22name%22: %22Ethel Price%22,%0A %22country%22: %22Scotland%22,%0A %22gender%22: %22female%22,%0A %22dependant%22: %22spouse%22,%0A %22offer%22: %22EMPLOYER%22,%0A %22offerStatus%22: %22OK%22,%0A %22englishScore%22: %2292%22,%0A %22englishScoreStatus%22: %22HIGH%22,%0A %22daysRemaining%22: %22183%22,%0A %22applicantStatus%22: %22APPROVED%22%0A %7D%0A%0A%5D;%0A
%0A
|
2ac31109219746d807c716643bc5dbaffc5a4280 | Update selector.js | gaems/selector.js | gaems/selector.js | var text = "Click Start button!! Нажмите кнопку Пуск! Cliquez sur le bouton Démarrer! Klicken den Startknopf!";
for(var i in text) {
if(text[i] === " ") {
$(".wavetext").append( $("<span>").html(" ") );
} else {
$(".wavetext").append( $("<span>").text(text[i]) );
}
}
| JavaScript | 0.000001 | @@ -4,16 +4,17 @@
text =
+%5B
%22Click S
@@ -29,89 +29,405 @@
ton!
-! %D0%9D%D0%B0%D0%B6%D0%BC%D0%B8%D1%82%D0%B5 %D0%BA%D0%BD%D0%BE%D0%BF%D0%BA%D1%83 %D0%9F%D1%83%D1%81%D0%BA! Cliquez sur le bouton D%C3%A9marrer! Klicken den Startknopf!%22;%0A
+%22, %22%D0%9D%D0%B0%D0%B6%D0%BC%D0%B8%D1%82%D0%B5 %D0%BA%D0%BD%D0%BE%D0%BF%D0%BA%D1%83 %D0%9F%D1%83%D1%81%D0%BA!%22, %22%D0%9D%D0%B0%D0%B6%D0%BC%D0%B8%D1%82%D0%B5 %D0%BA%D0%BD%D0%BE%D0%BF%D0%BA%D1%83 %D0%9F%D1%83%D1%81%D0%BA!%22, %22Klicken den Startknopf!%22%5D;%0Avar counter = 0;%0Avar elem = document.getElementById(%22wavetext%22);%0Avar inst = setInterval(change, 4000);%0A%0Afunction change() %7B%0A elem.innerHTML = text%5Bcounter%5D;%0A counter++;%0A if (counter %3E= text.length) %7B%0A counter = 0;%0A // clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle%0A %7D%0A%7D
%0Afor
|
80830a124c15bd09c42025ebdd876d51d4008475 | Rename banettes | client/components/banettes/banettes.constant.js | client/components/banettes/banettes.constant.js | 'use strict';
angular.module('impactApp').constant('banettes', [
{
id: 'toutes',
label: 'Toutes'
},
{
id: 'emise',
label: 'Émises'
},
{
id: 'complet',
label: 'Complètes'
},
{
id: 'incomplet',
label: 'Incomplètes'
},
{
id: 'archive',
label: 'Archivées'
}
]);
| JavaScript | 0.000379 | @@ -144,19 +144,18 @@
: '%C3%89mise
-s
'%0A
+
%7D,%0A %7B
@@ -190,25 +190,24 @@
l: 'Compl%C3%A8te
-s
'%0A %7D,%0A %7B%0A
@@ -248,17 +248,16 @@
compl%C3%A8te
-s
'%0A %7D,%0A
@@ -274,24 +274,24 @@
'archive',%0A
+
label: '
@@ -298,17 +298,16 @@
Archiv%C3%A9e
-s
'%0A %7D%0A%5D)
|
2308c636eccbaa9d472efbfc100a4d9b5dab99a2 | fix josh crash (#15026) | shared/common-adapters/icon.shared.js | shared/common-adapters/icon.shared.js | // @flow
import {globalColors} from '../styles'
import type {IconType} from './icon'
import {iconMeta} from './icon.constants'
export function defaultColor(type: IconType): ?string {
switch (type) {
case 'iconfont-proof-broken':
return globalColors.red
case 'iconfont-proof-pending':
return globalColors.black_40
case 'iconfont-close':
return globalColors.black_20
default:
return null
}
}
export function defaultHoverColor(type: IconType): ?string {
switch (type) {
case 'iconfont-proof-broken':
case 'iconfont-proof-pending':
return defaultColor(type)
case 'iconfont-close':
return globalColors.black_60
default:
return null
}
}
// Some types are the same underlying icon.
export function typeToIconMapper(type: IconType): IconType {
switch (type) {
case 'icon-progress-white-animated':
return __STORYBOOK__ ? 'icon-progress-white-static' : 'icon-progress-white-animated'
case 'icon-progress-grey-animated':
return __STORYBOOK__ ? 'icon-progress-grey-static' : 'icon-progress-grey-animated'
case 'icon-loader-infinity-64':
return __STORYBOOK__ ? 'icon-loader-infinity-static-64' : 'icon-loader-infinity-64'
case 'icon-loader-infinity-80':
return __STORYBOOK__ ? 'icon-loader-infinity-static-80' : 'icon-loader-infinity-80'
case 'icon-facebook-visibility':
return __STORYBOOK__ ? 'icon-facebook-visibility-static' : 'icon-facebook-visibility'
case 'icon-secure-266':
return __STORYBOOK__ ? 'icon-secure-static-266' : 'icon-secure-266'
case 'icon-securing-266':
return __STORYBOOK__ ? 'icon-securing-static-266' : 'icon-securing-266'
case 'icon-loader-uploading-16':
return __STORYBOOK__ ? 'icon-loader-uploading-16-static' : 'icon-loader-uploading-16'
case 'icon-loader-connecting-266':
return __STORYBOOK__ ? 'icon-loader-connecting-266-static' : 'icon-loader-connecting-266'
default:
return type
}
}
export function typeExtension(type: IconType): string {
return iconMeta[type].extension || 'png'
}
export function fontSize(type: IconType): ?Object {
const meta = iconMeta[type]
if (!meta) {
throw new Error('Invalid icon type: ' + type)
}
const fontSize: ?number = meta.gridSize
if (fontSize) {
return {fontSize}
} else {
return null
}
}
const idealSizeMultMap = {
'128': {'1': 256, '2': 256, '3': 960},
'16': {'1': 256, '2': 256, '3': 192},
'32': {'1': 256, '2': 256, '3': 192},
'48': {'1': 192, '2': 192, '3': 960},
'64': {'1': 256, '2': 256, '3': 192},
'96': {'1': 192, '2': 192, '3': 960},
}
const _getMultsMapCache = {}
export function getMultsMap(imgMap: {[size: string]: any}, targetSize: number): any {
let sizes: any = Object.keys(imgMap)
if (!sizes.length) {
return null
}
const sizeKey = targetSize + ']' + sizes.join(':')
if (_getMultsMapCache[sizeKey]) {
return _getMultsMapCache[sizeKey]
}
sizes = sizes.map(s => parseInt(s, 10)).sort((a: number, b: number) => a - b)
const multsMap: any = {
'1': null,
'2': null,
'3': null,
}
Object.keys(multsMap).forEach(mult => {
// find ideal size if it exist
const level1 = idealSizeMultMap[String(targetSize)]
if (level1) {
const level2 = level1[String(mult)]
if (level2) {
multsMap[mult] = level2
return
}
}
// fallback
const ideal = parseInt(mult, 10) * targetSize
const size = sizes.find(size => size >= ideal)
multsMap[mult] = size || sizes[sizes.length - 1]
})
_getMultsMapCache[sizeKey] = multsMap
return multsMap
}
export function castPlatformStyles(styles: any) {
return styles
}
| JavaScript | 0 | @@ -2737,19 +2737,22 @@
umber):
-any
+Object
%7B%0A let
@@ -2816,28 +2816,26 @@
%0A return
-null
+%7B%7D
%0A %7D%0A%0A cons
@@ -2954,16 +2954,22 @@
sizeKey%5D
+ %7C%7C %7B%7D
%0A %7D%0A%0A
|
452a94aafaf78f01207e1daca628869b1655c25c | add fix to wikipedia redux module to show error and only dispatch once api is done | src/redux/modules/Wikipedia/Wikipedia.js | src/redux/modules/Wikipedia/Wikipedia.js | /**
* resources
* http://stackoverflow.com/questions/8363531/accessing-main-picture-of-wikipedia-page-by-api
*/
// using this because json-fetch doesn't support jsonp
import fetchJsonp from 'fetch-jsonp'
// import { notifSend } from 'redux/modules/Notification/actions/notifs.js'
// ------------------------------------
// Constants
// ------------------------------------
export const SEARCH_INPUT_SET = 'SEARCH_INPUT_SET'
export const WIKI_SEARCH_REQUEST = 'WIKI_SEARCH_REQUEST'
export const WIKI_SEARCH_RECEIVE = 'WIKI_SEARCH_RECEIVE'
export const WIKI_SEARCH_FAILURE = 'WIKI_SEARCH_FAILURE'
// ------------------------------------
// Actions
// ------------------------------------
export const searchInputSet = (value = '') => ({
type: SEARCH_INPUT_SET,
payload: value
})
export const wikiSearchRequest = () => ({ type: WIKI_SEARCH_REQUEST })
export const wikiSearchFailure = () => ({ type: WIKI_SEARCH_FAILURE })
export const wikiSearchReceive = (articles) => ({
type: WIKI_SEARCH_RECEIVE,
payload: articles
})
/**
* Thunk actions
*/
// lesson: using es7 async/await pattern
export const wikiFetch = () => async (dispatch, getState) => {
dispatch(wikiSearchRequest())
try {
// get the search term from redux store
var searchTerm = getState().wikipedia.searchInput
// lesson: using jsonp because it's too cummbersome to use cors with wikipedia api
var articles = await fetchJsonp(`http://simple.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=${searchTerm}&pithumbsize=300&callback=JSON_CALLBACK`)
// resolve the promise and convert parse response to an object
.then(response => response.json())
// convert the articles object properties into an array of object using es7
// lesson: convert object properties to an array using es7 Object.values
// http://stackoverflow.com/questions/6857468/a-better-way-to-convert-js-object-to-array
.then(json => Object.values(json.query.pages))
dispatch(wikiSearchReceive(articles))
} catch (error) {
console.log(error)
// ToAsk: getting weird edge case error when user is deleting the search word too fast
// send popup if error
// dispatch(notifSend({
// message: "Something went wrong. Please refresh the page or go to wikipedia.org",
// kind: 'danger',
// dismissAfter: 5000
// }))
dispatch(wikiSearchFailure())
}
}
const shouldFetchWiki = (state) => {
// if is fetching
if (state.isFetching) {
return false
} else {
return true
}
}
export const fetchWikiIfNeeded = () => (dispatch, getState) => {
if (shouldFetchWiki(getState().wikipedia)) {
dispatch(wikiFetch())
}
}
export const actions = {
searchInputSet,
fetchWikiIfNeeded
}
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[SEARCH_INPUT_SET]: (state, action) => Object.assign({}, state, {
searchInput: action.payload
}),
[WIKI_SEARCH_REQUEST]: (state) => Object.assign({}, state, {
isFetching: true,
error: false
}),
[WIKI_SEARCH_RECEIVE]: (state, action) => Object.assign({}, state, {
isFetching: false,
articles: action.payload
}),
[WIKI_SEARCH_FAILURE]: (state) => Object.assign({}, state, {
isFetching: false,
error: true,
articles: []
})
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
searchInput: '',
articles: [],
isFetching: false,
error: true
}
export default function wikipedia(state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
} | JavaScript | 0 | @@ -1,12 +1,43 @@
+import %7BisEmpty%7D from 'lodash'%0A
/**%0A * resou
@@ -231,19 +231,16 @@
-jsonp'%0A
-//
import %7B
@@ -2081,45 +2081,423 @@
=%3E
-Object.values(json.query.pages))%0A%0A
+%7B%0A // if wikipedia api does return a query object then return json object otherwise dispactch a wikiSearchFailure action%0A // lesson: using es7 Object.values to return only the value of the object and not the property as an array%0A if (json.query) %7B%0A return Object.values(json.query.pages)%0A %7D else %7B%0A dispatch(wikiSearchFailure())%0A %7D%0A %7D)%0A%0A // if articles is not empty then
dis
@@ -2493,33 +2493,33 @@
ty then dispatch
-(
+
wikiSearchReceiv
@@ -2523,70 +2523,125 @@
eive
-(articles))%0A %7D catch (error) %7B%0A console.log
+%0A if (isEmpty(articles) === false) %7B%0A dispatch(wikiSearchReceive(articles))%0A %7D%0A %7D catch
(error)
+ %7B
%0A //
ToAs
@@ -2640,91 +2640,78 @@
//
-ToAsk: getting weird edge case error when user is deleting the search word too fast
+for all other errors dispatch wikiSearchFailure%0A console.log(error)
%0A
@@ -2737,19 +2737,16 @@
rror%0A
- //
dispatc
@@ -2762,19 +2762,16 @@
nd(%7B%0A
- //
messa
@@ -2849,19 +2849,16 @@
rg%22,%0A
- //
kind:
@@ -2876,13 +2876,10 @@
-//
-
dism
@@ -2896,19 +2896,16 @@
5000%0A
- //
%7D))%0A
|
31bc941fe26da909cc423d465f9ee10a5d43fded | Fix audio in JavaScript. Including a slug-crash that occurs the first time you try to load a sound. | Compiler/Translator/JavaScript/Browser/sound.js | Compiler/Translator/JavaScript/Browser/sound.js |
/*
A music native object is a struct-like list of 3 items.
music[0] -> audio object
music[1] -> user-given filepath
music[2] -> URL
music[3] -> is looping
*/
R.isAudioEnabled = function (audioObj) {
return !!audioObj.canPlayType('audio/ogg');
};
R.musicSetVolume = function (r) {
if (R.musicCurrent != null)
R.musicCurrent[0].volume = r;
};
R.musicCurrent = null;
R.musicPlay = function (music, loop) {
if (R.musicIsPlaying()) R.musicCurrent[0].pause();
if (R.isAudioEnabled(music[0])) {
music[0].currentTime = 0;
music[3] = loop;
R.musicCurrent = music;
music[0].play();
}
};
R.musicStop = function () {
if (R.musicIsPlaying()) R.musicCurrent[0].pause();
};
R.musicIsPlaying = function () {
return R.musicCurrent != null && !R.musicCurrent.paused;
};
R.musicLoad = function (filepath) {
var audioObject = new Audio(%%%JS_FILE_PREFIX%%% + filepath);
var m = [
audioObject,
filepath,
filepath,
false
];
audioObject.addEventListener('ended', function () {
if (m[3]) { // isLooping.
this.currentTime = 0;
this.play();
}
}, false);
return m;
};
/*
At the core of the sound mixer is a giant list of sound "structs" which are individually treated
as the "native sound object" to the rest of the translated code.
Each sound struct is a list composed of 3 items:
- soundStruct[0] -> a list of JS Audio objects.
- soundStruct[1] -> the original file name that should be used as the input to new Audio objects.
- soundStruct[2] -> the index of this object in the overall list of sound structs.
There is also a reverse lookup of filepaths to the index of where they are in this list.
When a sound is being loaded, the index is looked up in the reverse lookup. If none is
found, then a new sound struct is created with exactly 1 Audio object in it with that filename.
When a sound struct is going to be played, the first Audio object that is not currently playing has
its .play() method invoked. If there are no available objects, a new one is created and pushed to the
end of the list. Servers/browsers should be smart enough to start playing this instantly with a 304.
A channel instance is the following list-struct
- channelStruct[0] -> soundStruct index
- channelStruct[1] -> the current audio element that's playing
- channelStruct[2] -> currentTime value if paused, or null if playing
- channelStruct[3] -> current state: 0 -> playing, 1 -> paused, 2 -> stopped
*/
R.soundObjectIndexByFilename = {};
R.soundObjectsByIndex = [];
R.prepSoundForLoading = function (filepath) {
var index = R.soundObjectIndexByFilename[filepath];
if (index === undefined) {
index = R.soundObjectsByIndex.length;
var data = [[new Audio(%%%JS_FILE_PREFIX%%% + filepath)], filepath, index];
R.soundObjectIndexByFilename[filepath] = index;
R.soundObjectsByIndex.push(data);
}
return R.soundObjectsByIndex[index];
};
R.stopSound = function (channel, isPause) {
if (channel[3] == 0) {
var s = R.soundObjectsByIndex[channel[0]];
var audio = s[0][channel[1]];
if (!audio.ended) {
channel[2] = audio.currentTime;
audio.pause();
channle[3] = isPause ? 1 : 2;
}
}
};
R.resumeSound = function (channel) {
if (channel[3] == 1) {
var s = R.soundObjectsByIndex[channel[0]];
newChannel = R.playSound(s[1], channel[2]); // just discard the new channel object and apply the info to the currently existing reference.
channel[1] = newChannel[1];
channel[3] = 0;
}
};
R.playSound = function (sound, startFrom) {
var audioList = sound[0];
var audio = null;
var audioIndex = 0;
for (var i = 0; i < audioList.length; ++i) {
if (!audioList[i].playing) {
audio = audioList[i];
audioIndex = i;
break;
}
}
if (audio == null) {
audioIndex = audioList.length;
audio = new Audio(%%%JS_FILE_PREFIX%%% + sound[1]);
audioList.push(audio);
}
if (R.isAudioEnabled(audio)) {
audio.currentTime = startFrom;
audio.play();
// See channel struct comment above.
return [sound[2], audioIndex, null, 0];
}
return [sound[2], audioIndex, null, 2];
};
| JavaScript | 0 | @@ -165,16 +165,132 @@
%0D%0A*/%0D%0A%0D%0A
+R._dummyAudio = new Audio();%0D%0A%0D%0AR.isAudioSupported = function () %7B%0D%0A%09return R.isAudioEnabled(R._dummyAudio);%0D%0A%7D;%0D%0A%0D%0A
R.isAudi
@@ -333,24 +333,29 @@
eturn !!
-a
+R._dummyA
udio
-Obj
.canPlay
@@ -641,16 +641,52 @@
0%5D)) %7B%0D%0A
+%09%09if (music%5B0%5D.readyState == 2) %7B%0D%0A%09
%09%09music%5B
@@ -706,16 +706,21 @@
e = 0;%0D%0A
+%09%09%7D%0D%0A
%09%09music%5B
@@ -1196,24 +1196,24 @@
ction () %7B%0D%0A
+
%09%09if (m%5B3%5D)
@@ -1227,17 +1227,16 @@
Looping.
-
%0D%0A%09%09%09thi
@@ -4147,24 +4147,57 @@
(audio)) %7B%0D%0A
+%09%09if (audio.readyState == 2) %7B%0D%0A%09
%09%09audio.curr
@@ -4218,16 +4218,21 @@
tFrom;%0D%0A
+%09%09%7D%0D%0A
%09%09audio.
|
fb84ff3375fcc6beebafa1cb71e9336dc5de5be4 | Load lazy taxon tree using a single click | Resources/private/js/sylius-lazy-choice-tree.js | Resources/private/js/sylius-lazy-choice-tree.js | /*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
(function ($) {
'use strict';
$.fn.extend({
choiceTree: function (type, multiple, defaultLevel) {
var tree = $(this);
var loader = $(this).find('.dimmer');
var loadedLeafs = [];
var $input = $(this).find('input[type="hidden"]');
tree.api({
on: 'now',
method: 'GET',
url: tree.data('taxon-root-nodes-url'),
cache: false,
beforeSend: function(settings) {
loader.addClass('active');
return settings;
},
onSuccess: function (response) {
var rootContainer = createRootContainer();
$.each(response, function (rootNodeIndex, rootNode) {
rootContainer.append(createLeaf(rootNode.name, rootNode.code, rootNode.hasChildren, multiple, rootNode.level));
});
tree.append(rootContainer);
loader.removeClass('active');
}
});
var createLeaf = function (name, code, hasChildren, multipleChoice, level) {
var displayNameElement = createLeafTitleSpan(name);
var titleElement = createLeafTitleElement();
var iconElement = createLeafIconElement();
var checkboxElement = createCheckboxElement(name, code, multipleChoice);
bindCheckboxAction(checkboxElement);
var leafElement = $('<div class="item"></div>');
var leafContentElement = createLeafContentElement();
leafElement.append(iconElement);
titleElement.append(displayNameElement);
titleElement.append(checkboxElement);
leafContentElement.append(titleElement);
if (!hasChildren) {
iconElement.addClass('outline');
}
if (hasChildren) {
bindExpandLeafAction(code, displayNameElement, leafContentElement, iconElement, level);
}
leafElement.append(leafContentElement);
return leafElement;
};
var createRootContainer = function () {
return $('<div class="ui list"></div>');
};
var createLeafContainerElement = function () {
return $('<div class="list"></div>');
};
var createLeafIconElement = function () {
return $('<i class="folder icon"></i>');
};
var createLeafTitleElement = function () {
return $('<div class="header"></div>');
};
var createLeafTitleSpan = function (displayName) {
return $('<span style="margin-right: 5px; cursor: pointer;">'+displayName+'</span>')
};
var createLeafContentElement = function () {
return $('<div class="content"></div>');
};
var createCheckboxElement = function (name, code, multiple) {
var chosenNodes = $input.val().split(',');
var checked = '';
if (chosenNodes.some(function (chosenCode) {return chosenCode === code})) {
checked = 'checked="checked"';
}
if (multiple) {
return $('<div class="ui checkbox" data-value="'+code+'"><input '+checked+' type="checkbox" name="'+type+'"></div>');
}
return $('<div class="ui radio checkbox" data-value="'+code+'"><input '+checked+' type="radio" name="'+type+'"></div>');
};
var isLeafLoaded = function (code) {
return loadedLeafs.some(function (leafCode) {
return leafCode === code;
})
};
var bindExpandLeafAction = function (parentCode, expandButton, content, icon, level) {
var leafContainerElement = createLeafContainerElement();
if (defaultLevel > level) {
loadLeafAction(parentCode, expandButton, content, leafContainerElement);
icon.addClass('open');
}
expandButton.click(function () {
loadLeafAction(parentCode, expandButton, content, leafContainerElement);
leafContainerElement.toggle(200, function () {
if (icon.hasClass('open')) {
icon.removeClass('open');
return;
}
icon.addClass('open');
});
});
};
var loadLeafAction = function (parentCode, expandButton, content, leafContainerElement) {
if (!isLeafLoaded(parentCode)) {
expandButton.api({
on: 'now',
url: tree.data('taxon-leafs-url'),
method: 'GET',
cache: false,
data: {
parentCode: parentCode
},
beforeSend: function(settings) {
loader.addClass('active');
return settings;
},
onSuccess: function (response) {
$.each(response, function (leafIndex, leafNode) {
leafContainerElement.append(createLeaf(leafNode.name, leafNode.code, leafNode.hasChildren, multiple, leafNode.level));
});
content.append(leafContainerElement);
loader.removeClass('active');
loadedLeafs.push(parentCode);
}
});
}
};
var bindCheckboxAction = function (checkboxElement) {
checkboxElement.checkbox({
onChange: function () {
var $checkboxes = tree.find('.checkbox');
var checkedValues = [];
$checkboxes.each(function () {
if ($(this).checkbox('is checked')) {
checkedValues.push($(this).data('value'));
}
});
$input.val(checkedValues.join());
}
});
};
}
});
})(jQuery);
| JavaScript | 0 | @@ -4406,32 +4406,38 @@
Button, content,
+ icon,
leafContainerEl
@@ -4448,51 +4448,8 @@
t);%0A
- icon.addClass('open');%0A
@@ -4574,32 +4574,38 @@
utton, content,
+icon,
leafContainerEle
@@ -4612,317 +4612,8 @@
ment
-);%0A leafContainerElement.toggle(200, function () %7B%0A if (icon.hasClass('open')) %7B%0A icon.removeClass('open');%0A%0A return;%0A %7D%0A%0A icon.addClass('open');%0A %7D
);%0A
@@ -4720,24 +4720,30 @@
on, content,
+ icon,
leafContain
@@ -4747,32 +4747,75 @@
ainerElement) %7B%0A
+ icon.toggleClass('open');%0A%0A
@@ -5902,33 +5902,110 @@
%7D);%0A
- %7D
+%0A return;%0A %7D%0A%0A leafContainerElement.toggle();
%0A
|
bcce23cd443ffd5f836218cf2ecbb0a4abdf319c | prepend 'ask' to ask prices | config/market.js | config/market.js | /* global sails */
var Pusher = require('pusher-client');
var redis = require("./redis");
var log = require("./logger");
// connect to Bitstamp's pusher
var pusherBitstamp = new Pusher('de504dc5763aeef9ff52');
// subscribe to the `order_book` channel
var orderBookChannel = pusherBitstamp.subscribe('order_book');
// export the bind-ed the channel
module.exports.contRate = function() {
orderBookChannel.bind('data', function(data) {
// Bitstamp's trading fees
var netTradeMultiplier = 9975 / 10000; // deducts the .25% trade fee
var netWithdrawalMultiplier = 97 / 100; // deducts the 30 withdrawal fee
var profitMultiplier = 98 / 100; // deducts the profit for Payload services
var usd2pkr = 104.5;
var volBTC = 0; // the volume of bitcoins
var valBTC = 0; // the value of the bitcoins
var wBTC; // the weighted price per bitcoin
var netPriceUSD;
var netPricePKR;
for (i = 0; i < data.asks.length; i++) {
volBTC += parseFloat(data.asks[i][1]);
valBTC += parseFloat(data.asks[i][0]) * parseFloat(data.asks[i][1]);
}
// volume weighted price per bitcoin
wBTC = valBTC / volBTC;
// net price per bitcoin
netPriceUSD = wBTC * netTradeMultiplier * netWithdrawalMultiplier * profitMultiplier;
netPricePKR = usd2pkr * netPriceUSD;
log.debug("cumulative volume of bitcoin", volBTC);
log.debug("value of bitcoin in USD", valBTC);
log.debug("value per bitcoin", wBTC);
log.debug("price per bitcoin USD", netPriceUSD);
log.debug("price per bitcoin PKR", netPricePKR);
redis.set("rateUSD", netPriceUSD);
redis.set("ratePKR", netPricePKR);
});
};
| JavaScript | 0.00246 | @@ -729,17 +729,20 @@
var
-v
+askV
olBTC =
@@ -778,17 +778,20 @@
var
-v
+askV
alBTC =
@@ -830,17 +830,20 @@
var
-w
+askW
BTC; //
@@ -877,25 +877,28 @@
oin%0A var
-n
+askN
etPriceUSD;%0A
@@ -905,17 +905,20 @@
var
-n
+askN
etPriceP
@@ -973,17 +973,20 @@
%7B%0A
-v
+askV
olBTC +=
@@ -1021,17 +1021,20 @@
;%0A
-v
+askV
alBTC +=
@@ -1149,24 +1149,30 @@
-w
+askW
BTC =
-v
+askV
alBTC /
volB
@@ -1167,17 +1167,20 @@
alBTC /
-v
+askV
olBTC;%0A%0A
@@ -1208,25 +1208,28 @@
bitcoin%0A
-n
+askN
etPriceUSD =
@@ -1229,17 +1229,20 @@
ceUSD =
-w
+askW
BTC * ne
@@ -1308,17 +1308,20 @@
er;%0A
-n
+askN
etPriceP
@@ -1335,17 +1335,20 @@
d2pkr *
-n
+askN
etPriceU
@@ -1367,16 +1367,21 @@
.debug(%22
+ASK:
cumulati
@@ -1403,17 +1403,20 @@
tcoin%22,
-v
+askV
olBTC);%0A
@@ -1426,24 +1426,29 @@
log.debug(%22
+ASK:
value of bit
@@ -1461,17 +1461,20 @@
n USD%22,
-v
+askV
alBTC);%0A
@@ -1488,16 +1488,21 @@
.debug(%22
+ASK:
value pe
@@ -1513,17 +1513,20 @@
tcoin%22,
-w
+askW
BTC);%0A
@@ -1530,32 +1530,37 @@
%0A log.debug(%22
+ASK:
price per bitcoi
@@ -1563,25 +1563,28 @@
tcoin USD%22,
-n
+askN
etPriceUSD);
@@ -1599,16 +1599,21 @@
.debug(%22
+ASK:
price pe
@@ -1624,25 +1624,28 @@
tcoin PKR%22,
-n
+askN
etPricePKR);
@@ -1671,17 +1671,20 @@
teUSD%22,
-n
+askN
etPriceU
@@ -1713,17 +1713,20 @@
tePKR%22,
-n
+askN
etPriceP
|
f33f1783a381df78914f5730a40ba1fcfe8b5d7d | Remove comma. | share/spice/alternative_to/alternative_to.js | share/spice/alternative_to/alternative_to.js | function ddg_spice_alternative_to(api_result) {
Spice.render({
data : api_result,
source_name : 'AlternativeTo',
source_url : api_result.Url,
template_normal: "alternative_to",
template_frame : "carousel",
carousel_template_detail: "alternative_to_details",
carousel_css_id: "alternative_to",
carousel_items : api_result.Items,
});
} | JavaScript | 0.000002 | @@ -41,16 +41,35 @@
sult) %7B%0A
+ %22use strict%22;%0A%0A
Spic
@@ -423,17 +423,16 @@
lt.Items
-,
%0A %7D);
|
e362509851e62c63e5ddc03450690743f3cd658f | Implement findOrCreateRoomGivenUserIds | server/db/controllers/findOrCreateRoomGivenUserIds.js | server/db/controllers/findOrCreateRoomGivenUserIds.js | const db = require('../db.js');
module.exports = (user1Id, user2Id) => {
const queryStr = `
SELECT ur_1.ur1_id FROM (
(
SELECT user_id AS user1_id, id AS ur1_id FROM users_rooms
WHERE user_id = '${user1Id}'
) AS ur_1
INNER JOIN
(
SELECT user_id AS user2_id, id AS ur2_id FROM users_rooms
WHERE user_id = '${user2Id}'
) AS ur_2
ON ur_1.user1_id = ur_2.user2_id
)
`;
return db.query(queryStr).spread((results, metadata) => {
if (results.length > 0) {
return results;
} else {
}
});
};
| JavaScript | 0.99977 | @@ -25,16 +25,123 @@
b.js');%0A
+const Rooms = require('../models/roomModel.js');%0Aconst UsersRooms = require('../models/userRoomModel.js');%0A
%0A%0Amodule
@@ -891,22 +891,343 @@
%7D
- else %7B%0A%0A %7D
+%0A return Rooms.create(%7B%0A number_active_participants: 2,%0A %7D)%0A .then(room =%3E (%0A UsersRooms.bulkCreate(%5B%0A %7B%0A user_id: user1Id,%0A room_id: room.id,%0A %7D,%0A %7B%0A user_id: user2Id,%0A room_id: room.id,%0A %7D,%0A %5D)%0A .then(() =%3E (%0A %5Broom%5D%0A ))%0A ));
%0A %7D
|
026e5e6c65954b40306352301c6ede4d5e6a0fd1 | Clean up Pipelines model | server/webapp/WEB-INF/rails.new/webpack/models/preferences/pipelines.js | server/webapp/WEB-INF/rails.new/webpack/models/preferences/pipelines.js | /*
* Copyright 2017 ThoughtWorks, Inc.
*
* 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.
*/
;(function () { // eslint-disable-line no-extra-semi
"use strict";
const Stream = require("mithril/stream");
const _ = require("lodash");
function Pipelines(json) {
const DEFAULT_PIPELINE = "[Any Pipeline]";
const DEFAULT_STAGE = "[Any Stage]";
const pipelineNames = _.map(json, "pipeline");
const events = Stream([
"All",
"Passes",
"Fails",
"Breaks",
"Fixed",
"Cancelled"
]);
const stagesByPipeline = _.reduce(json, (memo, entry) => {
memo[entry.pipeline] = [DEFAULT_STAGE].concat(entry.stages);
return memo;
}, {});
pipelineNames.unshift(DEFAULT_PIPELINE);
stagesByPipeline[DEFAULT_PIPELINE] = [DEFAULT_STAGE];
const pipelines = Stream(pipelineNames);
const currentPipeline = Stream(DEFAULT_PIPELINE);
const stages = currentPipeline.map((pipeline) => {
return stagesByPipeline[pipeline];
});
return {
pipelines,
currentPipeline,
stages,
events
};
}
module.exports = Pipelines;
})();
| JavaScript | 0 | @@ -883,37 +883,178 @@
nst
-pipelineNames =
+data = json.slice(); // duplicate because we will modify%0A data.unshift(%7Bpipeline: DEFAULT_PIPELINE, stages: %5BDEFAULT_STAGE%5D%7D);%0A%0A const pipelines = Stream(
_.map(
-json
+data
, %22p
@@ -1062,16 +1062,17 @@
peline%22)
+)
;%0A co
@@ -1085,23 +1085,16 @@
ents
-
= Stream
@@ -1236,20 +1236,20 @@
.reduce(
-json
+data
, (memo,
@@ -1289,16 +1289,63 @@
eline%5D =
+ (entry.stages.indexOf(DEFAULT_STAGE) === -1) ?
%5BDEFAUL
@@ -1373,16 +1373,31 @@
.stages)
+ : entry.stages
;%0A
@@ -1426,157 +1426,8 @@
);%0A%0A
- pipelineNames.unshift(DEFAULT_PIPELINE);%0A stagesByPipeline%5BDEFAULT_PIPELINE%5D = %5BDEFAULT_STAGE%5D;%0A%0A const pipelines = Stream(pipelineNames);%0A
|
28b5e3d077468e6c453402e6ca96d64bc595f6ca | remove custom plugin tests | test/spawn/parent-custom-plugin-test.js | test/spawn/parent-custom-plugin-test.js | /*
* use-test.js: Basic tests for the carapace module
*
* (C) 2011 Nodejitsu Inc
* MIT LICENCE
*
*/
var assert = require('assert'),
path = require('path'),
exec = require('child_process').exec,
http = require('http'),
request = require('request'),
vows = require('vows'),
helper = require('../helper/macros.js'),
carapace = require('../../lib/carapace');
var jail = path.join(__dirname, '..', '..', 'examples', 'app'),
custom = path.join(__dirname, '..', 'fixtures', 'custom.js'),
options;
options = {
port: 5060,
script: path.join(jail, 'server.js'),
argv: ['--plugin', custom, '--plugin', 'heartbeat'],
cwd: process.cwd(),
keepalive: true
};
vows.describe('carapace/spawn/custom-plugin').addBatch({
"When using haibu-carapace": {
"spawning a child carapace with a custom plugin": helper.assertParentSpawn(options, {
"after the plugin is loaded": {
topic: function (info, child) {
var that = this;
child.once('message', function (info) {
if (info.event === 'custom') {
that.callback(null, child, info);
}
});
},
"should emit the `carapace::custom` event": function (_, child, info) {
assert.isTrue(info.data.custom);
child.kill();
}
}
})
}
}).export(module);
| JavaScript | 0 | @@ -99,18 +99,17 @@
%0A *%0A */%0A
-
%0A
+
var asse
@@ -527,21 +527,17 @@
ptions;%0A
-
%0A
+
options
@@ -696,13 +696,11 @@
%0A%7D;%0A
- %0A
+%0A//
vows
@@ -754,16 +754,18 @@
tch(%7B%0A
+//
%22When us
@@ -791,16 +791,18 @@
: %7B%0A
+//
%22spawnin
@@ -885,16 +885,18 @@
%7B%0A
+//
%22after t
@@ -927,16 +927,18 @@
+//
topic: f
@@ -971,16 +971,18 @@
+//
var that
@@ -996,24 +996,26 @@
;%0A
+//
child.once('
@@ -1054,16 +1054,18 @@
+//
if (info
@@ -1101,16 +1101,18 @@
+//
that.cal
@@ -1141,32 +1141,34 @@
o);%0A
+//
%7D%0A %7D);%0A
@@ -1163,16 +1163,18 @@
+//
%7D);%0A
@@ -1177,16 +1177,18 @@
+//
%7D,%0A
@@ -1190,16 +1190,18 @@
+//
%22should
@@ -1274,16 +1274,18 @@
+//
assert.i
@@ -1319,16 +1319,18 @@
+//
child.ki
@@ -1343,24 +1343,26 @@
+//
%7D%0A
%7D%0A %7D)
@@ -1357,21 +1357,29 @@
+//
%7D%0A
+//
%7D)%0A
-%7D%0A
+//%7D%0A//
%7D).e
|
078844d90c0559cd517dc4aa27f00c67099a396e | Fix lint error | common/models/account.js | common/models/account.js | 'use strict';
module.exports = function(Account) {
// Disable related accessTokens API
Account.disableRemoteMethodByName('prototype.__count__accessTokens');
Account.disableRemoteMethodByName('prototype.__create__accessTokens');
Account.disableRemoteMethodByName('prototype.__delete__accessTokens');
Account.disableRemoteMethodByName('prototype.__destroyById__accessTokens');
Account.disableRemoteMethodByName('prototype.__findById__accessTokens');
Account.disableRemoteMethodByName('prototype.__get__accessTokens');
Account.disableRemoteMethodByName('prototype.__updateById__accessTokens');
// Remove existing validations for email
delete Account.validations.email;
const re_username = /^[a-zA-Z0-9_\-]+$/;
Account.validate('username',
function (err) {
if (this.username !== undefined && !re_username.test(this.username)) err();
},
{ message: 'VALIDATE_ERR_ACCOUNT_USERNAME_PATTERN' });
};
| JavaScript | 0.000035 | @@ -45,18 +45,16 @@
ount) %7B%0A
-
// Dis
@@ -83,18 +83,16 @@
ens API%0A
-
Accoun
@@ -149,34 +149,32 @@
cessTokens');%0A
-
-
Account.disableR
@@ -220,34 +220,32 @@
accessTokens');%0A
-
Account.disabl
@@ -293,34 +293,32 @@
accessTokens');%0A
-
Account.disabl
@@ -371,34 +371,32 @@
accessTokens');%0A
-
Account.disabl
@@ -446,34 +446,32 @@
accessTokens');%0A
-
Account.disabl
@@ -522,26 +522,24 @@
Tokens');%0A
-
-
Account.disa
@@ -602,18 +602,16 @@
ens');%0A%0A
-
// Rem
@@ -645,18 +645,16 @@
r email%0A
-
delete
@@ -686,18 +686,16 @@
l;%0A%0A
-
const
re_u
@@ -690,20 +690,22 @@
const
-re_u
+validU
sername
@@ -729,18 +729,16 @@
%5D+$/;%0A
-
-
Account.
@@ -766,20 +766,16 @@
-
-
function
(er
@@ -774,17 +774,16 @@
tion
-
(err) %7B%0A
@@ -778,22 +778,16 @@
(err) %7B%0A
-
if
@@ -822,14 +822,24 @@
d &&
- !re_u
+%0A !validU
sern
@@ -870,20 +870,16 @@
err();%0A
-
%7D,%0A
@@ -885,14 +885,9 @@
-
- %7B
+%7B
mess
@@ -934,13 +934,14 @@
ERN'
-
%7D
+%0A
);%0A
-%0A
%7D;%0A
|
042d46067cdc33e3a1cd11f25dc245f9e33d4730 | Fix typo a event -> an event (#146) | src/event-target.js | src/event-target.js | import { reject, filter } from './helpers/array-helpers';
/*
* EventTarget is an interface implemented by objects that can
* receive events and may have listeners for them.
*
* https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
*/
class EventTarget {
constructor() {
this.listeners = {};
}
/*
* Ties a listener function to a event type which can later be invoked via the
* dispatchEvent method.
*
* @param {string} type - the type of event (ie: 'open', 'message', etc.)
* @param {function} listener - the callback function to invoke whenever a event is dispatched matching the given type
* @param {boolean} useCapture - N/A TODO: implement useCapture functionality
*/
addEventListener(type, listener /* , useCapture */) {
if (typeof listener === 'function') {
if (!Array.isArray(this.listeners[type])) {
this.listeners[type] = [];
}
// Only add the same function once
if (filter(this.listeners[type], item => item === listener).length === 0) {
this.listeners[type].push(listener);
}
}
}
/*
* Removes the listener so it will no longer be invoked via the dispatchEvent method.
*
* @param {string} type - the type of event (ie: 'open', 'message', etc.)
* @param {function} listener - the callback function to invoke whenever a event is dispatched matching the given type
* @param {boolean} useCapture - N/A TODO: implement useCapture functionality
*/
removeEventListener(type, removingListener /* , useCapture */) {
const arrayOfListeners = this.listeners[type];
this.listeners[type] = reject(arrayOfListeners, listener => listener === removingListener);
}
/*
* Invokes all listener functions that are listening to the given event.type property. Each
* listener will be passed the event as the first argument.
*
* @param {object} event - event object which will be passed to all listeners of the event.type property
*/
dispatchEvent(event, ...customArguments) {
const eventName = event.type;
const listeners = this.listeners[eventName];
if (!Array.isArray(listeners)) {
return false;
}
listeners.forEach((listener) => {
if (customArguments.length > 0) {
listener.apply(this, customArguments);
} else {
listener.call(this, event);
}
});
return true;
}
}
export default EventTarget;
| JavaScript | 0.055029 | @@ -342,16 +342,17 @@
ion to a
+n
event t
@@ -562,32 +562,33 @@
nvoke whenever a
+n
event is dispat
@@ -1325,16 +1325,17 @@
enever a
+n
event i
|
f47bbe39128442898f54df9baf2bea42ebce2988 | Fix pluralization | server/db/controllers/getMatchesGivenSelfAndOffset.js | server/db/controllers/getMatchesGivenSelfAndOffset.js | const db = require('../db.js');
module.exports = (self, offSet) => {
const queryStr = `SELECT teach.teach_id FROM (
(
SELECT users_languages_levels.user AS teach_id FROM users_languages_levels
INNER JOIN languages_levels
ON users_languages_levels.languages_levels = languages_levels.id
INNER JOIN languages
ON languages_levels.language = language.id
INNER JOIN levels
ON languages_levels.level = level.id
WHERE language.name IN (${self.willLearn.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native')
) AS teach
INNER JOIN
(
SELECT users_languages_levels.user AS learn_id FROM users_languages_levels
INNER JOIN languages_levels
ON users_languages_levels.languages_levels = languages_levels.id
INNER JOIN languages
ON languages_levels.language = language.id
INNER JOIN levels
ON languages_levels.level = level.id
WHERE language.name IN (${self.canTeach.map(language => language[0]).join(',')}) AND level.name IN ('fluent', 'native')
) AS learn
ON teach.teach_id = learn.learn_id
)
`;
// db.query();
};
| JavaScript | 0.999419 | @@ -486,32 +486,33 @@
guage = language
+s
.id%0A
@@ -594,32 +594,33 @@
ls.level = level
+s
.id%0A
@@ -638,32 +638,33 @@
WHERE language
+s
.name IN ($%7Bself
@@ -1202,16 +1202,17 @@
language
+s
.id%0A
@@ -1310,16 +1310,17 @@
= level
+s
.id%0A
@@ -1354,16 +1354,17 @@
language
+s
.name IN
|
368920532371b3893336c5c3013f46d594a8232d | Clean up | src/scripts/core/axis/time-scale-axis.js | src/scripts/core/axis/time-scale-axis.js | (function (ns, d3, _, $, undefined) {
// implements the following interface
/*
{
scale: returns the d3 scale for the type
range: returns the d3 range for the type
}
*/
function dateDiff(d1, d2) {
var diff = d1.getTime() - d2.getTime();
return diff / (24*60*60*1000);
}
function TimeScale(data, options) {
this.options = options;
this.data = data;
this.init();
}
TimeScale.prototype = {
init: function () {
delete this._scale;
},
scale: function (domain) {
this._domain = domain;
if(!this._scale) {
this._scale = new d3.time.scale()
.domain(d3.extent(domain));
this.range();
}
return this._scale;
},
axis: function () {
var options = this.options.xAxis;
var tickFormat = this.getOptimalTickFormat();
var axis = d3.svg.axis()
.scale(this._scale)
.tickFormat(tickFormat)
.innerTickSize(options.innerTickSize)
.outerTickSize(options.outerTickSize)
.tickPadding(options.tickPadding)
.tickValues(this._domain);
if (this.options.xAxis.maxTicks != null && this.options.xAxis.maxTicks < this._domain.length) {
// override the tickValues with custom array based on number of ticks
// we don't use D3 ticks() because you cannot force it to show a specific number of ticks
var customValues = [];
var len = this._domain.length;
var step = (len + 1) / this.options.xAxis.maxTicks;
// for (var j=0, index = 0; j<this.options.xAxis.ticks; j++, index += step) {
for (var j=0, index = 0; j<len; j += step, index += step) {
customValues.push(this._domain[Math.min(Math.ceil(index), len-1)]);
}
axis.tickValues(customValues);
} else if (this.options.xAxis.firstAndLast) {
// show only first and last tick
axis.tickValues(_.nw.firstAndLast(this._domain));
}
return axis;
},
postProcessAxis: function (axisGroup) {
var labels = axisGroup.selectAll('.tick text')[0];
$(labels[0]).attr('style', 'text-anchor: start');
$(labels[labels.length - 1]).attr('style', 'text-anchor: end');
},
rangeBand: function () {
return 4;
},
getOptimalTickFormat: function () {
var spanDays = dateDiff(this._domain[this._domain.length-1], this._domain[0]);
if (spanDays < 1) return d3.time.format('%H:%M');
return d3.time.format('%d %b');
},
range: function () {
return this._scale.rangeRound([0, this.options.chart.plotWidth], 0.1);
}
};
_.nw = _.extend({}, _.nw, { TimeScale: TimeScale });
})('Narwhal', window.d3, window._, window.jQuery);
| JavaScript | 0.000002 | @@ -743,16 +743,22 @@
.extent(
+this._
domain))
|
46618476fc72ca55522f409b181d8272e0eb14ca | Correct max price | src/Actions/ActionBuyIn/actionBuyIn.js | src/Actions/ActionBuyIn/actionBuyIn.js | // Copyright 2016 Gavin Wood
import BigNumber from 'bignumber.js';
import React, { Component, PropTypes } from 'react';
import { Dialog, FlatButton, TextField } from 'material-ui';
import { api } from '../../parity';
import AccountSelector from '../../AccountSelector';
import { ERRORS, validateAccount, validatePositiveNumber } from '../validation';
import styles from '../actions.css';
const NAME_ID = ' ';
export default class ActionBuyIn extends Component {
static contextTypes = {
instance: PropTypes.object.isRequired
}
static propTypes = {
accounts: PropTypes.array,
price: PropTypes.object,
onClose: PropTypes.func
}
state = {
account: {},
accountError: ERRORS.invalidAccount,
amount: 0,
amountError: ERRORS.invalidAmount,
maxPrice: api.util.fromWei(this.props.price.mul(1.2)).toFixed(0),
maxPriceError: null,
sending: false,
complete: false
}
render () {
const { complete } = this.state;
if (complete) {
return null;
}
return (
<Dialog
title='buy coins for a specific account'
modal open
className={ styles.dialog }
actions={ this.renderActions() }>
{ this.renderFields() }
</Dialog>
);
}
renderActions () {
const { complete } = this.state;
if (complete) {
return (
<FlatButton
className={ styles.dlgbtn }
label='Done'
primary
onTouchTap={ this.props.onClose } />
);
}
const { accountError, amountError, maxPriceError, sending } = this.state;
const hasError = !!(amountError || accountError || maxPriceError);
return ([
<FlatButton
className={ styles.dlgbtn }
label='Cancel'
primary
onTouchTap={ this.props.onClose } />,
<FlatButton
className={ styles.dlgbtn }
label='Buy'
primary
disabled={ hasError || sending }
onTouchTap={ this.onSend } />
]);
}
renderFields () {
const maxPriceLabel = `maximum price in ETH (current ${api.util.fromWei(this.props.price).toFormat(3)})`;
return (
<div>
<AccountSelector
accounts={ this.props.accounts }
account={ this.state.account }
errorText={ this.state.accountError }
floatingLabelText='from account'
hintText='the account the transaction will be made from'
onSelect={ this.onChangeAddress } />
<TextField
autoComplete='off'
floatingLabelFixed
floatingLabelText='amount in ETH'
fullWidth
hintText='the amount of ETH you wish to spend'
errorText={ this.state.amountError }
name={ NAME_ID }
id={ NAME_ID }
value={ this.state.amount }
onChange={ this.onChangeAmount } />
<TextField
autoComplete='off'
floatingLabelFixed
floatingLabelText={ maxPriceLabel }
fullWidth
hintText='the maxium price allowed for buying'
errorText={ this.state.maxPriceError }
name={ NAME_ID }
id={ NAME_ID }
value={ this.state.maxPrice }
onChange={ this.onChangeMaxPrice } />
</div>
);
}
onChangeAddress = (account) => {
this.setState({
account,
accountError: validateAccount(account)
}, this.validateTotal);
}
onChangeAmount = (event, amount) => {
this.setState({
amount,
amountError: validatePositiveNumber(amount)
}, this.validateTotal);
}
onChangeMaxPrice = (event, maxPrice) => {
this.setState({
maxPrice,
maxPriceError: validatePositiveNumber(maxPrice)
});
}
validateTotal = () => {
const { account, accountError, amount, amountError } = this.state;
if (accountError || amountError) {
return;
}
if (new BigNumber(amount).gt(account.ethBalance.replace(',', ''))) {
this.setState({
amountError: ERRORS.invalidTotal
});
}
}
onSend = () => {
const { instance } = this.context;
const maxPrice = api.util.toWei(this.state.maxPrice);
const values = [this.state.account.address, maxPrice.toString()];
const options = {
from: this.state.account.address,
value: api.util.toWei(this.state.amount).toString()
};
this.setState({
sending: true
});
instance.buyin
.estimateGas(options, values)
.then((gasEstimate) => {
options.gas = gasEstimate.mul(1.2).toFixed(0);
console.log(`buyin: gas estimated as ${gasEstimate.toFixed(0)} setting to ${options.gas}`);
return instance.buyin.postTransaction(options, values);
})
.then(() => {
this.props.onClose();
this.setState({
sending: false,
complete: true
});
})
.catch((error) => {
console.error('error', error);
this.setState({
sending: false
});
});
}
}
| JavaScript | 0.0015 | @@ -840,17 +840,17 @@
toFixed(
-0
+3
),%0A m
|
c0eab6593103e51e9b723216d6cec5978bf91780 | use size 500 for generative tests | spec/channels_spec.js | spec/channels_spec.js | 'use strict';
require('comfychair/jasmine');
var comfy = require('comfychair');
var chan = require('../index');
var merge = function() {
var args = Array.prototype.slice.call(arguments);
var result = args.every(Array.isArray) ? [] : {};
var i, obj, key;
for (i in args) {
obj = args[i];
for (key in obj)
result[key] = obj[key];
}
return result;
};
var model = function() {
var _transitions = {
init: function(state, arg) {
return {
state: {
count : 0,
buffer : [],
bsize : arg,
pullers: [],
pushers: [],
closed : false
}
};
},
push: function(state, val) {
var h = state.count + 1;
state = merge(state, { count: h });
if (state.closed) {
return {
state : state,
output: [[h, false]]
};
} else if (state.pullers.length > 0) {
return {
state : merge(state, { pullers: state.pullers.slice(1) }),
output: [[state.pullers[0], val], [h, true]]
};
} else if (state.bsize > state.buffer.length) {
return {
state : merge(state, { buffer: state.buffer.concat([val]) }),
output: [[h, true]]
};
} else {
return {
state : merge(state, { pushers: state.pushers.concat([[h, val]]) }),
output: []
};
}
},
pull: function(state) {
var h = state.count + 1;
state = merge(state, { count: h });
if (state.buffer.length > 0) {
if (state.pushers.length > 0) {
return {
state: merge(state, {
buffer : state.buffer.slice(1).concat(state.pushers[0][1]),
pushers: state.pushers.slice(1)
}),
output: [[state.pushers[0][0], true], [h, state.buffer[0]]]
};
} else {
return {
state: merge(state, {
buffer: state.buffer.slice(1)
}),
output: [[h, state.buffer[0]]]
};
}
} else if (state.closed) {
return {
state : state,
output: [[h, undefined]]
};
} else if (state.pushers.length > 0) {
return {
state : merge(state, { pushers: state.pushers.slice(1) }),
output: [[state.pushers[0][0], true], [h, state.pushers[0][1]]]
};
} else {
return {
state : merge(state, { pullers: state.pullers.concat([h]) }),
output: []
};
}
},
close: function(state) {
return {
state: merge(state, {
pullers: [],
pushers: [],
closed : true
}),
output: [].concat(
state.pushers.map(function(p) { return [p[0], false]; }),
state.pullers.map(function(p) { return [p, undefined]; }))
};
}
};
var _hasArgument = function(command) {
return ['init', 'push'].indexOf(command) >= 0;
};
return {
commands: function() {
var cmds = Object.keys(_transitions).slice();
cmds.splice(cmds.indexOf('init'), 1);
return cmds;
},
randomArgs: function(command, size) {
if (_hasArgument(command))
return [comfy.randomInt(0, size)];
else
return [];
},
shrinkArgs: function(command, args) {
if (_hasArgument(command) && args[0] > 0)
return [[args[0] - 1]];
else
return [];
},
apply: function(state, command, args) {
var result =_transitions[command].apply(null, [state].concat(args));
return {
state : result.state,
output: JSON.stringify(result.output)
};
}
};
};
var handler = function(buffer, n) {
var _isResolved = false;
return {
resolve: function(val) {
_isResolved = true;
buffer.push([n, val]);
},
reject: function(err) {
_isResolved = true;
buffer.push([n, err]);
},
isResolved: function() {
return _isResolved;
}
};
};
var implementation = function() {
return {
apply: function(command, args) {
if (command == 'init') {
this._buffer = [];
this._count = 0;
this._channel = chan.chan(args[0]);
} else {
this._buffer.splice(0, this._buffer.length);
if (command != 'close')
this._count += 1;
var h = handler(this._buffer, this._count);
if (command == 'push')
this._channel.requestPush(args[0], h);
else if (command == 'pull')
this._channel.requestPull(h);
else
this._channel.close();
return JSON.stringify(this._buffer);
}
}
};
};
describe('a channel', function() {
it('conforms to the channel model', function() {
expect(implementation()).toConformTo(model());
});
});
| JavaScript | 0 | @@ -4817,16 +4817,21 @@
(model()
+, 500
);%0A %7D);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.