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
|
---|---|---|---|---|---|---|---|
42c255f21b68517c4d274cda9c612ebda26cc953 | revert keep alive config | packages/twig-renderer/twig-renderer.js | packages/twig-renderer/twig-renderer.js | const TwigRenderer = require('@basalt/twig-renderer');
const sleep = require('sleep-promise');
const { getTwigNamespaceConfig } = require('@bolt/build-tools/utils/manifest');
const { getConfig } = require('@bolt/build-tools/utils/config-store');
const path = require('path');
let twigNamespaces;
let twigRenderer;
const STATES = {
NOT_STARTED: 'NOT_STARTED',
STARTING: 'STARTING',
READY: 'READY',
};
let state = STATES.NOT_STARTED;
async function init() {
state = STATES.STARTING;
const config = await getConfig();
const relativeFrom = path.dirname(config.configFileUsed);
// console.log({ config });
twigNamespaces = await getTwigNamespaceConfig(
relativeFrom,
config.extraTwigNamespaces,
);
twigRenderer = new TwigRenderer({
relativeFrom,
src: {
roots: [relativeFrom],
namespaces: TwigRenderer.convertLegacyNamespacesConfig(twigNamespaces),
},
debug: true,
alterTwigEnv: config.alterTwigEnv,
hasExtraInfoInResponses: false, // Will add `info` onto results with a lot of info about Twig Env
maxConcurrency: 50,
keepAlive: config.prod ? true : false, // setting this to true will cause subsequent template / page recompiles to not regenerate when the source files have changed
});
state = STATES.READY;
}
async function prep() {
switch (state) {
case STATES.READY:
return;
case STATES.NOT_STARTED:
return await init();
case STATES.STARTING:
while (state === STATES.STARTING) {
await sleep(20); // eslint-disable-line no-await-in-loop
}
}
}
/**
* Render Twig Template
* @param {string} template - Template name (i.e. `@bolt/button.twig`)
* @param {Object} data - Optional data to pass to template
* @return {Promise<{{ ok: boolean, html: string, message: string}}>} - Results of render
*/
async function render(template, data = {}) {
await prep();
const results = await twigRenderer.render(template, data);
return results;
}
/**
* Render Twig String
* @param {string} templateString - String that is a Twig template (i.e. `<p>{{ text }}</p>`)
* @param {Object} data - Optional data to pass to template
* @return {Promise<{{ ok: boolean, html: string, message: string}}>} - Results of render
*/
async function renderString(templateString, data = {}) {
await prep();
const results = await twigRenderer.renderString(templateString, data);
// console.log({ results });
return results;
}
// Both `render` and `renderString` will return something like this on success:
// {
// ok: true,
// html: '<p>Hello World</p>',
// }
// And something like this on failure:
// {
// ok: false,
// message: 'The confabulator was not configured correctly',
// }
module.exports = {
render,
renderString,
};
| JavaScript | 0.000004 | @@ -1094,29 +1094,8 @@
ive:
- config.prod ? true :
fal
|
f5091923b40a88ed20291b6422231220695f5c98 | clean groups when clearing storage | lib/api/storage.js | lib/api/storage.js | const STORAGE_KEY = `_mimic`;
import Emitter from 'api/emitter';
import EVENTS from 'api/constants/events';
import { migrateData } from 'api/migrations';
import get from 'lodash/get';
import assign from 'lodash/assign';
let AsyncStorage;
let NativeScriptStorage;
if (get(global, 'isReactNative')) {
AsyncStorage = global.AsyncStorage;
}
if (get(global, 'isNativeScript')) {
NativeScriptStorage = global.appSettings;
}
const defaultDataTree = {
version: '2.0.0',
mocks: [],
groups: []
};
let dataTree = assign({}, defaultDataTree);
class PersistentStorageSingleton {
constructor() {
this.appName = ''; // Use empty string to be backwards compatible
}
init() {
this.getRaw()
.then((data) => {
if (!data) {
dataTree = assign({}, defaultDataTree);
this.persist();
}
this._loadFromStorage();
});
}
_loadFromStorage() {
this.getSerialized()
.then((data) => {
assign(dataTree, data);
Emitter.emit(EVENTS.STORAGE_PERSIST);
Emitter.emit(EVENTS.STORAGE_READY);
});
}
persist() {
if (AsyncStorage) {
AsyncStorage.setItem(
this._getStorageKey(),
JSON.stringify(dataTree)
);
} else if (NativeScriptStorage) {
NativeScriptStorage.setString(
this._getStorageKey(),
JSON.stringify(dataTree)
)
} else {
localStorage.setItem(
this._getStorageKey(),
JSON.stringify(dataTree)
);
}
Emitter.emit(EVENTS.STORAGE_PERSIST);
return true;
}
clear() {
assign(dataTree, {
mocks: []
});
this.persist();
}
getRaw() {
return new Promise((resolve, reject) => {
if (AsyncStorage) {
AsyncStorage.getItem(this._getStorageKey())
.then((result) => resolve(result));
} else if (NativeScriptStorage) {
resolve(NativeScriptStorage.getString(this._getStorageKey()));
} else {
resolve(localStorage.getItem(this._getStorageKey()));
}
});
}
getSerialized() {
return this.getRaw()
.then((data) => {
const dataTree = JSON.parse(data);
return migrateData(dataTree);
});
}
_getStorageKey() {
return [STORAGE_KEY, this.appName].join('_')
}
get dataTree() {
return dataTree;
}
getAppName() {
return this.appName;
}
setAppName(appName) {
return this.appName = appName;
}
getVersion() {
return dataTree.version;
}
}
export const PersistentStorage = new PersistentStorageSingleton();
export default PersistentStorage;
| JavaScript | 0 | @@ -1604,16 +1604,34 @@
mocks:
+ %5B%5D,%0A groups:
%5B%5D%0A
|
765e38bb146b47410b39d5b1e35d6488cae0a3fb | Fix deprecation warnings: use OrderedSet#delete instead of OrderedSet#remove | packages/ember-data/lib/system/record_array_manager.js | packages/ember-data/lib/system/record_array_manager.js | /**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var forEach = Ember.EnumerableUtils.forEach;
/**
@class RecordArrayManager
@namespace DS
@private
@extends Ember.Object
*/
DS.RecordArrayManager = Ember.Object.extend({
init: function() {
this.filteredRecordArrays = Ember.MapWithDefault.create({
defaultValue: function() { return []; }
});
this.changedRecords = [];
},
recordDidChange: function(record) {
if (this.changedRecords.push(record) !== 1) { return; }
Ember.run.schedule('actions', this, this.updateRecordArrays);
},
recordArraysForRecord: function(record) {
record._recordArrays = record._recordArrays || Ember.OrderedSet.create();
return record._recordArrays;
},
/**
This method is invoked whenever data is loaded into the store by the
adapter or updated by the adapter, or when a record has changed.
It updates all record arrays that a record belongs to.
To avoid thrashing, it only runs at most once per run loop.
@method updateRecordArrays
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArrays: function() {
forEach(this.changedRecords, function(record) {
if (get(record, 'isDeleted')) {
this._recordWasDeleted(record);
} else {
this._recordWasChanged(record);
}
}, this);
this.changedRecords.length = 0;
},
_recordWasDeleted: function (record) {
var recordArrays = record._recordArrays;
if (!recordArrays) { return; }
forEach(recordArrays, function(array) {
array.removeRecord(record);
});
},
_recordWasChanged: function (record) {
var type = record.constructor,
recordArrays = this.filteredRecordArrays.get(type),
filter;
forEach(recordArrays, function(array) {
filter = get(array, 'filterFunction');
this.updateRecordArray(array, filter, type, record);
}, this);
// loop through all manyArrays containing an unloaded copy of this
// clientId and notify them that the record was loaded.
var manyArrays = record._loadingRecordArrays;
if (manyArrays) {
for (var i=0, l=manyArrays.length; i<l; i++) {
manyArrays[i].loadedRecord();
}
record._loadingRecordArrays = [];
}
},
/**
Update an individual filter.
@method updateRecordArray
@param {DS.FilteredRecordArray} array
@param {Function} filter
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArray: function(array, filter, type, record) {
var shouldBeInArray;
if (!filter) {
shouldBeInArray = true;
} else {
shouldBeInArray = filter(record);
}
var recordArrays = this.recordArraysForRecord(record);
if (shouldBeInArray) {
recordArrays.add(array);
array.addRecord(record);
} else if (!shouldBeInArray) {
recordArrays.remove(array);
array.removeRecord(record);
}
},
/**
This method is invoked if the `filterFunction` property is
changed on a `DS.FilteredRecordArray`.
It essentially re-runs the filter from scratch. This same
method is invoked when the filter is created in th first place.
@method updateFilter
@param array
@param type
@param filter
*/
updateFilter: function(array, type, filter) {
var typeMap = this.store.typeMapFor(type),
records = typeMap.records, record;
for (var i=0, l=records.length; i<l; i++) {
record = records[i];
if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) {
this.updateRecordArray(array, filter, type, record);
}
}
},
/**
Create a `DS.ManyArray` for a type and list of record references, and index
the `ManyArray` under each reference. This allows us to efficiently remove
records from `ManyArray`s when they are deleted.
@method createManyArray
@param {Class} type
@param {Array} references
@return {DS.ManyArray}
*/
createManyArray: function(type, records) {
var manyArray = DS.ManyArray.create({
type: type,
content: records,
store: this.store
});
forEach(records, function(record) {
var arrays = this.recordArraysForRecord(record);
arrays.add(manyArray);
}, this);
return manyArray;
},
/**
Create a `DS.RecordArray` for a type and register it for updates.
@method createRecordArray
@param {Class} type
@return {DS.RecordArray}
*/
createRecordArray: function(type) {
var array = DS.RecordArray.create({
type: type,
content: Ember.A(),
store: this.store,
isLoaded: true
});
this.registerFilteredRecordArray(array, type);
return array;
},
/**
Create a `DS.FilteredRecordArray` for a type and register it for updates.
@method createFilteredRecordArray
@param {Class} type
@param {Function} filter
@return {DS.FilteredRecordArray}
*/
createFilteredRecordArray: function(type, filter) {
var array = DS.FilteredRecordArray.create({
type: type,
content: Ember.A(),
store: this.store,
manager: this,
filterFunction: filter
});
this.registerFilteredRecordArray(array, type, filter);
return array;
},
/**
Create a `DS.AdapterPopulatedRecordArray` for a type with given query.
@method createAdapterPopulatedRecordArray
@param {Class} type
@param {Object} query
@return {DS.AdapterPopulatedRecordArray}
*/
createAdapterPopulatedRecordArray: function(type, query) {
return DS.AdapterPopulatedRecordArray.create({
type: type,
query: query,
content: Ember.A(),
store: this.store
});
},
/**
Register a RecordArray for a given type to be backed by
a filter function. This will cause the array to update
automatically when records of that type change attribute
values or states.
@method registerFilteredRecordArray
@param {DS.RecordArray} array
@param {Class} type
@param {Function} filter
*/
registerFilteredRecordArray: function(array, type, filter) {
var recordArrays = this.filteredRecordArrays.get(type);
recordArrays.push(array);
this.updateFilter(array, type, filter);
},
// Internally, we maintain a map of all unloaded IDs requested by
// a ManyArray. As the adapter loads data into the store, the
// store notifies any interested ManyArrays. When the ManyArray's
// total number of loading records drops to zero, it becomes
// `isLoaded` and fires a `didLoad` event.
registerWaitingRecordArray: function(record, array) {
var loadingRecordArrays = record._loadingRecordArrays || [];
loadingRecordArrays.push(array);
record._loadingRecordArrays = loadingRecordArrays;
}
});
| JavaScript | 0.000421 | @@ -2891,21 +2891,21 @@
dArrays.
-remov
+delet
e(array)
|
176128750d1d19df079aa060efefdbeeb6699988 | Fix first route | lib/application.js | lib/application.js | import React from 'react'
import crossroads from 'crossroads'
import hasher from 'hasher'
import * as actorActions from './actor/actions'
import ActorPage from './actor/components/actor_page.jsx!'
import ActorsPage from './actor/components/actors_page.jsx!'
import NotFoundPage from './core/components/not_found.jsx!'
export function renderToDOM( container ){
crossroads.shouldTypecast = true
crossroads.addRoute('actors', function(){
let element = React.createElement( ActorsPage )
React.render( element, container )
});
crossroads.addRoute('actors/{id}', function(id){
actorActions.loadActor( id )
let element = React.createElement( ActorPage, { actorId: id })
React.render( element, container )
});
crossroads.addRoute('/{path}', function(path){
let element = React.createElement( NotFoundPage )
React.render( element, container )
});
//setup hasher
function parseHash(newHash, oldHash){
crossroads.parse(newHash);
}
hasher.initialized.add(parseHash); //parse initial hash
hasher.changed.add(parseHash); //parse hash changes
hasher.init(); //start listening for history change
}
| JavaScript | 0.9998 | @@ -971,16 +971,200 @@
h);%0A %7D%0A
+ hasher.initialized.add(hash =%3E %7B%0A if (hash == '') %7B%0A // redirect to %22home%22 hash without keeping the empty hash on the history%0A hasher.replaceHash('actors');%0A %7D%0A %7D);%0A
hasher
@@ -1321,10 +1321,12 @@
change%0A
+%0A%0A
%7D%0A
|
a7281a6a44b89458d4a48c97f3e2c23b9b83d8ff | Move callback out to onCreateSessionCollection | app/controllers/experiments/list.js | app/controllers/experiments/list.js | import Ember from 'ember';
let ASC = '';
let DESC = '-';
export default Ember.Controller.extend({
newTitle: '',
isShowingModal: false,
queryParams: ['sort', 'match', 'state', 'q'],
state: 'All',
match: null,
sort: 'title',
sortProperty: Ember.computed('sort', {
get() {
var sort = this.get('sort');
if (sort) {
return sort.replace(DESC, '');
}
else {
return null;
}
},
set (_, value) {
var sort = this.get('sort');
if (sort) {
var sign = sort.indexOf(DESC) === 0 ? DESC : ASC;
this.set('sort', `${sign}${value}`);
}
else {
this.set('sort', `${ASC}${value}`);
}
return value;
}
}),
sortOrder: Ember.computed('sort', {
get() {
var sort = this.get('sort');
if (sort) {
return sort.indexOf(DESC) === 0 ? DESC : ASC;
}
else {
return null;
}
},
set (_, value) {
var sort = this.get('sort');
if (sort) {
var prop = sort.replace(DESC, '');
this.set('sort', `${value}${prop}`);
}
else {
this.set('sort', `${value}title`);
}
return value;
}
}),
toggleOrder: function(order) {
if (order === ASC) {
this.set('sortOrder', DESC);
} else {
this.set('sortOrder', ASC);
}
},
activeButtons: ['Active', 'Draft', 'Archived', 'All'],
actions: {
selectStatusFilter: function(status) {
this.set('state', status);
this.set('sortProperty', 'title');
this.set('sortOrder', ASC);
},
sortingMethod: function(sortProperty) {
if (Ember.isEqual(this.get('sortProperty'), sortProperty)) {
this.toggleOrder(this.get('sortOrder'));
} else {
this.set('sortOrder', ASC);
}
this.set('sortProperty', sortProperty);
},
resetParams: function() {
this.set('state', null);
this.set('match', null);
this.set('sortProperty', 'title');
this.set('sortOrder', ASC);
},
updateSearch: function(value) {
this.set('match', `${value}*`);
this.set('sortProperty', null);
},
toggleModal: function() {
this.set('newTitle', '');
this.toggleProperty('isShowingModal');
},
createExperiment: function() {
var newExperiment = this.store.createRecord('experiment', {
// should work after split bug is fixed and schema validation handles null values
// for structure, beginDate, endDate, and eligibilityCriteria
title: this.get('newTitle'),
description: 'Give your experiment a description here...', // TODO: Hardcoded parameter
state: 'Draft',
lastEdited: new Date(),
purpose: '',
duration: '',
exitUrl: '',
structure: {
frames: {},
sequence: []
}
});
newExperiment.save();
newExperiment.on('didCreate', () => {
var callback = () => {
this.send('toggleModal');
this.transitionToRoute('experiments.info', newExperiment.id);
};
if (newExperiment.get('_sessionCollection.isNew')) {
newExperiment.get('_sessionCollection').on('didCreate', callback);
}
else {
callback();
}
});
}
}
});
| JavaScript | 0 | @@ -3435,108 +3435,37 @@
-newExperiment.save();%0A newExperiment.on('didCreate', () =%3E %7B%0A var callback
+var onCreateSessionCollection
= (
@@ -3471,20 +3471,16 @@
() =%3E %7B%0A
-
@@ -3509,28 +3509,24 @@
gleModal');%0A
-
@@ -3607,14 +3607,60 @@
+%7D;%0A
-%7D;
+ newExperiment.on('didCreate', () =%3E %7B
%0A%0A
@@ -3802,24 +3802,41 @@
reate',
-callback
+onCreateSessionCollection
);%0A
@@ -3895,16 +3895,33 @@
-callback
+onCreateSessionCollection
();%0A
@@ -3946,32 +3946,66 @@
%7D);%0A
+ newExperiment.save();%0A
%7D%0A %7D%0A
|
b7bcd81d6e3e3bb1b72f7a3895ad27ff280ae4e0 | update NavMenuItem | examples/containers/app/navMenu/NavMenuItem.js | examples/containers/app/navMenu/NavMenuItem.js | import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import TouchRipple from 'src/TouchRipple';
export default class NavMenuItem extends Component {
constructor(props) {
super(props);
this.menuHeight = 50;
this.subMenuIndent = 20;
this.menuGroupMousedownHandle = this::this.menuGroupMousedownHandle;
this.menuMousedownHandle = this::this.menuMousedownHandle;
}
menuGroupMousedownHandle() {
const {expandMenuName, options, expandMenu} = this.props;
if (expandMenuName === options.text) {
expandMenu('');
} else {
expandMenu(options.text);
}
}
menuMousedownHandle() {
const {options, depth, expandMenu, updateActivatedMenu} = this.props;
depth === 0 && expandMenu('');
updateActivatedMenu(options);
}
render() {
const {expandMenuName, activatedMenu, options, depth, expandMenu, updateActivatedMenu} = this.props;
const {menuHeight, subMenuIndent} = this;
const collapsed = expandMenuName !== options.text,
hasChildren = options.children && options.children.length > 0;
return (
<div className={`nav-menu-item ${collapsed ? 'collapsed' : ''} ${hasChildren ? 'hasChildren' : ''}`}>
{/* title or link */}
{
hasChildren ?
(
<div className="nav-menu-item-title"
disabled={options.disabled}
onMouseDown={this.menuGroupMousedownHandle}>
<div className="nav-menu-item-name">
{options.text}
</div>
<i className={`fa fa-angle-down nav-menu-item-collapse-button
${collapsed ? 'collapsed' : ''}`}
aria-hidden="true"></i>
<TouchRipple/>
</div>
)
:
(
<Link
className={'nav-menu-item-link' + (activatedMenu && activatedMenu.route === options.route ? ' router-link-active' : '')}
to={options.route}
disabled={options.disabled}
onClick={this.menuMousedownHandle}>
<div className="nav-menu-item-name"
style={{marginLeft: depth * subMenuIndent}}>
{options.text}
</div>
<TouchRipple/>
</Link>
)
}
{/* sub menu */}
{
hasChildren
? (
<div className="nav-menu-children"
style={{height: options.children.length * menuHeight}}>
{
options.children.map((item, index) => {
return (
<NavMenuItem key={index}
expandMenuName={expandMenuName}
activatedMenu={activatedMenu}
options={item}
depth={depth + 1}
expandMenu={expandMenu}
updateActivatedMenu={updateActivatedMenu}/>
);
})
}
</div>
)
: null
}
</div>
);
}
}
NavMenuItem.propTypes = {
expandMenuName: PropTypes.string,
activatedMenu: PropTypes.object,
options: PropTypes.object,
depth: PropTypes.number,
expandMenu: PropTypes.func,
updateActivatedMenu: PropTypes.func
};
NavMenuItem.defaultProps = {
expandMenuName: '',
activatedMenu: null,
options: null,
depth: 0
}; | JavaScript | 0 | @@ -157,23 +157,8 @@
';%0A%0A
-export default
clas
@@ -4553,12 +4553,41 @@
depth: 0%0A%0A%7D;
+%0A%0Aexport default NavMenuItem;
|
af5e495a6a7fb06444faa8580346463b03af3b93 | Add prevent prop type warning | src/widgets/SensorHeader/LastSensorDownload.js | src/widgets/SensorHeader/LastSensorDownload.js | import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as Animatable from 'react-native-animatable';
import moment from 'moment';
import { useIntervalReRender } from '../../hooks';
import { TextWithIcon } from '../Typography/index';
import { MILLISECONDS } from '../../utilities/index';
import { WifiIcon, WifiOffIcon } from '../icons';
import { MISTY_CHARCOAL } from '../../globalStyles/index';
import {
selectIsDownloading,
selectLastDownloadFailed,
selectLastDownloadStatus,
selectLastDownloadTime,
} from '../../selectors/Bluetooth/sensorDownload';
import { vaccineStrings, generalStrings } from '../../localization';
import { selectSensorByMac } from '../../selectors/Entities/sensor';
const formatErrorMessage = status => vaccineStrings[status];
const formatLastSyncDate = date => (date ? moment(date).fromNow() : generalStrings.not_available);
const formatLogDelay = delay =>
`${vaccineStrings.logging_delayed_until}: ${moment(delay).format('HH:mm:ss')}`;
const getText = (isPaused, isDelayed, logDelay, lastDownloadTime, lastDownloadStatus) => {
if (lastDownloadStatus && lastDownloadStatus !== 'OK') {
return formatErrorMessage(lastDownloadStatus);
}
if (isPaused) {
return vaccineStrings.is_paused;
}
if (isDelayed) {
return formatLogDelay(logDelay);
}
return formatLastSyncDate(lastDownloadTime);
};
export const LastSensorDownloadComponent = ({
isDownloading,
isPaused,
lastDownloadFailed,
lastDownloadTime,
logDelay,
lastDownloadStatus,
}) => {
useIntervalReRender(MILLISECONDS.TEN_SECONDS);
const timeNow = new Date().getTime();
const isDelayed = logDelay > timeNow;
const wifiRef = useRef();
useEffect(() => {
if (isDownloading) wifiRef?.current.flash(MILLISECONDS.ONE_SECOND);
else wifiRef?.current?.stopAnimation();
}, [isDownloading, wifiRef]);
return (
<Animatable.View
ref={wifiRef}
animation="flash"
easing="ease-out"
iterationCount="infinite"
style={{ justifyContent: 'center' }}
>
<TextWithIcon
containerStyle={{ paddingHorizontal: 8 }}
margin={0}
size="s"
Icon={
lastDownloadFailed || isDelayed || isPaused ? (
<WifiOffIcon size={20} color={MISTY_CHARCOAL} />
) : (
<WifiIcon size={20} color={MISTY_CHARCOAL} />
)
}
>
{getText(isPaused, isDelayed, logDelay, lastDownloadTime, lastDownloadStatus)}
</TextWithIcon>
</Animatable.View>
);
};
LastSensorDownloadComponent.defaultProps = {
lastDownloadTime: null,
logDelay: 0,
lastDownloadStatus: '',
};
LastSensorDownloadComponent.propTypes = {
isDownloading: PropTypes.bool.isRequired,
isPaused: PropTypes.bool.isRequired,
lastDownloadFailed: PropTypes.bool.isRequired,
lastDownloadTime: PropTypes.instanceOf(Date),
logDelay: PropTypes.number,
lastDownloadStatus: PropTypes.string,
};
const stateToProps = (state, props) => {
const { macAddress } = props;
const lastDownloadTime = selectLastDownloadTime(state, macAddress);
const lastDownloadFailed = selectLastDownloadFailed(state, macAddress);
const isDownloading = selectIsDownloading(state, macAddress);
const sensor = selectSensorByMac(state, macAddress);
const { isPaused = false, logDelay } = sensor ?? {};
const lastDownloadStatus = selectLastDownloadStatus(state, macAddress);
return {
lastDownloadTime,
lastDownloadFailed,
lastDownloadStatus,
isDownloading,
logDelay,
isPaused,
};
};
export const LastSensorDownload = connect(stateToProps)(LastSensorDownloadComponent);
| JavaScript | 0 | @@ -832,16 +832,22 @@
%5Bstatus%5D
+ ?? ''
;%0Aconst
|
8c9ffb3ff1321ccea648fe1ebf2c8e8246456758 | Test error function | test/CLI.js | test/CLI.js | var should = require('should'),
stream = require('stream'),
CLI = require('../lib/CLI.js');
//not exactly cool tests.. but still..
describe('CLI Tool', function () {
var optimist = {}, argv = {},
_log, _error;
beforeEach(function () {
optimist = {};
argv = {};
_log = console.log;
_error = console.error;
});
afterEach(function () {
console.log = _log;
console.error = _error;
});
it('should call showHelp if -h is passed', function (done) {
argv = { h : true, help : true };
optimist.showHelp = done;
new CLI(argv, optimist);
});
it('should use stdin and stdout for input/output if files are not provided', function () {
var cli = new CLI(argv, optimist);
should(cli).have.property('in', process.stdin);
should(cli).have.property('out', process.stdout);
});
it('should call list if -l is passed', function (done) {
var _list = CLI.prototype.list, cli;
argv = { list : true };
CLI.prototype.list = function () {
done();
};
cli = new CLI(argv, optimist);
CLI.prototype.list = _list;
});
it('should return error if file not found', function (done) {
argv = { file : 'filethat!@#$%\n^CantExist' };
CLI.prototype.error = function (error) {
var notFoundExp = /not found/
notFoundExp.test(error).should.equal(true);
done();
};
var cli = new CLI(argv, optimist);
});
it('should return error if output file exists', function (done) {
argv = { output : 'test/file' };
CLI.prototype.error = function (error) {
var fileExistsExp = /already exists/
fileExistsExp.test(error).should.equal(true);
done();
};
var cli = new CLI(argv, optimist);
});
it('should have in parameter as ReadableStream', function () {
argv = { file : 'test/file', depth : 0 };
var cli = new CLI(argv, optimist);
should(cli).have.property('in').and.be.an.instanceOf(stream.Readable);
});
it('should fail if output file can\'t be created', function (done) {
CLI.prototype.error = function (error) {
error.match('Could not write to file').should.be.an.instanceOf(Array);
done();
};
argv = { output : 'nosuchDir/file' };
new CLI(argv, optimist);
});
});
| JavaScript | 0.000002 | @@ -219,18 +219,113 @@
, _error
+, CLI_error;%0A%0A _log = console.log;%0A _error = console.error;%0A CLI_error = CLI.prototype.error
;%0A
-
%0A befor
@@ -382,60 +382,8 @@
%7B%7D;%0A
- _log = console.log;%0A _error = console.error;%0A
%7D)
@@ -435,16 +435,16 @@
= _log;%0A
-
cons
@@ -463,16 +463,53 @@
_error;%0A
+ CLI.prototype.error = CLI_error;%0A
%7D);%0A%0A
@@ -2343,13 +2343,392 @@
);%0A %7D);
+%0A%0A it('should exit process if error occurs', function (done) %7B%0A var _exit = process.exit,%0A errStr = 'error',%0A errCode = 1;%0A%0A console.error = function () %7B%7D;%0A process.exit = function (ecode) %7B%0A if (errCode === ecode) %7B%0A done();%0A %7D%0A %7D;%0A%0A var cli = new CLI(argv, optimist);%0A cli.error(errStr, errCode);%0A%0A process.exit = _exit;%0A %7D);
%0A%7D);%0A
|
9dba3d4ce27b0e4dfc806a3af4a5b73252733d63 | Change .local(...) to .local[...] | lib/apps/person.js | lib/apps/person.js | "use strict";
var generic_document_app = require('./generic_document'),
_ = require('underscore');
module.exports = function () {
var opts = {
model_name: 'Person',
template_dir: 'person',
template_object_name: 'person',
template_objects_name: 'people',
url_root: '/person',
};
var app = generic_document_app(opts);
app.routes.get = _.reject(
app.routes.get,
function (route) { return route.path === '/:slug'; }
);
app.get(
'/:slug',
function (req, res, next) {
res
.local(opts.template_object_name)
.find_positions()
.populate('organisation')
.exec(function(err, positions) {
res.locals.positions = positions;
next(err);
});
},
function(req,res) {
res.render( opts.template_dir + '/view' );
}
);
return app;
};
| JavaScript | 0.000001 | @@ -603,17 +603,18 @@
.local
-(
+s%5B
opts.tem
@@ -630,17 +630,17 @@
ect_name
-)
+%5D
%0A
|
881c8f1dd01d2a4f0213f842134c7c6052867834 | Add unit tests for User model comparePassword | server/tests/user.model.js | server/tests/user.model.js | 'use strict';
var should = require('should');
var User = require('mongoose').model('User');
var user, user2;
describe('User Model Unit Tests:', function() {
before(function(done) {
user = new User({
email: 'test@test.com',
password: 'password',
});
user2 = new User({
email: 'test@test.com',
password: 'password',
});
done();
});
describe('Method Save', function() {
it('should begin with no users', function(done) {
User.find({}, function(err, users) {
users.should.have.length(0);
done();
});
});
it('should be able to save without problems', function(done) {
user.save(done);
});
it('should fail to save an existing user again', function(done) {
user.save();
return user2.save(function(err) {
should.exist(err);
done();
});
});
});
after(function(done) {
User.remove().exec();
done();
});
});
| JavaScript | 0 | @@ -666,17 +666,670 @@
ser.
-save(done
+password.should.equal('password');%0A user.save(function () %7B%0A user.password.should.not.equal('password'); // Password hashed now%0A done();%0A %7D);%0A %7D);%0A%0A it('should return error on incorrect password', function(done) %7B%0A user.comparePassword('incorrect', function (err, isMatch) %7B%0A (err === null).should.equal(true);%0A isMatch.should.equal(false);%0A done();%0A %7D);%0A %7D);%0A%0A it('should return success on correct password', function(done) %7B%0A user.comparePassword('password', function (err, isMatch) %7B%0A (err === null).should.equal(true);%0A isMatch.should.equal(true);%0A done();%0A %7D
);%0A
|
c7a46d887c5b10314543cf4a597bd6a1bae43aba | fix webpack build script | build/webpack.config.js | build/webpack.config.js | var path = require('path');
var webpack = require('webpack');
var config = {
entry: {
bundle: path.resolve(__dirname, '../src/index.js')
},
output: {
path: path.resolve(__dirname, '../dist'),
filename: 'index.js'
},
module: {
loaders: [{
test: /\.js?$/,
loaders: ['babel-loader'],
exclude: /node_modules/
}]
},
target: 'web',
devtool: 'source-map',
plugins: [],
resolve: {
extensions: ['.js'],
alias: {
}
}
}
module.exports = config;
| JavaScript | 0.000001 | @@ -310,9 +310,8 @@
%5C.js
-?
$/,%0A
|
1169d360a7402695911dfd630aaaf486b169843e | allow output split to existing folders | program.js | program.js | #!/usr/bin/env node
var csv = require('fast-csv');
var fs = require('fs');
var options = require('commander');
var grouper = require('./lib/grouper');
var geocoder = require('./lib/geocoder');
var streamSplitter = require('./lib/streamSplitter');
var through2 = require('through2');
var package = JSON.parse(fs.readFileSync(__dirname+'/package.json', 'utf8'));
options
.version(package.version)
.option('-i, --input [file]', 'Input (csv file) [stdin]', '-')
.option('-o, --output [file]', 'Output (csv file) [stdout]', '-')
.option('-s, --street-col [col]', 'Street col [street]', 'street')
.option('-z, --zipcode-col [col]', 'Zipcode col [zipcode]', 'zipcode')
.option('-c, --city-col [col]', 'City col [city]', 'city')
.option('-S, --state-col [col]', 'State col [state]', 'state') // short forms are dumb
.option('-d, --delimiter [symbol]', 'CSV delimiter in input file', ',')
.option('-O, --output-split [column]', 'Write to multiple files divided by column', '')
.option('-a, --auth-id [id]', 'SmartyStreets auth id [environment variable smartystreets_auth_id]', process.env.SMARTYSTREETS_AUTH_ID)
.option('-A, --auth-token [token]', 'SmartyStreets auth token [environment variable smartystreets_auth_token]', process.env.SMARTYSTREETS_AUTH_TOKEN)
.option('-j, --concurrency [jobs]', 'Maximum number of concurrent requests [48]', 48)
.option('-✈, --column-definition [mode]', 'Column definition mode or file [standard]', 'standard')
.option('-p, --column-prefix [text]', 'Prefix for smartystreets columns in the output file [ss_]', 'ss_')
.option('-x, --column-suffix [text]', 'Suffix for smartystreets columns in the output file', '')
.option('-q, --quiet', 'Quiet mode - turn off progress messages')
.option('-l, --log-interval [num]', 'Show progress after every X number of rows [1000]', 1000)
.parse(process.argv);
options.concurrency = parseInt(options.concurrency);
if (!options.concurrency) {
console.error('Invalid concurrency');
options.help();
}
if (!options.authId) {
console.error('Please specify a SmartyStreets auth id');
options.help();
}
if (!options.authToken) {
console.error('Please specify a SmartyStreets auth token');
options.help();
}
if (!options.input) {
console.error('Please specify an input file');
options.help();
}
if (!options.output) {
console.error('Please specify an input file');
options.help();
}
var columnModes = ['mail', 'standard', 'complete'];
if (columnModes.indexOf(options.columnDefinition) != -1) {
//modes are in structure/mode.json
options.structure = JSON.parse( fs.readFileSync(__dirname+'/structure/'+options.columnDefinition+'.json', 'utf8') );
} else if (options.columnDefinition.substr(0, 1) == '{') {
//it's a JSON object
options.structure = JSON.parse(options.columnDefinition);
} else {
//it's a JSON file
options.structure = JSON.parse( fs.readFileSync(options.columnDefinition, 'utf8') );
}
var readStream = options.input == '-' ? process.stdin : fs.createReadStream(options.input);
var writeStream;
if (options.outputSplit) {
fs.mkdirSync(options.output);
var firstRow = true, rowIndex, headers;
writeStream = streamSplitter(function(row){
if (firstRow) {
firstRow = false;
rowIndex = row.indexOf(options.outputSplit);
headers = row;
if (rowIndex == -1) {
console.error('couldn\'t find column', options.outputSplit, 'in', row);
process.exit();
}
return false;
}
return row[rowIndex];
}, function(streamName){
var source = csv.createWriteStream();
source.write(headers);
source.pipe( fs.createWriteStream(options.output+'/'+streamName+'.csv') );
return source;
}, {objectMode: true});
} else if (options.output == '-') {
writeStream = csv.createWriteStream();
writeStream.pipe( process.stdout );
} else {
writeStream = csv.createWriteStream();
writeStream.pipe( fs.createWriteStream(options.output+'/'+streamName+'.csv') );
}
readStream.pipe(csv({headers: true, delimiter: options.delimiter}))
.pipe(grouper(70))
.pipe(geocoder(options))
.pipe(writeStream); | JavaScript | 0.000002 | @@ -3063,16 +3063,26 @@
plit) %7B%0A
+ try %7B%0A
fs.mkd
@@ -3104,16 +3104,74 @@
output);
+%0A %7D catch(e) %7B%0A if ( e.code != 'EEXIST' ) throw e;%0A %7D
%0A%0A var
|
70fa8b902bc6023665603f90bc892fe0dc1d9564 | Refactor tests | test/api.js | test/api.js | 'use strict';
/* eslint-env mocha */
var ejsLint = require('../index.js');
var packageJSON = require('../package.json');
var readFile = require('fs').readFileSync;
var path = require('path');
var assert = require('assert');
function fixture(name){
return readFile(path.join('test/fixtures/', name)).toString();
}
// ******************************** //
suite('ejs-lint', function(){
test('empty string', function(){
assert.equal(ejsLint(''), undefined);
});
test('text', function(){
assert.equal(ejsLint('abc'), undefined);
});
test('valid scriptlet', function(){
assert.equal(ejsLint('<% foo(); %>'), undefined);
});
test('old-style include', function(){
assert.equal(ejsLint('<% include foo.ejs %>'), undefined);
});
test('valid multi-line file', function(){
assert.equal(ejsLint(fixture('valid.ejs')), undefined);
});
test('invalid multi-line file', function(){
var err = ejsLint(fixture('invalid.ejs'));
assert.equal(err.line, 3);
assert.equal(err.column, 4);
assert.equal(err.message, 'Unexpected token');
});
test('EJSLint.lint() is an alias', function(){
assert.equal(ejsLint, ejsLint.lint);
});
});
suite('misc.', function(){
test('EJS version is pinned', function(){
assert.equal(packageJSON.dependencies.ejs.search(/[\^~<=>]/), -1);
});
});
| JavaScript | 0.000001 | @@ -30,19 +30,21 @@
ocha */%0A
-var
+const
ejsLint
@@ -74,23 +74,17 @@
');%0A
-var packageJSON
+const pkg
= r
@@ -110,19 +110,21 @@
json');%0A
-var
+const
readFil
@@ -155,19 +155,21 @@
leSync;%0A
-var
+const
path =
@@ -185,19 +185,21 @@
path');%0A
-var
+const
assert
@@ -219,16 +219,17 @@
sert');%0A
+%0A
function
@@ -242,16 +242,17 @@
re(name)
+
%7B%0A retu
@@ -316,46 +316,8 @@
;%0A%7D%0A
-// ******************************** //
%0Asui
@@ -327,34 +327,30 @@
'ejs-lint',
-function()
+() =%3E
%7B%0A test('em
@@ -362,26 +362,22 @@
tring',
-function()
+() =%3E
%7B%0A as
@@ -398,27 +398,16 @@
Lint('')
-, undefined
);%0A %7D);
@@ -399,32 +399,33 @@
int(''));%0A %7D);%0A
+%0A
test('text', f
@@ -419,34 +419,30 @@
est('text',
-function()
+() =%3E
%7B%0A assert
@@ -462,27 +462,16 @@
t('abc')
-, undefined
);%0A %7D);
@@ -463,32 +463,33 @@
('abc'));%0A %7D);%0A
+%0A
test('valid sc
@@ -498,26 +498,22 @@
ptlet',
-function()
+() =%3E
%7B%0A as
@@ -542,35 +542,24 @@
foo(); %25%3E')
-, undefined
);%0A %7D);%0A t
@@ -547,32 +547,33 @@
); %25%3E'));%0A %7D);%0A
+%0A
test('old-styl
@@ -580,34 +580,30 @@
e include',
-function()
+() =%3E
%7B%0A assert
@@ -641,27 +641,16 @@
ejs %25%3E')
-, undefined
);%0A %7D);
@@ -642,32 +642,33 @@
js %25%3E'));%0A %7D);%0A
+%0A
test('valid mu
@@ -679,34 +679,30 @@
line file',
-function()
+() =%3E
%7B%0A assert
@@ -741,19 +741,8 @@
s'))
-, undefined
);%0A
@@ -738,32 +738,33 @@
.ejs')));%0A %7D);%0A
+%0A
test('invalid
@@ -781,26 +781,22 @@
file',
-function()
+() =%3E
%7B%0A va
@@ -957,16 +957,17 @@
;%0A %7D);%0A
+%0A
test('
@@ -995,26 +995,22 @@
alias',
-function()
+() =%3E
%7B%0A as
@@ -1054,16 +1054,17 @@
%7D);%0A%7D);%0A
+%0A
suite('m
@@ -1070,26 +1070,22 @@
misc.',
-function()
+() =%3E
%7B%0A test
@@ -1114,18 +1114,14 @@
d',
-function()
+() =%3E
%7B%0A
@@ -1140,18 +1140,10 @@
al(p
-ackageJSON
+kg
.dep
|
df29001d792171b55d2ff2dae5023dfd67ad8c5b | Migrate Tooltip to be a ref forwarder | src/Tooltip.js | src/Tooltip.js | import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import isRequiredForA11y from 'prop-types-extra/lib/isRequiredForA11y';
import { createBootstrapComponent } from './ThemeProvider';
const propTypes = {
/**
* @default 'tooltip'
*/
bsPrefix: PropTypes.string,
/**
* An html id attribute, necessary for accessibility
* @type {string|number}
* @required
*/
id: isRequiredForA11y(
PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
),
/**
* Sets the direction the Tooltip is positioned towards.
*
* > This is generally provided by the `Overlay` component positioning the tooltip
*/
placement: PropTypes.oneOf([
'auto-start',
'auto',
'auto-end',
'top-start',
'top',
'top-end',
'right-start',
'right',
'right-end',
'bottom-end',
'bottom',
'bottom-start',
'left-end',
'left',
'left-start',
]),
/**
* An Overlay injected set of props for positioning the tooltip arrow.
*
* > This is generally provided by the `Overlay` component positioning the tooltip
*
* @type {{ ref: ReactRef, style: Object }}
*/
arrowProps: PropTypes.shape({
ref: PropTypes.any,
style: PropTypes.object,
}),
/** @private */
innerRef: PropTypes.any,
/** @private */
scheduleUpdate: PropTypes.func,
/** @private */
outOfBoundaries: PropTypes.any,
};
const defaultProps = {
placement: 'right',
};
function Tooltip({
bsPrefix,
innerRef,
placement,
className,
style,
children,
arrowProps,
scheduleUpdate: _,
outOfBoundaries: _1,
...props
}) {
return (
<div
ref={innerRef}
style={style}
role="tooltip"
x-placement={placement}
className={classNames(className, bsPrefix, `bs-tooltip-${placement}`)}
{...props}
>
<div className="arrow" {...arrowProps} />
<div className={`${bsPrefix}-inner`}>{children}</div>
</div>
);
}
Tooltip.propTypes = propTypes;
Tooltip.defaultProps = defaultProps;
export default createBootstrapComponent(Tooltip, 'tooltip');
| JavaScript | 0 | @@ -174,21 +174,18 @@
mport %7B
-creat
+us
eBootstr
@@ -186,25 +186,22 @@
ootstrap
-Component
+Prefix
%7D from
@@ -1267,54 +1267,8 @@
),%0A%0A
- /** @private */%0A innerRef: PropTypes.any,%0A%0A
/*
@@ -1315,16 +1315,16 @@
s.func,%0A
+
%0A /** @
@@ -1425,27 +1425,56 @@
%7D;%0A%0A
-function Tooltip(%7B%0A
+const Tooltip = React.forwardRef(%0A (%0A %7B%0A
bs
@@ -1487,18 +1487,10 @@
,%0A
-innerRef,%0A
+
pl
@@ -1498,16 +1498,20 @@
cement,%0A
+
classN
@@ -1515,16 +1515,20 @@
ssName,%0A
+
style,
@@ -1528,16 +1528,20 @@
style,%0A
+
childr
@@ -1544,16 +1544,20 @@
ildren,%0A
+
arrowP
@@ -1562,16 +1562,20 @@
wProps,%0A
+
schedu
@@ -1587,16 +1587,20 @@
ate: _,%0A
+
outOfB
@@ -1614,16 +1614,20 @@
es: _1,%0A
+
...pro
@@ -1633,13 +1633,92 @@
ops%0A
-%7D) %7B%0A
+ %7D,%0A ref,%0A ) =%3E %7B%0A bsPrefix = useBootstrapPrefix(bsPrefix, 'tooltip');%0A%0A
re
@@ -1724,16 +1724,18 @@
eturn (%0A
+
%3Cdiv
@@ -1745,23 +1745,22 @@
+
ref=%7B
-innerR
+r
ef%7D%0A
+
@@ -1781,16 +1781,18 @@
%7D%0A
+
role=%22to
@@ -1798,16 +1798,18 @@
ooltip%22%0A
+
x-
@@ -1830,16 +1830,18 @@
cement%7D%0A
+
cl
@@ -1915,16 +1915,18 @@
%7D%0A
+
%7B...prop
@@ -1932,18 +1932,22 @@
ps%7D%0A
-%3E%0A
+ %3E%0A
%3Cd
@@ -1988,24 +1988,26 @@
s%7D /%3E%0A
+
%3Cdiv classNa
@@ -2056,21 +2056,31 @@
+
%3C/div%3E%0A
+
);%0A
-%7D
+ %7D,%0A);
%0A%0ATo
@@ -2165,50 +2165,13 @@
ult
-createBootstrapComponent(Tooltip, 'tooltip')
+Tooltip
;%0A
|
28ed37c8c27064be34e7ce157da462e3cf7e9e98 | Use requestAnimationFrame instead of setInterval for animate() | src/engine-refactor/adamengine/adamengine-dev.js | src/engine-refactor/adamengine/adamengine-dev.js | var body = document.querySelector('body');
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
body.appendChild(canvas);
var assets = [
'/img/robowalk/robowalk00.png',
'/img/robowalk/robowalk01.png',
'/img/robowalk/robowalk02.png',
'/img/robowalk/robowalk03.png',
'/img/robowalk/robowalk04.png',
'/img/robowalk/robowalk05.png',
'/img/robowalk/robowalk06.png',
'/img/robowalk/robowalk07.png',
'/img/robowalk/robowalk08.png',
'/img/robowalk/robowalk09.png',
'/img/robowalk/robowalk10.png',
'/img/robowalk/robowalk11.png',
'/img/robowalk/robowalk12.png',
'/img/robowalk/robowalk13.png',
'/img/robowalk/robowalk14.png',
'/img/robowalk/robowalk15.png',
'/img/robowalk/robowalk16.png',
'/img/robowalk/robowalk17.png',
'/img/robowalk/robowalk18.png'
];
var frames = [];
var currFrame = 0;
for(var i=0; i < assets.length; ++i) {
var newImg = new Image();
newImg.onload = function() {
console.log('image loaded');
};
newImg.src = assets[i];
frames[i] = newImg;
}
var animate = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(frames[currFrame], 100, 100);
currFrame = (currFrame + 1) % frames.length;
}
setInterval(animate, 1000/30); | JavaScript | 0 | @@ -1222,37 +1222,71 @@
th;%0A
-%7D%0A%0AsetInterval(animate, 1000/30
+%09requestAnimationFrame(animate);%0A%7D%0A%0ArequestAnimationFrame(animate
);
|
8cde95fd951fe5792d2751a9f6f6c65746a7da23 | Move hide-show instantiation until after the table has been initialised. | app/extensions/views/graph/table.js | app/extensions/views/graph/table.js | define([
'extensions/views/table',
'extensions/views/hideShow'
],
function (Table, HideShow) {
return Table.extend({
initialize: function () {
if (this.collection.options.axes) {
this.$toggleContainer = $('<div>', {'class': 'table-toggle'});
Table.prototype.initialize.apply(this, arguments);
this.toggleTable = new HideShow({
$reveal: this.$table,
$el: this.$toggleContainer,
showLabel: 'Show the data for this graph.',
hideLabel: 'Hide the data for this graph.'
});
}
},
prepareTable: function () {
if (this.collection.options.axes) {
this.$table = $('<table/>');
this.$table.appendTo(this.$toggleContainer);
this.$toggleContainer.insertAfter(this.$el);
}
}
});
});
| JavaScript | 0 | @@ -330,462 +330,462 @@
- this.toggleTable = new HideShow(%7B%0A $reveal: this.$table,%0A $el: this.$toggleContainer,%0A showLabel: 'Show the data for this graph.',%0A hideLabel: 'Hide the data for this graph.'%0A %7D);%0A %7D%0A %7D,%0A prepareTable: function () %7B%0A if (this.collection.options.axes) %7B%0A this.$table = $('%3Ctable/%3E');%0A this.$table.appendTo(this.$toggleContainer);%0A this.$toggleContainer.insertAfter(this.$el
+%7D%0A %7D,%0A prepareTable: function () %7B%0A if (this.collection.options.axes) %7B%0A this.$table = $('%3Ctable/%3E');%0A this.$table.appendTo(this.$toggleContainer);%0A this.$toggleContainer.insertAfter(this.$el);%0A this.toggleTable = new HideShow(%7B%0A $reveal: this.$table,%0A $el: this.$toggleContainer,%0A showLabel: 'Show the data for this graph.',%0A hideLabel: 'Hide the data for this graph.'%0A %7D
);%0A
|
aecfc968bd3f8f2447631398ee9b9f4f1a8f4dbc | Fix asynchronous logging of users | src/containers/authenticated/exercise/audience/UserPopover.js | src/containers/authenticated/exercise/audience/UserPopover.js | import React, {PropTypes, Component} from 'react';
import {connect} from 'react-redux';
import R from 'ramda'
import * as Constants from '../../../../constants/ComponentTypes'
import {Popover} from '../../../../components/Popover';
import {Menu} from '../../../../components/Menu'
import {Dialog} from '../../../../components/Dialog'
import {IconButton, FlatButton} from '../../../../components/Button'
import {Icon} from '../../../../components/Icon'
import {MenuItemLink, MenuItemButton} from "../../../../components/menu/MenuItem"
import {updateUser} from '../../../../actions/User'
import {updateAudience} from '../../../../actions/Audience'
import UserForm from '../../admin/users/UserForm'
const style = {
position: 'absolute',
top: '7px',
right: 0,
}
class UserPopover extends Component {
constructor(props) {
super(props);
this.state = {
openDelete: false,
openEdit: false,
openPopover: false
}
}
handlePopoverOpen(event) {
event.preventDefault()
this.setState({
openPopover: true,
anchorEl: event.currentTarget,
})
}
handlePopoverClose() {
this.setState({openPopover: false})
}
handleOpenEdit() {
this.setState({openEdit: true})
this.handlePopoverClose()
}
handleCloseEdit() {
this.setState({openEdit: false})
}
onSubmitEdit(data) {
return this.props.updateUser(this.props.user.user_id, data)
}
submitFormEdit() {
this.refs.userForm.submit()
}
handleOpenDelete() {
this.setState({openDelete: true})
this.handlePopoverClose()
}
handleCloseDelete() {
this.setState({openDelete: false})
}
submitDelete() {
const user_ids = R.pipe(
R.values,
R.filter(a => a.user_id !== this.props.user.user_id),
R.map(u => u.user_id)
)(this.props.audience.audience_users)
this.props.updateAudience(this.props.exerciseId, this.props.audience.audience_id, {audience_users: user_ids})
this.handleCloseDelete()
}
render() {
const editActions = [
<FlatButton label="Cancel" primary={true} onTouchTap={this.handleCloseEdit.bind(this)}/>,
<FlatButton label="Update" primary={true} onTouchTap={this.submitFormEdit.bind(this)}/>,
];
const deleteActions = [
<FlatButton label="Cancel" primary={true} onTouchTap={this.handleCloseDelete.bind(this)}/>,
<FlatButton label="Delete" primary={true} onTouchTap={this.submitDelete.bind(this)}/>,
];
let organization_name = R.pathOr('-', [this.props.user.user_organization, 'organization_name'], this.props.organizations)
let initialValues = R.pipe(
R.assoc('user_organization', organization_name), //Reformat organization
R.pick(['user_firstname', 'user_lastname', 'user_email', 'user_organization']) //Pickup only needed fields
)(this.props.user)
return (
<div style={style}>
<IconButton onClick={this.handlePopoverOpen.bind(this)}>
<Icon name={Constants.ICON_NAME_NAVIGATION_MORE_VERT}/>
</IconButton>
<Popover open={this.state.openPopover} anchorEl={this.state.anchorEl}
onRequestClose={this.handlePopoverClose.bind(this)}>
<Menu multiple={false}>
<MenuItemLink label="Edit" onTouchTap={this.handleOpenEdit.bind(this)}/>
<MenuItemButton label="Delete" onTouchTap={this.handleOpenDelete.bind(this)}/>
</Menu>
</Popover>
<Dialog title="Confirmation" modal={false} open={this.state.openDelete}
onRequestClose={this.handleCloseDelete.bind(this)}
actions={deleteActions}>
Do you confirm the removing of this user?
</Dialog>
<Dialog title="Update the user" modal={false} open={this.state.openEdit}
onRequestClose={this.handleCloseEdit.bind(this)}
actions={editActions}>
<UserForm ref="userForm" initialValues={initialValues}
organizations={this.props.organizations}
onSubmit={this.onSubmitEdit.bind(this)}
onSubmitSuccess={this.handleCloseEdit.bind(this)}/>
</Dialog>
</div>
)
}
}
const select = (state) => {
return {
organizations: state.referential.entities.organizations
}
}
UserPopover.propTypes = {
exerciseId: PropTypes.string,
user: PropTypes.object,
updateUser: PropTypes.func,
updateAudience: PropTypes.func,
audience: PropTypes.object,
organizations: PropTypes.object,
children: PropTypes.node
}
export default connect(select, {updateUser, updateAudience})(UserPopover)
| JavaScript | 0.000068 | @@ -2441,19 +2441,19 @@
%5D;%0A%0A
-let
+var
organiz
@@ -2461,29 +2461,14 @@
tion
-_name = R.pathOr('-',
+Path =
%5Bth
@@ -2476,25 +2476,27 @@
s.props.user
-.
+, '
user_organiz
@@ -2500,16 +2500,17 @@
nization
+'
, 'organ
@@ -2523,16 +2523,75 @@
n_name'%5D
+%0A let organization_name = R.pathOr('-', organizationPath
, this.p
|
45e975b6a7a66ed2b4673fb434649b067fa57fd9 | Fix spelling. | lib/snc-client.js | lib/snc-client.js | /*
* The util that controls sending the actual server communications
*/
var http = require('http');
var restler = require('@mishguru/restler');
var url = require('url');
var util = require('util');
var logger = false;
// service takes args: <init fn>, <props>, <API>.
var sncClient = restler.service(function sncClient(config) {
var debug = config.debug;
// ideally we use a kick ass logger passed in via config.
logger = config._logger ? config._logger : {
debug: function () {
console.log('please define your debugger (winston)');
},
info: function () {
console.log('please define your debugger (winston)');
},
error: function () {
console.log('please define your debugger (winston)');
}
};
var auth = new Buffer(config.auth, 'base64').toString(),
parts = auth.split(':'),
user = parts[0],
pass = parts[1],
// allow testing on localhost/http but default to https
protocol = config.protocol ? config.protocol : 'https',
clientOptions = {
baseURL: protocol + '://' + config.host
};
this.baseURL = clientOptions.baseURL;
this.defaults.username = user;
this.defaults.password = pass;
this.defaults.headers = {
'Content-Type': 'application/json',
'Accepts': 'application/json'
};
// proxy support
if (config.proxy) {
this.defaults.proxy = {
'host': config.proxy.host,
'port': config.proxy.port
};
}
}, {
// props already set in previous arguement
}, {
table: function table(tableName) {
var client = this;
function validateResponse(result, res) {
// consider moving low level debug to high level debug (end user as below)
logResponse(result, res);
var help = '';
// special failing case (connections blocked etc.)
if (result instanceof Error) {
var errorList = {
'ECONNREFUSED': 'Missing interent connection or connection was refused!',
'ENOTFOUND': 'No connection available (do we have internet?)',
'ETIMEDOUT': 'Connection timed out. Internet down?'
};
help = errorList[result.code] || 'Something failed badly.. internet connection rubbish?';
help += util.format('\ndetails: %j', result);
logger.warn(help);
logger.error(result);
return new Error(help);
}
// standard responses
if (res.statusCode !== 200) {
if (res.statusCode === 401) {
help = 'Check credentials.';
} else if (res.statusCode === 302) {
help = 'Verify JSON Web Service plugin is activated.';
}
var message = util.format('%s - %s', res.statusCode, http.STATUS_CODES[res.statusCode]);
if (help) {
message += ' - ' + help;
}
if (result instanceof Error) {
message += util.format('\ndetails: %j', result);
}
return new Error(message);
}
if (result instanceof Error) {
return result;
}
if (result.error) {
logger.error('ERROR found in obj.error : ', result.error);
// DP TODO : Investigate: Error: json object is null
return new Error(result.error);
// this is actually not an error! It's just that the server didn't return anything to us
//return null;
}
if (!result.records) {
return new Error(util.format('Response missing "records" key: %j\nCheck server logs.', result));
}
return null;
}
function logResponse(result, res) {
var resCode = res ? res.statusCode : 'no response';
logger.debug('-------------------------------------------------------');
logger.debug(result);
// TODO - dropped extra debug support with restler migration
// client.baseURL
logger.debug('-------------------------------------------------------');
}
function send(request) {
var maxRecords = request.rows || 1;
var urlObj = {
pathname: '/' + request.table + '.do',
query: {
// JSONv2 not JSON (Eureka+)
JSONv2: '',
sysparm_record_count: maxRecords,
sysparm_action: request.action,
displayvalue: true
}
};
if (request.parmName) {
urlObj.query['sysparm_' + request.parmName] = request.parmValue;
}
var path = url.format(urlObj);
logger.debug('snc-client send() path: ' + path);
function handleResponse(result, res) {
var err = validateResponse(result, res, request);
request.callback(err, result);
}
// we may have some connection issues with TCP resets (ECONNRESET). Lets debug them further.
try {
if (request.postObj) {
// TODO - consider adding more callbacks here like timeout and error/fail etc.
client.post(path, {
data: JSON.stringify(request.postObj)
}).on('complete', handleResponse);
} else {
client.get(path).on('complete', handleResponse);
}
} catch (err) {
logger.error('Some connection error happend...', err);
// fail hard!
process.exit(1);
}
}
function getRecords(query, callback) {
var parms = {
table: tableName,
action: 'getRecords',
parmName: 'query',
parmValue: query,
rows: 1,
callback: callback
};
if (query.query) {
parms.parmValue = query.query;
// ensures that tables that are extended are still restricted to 1 table
parms.parmValue += "^sys_class_name=" + tableName;
}
if (query.rows) {
parms.rows = query.rows;
}
if (query.sys_id) {
parms.parmName = 'sys_id';
parms.parmValue = query.sys_id;
}
send(parms);
}
function get(id, callback) {
send({
table: tableName,
action: 'get',
parmName: 'sys_id',
parmValue: id,
callback: callback
});
}
function insert(obj, callback) {
logger.warn('DP TODO : insert not yet tested nor supported!');
//send({table: tableName, action: 'insert', postObj: obj, callback: callback});
}
/**
* Update an instance record
* @param query {object} - contains query data
* @param callback {function}
*/
function update(query, callback) {
var parms = {
table: tableName,
action: 'update',
parmName: 'query',
parmValue: query.query,
postObj: query.payload,
callback: callback
};
// sys_id based updates
if (query.sys_id) {
parms.parmName = 'sys_id';
parms.parmValue = query.sys_id;
}
send(parms);
}
return {
get: get,
getRecords: getRecords,
insert: insert,
update: update
};
}
});
module.exports = sncClient;
| JavaScript | 0.001428 | @@ -2076,18 +2076,18 @@
ng inter
-e
n
+e
t connec
|
417970d403d57011a3dadb688ac7f08eba96da99 | update footer year (woo) | app/javascript/components/Footer.js | app/javascript/components/Footer.js | import React from "react"
class Footer extends React.Component {
render () {
return (
<footer className="grey-text no-print">
<div className="container center">
<div className="row">
<div className="col s12">
<div>
<a href="https://www.twitter.com/indentlabs" target="_blank">
<i className="fa fa-twitter blue-text"></i> Twitter
</a>
·
<a href="https://www.facebook.com/Notebookai-556092274722663/" target="_blank">
<i className="fa fa-facebook blue-text"></i> Facebook
</a>
·
<a href="https://github.com/indentlabs/notebook" target="_blank">
<i className="fa fa-github black-text"></i> GitHub
</a>
</div>
</div>
Notebook.ai © 2016-2021 <a href='http://www.indentlabs.com' className='grey-text'>
Indent Labs, LLC
</a>
</div>
</div>
</footer>
);
}
}
export default Footer;
| JavaScript | 0 | @@ -946,17 +946,17 @@
2016-202
-1
+2
%3Ca href
|
b710d4076a67ebaac85d0f39f956ecb660e44a4f | Add "French" prefix text to non translated strings examples to make localization example more clear | src/extensions/disabled/LocalizationExample/nls/fr/strings.js | src/extensions/disabled/LocalizationExample/nls/fr/strings.js | // French Translation
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define({
"COMMAND_NAME" : "Ma nouvelle commande",
"ALERT_MESSAGE" : "Il s'agit d'un message d'alerte échantillon"
});
| JavaScript | 0.001076 | @@ -124,16 +124,106 @@
ine */%0A%0A
+// This example currently displays English, but shows where French translations would go.%0A
define(%7B
@@ -251,33 +251,33 @@
- : %22Ma nouvelle c
+: %22French: My New C
ommand
-e
%22,%0A
@@ -303,56 +303,214 @@
- : %22Il s'agit d'un message d'alerte %C3%A9chantillon
+: %22French: This is a sample alert message%22,%0A %22DIALOG_TITLE%22%09%09: %22French: Localized Dialog Example%22,%0A %22DIALOG_TEXT%22%09%09: %22French: This is an example of localized text in Brackets%22,%0A %22DIALOG_OK%22%09%09%09: %22OK
%22%0A%7D)
|
d2b368b90e10e3276f1620a1792380e6f4b68b21 | Fix up the test to validate dependencies exist after update | test/cli.js | test/cli.js | var fs = require("fs")
, rimraf = require("rimraf")
, childProcess = require("child_process")
function cp (src, dest, cb) {
var rs = fs.createReadStream(src)
rs.on("end", function() { cb(null) })
rs.pipe(fs.createWriteStream(dest))
}
module.exports = {
setUp: function (cb) {
rimraf("test/tmp", function (er) {
if (er) throw er
fs.mkdir("test/tmp", cb)
})
},
"Test update and save dependencies, devDependencies & optionalDependencies": function (test) {
fs.mkdir("test/tmp/test-update", function (er) {
test.ifError(er)
cp("test/fixtures/test-update/package.json", "test/tmp/test-update/package.json", function () {
var proc = childProcess.exec("node ../../../bin/david update", { cwd: "test/tmp/test-update" }, function (er) {
test.ifError(er)
// Should have installed dependencies
var pkg = JSON.parse(fs.readFileSync("test/fixtures/test-update/package.json"))
, depNames = Object.keys(pkg.dependencies)
, devDepNames = Object.keys(pkg.devDependencies)
, optionalDepNames = Object.keys(pkg.optionalDependencies)
depNames.concat(devDepNames).concat(optionalDepNames).forEach(function (depName) {
test.ok(fs.existsSync("test/tmp/test-update/node_modules/" + depName), depName + " expected to be installed")
})
// Version numbers should have changed
var updatedPkg = JSON.parse(fs.readFileSync("test/tmp/test-update/package.json"))
depNames.forEach(function (depName) {
test.notEqual(pkg.dependencies[depName], updatedPkg.dependencies[depName], depName + " version expected to have changed")
})
devDepNames.forEach(function (depName) {
test.notEqual(pkg.devDependencies[depName], updatedPkg.devDependencies[depName], depName + " version expected to have changed")
})
optionalDepNames.forEach(function (depName) {
test.notEqual(pkg.optionalDependencies[depName], updatedPkg.optionalDependencies[depName], depName + " version expected to have changed")
})
test.done()
})
proc.stdout.on("data", function (data) {
console.log(data.toString().trim())
})
proc.stderr.on("data", function (data) {
console.error(data.toString().trim())
})
})
})
},
"Test update & save only async and grunt dependencies": function (test) {
fs.mkdir("test/tmp/test-filtered-update", function (er) {
test.ifError(er)
cp("test/fixtures/test-update/package.json", "test/tmp/test-filtered-update/package.json", function () {
var proc = childProcess.exec("node ../../../bin/david update async grunt", {cwd: "test/tmp/test-filtered-update"}, function (er) {
test.ifError(er)
// Should have installed dependencies
var pkg = JSON.parse(fs.readFileSync("test/fixtures/test-update/package.json"))
, depNames = Object.keys(pkg.dependencies)
, devDepNames = Object.keys(pkg.devDependencies)
, optionalDepNames = Object.keys(pkg.optionalDependencies)
depNames.concat(devDepNames).concat(optionalDepNames).forEach(function (depName) {
if (depName === "async" || depName === "grunt") {
test.ok(fs.existsSync("test/tmp/test-filtered-update/node_modules/" + depName), depName + " expected to be installed")
} else {
test.ok(!fs.existsSync("test/tmp/test-filtered-update/node_modules/" + depName), depName + " not expected to be installed")
}
})
// Version numbers should have changed
var updatedPkg = JSON.parse(fs.readFileSync("test/tmp/test-filtered-update/package.json"))
depNames.forEach(function (depName) {
if (depName === "async") {
test.notEqual(pkg.dependencies[depName], updatedPkg.dependencies[depName], depName + " version expected to have changed")
} else {
test.equal(pkg.dependencies[depName], updatedPkg.dependencies[depName], depName + " version not expected to have changed")
}
})
devDepNames.forEach(function (depName) {
if (depName === "grunt") {
test.notEqual(pkg.devDependencies[depName], updatedPkg.devDependencies[depName], depName + " version expected to have changed")
} else {
test.equal(pkg.devDependencies[depName], updatedPkg.devDependencies[depName], depName + " version not expected to have changed")
}
})
optionalDepNames.forEach(function (depName) {
test.equal(pkg.optionalDependencies[depName], updatedPkg.optionalDependencies[depName], depName + " version not expected to have changed")
})
test.done()
})
proc.stdout.on("data", function (data) {
console.log(data.toString().trim())
})
proc.stderr.on("data", function (data) {
console.error(data.toString().trim())
})
})
})
}
}
| JavaScript | 0.000001 | @@ -2464,20 +2464,22 @@
ync and
-grun
+reques
t depend
@@ -2797,20 +2797,22 @@
e async
-grun
+reques
t%22, %7Bcwd
@@ -3374,36 +3374,38 @@
%7C%7C depName === %22
-grun
+reques
t%22) %7B%0A
@@ -3875,16 +3875,169 @@
son%22))%0A%0A
+ // Ensure the dependencies still exist%0A test.ok(updatedPkg.dependencies.async)%0A test.ok(updatedPkg.devDependencies.request)%0A%0A
@@ -4521,12 +4521,14 @@
== %22
-grun
+reques
t%22)
|
631b6a2b0679787f0f4689d9732cc4d1e7de8d44 | Use `onLoad` in application.js, fix linter | app/javascript/packs/application.js | app/javascript/packs/application.js | // This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb
/* eslint-disable
import/no-unassigned-import,
import/newline-after-import,
import/first
*/
import Turbolinks from 'turbolinks';
import '../turbolinks_prefetch.coffee'; // The original is in coffee.
Turbolinks.start();
import '../cable';
import '../admin';
import '../api';
import '../code_status';
import '../data';
import '../flag_conditions';
import '../reasons';
import '../review';
import '../stack_exchange_users';
import '../status';
import '../user_site_settings';
import createDebug from 'debug';
const debug = createDebug('ms:app');
$(document).on('turbolinks:load', () => {
$('.sortable-table').tablesort();
$('.selectpicker').selectpicker();
$('.admin-report').click(function (ev) {
ev.preventDefault();
const reason = window.prompt('Why does this post need admin attention?');
if (reason === null) {
return;
}
$.ajax({
type: 'POST',
url: '/posts/needs_admin',
data: {
id: $(this).data('post-id'),
reason
}
}).done(data => {
if (data === 'OK') {
window.alert('Post successfully reported for admin attention.');
}
}).fail(jqXHR => {
window.alert('Post was not reported: status ' + jqXHR.status);
debug('report failed:', jqXHR.responseText, 'status:', jqXHR.status, '\n', jqXHR);
});
});
$('.admin-report-done').click(function (ev) {
ev.preventDefault();
$.ajax({
type: 'POST',
url: '/admin/clear_flag',
data: {
id: $(this).data('flag-id')
},
target: $(this)
}).done(function (data) {
if (data === 'OK') {
window.alert('Marked done.');
$(this.target).parent().parent().siblings().addBack().siblings('.flag-' + $(this.target).data('flag-id')).first().prev().remove();
$(this.target).parents('tr').remove();
}
}).fail(jqXHR => {
window.alert('Failed to mark done: status ' + jqXHR.status);
debug('flag completion failed:', jqXHR.responseText, 'status:', jqXHR.status, '\n', jqXHR);
});
});
$('.announcement-collapse').click(ev => {
ev.preventDefault();
const collapser = $('.announcement-collapse');
const announcements = $('.announcements').children('.alert-info');
const showing = collapser.text().indexOf('Hide') > -1;
if (showing) {
const text = announcements.map((i, x) => $('p', x).text()).toArray().join(' ');
localStorage.setItem('metasmoke-announcements-read', text);
$('.announcements').slideUp(500);
collapser.text('Show announcements');
} else {
localStorage.removeItem('metasmoke-announcements-read');
$('.announcements').slideDown(500);
collapser.text('Hide announcements');
}
});
(function () {
const announcements = $('.announcements').children('.alert-info');
const text = announcements.map((i, x) => $('p', x).text()).toArray().join(' ');
const read = localStorage.getItem('metasmoke-announcements-read');
if (read && read === text) {
$('.announcements').hide();
$('.announcement-collapse').text('Show announcements');
}
})();
});
| JavaScript | 0.000001 | @@ -667,16 +667,87 @@
art();%0A%0A
+import createDebug from 'debug';%0Aconst debug = createDebug('ms:app');%0A%0A
import '
@@ -1005,114 +1005,51 @@
ort
-createDebug from 'debug';%0Aconst debug = createDebug('ms:app');%0A%0A$(document).on('turbolinks:load',
+%7B onLoad %7D from '../util';%0A%0AonLoad(
() =%3E %7B%0A
$(
@@ -1044,16 +1044,17 @@
() =%3E %7B%0A
+%0A
$('.so
|
0ca6d2ddae95788ab1187b19c67d0242418ed99d | Add comma | static/js/classes/coordinate_system_drawing.js | static/js/classes/coordinate_system_drawing.js | var CoordinateSystemDrawing = AbstractDrawing.extend(function(base) {
return {
init: function() {
base.init.call(this);
this.particleSystem = null;
this.neighbors = null;
this.topWCoordinates = null;
},
/* Public */
setNeighbors: function(neighbors) {
this.neighbors = neighbors;
},
setTopWCoordinates: function(topWCoordinates) {
this.topWCoordinates = topWCoordinates;
},
setup: function() {
var object3D = this.getObject3D(),
axes = this._buildAxes(1000)
particleSystem = this._buildParticleSystem();
object3D.add(axes);
if (particleSystem) {
object3D.add(particleSystem);
this.particleSystem = particleSystem;
}
},
reset: function() {
base.reset.call(this);
this.neighbors = null;
this.topWCoordinates = null;
},
clear: function() {
if (!this.particleSystem) return;
var object3D = this.getObject3D(),
particleSystem = this.particleSystem;
object3D.remove(particleSystem);
this.particleSystem = null;
},
updateParticles: function() {
if (!this.particleSystem) return;
if (!this.topWCoordinates) return;
var particles = this.particleSystem.geometry,
neighbors = this.neighbors,
topWCoordinates = this.topWCoordinates;
for (var i = 0; i < particles.vertices.length; i++) {
var coordinate = neighbors[i];
var color = COLOR_DARK_NEIGHBOR,
topWCoordinatesCache = {};
if (_.fastContains(topWCoordinates, coordinate, topWCoordinatesCache)) {
color = COLOR_DARK_ACTIVE_NEIGHBOR;
}
particles.colors[i].setHex(color);
}
},
updateProximalSynapses: function() {
if (!this.particleSystem) return;
var inputDrawing = this.inputDrawing,
particles = this.particleSystem.geometry.vertices,
inputParticles = inputDrawing.getParticles(),
proximalSynapses = this.proximalSynapses,
showProximalSynapses = this.showProximalSynapses;
},
/* Private */
_buildParticleSystem: function() {
if (!this.neighbors) return null;
var neighbors = this.neighbors;
var particles = new THREE.Geometry(),
material = new THREE.ParticleBasicMaterial({
size: 1,
map: THREE.ImageUtils.loadTexture(
"img/particle.png"
),
blending: THREE.NormalBlending,
transparent: true,
vertexColors: true
}),
particleSystem = new THREE.ParticleSystem(particles, material);
particleSystem.sortParticles = true;
for (var i = 0; i < neighbors.length; i++) {
var neighbor = neighbors[i],
pX = neighbor[0],
pY = neighbor[1] || 0,
pZ = neighbor[2] || 0,
particle = new THREE.Vector3(pX, pY, pZ);
particles.vertices.push(particle);
particles.colors.push(new THREE.Color(COLOR_DARK_NEIGHBOR));
}
return particleSystem;
},
/* From https://github.com/sole/three.js-tutorials/blob/master/drawing_the_axes/main.js */
_buildAxes: function(length) {
var axes = new THREE.Object3D();
axes.add( this._buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( length, 0, 0 ), 0xFF0000, false ) ); // +X
axes.add( this._buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( -length, 0, 0 ), 0xFF0000, true) ); // -X
axes.add( this._buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, length, 0 ), 0x00FF00, false ) ); // +Y
axes.add( this._buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, -length, 0 ), 0x00FF00, true ) ); // -Y
axes.add( this._buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, length ), 0x0000FF, false ) ); // +Z
axes.add( this._buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, -length ), 0x0000FF, true ) ); // -Z
return axes;
},
_buildAxis: function(src, dst, colorHex, dashed) {
var geom = new THREE.Geometry(),
mat;
if(dashed) {
mat = new THREE.LineDashedMaterial({
linewidth: 3,
color: colorHex,
dashSize: 3,
gapSize: 3
});
} else {
mat = new THREE.LineBasicMaterial({
linewidth: 3,
color: colorHex
});
}
geom.vertices.push( src.clone() );
geom.vertices.push( dst.clone() );
geom.computeLineDistances(); // This one is SUPER important, otherwise dashed lines will appear as simple plain lines
var axis = new THREE.Line( geom, mat, THREE.LinePieces );
return axis;
},
};
});
| JavaScript | 0.999968 | @@ -624,16 +624,17 @@
es(1000)
+,
%0A
|
88b219262bcc36f86dab0442f4e73714c9af4611 | add undefined action types to remove warnings | src/actions.js | src/actions.js | import { createAction } from 'redux-actions';
import fetch from 'isomorphic-fetch';
export const CONFIG_REQUEST = '@app/CONFIG_REQUEST';
export const CONFIG_SUCCESS = '@app/CONFIG_SUCCESS';
export const CONFIG_FAILURE = '@app/CONFIG_FAILURE';
export const FEED_REQUEST = '@app/FEED_REQUEST';
export const FEED_SUCCESS = '@app/FEED_SUCCESS';
export const FEED_FAILURE = '@app/FEED_FAILURE';
export const CONTENT_REQUEST = '@app/CONTENT_REQUEST';
export const CONTENT_SUCCESS = '@app/CONTENT_SUCCESS';
export const ACCOUNT_REQUEST = '@app/ACCOUNT_REQUEST';
export const ACCOUNT_SUCCESS = '@app/ACCOUNT_SUCCESS';
export const OPEN_POST_MODAL = '@app/OPEN_POST_MODAL';
export const CLOSE_POST_MODAL = '@app/CLOSE_POST_MODAL';
export const openPostModal = createAction(OPEN_POST_MODAL);
export const closePostModal = createAction(CLOSE_POST_MODAL);
export const getConfig = () =>
(dispatch, getState, { steemAPI }) => {
dispatch({ type: CONFIG_REQUEST });
steemAPI.getConfig((err, config) => {
dispatch({
type: CONFIG_SUCCESS,
config,
});
});
};
export const SHOW_SIDEBAR = '@app/SHOW_SIDEBAR';
export const showSidebar = createAction(SHOW_SIDEBAR);
export const HIDE_SIDEBAR = '@app/HIDE_SIDEBAR';
export const hideSidebar = createAction(HIDE_SIDEBAR);
export const SET_LAYOUT = '@app/SET_LAYOUT';
export const setLayoutAction = createAction(SET_LAYOUT);
export const setLayout = layout =>
(dispatch) => {
dispatch(setLayoutAction({ layout }));
};
export const SET_LOCALE = '@app/SET_LOCALE';
export const setLocaleAction = createAction(SET_LOCALE);
export const setLocale = locale =>
(dispatch) => {
dispatch(setLocaleAction({ locale }));
};
export const RATE_REQUEST = '@app/RATE_REQUEST';
export const RATE_SUCCESS = '@app/RATE_SUCCESS';
export const getRate = () =>
(dispatch) => {
dispatch({ type: RATE_REQUEST });
fetch('https://api.cryptonator.com/api/ticker/steem-usd')
.then(res => res.json())
.then((json) => {
const rate = json.ticker.price;
dispatch({
type: RATE_SUCCESS,
rate,
});
});
};
| JavaScript | 0 | @@ -598,32 +598,113 @@
OUNT_SUCCESS';%0A%0A
+export const GET_LAYOUT = 'GET_LAYOUT';%0Aexport const GET_LOCALE = 'GET_LOCALE';%0A%0A
export const OPE
|
76e178d71347140005b26d22dcdf59099111fbb4 | Disable linting error | src/check-annotations.js | src/check-annotations.js | import logUpdate from 'log-update';
const matchAnyVariationSelectorOrModifier = /\s(FE0E|FE0F|1F3FB|1F3FC|1F3FD|1F3FE|1F3FF)/g;
export default function checkData({ languages, data }) {
logUpdate('⌛︎ check-annotations');
const normalizedDataSequences = data.map(datum =>
datum.sequence.replace(matchAnyVariationSelectorOrModifier, '')
);
const results = languages.map((language) => {
const annotations = require(`../lib/annotations/cldr/${language}.json`);
const annotationForSequence = annotations.reduce((prevAnnotationForSequence, annotation) => {
const nextAnnotationForSequence = prevAnnotationForSequence;
nextAnnotationForSequence[annotation.sequence] = annotation;
return nextAnnotationForSequence;
}, {});
const result = normalizedDataSequences.reduce((prevResult, sequence) => {
const nextResult = prevResult;
const annotationForNormalizedDataSequence = annotationForSequence[sequence];
if (annotationForNormalizedDataSequence == null) {
nextResult.numEmojiMissingTts += 1;
nextResult.numEmojiMissingKeywords += 1;
} else {
if (annotationForNormalizedDataSequence.tts == null) {
nextResult.numEmojiMissingTts += 1;
}
if (annotationForNormalizedDataSequence.keywords == null) {
nextResult.numEmojiMissingKeywords += 1;
}
}
return nextResult;
}, {
language,
numEmojiMissingTts: 0,
numEmojiMissingKeywords: 0,
});
return result;
});
const success = results.reduce((prevSuccess, result) => {
if (result.numEmojiMissingTts > 0 || result.numEmojiMissingKeywords > 0) {
logUpdate(`x check-annotations ${result.language}:`);
logUpdate.done();
if (result.numEmojiMissingTts > 0) {
logUpdate(` ${result.numEmojiMissingTts} sequences missing tts`);
logUpdate.done();
}
if (result.numEmojiMissingKeywords > 0) {
logUpdate(` ${result.numEmojiMissingKeywords} sequences missing keywords`);
logUpdate.done();
}
return false;
}
logUpdate(`✓ check-annotations ${result.language}`);
logUpdate.done();
return prevSuccess;
}, true);
logUpdate(`${success ? '✓' : 'x'} check-annotations`);
logUpdate.done();
return results;
}
| JavaScript | 0.000001 | @@ -458,16 +458,54 @@
.json%60);
+ // eslint-disable-line global-require
%0A%09%09const
|
b7a2106f4ad7795fe86f5767fcfba0d8d7773bb5 | implement readonly | src/checkbox/checkbox.js | src/checkbox/checkbox.js | import { bindable, customElement } from 'aurelia-templating';
import { bindingMode } from 'aurelia-binding';
import { inject } from 'aurelia-dependency-injection';
import { AttributeManager } from '../common/attributeManager';
import { getBooleanFromAttributeValue } from '../common/attributes';
// import {fireEvent} from '../common/events';
@customElement('md-checkbox')
@inject(Element)
export class MdCheckbox {
static id = 0;
@bindable({
defaultBindingMode: bindingMode.twoWay
}) mdChecked;
@bindable() mdDisabled;
@bindable() mdReadonly = false;
@bindable() mdFilledIn;
@bindable() mdMatcher;
@bindable() mdModel;
constructor(element) {
this.element = element;
this.controlId = `md-checkbox-${MdCheckbox.id++}`;
// this.handleChange = this.handleChange.bind(this);
}
attached() {
this.attributeManager = new AttributeManager(this.checkbox);
if (getBooleanFromAttributeValue(this.mdFilledIn)) {
this.attributeManager.addClasses('filled-in');
}
if (this.mdChecked === null) {
this.checkbox.indeterminate = true;
} else {
this.checkbox.indeterminate = false;
}
if (getBooleanFromAttributeValue(this.mdDisabled)) {
this.checkbox.disabled = true;
}
this.mdReadonly = getBooleanFromAttributeValue(this.mdReadonly);
// this.checkbox.checked = getBooleanFromAttributeValue(this.mdChecked);
// this.checkbox.addEventListener('change', this.handleChange);
}
// blur() {
// fireEvent(this.element, 'blur');
// }
detached() {
this.attributeManager.removeClasses(['filled-in', 'disabled']);
// this.checkbox.removeEventListener('change', this.handleChange);
}
// handleChange() {
// this.mdChecked = this.checkbox.checked;
// fireEvent(this.element, 'blur');
// }
// mdCheckedChanged(newValue) {
// // if (this.checkbox) {
// // this.checkbox.checked = !!newValue;
// // }
// fireEvent(this.element, 'blur');
// }
mdDisabledChanged(newValue) {
if (this.checkbox) {
this.checkbox.disabled = !!newValue;
}
}
}
| JavaScript | 0 | @@ -560,16 +560,229 @@
false;%0A
+ mdReadonlyChanged() %7B%0A if (this.mdReadonly) %7B%0A this.checkbox.addEventListener('change', this.preventChange);%0A %7D else %7B%0A this.checkbox.removeEventListener('change', this.preventChange);%0A %7D%0A %7D%0A
@binda
@@ -2292,11 +2292,70 @@
%7D%0A %7D
+%0A%0A preventChange() %7B%0A this.checked = !this.checked;%0A %7D
%0A%7D%0A
|
76d6ce43dd2928f46f97dbb732b7ce545dd5e575 | Fix error flag | ui/src/reducers/util.js | ui/src/reducers/util.js | import _ from 'lodash';
export function mergeResults(previous, current) {
if (previous === undefined || previous.results === undefined || current.offset === 0) {
return current;
}
const expectedOffset = (previous.limit + previous.offset);
if (current.offset === expectedOffset) {
return { ...current, results: [...previous.results, ...current.results] };
}
if (Number.isNaN(expectedOffset)) return current;
return previous;
}
export function timestamp() {
return new Date().toISOString();
}
export function loadComplete(data) {
return {
...data,
isLoading: false,
isError: false,
shouldLoad: false,
loadedAt: timestamp(),
error: undefined,
};
}
export function objectLoadComplete(state, id, data = {}) {
return { ...state, [id]: loadComplete(data) };
}
export function updateResults(state, { query, result }) {
const key = query.toKey();
const res = { ...result, results: result.results.map(r => r.id) };
return objectLoadComplete(state, key, mergeResults(state[key], res));
}
export function loadState(data) {
const state = data || {};
return { ...state, isLoading: false, shouldLoad: true, isError: false };
}
export function loadStart(state) {
const prevState = state || {};
return { ...prevState, isLoading: true, shouldLoad: false, isError: false, loadedAt: null };
}
export function objectLoadStart(state, id) {
return { ...state, [id]: loadStart(state[id]) };
}
export function resultLoadStart(state, query) {
return objectLoadStart(state, query.toKey());
}
export function loadError(state, error) {
const prevState = state || {};
return {
...prevState,
isLoading: false,
shouldLoad: false,
isError: false,
loadedAt: undefined,
error,
};
}
export function objectLoadError(state, id, error) {
return { ...state, [id]: loadError(state[id], error) };
}
export function resultLoadError(state, query, error) {
return objectLoadError(state, query.toKey(), error);
}
export function objectReload(state, id) {
const object = { isLoading: false, shouldLoad: true };
return { ...state, [id]: _.assign({}, state[id], object) };
}
export function objectDelete(state, id) {
_.unset(state, id);
return state;
}
export function resultObjects(state, result, onComplete = objectLoadComplete) {
if (result.results !== undefined) {
return result.results
.reduce((finalState, object) => onComplete(finalState, object.id, object), state);
}
return state;
}
| JavaScript | 0.000003 | @@ -1331,16 +1331,29 @@
oadedAt:
+ null, error:
null %7D;
@@ -1712,28 +1712,27 @@
isError:
-fals
+tru
e,%0A loade
|
3d9dd9c86a37b9a17ac1068d1955f6b3e8c19cae | fix tests | app/js/services/situationService.js | app/js/services/situationService.js | 'use strict';
angular.module('ddsApp').factory('SituationService', function($http, $sessionStorage, $filter) {
var situation, months;
return {
nationaliteLabels: {
francaise: 'française',
ue: 'UE',
autre: 'hors UE'
},
relationTypeLabels: {
mariage: 'marié(e)',
pacs: 'pacsé(e)',
relationLibre: 'en relation libre'
},
find: function(situationId) {
return $http.get('/api/situations/' + situationId).then(function(result) {
return result.data;
});
},
saveRemote: function(situation) {
return $http.post('/api/situations', situation);
},
newSituation: function() {
delete $sessionStorage.situation;
situation = null;
},
saveLocal: function(situation) {
$sessionStorage.situation = situation;
},
restoreLocal: function() {
if (!situation) {
situation = $sessionStorage.situation || {};
}
return situation;
},
createIndividusList: function() {
var individus = [
{
name: 'Vous',
type: 'demandeur',
individu: situation.demandeur
}
];
if (situation.conjoint) {
individus.push({
name: 'Votre conjoint',
type: 'conjoint',
individu: situation.conjoint
});
}
situation.enfants.forEach(function(child) {
individus.push({name: child.firstName, type: 'child', individu: child});
});
situation.personnesACharge.forEach(function(personne) {
individus.push({name: personne.firstName, type: 'personneACharge', individu: personne});
});
return individus;
},
formatStatutsSpecifiques: function(individu) {
var statuses = [];
_.forEach(this.statutsSpecifiquesLabels, function(statut, statutId) {
if (individu[statutId]) {
statuses.push(statut);
}
});
statuses = statuses.join(', ');
statuses = $filter('uppercaseFirst')(statuses);
return statuses;
},
statutsSpecifiquesLabels: {
'boursierEnseignementSup': 'boursier enseignement supérieur',
'etudiant': 'étudiant',
'demandeurEmploi': 'demandeur d\'emploi',
'retraite': 'retraité'
},
getMonths: function() {
if (months) {
return months;
}
// FIXME prendre la date du serveur
return _.map([3, 2, 1], function(i) {
var date = moment().subtract('months', i);
return {
id: date.format('YYYY-MM'),
label: date.format('MMMM YYYY')
};
});
},
logementTypes: [
{
label: 'locataire',
value: 'locataire'
},
{
label: 'propriétaire',
value: 'proprietaire'
},
{
label: 'occupant à titre gratuit',
value: 'gratuit'
}
],
revenusSections: [
{
name: 'revenusActivite',
label: 'Revenus d\'activité',
subsections: [
{
name: 'revenusSalarie',
label: 'Salaires'
}, {
name: 'revenusNonSalarie',
label: 'Revenus non salariés'
}, {
name: 'revenusAutoEntrepreneur',
label: 'Revenus auto-entrepreneur'
},
]
},
{
name: 'allocations',
label: 'Allocations',
subsections: [
{
name: 'allocationsChomage',
label: 'Allocation chômage'
}, {
name: 'allocationLogement',
label: 'Allocation logement'
}, {
name: 'rsa',
label: 'Revenu de solidarité active (RSA)'
}, {
name: 'aspa',
label: 'Allocation de solidarité aux personnes âgées (ASPA)'
}, {
name: 'ass',
label: 'Allocation de solidarité spécifique (ASS)'
}
]
},
{
name: 'indemnites',
label: 'Indemnités',
subsections: [
{
name: 'indJourMaternite',
label: 'Indemnités de maternité'
}, {
name: 'indJourPaternite',
label: 'Indemnités de paternité'
}, {
name: 'indJourAdoption',
label: 'Indemnités d\'adoption'
}, {
name: 'indJourMaladie',
label: 'Indemnités maladie'
}, {
name: 'indJourMaladieProf',
label: 'Indemnités maladie professionnelle'
}, {
name: 'indJourAccidentDuTravail',
label: 'Indemnités accident du travail'
}, {
name: 'indChomagePartiel',
label: 'Indemnités de chômage partiel'
}
]
},
{
name: 'pensions',
label: 'Pensions',
subsections: [
{
name: 'pensionsAlimentaires',
label: 'Pensions alimentaires'
}, {
name: 'pensionsRetraitesRentes',
label: 'Retraites, rentes'
}
]
}
]
};
});
| JavaScript | 0.000001 | @@ -1628,32 +1628,42 @@
%7D%0A%0A
+_.forEach(
situation.enfant
@@ -1663,25 +1663,18 @@
.enfants
-.forEach(
+,
function
@@ -1793,32 +1793,42 @@
);%0A%0A
+_.forEach(
situation.person
@@ -1837,25 +1837,18 @@
sACharge
-.forEach(
+,
function
|
a4bb417d23964ac39a8c8f4dbf4176421159c32e | Update group profile message (closes #1756) | react/components/ProfileEmptyMessage/index.js | react/components/ProfileEmptyMessage/index.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { propType } from 'graphql-anywhere';
import styled from 'styled-components';
import emptyProfileFragment from 'react/components/ProfileEmptyMessage/fragments/indentifiable';
import Text from 'react/components/UI/Text';
import Modal from 'react/components/UI/Modal';
import NewChannelForm from 'react/components/NewChannelForm';
const Copy = styled(Text)`
a {
font-weight: bold;
}
a:hover{
color: ${x => x.theme.colors.gray.base};
}
`;
export default class ProfileEmptyMessage extends Component {
static propTypes = {
isMine: PropTypes.bool,
identifiable: propType(emptyProfileFragment).isRequired,
}
static defaultProps = {
isMine: false,
}
openNewChannelModal = () => {
const { identifiable } = this.props;
const newChannelProps = identifiable.__typename === 'Group' && {
group_id: identifiable.id,
authorType: 'GROUP',
visibility: 'PRIVATE',
};
const modal = new Modal(NewChannelForm, newChannelProps);
modal.open();
}
render() {
const { isMine, identifiable } = this.props;
const isGroup = identifiable.__typename === 'Group';
return (
<Copy f={6} my={8} color="gray.medium" lineHeight={2}>
{/* Profile is the current user's */}
{isMine && !isGroup &&
<div>
This is your profile.<br />
All of your channels and content will show up here.
</div>
}
{/* Profile is the current user's group */}
{isMine && isGroup &&
<div>
This is your group's profile.<br />
All of your group's channels will show up here.
</div>
}
{/* Profile is either the current user's or the current user's group */}
{isMine &&
<div>
Try{' '}
<a href="#" onClick={this.openNewChannelModal}>creating a channel</a>.
</div>
}
{/* Profile is not associated with the current user */}
{!isMine &&
<div>
There's no public content here yet.<br />
Try{' '}
<a href="/explore">explore</a>
{' '}to see what other people are up to.
</div>
}
</Copy>
);
}
}
| JavaScript | 0 | @@ -1666,32 +1666,31 @@
-All of y
+Note: Y
our group
@@ -1690,41 +1690,69 @@
roup
-'s channels will show up here
+ will stay secret until you create a publicly visible channel
.%0A
|
b831bb8350184c89a1cef094e460ccddf5a70a7c | add roomPasswordNumberOfDigits to whitelist | react/features/base/config/configWhitelist.js | react/features/base/config/configWhitelist.js | import extraConfigWhitelist from './extraConfigWhitelist';
/**
* The config keys to whitelist, the keys that can be overridden.
* Currently we can only whitelist the first part of the properties, like
* 'p2p.useStunTurn' and 'p2p.enabled' we whitelist all p2p options.
* The whitelist is used only for config.js.
*
* @type Array
*/
export default [
'_desktopSharingSourceDevice',
'_peerConnStatusOutOfLastNTimeout',
'_peerConnStatusRtcMuteTimeout',
'abTesting',
'analytics.disabled',
'audioLevelsInterval',
'autoRecord',
'autoRecordToken',
'avgRtpStatsN',
/**
* The display name of the CallKit call representing the conference/meeting
* associated with this config.js including while the call is ongoing in the
* UI presented by CallKit and in the system-wide call history. The property
* is meant for use cases in which the room name is not desirable as a
* display name for CallKit purposes and the desired display name is not
* provided in the form of a JWT callee. As the value is associated with a
* conference/meeting, the value makes sense not as a deployment-wide
* configuration, only as a runtime configuration override/overwrite
* provided by, for example, Jitsi Meet SDK for iOS.
*
* @type string
*/
'callDisplayName',
'callFlowsEnabled',
/**
* The handle
* ({@link https://developer.apple.com/documentation/callkit/cxhandle}) of
* the CallKit call representing the conference/meeting associated with this
* config.js. The property is meant for use cases in which the room URL is
* not desirable as the handle for CallKit purposes. As the value is
* associated with a conference/meeting, the value makes sense not as a
* deployment-wide configuration, only as a runtime configuration
* override/overwrite provided by, for example, Jitsi Meet SDK for iOS.
*
* @type string
*/
'callHandle',
'callStatsConfIDNamespace',
'callStatsID',
'callStatsSecret',
/**
* The UUID of the CallKit call representing the conference/meeting
* associated with this config.js. The property is meant for use cases in
* which Jitsi Meet is to work with a CallKit call created outside of Jitsi
* Meet and to be adopted by Jitsi Meet such as, for example, an incoming
* and/or outgoing CallKit call created by Jitsi Meet SDK for iOS
* clients/consumers prior to giving control to Jitsi Meet. As the value is
* associated with a conference/meeting, the value makes sense not as a
* deployment-wide configuration, only as a runtime configuration
* override/overwrite provided by, for example, Jitsi Meet SDK for iOS.
*
* @type string
*/
'callUUID',
'channelLastN',
'constraints',
'debug',
'debugAudioLevels',
'defaultLanguage',
'desktopSharingFrameRate',
'desktopSharingSources',
'disable1On1Mode',
'disableAEC',
'disableAGC',
'disableAP',
'disableAudioLevels',
'disableDeepLinking',
'disableH264',
'disableHPF',
'disableInviteFunctions',
'disableLocalVideoFlip',
'disableNS',
'disableRemoteControl',
'disableRemoteMute',
'disableRtx',
'disableSimulcast',
'disableSuspendVideo',
'disableThirdPartyRequests',
'displayJids',
'doNotStoreRoom',
'e2eping',
'enableDisplayNameInStats',
'enableEmailInStats',
'enableIceRestart',
'enableInsecureRoomNameWarning',
'enableLayerSuspension',
'enableLipSync',
'enableRemb',
'enableScreenshotCapture',
'enableTalkWhileMuted',
'enableNoAudioDetection',
'enableNoisyMicDetection',
'enableTcc',
'etherpad_base',
'failICE',
'feedbackPercentage',
'fileRecordingsEnabled',
'firefox_fake_device',
'forceJVB121Ratio',
'gatherStats',
'googleApiApplicationClientID',
'hiddenDomain',
'hosts',
'iAmRecorder',
'iAmSipGateway',
'iceTransportPolicy',
'ignoreStartMuted',
'liveStreamingEnabled',
'localRecording',
'minParticipants',
'nick',
'openBridgeChannel',
'opusMaxAvgBitrate',
'p2p',
'pcStatsInterval',
'preferH264',
'prejoinPageEnabled',
'requireDisplayName',
'remoteVideoMenu',
'resolution',
'startAudioMuted',
'startAudioOnly',
'startBitrate',
'startScreenSharing',
'startSilent',
'startVideoMuted',
'startWithAudioMuted',
'startWithVideoMuted',
'stereo',
'subject',
'testing',
'useStunTurn',
'useTurnUdp',
'webrtcIceTcpDisable',
'webrtcIceUdpDisable'
].concat(extraConfigWhitelist);
| JavaScript | 0 | @@ -4307,16 +4307,50 @@
oMenu',%0A
+ 'roomPasswordNumberOfDigits',%0A
'res
|
ad523ca3a3e653b2879f0b0a98ff94fdcf896bbd | remove the dragClass after a drop event | filereader.js | filereader.js | /*
filereader.js - a lightweight wrapper for common FileReader usage.
Open source code under MIT license: http://www.opensource.org/licenses/mit-license.php
Author: Brian Grinstead
See http://dev.w3.org/2006/webapi/FileAPI/#FileReader-interface for basic information
See http://dev.w3.org/2006/webapi/FileAPI/#event-summary for details on Options/on.* callbacks
Usage:
FileReaderJS.setupInput(input, opts);
FileReaderJS.setupDrop(element, opts);
Options:
readAs: 'ArrayBuffer' | 'BinaryString' | 'Text' | 'DataURL' (default)
accept: A regex string to match the contenttype of a given file.
For example: 'image/*' to only accept images.
on.skip will be called when a file does not match the filter.
dragClass: A CSS class to add onto the element called with setupDrop while dragging
on:
loadstart: function(e) { }
progress: function(e) { }
load: function(e) { }
abort: function(e) { }
error: function(e) { }
loadend: function(e) { }
skip: function(file) { } Called only when a read has been skipped because of the accept string
*/
(function(global) {
var FileReader = global.FileReader;
var FileReaderJS = global.FileReaderJS = {
enabled: false,
opts: {
readAs: 'DataURL',
dragClass: false,
accept: false,
on: {
loadstart: noop,
progress: noop,
load: noop,
abort: noop,
error: noop,
loadend: noop,
skip: noop
}
}
};
if (!FileReader) {
// Not all browsers support the FileReader interface. Return with the enabled bit = false
return;
}
FileReaderJS.enabled = true;
FileReaderJS.setupInput = setupInput;
FileReaderJS.setupDrop = setupDrop;
var fileReaderEvents = ['loadstart', 'progress', 'load', 'abort', 'error', 'loadend'];
function setupInput(input, opts) {
var instanceOptions = extend(extend({}, FileReaderJS.opts), opts);
input.addEventListener("change", inputChange, false);
function inputChange(e) {
handleFiles(e.target.files, instanceOptions);
}
}
function setupDrop(dropbox, opts) {
var instanceOptions = extend(extend({}, FileReaderJS.opts), opts),
dragClass = opts.dragClass;
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragleave", dragleave, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);
function drop(e) {
e.stopPropagation();
e.preventDefault();
handleFiles(e.dataTransfer.files, instanceOptions);
}
function dragenter(e) {
if (dragClass) {
addClass(dropbox, dragClass);
}
e.stopPropagation();
e.preventDefault();
}
function dragleave(e) {
if (dragClass) {
removeClass(dropbox, dragClass);
}
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
}
function handleFiles(files, opts) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (opts.accept && !file.type.match(new RegExp(opts.accept))) {
opts.on.skip(file);
continue;
}
var reader = new FileReader();
for (var j = 0; j < fileReaderEvents.length; j++) {
reader['on' + fileReaderEvents[j]] = opts.on[fileReaderEvents[j]];
}
reader['readAs' + opts.readAs](files[i]);
}
}
// noop - A function that does nothing
function noop() {
}
// extend - used to make deep copies of options object
function extend(destination, source) {
for (var property in source) {
if (source[property] && source[property].constructor &&
source[property].constructor === Object) {
destination[property] = destination[property] || {};
arguments.callee(destination[property], source[property]);
}
else {
destination[property] = source[property];
}
}
return destination;
}
// add/remove/has Class: basic class manipulation for drop zone
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
})(this);
| JavaScript | 0.000001 | @@ -2487,16 +2487,81 @@
ult();%0D%0A
+%09%09%09if (dragClass) %7B%0D%0A%09%09%09%09removeClass(dropbox, dragClass);%0D%0A%09%09%09%7D%0D%0A
%09%09%09handl
|
d82177e74b02733a9f5f4a38420a81c7b8a11444 | fix redis connect to 127.0.0.1 some cases | service/src/utils/redis.js | service/src/utils/redis.js | var redis = require('redis'),
config = require('../config'),
logger = require('./winston').appLogger;
module.exports = function (server) {
var client;
if(server.resMgr && (client = server.resMgr.get('redis'))){
return client;
}
var redisOpts = {
host: config.redis.host,
port: config.redis.port,
retry_strategy: function (options) {
if (options.error && options.error.code === 'ECONNREFUSED') {
// End reconnecting on a specific error and flush all commands with a individual error
return new Error('The server refused the connection');
}
if (options.total_retry_time > 1000 * 60 * 60) {
// End reconnecting after a specific timeout and flush all commands with a individual error
return new Error('Retry time exhausted');
}
if (options.times_connected > 10) {
// End reconnecting with built in error
return undefined;
}
// reconnect after
return Math.min(options.attempt * 100, 3000);
}
};
if(config.redis.password){
redisOpts.password = config.redis.password;
}
client = redis.createClient(redisOpts);
client.on('error', function(err){
logger.error('Redis Error: ' + err);
});
server.resMgr.add('redis', client, function(){
client.quit();
logger.info('Redis client quit');
})
}; | JavaScript | 0.000001 | @@ -1490,11 +1490,31 @@
;%0A %7D)
+;%0A return client;
%0A%7D;
|
496dac3f7de8e3e919cf6056c2a0c150b7ac70f2 | Fix the upload file path | bs-config.js | bs-config.js | var proxyMiddleware = require('http-proxy-middleware');
module.exports = {
port: 3000,
open: false,
files: ["./dist/**/*.{html,css,js,less}"],
server: {
baseDir: './dist',
routes: {
'/upload': '../output'
},
middleware: {
1: proxyMiddleware('/api', {
target: 'http://localhost:5000',
changeOrigin: true // for vhosted sites, changes host header to match to target's host
})
}
}
};
| JavaScript | 0 | @@ -217,14 +217,22 @@
'../
-output
+testenv/upload
'%0A
|
bf8711353f6b2da76c72d69f6c30a096b8d790d8 | Change multiformset.js to just define a function. pages need to call it to setup multiformset | multiformset/static/multiformset.js | multiformset/static/multiformset.js | $(function() {
var $chooser = $('#multiformset-form_chooser');
$(".form_template").each(function(idx, el) {
var $el = $(el);
$chooser.append($("<option></option>")
.attr("value", $el.attr('data-form-class'))
.text($el.attr('data-form-class')));
});
$("#multiformset-add_form").click(function(evt) {
// don't submit if this input happens to be within the form
evt.preventDefault();
// update total form count
var form_name = $chooser.val();
var $total_forms = $("#id_" + form_name + "-TOTAL_FORMS");
var qty = parseInt($total_forms.val());
$total_forms.val(qty + 1);
// copy the template and replace prefixes with the correct index
var html = $("#" + form_name + "-form_template").clone().html().replace(/__prefix__/g, qty);
$("#multiformset-new_forms").append(html);
});
}); | JavaScript | 0.000001 | @@ -1,14 +1,12 @@
-$(
function
() %7B
@@ -5,87 +5,505 @@
tion
-(
+ multiformset( options
) %7B%0A
+%0A
-var $chooser = $('#multiformset-form_chooser'
+// Create some defaults, extending them with any options that were provided%0A var settings = $.extend( %7B%0A 'template_selector' : '.form_template',%0A 'add_form_selector' : '#multiformset-add_form',%0A 'new_form_parent' : '#multiformset-new_forms',%0A 'template_value_attr': 'data-form-class',%0A 'template_text_attr': 'data-form-class'%0A%0A %7D, options
);%0A
+%0A
-$(%22.form_template%22
+var $chooser = $(settings.add_form_selector);%0A $(settings.template_selector
).ea
@@ -641,33 +641,44 @@
el.attr(
-'data-form-class'
+settings.template_value_attr
))%0A
@@ -703,33 +703,43 @@
el.attr(
-'data-form-class'
+settings.template_text_attr
)));%0A
@@ -753,32 +753,34 @@
$(
-%22#multi
+settings.add_
form
+_
se
-t-add_form%22
+lector
).cl
@@ -1312,31 +1312,25 @@
$(
-%22#multiformset-
+settings.
new_form
s%22).
@@ -1329,10 +1329,15 @@
form
-s%22
+_parent
).ap
@@ -1356,11 +1356,10 @@
%7D);%0A
+%0A
%7D
-);
|
666db67db42bc0dd668e12db8a8fe64af2e5567f | Remove logic for storing player ID locally | app/scripts/components/dashboard.js | app/scripts/components/dashboard.js | import m from 'mithril';
// The area of the game UI consisting of game UI controls and status messages
class DashboardComponent {
oninit({ attrs: { game, session } }) {
this.game = game;
this.session = session;
}
// Prepare game players by creating new players (if necessary) and deciding
// which player has the starting move
setPlayers(humanPlayerCount) {
if (this.game.players.length > 0) {
// Reset new games before choosing number of players (no need to reset
// the very first game)
this.game.resetGame();
}
this.game.setPlayers(humanPlayerCount);
}
startGame(newStartingPlayer) {
this.game.startGame({
startingPlayer: newStartingPlayer
});
}
endGame() {
this.game.endGame();
}
promptForPlayerName() {
this.currentPlayerName = null;
}
setOnlinePlayerName(inputEvent) {
this.currentPlayerName = inputEvent.target.value;
inputEvent.redraw = false;
}
startOnlineGame(submitEvent) {
console.log('start online game!', this);
submitEvent.preventDefault();
this.connectingToServer = true;
this.session.connect();
this.session.on('connect', () => {
this.connectingToServer = false;
this.waitingForOtherPlayer = true;
this.game.setPlayers(2);
this.game.players[0].name = this.currentPlayerName;
m.redraw();
// Request a new room and retrieve the room code returned from the server
this.session.emit('new-room', { firstPlayer: this.game.players[0] }, ({ room }) => {
console.log(room);
var playerIds = JSON.parse(localStorage.getItem('c4-player-ids'));
playerIds[room.code] = 0;
localStorage.setItem('c4-player-ids', JSON.stringify(playerIds));
});
});
}
view() {
return m('div#game-dashboard', [
m('p#game-message',
// If the current player needs to enter a name
this.currentPlayerName === null ?
'Enter your player name:' :
this.waitingForOtherPlayer ?
'Waiting for other player...' :
this.connectingToServer ?
'Connecting to server...' :
// If user has not started any game yet
this.game.players.length === 0 ?
'Welcome! How many players?' :
// If a game is in progress
this.game.currentPlayer ?
this.game.currentPlayer.name + ', your turn!' :
// If a player wins the game
this.game.winner ?
this.game.winner.name + ' wins! Play again?' :
// If the grid is completely full
this.game.grid.checkIfFull() ?
'We\'ll call it a draw! Play again?' :
// If the user just chose a number of players for the game to be started
!this.waitingForOtherPlayer && this.game.humanPlayerCount !== null ?
'Which player should start first?' :
// Otherwise, if game was ended manually by the user
'Game ended. Play again?'
),
// If game is in progress, allow user to end game at any time
this.game.inProgress ? [
m('button', { onclick: () => this.endGame() }, 'End Game')
] :
this.currentPlayerName === null ? [
m('form', {
onsubmit: (submitEvent) => this.startOnlineGame(submitEvent)
}, [
m('input[type=text]#current-player-name', {
name: 'current-player-name',
autofocus: true,
oninput: (inputEvent) => this.setOnlinePlayerName(inputEvent)
}),
m('button[type=submit]', 'Start Game')
])
] :
!this.connectingToServer && !this.waitingForOtherPlayer ? [
// If number of players has been chosen, ask user to choose starting player
this.game.humanPlayerCount !== null ?
this.game.players.map((player) => {
return m('button', {
onclick: () => this.startGame(player)
}, player.name);
}) :
// Select a number of human players
[
m('button', {
onclick: () => this.setPlayers(1)
}, '1 Player'),
m('button', {
onclick: () => this.setPlayers(2)
}, '2 Players'),
m('button', {
onclick: () => this.promptForPlayerName()
}, 'Online')
]
] : null
]);
}
}
export default DashboardComponent;
| JavaScript | 0.000001 | @@ -1548,195 +1548,24 @@
log(
-room);%0A var playerIds = JSON.parse(localStorage.getItem('c4-player-ids'));%0A playerIds%5Broom.code%5D = 0;%0A localStorage.setItem('c4-player-ids', JSON.stringify(playerIds)
+'new room', room
);%0A
|
9129d9d69a2d040c0bb4ea6ad6fb5049b14e74fa | Enable storage provisioning for portal mode. | app/scripts/configs/modes/portal.js | app/scripts/configs/modes/portal.js | 'use strict';
angular.module('ncsaas')
.constant('MODE', {
modeName: 'modePortal',
toBeFeatures: [
'localSignup',
'localSignin',
'password',
'people',
'compare',
'templates',
'sizing',
'projectGroups',
'apps',
'premiumSupport'
],
featuresVisible: false,
appStoreCategories: [
{
name: 'Virtual machines',
type: 'provider',
icon: 'desktop',
services: ['Amazon', 'DigitalOcean', 'OpenStack']
}
],
serviceCategories: [
{
name: 'Virtual machines',
services: ['Amazon', 'DigitalOcean', 'OpenStack'],
}
],
futureCategories: [
'support',
'apps',
]
});
| JavaScript | 0 | @@ -503,16 +503,142 @@
Stack'%5D%0A
+ %7D,%0A %7B%0A name: 'Storages',%0A type: 'provider',%0A key: 'storages',%0A services: %5B'OpenStack'%5D%0A
%7D%0A
|
2b8eeb02f55ec27c0be03a8031b678845629375f | Decrease the slerp increment for dramatic effect | adapters/camera.js | adapters/camera.js | var THREE = require('three'),
raf = require('raf-component');
module.exports = function camera (cam) {
var cameraPosition = cam.position.clone(),
cameraLookAt = new THREE.Vector3(0, 20000, 0);
update();
return {
moveCamera: function (x, y, z) {
cameraPosition.set(x, y, z);
},
lookTo: function (x, y, z) {
cameraLookAt.set(x, y, z);
}
};
function update () {
raf(update);
cam.position.lerp(cameraPosition, 0.01);
var targetMat = new THREE.Matrix4();
targetMat.lookAt(cam.position, cameraLookAt, cam.up);
var targetQuat = new THREE.Quaternion();
targetQuat.setFromRotationMatrix(targetMat);
cam.quaternion.slerp(targetQuat, 0.07);
}
};
| JavaScript | 0.000147 | @@ -705,9 +705,9 @@
0.0
-7
+1
);%0A
|
e37a7764c102632442f53e2ee94c5962a6be279c | fix first sign in | app/scripts/services/cockpit.api.js | app/scripts/services/cockpit.api.js | 'use strict';
/**
* @ngdoc service
* @name blimpCockpitApp.cockpit.api
* @description
* # cockpit.api
* Service in the blimpCockpitApp.
*/
angular.module('blimpCockpitApp')
.factory('cockpitApi', ['$resource', '$http', '$q', '$rootScope', '$state', '$localstorage',
function ($resource, $http, $q, $rootScope, $state, $localstorage) {
var localStorageUserKey = 'cloudfleet.cockpit.currentUser';
var storeCurrentUser = function(user)
{
$localstorage.setObject(localStorageUserKey, user);
};
var clearCurrentUser = function()
{
$localstorage.getObject(localStorageUserKey, null);
};
var service = {
getCurrentUser: function()
{
return $localstorage.getObject(localStorageUserKey);
},
login: function (username, password) {
console.log('logging in user ' + username)
var deferred = $q.defer();
$http.post('/musterroll/login', {
'username': username,
'password': password
}).
success(function () {
$http.get('/musterroll/api/v1/currentUser').
success(function(data){
storeCurrentUser(data);
deferred.resolve(data);
}).
error(function () {
deferred.resolve(false);
});
}).
error(function () {
deferred.resolve(false);
});
return deferred.promise;
},
logOut: function(){
var deferred = $q.defer();
$http.get('/musterroll/logout').
success(function (data) {
clearCurrentUser();
deferred.resolve(data);
}).
error(function (_, status) {
deferred.resolve(status);
});
return deferred.promise;
},
loadCurrentUser: function () {
var deferred = $q.defer();
deferred.resolve(status);
$http.get('/musterroll/api/v1/currentUser').
success(function (data) {
storeCurrentUser(data);
deferred.resolve(data);
}).
error(function (_, status) {
clearCurrentUser();
deferred.resolve(null);
});
return deferred.promise;
}
};
return service;
}]);
| JavaScript | 0.000002 | @@ -779,16 +779,22 @@
UserKey)
+ %7C%7C %7B%7D
;%0A
|
92cdadbcee676575da8e7d47282640747495c436 | Set Config JSON | PublicGallery/arcgis_item/configJSON.js | PublicGallery/arcgis_item/configJSON.js | {
"configurationSettings":[
{
"category":"<b>Site Information</b>",
"fields":[
{
"type":"string",
"fieldName":"group",
"label":"Group ID:",
"tooltip":"ID of the group. Either set this or both the groupOwner and groupTitle.",
"placeHolder":""
},
{
"type":"string",
"fieldName":"groupTitle",
"label":"Group Title:",
"tooltip":"Title of the group. Should be set along with groupOwner.",
"placeHolder":""
},
{
"type":"string",
"fieldName":"groupOwner",
"label":"Group Owner:",
"tooltip":"The owner of the group. Should be set along with groupTitle.",
"placeHolder":""
},
{
"type":"string",
"fieldName":"siteTitle",
"label":"Website Title:",
"tooltip":"The title of this template's website.",
"placeHolder":"My Gallery"
},
{
"type":"string",
"fieldName":"siteBannerImage",
"tooltip":"URL for the navigation header logo image. If empty, Site Title text is used.",
"placeHolder":"URL to image:",
"label":"Logo on top navigation."
},
{
"type":"string",
"fieldName":"addThisProfileId",
"label":"Addthis profile Id:",
"tooltip":"Account ID for AddThis.com.",
"placeHolder":"xa-4f3bf72958320e9e"
}
]
},
{
"category":"<b>Home page Settings</b>",
"fields":[
{
"type":"string",
"fieldName":"homeSideHeading",
"label":"Homepage side heading:",
"tooltip":"Heading displayed within the side panel on the index page.",
"placeHolder":""
}
]
},
{
"category":"<b>Footer Settings</b>",
"fields":[
{
"type":"string",
"fieldName":"footerHeading",
"label":"Footer heading:",
"tooltip":"Heading displayed in the footer.",
"placeHolder":""
},
{
"type":"paragraph",
"fieldName":"footerDescription",
"label":"Footer content:",
"tooltip":"Content description displayed in the footer.",
"placeHolder":""
}
]
},
{
"category":"<b>General Settings</b>",
"fields":[
{
"type":"string",
"fieldName":"theme",
"tooltip":"Color theme to use.",
"label":"Color Theme:",
"options":[
{
"label":"Blue",
"value":"blueTheme"
},
{
"label":"Red",
"value":"redTheme"
},
{
"label":"Green",
"value":"greenTheme"
}
]
},
{
"type":"string",
"fieldName":"defaultLayout",
"tooltip":"Specify to use Grid view or List view.",
"label":"Default layout to use:",
"options":[
{
"label":"Grid",
"value":"grid"
},
{
"label":"List",
"value":"list"
}
]
},
{
"type":"string",
"fieldName":"sortField",
"tooltip":"Field to sort the group items by.",
"label":"Group Sort Field:",
"options":[
{
"label":"Created Date",
"value":"created"
},
{
"label":"Title",
"value":"title"
},
{
"label":"Type",
"value":"type"
},
{
"label":"Owner",
"value":"owner"
},
{
"label":"Average rating",
"value":"avgRating"
},
{
"label":"Number of ratings",
"value":"numRatings"
},
{
"label":"Number of comments",
"value":"numComments"
},
{
"label":"Number of views",
"value":"numViews"
}
]
},
{
"type":"string",
"fieldName":"sortOrder",
"tooltip":"Ordering of the sorting field.",
"label":"Sort order:",
"options":[
{
"label":"Descending",
"value":"desc"
},
{
"label":"Ascending",
"value":"asc"
}
]
},
{
"type":"string",
"fieldName":"mapViewer",
"tooltip":"Open maps in this viewer.",
"label":"Open maps in:",
"options":[
{
"label":"Simple Viewer",
"value":"simple"
},
{
"label":"ArcGIS Explorer Online",
"value":"explorer"
},
{
"label":"ArcGIS Explorer Online Presentation Mode",
"value":"explorer_present"
},
{
"label":"ArcGIS Online",
"value":"arcgis"
}
]
},
{
"type":"string",
"fieldName":"galleryItemsPerPage",
"tooltip":"Gallery items to show per page.",
"label":"Items per page:",
"options":[
{
"label":"3",
"value":3
},
{
"label":"6",
"value":6
},
{
"label":"9",
"value":9
},
{
"label":"12",
"value":12
},
{
"label":"15",
"value":15
}
]
}
]
}
],
"values":{
"theme":"blueTheme",
"addThisProfileId":"xa-4f3bf72958320e9e",
"defaultLayout":"grid",
"sortField":"created",
"sortOrder":"desc",
"mapViewer":"simple",
"galleryItemsPerPage":9
}
} | JavaScript | 0.000003 | @@ -1402,21 +1402,38 @@
r%22:%22
-URL to image:
+http://www.mysite.com/logo.png
%22,%0D%0A
@@ -1460,31 +1460,20 @@
l%22:%22
-Logo on top navigation.
+Banner Logo:
%22%0D%0A
@@ -1614,14 +1614,18 @@
%22Add
-this p
+This.com P
rofi
@@ -1992,14 +1992,14 @@
age
-s
+S
ide
-h
+H
eadi
@@ -2364,17 +2364,17 @@
%22Footer
-h
+H
eading:%22
@@ -2618,17 +2618,17 @@
%22Footer
-c
+C
ontent:%22
@@ -3579,23 +3579,23 @@
p%22:%22
-Specify
+Whether
to use
Grid
@@ -3590,17 +3590,17 @@
to use
-G
+g
rid view
@@ -3607,17 +3607,17 @@
or
-L
+l
ist view
.%22,%0D
@@ -3612,16 +3612,38 @@
ist view
+ as the default layout
.%22,%0D%0A
@@ -3675,21 +3675,14 @@
ult
-l
+L
ayout
- to use
:%22,%0D
@@ -5390,26 +5390,26 @@
rder
-ing of the sorting
+ to sort the group
fie
@@ -5443,14 +5443,20 @@
l%22:%22
+Group
Sort
-o
+O
rder
@@ -5892,18 +5892,20 @@
en maps
-in
+with
this vi
@@ -5946,15 +5946,17 @@
pen
-m
+M
aps
-in
+With
:%22,%0D
@@ -6771,21 +6771,21 @@
:%22Items
-per p
+Per P
age:%22,%0D%0A
|
0a218dd28ada00c97cc20825580c9f28e9f15b23 | fix previous commit | test/run.js | test/run.js | 'use strict';
var lib = require('..');
var crypto = require('crypto');
var through2 = require('through2');
describe('run', function() {
afterEach(calls.run);
it('hashes a single file in directory', function() {
var boundary = new lib.Boundary();
var directory = '/' + id('directory');
var buffer = new Buffer(id('buffer'), 'utf8');
var filename = id('filename');
calls('calling boundary.fs.createReadStream', function() {
var fs = boundary.fs;
this.createReadStreamSpy = stub(fs, 'createReadStream', function() {
var stream = through2();
stream.end(buffer);
return stream;
});
}, function() {
var path = directory + '/' + filename;
expect(this.createReadStreamSpy).to.have.been.calledOnce;
expect(this.createReadStreamSpy)
.to.have.been.calledWithExactly(path);
});
calls('calling boundary.fs.readDirectory', function() {
this.readDirectorySpy = stub(boundary.fs, 'readDirectory', function() {
return Promise.resolve(['.', '..', filename]);
});
}, function() {
expect(this.readDirectorySpy).to.have.been.calledOnce;
expect(this.readDirectorySpy)
.to.have.been.calledWithExactly(directory);
});
boundary.argv = [directory];
boundary.stdout = through2();
var hash = crypto.createHash('sha512');
hash.update(buffer);
hash = hash.digest('hex');
return Promise
.resolve(lib.run(boundary))
.then(function() {
return lib.pumpAndConcat(boundary, [boundary.stdout]);
})
.then(function(output) {
expect(output.toString('utf8'))
.to.equal(hash + ' /' + filename + '\n');
});
});
});
| JavaScript | 0.000001 | @@ -387,32 +387,24 @@
%0A calls('
-calling
boundary.fs.
@@ -872,16 +872,8 @@
ls('
-calling
boun
|
9e2988c2ce3c2d0739d588eb5c2d1b503983db1b | Remove unused and improperly updated state variabel | src/app/App.js | src/app/App.js | import React from "react";
import Header from "./components/Header";
import View from "./views";
import Footer from "./components/Footer";
import PlayQueue from "./components/PlayQueue";
import {Notifications, Notification} from "./components/Notifications";
import Socket from "./libs/Socket";
import Api from "./libs/Api";
import Spotify from "./libs/Spotify";
import Settings from "./components/Settings";
import {BrowserRouter, Switch, Route} from "react-router-dom";
import Kiosk from "./views/Kiosk";
class App extends React.Component {
state = {
playState: {
playing: true,
shuffled: false,
phone: false
},
volume: 70,
progress: 0,
queue: [],
queueRaw: [],
connected: true,
settings: false,
idleMode: true,
idleTimeout: null
};
componentWillMount() {
if (Socket && Socket.on) {
Socket.on("playState", (playState) => this.setState({playState: playState}));
Socket.on("volume", (volume) => this.setState({volume: volume}));
Socket.on("token", (token) => Spotify.setAccessToken(token));
Socket.on("seek", (seek) => this.setState({progress: seek}));
Socket.on("queue", (queue) => this.loadTracks(queue.map((item) => ({id: item[0], uuid: item[1], source: item[2]}))));
Socket.on("removeTrack", (uuid) => this.setState({queue: this.state.queue.filter((track) => track.uuid !== uuid)}));
Socket.on("notification", (notification) => {
Notifications.add(<Notification {...notification} />)
});
let disconnectNotification;
Socket.on('disconnect', function () {
disconnectNotification = Notifications.add(<Notification text="Connection lost"/>);
});
Socket.on('reconnect', function () {
if (disconnectNotification) {
Notifications.remove(disconnectNotification);
}
});
} else {
//Shit's broken
this.setState({
connected: false
}, () => alert("Couldn't load the socket, please reload the page and try again"));
}
}
onRemoveTrack(uuid) {
let queue = this.state.queue.filter((track) => track.uuid !== uuid);
this.setState({
queue: queue
});
Api.delete('queue/' + uuid);
}
onReorder(order) {
let tracks = {};
this.state.queue.forEach((track) => tracks[track.uuid] = track);
let queue = order.map((uuid) => tracks[uuid]);
this.setState({
queue: queue
});
Api.post("queue/order", {tracks: order})
}
loadTracks(queue) {
this.state.queueRaw = queue;
Spotify.getTracks(queue).then((tracks) => this.setState({
queue: tracks
}));
}
onSettingsClose() {
this.setState({
settings: false
})
}
onSettingsOpen() {
this.setState({
settings: true
})
}
updateIdle() {
if (this.state.idleTimeout) clearTimeout(this.state.idleTimeout);
this.setState({
idleMode: false,
idleTimeout: setTimeout(this.startIdleMode.bind(this), 5000)
})
}
startIdleMode() {
this.setState({
idleMode: true,
idleTimeout: null
})
}
render() {
return (
<BrowserRouter>
<div onClick={this.updateIdle.bind(this)} onTouchMove={this.updateIdle.bind(this)} onMouseMove={this.updateIdle.bind(this)}>
<Notifications/>
<Switch>
<Route path="/kiosk">
<div>
<Kiosk queue={this.state.queue} idleMode={this.state.idleMode} progress={this.state.progress}/>
<Footer currentTrack={this.state.queue[0]}
progress={this.state.progress}
volume={this.state.volume}
playState={this.state.playState}
kioskMode={true}
idleMode={this.state.idleMode}
/>
</div>
</Route>
<Route path="/">
<div>
<Header onSettingsOpen={this.onSettingsOpen.bind(this)}/>
<View queue={this.state.queue} progress={this.state.progress}/>
<PlayQueue queue={this.state.queue}
onRemoveTrack={this.onRemoveTrack.bind(this)}
onReorder={this.onReorder.bind(this)}/>
<Footer currentTrack={this.state.queue[0]}
progress={this.state.progress}
volume={this.state.volume}
playState={this.state.playState}
/>
<Settings active={this.state.settings}
onClose={this.onSettingsClose.bind(this)}/>
</div>
</Route>
</Switch>
</div>
</BrowserRouter>
);
}
}
export default App;
| JavaScript | 0 | @@ -729,30 +729,8 @@
%5B%5D,%0A
- queueRaw: %5B%5D,%0A
@@ -2765,46 +2765,8 @@
) %7B%0A
- this.state.queueRaw = queue;%0A%0A
|
7a3f8e56b87d4c544258b66b6520b58907f8ea43 | Fix sound on iOS | client/client.js | client/client.js | Template.view.helpers({
isLogged: ()=> !Session.get('authorization') ? false : true
})
let boardData;
Template.board.helpers({
rows: function () {
let room;
if (location.pathname.split('/')[1] === 'rooms')
room = Rooms.findOne({_id: location.pathname.split('/')[location.pathname.split('/').length - 1]});
else room = Rooms.findOne();
if (!room)
return false;
if (!boardData) {
boardData = [];
for (let y = 0; y < room.board.height ; y++) {
let row = [];
for (let x = 0; x < room.board.width; x++) {
row.push(cell(x, y));
}
boardData.push(row)
}
}
room.partition.forEach(function (cell) {
boardData[cell.y][cell.x] = cell;
});
setNotes();
return boardData;
}
});
Template.controls.helpers({
players: function() {
var count = Connections.find().count();
if (count > 1) {
return count+" players";
}
return count+" player";
}
});
Template.login.helpers({
random_color: function() {
var colors = [];
for (color in COLOR_VALUES) {
colors.push({
name: color,
code: COLOR_VALUES[color]
});
}
return colors[parseInt(Math.random() * (colors.length))];
}
});
Template.login.events({
'submit #login-form': event => {
event.preventDefault();
const surname = event.target.surname.value;
const color = event.target.color.value;
const roomId = Rooms.findOne()._id;
Meteor.call('addUser', roomId, { surname, color});
Session.setPersistent('authorization', "true");
Session.setPersistent('surname', surname);
Session.setPersistent('color', color);
return false;
}
});
Template.board.events({
'click td': function (event, template) {
let x = $(event.target).data('x');
let y = $(event.target).data('y');
let room = Rooms.findOne();
boardData[y][x].color = Session.get('color');
boardData[y][x].i = !boardData[y][x].i;
Meteor.call('addNote', room._id, boardData[y][x]);
},
});
Template.controls.events({
'click #play': function (event, template) {
togglePlay();
}
});
Meteor.startup( function() {
var Instrument = function() {
}
Instrument.prototype = {
getWad: function() {
return new Wad({source : 'sine'});
},
playNote: function(frequency) {
var wad = this.getWad()
var duration = noteDuration()
wad.play({
pitch : frequency, // A4 is 440 hertz.
env : {
decay: duration / 1000 * .1,
hold: duration / 1000 * 1.1,
release: duration / 1000 * .75
},
reverb: {
wet: 1
}
});
}
}
instrument = new Instrument();
});
// client code: ping heartbeat every 5 seconds
Meteor.setInterval(function () {
Meteor.call('keepalive', Meteor.userId());
}, 5000);
function cell(x, y, userId) {
return {
x: x || 0,
y: y || 0,
frequency: 200,
title: 200,
timestamp: new Date(),
userId: userId || '',
i: false,
}
}
let togglePlay = (function() {
let handler = -1;
return function() {
if (handler === -1) {
handler = setInterval(function () {
play();
}, noteDuration());
} else {
clearInterval(handler);
handler = -1;
}
}
})();
function play () {
let room = Rooms.findOne();
if (cursor >= room.board.width) {
cursor = 0;
}
$('td').removeClass('p p1 p2');
for(let y = 0; y < room.board.height; y++) {
let cell = boardData[y][cursor];
if (cell.i) {
$(`td[data-x="${cursor}"][data-y="${y}"]`).toggleClass('p');
// cell.p = true;
// visualEffect(cell);
instrument.playNote(cell.frequency);
}
}
cursor++;
}
function noteDuration() {
return 60 / Rooms.findOne().tempo * 1000 / 4;
}
var cursor = 0;
// Calculate note from base and interval
function calcNote(base,interval) {
return Math.round(base * Math.pow(2,interval/12)*100)/100;
}
// Get 'max' notes of 'scale' from 'base'
function getScaleNotes(scale,base,max) {
interval = 0;
ni = 0;
notes = new Array();
ints = new Array();
for(n = 0; n < max; n++) {
note = calcNote(base,interval);
interval = interval + scale[ni];
ints[n] = scale[ni];
notes[n] = note;
ni++;
if (ni >= scale.length) ni = 0;
}
return notes;
}
// Each cell get its note
function setNotes() {
var base = 260;
var board_height = Rooms.findOne().board.height;
var board_width = Rooms.findOne().board.width;
var notes = getScaleNotes(SCALE_VALUES.MAJOR, base, board_height);
for(x = 0; x < board_width; x++) {
for(y = 0; y < board_height; y++) {
boardData[x][y].frequency = notes[board_height-x-1];
boardData[x][y].title = notes[board_height-x-1];
}
}
}
| JavaScript | 0.000004 | @@ -2126,16 +2126,79 @@
Play();%0A
+ instrument.playNote(1); // Hack to fix sound in Safari iOS%0A
%7D%0A%7D);%0A
|
c0705a4230bfe726d99e2ae6fc9db52c7345cf25 | Add I should by @dmsinger Pull request could not be automatically merged due to conflicts. | src/Warnings.js | src/Warnings.js | var WARNINGS = {
warnings: [
{ keyword: 'just',
source: 'http://www.taramohr.com/8-ways-women-undermine-themselves-with-their-words/',
message: '"Just" demeans what you have to say. "Just" shrinks your power. ' +
'It\'s time to say goodbye to the justs. --Tara Sophia Mohr', },
{ keyword: 'actually',
source: 'http://www.taramohr.com/8-ways-women-undermine-themselves-with-their-words/',
message: '"Actually" communicates a sense of surprise that you have ' +
'something to say. Of course you want to add something. Of ' +
'course you have questions. There\'s nothing surprising about ' +
'it. --Tara Sophia Mohr', },
{ keyword: 'sorry',
source: 'http://www.fastcompany.com/3032112/strong-female-lead/sorry-not-sorry-why-women-need-to-stop-apologizing-for-everything',
message: 'Using "sorry" frequently undermines your gravitas and makes you ' +
'appear unfit for leadership. --Sylvia Ann Hewlett', },
{ keyword: 'apologize',
source: 'http://www.fastcompany.com/3032112/strong-female-lead/sorry-not-sorry-why-women-need-to-stop-apologizing-for-everything',
message: 'Apologizing unnecessarily puts you in a subservient position and ' +
'makes people lose respect for you --Bonnie Marcus', },
{ keyword: 'I think',
source: 'http://www.fastcompany.com/3049609/the-future-of-work/4-types-of-useless-phrases-you-need-to-eliminate-from-your-emails',
message: '"I think" undermines your idea and displays an overall lack of ' +
'self-confidence. --Lydia Dishman', },
{ keyword: 'I\'m no expert',
source: 'http://www.fastcompany.com/3049609/the-future-of-work/4-types-of-useless-phrases-you-need-to-eliminate-from-your-emails',
message: '"I\'m no expert" undermines your idea and displays an overall ' +
'lack of self-confidence. --Lydia Dishman', },
{ keyword: 'does that make sense',
source: 'http://goop.com/how-women-undermine-themselves-with-words/',
message: '"does that make sense" comes across either as condescending ' +
'(like your audience can\'t understand) or it implies you feel ' +
'you\'ve been incoherent. A better way to close is something like ' +
'"I look forward to hearing your thoughts." You can leave it up ' +
'to the other party to let you know if they are confused about ' +
'something, rather than implying that you "didn\'t make sense." ' +
'--Tara Sophia Mohr', },
{ keyword: 'try|trying',
source: 'http://www.lifehack.org/articles/communication/7-things-not-to-say-and-7-things-to-start-saying.html',
message: '"Do or do not. There is no try." --Yoda' },
],
};
| JavaScript | 0 | @@ -2821,16 +2821,611 @@
oda' %7D,%0A
+ %7B keyword: 'I should',%0A source: 'http://www.lifehack.org/articles/communication/7-things-not-to-say-and-7-things-to-start-saying.html',%0A message: 'The word %22should%22 is inherently negative. %22Should%22 implies a lose: lose ' +%0A 'situation and it%5C's just not conducive to positive outcomes in life. ' +%0A 'It%5C's a form of criticism, and it%5C's best left out of your everyday language. ' +%0A 'Instead of beating yourself up for what you should have done, ' +%0A 'focus on what you have the power to change.' +%0A '-- Zoe B', %7D,%0A
%5D,%0A%7D;%0A
|
7af4a1e72f5904d5535b8b3eba572107ca610247 | Fix the router. | src/owl.Router.js | src/owl.Router.js | (function(window, owl) {
function Router(routes, defaultRoute, controller){
var that = this;
this.routes = [];
this.defaultRoute = defaultRoute || ({
callback: function() {
console.log('Default route is not defined');
}
});
this.controller = controller;
if (routes instanceof Array) {
routes.forEach(function(route) {
that.addRoute(route);
});
}
}
Router.prototype = {
/**
* Opens page by path
* @param path
*/
open: function(path) {
var route = this.getRoute(path);
if (!route) {
return;
}
if (this.resolve(route)) {
this.run(path, route);
}
},
/**
* Calls resolve callback
* @param route
* @returns {boolean}
*/
resolve: function(route) {
var resolves = route.resolves;
if (resolves && resolves.length) {
return resolves.every(function(resolve) {
var callback = owl.history.getResolve(resolve);
if(callback) {
return callback();
} else {
console.info('Resolve' + resolve + 'is not found');
return true;
}
});
}
return true
},
/**
* Runs the route
* @param path
* @param route
*/
run: function(path, route) {
var match,
controller,
controllerName,
i,
params = {};
if (route.regexp) {
match = path.match(route.regexp);
if (match) {
for (i = 1; i < match.length; i++) {
params[route.params[i - 1]] = match[i];
}
}
}
if (route.action && (route.controller || this.controller)) {
controllerName = route.controller || this.controller;
controller = owl.require(controllerName);
if(controller[route.action]) {
controller[route.action](params);
} else {
console.info('Action ' + route.action + ' is missing');
}
} else if(route.callback) {
route.callback(params);
} else {
console.error('Either controller.action and collback are missing');
}
},
/**
* Adds a route
* @param route
*/
addRoute: function(route) {
var paramRegexp = /:[a-zA-Z0-9]*/g,
pattern = route.path.replace(paramRegexp, '([^/]*)'),
match = route.path.match(paramRegexp),
params = {};
route.regexp = new RegExp('^' + pattern + '$');
if (match) {
params = match.map(function(param) {
return param.substring(1);
});
}
route.params = params;
this.routes.push(route);
},
/**
* Returns the route by path
* @param path
* @returns {Object}
*/
getRoute: function(path) {
var that = this,
route;
this.routes.forEach(function(currentRoute) {
var test = currentRoute.regexp.test(path);
if(test) {
route = currentRoute;
return true;
}
return false;
});
if (route) {
return route;
} else {
return this.defaultRoute;
}
},
/**
* Sets default route
* @param route
*/
setDefaultRoute: function(route) {
this.defaultRoute = route;
},
/**
* Gets default route
* @returns {Function}
*/
getDefaultRoute: function() {
return this.defaultRoute;
},
/**
* Sets controller
* @param controller
*/
setController: function(controller) {
this.controller = controller;
},
/**
* Gets default controller
* @returns {*}
*/
getController: function() {
return this.controller;
}
};
owl.Router = Router;
})(window, owl); | JavaScript | 0 | @@ -3018,16 +3018,45 @@
s = %7B%7D;%0A
+ if (match) %7B%0A
@@ -3103,24 +3103,38 @@
ern + '$');%0A
+ %7D%0A
@@ -3583,31 +3583,28 @@
this.routes.
-forEach
+some
(function(cu
@@ -3667,19 +3667,70 @@
gexp
-.test(path)
+ ? currentRoute.regexp.test(path) : currentRoute.path === path
;%0A
|
88928330b60de1b0261722c1c1327f498df1c475 | update demos | demo/main.js | demo/main.js | (function(document, Scrollbar) {
'use strict';
Scrollbar.initAll();
var toggle = document.querySelector('#toggle'),
curSB = document.querySelector('#cur-sb'),
compare = document.querySelector('#compare');
toggle.addEventListener('click', function() {
if (Scrollbar.has(compare)) {
Scrollbar.destroy(compare);
curSB.textContent = 'Native Scrollbar';
} else {
Scrollbar.init(compare);
curSB.textContent = 'Smooth Scrollbar'
}
});
var infinite = Scrollbar.init(document.querySelector('#infinite'));
var x = document.querySelector('#x'),
y = document.querySelector('#y'),
status = document.querySelector('#status');
var createPara = function() {
var p = document.createElement('p');
p.textContent = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam, accusamus laudantium nostrum minima possimus optio voluptates id dignissimos, libero voluptas nesciunt. Consequatur deleniti corporis recusandae nesciunt. Maiores dignissimos praesentium tempore.';
return p;
};
infinite.addListener(function(status) {
var offset = status.offset;
x.textContent = offset.x.toFixed(2);
y.textContent = offset.y.toFixed(2);
});
var count = 0;
infinite.infiniteScroll(function() {
if (count++ > 10) {
status.textContent = 'the end';
} else {
status.textContent = 'loading...';
setTimeout(function() {
status.textContent = 'pending...';
infinite.appendChild(createPara()).appendChild(createPara());
infinite.update();
}, 500);
}
});
})(document, window.Scrollbar);
| JavaScript | 0.000015 | @@ -1341,16 +1341,67 @@
nt = 0;%0A
+ var scrollContent = infinite.getContentElem();%0A
infi
@@ -1673,24 +1673,29 @@
-infinite
+scrollContent
.appendC
@@ -1712,16 +1712,47 @@
ePara())
+;%0A scrollContent
.appendC
@@ -1763,32 +1763,33 @@
(createPara());%0A
+%0A
|
8303037c9033d08a92000560d6ff39010cce7583 | Fix viewport test on travis | test/set.js | test/set.js | 'use strict';
const assert = require('chai').assert;
const express = require('express');
const path = require('path');
const _ = require('lodash');
const navit = require('../');
const auth = require('basic-auth');
describe('Navit.set.*', function () {
let server;
let browser;
before(function (done) {
browser = navit({ prefix: 'http://localhost:17345', engine: process.env.ENGINE });
server = express()
.get('/test/fixtures/set/authentication.html', (req, res, next) => {
let user = auth(req);
if (!user || user.name !== 'john' || user.pass !== 'doe') {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="example"');
res.end('Access denied');
return;
}
next();
})
.use(express.static(path.join(__dirname, '..')))
.get('/test/fixtures/set/headers.html', (req, res) => {
res.send(JSON.stringify(req.headers));
})
.listen(17345, err => {
if (err) return done(err);
// Init phantom before execute first test
browser.run(done);
});
});
it('authentication', function () {
return browser
.set.authentication('john', 'doe')
.open('/test/fixtures/set/authentication.html')
.test.exists('#test-div');
});
it('useragent', function () {
return browser
.set.useragent('test-ua')
.open('/test/fixtures/set/useragent.html')
.test.evaluate(function () {
return window.navigator.userAgent === 'test-ua';
});
});
it.only('zoom', function () {
if (process.env.ENGINE === 'electron') return this.skip();
let size;
return browser
.open('/test/fixtures/set/zoom.html')
.get.evaluate(function () {
return [ window.innerWidth, window.innerHeight ];
}, data => { size = data; })
.set.zoom(0.5)
.get.evaluate(function () {
return [ window.innerWidth, window.innerHeight ];
}, data => assert.deepEqual(data, [ size[0] * 2, size[1] * 2 ]))
.set.zoom(1);
});
it.skip('viewport', function () {
return browser
.open('/test/fixtures/set/viewport.html')
// .set.zoom(1)
.set.viewport(300, 400)
.get.evaluate(function () {
return [ window.innerWidth, window.innerHeight ];
}, data => assert.deepEqual(data, [ 300, 400 ]))
.set.viewport(110, 128)
.get.evaluate(function () {
return [ window.innerWidth, window.innerHeight ];
}, data => assert.deepEqual(data, [ 110, 128 ]));
});
it('cookies', function () {
return browser
.open('/test/fixtures/set/cookies.html')
.set.cookie({
name: 'test',
value: 'cookie',
path: '/test'
})
.get.cookies(cookies => {
let cookie = _.find(cookies, cookie => cookie.name === 'test');
assert.equal(cookie.value, 'cookie');
})
// Remove cookie
.set.cookie({
name: 'test',
path: '/test',
value: 'cookie',
expires: Date.now() - 1000
})
.get.cookies(cookies => assert.equal(cookies.length, 0));
});
it('headers', function () {
return browser
.set.headers({ 'test-header': 'test-value' })
.open('/test/fixtures/set/headers.html')
.test.body(/test-value/);
});
after(function (done) {
server.close();
browser.exit(done);
});
});
| JavaScript | 0.000001 | @@ -1570,13 +1570,8 @@
it
-.only
('zo
@@ -2073,21 +2073,16 @@
);%0A%0A it
-.skip
('viewpo
@@ -2111,32 +2111,164 @@
return browser%0A
+ // Check width only, because heght of electron in Travis-CI%0A // is 25px less, for unknown reasons (local tests pass ok).%0A
.open('/te
@@ -2341,24 +2341,24 @@
iewport(
-300, 400
+641, 481
)%0A
@@ -2485,22 +2485,16 @@
data
-, %5B 300, 400 %5D
+%5B0%5D, 641
))%0A
@@ -2512,24 +2512,24 @@
iewport(
-110, 128
+799, 599
)%0A
@@ -2656,22 +2656,16 @@
data
-, %5B 110, 128 %5D
+%5B0%5D, 799
));%0A
|
6e0c0e485018fc89137ae212005bbe2dde090b3f | Remove old httprequest to state | client/client.js | client/client.js | var url = "https://brew-fridge.herokuapp.com";
//var url = "http://localhost:5000";
var graph = require('./graph.js');
function start() {
$.post(url + "/start", function(data) {});
}
function stop() {
$.post(url + "/stop", function(data) {});
}
$(document).ready(function() {
var photonUrl = "https://api.particle.io/v1/devices/310019000447343337373739/temp"
//var url = "http://localhost:5000";
var data = {
on: true
};
$.get(url + "/state", function(data) {
$(".result").html(data.body);
})
$.get(url + "/data", graph.buildGraph);
$.get(url + "/currentTemp", function(data) {
$(".result").html(data + "\xB0 C er temperaturen nå");
});
$('.startbutton').click(start);
$('.stopbutton').click(stop);
});
| JavaScript | 0 | @@ -441,89 +441,8 @@
%7D;%0A%0A
- $.get(url + %22/state%22, function(data) %7B%0A $(%22.result%22).html(data.body);%0A %7D)%0A%0A
$.
|
0c2ddfde44ccee7a71cd338e3b93ae40439f43d4 | Change the minimum number of ratings needed to show an average in the gallery to just 1. | core/templates/dev/head/components/ratings.js | core/templates/dev/head/components/ratings.js | // Copyright 2014 The Oppia 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.
/**
* @fileoverview Tools for displaying and awarding ratings.
*
* @author Jacob Davis
*/
// A service that maintains a record of which state in the exploration is
// currently active.
oppia.factory('ratingVisibilityService', [function() {
return {
areRatingsShown: function(ratingFrequencies) {
var MINIMUM_ACCEPTABLE_NUMBER_OF_RATINGS = 3;
var totalNumber = 0;
for (var value in ratingFrequencies) {
totalNumber += ratingFrequencies[value];
}
return totalNumber >= MINIMUM_ACCEPTABLE_NUMBER_OF_RATINGS;
}
};
}]);
oppia.directive('ratingFromValue', [function() {
return {
// This will display a star-rating based on the given data. The attributes
// passed in are as follows:
// - isEditable: true or false; whether the rating is user-editable.
// - onEdit: should be supplied iff isEditable is true, and be a function
// that will be supplied with the new rating when the rating is changed.
// - ratingValue: an integer 1-5 giving the rating
restrict: 'E',
scope: {
isEditable: '=',
onEdit: '=',
ratingValue: '='
},
templateUrl: 'rating/fromValue',
controller: ['$scope', function($scope) {
var POSSIBLE_RATINGS = [1, 2, 3, 4, 5];
$scope.stars = POSSIBLE_RATINGS.map(function(starValue) {
return {
cssClass: 'fa-star-o',
value: starValue
};
});
var STATUS_ACTIVE = 'active';
var STATUS_INACTIVE = 'inactive';
var STATUS_RATING_SET = 'rating_set';
$scope.status = STATUS_INACTIVE;
var displayValue = function(ratingValue) {
for (var i = 0; i < $scope.stars.length; i++) {
$scope.stars[i].cssClass = (
ratingValue === undefined ? 'fa-star-o' :
ratingValue < $scope.stars[i].value - 0.75 ? 'fa-star-o' :
ratingValue < $scope.stars[i].value - 0.25 ? 'fa-star-half-o' :
'fa-star');
if ($scope.status === STATUS_ACTIVE &&
ratingValue >= $scope.stars[i].value) {
$scope.stars[i].cssClass += ' oppia-rating-star-active';
}
}
};
displayValue($scope.ratingValue);
$scope.$watch('ratingValue', function() {
displayValue($scope.ratingValue);
});
$scope.clickStar = function(starValue) {
if ($scope.isEditable && $scope.status === STATUS_ACTIVE) {
$scope.status = STATUS_RATING_SET;
$scope.ratingValue = starValue;
displayValue(starValue);
$scope.onEdit(starValue);
}
};
$scope.enterStar = function(starValue) {
if (
$scope.isEditable &&
($scope.status === STATUS_ACTIVE ||
$scope.status === STATUS_INACTIVE)) {
$scope.status = STATUS_ACTIVE;
displayValue(starValue);
}
};
$scope.leaveArea = function() {
$scope.status = STATUS_INACTIVE;
displayValue($scope.ratingValue);
};
$scope.getCursorStyle = function() {
return 'cursor: ' + ($scope.isEditable ? 'pointer' : 'auto');
};
}]
};
}]);
oppia.directive('ratingFromFrequencies', [function() {
return {
restrict: 'E',
scope: {
// A dictionary with keys '1' to '5' giving the number of times each
// rating has been awarded; from this the average rating will be computed
// and displayed.
ratingFrequencies: '&'
},
templateUrl: 'rating/fromFrequencies',
controller: [
'$scope', 'ratingVisibilityService',
function($scope, ratingVisibilityService) {
$scope.computeAverageRating = function(ratingFrequencies) {
if (!ratingVisibilityService.areRatingsShown(ratingFrequencies)) {
return undefined;
} else {
var totalNumber = 0;
var totalValue = 0.0;
for (var value in ratingFrequencies) {
totalValue += value * ratingFrequencies[value];
totalNumber += ratingFrequencies[value];
}
return totalValue / totalNumber;
}
};
$scope.ratingValue = $scope.computeAverageRating(
$scope.ratingFrequencies());
}
]
};
}]);
| JavaScript | 0 | @@ -967,17 +967,17 @@
TINGS =
-3
+1
;%0A%0A
|
d222442bb386e8b9196aca83ac80ad6133cc21f1 | remove facet | caido/app/controller.js | caido/app/controller.js | import Controller from 'cerebral-react-baobab'
const state = {
'synced': {
'live': {
'level': 1,
'systems': []
}
},
'local': {
'selected': {
'uuid': null,
'$system': [
['local', 'selected', 'uuid'],
['synced', 'live', 'systems'],
(uuid, systems) => systems.find(s => s.uuid === uuid)
]
}
}
}
const defaultArgs = {}
const baobabOptions = {
autoCommit: false
}
export default Controller(state, defaultArgs, baobabOptions)
| JavaScript | 0.001807 | @@ -183,23 +183,25 @@
d': null
-,
%0A
+ //
'$syste
@@ -207,24 +207,27 @@
em': %5B%0A
+ //
%5B'local',
@@ -253,16 +253,19 @@
%5D,%0A
+ //
%5B'syn
@@ -295,16 +295,19 @@
%5D,%0A
+ //
(uuid
@@ -360,16 +360,19 @@
d)%0A
+ //
%5D%0A %7D
|
e8df8c3b0e44c26386f790bea31a2372c55b0c9e | update flightplan | flightplan.js | flightplan.js | // To use: fly production
/*global process*/
var plan = require('flightplan')
var url = 'webuy-china.com'
var appName = 'uestcchat'
var configFile = '../uestcchat.config.js'
var username = 'root'
var rsaKey = '/Users/jeff/.ssh/id_rsa'
const now = new Date()
var tmpDir = appName + '-' + now.getFullYear() + '-' + (now.getMonth()+1) + '-' + now.getDate() + '-' + now.getHours()
+ '-' + now.getMinutes() + '-' + now.getSeconds() + '-' + now.getMilliseconds()
plan.target('production', [
{
host: url,
username: username,
privateKey: rsaKey,
agent: process.env.SSH_AUTH_SOCK
}
])
plan.local(function(local) {
local.log('Local side')
var filesToCopy = local.exec('git ls-files', {silent: true})
local.transfer(filesToCopy, '/tmp/' + tmpDir)
})
plan.remote(function(remote) {
remote.log('Server side')
remote.exec('cp -R /tmp/' + tmpDir + ' ~/', {user: username})
remote.rm('-rf /tmp/' + tmpDir)
remote.exec('npm --prefix ~/' + tmpDir + ' install ~/' + tmpDir, {user: username})
remote.exec('ln -snf ~/' + tmpDir + ' ~/' + appName, {user: username})
remote.exec('pm2 delete ' + appName, {user: username, failsafe: true})
remote.exec('cd ~/' + appName + ';pm2 start ' + configFile, {user: username})
})
| JavaScript | 0 | @@ -24,30 +24,13 @@
on%0A%0A
-/*global process*/%0Avar
+const
pla
@@ -60,27 +60,35 @@
')%0A%0A
-var url = 'webuy-ch
+const url = 'shijiba
ina.
@@ -92,19 +92,21 @@
na.com'%0A
-var
+const
appName
@@ -106,16 +106,19 @@
appName
+
= 'uestc
@@ -123,19 +123,21 @@
tcchat'%0A
-var
+const
configF
@@ -167,19 +167,21 @@
fig.js'%0A
-var
+const
usernam
@@ -186,28 +186,34 @@
ame
+
= '
-root'%0Avar
+deploy'%0Aconst
rsaKey
= '/
@@ -208,16 +208,20 @@
rsaKey
+
= '/User
@@ -244,134 +244,249 @@
sa'%0A
+%0A
const
-now = new Date()%0Avar tmpDir = appName + '-' + now.getFullYear() + '-' + (now.getMonth()+1) + '-' + now.getDate() + '-' +
+formatNumber = n =%3E %7B%0A n = n.toString()%0A return n%5B1%5D ? n : '0' + n%0A%7D%0A%0Aconst formatTime = () =%3E %7B%0A const now = new Date()%0A const year = now.getFullYear()%0A const month = now.getMonth() + 1%0A const day = now.getDate()%0A const hour =
now
@@ -500,28 +500,25 @@
rs()
-
%0A
- + '-' +
+const minute =
now
@@ -530,24 +530,33 @@
inutes()
- + '-' +
+%0A const second =
now.get
@@ -568,16 +568,21 @@
ds()
- + '-' +
+%0A const ms =
now
@@ -599,16 +599,203 @@
econds()
+%0A return %5Byear, month, day%5D.map(formatNumber).join('_') %0A + '-' %0A + %5Bhour, minute, second%5D.map(formatNumber).join(':')%0A + '-' + ms%0A%7D%0A%0Aconst tmpDir = appName + '-' + formatTime()
%0A%0Aplan.t
@@ -819,15 +819,10 @@
', %5B
+%7B
%0A
- %7B%0A
ho
@@ -830,18 +830,16 @@
t: url,%0A
-
userna
@@ -854,18 +854,16 @@
name,%0A
-
-
privateK
@@ -876,18 +876,16 @@
aKey,%0A
-
-
agent: p
@@ -913,12 +913,9 @@
OCK%0A
- %7D%0A
+%7D
%5D)%0A%0A
@@ -975,11 +975,13 @@
)%0A
-var
+const
fil
@@ -1552,13 +1552,12 @@
sername%7D)%0A%7D)
-%0A
|
3fa8da600c710f62eea6bbeab4af0fa6dc5ce928 | Add method 'relativeFrom' in `dynapi` | lib/core/dynapi.js | lib/core/dynapi.js | import { existsSync } from 'fs'
import { join } from 'path'
import Tapable from 'tappable'
import nrequire from 'native-require'
import { Options } from 'common'
export default class Dynapi extends Tapable {
constructor (_options = {}) {
super()
this.options = Options.from(_options)
this.nativeRequire = nrequire.from(this.options.rootDir)
}
middleware () {
return async (req, res, next) => {
await this.renderer.renderRoute(req.path, {req, res})
// TODO Custom user handling
if (!res.headersSent) {
res.sendStatus(404)
}
}
}
checkGenerated () {
return existsSync(join(this.options.buildDir, 'index.js'))
}
async close (callback) {
await this.applyPluginsAsync('close')
if (typeof callback === 'function') {
await callback()
}
}
// Only allowed resolve from `node_modules` and `aliases` this time
resolve (type, name) {
if (name === undefined) {
[name, type] = [type, '']
}
if (name.startsWith('.')) {
throw new SyntaxError('Unsupport resolving relative modules yet.')
}
// Resolve from node_modules (rootDir)
if (!name.startsWith('.') && !name.startsWith('~')) {
return this.nativeRequire.resolve(name)
}
type = name.slice(1, name.indexOf('/'))
const alias = `~${type}/`
if (name.startsWith(alias)) {
name = name.slice(alias.length)
}
return this.nativeRequire.resolve(join(this.options.srcDir, type, name))
}
}
| JavaScript | 0 | @@ -38,16 +38,26 @@
t %7B join
+, relative
%7D from
@@ -1495,11 +1495,343 @@
me))%0A %7D
+%0A%0A relativeFrom (_type, filename) %7B%0A const type = _type.replace(/Dir$/, '')%0A%0A if (typeof this.options%5Btype + 'Dir'%5D !== 'string') %7B%0A throw new SyntaxError(%60Undefined dirtype of '$%7B_type%7D'. See 'dynapi.options.%7Btype%7DDir'.%60)%0A %7D%0A%0A const dirFrom = this.options%5Btype + 'Dir'%5D%0A%0A return relative(dirFrom, filename)%0A %7D
%0A%7D%0A
|
c9e91029e636f4b8178934a073892d3a129b81c1 | remove duplicate entry from allowed search terms | src/common/commonData.js | src/common/commonData.js | // @flow
// Utils/Common
import getWidth, { widths } from '../utils/getWidth';
/* ------------------------- SHARED OBJECTS ------------------------- */
/**
* An array of all the allowed search terms.
* @type {Array<string>}
*/
export const searchTerms = [
'Android',
'Art',
'Artificial Intelligence',
'Astronomy',
'Austen',
'Baseball',
'Basketball',
'Bhagat',
'Biography',
'Brief',
'Business',
'Camus',
'Cervantes',
'Christie',
'Classics',
'Comics',
'Cook',
'Cricket',
'Cycling',
'Desai',
'Design',
'Development',
'Digital Marketing',
'Drama',
'Drawing',
'Dumas',
'Education',
'Everything',
'Fantasy',
'Film',
'Finance',
'First',
'Fitness',
'Football',
'Future',
'Games',
'Gandhi',
'History',
'History',
'Homer',
'Horror',
'Hugo',
'Ibsen',
'Journey',
'Kafka',
'King',
'Lahiri',
'Larsson',
'Learn',
'Literary Fiction',
'Make',
'Manage',
'Marquez',
'Money',
'Mystery',
'Negotiate',
'Painting',
'Philosophy',
'Photography',
'Poetry',
'Production',
'Program Javascript',
'Programming',
'React',
'Redux',
'River',
'Robotics',
'Rowling',
'Satire',
'Science Fiction',
'Shakespeare',
'Singh',
'Swimming',
'Tale',
'Thrun',
'Time',
'Tolstoy',
'Travel',
'Ultimate',
'Virtual Reality',
'Web Development',
'iOS'
];
/**
* Data for the bookshelves in the app
* @prop {Array<string>} shelves a list of all 3 shelves in the app
* @prop {Array<string>} maybeShelves a list of all 3 shelves, plus the none shelf
*
* @prop {Object} read the Read shelf
* @prop {string} read.narrow narrow name of the Read shelf
* @prop {string} read.wide wide name of the Read shelf
*
* @prop {Object} wantToRead the Want to Read shelf
* @prop {string} wantToRead.narrow narrow name of the Want to Read shelf
* @prop {string} wantToRead.wide wide name of the Want to Read shelf
*
* @prop {Object} currentlyReading the Currently Reading shelf
* @prop {string} currentlyReading.narrow narrow name of the Currently Reading shelf
* @prop {string} currentlyReading.wide wide name of the Currently Reading shelf
*
* @prop {Object} none the none shelf, for books not on a shelf
* @prop {string} none.narrow narrow name of the none shelf
* @prop {string} none.wide wide name of the none shelf
*
* @prop {function(string)} getShelfWithWidth gets the shelf name with width adjusted by window size
*/
export const shelfData = {
shelves: ['currentlyReading', 'wantToRead', 'read'],
maybeShelves: ['currentlyReading', 'wantToRead', 'read', 'none'],
read: {
narrow: 'Read',
wide: 'Read'
},
wantToRead: {
narrow: 'Want',
wide: 'Want to Read'
},
currentlyReading: {
narrow: 'Current',
wide: 'Currently Reading'
},
none: {
narrow: 'No Shelf',
wide: 'No Shelf'
}
};
shelfData.getShelfWithWidth = function(shelf: string) {
return getWidth() === widths.large ? this[shelf].wide : this[shelf].narrow;
}.bind(shelfData);
| JavaScript | 0 | @@ -730,28 +730,16 @@
story',%0A
-%09'History',%0A
%09'Homer'
|
35635bffa87a91becb4631b6ca8c7eb4bcb6ad77 | Update PCN Service w/ more creator methods | public/modules/diagrams/services/pcn.client.service.js | public/modules/diagrams/services/pcn.client.service.js | 'use strict';
angular.module('diagrams').factory('PCN', ['uuid',
function (uuid) {
return {
initPCN: function (title, description, author) {
return {
'metadata': {
'title': title,
'description': description,
'author': author
},
'domains':[],
'steps':[]
};
},
initStep: function (domain, title, type, relatedDomain) {
// type = 'independent' | 'surrogate' | 'direct'
if (!domain) throw new Error('Bad caller: required domain');
var step = {
'id': uuid.generate(),
'title': title,
'type': 'process',
'emphasized': false,
'value_specific': 0,
'value_generic': 0,
'predecessors': [],
'domain': {
'id': domain.id,
'region': {
'type': type,
},
},
'problems': []
};
if (relatedDomain)
step.domain.region.with_domain = relatedDomain.id;
return step;
},
initDomain: function (title, subtitle) {
return {
'id': uuid.generate(),
'title': title,
'subtitle': subtitle
};
}
};
}
]);
| JavaScript | 0 | @@ -85,24 +85,357 @@
%0A%09%09return %7B%0A
+ CONSTANTS: %7B%0A 'PREDECESSOR_TYPES': %7B%0A NORMAL: 'normal_relationship',%0A LOOSE: 'loose_temporal_relationship'%0A %7D,%0A 'CONNECTOR': %7B%0A INDEPENDENT: '',%0A SURROGATE: '',%0A 'DIRECT_LEADING': 'direct_leading',%0A 'DIRECT_SHARED': 'direct_shared'%0A %7D%0A %7D,%0A%0A
initPC
@@ -473,24 +473,24 @@
, author) %7B%0A
-
retu
@@ -673,17 +673,24 @@
eps':%5B%5D%0A
-%09
+
%7D;%0A
@@ -1272,18 +1272,24 @@
ms': %5B%5D%0A
-%09%09
+
%7D;%0A%0A
@@ -1396,32 +1396,472 @@
step;%0A %7D,%0A%0A
+ initPredecessor: function (id, type, title) %7B%0A return %7B%0A %22id%22: id,%0A %22type%22: type,%0A %22title%22: title %0A %7D%0A %7D,%0A%0A initStepDomain: function (owner, type, related) %7B%0A if (!owner) owner = %7B%7D;%0A if (!related) related = %7B%7D;%0A%0A return %7B%0A id: owner.id,%0A region: %7B%0A type: type,%0A 'with_domain': related.id %0A %7D%0A %7D%0A %7D,%0A%0A
initDomain
@@ -2002,12 +2002,17 @@
tle%0A
-%09%09%7D;
+ %7D
%0A
|
87b7c03a5fb2112181835ae724f26e721c84a581 | Load list of movies on every page | client/js/app.js | client/js/app.js | angular
.module('MovieDatabase', ['ngRoute'])
.config(function ($routeProvider, $locationProvider, $httpProvider, $provide) {
'use strict';
$routeProvider
.when('/', {
controller: 'MoviesListController',
templateUrl: '/partial/index.html',
resolve: {
movieList: function(MovieService) {
return MovieService.loadList();
},
},
})
.when('/movies', {
controller: 'MoviesListController',
resolve: {
movieList: function(MovieService) {
return MovieService.loadList();
},
},
templateUrl: '/partial/movies/list.html'
})
.when('/movies/new', {
controller: 'MoviesAddController',
templateUrl: '/partial/movies/add.html'
})
.when('/movies/:id', {
controller: 'MovieDetailController',
resolve: {
movie: function(MovieService, $route) {
var movieId = $route.current.params.id;
return MovieService.load(movieId);
},
},
templateUrl: '/partial/movies/detail.html'
})
.when('/movies/:id/edit', {
controller: 'MovieEditController',
resolve: {
movie: function(MovieService, $route) {
var movieId = $route.current.params.id;
return MovieService.load(movieId);
},
},
templateUrl: '/partial/movies/edit.html'
})
.when('/404', {
controller: 'NotFoundController',
templateUrl: '/partial/notFound.html'
})
.when('/error', {
controller: 'ErrorController',
templateUrl: '/partial/error.html'
})
.otherwise({
redirectTo: function () {
return '/404?culprit=client';
}
});
// use the new History API (Angular provides automatic fallback)
$locationProvider.html5Mode(true);
// We explicitly have to set the HashPrefix to comply with Google's
// crawlable hash prefix.
$locationProvider.hashPrefix('!');
$provide.factory('errorInterceptor', function($q, $location) {
return {
responseError: function(response) {
var status = response.status;
if (status === 404) {
$location.path('/404');
$location.search('culprit', 'server');
} else if (status >= 500) {
$location.path('/error');
$location.search('culprit', 'server');
}
return $q.reject(response);
}
};
});
$httpProvider.interceptors.push('errorInterceptor');
});
| JavaScript | 0 | @@ -138,16 +138,112 @@
rict';%0A%0A
+ var movieResolve = function(MovieService) %7B%0A return MovieService.loadList();%0A %7D;%0A%0A
$rou
@@ -404,370 +404,219 @@
st:
-function(MovieService) %7B%0A return MovieService.loadList();%0A %7D,%0A %7D,%0A %7D)%0A .when('/movies', %7B%0A controller: 'MoviesListController',%0A resolve: %7B%0A movieList: function(MovieService) %7B%0A return MovieService.loadList();%0A %7D,%0A %7D,%0A templateUrl: '/partial/movies/list.html'
+movieResolve%0A %7D%0A %7D)%0A .when('/movies', %7B%0A controller: 'MoviesListController',%0A templateUrl: '/partial/movies/list.html',%0A resolve: %7B%0A movieList: movieResolve%0A %7D
%0A
@@ -732,24 +732,90 @@
es/add.html'
+,%0A resolve: %7B%0A movieList: movieResolve%0A %7D
%0A %7D)%0A
@@ -1067,32 +1067,68 @@
%0A %7D,%0A
+ movieList: movieResolve%0A
%7D,%0A
@@ -1440,32 +1440,68 @@
%0A %7D,%0A
+ movieList: movieResolve%0A
%7D,%0A
@@ -1870,16 +1870,82 @@
lient';%0A
+ %7D,%0A resolve: %7B%0A movieList: movieResolve%0A
|
efa6e0ec40d9839ab2b9d0c83dbb0613652b95da | Fix typo | lib/core/system.js | lib/core/system.js | /* See license.txt for terms of usage */
"use strict";
const { Cu, Ci } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { getMostRecentBrowserWindow } = require("sdk/window/utils");
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
const currentBrowserVersion = Services.appinfo.platformVersion;
let System = {};
/**
* Compare the current browser version with the provided version argument.
*
* @param version string to compare with.
* @returns {Integer} Possible result values:
* is smaller than 0, the current version < version
* equals 0 then the current version == version
* is bigger than 0, then the current version > version
*/
System.compare = function(version) {
return Services.vc.compare(currentBrowserVersion, version);
}
/**
* Returns true if the current browser version is equal or bigger than
* the giver version. The version can be specified as a string or number.
*
* @param version {String|Number} string that must correspond
* to the version format. Read the following pages:
* https://developer.mozilla.org/en/docs/Toolkit_version_format
* https://addons.mozilla.org/en-US/firefox/pages/appversions/
* The version can be also specified as a simple number that is converted
* to the version string.
*
* @returns {Boolean} True if the current browser version is equal or bigger.
*/
System.versionIsAtLeast = function(version) {
if (typeof version == "number") {
version = version + ".0a1";
}
return System.compare(version) >= 0;
}
/**
* Returns true if the current browser comes from Developer Edition channel
* (formerly Aurora).
*/
System.isDeveloperBrowser = function() {
try {
let value = Services.prefs.getCharPref("app.update.channel");
// xxxHonza: "nightly-gum" can be removed at some point.
return (value == "aurora") || (value == "nightly-gum");
}
catch (err) {
// Exception is thrown when the preference doesn't exist
}
return false;
}
/**
* Returns true if the current browser supports multiprocess feature
* (known also as Electrolysis & e10s)
*/
System.isMultiprocessEnabled = function(browserDoc) {
if (Services.prefs.getBoolPref("browser.tabs.remote.autostart")) {
return true;
}
if (Services.prefs.getBoolPref("browser.tabs.remote.autostart.1")) {
return true;
}
if (browserDoc) {
let browser = browserDoc.getElementById("content");
if (browser && browser.mCurrentBrowser.isRemoteBrowser) {
return true;
}
}
let browser = getMostRecentBrowserWindow();
if (browser && browser.gBrowser.isRemoteBrowser) {
return true;
}
return false;
}
/**
* Safe require for devtools modules.
*/
System.devtoolsRequire = function(uri) {
try {
return devtools["require"]("devtools/server/actors/actor-registry");
} catch (err) {
}
return {};
}
// Exports from this module
exports.System = System;
| JavaScript | 0.999999 | @@ -2884,47 +2884,11 @@
e%22%5D(
-%22devtools/server/actors/actor-registry%22
+uri
);%0A
|
e664d5df1a8139673c1336859b2872f2a4bd1d2d | allow to load animation when offline | publish.js | publish.js | /*
* Copyright (c) 2011-2012 by Animatron.
* All rights are reserved.
*/
var inIFrame = false;
var _u = (function () { /* utils */
return {
extractVal: function (params, name) {
if (!params) return null;
var res;
if (res = params.match(
new RegExp('[\\?&]' + name + '=([\\w\\.\\-]+)')
)) return (res.length && res[1]) ? res[1] : null;
},
injectVal: function (params, name, value) {
if (!params) return name + '=' + value;
var res = params.match(
new RegExp('[\\?&]' + name + '=[\\w-]+'));
if (!res || !res.length) return params + '&' + name + '=' + value;
return params.replace(
new RegExp('([\\?&])' + name + '=[\\w-]+'),
'$1' + name + '=' + value
);
},
injectIfNotPresent: function (params, name, value) {
if (!this.extractVal(params, name)) {
return this.injectVal(params, name, value);
} else {
return params;
}
},
getRequiredRect: function () {
if (inIFrame) {
return _u.getIframeSize();
} else {
return [ width, height ];
}
},
getIframeSize: function () {
var size = [0, 0];
if (typeof window.innerWidth == 'number') {
size = [window.innerWidth, window.innerHeight];
} else {
size = [document.documentElement.clientWidth, document.documentElement.clientHeight];
}
return size;
},
reportError: function (_e) {
if (console) console.error(_e.message || _e);
else alert(_e.message || _e);
},
forcedJS: function (_path, _then) {
var scriptElm = document.createElement('script');
scriptElm.type = 'text/javascript';
scriptElm.async = 'async';
scriptElm.src = _path + '?' + (new Date()).getTime();
scriptElm.onload = scriptElm.onreadystatechange = (function () {
var _success = false;
return function () {
if (!_success && (!this.readyState || (this.readyState == 'complete'))) {
_success = true;
_then();
} else if (!_success) {
_u.reportError(new Error('Request failed: ' + this.readyState));
}
}
})();
scriptElm.onerror = _u.reportError;
var headElm = document.head || document.getElementsByTagName('head')[0];
headElm.appendChild(scriptElm);
}
};
})();
var start = (function () {
var VERSION_MASK = '^(v[0-9]+(\\.[0-9]+){0,2})$|^latest$';
var CANVAS_ID = 'target',
PROTOCOL = ('https:' === document.location.protocol) ? 'https://' : 'http://',
PLAYER_VERSION_ID = playerVersion;
if (!playerVersion || !playerVersion.match(VERSION_MASK)) {
_u.reportError(new Error('Snapshot Version ID \'' + playerVersion + '\' is incorrect'));
return;
}
inIFrame = (window.self !== window.top);
var _params_ = location.search;
var rect = _u.getRequiredRect();
if (rect) {
if (_params_) {
_params_ = _u.injectIfNotPresent(_params_, "w", rect[0]);
_params_ = _u.injectIfNotPresent(_params_, "h", rect[1]);
} else {
_params_ = '?w=' + rect[0] + '&' + 'h=' + rect[1];
}
}
if (autostart) {
_params_ = _u.injectIfNotPresent(_params_, "t", 0);
}
if (loop) {
_params_ = _u.injectIfNotPresent(_params_, "r", 1);
}
var _snapshotUrl_ = amazonDomain + '/' + filename + (_params_ || '');
var temp_v = null;
if (temp_v = _u.extractVal(_params_, 'v')) {
if (!temp_v.match(VERSION_MASK)) {
_u.reportError(new Error('Player Version ID \'' + temp_v + '\' is incorrect'));
return;
}
PLAYER_VERSION_ID = temp_v;
}
return function () {
try {
var cvs = document.getElementById(CANVAS_ID);
if (!inIFrame) {
document.body.className = 'no-iframe';
cvs.className = 'no-iframe';
}
if (rect) {
cvs.style.width = rect[0] + 'px';
cvs.style.height = rect[1] + 'px';
if (!inIFrame) {
cvs.style.marginLeft = -Math.floor(rect[0] / 2) + 'px';
cvs.style.marginTop = -Math.floor(rect[1] / 2) + 'px';
}
} else if (!inIFrame) {
cvs.className += ' no-rect';
}
_u.forcedJS(PROTOCOL + playerDomain + '/' + PLAYER_VERSION_ID + '/bundle/animatron.js',
function () {
var animatronImporter = (typeof AnimatronImporter !== 'undefined') ? new AnimatronImporter()
: anm.createImporter('animatron');
var player = anm.Player.forSnapshot(CANVAS_ID, _snapshotUrl_, animatronImporter);
}
);
} catch (e) {
_u.reportError(e);
}
}
})();
| JavaScript | 0 | @@ -4974,126 +4974,90 @@
-var animatronImporter = (typeof AnimatronImporter !== 'undefined') ? new AnimatronImporter()%0A :
+if (offline) %7B%0A anm.createPlayer(CANVAS_ID).load(animation,
anm
@@ -5084,16 +5084,17 @@
matron')
+)
;%0A
@@ -5111,20 +5111,40 @@
-var player =
+%7D else %7B%0A
anm
@@ -5155,19 +5155,12 @@
yer.
-forSnapshot
+load
(CAN
@@ -5188,25 +5188,61 @@
, an
-imatronImporter);
+m.createImporter('animatron'));%0A %7D
%0A
|
26ed31dbd07a8ecbffb50f27d3bf91e31abd8e74 | Update the Ohloh (now Open HUB) URL to code.openhub.net | src/common/lib/Option.js | src/common/lib/Option.js | /**
* The MIT License
*
* Copyright (c) 2009 Steven G. Brown
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* ----------------------------------------------------------------------------
* Option
* ----------------------------------------------------------------------------
*/
/**
* Option which can be configured to change the behaviour of the script.
* @param {{key: string, defaultValue: string, type,
* upgrade: function(string, string)}} properties The option properties.
* @constructor
*/
Option = function(properties) {
this.key = properties.key;
this.defaultValue = properties.defaultValue;
this.type = properties.type;
this.upgrade = properties.upgrade;
};
/**#@+
* Option recognised by this script.
*/
/**
* @type {Option}
*/
Option.AUTO_OPEN = new Option({
key: 'auto_open',
defaultValue: false,
type: Boolean,
upgrade: function(value, lastSavedVersion) {
return value;
}
});
/**
* @type {Option}
*/
Option.HIDE_PACKAGE_FRAME = new Option({
key: 'hide_package_frame',
defaultValue: true,
type: Boolean,
upgrade: function(value, lastSavedVersion) {
return value;
}
});
/**
* @type {Option}
*/
Option.PACKAGE_MENU = new Option({
key: 'package_menu',
defaultValue:
'@1:search(Ohloh) -> http://code.ohloh.net/?s=##PACKAGE_NAME##\n' +
'@2:search(Docjar) -> http://www.docjar.com/s.jsp?q=##PACKAGE_NAME##',
type: String,
upgrade: function(value, lastSavedVersion) {
return this._upgradeMenuOption(value, lastSavedVersion);
}
});
/**
* @type {Option}
*/
Option.CLASS_MENU = new Option({
key: 'class_menu',
defaultValue:
'@1:search(Ohloh) -> http://code.ohloh.net/' +
'?s=##PACKAGE_NAME##+##CLASS_NAME##+##MEMBER_NAME##\n' +
'@2:search(Docjar) -> http://www.docjar.com/s.jsp?q=##CLASS_NAME##\n' +
'@3:source(Docjar) -> http://www.docjar.com/html/api/' +
'##PACKAGE_PATH##/##CLASS_NAME##.java.html\n' +
'@4:search(grepcode) -> http://grepcode.com/' +
'search/?query=##PACKAGE_NAME##.##CLASS_NAME##.##MEMBER_NAME##',
type: String,
upgrade: function(value, lastSavedVersion) {
value = this._upgradeMenuOption(value, lastSavedVersion);
if (lastSavedVersion === '1.4.6' && value.indexOf('grepcode') === -1) {
for (var i = 1; i < 10; i++) {
if (value.indexOf('@' + i + ':') === -1) {
value += '\n@' + i + ':search(grepcode) -> http://grepcode.com/' +
'search/?query=' +
'##PACKAGE_NAME##.##CLASS_NAME##.##MEMBER_NAME##';
break;
}
}
}
return value;
}
});
/**#@-
*/
/**
* Upgrade a configured menu option. This function performs the changes which
* are used to upgrade both the class menu and package menu.
* @param {string} value The current value of the option.
* @param {string} lastSavedVersion The last version of the script to save the
* option.
* @return {string} The new value.
*/
Option.prototype._upgradeMenuOption = function(value, lastSavedVersion) {
if (lastSavedVersion === '1.4.6') {
if (value.indexOf('->') === -1) {
value = this.defaultValue;
} else {
value = value.replace('search(koders)', 'search(Ohloh)');
value = value.replace('//www.koders.com/', '//code.ohloh.net/');
}
}
return value;
};
| JavaScript | 0 | @@ -2301,36 +2301,39 @@
'@1:search(O
-hloh
+pen HUB
) -%3E http://code
@@ -2330,28 +2330,30 @@
ttp://code.o
-hloh
+penhub
.net/?s=##PA
@@ -2695,20 +2695,23 @@
search(O
-hloh
+pen HUB
) -%3E htt
@@ -2716,28 +2716,30 @@
ttp://code.o
-hloh
+penhub
.net/' +%0A
@@ -4360,16 +4360,223 @@
%7D%0A %7D%0A
+ if (lastSavedVersion === '1.4.6' %7C%7C lastSavedVersion === '1.5') %7B%0A value = value.replace('search(Ohloh)', 'search(Open HUB)');%0A value = value.replace('//code.ohloh.net/', '//code.openhub.net/');%0A %7D%0A
return
|
25e36cdd4ea57abcf7981d15df3b7aa6da7f3b7e | clean common/list | src/common/list/index.js | src/common/list/index.js |
//var SelectionList = Focus.components.list.selection.list.component;
import builder from 'focus-core/component/builder';
import React from 'react';
import type from 'focus-core/component/types';
import {omit} from 'lodash';
import memoryMixin from '../../list/mixin/memory-scroll';
let MemoryListMixin = {
mixins: [memoryMixin],
propTypes: {
listComponent: type(['func', 'object'])
},
/** @inheritdoc */
render: function renderFormList() {
let data = this.props.data || [];
let hasMoreData = data.length > this.state.maxElements;
let childProps = omit(this.props, ['lineComponent', 'data']);
return (
<this.props.listComponent
ref='list'
data={this.getDataToUse()}
hasMoreData={hasMoreData}
LineComponent={this.props.LineComponent}
isSelection={false}
isManualFetch
fetchNextPage={this.fetchNextPage}
reference={this.getReference()}
{...childProps}
/>
);
}
};
const builtComp = builder(MemoryListMixin);
const {component, mixin} = builtComp;
export {
component,
mixin
}
export default builtComp; | JavaScript | 0.000002 | @@ -1,75 +1,4 @@
-%0A//var SelectionList = Focus.components.list.selection.list.component;%0A
impo
@@ -127,20 +127,22 @@
import %7B
+
omit
+
%7D from '
@@ -371,33 +371,8 @@
nder
-: function renderFormList
() %7B
@@ -1056,16 +1056,17 @@
%0Aconst %7B
+
componen
@@ -1073,16 +1073,17 @@
t, mixin
+
%7D = buil
|
bbdce894bf624f618c57302c5209d6d788c54c83 | Check to see if a stream actually exists before trying to terminate it. | webApp/src/lib/broadCaster.js | webApp/src/lib/broadCaster.js | var Broadcaster = function(streamId, inputSourcesCB, renderAudioCallback) {
//handle web audio api not supported
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
//binaryJS client - server/socket connection
this.stream;
this.client;
this.streamId = streamId;
this.ctx = new AudioContext();
if (typeof MediaStreamTrack === 'undefined' ||
typeof MediaStreamTrack.getSources === 'undefined') {
alert('This browser does not support MediaStreamTrack.\n\nTry Chrome.');
} else {
MediaStreamTrack.getSources(inputSourcesCB);
}
this.renderAudioCallback = renderAudioCallback;
}
Broadcaster.prototype.start = function(sourceId) {
if (!sourceId) {
return 'Broadcast source not set!';
}
var protocol = (window.location.protocol === "https:") ? 'wss://' : 'ws://';
this.client = new BinaryClient(protocol + document.location.host + '/binary-endpoint');
this.client.on('open', function() {
this.stream = this.client.createStream({
sampleRate: this.ctx.sampleRate,
streamId: this.streamId
});
var constraints = {
audio: {
optional: [{
sourceId: sourceId
}]
},
video: false
};
navigator.getUserMedia(constraints, function(stream) {
var audioInput = this.ctx.createMediaStreamSource(stream);
var bufferSize = 0; // let implementation decide
this.recorder = this.ctx.createScriptProcessor(bufferSize, 2, 2);
this.recorder.onaudioprocess = function(e) {
this.onAudio(e);
}.bind(this);
audioInput.connect(this.recorder);
this.recorder.connect(this.ctx.destination);
}.bind(this), function(e) {
console.log('error connectiing to audio source');
throw e;
});
}.bind(this));
}
Broadcaster.prototype.startFromHTML = function(elementId) {
var protocol = (window.location.protocol === "https:") ? 'wss://' : 'ws://';
this.client = new BinaryClient(protocol + document.location.host + '/binary-endpoint');
this.client.on('open', function() {
this.stream = this.client.createStream({
sampleRate: this.ctx.sampleRate,
streamId: this.streamId
});
var audioElement = document.getElementById(elementId);
var audioSrc = this.ctx.createMediaElementSource(audioElement);
var bufferSize = 0; // let implementation decide
this.recorder = this.ctx.createScriptProcessor(bufferSize, 2, 2);
this.recorder.onaudioprocess = function(e) {
this.onAudio(e);
}.bind(this);
audioSrc.connect(this.recorder);
this.recorder.connect(this.ctx.destination);
}.bind(this));
}
Broadcaster.prototype.stop = function() {
this.recorder.disconnect();
this.stream.end();
this.client.close();
}
Broadcaster.prototype.onAudio = function(e) {
var left = e.inputBuffer.getChannelData(0);
var right = e.inputBuffer.getChannelData(1);
var stereoBuff = this._interleave(left, right);
this.stream.write(this._convertFloat32ToInt16(stereoBuff));
if (this.renderAudioCallback) {
this.renderAudioCallback(left); //callback to render audio value
}
}
Broadcaster.prototype._convertFloat32ToInt16 = function(buffer) {
var l = buffer.length;
var buf = new Int16Array(l);
while (l--) {
buf[l] = Math.min(1, buffer[l]) * 0x7FFF;
}
return buf.buffer;
}
Broadcaster.prototype._interleave = function(leftChannel, rightChannel) {
var length = leftChannel.length + rightChannel.length;
var result = new Float32Array(length);
var inputIndex = 0;
for (var index = 0; index < length;) {
result[index++] = leftChannel[inputIndex];
result[index++] = rightChannel[inputIndex];
inputIndex++;
}
return result;
}
| JavaScript | 0 | @@ -2745,16 +2745,41 @@
ion() %7B%0A
+ if (this.recorder) %7B%0A
this.r
@@ -2806,27 +2806,81 @@
;%0A
-this.stream.end();%0A
+%7D%0A if (this.stream) %7B%0A this.stream.end();%0A %7D%0A if (this.client) %7B%0A
th
@@ -2898,16 +2898,20 @@
lose();%0A
+ %7D%0A
%7D%0A%0ABroad
|
abb69263a94981929033491c6c0c295e2cebb6f5 | Add an endpoint that connect to the tasks listing in a card | src/api/task.js | src/api/task.js | module.exports = ( api, request ) => {
api.task = {};
api.task.create = ( cardId, taskCreateRequest ) => {
taskCreateRequest.cardId = cardId;
if ( !taskCreateRequest.laneType && !taskCreateRequest.laneTitle ) {
taskCreateRequest.laneTitle = "todo";
}
return request( {
url: `/io/card/${ cardId }/tasks`,
method: "POST",
data: taskCreateRequest
} );
};
api.task.get = ( cardId, taskId ) => {
return request( {
url: `/io/card/${ cardId }/tasks/${ taskId }`,
method: "GET"
} );
};
};
| JavaScript | 0.000001 | @@ -368,24 +368,140 @@
%09%09%7D );%0A%09%7D;%0A%0A
+%09api.task.list = cardId =%3E %7B%0A%09%09return request( %7B%0A%09%09%09url: %60/io/card/$%7B cardId %7D/tasks%60,%0A%09%09%09method: %22GET%22%0A%09%09%7D );%0A%09%7D;%0A%0A
%09api.task.ge
|
62af091fd34a8608b6584a1b43cc650e9fb8cb7d | Add some aliases. | webpack.development.config.js | webpack.development.config.js | 'use strict'
const webpack = require('webpack')
const path = require('path')
var HtmlWebpackPlugin = require('html-webpack-plugin')
const configuration = {
entry: [
'webpack-dev-server/client?http://0.0.0.0:8080',
'webpack/hot/only-dev-server',
path.resolve(__dirname, 'app')
],
output: {
path: path.resolve(__dirname, 'public/build/'),
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.html$/,
loaders: [ 'html-loader' ]
},
{
test: /\.scss$/,
loaders: [ 'style-loader', 'css-loader', 'sass-loader' ]
}
]
},
plugins: [
new webpack.DefinePlugin(
{
'process.env.NODE_ENV': JSON.stringify('development')
}
),
new HtmlWebpackPlugin(
{
template: path.resolve(__dirname, 'public/index.html'),
favicon: path.resolve(__dirname, 'public/favicon.ico'),
inject: true,
minify: false
}
),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.NamedModulesPlugin()
],
devtool: 'eval-cheap-module-source-map'
}
module.exports = configuration
| JavaScript | 0.000001 | @@ -386,16 +386,225 @@
s'%0A %7D,%0A
+ resolve: %7B%0A extensions: %5B '.js', '.jsx', '.json', '.scss', '.css' %5D,%0A alias: %7B%0A components: path.resolve(__dirname, 'app/components'),%0A views: path.resolve(__dirname, 'app/views')%0A %7D%0A %7D,%0A
module
|
2d083a2921732900a47a862ae95875442ab6cc0a | Remove this check which will never pass with the new cache. | src/path/index.js | src/path/index.js | /* eslint max-len: 0 */
import type Hub from "../hub";
import type TraversalContext from "../context";
import * as virtualTypes from "./lib/virtual-types";
import buildDebug from "debug";
import invariant from "invariant";
import traverse from "../index";
import assign from "lodash/object/assign";
import Scope from "../scope";
import * as t from "babel-types";
import { path as pathCache } from "../cache";
let debug = buildDebug("babel");
export default class NodePath {
constructor(hub: Hub, parent: Object) {
this.parent = parent;
this.hub = hub;
this.contexts = [];
this.data = {};
this.shouldSkip = false;
this.shouldStop = false;
this.removed = false;
this.state = null;
this.opts = null;
this.skipKeys = null;
this.parentPath = null;
this.context = null;
this.container = null;
this.listKey = null;
this.inList = false;
this.parentKey = null;
this.key = null;
this.node = null;
this.scope = null;
this.type = null;
this.typeAnnotation = null;
}
parent: Object;
hub: Hub;
contexts: Array<TraversalContext>;
data: Object;
shouldSkip: boolean;
shouldStop: boolean;
removed: boolean;
state: any;
opts: ?Object;
skipKeys: ?Object;
parentPath: ?NodePath;
context: TraversalContext;
container: ?Object | Array<Object>;
listKey: ?string;
inList: boolean;
parentKey: ?string;
key: ?string;
node: ?Object;
scope: Scope;
type: ?string;
typeAnnotation: ?Object;
static get({ hub, parentPath, parent, container, listKey, key }): NodePath {
if (!hub && parentPath) {
hub = parentPath.hub;
}
invariant(parent, "To get a node path the parent needs to exist");
let targetNode = container[key];
let paths = pathCache.get(parent) || [];
if (!pathCache.has(parent)) {
pathCache.set(parent, paths);
}
let path;
for (let i = 0; i < paths.length; i++) {
let pathCheck = paths[i];
if (pathCheck.node === targetNode) {
path = pathCheck;
break;
}
}
if (path && !(path instanceof NodePath)) {
if (path.constructor.name === "NodePath") {
// we're going to absolutley thrash the tree and allocate way too many node paths
// than is necessary but there's no way around this as the node module resolution
// algorithm is ridiculous
path = null;
} else {
// badly deserialised probably
throw new Error("We found a path that isn't a NodePath instance. Possibly due to bad serialisation.");
}
}
if (!path) {
path = new NodePath(hub, parent);
paths.push(path);
}
path.setup(parentPath, container, listKey, key);
return path;
}
getScope(scope: Scope) {
let ourScope = scope;
// we're entering a new scope so let's construct it!
if (this.isScope()) {
ourScope = new Scope(this, scope);
}
return ourScope;
}
setData(key: string, val: any): any {
return this.data[key] = val;
}
getData(key: string, def?: any): any {
let val = this.data[key];
if (!val && def) val = this.data[key] = def;
return val;
}
buildCodeFrameError(msg: string, Error: typeof Error = SyntaxError): Error {
return this.hub.file.buildCodeFrameError(this.node, msg, Error);
}
traverse(visitor: Object, state?: any) {
traverse(this.node, visitor, this.scope, state, this);
}
mark(type: string, message: string) {
this.hub.file.metadata.marked.push({
type,
message,
loc: this.node.loc
});
}
set(key: string, node: Object) {
t.validate(this.node, key, node);
this.node[key] = node;
}
getPathLocation(): string {
let parts = [];
let path = this;
do {
let key = path.key;
if (path.inList) key = `${path.listKey}[${key}]`;
parts.unshift(key);
} while (path = path.parentPath);
return parts.join(".");
}
debug(buildMessage: Function) {
if (!debug.enabled) return;
debug(`${this.getPathLocation()} ${this.type}: ${buildMessage()}`);
}
}
assign(NodePath.prototype, require("./ancestry"));
assign(NodePath.prototype, require("./inference"));
assign(NodePath.prototype, require("./replacement"));
assign(NodePath.prototype, require("./evaluation"));
assign(NodePath.prototype, require("./conversion"));
assign(NodePath.prototype, require("./introspection"));
assign(NodePath.prototype, require("./context"));
assign(NodePath.prototype, require("./removal"));
assign(NodePath.prototype, require("./modification"));
assign(NodePath.prototype, require("./family"));
assign(NodePath.prototype, require("./comments"));
for (let type of (t.TYPES: Array<string>)) {
let typeKey = `is${type}`;
NodePath.prototype[typeKey] = function (opts) {
return t[typeKey](this.node, opts);
};
NodePath.prototype[`assert${type}`] = function (opts) {
if (!this[typeKey](opts)) {
throw new TypeError(`Expected node path of type ${type}`);
}
};
}
for (let type in virtualTypes) {
if (type[0] === "_") continue;
if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type);
let virtualType = virtualTypes[type];
NodePath.prototype[`is${type}`] = function (opts) {
return virtualType.checkPath(this, opts);
};
}
| JavaScript | 0 | @@ -2058,521 +2058,8 @@
%7D%0A%0A
- if (path && !(path instanceof NodePath)) %7B%0A if (path.constructor.name === %22NodePath%22) %7B%0A // we're going to absolutley thrash the tree and allocate way too many node paths%0A // than is necessary but there's no way around this as the node module resolution%0A // algorithm is ridiculous%0A path = null;%0A %7D else %7B%0A // badly deserialised probably%0A throw new Error(%22We found a path that isn't a NodePath instance. Possibly due to bad serialisation.%22);%0A %7D%0A %7D%0A%0A
|
ba0f45c62a3a46993bcf485a45710c890ccba846 | Remove console.logs | factories/timer.js | factories/timer.js | 'use strict';
const _ = require('lodash');
const chalk = require('chalk');
function print(result, identifier) {
console.info(chalk.green('timer: ') + _.padEnd(_.truncate(`[${identifier}]`, { length: 24 }), 25) + chalk.green.bold(result[0] * 1e3 + result[1] / 1e6 + ' ms'));
}
module.exports = (mw, identifier = mw.name || 'anonymous') => (req, res, next) => {
res.___send = res.___send || res.send;
res.send = (...args) => {
print(process.hrtime(start), identifier);
res.___send(...args);
}
const _next = (...args) => {
print(process.hrtime(start), identifier);
console.log(args);
next(...args);
};
const start = process.hrtime();
console.log(mw);
mw(req, res, _next);
};
| JavaScript | 0.000002 | @@ -588,31 +588,8 @@
);%0A%0A
- console.log(args);%0A
@@ -648,27 +648,8 @@
);%0A%0A
- console.log(mw);%0A
mw
|
5993382c7ea627a288922cedbbac1864cbfef227 | Update component name | src/components/Button.js | src/components/Button.js | import React, { Component } from 'react';
import {
View,
StyleSheet,
Text,
TouchableOpacity,
Image
} from "react-native";
import AppStyleSheet from "../styles";
import Icon from 'react-native-vector-icons/Foundation';
export default class SearchBox extends Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
render() {
let { icon, title, style } = this.props;
return (
<TouchableOpacity
onPress={() =>
this.props.onSearch &&
this.props.onSearch(title)}
>
<View style={[styles.buttonContainer, style]}>
<Image style={styles.buttonIcon} source={icon} />
<Text style={styles.text}>{title}</Text>
</View>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
searchContainer: {
flexDirection: 'row',
alignSelf: 'stretch'
},
searchIcon: {
padding: 8
},
searchInput: {
flex: 1,
backgroundColor: '#f5f8fa'
},
buttonIcon: {
marginLeft: 0,
width: 45,
height: 45
},
text: {
padding: 12,
fontSize: 16,
fontWeight: 'bold',
flex: 1,
backgroundColor: '#f5f8fa'
},
buttonContainer: {
flexDirection: 'row',
alignItems: 'center',
alignSelf: 'stretch',
backgroundColor: '#f5f8fa'
},
}); | JavaScript | 0.000001 | @@ -251,17 +251,14 @@
ass
-SearchBox
+Button
ext
|
1567f6a0db3ba78563b9640dea785253f65a927c | Change Button padding back to 7px | src/components/Button.js | src/components/Button.js | const React = require('react');
const Radium = require('radium');
const StyleConstants = require('../constants/Style');
const Icon = require('../components/Icon');
const StyleUtils = require('../utils/Style');
const Button = React.createClass({
propTypes: {
icon: React.PropTypes.string,
primaryColor: React.PropTypes.string,
type: React.PropTypes.oneOf([
'base',
'disabled',
'neutral',
'primary',
'primaryOutline',
'secondary',
'secondaryOutline'
])
},
getDefaultProps () {
return {
primaryColor: StyleConstants.Colors.PRIMARY,
type: 'primary'
};
},
render () {
const styles = {
component: {
borderRadius: 2,
borderStyle: 'solid',
borderWidth: 1,
borderColor: 'transparent',
display: 'inline-block',
padding: '10px 14px',
textAlign: 'center',
fontSize: StyleConstants.FontSizes.MEDIUM,
fontFamily: StyleConstants.Fonts.SEMIBOLD,
cursor: 'pointer',
transition: 'all .2s ease-in'
},
primary: {
backgroundColor: this.props.primaryColor,
borderColor: this.props.primaryColor,
color: StyleConstants.Colors.WHITE,
fill: StyleConstants.Colors.WHITE,
transition: 'all .2s ease-in',
':hover': {
backgroundColor: StyleUtils.adjustColor(this.props.primaryColor, -8),
borderColor: StyleUtils.adjustColor(this.props.primaryColor, -8),
transition: 'all .2s ease-in'
},
':active': {
backgroundColor: StyleUtils.adjustColor(this.props.primaryColor, -16),
borderColor: StyleUtils.adjustColor(this.props.primaryColor, -16),
transition: 'all .2s ease-in'
}
},
primaryOutline: {
backgroundColor: 'transparent',
borderColor: this.props.primaryColor,
color: this.props.primaryColor,
fill: this.props.primaryColor,
transition: 'all .2s ease-in',
':hover': {
backgroundColor: this.props.primaryColor,
color: StyleConstants.Colors.WHITE,
fill: StyleConstants.Colors.WHITE,
transition: 'all .2s ease-in'
},
':active': {
backgroundColor: StyleUtils.adjustColor(this.props.primaryColor, -16),
borderColor: StyleUtils.adjustColor(this.props.primaryColor, -16),
color: StyleConstants.Colors.WHITE,
fill: StyleConstants.Colors.WHITE,
transition: 'all .2s ease-in'
}
},
secondary: {
backgroundColor: StyleConstants.Colors.FOG,
borderColor: StyleConstants.Colors.FOG,
color: StyleConstants.Colors.CHARCOAL,
fill: StyleConstants.Colors.CHARCOAL,
transition: 'all .2s ease-in',
':hover': {
backgroundColor: StyleUtils.adjustColor(StyleConstants.Colors.FOG, -5),
borderColor: StyleUtils.adjustColor(StyleConstants.Colors.FOG, -5),
transition: 'all .2s ease-in'
},
':active': {
backgroundColor: StyleUtils.adjustColor(StyleConstants.Colors.FOG, -10),
borderColor: StyleUtils.adjustColor(StyleConstants.Colors.FOG, -10),
transition: 'all .2s ease-in'
}
},
secondaryOutline: {
backgroundColor: 'transparent',
borderColor: StyleConstants.Colors.ASH,
color: StyleConstants.Colors.ASH,
fill: StyleConstants.Colors.ASH,
transition: 'all .2s ease-in',
':hover': {
backgroundColor: StyleConstants.Colors.ASH,
borderColor: StyleConstants.Colors.ASH,
color: StyleConstants.Colors.WHITE,
fill: StyleConstants.Colors.WHITE,
transition: 'all .2s ease-in'
},
':active': {
backgroundColor: StyleUtils.adjustColor(StyleConstants.Colors.ASH, -10),
borderColor: StyleUtils.adjustColor(StyleConstants.Colors.ASH, -10),
color: StyleConstants.Colors.WHITE,
fill: StyleConstants.Colors.WHITE,
transition: 'all .2s ease-in'
}
},
base: {
backgroundColor: 'transparent',
color: this.props.primaryColor,
fill: this.props.primaryColor,
transition: 'all .2s ease-in',
':hover': {
color: StyleUtils.adjustColor(this.props.primaryColor, -8),
fill: StyleUtils.adjustColor(this.props.primaryColor, -8),
transition: 'all .2s ease-in'
},
':active': {
color: StyleUtils.adjustColor(this.props.primaryColor, -16),
fill: StyleUtils.adjustColor(this.props.primaryColor, -16),
transition: 'all .2s ease-in'
}
},
disabled: {
backgroundColor: StyleConstants.Colors.PORCELAIN,
borderColor: StyleConstants.Colors.PORCELAIN,
color: StyleConstants.Colors.FOG,
fill: StyleConstants.Colors.FOG
},
icon: {
margin: '-6px -5px -5px -5px',
paddingRight: this.props.children ? 10 : 0
}
};
return (
<div {...this.props} style={[styles.component, styles[this.props.type], this.props.style]}>
{this.props.icon ? <Icon size={20} style={styles.icon} type={this.props.icon} /> : null}
{this.props.children}
</div>
);
}
});
module.exports = Radium(Button); | JavaScript | 0 | @@ -856,18 +856,17 @@
dding: '
-10
+7
px 14px'
|
03997837906c78aed87158b3c1a025d7976490e3 | Fix for circular redirect error | src/components/Layout.js | src/components/Layout.js | import { Layout } from 'antd';
import 'antd/dist/antd.less';
import React from 'react';
import Helmet from 'react-helmet';
import 'react-typist/dist/Typist.css';
import '../app.less';
import Footer from '../components/Footer';
import Navbar from '../components/Navbar';
import useSiteMetadata from './SiteMetadata';
const TemplateWrapper = ({ children }) => {
const { title, description } = useSiteMetadata()
return (
<div>
<Helmet>
<html lang="en" />
<title>{title}</title>
<meta name="description" content={description} />
<link
rel="apple-touch-icon"
sizes="180x180"
href="/img/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
href="/img/favicon-32x32.png"
sizes="32x32"
/>
<link
rel="icon"
type="image/png"
href="/img/favicon-16x16.png"
sizes="16x16"
/>
<link
rel="mask-icon"
href="/img/safari-pinned-tab.svg"
color="#ff4400"
/>
<meta name="theme-color" content="#fff" />
<meta property="og:type" content="website" />
<meta property="og:title" content={title} />
<meta property="og:url" content="http://cict.wvsu.edu.ph" />
<meta property="og:image" content="https://cictwvsu.com/img/og-image.jpg" />
</Helmet>
<Layout className="layout">
<Navbar />
<div style={{backgroundColor: '#fff', borderTop:' 1px solid #e8e8e8', padding: '0 2rem'}}>{children}</div>
<Footer />
</Layout>
</div>
)
}
export default TemplateWrapper
| JavaScript | 0 | @@ -1304,16 +1304,17 @@
u.edu.ph
+/
%22 /%3E%0A
|
6e8dc8d53b4c1d661c52cd137bda62a678d90db4 | connect action-creators to 'Voting' component | src/components/Voting.js | src/components/Voting.js | import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import {connect} from 'react-redux';
import Winner from './Winner';
import Vote from './Vote';
export const Voting = React.createClass({
mixins: [PureRenderMixin],
render: function() {
return <div>
{
this.props.winner ?
<Winner ref="winner" winner={this.props.winner} /> :
<Vote {...this.props} />
}
</div>;
}
});
function mapStateToProps(state) {
return {
pair: state.getIn(['vote', 'pair']),
hasVoted: state.get('hasVoted'),
winner: state.get('winner')
}
}
export const VotingContainer = connect(mapStateToProps)(Voting);
| JavaScript | 0 | @@ -177,16 +177,70 @@
./Vote';
+%0Aimport * as actionCreators from '../action_creators';
%0A%0Aexport
@@ -705,16 +705,19 @@
connect(
+%0A
mapState
@@ -723,16 +723,35 @@
eToProps
+,%0A actionCreators%0A
)(Voting
|
da9846c8fbce9fb95b9c32db9c91317391aed65d | fix Edit Chosen Seats. | Source/public/js/express/book-ticket.js | Source/public/js/express/book-ticket.js | (function() {
var app = angular.module("book-ticket", []);
app.controller("BookTicketController", function($scope) {
$scope.back = function() {
$("#result-operator").empty();
$("#result-date").empty();
$("#result-from").empty();
$("#result-to").empty();
$("#result-price").empty();
$("#step-2").fadeOut();
$("#step-1").fadeIn();
};
$(".book-seat td").click(function() {
var seat = $(this);
console.log(seat);
})
})
})(); | JavaScript | 0 | @@ -115,24 +115,49 @@
n($scope) %7B%0A
+ var seats = %5B%5D;%0A%0A
$sco
@@ -171,32 +171,32 @@
= function() %7B%0A
-
$(%22#
@@ -374,24 +374,49 @@
).empty();%0A%0A
+ seats = %5B%5D;%0A%0A
@@ -562,17 +562,442 @@
$(this)
-;
+.context;%0A%0A if (seat.className == %22seat-available%22) %7B%0A $(seat).removeClass();%0A $(seat).addClass(%22seat-checked%22);%0A seats.push(seat.innerHTML);%0A %7D else if (seat.className == %22seat-checked%22) %7B%0A $(seat).removeClass();%0A $(seat).addClass(%22seat-available%22);%0A seats.splice(seats.indexOf(seat.innerHTML), 1);%0A %7D%0A
%0A
@@ -1017,16 +1017,17 @@
log(seat
+s
);%0A
|
46410d6c2ef12a8b81a254e9e37b7bb1891bc9e2 | Change reference to app.jade to main.jade. Potentially fixes #5. | server/controllers/app-control.js | server/controllers/app-control.js | var rootDir = process.cwd(),
CivicSeed = require(rootDir + '/CivicSeed').getGlobals(),
ss = require('socketstream');
var self = module.exports = {
init: function(app) {
ss.client.define('main', {
view: 'main.jade',
css: ['styles.styl'],
code: [
'libs/jquery.min.js',
'libs/davis-0.9.6.min.js',
'libs/underscore-min.js',
'libs/backbone-min.js',
'libs/bootstrap.min.js',
'libs/d3.min.js',
'libs/howler.min.js',
'libs/plugins.js',
'routes',
'admin',
'shared',
'game',
'main'
],
tmpl: '*'
});
ss.http.route('/', function(req, res) {
res.serveClient('main');
});
// 404'd
app.use(function(req, res, next) {
// res.send(404, 'Sorry cant find that!');
CivicSeed.SocketStream = false;
res.render(rootDir + '/client/views/app.jade', {
title: '404 - Page Not Found',
CivicSeed: JSON.stringify(CivicSeed),
SocketStream: ''
});
});
}
};
| JavaScript | 0 | @@ -805,19 +805,20 @@
t/views/
-app
+main
.jade',
|
77b799dcebd313fe7bb3cb07b0aab101e438ab79 | Add .elm extension to ci tests | tests/ci.js | tests/ci.js | const shell = require("shelljs");
var _ = require("lodash");
var fs = require("fs-extra");
var path = require("path");
var spawn = require("cross-spawn");
var filename = __filename.replace(__dirname + "/", "");
var elmTest = "elm-test";
const elmHome = path.join(__dirname, "..", "fixtures", "elm-home");
const spawnOpts = { silent: true, env: Object.assign({ELM_HOME: elmHome}, process.env)};
function run(testFile) {
console.log("\nClearing elm-stuff prior to run");
shell.rm("-rf", "elm-stuff");
if (!testFile) {
var cmd = [elmTest, "--color"].join(" ");
shell.echo("Running: " + cmd);
return shell.exec(cmd, spawnOpts).code;
} else {
var cmd = [elmTest, testFile, "--color"].join(" ");
shell.echo("Running: " + cmd);
return shell.exec(cmd, spawnOpts).code;
}
}
function assertTestErrored(testfile) {
var code = run(testfile);
if (code !== 1) {
shell.exec(
"echo " +
filename +
": error: " +
(testfile ? testfile + ": " : "") +
"expected tests to exit with ERROR exit code, not exit code" +
code +
" >&2"
);
shell.exit(1);
}
}
function assertTestIncomplete(testfile) {
var code = run(testfile);
if (code !== 3) {
shell.exec(
"echo " +
filename +
": error: " +
(testfile ? testfile + ": " : "") +
"expected tests to exit with INCOMPLETE exit code, not exit code" +
code +
" >&2"
);
shell.exit(1);
}
}
function assertTestFailure(testfile) {
var code = run(testfile);
if (code < 2) {
shell.exec(
"echo " +
filename +
": error: " +
(testfile ? testfile + ": " : "") +
"expected tests to fail >&2"
);
shell.exit(1);
}
}
function assertTestSuccess(testFile) {
var code = run(testFile);
if (code !== 0) {
shell.exec(
"echo " +
filename +
": ERROR: " +
(testFile ? testFile + ": " : "") +
"Expected tests to pass >&2"
);
shell.exit(1);
}
}
shell.echo(filename + ": Uninstalling old elm-test...");
shell.exec("npm remove --ignore-scripts=false --global " + elmTest);
shell.echo(filename + ": Installing elm-test...");
shell.exec("npm link --ignore-scripts=false");
var interfacePath = require("elmi-to-json").paths["elmi-to-json"];
shell.echo(filename + ": Verifying installed elmi-to-json...");
var interfaceResult = spawn.sync(interfacePath, ["--help"]);
var interfaceExitCode = interfaceResult.status;
if (interfaceExitCode !== 0) {
shell.echo(
filename +
": Failed because `elmi-to-json` is present, but `elmi-to-json --help` returned with exit code " +
interfaceExitCode
);
shell.echo(interfaceResult.stdout.toString());
shell.echo(interfaceResult.stderr.toString());
shell.exit(1);
}
shell.echo(filename + ": Verifying installed elm-test version...");
run("--version");
shell.echo("### Testing elm-test on example-application/");
shell.cd("example-application");
assertTestFailure();
assertTestSuccess(path.join("tests", "*Pass*"));
assertTestFailure(path.join("tests", "*Fail*"));
shell.cd("../");
shell.echo("### Testing elm-test on example-package/");
shell.cd("example-package");
assertTestSuccess(path.join("tests", "*Pass*"));
assertTestFailure(path.join("tests", "*Fail*"));
assertTestFailure();
shell.cd("../");
shell.ls("tests/*.elm").forEach(function(testToRun) {
if (/Passing\.elm$/.test(testToRun)) {
shell.echo("\n### Testing " + testToRun + " (expecting it to pass)\n");
assertTestSuccess(testToRun);
} else if (/Failing\.elm$/.test(testToRun)) {
shell.echo("\n### Testing " + testToRun + " (expecting it to fail)\n");
assertTestFailure(testToRun);
} else if (/PortRuntimeException\.elm$/.test(testToRun)) {
shell.echo(
"\n### Testing " +
testToRun +
" (expecting it to error with a runtime exception)\n"
);
assertTestErrored(testToRun);
} else if (/Port\d\.elm$/.test(testToRun)){
shell.echo("\n### Skipping " + testToRun + " (helper file)\n");
return;
} else {
shell.echo(
"Tried to run " +
testToRun +
' but it has an invalid filename; node-test-runner tests should fit the pattern "*Passing.elm" or "*Failing.elm"'
);
shell.exit(1);
}
});
shell.echo("");
shell.echo(filename + ": Everything looks good!");
shell.echo(" ");
shell.echo(" __ ,_ _ __, -/- , __ __ _ , , ");
shell.echo("_(_/__/ (__(/_(_/(__/_ _/_)__(_/__(_,__(_,__(/__/_)__/_)_");
shell.echo(" _/_ ");
shell.echo("(/ ");
| JavaScript | 0 | @@ -3047,32 +3047,36 @@
%22tests%22, %22*Pass*
+.elm
%22));%0AassertTestF
@@ -3104,24 +3104,28 @@
ts%22, %22*Fail*
+.elm
%22));%0A%0Ashell.
@@ -3267,16 +3267,20 @@
%22*Pass*
+.elm
%22));%0Aass
@@ -3320,16 +3320,20 @@
%22*Fail*
+.elm
%22));%0Aass
|
082df1a1fd47c4ffbd11b08b2e8ee3564aa863ef | Use better rate filter | server/discord/cogs/rate/index.js | server/discord/cogs/rate/index.js | const config = require('config');
const crypto = require('crypto');
module.exports.info = {
name: 'Rate and Rank',
description: 'Interprets and determines the relevant rank for a query',
category: 'Fun',
aliases: [
'rate',
'rank'
],
use: [
{
name: '',
value: 'Rate the empty air of silence after you and your children\'s deaths, past the end of civilisation, past the end of our Sun, past the heat death of the universe, and is at a global temperature of absolute zero.'
}, {
name: '<thing>',
value: 'Rate the thing'
}
]
};
module.exports.command = (message) => {
if (message.input) {
const input = message.input.replace(/\W/g, '');
const hash = crypto.createHash('md5').update(input + config.get('secret')).digest('hex').substring(0, 4);
const rank = parseInt(hash, 16) % 11;
const thing = message.input.length < 100 ? input : `${input.substring(0, 100)}...`;
message.channel.createMessage(`I ${message.command} ${thing} a ${rank} out of 10`);
}
};
| JavaScript | 0.000003 | @@ -653,10 +653,95 @@
ce(/
-%5CW
+%5B%5E@ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5C%5C%5D%5E_%60abcdefghijklmno0123456789:;%3C=%3E?pqrstuvwxyz%7B%7C%7D~!%E3%83%84 %5D
/g,
|
83300944a0c17d344435455f3f44f053f27f6ec5 | fix selector | non-user-js/newthread_forum_list.js | non-user-js/newthread_forum_list.js | /*
MIT License
Copyright (c) 2016 Alex P. (alexp.frl@gmail.com, http://programmersforum.ru/member.php?u=129198)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
var newthreadForumList = new function() {
'use strict';
var self = this;
this.parseUrlQuery = function(queryStr) {
var dict = {};
var queries = queryStr.replace(/^\?/, '').split('&');
var i;
for (i = 0; i < queries.length; i++) {
var parts = queries[i].split('=');
dict[parts[0]] = parts[1];
}
return dict;
};
this.parseForums = function(html) {
var forums = [];
var elements = $(html).find('select[name="forumchoice[]"] option[class^="f"]');
var lastForum = null;
$.each(elements, function (i, el) {
var classAttr = $(el).attr('class');
var lastClassChar = classAttr.slice(-1);
if (lastClassChar === '0') {
lastForum = { name: $.trim(el.text), children: [] };
forums.push(lastForum);
} else {
var id = parseInt($(el).attr('value'));
if (id) {
lastForum.children.push({ name: $.trim(el.text), id: id });
}
}
});
return forums;
};
this.loadForums = function(callback, errorCallback) {
$.get('/search.php', function (html) {
callback(self.parseForums(html));
}).fail(errorCallback);
};
function createForumsListHtml(forums) {
var html = '<table cellpadding="0" cellspacing="0" border="0" class="fieldset"><tbody>';
html += '<tr><td class="smallfont" colspan="4">Уточните <b>раздел</b>, к которому относится вопрос:</td></tr>';
var comboboxHtml = '<select id="newthreadForum">';
$.each(forums, function (i, forum) {
comboboxHtml += '<optgroup label="' + forum.name + '">';
if (forum.children) {
$.each(forum.children, function (i, child) {
comboboxHtml += '<option value="' + child.id + '">' + child.name + '</option>';
});
}
comboboxHtml += '</optgroup>';
});
comboboxHtml += '</select>';
html += '<tr><td>' + comboboxHtml + '</td></tr>';
html += '</tbody></table>';
return html;
}
this.init = function(options) {
var defaultOptions = {
allNewThreadPages: false,
newthreadPagesIds: [ 31 ]
};
if (options === undefined) {
options = defaultOptions;
} else {
options = $.extend(defaultOptions, options);
}
if (window.newthreadForumListInitialized) {
return;
}
window.newthreadForumListInitialized = true;
var urlQuery = self.parseUrlQuery(window.location.search);
if (urlQuery['do'] !== 'newthread' && urlQuery['do'] !== 'postthread') {
return;
}
if (!options.allNewThreadPages && $.inArray(parseInt(urlQuery["f"]), options.newthreadPagesIds) < 0) {
return;
}
self.loadForums(function (forums) {
$(function() {
var form = $('form[name="vbform"]');
if (!form.length) {
return;
}
var forumInput = form.find('input[name="f"]');
if (!forumInput.length) {
return;
}
var currentForumId = forumInput.attr('value');
var titleTable = form.find('td.smallfont:contains("Заголовок:")').closest('table');
if (!titleTable.length) {
return;
}
var listHtml = createForumsListHtml(forums);
$(listHtml).insertBefore(titleTable);
var cbb = $('#newthreadForum');
cbb.find('option[value="' + currentForumId + '"]').prop('selected',true);
$('select').on('change', function() {
forumInput.attr('value', this.value);
});
});
});
};
};
| JavaScript | 0.000001 | @@ -5176,33 +5176,19 @@
-$('select').on('
+cbb.
change
-',
+(
func
|
a4138783341f6519734d7b88d14b57eaa9f77073 | fix karma timeout | src/config/karma.conf.js | src/config/karma.conf.js | 'use strict'
const merge = require('webpack-merge')
const webpack = require('webpack')
const webpackConfig = require('./webpack.config')
const { fromRoot, hasFile } = require('../utils')
const userConfig = require('./user')()
const isProduction = process.env.NODE_ENV === 'production'
const isWebworker = process.env.AEGIR_RUNNER === 'webworker'
// Env to pass in the bundle with DefinePlugin
const env = {
'process.env.AEGIR_RUNNER': JSON.stringify(process.env.AEGIR_RUNNER),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.IS_WEBPACK_BUILD': JSON.stringify(true),
TEST_DIR: JSON.stringify(fromRoot('test')),
TEST_BROWSER_JS: hasFile('test', 'browser.js')
? JSON.stringify(fromRoot('test', 'browser.js'))
: JSON.stringify('')
}
// Webpack overrides for karma
const karmaWebpackConfig = merge(webpackConfig({ production: isProduction }), {
entry: '',
devtool: 'inline-source-map',
output: {
libraryTarget: 'var'
},
plugins: [
new webpack.DefinePlugin(env)
]
})
const karmaConfig = (config, argv) => {
const files = argv.filesCustom
const mocha = {
reporter: 'spec',
timeout: Number(argv.timeout),
bail: argv.bail,
grep: argv.grep
}
const karmaEntry = `${__dirname}/karma-entry.js`
if (!files.length) {
// only try to load *.spec.js if we aren't specifying custom files
files.push(karmaEntry)
}
return {
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
frameworks: isWebworker ? ['mocha-webworker'] : ['mocha'],
basePath: process.cwd(),
files: files.map(f => {
return {
pattern: f,
included: !isWebworker
}
}).concat([
{
pattern: 'test/fixtures/**/*',
watched: false,
served: true,
included: false
}
]),
preprocessors: files.reduce((acc, f) => {
acc[f] = ['webpack', 'sourcemap']
return acc
}, {}),
client: {
mocha,
mochaWebWorker: {
pattern: [
...files,
'karma-entry.js'
],
mocha
}
},
webpack: karmaWebpackConfig,
webpackMiddleware: {
stats: 'errors-only'
},
reporters: [
argv.progress && 'progress',
!argv.progress && 'mocha',
process.env.CI && 'junit'
].filter(Boolean),
mochaReporter: {
output: 'autowatch',
showDiff: true
},
junitReporter: {
outputDir: process.cwd(),
outputFile: isWebworker ? 'junit-report-webworker.xml' : 'junit-report-browser.xml',
useBrowserName: false
},
plugins: [
'karma-chrome-launcher',
'karma-edge-launcher',
'karma-firefox-launcher',
'karma-junit-reporter',
'karma-mocha',
'karma-mocha-reporter',
'karma-mocha-webworker',
'karma-sourcemap-loader',
'karma-webpack'
],
autoWatch: false,
singleRun: true,
colors: true,
browserNoActivityTimeout: 50 * 1000
}
}
module.exports = (config) => {
var argv = require('yargs-parser')(process.argv.slice(2), {
array: ['files-custom'],
boolean: ['progress', 'bail'],
string: ['timeout']
})
config.set(merge(karmaConfig(config, argv), userConfig.karma))
}
| JavaScript | 0.000071 | @@ -1149,16 +1149,31 @@
timeout:
+ argv.timeout ?
Number(
@@ -1185,16 +1185,22 @@
timeout)
+: 5000
,%0A ba
|
409b2797144b54a26c7c64d63279f67ab910f344 | Make travis happy | server/startup/migrations/v061.js | server/startup/migrations/v061.js | RocketChat.Migrations.add({
version: 61,
up: function() {
RocketChat.models.Users.find({}).forEach((user) => {
RocketChat.models.Messages.updateAllNamesByUserId(user._id, user.name);
RocketChat.models.Subscriptions.setRealNameForDirectRoomsWithUsername(user.username, user.name);
});
}
});
| JavaScript | 0.000118 | @@ -53,24 +53,18 @@
ion() %7B%0A
-
+%09%09
RocketCh
@@ -108,28 +108,19 @@
r) =%3E %7B%0A
-
+%09%09%09
RocketCh
@@ -187,20 +187,11 @@
e);%0A
-
+%09%09%09
Rock
@@ -287,16 +287,10 @@
e);%0A
-
+%09%09
%7D);%0A
|
9804e5579f7e5e260749fa2bc4cc6cddceedb91d | Fix e-speed | mods/tsumeta/moves.js | mods/tsumeta/moves.js | /*List of flags and their descriptions:authentic: Ignores a target's substitute.bite: Power is multiplied by 1.5 when used by a Pokemon with the Ability Strong Jaw.bullet: Has no effect on Pokemon with the Ability Bulletproof.charge: The user is unable to make a move between turns.contact: Makes contact.defrost: Thaws the user if executed successfully while the user is frozen.distance: Can target a Pokemon positioned anywhere in a Triple Battle.gravity: Prevented from being executed or selected during Gravity's effect.heal: Prevented from being executed or selected during Heal Block's effect.mirror: Can be copied by Mirror Move.nonsky: Prevented from being executed or selected in a Sky Battle.powder: Has no effect on Grass-type Pokemon, Pokemon with the Ability Overcoat, and Pokemon holding Safety Goggles.protect: Blocked by Detect, Protect, Spiky Shield, and if not a Status move, King's Shield.pulse: Power is multiplied by 1.5 when used by a Pokemon with the Ability Mega Launcher.punch: Power is multiplied by 1.2 when used by a Pokemon with the Ability Iron Fist.recharge: If this move is successful, the user must recharge on the following turn and cannot make a move.reflectable: Bounced back to the original user by Magic Coat or the Ability Magic Bounce.snatch: Can be stolen from the original user and instead used by another Pokemon using Snatch.sound: Has no effect on Pokemon with the Ability Soundproof.*/
'use strict';
exports.BattleMovedex = {
"aircutter": {
inherit: true,
basePower: 110,
critRatio: 1,
accuracy: 85,
//UNABLE TO DO 1.2x IF HITTING SINGLE FOE.
},
"razorwind": {
inherit: true,
type: "Flying",
critRatio: 1,
flags: {protect: 1, mirror: 1},
desc: "Has a 10% chance to lower the foes special defense by 1.",
shortDesc: "10% chance to lower foes spd by 1.",
secondary: {
chance: 10,
target: {boosts: {spd: -1}},
}
},
"focusblast": {
inherit: true,
basePower: 100,
accuracy: 100
},
"aurasphere": {
inherit: true,
critRate: 2
},
"forcepalm": {
inherit: true,
basePower: 90,
secondary: {
chance: 15,
status: "par",
}
},
"closecombat": {
inherit: true,
basePower: 150,
self: {
boosts: {def: -1, spd: -1, spe: -1}
}
},
"extremespeed": {
inherit: true,
onTryHit: function (target) {
let broke = false;
for (let i in {kingsshield:1, protect:1, spikyshield:1}) {
if (target.removeVolatile(i)) broke = true;
}
let chance = Math.round(Math.random() * 99);
if (broke && chance < 30) {
this.add('-activate', target, 'move: Extreme Speed', '[broken]');
}
},
},
"toxic": {
inherit: true,
accuracy: 80
},
"wildcharge": {
inherit: true,
basePower: 120,
recoil: [1, 3]
},
"xscissor": {
inherit: true,
basePower: 100,
critRatio: 2,
},
"dragonrush": {
inherit: true,
basePower: 135,
accuracy: 85,
recoil: [1, 4],
secondary: {
chance: 10,
volatileStatus: 'flinch'
}
}
}
| JavaScript | 0.000559 | @@ -2483,25 +2483,42 @@
emespeed%22: %7B
+ //FAILED TO WORK
%0A
-
inhe
@@ -2562,24 +2562,79 @@
(target) %7B%0A
+ if (Math.floor(Math.random()*99) %3C 30) %7B%0A
@@ -2664,16 +2664,18 @@
+
+
for (let
@@ -2737,24 +2737,26 @@
+
if (target.r
@@ -2791,32 +2791,36 @@
ue;%0A
+
%7D%0A le
@@ -2821,93 +2821,27 @@
-let chance = Math.round(Math.random() * 99);%0A if (broke && chance %3C 30
+ if (broke
) %7B%0A
+
@@ -2918,16 +2918,34 @@
ken%5D');%0A
+ %7D%0A
|
86cad4be6e74677a59dcf4e6e8f60e2b9d954d8b | Rename arraySort to lexicalSort | module/fuzzyfinder.js | module/fuzzyfinder.js | exports.find = function(needle, haystack) {
needle = removeSpecialChars(needle)
if (needle.trim() == '') return []
var regex = new RegExp(needle.split('').join('.*?'))
var result = haystack.map(function(s) {
var info = regex.exec(s)
if (!info) return null
return [info[0].length, info.index, info.input]
}).filter(function(s) { return s != null })
result.sort(arraySort)
return result.map(function(x) { return x[2] })
}
function removeSpecialChars(input) {
return input.replace(/[.*+?^${}()|[\]\\]/g, '')
}
function arraySort(a, b) {
if (a.length == 0 || b.length == 0) return a.length - b.length
if (a[0] < b[0]) return -1
else if (a[0] > b[0]) return 1
return arraySort(a.slice(1), b.slice(1))
}
| JavaScript | 0.999985 | @@ -404,21 +404,23 @@
lt.sort(
-array
+lexical
Sort)%0A
@@ -572,21 +572,23 @@
unction
-array
+lexical
Sort(a,
@@ -740,13 +740,15 @@
urn
-array
+lexical
Sort
|
f086cd63ead67b30510970fc3fdeda337ef1a0e5 | fix test | test/data/propTemplates/siblingTemplates.rt.js | test/data/propTemplates/siblingTemplates.rt.js | define([
'react',
'lodash'
], function (React, _) {
'use strict';
function templateProp11(brother) {
return React.createElement('div', {}, 'Brother: ', brother);
}
function templateProp22(sister) {
return React.createElement('div', {}, 'Sister: ', sister);
}
function templateProp33(other) {
return React.createElement('div', {}, 'Other: ', other);
}
return function () {
return React.createElement('div', {
'templateProp1': templateProp11.bind(this),
'templateProp2': templateProp22.bind(this),
'templateProp3': templateProp33.bind(this)
}, React.createElement('div', {}, 'Separator'));
};
});
| JavaScript | 0.000002 | @@ -71,16 +71,45 @@
trict';%0A
+ return function () %7B%0A
func
@@ -131,32 +131,36 @@
op11(brother) %7B%0A
+
return R
@@ -208,38 +208,46 @@
, brother);%0A
-%7D%0A
+ %7D%0A
+
function templat
@@ -260,24 +260,28 @@
2(sister) %7B%0A
+
retu
@@ -331,24 +331,28 @@
', sister);%0A
+
%7D%0A fu
@@ -345,24 +345,28 @@
%7D%0A
+
+
function tem
@@ -378,32 +378,36 @@
Prop33(other) %7B%0A
+
return R
@@ -463,34 +463,13 @@
-%7D%0A
-return function () %7B
+%7D
%0A
|
6bed9883420b9fb8876c0ee71859d8712c293a30 | remove duplicate `export default` from Courses | views/sis/courses.js | views/sis/courses.js | // @flow
/**
* All About Olaf
* Courses page
*/
import React from 'react'
import {
StyleSheet,
View,
Text,
ListView,
TouchableHighlight,
RefreshControl,
} from 'react-native'
import * as c from '../components/colors'
import zip from 'lodash/zip'
import type {CourseType} from '../../lib/courses'
import {loadAllCourses} from '../../lib/courses'
import LoadingScreen from '../components/loading'
const SEMESTERS = {
'0': 'Abroad',
'1': 'Fall',
'2': 'Interim',
'3': 'Spring',
'4': 'Summer Session 1',
'5': 'Summer Session 2',
'9': 'Non-St. Olaf',
}
export default function semesterName(semester: number|string): string {
if (typeof semester === 'number') {
semester = String(semester)
}
return SEMESTERS.hasOwnProperty(semester)
? SEMESTERS[semester]
: `Unknown (${semester})`
}
function toPrettyTerm(term: number): string {
let str = String(term)
let semester = semesterName(term[4])
return `${semester} ${str.substr(0, 4)}`
}
export default class CoursesView extends React.Component {
state = {
dataSource: new ListView.DataSource({
rowHasChanged: this.rowHasChanged,
sectionHeaderHasChanged: this.sectionHeaderHasChanged,
}),
loading: true,
error: null,
}
componentWillMount() {
this.fetchData()
}
onRefresh = () => {
this.fetchData(true)
}
rowHasChanged(r1: CourseType, r2: CourseType) {
return r1.clbid !== r2.clbid
}
sectionHeaderHasChanged(h1: number, h2: number) {
return h1 !== h2
}
async fetchData(forceFromServer?: bool) {
try {
let courses = await loadAllCourses(forceFromServer)
this.setState({dataSource: this.state.dataSource.cloneWithRowsAndSections(courses)})
} catch (error) {
this.setState({error})
console.error(error)
}
this.setState({loading: false})
}
renderRow = (course: CourseType) => {
if (course.error) {
return (
<TouchableHighlight underlayColor={'#ebebeb'}>
<View style={styles.rowContainer}>
<Text style={styles.itemTitle}>Error: {course.error}</Text>
</View>
</TouchableHighlight>
)
}
let locationTimePairs = zip(course.locations, course.times)
let deptnum = `${course.department.join('/')} ${course.number}` + (course.section || '')
return (
<TouchableHighlight underlayColor={'#ebebeb'}>
<View style={styles.rowContainer}>
<Text style={styles.itemTitle} numberOfLines={1}>{course.name}</Text>
<Text style={styles.itemPreview} numberOfLines={2}>{deptnum}</Text>
{locationTimePairs.map(([place, time], i) =>
<Text key={i} style={styles.itemPreview} numberOfLines={1}>{place}: {time}</Text>)}
</View>
</TouchableHighlight>
)
}
renderSectionHeader = (courses: Object, term: number) => {
return (
<View style={styles.rowSectionHeader}>
<Text style={styles.rowSectionHeaderText} numberOfLines={1}>
{toPrettyTerm(term)}
</Text>
</View>
)
}
render() {
if (this.state.error) {
return <Text>Error: {this.state.error.message}</Text>
}
if (this.state.loading) {
return <LoadingScreen />
}
return (
<ListView
style={styles.listContainer}
dataSource={this.state.dataSource}
renderRow={this.renderRow}
renderSectionHeader={this.renderSectionHeader}
refreshControl={
<RefreshControl
refreshing={this.state.loading}
onRefresh={this.onRefresh}
/>
}
/>
)
}
}
const styles = StyleSheet.create({
listContainer: {
paddingBottom: 50,
backgroundColor: '#ffffff',
},
rowContainer: {
marginLeft: 10,
paddingRight: 10,
paddingTop: 8,
paddingBottom: 8,
borderBottomWidth: 1,
borderBottomColor: '#ebebeb',
},
itemTitle: {
color: c.black,
paddingLeft: 10,
paddingRight: 10,
paddingBottom: 3,
fontSize: 16,
textAlign: 'left',
},
itemPreview: {
color: c.iosText,
paddingLeft: 10,
paddingRight: 10,
fontSize: 13,
textAlign: 'left',
},
rowSectionHeader: {
backgroundColor: c.iosListSectionHeader,
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 20,
borderTopWidth: 1,
borderBottomWidth: 1,
borderColor: '#ebebeb',
},
rowSectionHeaderText: {
color: 'black',
fontWeight: 'bold',
},
})
| JavaScript | 0 | @@ -573,31 +573,16 @@
af',%0A%7D%0A%0A
-export default
function
|
5586194fa80eee1ec6ad73b5cc40f507d2d3c285 | Rename TextButton.button to TextButton.sprite | src/buttons.js | src/buttons.js | import * as PhaserObjects from './phaserObjects';
/** Group with some added functionality for text overlays.
* @private
* @extends Phaser.Group
*/
class TextGroup extends PhaserObjects.Group {
/**
* @param {Object} game - Current game instance.
* @param {number} x - The x coordinate on screen where the sprite will be placed.
* @param {number} y - The y coordinate on screen where the sprite will be placed.
*/
constructor(game, x, y) {
super(game, x, y);
this.game = game;
this.x = x;
this.y = y;
game.add.existing(this);
}
/**
* @param {string} label - The text to place on top of the sprite.
* @param {Object} style - The style properties to be set on the Text.
*/
setText(label, style) {
if (this.text) {
this.text.destroy();
}
if (this.version === 3) {
this.text = this.game.add.text(0, 0, label, style);
this.text.setOrigin(0.5, 0.5);
} else {
this.text = this.game.add.text(this.width / 2, this.height / 2, label, style);
this.text.anchor.set(0.5, 0.5);
}
this.add(this.text);
this.text.wordWrap = true;
this.text.wordWrapWidth = this.width;
return this;
}
/** When setOrigin is called, align the text as well. */
setOrigin(x, y) {
this.sprite.setOrigin(x, y);
this.text.x = this.sprite.width / 2;
this.text.y = this.sprite.height / 2;
return this;
}
}
/** Sprite with text added as a child.
* @extends Phaser.Group
*/
export class TextSprite extends TextGroup {
/**
* @param {Object} game - Current game instance.
* @param {number} x - The x coordinate on screen where the textSprite will be placed.
* @param {number} y - The y coordinate on screen where the textSprite will be placed.
* @param {string} key - The image to create a sprite with.
*/
constructor(game, x, y, key) {
super(game, x, y);
this.sprite = new PhaserObjects.Sprite(game, 0, 0, key);
this.add(this.sprite);
this.width = this.sprite.width;
this.height = this.sprite.height;
}
}
/** Phaser Group containing a button with text anchored in the button's center.
* @extends Phaser.Group
*/
export class TextButton extends TextGroup {
/**
* @param {Object} game - Current game instance.
* @param {number} x - The x coordinate on screen where the textSprite will be placed.
* @param {number} y - The y coordinate on screen where the textSprite will be placed.
* @param {string} key - The image to create a sprite with.
* @param {Object} callback - Callback to use when the button is clicked.
* @param {Object} callbackContext - The context the callback is called in.
* @param {number} overKey - The frame to switch to when an over event is triggered.
* @param {number} outKey - The frame to switch to when an out event is triggered.
* @param {number} downKey - The frame to switch to when a down event is triggered.
* @param {number} upKey - The frame to switch to when an up event is triggered.
*/
constructor(game, x, y, key, callback, callbackContext, overKey, outKey, downKey, upKey) {
super(game, x, y);
this.button = new PhaserObjects.Button(
game,
0,
0,
key,
callback,
callbackContext,
overKey,
outKey,
downKey,
upKey,
);
this.add(this.button);
this.width = this.button.width;
this.height = this.button.height;
}
/** Adds an adjustment to the text on down/up events. */
eventTextYAdjustment(number) {
const startY = this.text.y;
this.button.addDownEvent(() => { this.text.y += number; });
this.button.addUpEvent(() => { this.text.y = startY; });
// A pointerout event should reset the text position too.
this.button.addOutEvent(() => { this.text.y = startY; });
return this;
}
}
| JavaScript | 0.000988 | @@ -3332,22 +3332,22 @@
this.
-button
+sprite
= new P
@@ -3597,22 +3597,22 @@
dd(this.
-button
+sprite
);%0A%0A
@@ -3633,22 +3633,22 @@
= this.
-button
+sprite
.width;%0A
@@ -3674,22 +3674,22 @@
= this.
-button
+sprite
.height;
@@ -3838,30 +3838,30 @@
this.
-button
+sprite
.addDownEven
@@ -3906,30 +3906,30 @@
this.
-button
+sprite
.addUpEvent(
@@ -4042,22 +4042,22 @@
this.
-button
+sprite
.addOutE
|
3afde8909a60a74d4539b19cdf44f99f5ea75ee9 | add y axis label to timeline | timeline.js | timeline.js | createTimeline = function(domId) {
var xScale;
var barWidth;
var yScale;
var vis;
var width = 100;
var height = 100;
var padding = 20;
const SVG_ID = "svg_" + domId;
var selectCallback = function(key) {
console.log("Default callback, please pass callback to onSelect.");
}
function setX(buckets) {
var bucketWidth = buckets[1].key - buckets[0].key;
var mindate = buckets[0].key;
var maxdate = buckets[buckets.length - 1].key;
//pad min/max so centered bars do not overlow
mindate = mindate - (bucketWidth/2);
maxdate = maxdate + (bucketWidth/2);
xScale = d3.time.scale()
.domain([mindate, maxdate])
.range([0, width]);
const barGap = 4;
barWidth = xScale(buckets[1].key) - xScale(buckets[0].key);
if(barWidth > 10) barWidth = barWidth - barGap; //only pad bars when they are large
if(barWidth <= 0) barWidth = 1;
}
function setY(buckets) {
var min = 0;
var max = buckets[0].doc_count;
buckets.forEach(function(bucket) {
var val = bucket.doc_count;
if(bucket.seasonal_avg && bucket.seasonal_avg.value > val) val = bucket.seasonal_avg.value;
if(val > max) max = val;
});
yScale = d3.scale.linear()
.domain([min, max])
.range([height - padding, 0]);
}
function clear() {
d3.select('#' + SVG_ID).remove();
}
function initVis(buckets) {
width = document.getElementById(domId).offsetWidth;
height = document.getElementById(domId).offsetHeight;
setX(buckets);
setY(buckets);
clear();
vis = d3.select('#' + domId)
.append("svg:svg")
.attr("width", width)
.attr("height", height)
.attr("id", SVG_ID);
var xAxis = d3.svg.axis()
.orient("bottom")
.scale(xScale);
vis.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height - padding) + ")")
.call(xAxis);
}
function drawMovingAvg(buckets) {
var lineFunction = d3.svg.line()
.x(function(d) { return xScale(d.key); })
.y(function(d) {
var y = 0;
if(d.seasonal_avg) y = d.seasonal_avg.value;
return yScale(y);
})
.interpolate("linear");
vis.append("path")
.attr("class", "movingAvg")
.attr("d", lineFunction(buckets));
}
function makeId(key) {
return "date_histo_bucket_" + key;
}
return {
clear : function() {
clear();
},
draw : function(buckets) {
initVis(buckets);
vis.selectAll(".bar")
.data(buckets)
.enter().append("rect")
.attr("class", "bar")
.attr("id", function(d) {return makeId(d.key);})
.attr("x", function(d) { return xScale(d.key) - (barWidth/2); })
.attr("width", barWidth)
.attr("y", function(d) { return yScale(d.doc_count); })
.attr("height", function(d) { return (height - padding) - yScale(d.doc_count); })
.on("click", function() {
d3.selectAll(".selectedBar")
.attr("class", "bar")
var selected = d3.select(this);
selected.attr("class", "selectedBar");
d3.event.stopPropagation();
selectCallback(selected.data()[0].key);
});
drawMovingAvg(buckets);
},
onSelect : function(callback) {
selectCallback = callback;
},
selectBucket : function(bucketKey) {
var event = document.createEvent("SVGEvents");
event.initEvent("click",true,true);
var selection = d3.select('#' + makeId(bucketKey));
selection[0][0].dispatchEvent(event);
}
}
} | JavaScript | 0.000001 | @@ -118,24 +118,47 @@
ight = 100;%0A
+ var leftMargin = 45;%0A
var paddin
@@ -692,17 +692,26 @@
.range(%5B
-0
+leftMargin
, width%5D
@@ -1728,16 +1728,17 @@
VG_ID);%0A
+%0A
var
@@ -1944,16 +1944,239 @@
xAxis);%0A
+%0A var yAxis = d3.svg.axis()%0A .scale(yScale)%0A .orient(%22left%22)%0A .ticks(5);%0A vis.append(%22g%22)%0A .attr(%22class%22, %22y axis%22)%0A .attr(%22transform%22, %22translate(%22 + leftMargin + %22,0)%22)%0A .call(yAxis);%0A%0A
%7D%0A%0A f
|
663cad8c682c34fa79ab54a9f4a699fd4b7f6010 | remove G operator, apperantly this version of ecmascript is not yet compatiable. Additionally the G opperator is not easily transpileable, so we will have to wait till runtimes support it natively... | Brocfile.js | Brocfile.js | /* jshint node:true, undef:true, unused:true */
var AMDFormatter = require('es6-module-transpiler-amd-formatter');
var closureCompiler = require('broccoli-closure-compiler');
var compileModules = require('broccoli-compile-modules');
var mergeTrees = require('broccoli-merge-trees');G
var moveFile = require('broccoli-file-mover');
var concat = require('broccoli-concat');
var replace = require('broccoli-string-replace');
var calculateVersion = require('./lib/calculateVersion');
var path = require('path');
var trees = [];
var bundle = compileModules('lib', {
inputFiles: ['rsvp.umd.js'],
output: '/rsvp.js',
formatter: 'bundle',
});
trees.push(bundle);
trees.push(compileModules('lib', {
inputFiles: ['**/*.js'],
output: '/amd/',
formatter: new AMDFormatter()
}));
if (process.env.ENV === 'production') {
trees.push(closureCompiler(moveFile(bundle, {
srcFile: 'rsvp.js',
destFile: 'rsvp.min.js'
}), {
compilation_level: 'ADVANCED_OPTIMIZATIONS',
}));
}
var distTree = mergeTrees(trees.concat('config'));
var distTrees = [];
distTrees.push(concat(distTree, {
inputFiles: [
'versionTemplate.txt',
'rsvp.js'
],
outputFile: '/rsvp.js'
}));
if (process.env.ENV === 'production') {
distTrees.push(concat(distTree, {
inputFiles: [
'versionTemplate.txt',
'rsvp.min.js'
],
outputFile: '/rsvp.min.js'
}));
}
distTree = mergeTrees(distTrees);
var distTree = replace(distTree, {
files: [
'rsvp.js',
'rsvp.min.js'
],
pattern: {
match: /VERSION_PLACEHOLDER_STRING/g,
replacement: calculateVersion()
}
});
module.exports = distTree;
| JavaScript | 0 | @@ -275,17 +275,16 @@
trees');
-G
%0Avar mov
|
f56b39607a96ad1785ee7a5a8d0e4d947780abfc | Add globals to build output | Brocfile.js | Brocfile.js | var filterES6Modules = require('broccoli-es6-module-filter'),
concat = require('broccoli-concat'),
pkg = require('./package');
module.exports = function(broccoli) {
var global = 'Ember',
namespace = 'DeviseSimpleAuth';
var appTree = broccoli.makeTree('app'),
configTree = broccoli.makeTree('config');
var amdTree = filterES6Modules(appTree, {
moduleType: 'amd',
main: 'index',
packageName: 'app',
anonymous: false
});
var pluginTree = filterES6Modules(configTree, {
moduleType: 'amd',
main: 'plugin',
packageName: pkg.name,
anonymous: false
});
return concat(new broccoli.MergedTree([amdTree, pluginTree]), {
inputFiles: ['**/*.js'],
outputFile: '/index.js'
});
};
| JavaScript | 0.000002 | @@ -615,14 +615,312 @@
%0A%0A
-return
+var globalTree = filterES6Modules(new broccoli.MergedTree(%5BappTree, configTree%5D), %7B%0A moduleType: 'globals',%0A global: global,%0A namespace: namespace,%0A anonymous: false%0A %7D);%0A%0A globalTree = concat(globalTree, %7B%0A inputFiles: %5B'**/*.js'%5D,%0A outputFile: '/globals/index.js'%0A %7D);%0A%0A amdTree =
con
@@ -1020,16 +1020,23 @@
File: '/
+appkit/
index.js
@@ -1042,12 +1042,45 @@
s'%0A %7D);
+%0A%0A return %5BglobalTree, amdTree%5D;
%0A%7D;%0A
|
67a1f37bac0c21bda38ec5ee49ecebc55a1fc818 | change emit timing | Building.js | Building.js | Building = function(game, x, y, resource) {
Phaser.Sprite.call(this, game, x, y, resource);
this.anchor.setTo(0.5, 0.5);
this.lastWavesSentTime = 0;
};
Building.prototype = Object.create(Phaser.Sprite.prototype);
Building.prototype.constructor = Building;
Building.prototype.doTick = function(time) {
var time = new Date();
var delta = Math.round(Math.random()*3) + 1
if ((time/1000 - this.lastWavesSentTime / 1000) > delta) {
this.sendWaves();
this.lastWavesSentTime = time;
}
}; | JavaScript | 0.000001 | @@ -375,9 +375,10 @@
m()*
-3
+11
) +
|
107c19530cb8f5cca997c5f7bc6f91f185d5b9c8 | Add TODO comment about defineMessages() | src/react-intl.js | src/react-intl.js | /*
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
import {__addLocaleData as addIMFLocaleData} from 'intl-messageformat';
import {__addLocaleData as addIRFLocaleData} from 'intl-relativeformat';
import defaultLocaleData from './en';
export {default as IntlProvider} from './components/intl';
export {default as FormattedGroup} from './components/group';
export {default as FormattedDate} from './components/date';
export {default as FormattedTime} from './components/time';
export {default as FormattedRelative} from './components/relative';
export {default as FormattedNumber} from './components/number';
export {default as FormattedPlural} from './components/plural';
export {default as FormattedMessage} from './components/message';
export {default as FormattedHTMLMessage} from './components/html-message';
export {intlShape} from './types';
export function defineMessage(messageDescriptor) {
// TODO: Type check in dev? Return something different?
return messageDescriptor;
}
export function addLocaleData(data = []) {
let locales = Array.isArray(data) ? data : [data];
locales.forEach((localeData) => {
addIMFLocaleData(localeData);
addIRFLocaleData(localeData);
});
}
addLocaleData(defaultLocaleData);
| JavaScript | 0 | @@ -924,24 +924,103 @@
'./types';%0A%0A
+// TODO Should there be a %60defineMessages()%60 function that takes a collection?%0A
export funct
|
8fe16187a8253e3d73e9bbf334b7ff1aa406a999 | move whitelist.length up | src/browser/predicates.js | src/browser/predicates.js | var _ = require('../utility');
var logger = require('./logger');
function checkIgnore(item, settings) {
var level = item.level;
var levelVal = _.LEVELS[level] || 0;
var reportLevel = _.LEVELS[settings.reportLevel] || 0;
if (levelVal < reportLevel) {
return false;
}
var plugins = settings.plugins || {};
if (plugins && plugins.jquery && plugins.jquery.ignoreAjaxErrors) {
try {
return !(item.data.body.message.extra.isAjax);
} catch (e) {
return true;
}
}
return true;
}
function userCheckIgnore(item, settings) {
try {
if (_.isFunction(settings.checkIgnore) && settings.checkIgnore(item, settings)) {
return false;
}
} catch (e) {
settings.checkIgnore = null; // TODO
logger.error('Error while calling custom checkIgnore(), removing', e);
}
return true;
}
function urlIsWhitelisted(item, settings) {
var whitelist, trace, frame, filename, frameLength, url, listLength, urlRegex;
var i, j;
try {
whitelist = settings.hostWhiteList;
trace = item && item.data && item.data.body && item.data.body.trace;
if (!whitelist || whitelist.length === 0) {
return true;
}
if (!trace || !trace.frames) {
return true;
}
listLength = whitelist.length;
frameLength = trace.frames.length;
for (i = 0; i < frameLength; i++) {
frame = trace.frames[i];
filename = frame.filename;
if (!_.isType(filename, 'string')) {
return true;
}
for (j = 0; j < listLength; j++) {
url = whitelist[j];
urlRegex = new RegExp(url);
if (urlRegex.test(filename)){
return true;
}
}
}
} catch (e)
/* istanbul ignore next */
{
settings.hostWhiteList = null; // TODO
logger.error('Error while reading your configuration\'s hostWhiteList option. Removing custom hostWhiteList.', e);
return true;
}
return false;
}
function messageIsIgnored(item, settings) {
var exceptionMessage, i, ignoredMessages, len, messageIsIgnored, rIgnoredMessage, trace, body, traceMessage, bodyMessage;
try {
messageIsIgnored = false;
ignoredMessages = settings.ignoredMessages;
if (!ignoredMessages || ignoredMessages.length === 0) {
return true;
}
body = item &&
item.data &&
item.data.body;
traceMessage = body &&
body.trace &&
body.trace.exception &&
body.trace.exception.message;
bodyMessage = body &&
body.message &&
body.message.body;
exceptionMessage = traceMessage || bodyMessage;
if (!exceptionMessage){
return true;
}
len = ignoredMessages.length;
for (i = 0; i < len; i++) {
rIgnoredMessage = new RegExp(ignoredMessages[i], 'gi');
messageIsIgnored = rIgnoredMessage.test(exceptionMessage);
if (messageIsIgnored) {
break;
}
}
} catch(e)
/* istanbul ignore next */
{
settings.ignoredMessages = null; // TODO
logger.error('Error while reading your configuration\'s ignoredMessages option. Removing custom ignoredMessages.');
}
return !messageIsIgnored;
}
module.exports = {
checkIgnore: checkIgnore,
userCheckIgnore: userCheckIgnore,
urlIsWhitelisted: urlIsWhitelisted,
messageIsIgnored: messageIsIgnored
};
| JavaScript | 0.000006 | @@ -1017,16 +1017,64 @@
teList;%0A
+ listLength = whitelist && whitelist.length;%0A
trac
@@ -1161,27 +1161,21 @@
list %7C%7C
-white
list
-.l
+L
ength ==
@@ -1271,43 +1271,8 @@
%7D%0A%0A
- listLength = whitelist.length;%0A
|
9aaaba7d259a8643ff7d01044fafb7bcfa633e9d | fix iconSrc type | modules/icon/index.js | modules/icon/index.js | const fs = require('fs-extra')
const path = require('path')
const Jimp = require('jimp')
const fixUrl = url => url.replace(/\/\//g, '/').replace(':/', '://')
const isUrl = url => url.indexOf('http') === 0 || url.indexOf('//') === 0
module.exports = function nuxtIcon (options, cb) {
const iconSrc = options.src || path.resolve(this.options.srcDir, 'static', 'icon.png')
const sizes = options.sizes || [16, 120, 144, 152, 192, 384, 512]
// routerBase and publicPath
const routerBase = this.options.router.base
let publicPath = fixUrl(`${routerBase}/${this.options.build.publicPath}`)
if (isUrl(this.options.build.publicPath)) { // CDN
publicPath = this.options.build.publicPath
if (publicPath.indexOf('//') === 0) {
publicPath = '/' + publicPath // escape fixUrl
}
}
Jimp.read(iconSrc).then(srcIcon => {
// get base64 phash of source image
const hash = srcIcon.hash()
Promise.all(sizes.map(size => new Promise((resolve, reject) => {
srcIcon.clone().contain(size, size).getBuffer(Jimp.MIME_PNG, (err, buff) => {
if (err) {
return reject(err)
}
let fileName = `icons/icon_${size}.${hash}.png`
resolve({ size, buff, fileName })
})
}))).then(icons => {
// Fill manifest icons
if (!this.options.manifest) {
this.options.manifest = {}
}
if (!this.options.manifest.icons) {
this.options.manifest.icons = []
}
icons.forEach(icon => {
this.options.manifest.icons.push({
src: fixUrl(`${publicPath}/${icon.fileName}`),
sizes: `${icon.size}x${icon.size}`,
type: `image/png`
})
})
// Register webpack plugin to emit icons
this.options.build.plugins.push({
apply (compiler) {
compiler.plugin('emit', function (compilation, _cb) {
icons.forEach(icon => {
compilation.assets[icon.fileName] = {
source: () => icon.buff,
size: () => icon.buff.length
}
})
_cb()
})
}
})
// Well done
return cb()
})
}).catch(err => {
console.error('[icon] unable to read', err)
return cb()
})
}
module.exports.meta = require('./package.json')
| JavaScript | 0.000002 | @@ -304,17 +304,21 @@
options.
-s
+iconS
rc %7C%7C pa
|
3b4d7317488aa2cc9f0de76fb47731d5bd9489a9 | Remove logs | src/routes/api.js | src/routes/api.js | // Api Routes --
// RESTful API cheat sheet : http://ricostacruz.com/cheatsheets/rest-api.html
var express = require('express'),
router = express.Router(),
db = require('../modules/database'),
schema = require('../modules/schema'),
passport = require('passport');
/* Check if API is up */
router.get('/', function(req, res) {
res.json({
message: 'Server is running'
});
});
var responseInsufficientRights = function(req, res) {
return res.status(401).json({
title: req.t('Error'),
message: req.t('Insufficient rights'),
status: 'error'
});
};
var responseCatchError = function(e, req, res) {
console.log('error', e);
res.status(401).json({
title: req.t('Error'),
message: e.property ? e.property.getErrorLabel(e.type, req) : e,
status: 'error'
});
};
// -- Auth system (API methods below are protected) --
router.use(function (req, res, next) {
passport.authenticate('jwt', function(err, user, info) {
if (!info) {
req.user = user;
req.i18n.changeLanguage(req.user.language);
return next();
}
// If an message (error) occurs --
if (info === {}) {
info.error = req.t('Unauthorized');
info.title = req.t('Error');
}
else if(info instanceof Error) {
info.error = info.message;
}
res.status(401).json({
title: info.title || req.t('Error', {lng: 'en'}),
message: info.error,
status: 'error'
});
// If not, continue --
})(req, res, next);
});
// -- ConfigClass Parameter --
router.param('configClass', function (req, res, next, configClass) {
configClass = schema.getConfigClassByPath(configClass);
if(!configClass)
return res.status(404).send('This config class does\'n exists.');
else {
req.params.configClass = configClass;
next();
}
});
// Listing --
router.get('/:configClass', function(req, res) {
var configClass = req.params.configClass;
// if(configClass.type === 'user' && req.user.role != 'admin')
// return responseInsufficientRights(req, res);
configClass.getAllWithReferences({req: req})
.then(function (items) {
var result = {};
result[configClass.path] = items ? items : [];
res.status(200).json(result);
});
});
// Creation --
router.post('/:configClass', function(req, res) {
var configClass = req.params.configClass;
if(req.user.role === 'viewer')
return responseInsufficientRights(req, res);
if(configClass.type === 'user' && req.user.role != 'admin')
return responseInsufficientRights(req, res);
configClass.createFromReq(req)
.then(function (items) {
var result = {
title: req.t('Created'),
status: 'success'
};
if (Array.isArray(items)) {
result.rid = [];
items.forEach((item) => { result.rid.push(item.rid); });
result.message= req.t('Created_description', {type: configClass.getLabel(req), count: items.length});
} else {
result.rid = items.rid;
result.message= req.t('Created_description', {type: configClass.getLabel(req)});
}
return res.status(201).json(result);
})
.catch((e) => { responseCatchError(e, req, res); });
});
// Rid parameter --
router.param('rid', function (req, res, next, rid) {
req.params.rid = db.helper.unsimplifyRid(rid);
var configClass = req.params.configClass;
if(configClass.type === 'user' && req.user.role !== 'admin' ) {
if(rid === req.user.rid) {
req.editBypass = true;
req.userEditSituation = true;
}
else {
return responseInsufficientRights(req, res);
}
}
next();
});
// Reading --
router.get('/:configClass/:rid', function(req, res) {
var configClass = req.params.configClass;
configClass.getByRid(req.params.rid, {req: req})
.then(function (item) {
res.status(200).json(item);
});
});
// Edition --
router.put('/:configClass/:rid', function(req, res) {
if(req.user.role === 'viewer' && !req.editBypass)
return responseInsufficientRights(req, res);
if(req.userEditSituation) {
req.body['role'] = undefined;
}
var configClass = req.params.configClass;
configClass.updateFromReq(req.params.rid, req)
.then(function () {
return res.status(201).json({
title: req.t('Edited'),
message: req.t('Edited_description', {type: configClass.getLabel(req)}),
status: 'success'
});
})
.catch((e) => { responseCatchError(e, req, res); });
});
// Removal --
router.delete('/:configClass/:rid', function(req, res) {
if(req.user.role === 'viewer' || req.editBypass)
return responseInsufficientRights(req, res);
var configClass = req.params.configClass;
configClass.deleteByRid(req.params.rid)
.then(function () {
res.status(200).json({
title: req.t('Deleted'),
message: req.t('Deleted_description', {type: configClass.getLabel(req)}),
status: 'success'
});
});
});
router.use(function(req, res) {
return res.status(404).json({
title: req.t('Error'),
message: req.t('Route not found'),
status: 'error'
});
});
module.exports = router;
| JavaScript | 0.000001 | @@ -649,35 +649,8 @@
) %7B%0A
- console.log('error', e);%0A
re
|
803a6c069f20ddbc02606004e0461d3d5640f883 | fix typo | babel_es2015/src/core/decorators.js | babel_es2015/src/core/decorators.js | export default function decorators() {
console.group('ES-next: Stage-2: decorators');
{
console.group('Base');
console.log(`
class Hoge {
@decorator
instance = 1;
@decorator()
method() {
console.log('Hoge.prototype.method()');
}
}
function decorator(...args) {
console.log('decorator()', ...args);
return function(target, key, descriptor) {
console.log('decorator(): target =>', target);
console.log('decorator(): key =>', key);
console.log('decorator(): descriptor =>', descriptor);
return descriptor;
};
}
`);
class Hoge {
@decorator
instance = 1;
@decorator()
method() {
console.log('Hoge.prototype.method()');
}
}
function decorator(...args) {
console.log('decorator()', ...args);
return (target, key, descriptor) => {
console.log('decorator(): target =>', target);
console.log('decorator(): key =>', key);
console.log('decorator(): descriptor =>', descriptor);
return descriptor;
};
}
const hoge = new Hoge();
hoge.method();
}
console.groupEnd();
}
console.groupEnd();
}
| JavaScript | 0.999716 | @@ -108,24 +108,30 @@
up('Base');%0A
+ %7B%0A
consol
|
b9e897bd8c51787d002fa2ce1c150f49f1842b12 | create category factory -> server | client/app.js | client/app.js | var app = angular.module("itemsApp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider.when("/", {
templateUrl: "/partials/items-index.html",
controller: "itemsIndexController"
}).when("/new", {
templateUrl: "/partials/new-item.html",
controller: "newItemController"
}).when("/new-category", {
templateUrl: "/partials/new-category.html",
controller: "newCategoryController"
});
});
app.factory("itemFactory", function ($http) {
var factory = {};
factory.getAllItems = function (foundItems) {
$http.get("/api/items").then(function (response) {
console.log("RESPONSE:", response);
foundItems(response.data.items);
});
};
factory.createItem = function (item, createdItem) {
$http.post("/api/items", item).then(function (response) {
createdItem(true);
}).catch(function (error) {
createdItem(false);
});
};
factory.createSubItem = function (item, subItem, createdSubItem) {
$http.post("/api/items/" + item._id + "/subitems", subItem).then(function (response) {
createdSubItem(true);
}).catch(function (error) {
createdSubItem(false);
});
};
return factory;
});
app.controller("itemsIndexController", function ($scope, itemFactory) {
function loadItemsIntoScope () {
itemFactory.getAllItems(function (items) {
console.log("ITEMS:", items);
$scope.items = items;
});
}
loadItemsIntoScope();
$scope.submitSubItemForm = function (item, subItem) {
itemFactory.createSubItem(item, subItem, function (success) {
if (success) {
alert("SUCCESS");
loadItemsIntoScope();
} else {
alert("ERROR");
}
});
}
});
app.controller("newItemController", function ($scope, $location, itemFactory){
$scope.submitForm = function () {
itemFactory.createItem($scope.item, function (success) {
if (success) {
alert("SUCCESS");
$location.url("/");
} else {
alert("ERROR");
}
});
};
});
app.controller("newCategoryController", function ($scope) {
$scope.submitForm = function () {
alert($scope.category.name);
}
});
| JavaScript | 0 | @@ -680,32 +680,328 @@
);%0A %7D);%0A %7D;%0A
+ factory.createCategory = function (category, createdCategory) %7B%0A $http.post(%22/api/categories%22, category).then(function (response) %7B%0A console.log(%22CATEGORY:%22, response.data.category);%0A createdCategory(true);%0A %7D).catch(function (error) %7B%0A createdCategory(false);%0A %7D);%0A %7D%0A
factory.create
@@ -2369,16 +2369,29 @@
($scope
+, itemFactory
) %7B%0A $s
@@ -2430,36 +2430,173 @@
-alert($scope.category.name);
+itemFactory.createCategory($scope.category, function (success) %7B%0A if (success) %7B%0A alert(%22SUCCESS%22);%0A %7D else %7B%0A alert(%22ERROR%22);%0A %7D%0A %7D)
%0A %7D
|
54ba2c5044d03ac67f579921b4fda81e3775599b | Fix day selection. | client/app.js | client/app.js | Meteor.subscribe('events');
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
Template.calendar.created = function() {
Session.set('selectedMonth', moment().startOf('month').toDate());
};
Template.calendar.helpers({
monthName: function(month) {
return monthNames[Session.get('selectedMonth').getMonth()];
},
weeks: function() {
var currentMonth = moment(Session.get('selectedMonth'));
var firstOfMonth = currentMonth.clone().startOf('month');
var firstOfWeek = firstOfMonth.clone().startOf('week');
var endOfMonth = currentMonth.clone().endOf('month');
var endOfWeek = endOfMonth.clone().endOf('week');
var weeksOfMonth = [];
var range = moment().range(firstOfWeek, endOfWeek);
range.by('weeks', function(week) {
var currentWeek = [];
moment()
.range(week.clone().startOf('week'), week.clone().endOf('week'))
.by('days', function(day) {
currentWeek.push(day);
});
weeksOfMonth.push(currentWeek);
});
return weeksOfMonth;
},
});
Template.calendar.events({
'click .increment-month': function() {
var date = moment(Session.get('selectedMonth'));
Session.set('selectedMonth', date.add('month', 1).toDate());
},
'click .decrement-month': function() {
var date = moment(Session.get('selectedMonth'));
Session.set('selectedMonth', date.subtract('month', 1).toDate());
},
});
Template.day.helpers({
dayOfMonth: function(date) {
return date.date();
},
isInMonth: function(date) {
return date.month() === Session.get('selectedMonth').getMonth() ? 'day-in-month' : 'day-out-of-month';
},
theEvents: function(date) {
date = moment(date);
return Events.find({ date: { $gte: date.clone().startOf('day').toDate(), $lte: date.clone().endOf('day').toDate() } });
},
});
Template.day.events({
'click .calendar-day': function() {
var month = moment(Session.get('selectedMonth'));
var date = moment(this);
date = month.day(date.date());
Session.set('selectedDay', date.toDate());
$('#add_event_modal').modal();
},
});
Template.add_event_modal.helpers({
eventDate: function() {
return moment(Session.get("selectedDay")).format("dddd, MMMM Do YYYY");
},
});
Template.add_event_modal.events({
'click button.new-event': function() {
var titleField = $('#new_event_title')[0];
var timeField = $('#new_event_time')[0];
var date = moment(Session.get('selectedDay'));
var time = moment(timeField.value, "HH:mm");
date.startOf('day').hour(time.hour());
date.minute(time.minute());
var obj = {
name: titleField.value,
date: date.toDate(),
};
Events.insert(obj);
titleField.value = '';
timeField.value = '';
$('#add_event_modal').modal('hide');
},
});
Template.add_event_modal.rendered = function () {
$('.clockpicker').clockpicker();
};
| JavaScript | 0 | @@ -1896,111 +1896,41 @@
var
-month = moment(Session.get('selectedMonth'));%0A%09%09var date = moment(this);%0A%09%09date = month.day(date.date()
+date = moment(this).startOf('day'
);%0A%09
|
6af6a2dec1cc0eaf36a627ff56580416851f0ec5 | remove dead code try searching | client/app.js | client/app.js |
window.AudioContext = window.AudioContext||window.webkitAudioContext;
var gAudioContext = new AudioContext();
var myAudioElement = null;
var mySource = null;
function playSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
gAudioContext.decodeAudioData(request.response, function(inBuffer) {
var aBufferSource = gAudioContext.createBufferSource();
aBufferSource.buffer = inBuffer;
aBufferSource.connect(gAudioContext.destination);
aBufferSource.start();
}, function (e) {
console.log('error handler', e);
});
}
request.send();
}
window.onload = function(){
freesound.setToken("1beba8e340a9f1b0fad8c5bf14f0361df331a6fb");
freesound.getSound(96541,
function(sound){
var msg = "";
msg = "<h3>Getting info of sound: " + sound.name + "</h3>";
msg += "<strong>Url:</strong> " + sound.url + "<br>";
msg += "<strong>Description:</strong> " + sound.description + "<br>";
msg += "<strong>Tags:</strong><ul>";
for (i in sound.tags){
msg += "<li>" + sound.tags[i] + "</li>";
}
msg += "</ul><br>";
msg += "<img src='" + sound.images.waveform_l + "'>";
if (true) {
playSound(sound.previews['preview-hq-mp3']);
} else {
myAudioElement = new Audio(sound.previews['preview-hq-mp3']);
myAudioElement.setAttribute('crossorigin', 'anonymous')
mySource = gAudioContext.createMediaElementSource(myAudioElement);
mySource.connect(gAudioContext.destination);
}
displayMessage(msg,'resp1');
}, function(){ displayError("Sound could not be retrieved.")}
);
};
function displayError(text){
document.getElementById('error').innerHTML=text;
}
function displayMessage(text,place){
document.getElementById(place).innerHTML=text;
}
| JavaScript | 0.000001 | @@ -856,16 +856,210 @@
1a6fb%22);
+%0A%0A freesound.textSearch('piano', %7B%7D, function(results) %7B%0A console.log('textsearch', results);%0A %7D, function(err) %7B%0A console.log('textsearch err', err);%0A %7D);
%0A %0A
@@ -1676,85 +1676,36 @@
-if (true) %7B%0A playSound(sound.previews%5B'preview-hq-mp3'%5D
+displayMessage(msg,'resp1'
);
-%0A
@@ -1720,16 +1720,13 @@
-%7D else %7B
+ %0A
%0A
@@ -1742,38 +1742,17 @@
- myAudioElement = new Audio
+playSound
(sou
@@ -1787,320 +1787,8 @@
%5D);%0A
- myAudioElement.setAttribute('crossorigin', 'anonymous')%0A mySource = gAudioContext.createMediaElementSource(myAudioElement);%0A mySource.connect(gAudioContext.destination);%0A %7D%0A%0A displayMessage(msg,'resp1'); %0A
|
21efb07b47bfdd21332aa705b8205a6291db483f | add maxAge of a month to session | client/app.js | client/app.js | var express = require('express');
var session = require('express-session');
var methodOverride = require('method-override')
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
dotenv.load();
var routes = require('./routes/index');
var users = require('./routes/users');
var houses = require('./routes/houses');
var expenses = require('./routes/expenses');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(methodOverride('_method'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true
}));
app.use('/', routes);
app.use('/users', users);
app.use('/houses', houses);
app.use('/expenses', expenses);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// // development error handler
// // will print stacktrace
// if (app.get('env') === 'development') {
// app.use(function(err, req, res, next) {
// res.status(err.status || 500);
// res.render('error', {
// message: err.message,
// error: err
// });
// });
// }
// // production error handler
// // no stacktraces leaked to user
// app.use(function(err, req, res, next) {
// res.status(err.status || 500);
// res.render('error', {
// message: err.message,
// error: {}
// });
// });
module.exports = app;
| JavaScript | 0 | @@ -1074,16 +1074,50 @@
ed: true
+,%0A cookie: %7BmaxAge: 2628000000%7D
%0A%7D));%0A%0A%0A
|
5dbf6e94ce397dcbe5ef2c9ce677380bd2ed5b81 | Update sTouch-pro.js | src/sTouch-pro.js | src/sTouch-pro.js | /**
* TODO: 更改为on,off事件注册机制
*/
void function (window,sTouch){
sTouch(window, window.document);
}(window, function (w, doc, undefined){
'use strict';
var ua = w.navigator.userAgent;
var isAndroid = /Android/gi.test(ua);
var isIPhone = /iPhone/gi.test(ua);
var isIpad = /iPad/gi.test(ua);
var isMobile = isAndroid || isIPhone || isIpad;
if(!isMobile) {
return;
}
function STouch(ele) {
if (typeof ele === 'string') {
ele = doc.querySelector(ele);
}
if (!ele instanceof HTMLElement) {
throw new Error('wrong arguments');
}
return new T(ele);
}
function T(ele) {
this.target = ele;
this._events = {};
this._process();
}
// 事件&逻辑处理
T.prototype = {
_process: function () {
var ele = this.target;
var me = this;
var touchStamp = 0, cgStamp=0, oriX= 0, oriY= 0,
changeX=0, changeY= 0, isDrag=false, deltaX= 0, deltaY= 0, delta,
isSwipe=false;
//touch事件中,根据条件触发不同的自定义事件
ele.addEventListener('touchstart', function(e){
touchStamp = e.timeStamp;
isDrag = true;
oriX = e.touches[0].clientX;
oriY = e.touches[0].clientY;
}, false);
var crtX = 0,crtY = 0;
ele.addEventListener('touchmove', function(e){
if (isDrag) {
crtX = e.touches[0].clientX;
crtY = e.touches[0].clientY;
changeX = crtX - oriX;
changeY = crtY - oriY;
}
});
ele.addEventListener('touchend', function (e){
cgStamp = e.timeStamp - touchStamp;
deltaX = Math.abs(changeX);
deltaY = Math.abs(changeY);
delta = Math.sqrt(Math.pow(deltaX,2)+Math.pow(deltaY,2));
if (deltaX < 30 && deltaY < 30){
//tap间隔时限符合则触发tap deltaX < 30 && deltaY < 30
me._trigger('tap', e);
if (cgStamp > 750 && delta >= 0 && delta <= 250) {
me._trigger('longTap', e);
}
}
else if (deltaX > 30 || deltaY > 30) {
me._trigger('swipe', e);
if (changeX < -30 && changeY < 100) {
//swipeLeft
me._trigger('swipeLeft', e);
}
if (changeX > 30 && changeY < 100) {
//swipeRight
me._trigger('swipeRight', e);
}
if (changeX < 100 && changeY < -30) {
//swipeUp
me._trigger('swipeUp', e);
}
if(changeX < 100 && changeY > 30){
//swipeDown
me._trigger('swipeDown', e);
}
}
//恢复标识变量
changeX = changeY = deltaX = deltaY = delta = 0;
isDrag = false;
isSwipe = false;
},false);
},
on: function (type, fn) {
if(!this._events){
return;
}
if ( !this._events[type] ) {
this._events[type] = [];
}
this._events[type].push(fn);
},
off: function (type, fn) {
if(!this._events){
return;
}
if ( !this._events[type] ) {
return;
}
var index = this._events[type].indexOf(fn);
if ( index > -1 ) {
this._events[type].splice(index, 1);
}
},
_trigger: function (type) {
if ( !this._events[type] ) {
return;
}
var i = 0,
l = this._events[type].length;
if ( !l ) {
return;
}
for ( ; i < l; i++ ) {
this._events[type][i].apply(this, [].slice.call(arguments, 1));
}
}
};
w.$= STouch;
});
| JavaScript | 0 | @@ -1144,20 +1144,10 @@
%E4%BA%8B%E4%BB%B6%E4%B8%AD%EF%BC%8C
-%E6%A0%B9%E6%8D%AE%E6%9D%A1%E4%BB%B6%E8%A7%A6%E5%8F%91%E4%B8%8D%E5%90%8C%E7%9A%84%E8%87%AA%E5%AE%9A%E4%B9%89
+%E6%A3%80%E6%B5%8B
%E4%BA%8B%E4%BB%B6%0D%0A
@@ -3631,16 +3631,43 @@
%7D,%0D%0A
+ %0D%0A // %E4%BA%8B%E4%BB%B6%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6
%0D%0A
@@ -4436,19 +4436,35 @@
-w.$
+%0D%0A !w.$ && (w.$
= STouch
;%0D%0A%7D
@@ -4459,16 +4459,17 @@
= STouch
+)
;%0D%0A%7D);%0D%0A
|
6eb3a1490ff0aeb0f56916164579fdefc1df64ea | remove path separators when humanising module location in `kpm check` | src/cli/commands/check.js | src/cli/commands/check.js | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
import type { Reporter } from "kreporters";
import type Config from "../../config.js";
import { Install } from "./install.js";
import Lockfile from "../../lockfile/index.js";
import { MessageError } from "../../errors.js";
import * as constants from "../../constants.js";
import * as fs from "../../util/fs.js";
import * as util from "../../util/misc.js";
let semver = require("semver");
let path = require("path");
export let noArguments = true;
export function setFlags(commander: Object) {
commander.option("--quick-sloppy");
}
export async function run(
config: Config,
reporter: Reporter,
flags: Object,
args: Array<string>
): Promise<void> {
if (!await fs.exists(path.join(config.cwd, constants.LOCKFILE_FILENAME))) {
throw new MessageError("No lockfile in this directory. Run `fbkpm install` to generate one.");
}
let lockfile = await Lockfile.fromDirectory(config.cwd, reporter, {
silent: true,
strict: true
});
let install = new Install("update", flags, args, config, reporter, lockfile, true);
let valid = true;
// get patterns that are installed when running `kpm install`
let [depRequests, rawPatterns] = await install.fetchRequestFromCwd();
// check if patterns exist in lockfile
for (let pattern of rawPatterns) {
if (!lockfile.getLocked(pattern)) {
reporter.error(`Lockfile does not contain pattern: ${pattern}`);
valid = false;
}
}
if (flags.quickSloppy) {
// in sloppy mode we don't resolve dependencies, we just check a hash of the lockfile
// against one that is created when we run `kpm install`
let integrityLoc = path.join(config.cwd, "node_modules", constants.INTEGRITY_FILENAME);
if (await fs.exists(integrityLoc)) {
let actual = await fs.readFile(integrityLoc);
let expected = util.hash(lockfile.source);
if (actual.trim() !== expected) {
valid = false;
reporter.error(`Expected an integrity hash of ${expected} but got ${actual}`);
}
} else {
reporter.error("Couldn't find an integrity hash file");
valid = false;
}
} else {
// seed resolver
await install.resolver.init(depRequests);
// check if any of the node_modules are out of sync
let res = await install.linker.initCopyModules(rawPatterns);
for (let [loc] of res) {
let human = path.relative(path.join(process.cwd(), "node_modules"), loc);
human = human.replace(/node_modules/g, " > ");
if (!(await fs.exists(loc))) {
reporter.error(`Module not installed: ${human}`);
valid = false;
}
let pkg = await fs.readJson(path.join(loc, "package.json"));
let deps = Object.assign({}, pkg.dependencies, pkg.devDependencies, pkg.peerDependencies);
for (let name in deps) {
let range = deps[name];
if (!semver.validRange(range)) continue; // exotic
let depPkgLoc = path.join(loc, "node_modules", name, "package.json");
if (!(await fs.exists(depPkgLoc))) {
// we'll hit the module not install error above when this module is hit
continue;
}
let depPkg = await fs.readJson(depPkgLoc);
if (semver.satisfies(depPkg.version, range)) continue;
// module isn't correct semver
reporter.error(
`Module ${human} depends on ${name} with the range ${range} but it doesn't match the ` +
`installed version of ${depPkg.version}`
);
}
}
}
if (valid) {
process.exit(0);
} else {
process.exit(1);
}
}
| JavaScript | 0 | @@ -2754,23 +2754,61 @@
ace(
-/node_modules/g
+new RegExp(%60$%7Bpath.sep%7Dnode_modules$%7Bpath.sep%7D%60, %22g%22)
, %22
|
84159c185cbe6a55037f1c634d32e699e6b8ffc2 | Add correct path in send-email.hbs | src/send-email.js | src/send-email.js | 'use strict';
const handelbars = require('handlebars');
const fs = require('fs');
const path = require('path');
const nodemailer = require('nodemailer');
require('env2')(`${__dirname}/../.env`);
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.PASS
}
});
function sendMail(emailAddress, emailContent, cb){
const emailTemplate = fs.readFileSync(path.join(__dirname, '..', 'public', 'views', 'email.hbs'), 'utf8');
const template = handelbars.compile(emailTemplate);
const emailBody = template(emailContent);
const mailOptions = {
from: '"CAMHS 😀" <welcome.to.cahms@hotmail.co.uk>',
subject: 'Getting to know you Questionnaire',
text: 'Questionnaire',
html: emailBody,
to: emailAddress
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return cb(error)
}
return cb(null, `Message ${info.messageId} sent: ${info.response}`)
});
}
module.exports = sendMail;
| JavaScript | 0.000011 | @@ -524,20 +524,17 @@
e, '
-..', 'public
+templates
', '
|
67b004bb55e87d1745d5e80cddbc28cc346a6dfd | remove unecessary comment | src/commands/ship/ship.js | src/commands/ship/ship.js | /*
* Ship Command
*
* Blame Kawaiibot
*
* Contributed by Capuccino
*/
exports.commands = [
'ship'
];
exports.ship = {
desc: 'basically a ship command.',
longDesc: 'Happy Shipping!',
usage: '<user Mention (Maximum 2)>',
main: (bot, ctx) => {
return new Promise((resolve,reject) => {
if(ctx.msg.mentions.length < 2) {
ctx.msg.channel.createMessage('Specify at least two users').then(() => reject(new Error('No User Specified'))).catch(reject);
} else {
//placeholder lets for now
let user1 = ctx.msg.mentions[1];
let user2 = ctx.msg.mentions[2];
let result = user1.username.substring(0, Math.floor(user1.username.length / 2)) + user2.username.substring(Math.floor(user2.username.length / 2));
ctx.msg.channel.createMessage({embed : {
title: 'Happy Shipping!',
color: 0xFD7BB5,
fields : [
{name: 'Your Ship name is', value: result, inline: true}
],
footer: "We are not solely responsible for anyone's broken heart resulting from your ship."
}}).then(() => resolve).catch(reject);
}
});
}
}; | JavaScript | 0 | @@ -526,51 +526,8 @@
e %7B%0A
- //placeholder lets for now%0A
|
4c45c2a5b2db2f65ab1a36cf3c2e5857c1a879e9 | remove toUpperCase for button text | src/common/InnerButton.js | src/common/InnerButton.js | import React, { Component, PropTypes } from 'react';
import {
View,
Text,
Animated,
StyleSheet,
Image,
} from 'react-native';
import { AnimatedCircularProgress } from 'react-native-circular-progress';
import Spinner from 'react-native-spinkit';
const propTypes = {
imageAnim: PropTypes.object,
textAnim: PropTypes.object,
textStyle: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
imageStyle: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
progressAnim: PropTypes.object,
progressStyle: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
progressSize: PropTypes.number,
progressWidth: PropTypes.number,
progressTintColor: PropTypes.string,
progressBackgroundColor: PropTypes.string,
progressFill: PropTypes.number,
progress: PropTypes.bool,
spinnerAnim: PropTypes.object,
spinner: PropTypes.bool,
spinnerSize: PropTypes.number,
spinnerType: PropTypes.string,
spinnerStyle: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
spinnerColor: PropTypes.string,
image: PropTypes.any,
text: PropTypes.string,
};
const defaultProps = {
progressSize: 30,
progressWidth: 3,
progressTintColor: '#00e0ff',
progressBackgroundColor: '#3d5875',
spinnerSize: 25,
spinnerType: 'Wave',
spinnerColor: '#ffffff',
};
class InnerButton extends Component {
static propTypes = propTypes;
static defaultProps = defaultProps;
render() {
let image = null;
let text = null;
let spinner = null;
let progress = null;
let contentStyle = null;
if (this.props.image && !this.props.progress && !this.props.spinner) {
image = (
<Animated.Image
source={this.props.image}
style={[styles.image, this.props.imageStyle, this.props.imageAnim]}
/>
);
}
if (this.props.text) {
text = (
<Animated.Text style={[styles.text, this.props.textStyle, this.props.textAnim]}>
<Text>{this.props.text.toUpperCase()}</Text>
</Animated.Text>
);
}
if (this.props.progress) {
contentStyle = styles.progressContent;
progress = (
<Animated.View style={[styles.progress, this.props.progressStyle, this.props.imageAnim]}>
<AnimatedCircularProgress
size={this.props.progressSize}
width={this.props.progressWidth}
fill={this.props.progressFill}
tintColor={this.props.progressTintColor}
backgroundColor={this.props.progressBackgroundColor}
/>
</Animated.View>
);
}
if (this.props.spinner && !this.props.progress && !this.props.image) {
contentStyle = styles.spinnerContent;
spinner = (
<Animated.View
style={[styles.spinner, this.props.spinnerStyle, this.props.imageAnim]}
>
<Spinner
isVisible
style={[styles.spinner, this.props.spinnerStyle]}
size={this.props.spinnerSize}
type={this.props.spinnerType}
color={this.props.spinnerColor}
/>
</Animated.View>
);
}
return (
<View style={[styles.content, contentStyle]}>
{image}
{progress}
{spinner}
{text}
</View>
);
}
}
const styles = StyleSheet.create({
content: {
position: 'absolute',
left: 0,
top: 0,
right: 0,
bottom: 0,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
progressContent: {
flexDirection: 'column',
},
spinnerContent: {
flexDirection: 'column',
},
progress: {
alignItems: 'center',
},
image: {
marginRight: 12,
},
spinner: {
},
text: {
letterSpacing: 10,
fontSize: 12,
color: 'white',
},
});
export default InnerButton;
| JavaScript | 0.000021 | @@ -1963,22 +1963,8 @@
text
-.toUpperCase()
%7D%3C/T
|
d157b2ab48bb6855abe4bfbb5aa7ad2307aa5b55 | Use new helper (#239) | src/compatibility/date.js | src/compatibility/date.js | /**
* @file Date methods polyfill
* @since 0.1.5
*/
/*#ifndef(UMD)*/
"use strict";
/*global _gpfArrayForEach*/ // Almost like [].forEach (undefined are also enumerated)
/*global _gpfInstallCompatibility*/ // Define and install compatible methods
/*global _gpfMainContext*/ // Main context object
/*global _gpfNewApply*/ // Apply new operator with an array of parameters
/*exported _gpfIsISO8601String*/ // Check if the string is an ISO 8601 representation of a date
/*#endif*/
function _pad (number) {
if (10 > number) {
return "0" + number;
}
return number;
}
function _gpfDateToISOString (date) {
return date.getUTCFullYear()
+ "-"
+ _pad(date.getUTCMonth() + 1)
+ "-"
+ _pad(date.getUTCDate())
+ "T"
+ _pad(date.getUTCHours())
+ ":"
+ _pad(date.getUTCMinutes())
+ ":"
+ _pad(date.getUTCSeconds())
+ "."
+ (date.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5)
+ "Z";
}
_gpfInstallCompatibility("Date", {
on: Date,
methods: {
// Introduced with JavaScript 1.8
toISOString: function () {
return _gpfDateToISOString(this);
}
},
statics: {
now: function () {
return new Date().getTime();
}
}
});
//region Date override
var _gpfISO8601RegExp = new RegExp("^([0-9][0-9][0-9][0-9])\\-([0-9][0-9])\\-([0-9][0-9])"
+ "(?:T([0-9][0-9])\\:([0-9][0-9])\\:([0-9][0-9])(?:\\.([0-9][0-9][0-9])Z)?)?$");
function _gpfIsValidDateInDateArray (dateArray) {
return dateArray[1] < 12 && dateArray[2] < 32;
}
function _gpfIsValidTimeInDateArray (dateArray) {
return dateArray[3] < 24 && dateArray[4] < 60 && dateArray[5] < 60;
}
function _gpfCheckDateArray (dateArray) {
if (_gpfIsValidDateInDateArray(dateArray) && _gpfIsValidTimeInDateArray(dateArray)) {
return dateArray;
}
}
function _gpfAddDatePartToArray (dateArray, datePart) {
if (datePart) {
dateArray.push(parseInt(datePart, 10));
} else {
dateArray.push(0);
}
}
function _gpfToDateArray (matchResult) {
var dateArray = [],
len = matchResult.length, // 0 is the recognized string
idx;
for (idx = 1; idx < len; ++idx) {
_gpfAddDatePartToArray(dateArray, matchResult[idx]);
}
return dateArray;
}
function _gpfProcessISO8601MatchResult (matchResult) {
var dateArray;
if (matchResult) {
dateArray = _gpfToDateArray(matchResult);
// Month must be corrected (0-based)
--dateArray[1];
// Some validation
return _gpfCheckDateArray(dateArray);
}
}
/**
* Check if the value is a string respecting the ISO 8601 representation of a date. If so, the string is parsed and the
* date details is returned.
*
* The function supports supports long and short syntax.
*
* @param {*} value Value to test
* @return {Number[]|undefined} 7 numbers composing the date (Month is 0-based). undefined if not matching.
* @since 0.1.5
*/
function _gpfIsISO8601String (value) {
if ("string" === typeof value) {
_gpfISO8601RegExp.lastIndex = 0;
return _gpfProcessISO8601MatchResult(_gpfISO8601RegExp.exec(value));
}
}
// Backup original Date constructor
var _GpfGenuineDate = _gpfMainContext.Date;
/**
* Date constructor supporting ISO 8601 format
*
* @constructor
* @since 0.1.5
*/
function _GpfDate () {
var firstArgument = arguments[0],
values = _gpfIsISO8601String(firstArgument);
if (values) {
return new _GpfGenuineDate(_GpfGenuineDate.UTC.apply(_GpfGenuineDate.UTC, values));
}
return _gpfNewApply(_GpfGenuineDate, arguments);
}
function _gpfCopyDateStatics () {
_gpfArrayForEach([
"prototype", // Ensure instanceof
"UTC",
"parse",
"now"
], function (member) {
_GpfDate[member] = _GpfGenuineDate[member];
});
}
function _gpfInstallCompatibleDate () {
_gpfCopyDateStatics();
// Test if ISO 8601 format variations are supported
var longDateAsString,
shortDateAsString;
try {
longDateAsString = _gpfDateToISOString(new Date("2003-01-22T22:45:34.075Z"));
shortDateAsString = _gpfDateToISOString(new Date("2003-01-22"));
} catch (e) {} //eslint-disable-line no-empty
if (longDateAsString !== "2003-01-22T22:45:34.075Z"
|| shortDateAsString !== "2003-01-22T00:00:00.000Z") {
// Replace constructor with new one
_gpfMainContext.Date = _GpfDate;
}
}
_gpfInstallCompatibleDate();
//endregion
/*#ifndef(UMD)*/
gpf.internals._gpfIsISO8601String = _gpfIsISO8601String;
gpf.internals._GpfDate = _GpfDate;
/*#endif*/
| JavaScript | 0 | @@ -174,31 +174,24 @@
*global _gpf
-Install
Compatibilit
@@ -191,16 +191,30 @@
tibility
+InstallMethods
*/ // De
@@ -248,16 +248,36 @@
methods
+ on standard objects
%0A/*globa
@@ -1025,39 +1025,32 @@
+ %22Z%22;%0A%7D%0A%0A_gpf
-Install
Compatibility(%22D
@@ -1046,16 +1046,30 @@
tibility
+InstallMethods
(%22Date%22,
|
513d1c75af561c4ff9695e78ebe5b2561eebf3d5 | Improve project name style | src/components/Project.js | src/components/Project.js | import React from 'react';
import styled from '@emotion/styled';
const Link = styled.a`
display: block;
width: calc(33.3333% - 10px);
border: 1px solid rgba(0, 0, 0, 0.01);
border-radius: 3px;
margin: 0 5px 10px;
background: rgba(0, 0, 0, 0.025);
text-decoration: none;
font-weight: normal;
transition: background 0.1s ease-in;
&:hover {
background: rgba(0, 0, 0, 0.01);
}
@media (max-width: 980px) {
& {
width: calc(50% - 10px);
}
}
@media (max-width: 810px) {
& {
width: 100%;
margin-right: 0;
margin-left: 0;
}
}
`;
const ImageWrapper = styled.div`
display: flex;
justify-content: center;
padding: 20px 0;
border-radius: 3px;
margin: 0 0 5px;
background: #fff;
text-align: center;
`;
const Image = styled.img`
display: block;
height: 60px;
animation: 0.5s zoom-in;
transition: transform 0.1s ease-in;
a:hover & {
transform: scale3d(1.075, 1.075, 1.075);
}
`;
const Content = styled.div`
padding: 14px 20px;
`;
const Name = styled.strong`
display: block;
font-weight: bold;
color: rgba(0, 0, 0, 0.75);
@media (max-width: 720px) {
& {
word-wrap: break-word;
}
}
`;
const Description = styled.span`
display: block;
padding: 6px 0 0;
color: rgba(0, 0, 0, 0.75);
`;
const Tags = styled.em`
display: block;
padding: 8px 0 0;
font-size: 12px;
font-style: normal;
color: rgba(0, 0, 0, 0.3);
`;
export default ({url, name, logo, description, tags}) => (
<Link href={url} target="_blank" rel="noopener">
<ImageWrapper>
<Image src={logo} alt={name} />
</ImageWrapper>
<Content>
<Name>{name}</Name>
<Description>{description}</Description>
<Tags>{tags}</Tags>
</Content>
</Link>
);
| JavaScript | 0.00031 | @@ -685,16 +685,21 @@
: 20px 0
+ 16px
;%0A bord
@@ -718,27 +718,8 @@
px;%0A
- margin: 0 0 5px;%0A
ba
@@ -1059,55 +1059,166 @@
;%0A
-font-weight: bold;%0A color: rgba(0, 0, 0, 0.75)
+padding: 0 0 14px;%0A font-weight: bold;%0A font-family: 'noe', serif;%0A font-size: 16px;%0A color: rgba(0, 0, 0, 0.75);%0A text-align: center;%0A background: #fff
;%0A%0A
@@ -1730,24 +1730,8 @@
r%3E%0A%0A
- %3CContent%3E%0A
@@ -1750,16 +1750,30 @@
%3C/Name%3E%0A
+ %3CContent%3E%0A
%3CD
|
43d886698b200e44ccb7f5b85af2587235fc6808 | Remove Logout button on Sidebar | src/components/Sidebar.js | src/components/Sidebar.js | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class Sidebar extends Component {
render(){
return (
<div id='sidebar' className='sidebar app-aside'>
<div className='sidebar-container'>
<nav>
<ul className="main-navigation-menu">
<li>
<Link to="/identity">
<div className="item-content">
<div className="item-media">
<i className="ti-user"></i>
</div>
<div className="item-inner">
<span className="title">Profile</span><i className="icon-arrow"></i>
</div>
</div>
</Link>
<ul className="sub-menu">
<li>
<Link to="/login">
<span className="title">Login Form</span>
</Link>
</li>
<li>
<Link to="/login">
<span className="title">Registration Form</span>
</Link>
</li>
<li>
<a href="#">Forgot Password Form</a>
</li>
<li>
<a href="#">Lock Screen</a>
</li>
</ul>
</li>
<li>
<Link to="/documents">
<div className="item-content">
<div className="item-media">
<i className="ti-layers-alt"></i>
</div>
<div className="item-inner">
<span className="title ng-scope">Documents</span><i className="icon-arrow"></i>
</div>
</div>
</Link>
</li>
<li>
<Link to="/signatures">
<div className="item-content">
<div className="item-media">
<i className="ti-pencil-alt"></i>
</div>
<div className="item-inner">
<span className="title">Claims/Attestations</span><i className="icon-arrow"></i>
</div>
</div>
</Link>
</li>
<li className="open active">
<a href="#">
<div className="item-content">
<div className="item-media">
<i className="ti-layout-grid2"></i>
</div>
<div className="item-inner">
<span className="title">Transactions</span><i className="icon-arrow"></i>
</div>
</div>
</a>
<ul className="sub-menu">
<li className="active">
<a href="#/app/form/elements">
<span className="title">Create</span>
</a>
</li>
<li>
<a href="#/app/form/xeditable">
<span className="title">Pending</span>
</a>
</li>
<li>
<a href="#/app/form/editor">
<span className="title">Completed</span>
</a>
</li>
</ul>
</li>
<li>
<a href="/logout">
<div className="item-content">
<div className="item-media">
<i className="ti-shift-right"></i>
</div>
<div className="item-inner">
<span className="title ng-scope">Logout</span><i className="icon-arrow"></i>
</div>
</div>
</a>
</li>
</ul>
</nav>
</div>
</div>
);
}
}
| JavaScript | 0.000001 | @@ -5133,712 +5133,13 @@
- %3Cli%3E%0A %3Ca href=%22/logout%22%3E%0A %3Cdiv className=%22item-content%22%3E%0A %3Cdiv className=%22item-media%22%3E%0A %3Ci className=%22ti-shift-right%22%3E%3C/i%3E%0A %3C/div%3E%0A %3Cdiv className=%22item-inner%22%3E%0A %3Cspan className=%22title ng-scope%22%3ELogout%3C/span%3E%3Ci className=%22icon-arrow%22%3E%3C/i%3E%0A %3C/div%3E%0A %3C/div%3E%0A %3C/a%3E%0A %3C/li%3E%0A%0A %3C/ul%3E%0A
+%3C/ul%3E
%0A
@@ -5162,17 +5162,16 @@
%3C/nav%3E%0A
-%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.