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
|
---|---|---|---|---|---|---|---|
3036afd4af438b546f942f96ee349cc723bb69a0
|
Update dashboard.js
|
am-dashboard/app/dashboard.js
|
am-dashboard/app/dashboard.js
|
function Dashboard() {
var self = this;
this.Tools = new Tools(this);
this.Tickets = new Tickets(this);
this.HTML = {};
this.HTML.dashboard = this.Tools.createElement(document.body, 'div', {
className: 'navbar navbar-inverse navbar-fixed-bottom',
id: 'dashboard',
});
this.HTML.style = this.Tools.createElement(this.HTML.dashboard, 'link', {
rel: 'stylesheet',
type: 'text/css',
href: 'https://rawgit.com/jamesona/SEO-Tools/master/am-dashboard/dashboard.css',
});
this.HTML.nav = this.Tools.createElement(this.HTML.dashboard, 'ul', {
className: 'nav navbar-nav',
});
this.HTML.tools = this.Tools.createElement(this.HTML.nav, 'li', {
innerHTML: '<a class="dropdown-toggle" data-toggle="dropdown">Tools</a>',
className: 'dropup',
});
this.HTML.toolsMenu = this.Tools.createElement(this.HTML.tools, 'ul', {
className: 'dropdown-menu',
});
this.HTML.todoistExport = this.Tools.createElement(this.HTML.toolsMenu, 'li', {
innerHTML: '<a>Todoist Export</a>',
onclick: function(){
self.Tools.todoistExport();
},
});
this.HTML.bobCalendar = this.Tools.createElement(this.HTML.toolsMenu, 'li', {
innerHTML: '<a>BoB Calendar</a>',
onclick: function(){
bootbox.dialog({
message: " ",
title: "",
className: "big-modal",
buttons: {},
});
var modals = document.getElementsByClassName('bootbox-body'), modal = modals[modals.length-1],
data = self.Tools.bobParse(prompt('Paste BoB data')),
calendar = new self.Tickets.calendar(data);
calendar.draw(modal);
},
});
this.HTML.tickets = this.Tools.createElement(this.HTML.nav, 'li', {
innerHTML: '<a class="dropdown-toggle" data-toggle="dropdown">Tickets</a>',
className: 'dropup',
});
this.HTML.ticketsMenu = this.Tools.createElement(this.HTML.tickets, 'ul', {
className: 'dropdown-menu',
});
this.HTML.ticketCalendar = this.Tools.createElement(this.HTML.ticketsMenu, 'li', {
innerHTML: '<a>Calendar</a>',
onclick: function(){
bootbox.dialog({
message: " ",
title: "",
className: "big-modal",
buttons: {},
});
var modals = document.getElementsByClassName('bootbox-body'), modal = modals[modals.length-1],
data = self.Tickets.sortTickets(),
calendar = new self.Tickets.calendar(data);
calendar.draw(modal);
},
});
this.HTML.nextTicket = this.Tools.createElement(this.HTML.ticketsMenu, 'li', {
innerHTML: 'Next Ticket',
onclick: function(){
self.Tools.nextTicket(self.Tickets.sortTickets()[self.Tools.today()]);
},
});
this.HTML.critical = this.Tools.createElement(this.HTML.nav, 'li', {
innerHTML: '<a>Show Critical Count</a>',
id: 'critical',
onclick: function(){
self.HTML.critical.innerHTML = self.Tickets.countCritical();
},
});
window.beforeunload = function(){
self.Tickets.tryCache();
};
window.onhashchange = function(){
if (window.location.href == 'https://launchpad.boostability.com/#/customerservice/activetickets'){
self.Tickets.tryCache();
}
};
if (localStorage.getItem('ticketCache') !== null) self.Tickets.ticketArray = JSON.parse(localStorage.getItem('ticketCache'));
}
|
JavaScript
| 0.000001 |
@@ -2515,16 +2515,19 @@
rHTML: '
+%3Ca%3E
Next Tic
@@ -2529,16 +2529,20 @@
t Ticket
+%3C/a%3E
',%0A o
|
2c746db84716656ea6ec66828878b614c23ae765
|
Move update pagers to seperate function
|
src/notebook/epics/execute.js
|
src/notebook/epics/execute.js
|
import {
createMessage,
} from '../kernel/messaging';
import {
createCellAfter,
updateCellExecutionCount,
updateCellSource,
updateCellOutputs,
updateCellPagers,
updateCellStatus,
} from '../actions';
import {
REMOVE_CELL,
ABORT_EXECUTION,
ERROR_EXECUTING,
} from '../constants';
const Rx = require('rxjs/Rx');
const Immutable = require('immutable');
const emptyOutputs = new Immutable.List();
export function msgSpecToNotebookFormat(msg) {
return Object.assign({}, msg.content, {
output_type: msg.header.msg_type,
});
}
export function createExecuteRequest(code) {
const executeRequest = createMessage('execute_request');
executeRequest.content = {
code,
silent: false,
store_history: true,
user_expressions: {},
allow_stdin: false,
stop_on_error: false,
};
return executeRequest;
}
export function reduceOutputs(outputs, output) {
if (output.output_type === 'clear_output') {
return emptyOutputs;
}
// Naive implementation of kernel stream buffering
// This should be broken out into a nice testable function
if (outputs.size > 0 &&
output.output_type === 'stream' &&
typeof output.name !== 'undefined' &&
outputs.last().get('output_type') === 'stream'
) {
// Invariant: size > 0, outputs.last() exists
if (outputs.last().get('name') === output.name) {
return outputs.updateIn([outputs.size - 1, 'text'], text => text + output.text);
}
const nextToLast = outputs.butLast().last();
if (nextToLast &&
nextToLast.get('output_type') === 'stream' &&
nextToLast.get('name') === output.name) {
return outputs.updateIn([outputs.size - 2, 'text'], text => text + output.text);
}
}
return outputs.push(Immutable.fromJS(output));
}
export function executeCellObservable(channels, id, code) {
if (!channels || !channels.iopub || !channels.shell) {
return Rx.Observable.throw(new Error('kernel not connected'));
}
const executeRequest = createExecuteRequest(code);
const { iopub, shell } = channels;
// Payload streams in general
const payloadStream = shell.childOf(executeRequest)
.ofMessageType('execute_reply')
.pluck('content', 'payload')
.filter(Boolean)
.flatMap(payloads => Rx.Observable.from(payloads));
// Payload stream for setting the input, whether in place or "next"
const setInputStream = payloadStream
.filter(payload => payload.source === 'set_next_input');
// All child messages for the cell
const cellMessages = iopub
.filter(msg =>
executeRequest.header.msg_id === msg.parent_header.msg_id
);
const cellAction$ = Rx.Observable.merge(
// Inline %load
setInputStream.filter(x => x.replace)
.pluck('text')
.map(text => updateCellSource(id, text)),
// %load for the cell _after_
setInputStream.filter(x => !x.replace)
.pluck('text')
.map((text) => createCellAfter('code', id, text)),
// Clear any old pager
Rx.Observable.of(updateCellPagers(id, new Immutable.List())),
// Update the doc/pager section with new bundles
payloadStream.filter(p => p.source === 'page')
.scan((acc, pd) => acc.push(Immutable.fromJS(pd)), new Immutable.List())
.map((pagerDatas) => updateCellPagers(id, pagerDatas)),
// Set the cell status
cellMessages.ofMessageType(['status'])
.pluck('content', 'execution_state')
.map(status => updateCellStatus(id, status)),
// Update the input numbering: `[ ]`
cellMessages.ofMessageType(['execute_input'])
.pluck('content', 'execution_count')
.first()
.map(ct => updateCellExecutionCount(id, ct)),
// Clear cell outputs
Rx.Observable.of(updateCellOutputs(id, new Immutable.List())),
// Handle all nbformattable messages
cellMessages
.ofMessageType(['execute_result', 'display_data', 'stream', 'error', 'clear_output'])
.map(msgSpecToNotebookFormat)
// Iteratively reduce on the outputs
.scan(reduceOutputs, emptyOutputs)
// Update the outputs with each change
.map(outputs => updateCellOutputs(id, outputs))
);
// On subscription, send the message
return Rx.Observable.create(observer => {
const subscription = cellAction$.subscribe(observer);
channels.shell.next(executeRequest);
return subscription;
});
}
export const EXECUTE_CELL = 'EXECUTE_CELL';
export function executeCell(id, source) {
return {
type: EXECUTE_CELL,
id,
source,
};
}
/**
* the execute cell epic processes execute requests for all cells, creating
* inner observable streams of the running execution responses
*/
export function executeCellEpic(action$, store) {
return action$.ofType('EXECUTE_CELL')
.do(action => {
if (!action.id) {
throw new Error('execute cell needs an id');
}
if (typeof action.source !== 'string') {
throw new Error('execute cell needs source string');
}
})
// Split stream by cell IDs
.groupBy(action => action.id)
// Work on each cell's stream
.map(cellActionObservable =>
cellActionObservable
// When a new EXECUTE_CELL comes in with the current ID, we create a
// a new observable and unsubscribe from the old one.
.switchMap(({ source, id }) => {
const state = store.getState();
const channels = state.app.channels;
const kernelConnected = channels &&
!(state.app.executionState === 'starting' ||
state.app.executionState === 'not connected');
if (!kernelConnected) {
// TODO: Switch this to dispatching an error
state.app.notificationSystem.addNotification({
title: 'Could not execute cell',
message: 'The cell could not be executed because the kernel is not connected.',
level: 'error',
});
return Rx.Observable.of(updateCellExecutionCount(id, undefined));
}
return executeCellObservable(channels, id, source)
.takeUntil(action$.filter(laterAction => laterAction.id === id)
.ofType(ABORT_EXECUTION, REMOVE_CELL));
})
)
// Bring back all the inner Observables into one stream
.mergeAll()
.catch(error =>
Rx.Observable.of({
type: ERROR_EXECUTING,
payload: error,
error: true,
})
);
}
|
JavaScript
| 0.000001 |
@@ -1773,24 +1773,276 @@
utput));%0A%7D%0A%0A
+export function createPagerActions(id, payloadStream) %7B%0A return payloadStream.filter(p =%3E p.source === 'page')%0A .scan((acc, pd) =%3E acc.push(Immutable.fromJS(pd)), new Immutable.List())%0A .map((pagerDatas) =%3E updateCellPagers(id, pagerDatas));%0A%7D%0A%0A
export funct
@@ -3354,193 +3354,44 @@
-payloadStream.filter(p =%3E p.source === 'page')%0A .scan((acc, pd) =%3E acc.push(Immutable.fromJS(pd)), new Immutable.List())%0A .map((pagerDatas) =%3E updateCellPagers(id, pagerDatas)
+createPagerActions(id, payloadStream
),%0A
|
25373d1894ef870633713ee8b4e914eb0feed23e
|
add dashboard to test
|
utils/run-tests.js
|
utils/run-tests.js
|
var Path = require('path');
var Fs = require('fs');
var Chalk = require('chalk');
var SpawnSync = require('child_process').spawnSync;
var exePath = '';
var cwd = process.cwd();
if ( process.platform === 'darwin' ) {
exePath = Path.join(cwd, 'bin/electron/Electron.app/Contents/MacOS/Electron');
}
else {
exePath = Path.join(cwd, 'bin/electron/Electron.exe');
}
var files;
var indexFile = Path.join( cwd, 'test/index.js' );
var testDirs = [
Path.join( cwd, './test/' ),
Path.join( cwd, './editor-framework/test/' ),
];
var singleTestFile = process.argv[2];
// accept
if (singleTestFile) {
var splited = singleTestFile.split('/');
// handle test in submodules
if (splited.length > 1) {
var testIdx = splited.indexOf('test');
//optional test folder in path
if (testIdx !== -1) {
splited.splice(testIdx, 1);
}
// get test file path based on test folder
var filePath = splited.reduce(function(previousValue, currentValue, index, array) {
if (index > 1) {
return previousValue + '/' + currentValue;
} else if (index === 1){
return currentValue;
} else {
return '';
}
});
singleTestFile = ('./' + splited[0] + '/test/' + filePath + '.js').replace('.js.js', '.js');
} else {
singleTestFile = ('./test/' + process.argv[2] + '.js').replace('.js.js', '.js');
}
SpawnSync(exePath, [cwd, '--test', singleTestFile], {stdio: 'inherit'});
}
else {
testDirs.forEach( function ( path ) {
if ( !Fs.existsSync(path) ) {
console.error( 'Path not found %s', path );
return;
}
var indexFile = Path.join( path, 'index.js' );
if ( Fs.existsSync(indexFile) ) {
files = require(indexFile);
files.forEach(function ( file ) {
console.log( Chalk.magenta( 'Start test (' + file + ')') );
SpawnSync(exePath, [cwd, '--test', file], {stdio: 'inherit'});
});
}
else {
Globby ( Path.join(path, '**/*.js'), function ( err, files ) {
files.forEach(function (file) {
console.log( Chalk.magenta( 'Start test (' + file + ')') );
SpawnSync(exePath, [cwd, '--test', file], {stdio: 'inherit'});
});
});
}
});
}
|
JavaScript
| 0 |
@@ -527,16 +527,59 @@
st/' ),%0A
+ Path.join( cwd, './dashboard/test/' ),%0A
%5D;%0Avar s
|
7956813945b0ced47fada839dbef1903c72252ec
|
Update for 2.3.0-rc.5
|
version.js
|
version.js
|
if (enyo && enyo.version) {
enyo.version.onyx = "2.3.0-rc.4";
}
|
JavaScript
| 0 |
@@ -56,9 +56,9 @@
-rc.
-4
+5
%22;%0A%7D
|
0495a88f4626822c850929132084294b2e660f0b
|
Fix path date filename.
|
plugins/path.js
|
plugins/path.js
|
var
FilePath = require('filepath').FilePath,
INI = require('ini');
exports.initialize = function (API, args) {
API.path = FilePath.create;
API.path.root = FilePath.root;
API.path.home = FilePath.home;
API.path.datename = dateFileName;
API.path.expand = function (filepath) {
return FilePath.create(filepath.toString().replace(/^\~/, FilePath.home().toString()));
};
FilePath.prototype.appendDatename = function (ext) {
var filename = dateFileName + ext;
return FilePath.create(this.path, filename);
};
FilePath.prototype.readIni = function () {
return this.read().then(function (text) {
if (!text) {
return null;
}
return INI.parse(text);
});
};
return API;
};
function dateFileName(conf) {
return function () {
var
now = new Date(),
pad = function(num) {
var norm = Math.abs(Math.floor(num));
return (norm < 10 ? '0' : '') + norm;
};
return now.getFullYear()
+ '_' + pad(now.getMonth()+1)
+ '_' + pad(now.getDate())
+ 'T' + pad(now.getHours())
+ '.' + pad(now.getMinutes())
+ '.' + pad(now.getSeconds());
};
}
|
JavaScript
| 0.999841 |
@@ -474,14 +474,24 @@
Name
+()
+
+(
ext
+ %7C%7C '')
;%0A
@@ -771,49 +771,18 @@
ame(
-conf
) %7B%0A
- return function () %7B%0A
var%0A
-
no
@@ -799,18 +799,16 @@
te(),%0A
-
-
pad = fu
@@ -817,26 +817,24 @@
tion(num) %7B%0A
-
var norm
@@ -863,26 +863,24 @@
(num));%0A
-
return (norm
@@ -909,17 +909,13 @@
rm;%0A
-
%7D;%0A
-
re
@@ -937,26 +937,24 @@
lYear()%0A
-
-
+ '_' + pad(
@@ -975,18 +975,16 @@
+1)%0A
-
+ '_' +
@@ -1006,18 +1006,16 @@
())%0A
-
-
+ 'T' +
@@ -1030,26 +1030,24 @@
getHours())%0A
-
+ '.' +
@@ -1072,18 +1072,16 @@
())%0A
-
+ '.' +
@@ -1103,15 +1103,10 @@
nds());%0A
- %7D;%0A
%7D%0A
|
064e828d8e623c023f8ac67c00fab4c64d45cdb2
|
Add header and disabled props to DropDown
|
src/widgets/DropDown.js
|
src/widgets/DropDown.js
|
/* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Picker } from 'react-native';
import { COMPONENT_HEIGHT, SUSSOL_ORANGE } from '../globalStyles';
/**
* A single selection dropdown menu implemented as a simple light-weight wrapper over the
* native Picker component.
*
* @param {Array.<string>} values A list of values to render in the dropdown selection.
* @param {string} selectedValue The currently selected value.
* @param {Func} onValueChange On selection callback handler.
* @param {object} style Optional additional component styling.
*/
export const DropDown = React.memo(({ values, selectedValue, onValueChange, style }) => {
const Items = values.map(value => (
<Picker.Item key={value} label={value} value={value} color={SUSSOL_ORANGE} />
));
return (
<Picker
selectedValue={selectedValue}
mode="dropdown"
onValueChange={onValueChange}
style={{ ...localStyles.picker, ...localStyles.pickerText, ...style }}
>
{Items}
</Picker>
);
});
export default DropDown;
export const localStyles = {
pickerText: {
color: SUSSOL_ORANGE,
},
picker: {
marginBottom: 45,
marginLeft: 8.5,
marginTop: 10,
height: COMPONENT_HEIGHT,
width: 285,
},
};
DropDown.defaultProps = {
style: {},
selectedValue: null,
};
DropDown.propTypes = {
values: PropTypes.array.isRequired,
selectedValue: PropTypes.string,
onValueChange: PropTypes.func.isRequired,
style: PropTypes.object,
};
|
JavaScript
| 0 |
@@ -216,16 +216,29 @@
import %7B
+ DARKER_GREY,
COMPONE
@@ -581,16 +581,18 @@
m %7BFunc%7D
+
onValue
@@ -693,16 +693,176 @@
tyling.%0A
+ * @param %7Bstring%7D headerValue Optional value for a header within the popup.%0A * @param %7Bbool%7D isDisabled Optional inidicator that this dropdown is disabled.%0A
*/%0Aexpo
@@ -892,16 +892,19 @@
ct.memo(
+%0A
(%7B value
@@ -941,16 +941,41 @@
e, style
+, headerValue, isDisabled
%7D) =%3E %7B
@@ -979,16 +979,18 @@
%3E %7B%0A
+
const
Item
@@ -989,15 +989,232 @@
nst
-Items =
+header = React.useMemo(%0A () =%3E (%0A %3CPicker.Item key=%7BheaderValue%7D label=%7BheaderValue%7D enabled=%7Bfalse%7D color=%7BDARKER_GREY%7D /%3E%0A ),%0A %5BheaderValue%5D%0A );%0A const items = React.useMemo(%0A () =%3E%0A
val
@@ -1228,24 +1228,30 @@
(value =%3E (%0A
+
%3CPicker.
@@ -1326,12 +1326,118 @@
%3E%0A
-));%0A
+ )),%0A %5B%5D%0A );%0A const withHeader = React.useMemo(() =%3E %5Bheader, ...items%5D, %5Bheader, items%5D);%0A%0A
re
@@ -1443,16 +1443,18 @@
eturn (%0A
+
%3CPic
@@ -1457,16 +1457,18 @@
%3CPicker%0A
+
se
@@ -1501,16 +1501,18 @@
%7D%0A
+
+
mode=%22dr
@@ -1519,16 +1519,18 @@
opdown%22%0A
+
on
@@ -1557,16 +1557,18 @@
Change%7D%0A
+
st
@@ -1636,16 +1636,48 @@
tyle %7D%7D%0A
+ enabled=%7B!isDisabled%7D%0A
%3E%0A
@@ -1684,16 +1684,47 @@
+
-%7BI
+ %7BheaderValue ? withHeader : i
tems%7D%0A
+
@@ -1739,12 +1739,17 @@
%3E%0A
+
+
);%0A
-%7D
+ %7D%0A
);%0A%0A
@@ -2041,16 +2041,56 @@
: null,%0A
+ headerValue: '',%0A isDisabled: false,%0A
%7D;%0A%0ADrop
@@ -2252,11 +2252,74 @@
object,%0A
+ headerValue: PropTypes.string,%0A isDisabled: PropTypes.bool,%0A
%7D;%0A
|
34d62b8b46494786cf16003f9cf2a7d2911d376c
|
Update asylum data date
|
src/js/model/refugee-constants.js
|
src/js/model/refugee-constants.js
|
var moment = require('moment');
// note that month indices are zero-based
module.exports.DATA_START_YEAR = 2012;
module.exports.DATA_START_MONTH = 0;
module.exports.DATA_END_YEAR = 2015;
module.exports.DATA_END_MONTH = 8;
module.exports.DATA_END_MOMENT = moment([
module.exports.DATA_END_YEAR,
module.exports.DATA_END_MONTH, 30]);
module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2015, 10, 4]);
module.exports.SYRIA_REFUGEES_DATA_UPDATED_MOMENT = moment([2015, 10, 3]);
module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN'];
module.exports.labelShowBreakPoint = 992;
|
JavaScript
| 0.000012 |
@@ -409,9 +409,9 @@
10,
-4
+5
%5D);%0A
|
2370ef67dfc6912a9b804a6097ede395b73b2252
|
Add support for adjusting pageinfo fontSize/color
|
src/widgets/PageInfo.js
|
src/widgets/PageInfo.js
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Dimensions, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { APP_FONT_FAMILY, DARK_GREY, SUSSOL_ORANGE } from '../globalStyles';
const renderTitleComponent = (isEditingDisabled, columnIndex, rowData, rowIndex) => {
// If null or empty string, use single space to avoid squishing row
const titleString = rowData.title ? rowData.title : ' ';
const titleComponent = (
<Text
key={`Title ${columnIndex}-${rowIndex}`}
style={[localStyles.text, localStyles.titleText]}
numberOfLines={1}
>
{titleString}
</Text>
);
if (rowData.onPress && !isEditingDisabled) {
return (
<TouchableOpacity
style={localStyles.rowContainer}
key={`Touchable ${columnIndex}-${rowIndex}`}
onPress={rowData.onPress}
>
{titleComponent}
</TouchableOpacity>
);
}
return (
<View style={localStyles.rowContainer} key={`ViewTitle ${columnIndex}-${rowIndex}`}>
{titleComponent}
</View>
);
};
const renderInfoComponent = (isEditingDisabled, columnIndex, rowData, rowIndex) => {
let editTextStyle;
let containerStyle;
let iconName;
const { editableType, canEdit } = rowData;
switch (editableType) {
case 'selectable':
containerStyle = localStyles.selectContainer;
iconName = 'angle-down';
break;
case 'text':
default:
containerStyle = localStyles.editableTextContainer;
iconName = 'pencil';
editTextStyle = localStyles.infoText;
break;
}
// If null or empty string, use single space to avoid squishing row
let infoString = (rowData.info || rowData.info === 0) && String(rowData.info);
infoString = infoString && infoString.length > 0 ? infoString : ' ';
const infoComponent = (
<Text
key={`Info ${columnIndex}-${rowIndex}`}
style={[localStyles.text, editTextStyle]}
numberOfLines={1}
>
{infoString}
</Text>
);
if (rowData.onPress && (!isEditingDisabled && canEdit)) {
return (
<TouchableOpacity
style={localStyles.rowContainer}
key={`Touchable ${columnIndex}-${rowIndex}`}
onPress={rowData.onPress}
>
<View style={containerStyle}>
{infoComponent}
<Icon name={iconName} size={14} style={localStyles.editIcon} color={SUSSOL_ORANGE} />
</View>
</TouchableOpacity>
);
}
return (
<View style={localStyles.rowContainer} key={`ViewInfo ${columnIndex}-${rowIndex}`}>
{infoComponent}
</View>
);
};
/**
* A component to display info in a generic way at the top of a page.
*
* @prop {array} columns An array containing columns of information to be
* displayed, with an entry in the array representing
* a column, which is an array of info objects
* containing a title and info.
*
* E.g.:
*
* [[{title: 'col1:', info: 'row1'},
* {title: 'col1:', info: 'row2'}]
* [{title: 'col2:', info: 'row1',
* editableType: 'selectable'},
* {title: 'col2:', info: 'row2',
* editableType: 'text'}]]
*
* would display:
*
* col1: row1 col2: row1
* col1: row2 col2: row2
*/
export const PageInfo = props => {
const { columns, isEditingDisabled } = props;
return (
<View style={[localStyles.horizontalContainer]}>
{columns.map((columnData, columnIndex) => {
const isRightMostColumn = columnIndex === props.columns.length - 1;
return (
<View
// TODO: use key which is not index.
// eslint-disable-next-line react/no-array-index-key
key={`Column ${columnIndex}`}
style={
isRightMostColumn ? localStyles.rightmostColumnContainer : localStyles.columnContainer
}
>
<View>
{columnData
.filter(data => data.shouldShow !== false)
.map((...args) => renderTitleComponent(isEditingDisabled, columnIndex, ...args))}
</View>
<View style={localStyles.infoContainer}>
{columnData
.filter(data => data.shouldShow !== false)
.map((...args) => renderInfoComponent(isEditingDisabled, columnIndex, ...args))}
</View>
</View>
);
})}
</View>
);
};
export default PageInfo;
/* eslint-disable react/forbid-prop-types, react/require-default-props */
PageInfo.propTypes = {
columns: PropTypes.array,
isEditingDisabled: PropTypes.bool,
};
const localStyles = StyleSheet.create({
horizontalContainer: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'flex-start',
marginHorizontal: 5,
marginBottom: 10,
},
columnContainer: {
flex: 1,
flexDirection: 'row',
justifyContent: 'flex-start',
marginRight: 25,
},
rowContainer: {
marginVertical: 1,
},
rightmostColumnContainer: {
flex: 2,
flexDirection: 'row',
justifyContent: 'flex-start',
marginRight: 5,
},
infoContainer: {
flex: 1,
flexDirection: 'column',
},
editableTextContainer: {
borderBottomWidth: 1,
borderColor: SUSSOL_ORANGE,
flexDirection: 'row',
justifyContent: 'space-between',
},
selectContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
},
editIcon: {
marginTop: 4,
marginLeft: 4,
},
text: {
fontSize: Dimensions.get('window').width / 80,
fontFamily: APP_FONT_FAMILY,
color: SUSSOL_ORANGE,
marginTop: 4,
},
titleText: {
color: DARK_GREY,
marginRight: 25,
},
infoText: {
alignSelf: 'stretch',
},
});
|
JavaScript
| 0 |
@@ -1369,16 +1369,37 @@
canEdit
+, infoColor, infoSize
%7D = row
@@ -1725,16 +1725,165 @@
ak;%0A %7D%0A
+%0A if (infoColor) editTextStyle = %7B ...editTextStyle, color: infoColor %7D;%0A if (infoSize) editTextStyle = %7B ...editTextStyle, fontSize: infoSize %7D;%0A%0A
// If
@@ -2604,16 +2604,28 @@
%3CIcon
+%0A
name=%7Bi
@@ -2636,55 +2636,116 @@
ame%7D
- size=%7B14%7D style=%7BlocalStyles.editIcon%7D color=%7B
+%0A size=%7BinfoSize %7C%7C 14%7D%0A style=%7BlocalStyles.editIcon%7D%0A color=%7BinfoColor %7C%7C
SUSS
@@ -2754,16 +2754,26 @@
_ORANGE%7D
+%0A
/%3E%0A
|
a3b84bff7bb26540ee2519c5ca943e6d49895ca8
|
Remove commented out code
|
src/js/settings/AutoWootToggle.js
|
src/js/settings/AutoWootToggle.js
|
/**
* Stores the state of the Auto-Woot setting
* @module settings/AutoWootToggle
*/
/**
* AutoWoot setting constructor
* @constructor
* @param {object} toggler - The Toggle API used to keep track of state.
*/
function AutoWoot( toggler, userId ){
this.toggler = toggler || {};
this.userId = userId;
this.localStorageName = "autowoot";
toggler.onChange( this.setWootState.bind( this ) );
if( toggler.isOn ){
this.startWooting();
}
/*
this.onChange = function(isOn){
if(isOn){
startWooting();
API.on(API.DJ_ADVANCE, startWooting);
}else{
API.off(API.DJ_ADVANCE, startWooting);
}
};
// Initialize if setting is already turned on
if(this.isOn){
this.onChange(this.isOn);
}
*/
}
/**
* Sets auto-woot to ON/OFF
* @param {boolean} isOn - true to turn auto-woot on, false to turn it off
*/
AutoWoot.prototype.setWootState = function( isOn ){
if( isOn ){
this.startWooting.apply(this);
API.on( API.DJ_ADVANCE, this.startWooting.bind(this) );
}else{
API.off( API.DJ_ADVANCE, this.startWooting.bind(this) );
}
};
/**
* Determines when to start wooting for current song
* @param {object} newSongInfo - Info about the newly started song. (Provided by Plug.dj API)
*/
AutoWoot.prototype.startWooting = function( newSongInfo ){
var wootButton = $('#woot');
// Immediately start wooting if the user just turned the feature on
if( !newSongInfo ){
wootButton.click();
return;
}
// No need to woot for yourself
if( newSongInfo.dj.id === this.userId ){
return;
}
// woot at a random time in the first 35 seconds of each song
var randTimeout = Math.round( 35 * Math.random() ) * 1000;
setTimeout(wootButton.click, randTimeout);
return randTimeout;
};
module.exports = AutoWoot;
|
JavaScript
| 0 |
@@ -447,275 +447,8 @@
%09%7D%0A%0A
-%09/*%0A%09this.onChange = function(isOn)%7B%0A%09%09if(isOn)%7B%0A%09%09%09startWooting();%0A%09%09%09API.on(API.DJ_ADVANCE, startWooting);%0A%09%09%7Delse%7B%0A%09%09%09API.off(API.DJ_ADVANCE, startWooting);%0A%09%09%7D%0A%09%7D;%0A%0A%09// Initialize if setting is already turned on%0A%09if(this.isOn)%7B%0A%09%09this.onChange(this.isOn);%0A%09%7D%0A%09*/%0A
%7D%0A%0A/
|
b1ff4a1dd88570f92caece960c03de7961eff766
|
remove unnecessary indirection
|
lib/compiler.js
|
lib/compiler.js
|
'use strict';
const path = require('path');
const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin');
const util = require('./util.js');
module.exports.compileTemplate = function compileTemplate (options, context, compilation) {
// The entry file is just an empty helper as the dynamic template
// require is added in "loader.js"
const outputOptions = {
filename: '[hash]',
publicPath: compilation.outputOptions.publicPath
};
// Create an additional child compiler which takes the template
// and turns it into an Node.JS html factory.
// This allows us to use loaders during the compilation
const childCompiler = compilation.createChildCompiler('favicons-webpack-plugin', outputOptions);
childCompiler.context = context;
new SingleEntryPlugin(context, '!!' + require.resolve('./favicons.js') + '?' +
JSON.stringify({
outputFilePrefix: options.prefix,
faviconsOptions: options.favicons,
}) + '!' + options.logo
).apply(childCompiler);
util.tap(childCompiler, 'compilation', 'Favicons', (compilation) => {
util.tapAsync(compilation, 'optimize-chunk-assets', 'Favicons', (chunks, callback) => {
if (!chunks[0]) {
return callback(compilation.errors[0] || 'Favicons generation failed');
}
const resultFile = chunks[0].files[0];
const resultCode = compilation.assets[resultFile].source();
try {
const resultJson = JSON.stringify(eval(resultCode));
compilation.assets[resultFile] = {
source: () => resultJson,
size: () => resultJson.length
};
callback(null);
} catch (e) {
return callback(e);
}
});
});
// Compile and return a promise
return new Promise((resolve, reject) => {
childCompiler.runAsChild((err, entries, childCompilation) => {
if (childCompilation && childCompilation.errors && childCompilation.errors.length) {
const errorDetails = childCompilation.errors.map((error) =>
error.message + (error.error ? ':\n' + error.error : '')
).join('\n');
reject(new Error('Child compilation failed:\n' + errorDetails));
} else if (err) {
reject(err);
} else {
// Replace [hash] placeholders in filename
const outputName = util.getAssetPath(compilation.mainTemplate, outputOptions.filename, {
hash: childCompilation.hash,
chunk: entries[0]
});
const stats = JSON.parse(childCompilation.assets[outputName].source());
delete compilation.assets[outputName];
childCompilation.assets = {};
resolve(stats);
}
});
});
};
/**
* Returns the child compiler name e.g. 'html-webpack-plugin for "index.html"'
*/
function getCompilerName (context, filename) {
var absolutePath = path.resolve(context, filename);
var relativePath = path.relative(context, absolutePath);
return 'favicons-webpack-plugin for "' + (absolutePath.length < relativePath.length ? absolutePath : relativePath) + '"';
}
|
JavaScript
| 0.99921 |
@@ -995,693 +995,8 @@
);%0A%0A
- util.tap(childCompiler, 'compilation', 'Favicons', (compilation) =%3E %7B%0A util.tapAsync(compilation, 'optimize-chunk-assets', 'Favicons', (chunks, callback) =%3E %7B%0A if (!chunks%5B0%5D) %7B%0A return callback(compilation.errors%5B0%5D %7C%7C 'Favicons generation failed');%0A %7D%0A const resultFile = chunks%5B0%5D.files%5B0%5D;%0A const resultCode = compilation.assets%5BresultFile%5D.source();%0A try %7B%0A const resultJson = JSON.stringify(eval(resultCode));%0A compilation.assets%5BresultFile%5D = %7B%0A source: () =%3E resultJson,%0A size: () =%3E resultJson.length%0A %7D;%0A callback(null);%0A %7D catch (e) %7B%0A return callback(e);%0A %7D%0A %7D);%0A %7D);%0A%0A
//
@@ -1771,18 +1771,12 @@
s =
-JSON.parse
+eval
(chi
|
e71b0b3e81ff7ec00305e3df716719730b485e48
|
update config example
|
api/_global-config-example.js
|
api/_global-config-example.js
|
// Setup config
// NOTE - Change filename to _global-config.js for use
var config;
var env = process.env.ENV_NAME || 'dev';
if (env === 'staging' || env === 'production') {
config = {
port: process.env.PORT || 3000,
version: '/v1',
cookieSecret: 'SUPERcookieSECRET',
tokenSecret: 'SERIOUStokenSECRET',
mailTokenSecret: 'SERIOUSmailTokenSECRET',
mongoHost: 'mongodb://mongo:27017/test1',
sendgrid: {
apikey: 'somekey'
},
facebook : {
app_id: 'your-secret-clientID-here', // your App ID
app_secret: 'your-client-secret-here', // your App Secret
callback_url: 'http://somedomain.com/auth/facebook/callback'
},
twitter: {
app_key: 'your-consumer-key-here', // consumer_key
app_secret: 'your-client-secret-here', // consumer_secret
callback_url: 'http://somedomain.com/auth/twitter/callback'
},
google: {
app_id: 'your-secret-clientID-here', // client_id
app_secret: 'your-client-secret-here', // client_secret
callback_url: 'http://somedomain.com/auth/google/callback'
}
};
} else {
config = {
port: process.env.PORT || 3000,
version: '/v1',
cookieSecret: 'localCookieSecret',
tokenSecret: 'localTokenSecret',
mailTokenSecret: 'localMailTokenSecret',
mongoHost: 'mongodb://localhost:27017/test1',
sendgrid: {
apikey: 'somekey'
},
facebook : {
app_id: 'your-secret-clientID-here', // your App ID
app_secret: 'your-client-secret-here', // your App Secret
callback_url: 'http://localhost:8080/auth/facebook/callback'
},
twitter: {
app_key: 'your-consumer-key-here', // consumer_key
app_secret: 'your-client-secret-here', // consumer_secret
callback_url: 'http://localhost:8080/auth/twitter/callback'
},
google: {
app_id: 'your-secret-clientID-here', // client_id
app_secret: 'your-client-secret-here', // client_secret
callback_url: 'http://localhost:8080/auth/google/callback'
}
};
}
// Export Rest routes
module.exports = config;
|
JavaScript
| 0.000001 |
@@ -103,17 +103,20 @@
.env
-.ENV_NAME
+%5B'NODE_ENV'%5D
%7C%7C
@@ -195,37 +195,40 @@
ort: process.env
-.
+%5B'
PORT
+'%5D
%7C%7C 3000,%0A%09%09vers
@@ -404,34 +404,46 @@
st1',%0A%09%09
-sendgrid
+mailgun: %7B%0A%09%09%09auth
: %7B%0A%09%09%09
+%09
api
+_
key: 'so
@@ -440,32 +440,64 @@
i_key: 'somekey'
+,%0A%09%09%09%09domain: 'somedomaine'%0A%09%09%09%7D
%0A%09%09%7D,%0A%09%09facebook
@@ -1120,13 +1120,16 @@
.env
-.
+%5B'
PORT
+'%5D
%7C%7C
@@ -1321,26 +1321,38 @@
,%0A%09%09
-sendgrid
+mailgun: %7B%0A%09%09%09auth
: %7B%0A%09%09%09
+%09
api
+_
key:
@@ -1361,16 +1361,48 @@
somekey'
+,%0A%09%09%09%09domain: 'somedomaine'%0A%09%09%09%7D
%0A%09%09%7D,%0A%09%09
|
446615f23d461d0f4f880c6fc1efe48779c718a4
|
Make the bubble chart sexy
|
api/controllers/statistics.js
|
api/controllers/statistics.js
|
'use strict'
let Rat = require('../models/rat')
let Rescue = require('../models/rescue')
exports.get = function (request, response, next) {
let operations = []
operations.push(getOverallRescueCount())
operations.push(getPopularSystemsCount())
operations.push(getLeaderboardRats())
Promise.all(operations).then(function (values) {
response.model.data = values
response.status(200)
next()
}, function (errors) {
console.log(errors)
})
}
let groupByDateAggregator = {
$group: {
_id: {
month: {
$month: '$createdAt'
},
day: {
$dayOfMonth: '$createdAt'
},
year: {
$year: '$createdAt'
},
successful: '$successful'
},
count: {
$sum: 1
}
}
}
let getOverallRescueCount = function () {
return new Promise(function (resolve, reject) {
Rescue.aggregate([
groupByDateAggregator
]).exec().then(function (objs) {
let organisedCollection = []
for (let obj of objs) {
let date = Date.parse(`${obj._id.year}-${obj._id.month}-${obj._id.day}`)
let days = organisedCollection.filter(function (el) {
return el.date === date
})
let day
if (days.length === 0) {
day = { date: date, success: 0, failure: 0 }
} else {
day = days[0]
organisedCollection.splice(organisedCollection.indexOf(day), 1)
}
if (obj._id.successful === true) {
day.success = obj.count
} else {
day.failure = obj.count
}
organisedCollection.push(day)
}
organisedCollection = organisedCollection.sort(function (x, y) {
return y - x
})
resolve(organisedCollection)
}, function (errors) {
reject(errors)
})
})
}
let getPopularSystemsCount = function () {
return Rescue.aggregate([
{
$group: {
_id: '$system',
count: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
name: '$_id',
count: 1
}
},
{
$limit : 200
}
]).exec()
}
let getLeaderboardRats = function () {
return Rat.aggregate([
{
$match: {
rescueCount: {
$gte: 10
}
}
},
// {
// $unwind: {
// path: '$rescues'
// }
// },
// {
// $group: {
// _id: {
// CMDRname: '$CMDRname',
// platform: '$platform'
// },
// rescues: {
// $sum: {
// $cond: [{$eq: ['$rescues.successful', true]}, 1, 0]
// }
// }
// }
// },
// {
// $project: {
// _id: 0,
// CMDRname: '$_id.CMDRname',
// platform: '$_id.platform',
// rescues: 1
// }
// },
{
$project: {
CMDRname: 1,
platform: 1,
rescues: {
$size: '$rescues'
}
}
},
{
$sort: {
rescues: -1
}
}
]).exec()
}
|
JavaScript
| 0.00007 |
@@ -1977,32 +1977,115 @@
%7D%0A %7D,%0A %7B%0A
+ $match: %7B%0A count: %7B%0A $gte: 10%0A %7D%0A %7D%0A %7D,%0A %7B%0A
$project:
@@ -2078,32 +2078,32 @@
$project: %7B%0A
-
_id: 0,%0A
@@ -2153,40 +2153,8 @@
%7D%0A
- %7D,%0A %7B%0A $limit : 200%0A
@@ -2328,518 +2328,8 @@
%7D,%0A
-// %7B%0A// $unwind: %7B%0A// path: '$rescues'%0A// %7D%0A// %7D,%0A// %7B%0A// $group: %7B%0A// _id: %7B%0A// CMDRname: '$CMDRname',%0A// platform: '$platform'%0A// %7D,%0A// rescues: %7B%0A// $sum: %7B%0A// $cond: %5B%7B$eq: %5B'$rescues.successful', true%5D%7D, 1, 0%5D%0A// %7D%0A// %7D%0A// %7D%0A// %7D,%0A// %7B%0A// $project: %7B%0A// _id: 0,%0A// CMDRname: '$_id.CMDRname',%0A// platform: '$_id.platform',%0A// rescues: 1%0A// %7D%0A// %7D,%0A
|
4c0d60fd3675aa4e886dde3b56967b07807027b4
|
change night to evening
|
plugins/time.js
|
plugins/time.js
|
var moment = require("moment");
var COEFF = 1000 * 60 * 5;
var getSeason = function() {
var now = moment();
now.dayOfYear()
var doy = now.dayOfYear();
if (doy > 80 && doy < 172) {
return "spring";
} else if (doy > 172 && doy < 266) {
return "summer"
} else if (doy > 266 && doy < 357) {
return "fall"
} else if ( doy < 80 || doy > 357) {
return "winter";
}
}
exports.getDOW = function(cb) {
cb(null, moment().format("dddd"));
}
exports.getDate = function(cb) {
cb(null, moment().format("ddd, MMMM Do"));
}
exports.getDateTomorrow = function(cb) {
var date = moment().add('d', 1).format("ddd, MMMM Do");
cb(null, date);
}
exports.getSeason = function(cb) {
var date = moment().add('d', 1).format("ddd, MMMM Do");
cb(null, getSeason());
}
exports.getTime = function(cb) {
var date = new Date();
var rounded = new Date(Math.round(date.getTime() / COEFF) * COEFF);
var time = moment(rounded).format("h:mm");
cb(null, "The time is " + time);
}
exports.getTimeOfDay = function(cb) {
var date = new Date();
var rounded = new Date(Math.round(date.getTime() / COEFF) * COEFF);
var time = moment(rounded).format("H")
var tod
if (time < 12) {
tod = "morning"
} else if (time < 17) {
tod = "afternoon"
} else {
tod = "night"
}
cb(null, tod);
}
exports.getDayOfWeek = function(cb) {
cb(null, moment().format("dddd"));
}
exports.getMonth = function(cb) {
var reply = "";
if (this.message.words.indexOf("next") != -1) {
reply = moment().add('M', 1).format("MMMM");
} else if (this.message.words.indexOf("previous") != -1) {
reply = moment().subtract('M', 1).format("MMMM");
} else if (this.message.words.indexOf("first") != -1) {
reply = "January";
} else if (this.message.words.indexOf("last") != -1) {
reply = "December";
} else {
var reply = moment().format("MMMM");
}
cb(null, reply);
}
|
JavaScript
| 0.006486 |
@@ -1254,13 +1254,15 @@
= %22
-night
+evening
%22%0A%09%7D
|
2c9a82216cd4a97bd4bb2b9c40f95dbb0a6d2222
|
Make isColliding return false if edges overlapping
|
space-invaders/space-invaders.js
|
space-invaders/space-invaders.js
|
;(function() {
var Game = function() {
var screen = document.getElementById("screen").getContext('2d');
this.size = { x: screen.canvas.width, y: screen.canvas.height };
this.bodies = createInvaders(this).concat(new Player(this));
this.shootSound = document.getElementById('shoot-sound');
var self = this;
var tick = function() {
self.update();
self.draw(screen);
requestAnimationFrame(tick);
};
tick();
};
Game.prototype = {
update: function() {
reportCollisions(this.bodies);
for (var i = 0; i < this.bodies.length; i++) {
if (this.bodies[i].update !== undefined) {
this.bodies[i].update();
}
}
},
draw: function(screen) {
screen.clearRect(0, 0, this.size.x, this.size.y);
for (var i = 0; i < this.bodies.length; i++) {
if (this.bodies[i].draw !== undefined) {
this.bodies[i].draw(screen);
}
}
},
invadersBelow: function(invader) {
return this.bodies.filter(function(b) {
return b instanceof Invader &&
Math.abs(invader.center.x - b.center.x) < b.size.x &&
b.center.y > invader.center.y;
}).length > 0;
},
addBody: function(body) {
this.bodies.push(body);
},
removeBody: function(body) {
var bodyIndex = this.bodies.indexOf(body);
if (bodyIndex !== -1) {
this.bodies.splice(bodyIndex, 1);
}
}
};
var Invader = function(game, center) {
this.game = game;
this.center = center;
this.size = { x: 15, y: 15 };
this.patrolX = 0;
this.speedX = 0.3;
};
Invader.prototype = {
update: function() {
if (this.patrolX < 0 || this.patrolX > 30) {
this.speedX = -this.speedX;
}
if (Math.random() > 0.995 &&
!this.game.invadersBelow(this)) {
var bullet = new Bullet(this.game,
{ x: this.center.x, y: this.center.y + this.size.y / 2 },
{ x: Math.random() - 0.5, y: 2 });
this.game.addBody(bullet);
}
this.center.x += this.speedX;
this.patrolX += this.speedX;
},
draw: function(screen) {
drawRect(screen, this);
},
collision: function() {
this.game.removeBody(this);
}
};
var createInvaders = function(game) {
var invaders = [];
for (var i = 0; i < 24; i++) {
var x = 35 + (i % 8) * 30;
var y = 35 + (i % 3) * 30;
invaders.push(new Invader(game, { x: x, y: y}));
}
return invaders;
};
var Player = function(game) {
this.game = game;
this.size = { x: 15, y: 15 };
this.center = { x: this.game.size.x / 2, y: this.game.size.y - 35 };
this.keyboarder = new Keyboarder();
};
Player.prototype = {
update: function() {
if (this.keyboarder.isDown(this.keyboarder.KEYS.LEFT)) {
this.center.x -= 2;
} else if (this.keyboarder.isDown(this.keyboarder.KEYS.RIGHT)) {
this.center.x += 2;
}
if (this.keyboarder.isDown(this.keyboarder.KEYS.SPACE)) {
var bullet = new Bullet(this.game,
{ x: this.center.x, y: this.center.y - this.size.y - 10 },
{ x: 0, y: -7 });
this.game.addBody(bullet);
this.game.shootSound.load();
this.game.shootSound.play();
}
},
draw: function(screen) {
drawRect(screen, this);
},
collision: function() {
this.game.removeBody(this);
}
};
var Bullet = function(game, center, velocity) {
this.game = game;
this.center = center;
this.size = { x: 3, y: 3 };
this.velocity = velocity;
};
Bullet.prototype = {
update: function() {
this.center.x += this.velocity.x;
this.center.y += this.velocity.y;
var screenRect = {
center: { x: this.game.size.x / 2, y: this.game.size.y / 2 },
size: this.game.size
};
if (!isColliding(this, screenRect)) {
this.game.removeBody(this);
}
},
draw: function(screen) {
drawRect(screen, this);
},
collision: function() {
this.game.removeBody(this);
}
};
var Keyboarder = function() {
var keyState = {};
window.addEventListener('keydown', function(e) {
keyState[e.keyCode] = true;
});
window.addEventListener('keyup', function(e) {
keyState[e.keyCode] = false;
});
this.isDown = function(keyCode) {
return keyState[keyCode] === true;
};
this.KEYS = { LEFT: 37, RIGHT: 39, SPACE: 32 };
};
var drawRect = function(screen, body) {
screen.fillRect(body.center.x - body.size.x / 2,
body.center.y - body.size.y / 2,
body.size.x,
body.size.y);
};
var isColliding = function(b1, b2) {
return !(
b1 === b2 ||
b1.center.x + b1.size.x / 2 < b2.center.x - b2.size.x / 2 ||
b1.center.y + b1.size.y / 2 < b2.center.y - b2.size.y / 2 ||
b1.center.x - b1.size.x / 2 > b2.center.x + b2.size.x / 2 ||
b1.center.y - b1.size.y / 2 > b2.center.y + b2.size.y / 2
);
};
var reportCollisions = function(bodies) {
var bodyPairs = [];
for (var i = 0; i < bodies.length; i++) {
for (var j = i + 1; j < bodies.length; j++) {
if (isColliding(bodies[i], bodies[j])) {
bodyPairs.push([bodies[i], bodies[j]]);
}
}
}
for (var i = 0; i < bodyPairs.length; i++) {
if (bodyPairs[i][0].collision !== undefined) {
bodyPairs[i][0].collision(bodyPairs[i][1]);
}
if (bodyPairs[i][1].collision !== undefined) {
bodyPairs[i][1].collision(bodyPairs[i][0]);
}
}
};
window.addEventListener('load', function() {
new Game();
});
})();
|
JavaScript
| 0.999613 |
@@ -4924,24 +4924,25 @@
size.x / 2 %3C
+=
b2.center.x
@@ -4998,16 +4998,17 @@
.y / 2 %3C
+=
b2.cent
@@ -5064,24 +5064,25 @@
size.x / 2 %3E
+=
b2.center.x
@@ -5138,16 +5138,17 @@
.y / 2 %3E
+=
b2.cent
|
9f0a34aa99577c8c012da7c2270a5082a006f1ab
|
Tweak instance var name
|
modules/History.js
|
modules/History.js
|
import warning from 'warning'
import React, { PropTypes } from 'react'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import useQueries from 'history/lib/useQueries'
import {
history as historyType,
location as locationType
} from './PropTypes'
const isBrowserEnvironment = typeof window === 'object'
const controlledLocationType = (props, propName, componentName) => {
if (props[propName]) {
const error = locationType(props, propName, componentName)
if (error)
return error
if (typeof props.onChange !== 'function' && isBrowserEnvironment) {
return new Error(
'You provided a `location` prop to a <History> component without an `onChange` handler. ' +
'This will make the back/forward buttons and the address bar unusable. If you intend to ' +
'let the user navigate using the browser\'s built-in controls, use `defaultLocation` with ' +
'a `history` prop. Otherwise, set `onChange`.'
)
}
}
}
class History extends React.Component {
static propTypes = {
history: historyType,
location: controlledLocationType,
onChange: PropTypes.func,
children: PropTypes.oneOfType([ PropTypes.node, PropTypes.func ]),
render: PropTypes.func,
component: PropTypes.func
}
static defaultProps = {
history: useQueries(createBrowserHistory)()
}
static childContextTypes = {
location: locationType
}
getChildContext() {
const { location } = this.isControlled() ? this.props : this.state
return {
location
}
}
state = {
location: null
}
unlisten = null
unlistenBefore = null
// need to teardown and setup in cWRP too
componentWillMount() {
if (this.isControlled()) {
this.listenBefore()
} else {
this.listen()
}
}
componentWillReceiveProps(nextProps) {
warning(
nextProps.history === this.props.history,
'Don’t change the history please. Thanks.'
)
if (nextProps.location && this.props.location == null) {
this.switchToControlled()
} else if (!nextProps.location && this.props.location) {
this.switchToUncontrolled()
}
if (nextProps.location !== this.props.location) {
this.transitioning = true
const { location } = nextProps
const { history } = this.props
if (location.action === 'PUSH') {
history.push(location)
} else {
history.replace(location)
}
}
}
isControlled() {
return !!this.props.location
}
listen() {
const { history } = this.props
this.setState({
location: history.getCurrentLocation()
})
this.unlisten = history.listen(location => {
this.setState({ location })
})
}
listenBefore() {
const { history, onChange } = this.props
this.unlistenBefore = history.listenBefore((location) => {
if (!this.transitioning) {
if (onChange)
onChange(location)
return false
} else {
this.transitioning = false
return true
}
})
}
switchToControlled() {
this.unlisten()
this.unlisten = null
this.listen()
}
switchToUncontrolled() {
this.unlistenBefore()
this.unlistenBefore = null
this.listen()
}
render() {
const { children } = this.props
const { location } = this.isControlled() ? this.props : this.state
return (
typeof children === 'function' ? children({ location }) : children
)
}
}
export default History
|
JavaScript
| 0.000001 |
@@ -1608,17 +1608,16 @@
= null%0A
-%0A
unlist
@@ -1631,16 +1631,42 @@
e = null
+%0A isTransitioning = false
%0A%0A // n
@@ -2239,33 +2239,35 @@
n) %7B%0A this.
-t
+isT
ransitioning = t
@@ -2899,25 +2899,27 @@
if (!this.
-t
+isT
ransitioning
@@ -3023,17 +3023,19 @@
this.
-t
+isT
ransitio
|
58c0127b6e18f448d95650a4e0d89b6fc43ca56b
|
refactor umb editor toolbar directive to follow angular style guide
|
src/Umbraco.Web.UI.Client/src/common/directives/components/editor/umbeditortoolbar.directive.js
|
src/Umbraco.Web.UI.Client/src/common/directives/components/editor/umbeditortoolbar.directive.js
|
angular.module("umbraco.directives")
.directive('umbEditorToolbar', function () {
return {
restrict: 'E',
replace: true,
templateUrl: 'views/components/editor/umb-editor-toolbar.html',
scope: {
tools: "="
}
};
});
|
JavaScript
| 0 |
@@ -1,60 +1,48 @@
-angular.module(%22umbraco.directives%22)%0A .directive('umb
+(function() %7B%0A 'use strict';%0A%0A function
Edit
@@ -54,45 +54,47 @@
lbar
-', function
+Directive
() %7B%0A
+%0A
- return %7B%0A
+var directive = %7B%0A
@@ -122,19 +122,16 @@
-
-
replace:
@@ -137,19 +137,16 @@
: true,%0A
-
@@ -219,19 +219,16 @@
-
scope: %7B
@@ -228,18 +228,16 @@
cope: %7B%0A
-
@@ -261,30 +261,151 @@
+ %7D%0A
%7D
+;%0A
%0A
+ return directive;%0A
%7D
-;
+%0A
%0A
- %7D);
+angular.module('umbraco.directives').directive('umbEditorToolbar', EditorToolbarDirective);%0A%0A%7D)();%0A
|
db8c9e4daf185faba078b85a084e8ffa30e31c0f
|
Use ui-router's state changes for default route, this ensures we don't get the infinite redirect loop
|
controller/static/app/config.routes.js
|
controller/static/app/config.routes.js
|
(function() {
'use strict';
angular
.module('shipyard')
.config(getRoutes);
getRoutes.$inject = ['$stateProvider', '$urlRouterProvider'];
function getRoutes($stateProvider, $urlRouterProvider) {
$stateProvider
.state('error', {
url: '/error',
templateUrl: 'app/error/error.html',
authenticate: false
});
$urlRouterProvider.otherwise('/containers');
}
})();
|
JavaScript
| 0 |
@@ -455,21 +455,137 @@
ise(
-'/containers'
+function ($injector) %7B%0A var $state = $injector.get('$state');%0A $state.go('dashboard.containers');%0A %7D
);%0A
|
04018aa6a4a3c9967f7317821959df2144040822
|
make rollup cache folder name
|
packages/vue-inbrowser-compiler/rollup.config.js
|
packages/vue-inbrowser-compiler/rollup.config.js
|
import * as path from 'path'
import nodeResolve from 'rollup-plugin-node-resolve'
import typescript from 'rollup-plugin-typescript2'
import commonjs from 'rollup-plugin-commonjs'
import pkg from './package.json'
const resolve = _path => path.resolve(__dirname, _path)
export default {
input: resolve('./src/index.ts'),
output: [
{
file: pkg.main,
name: 'vueInbrowserCompiler',
format: 'umd'
},
{
file: pkg.module,
format: 'es' // the preferred format
}
],
plugins: [
// allow rollup to look for modules in node_modules
nodeResolve(),
// Compile TypeScript files
typescript({
useTsconfigDeclarationDir: true,
tsconfig: './tsconfig.build.json',
cacheRoot: '../../node_modules/.rpt2_cache'
}),
// Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
commonjs()
],
external: Object.keys(pkg.dependencies)
}
|
JavaScript
| 0.000004 |
@@ -714,19 +714,34 @@
dules/.r
-pt2
+ollup_vue-compiler
_cache'%0A
|
94a330ea3ff339ae5dbc3782fbe09e7202a03ef1
|
Isolate "reducers may not dispatch actions" bug for now
|
packages/vulcan-lib/lib/server/render_context.js
|
packages/vulcan-lib/lib/server/render_context.js
|
import { createMemoryHistory } from 'react-router';
import { compose } from 'redux';
import cookieParser from 'cookie-parser';
import { Meteor } from 'meteor/meteor';
import { DDP } from 'meteor/ddp';
import { Accounts } from 'meteor/accounts-base';
import { RoutePolicy } from 'meteor/routepolicy';
import { WebApp } from 'meteor/webapp';
import {
createApolloClient,
configureStore, getActions, getReducers, getMiddlewares,
Utils,
} from '../modules/index.js';
import { webAppConnectHandlersUse } from './meteor_patch.js';
const Fiber = Npm.require('fibers');
// check the req url
function isAppUrl(req) {
const url = req.url;
if (url === '/favicon.ico' || url === '/robots.txt') {
return false;
}
if (url === '/app.manifest') {
return false;
}
// Avoid serving app HTML for declared routes such as /sockjs/.
if (RoutePolicy.classify(url)) {
return false;
}
// we only need to support HTML pages only for browsers
// Facebook's scraper uses a request header Accepts: */*
// so allow either
const facebookAcceptsHeader = new RegExp("/*\/*/");
return /html/.test(req.headers.accept) || facebookAcceptsHeader.test(req.headers.accept);
}
// for meteor.user
const LoginContext = function LoginContext(loginToken) {
this._loginToken = loginToken;
// get the user
if (Meteor.users) {
// check to make sure, we've the loginToken,
// otherwise a random user will fetched from the db
let user;
if (loginToken) {
const hashedToken = loginToken && Accounts._hashLoginToken(loginToken);
const query = { 'services.resume.loginTokens.hashedToken': hashedToken };
const options = { fields: { _id: 1 } };
user = Meteor.users.findOne(query, options);
}
if (user) {
this.userId = user._id;
}
}
};
// for req.cookies
webAppConnectHandlersUse(cookieParser(), { order: 10, name: 'cookieParserMiddleware' });
// initRenderContextMiddleware
webAppConnectHandlersUse(Meteor.bindEnvironment(function initRenderContextMiddleware(req, res, next) {
// check the req url
if (!isAppUrl(req)) {
next();
return;
}
// init
const history = createMemoryHistory(req.url);
const loginToken = req.cookies && req.cookies.meteor_login_token;
const apolloClient = createApolloClient({ loginToken: loginToken });
let actions = {};
let reducers = { apollo: apolloClient.reducer() };
let middlewares = [Utils.defineName(apolloClient.middleware(), 'apolloClientMiddleware')];
// renderContext object
req.renderContext = {
history,
loginToken,
apolloClient,
addAction(addedAction) { // context.addAction: add action to renderContext
actions = { ...actions, ...addedAction };
return this.getActions();
},
getActions() { // SSR actions = server actions + renderContext actions
return { ...getActions(), ...actions };
},
addReducer(addedReducer) { // context.addReducer: add reducer to renderContext
reducers = { ...reducers, ...addedReducer };
return this.getReducers();
},
getReducers() { // SSR reducers = server reducers + renderContext reducers
return { ...getReducers(), ...reducers };
},
addMiddleware(middlewareOrMiddlewareArray) { // context.addMiddleware: add middleware to renderContext
const addedMiddleware = Array.isArray(middlewareOrMiddlewareArray) ? middlewareOrMiddlewareArray : [middlewareOrMiddlewareArray];
middlewares = [...middlewares, ...addedMiddleware];
return this.getMiddlewares();
},
getMiddlewares() { // SSR middlewares = server middlewares + renderContext middlewares
return [...getMiddlewares(), ...middlewares];
},
};
// create store
req.renderContext.store = configureStore(req.renderContext.getReducers, {}, (store) => {
let chain, newDispatch;
return next => (action) => {
if (!chain) {
chain = req.renderContext.getMiddlewares().map(middleware => middleware(store));
newDispatch = compose(...chain)(next)
}
return newDispatch(action);
};
})
// for meteor.user
req.loginContext = new LoginContext(loginToken);
next();
}), { order: 20 });
// render context object
export const renderContext = new Meteor.EnvironmentVariable();
// render context get function
export const getRenderContext = () => renderContext.get();
// withRenderContextEnvironment
export const withRenderContextEnvironment = (fn, options = {}) => {
// set newfn
const newfn = (req, res, next) => {
if (!isAppUrl(req)) {
next();
return;
}
Fiber.current._meteor_dynamics = Fiber.current._meteor_dynamics || [];
Fiber.current._meteor_dynamics[DDP._CurrentInvocation.slot] = req.loginContext;
Fiber.current._meteor_dynamics[renderContext.slot] = req.renderContext;
fn(req.renderContext, req, res, next);
if (options.autoNext) {
next();
}
};
// get evfn
const evfn = Meteor.bindEnvironment(newfn);
// use it
WebApp.connectHandlers.use(evfn);
// get handle
const handle = WebApp.connectHandlers.stack[WebApp.connectHandlers.stack.length - 1].handle;
// copy options to handle
Object.keys(options).forEach((key) => {
handle[key] = options[key];
});
};
// withRenderContext make it easy to access context
export const withRenderContext = (func, options = {}) => {
withRenderContextEnvironment(func, { ...options, autoNext: true });
};
|
JavaScript
| 0 |
@@ -3814,16 +3814,22 @@
spatch;%0A
+ %0A
retu
@@ -3849,24 +3849,38 @@
ction) =%3E %7B%0A
+ try %7B%0A
if (!c
@@ -3883,24 +3883,26 @@
(!chain) %7B%0A
+
chai
@@ -3978,16 +3978,26 @@
tore));%0A
+ %7D%0A
@@ -4036,22 +4036,16 @@
next)%0A
- %7D%0A
re
@@ -4066,24 +4066,112 @@
ch(action);%0A
+ %7D catch (error) %7B%0A // console.log(error)%0A return _.identity%0A %7D%0A
%7D;%0A %7D)%0A
|
781989b159536410b84b68991ccc3b1355021475
|
update example
|
packages/web/examples/MultiListAntd/src/index.js
|
packages/web/examples/MultiListAntd/src/index.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import { List, Checkbox, Card, Row, Col } from 'antd';
import { ReactiveBase, MultiList, ReactiveList, SelectedFilters } from '@appbaseio/reactivesearch';
import 'antd/dist/antd.css';
import './index.css';
const { Meta } = Card;
const Main = () => (
<ReactiveBase
app="good-books-ds"
url="https://a03a1cb71321:75b6603d-9456-4a5a-af6b-a487b309eb61@appbase-demo-ansible-abxiydt-arc.searchbase.io"
enableAppbase
>
<div className="row">
<div className="col">
<MultiList
componentId="BookSensor"
dataField="authors.keyword"
title="Filter by Authors"
aggregationSize={10}
showSearch={false}
render={({
loading, error, data, value, handleChange,
}) => {
if (loading) {
return <div>Fetching Results.</div>;
}
if (error) {
return (
<div>
Something went wrong! Error details {JSON.stringify(error)}
</div>
);
}
return (
<List
itemLayout="horizontal"
dataSource={data}
renderItem={item => (
<List.Item>
<Checkbox
style={{
marginRight: 20,
}}
value={item.key}
checked={value ? value[item.key] : false}
onChange={handleChange}
/>
<List.Item.Meta title={item.key} />
<div>{item.doc_count}</div>
</List.Item>
)}
/>
);
}}
/>
</div>
<div className="col">
<SelectedFilters />
<ReactiveList
componentId="SearchResult"
dataField="original_title"
className="result-list-container"
from={0}
size={5}
react={{
and: ['BookSensor'],
}}
render={({ data }) => (
<div className="site-card-wrapper">
<Row gutter={16}>
{data.map(item => (
<Col key={item._id} span={8}>
<Card
hoverable
cover={
<img alt={item.original_title} src={item.image} />
}
>
<Meta
title={item.original_title}
description={item.description}
/>
<div>
by{' '}
<span className="authors-list">{item.authors}</span>
</div>
<div className="ratings-list flex align-center">
<span className="stars">
{Array(item.average_rating_rounded)
.fill('x')
.map((_, index) => (
<i
className="fas fa-star"
key={index} //eslint-disable-line
/>
))}
</span>
<span className="avg-rating">
({item.average_rating} avg)
</span>
</div>
</Card>
</Col>
))}
</Row>
</div>
)}
/>
</div>
</div>
</ReactiveBase>
);
ReactDOM.render(<Main />, document.getElementById('root'));
|
JavaScript
| 0.000308 |
@@ -498,33 +498,37 @@
e=%22row%22%3E%0A%09%09%09%3Cdiv
-
+%0A%09%09%09%09
className=%22col%22%3E
@@ -522,24 +522,68 @@
ssName=%22col%22
+%0A%09%09%09%09style=%7B%7B%0A%09%09%09%09%09minWidth: 300,%0A%09%09%09%09%7D%7D%0A%09%09%09
%3E%0A%09%09%09%09%3CMulti
|
0e551bf72ba050bdd3df0724407a93b5272ba37e
|
Reduce duplication
|
modules/__tests__/describeHistory.js
|
modules/__tests__/describeHistory.js
|
import assert from 'assert';
import expect from 'expect';
import { PUSH, REPLACE, POP } from '../Actions';
function describeHistory(createHistory) {
describe('when the user confirms a transition', function () {
var confirmationMessage, location, history, unlisten;
beforeEach(function () {
location = null;
confirmationMessage = 'Are you sure?';
history = createHistory({
getUserConfirmation(message, callback) {
expect(message).toBe(confirmationMessage);
callback(true);
}
});
history.registerTransitionHook(function () {
return confirmationMessage;
});
unlisten = history.listen(function (loc) {
location = loc;
});
});
afterEach(function () {
if (unlisten)
unlisten();
});
it('updates the location', function () {
var initialLocation = location;
history.pushState({ the: 'state' }, '/home?the=query');
expect(initialLocation).toNotBe(location);
assert(location);
assert(location.key);
expect(location.state).toEqual({ the: 'state' });
expect(location.pathname).toEqual('/home');
expect(location.search).toEqual('?the=query');
expect(location.action).toEqual(PUSH);
});
});
describe('when the user cancels a transition', function () {
var confirmationMessage, location, history, unlisten;
beforeEach(function () {
location = null;
confirmationMessage = 'Are you sure?';
history = createHistory({
getUserConfirmation(message, callback) {
expect(message).toBe(confirmationMessage);
callback(false);
}
});
history.registerTransitionHook(function () {
return confirmationMessage;
});
unlisten = history.listen(function (loc) {
location = loc;
});
});
afterEach(function () {
if (unlisten)
unlisten();
});
it('does not update the location', function () {
var initialLocation = location;
history.pushState(null, '/home');
expect(initialLocation).toBe(location);
});
});
describe('pushState', function () {
var location, history, unlisten;
beforeEach(function () {
location = null;
history = createHistory();
unlisten = history.listen(function (loc) {
location = loc;
});
});
afterEach(function () {
if (unlisten)
unlisten();
});
it('calls change listeners with the new location', function () {
history.pushState({ the: 'state' }, '/home?the=query');
assert(location);
assert(location.key);
expect(location.state).toEqual({ the: 'state' });
expect(location.pathname).toEqual('/home');
expect(location.search).toEqual('?the=query');
expect(location.action).toEqual(PUSH);
});
});
describe('replaceState', function () {
var location, history, unlisten;
beforeEach(function () {
location = null;
history = createHistory();
unlisten = history.listen(function (loc) {
location = loc;
});
});
afterEach(function () {
if (unlisten)
unlisten();
});
it('calls change listeners with the new location', function () {
history.replaceState({ more: 'state' }, '/feed?more=query');
assert(location);
assert(location.key);
expect(location.state).toEqual({ more: 'state' });
expect(location.pathname).toEqual('/feed');
expect(location.search).toEqual('?more=query');
expect(location.action).toEqual(REPLACE);
});
});
describe('goBack', function () {
var history, unlisten;
beforeEach(function () {
window.history.replaceState(null, null, '/');
history = createHistory();
});
afterEach(function () {
if (unlisten)
unlisten();
});
it('calls change listeners with the previous location', function (done) {
var initialLocation;
var steps = [
function (location) {
initialLocation = location;
history.pushState({ the: 'state' }, '/two?a=query');
},
function (location) {
expect(location.state).toEqual({ the: 'state' });
expect(location.pathname).toEqual('/two');
expect(location.search).toEqual('?a=query');
expect(location.action).toEqual(PUSH);
history.goBack();
},
function (location) {
expect(location.action).toEqual(POP);
expect(initialLocation).toEqual(location);
done();
}
];
function execNextStep() {
try {
steps.shift().apply(this, arguments);
} catch (error) {
done(error);
}
}
unlisten = history.listen(execNextStep);
});
});
describe('goForward', function () {
var history, unlisten;
beforeEach(function () {
window.history.replaceState(null, null, '/');
history = createHistory();
});
afterEach(function () {
if (unlisten)
unlisten();
});
it('calls change listeners with the previous location', function (done) {
var initialLocation, nextLocation;
var steps = [
function (location) {
initialLocation = location;
history.pushState({ the: 'state' }, '/two?a=query');
},
function (location) {
nextLocation = location;
expect(location.state).toEqual({ the: 'state' });
expect(location.pathname).toEqual('/two');
expect(location.search).toEqual('?a=query');
expect(location.action).toEqual(PUSH);
history.goBack();
},
function (location) {
expect(location.action).toEqual(POP);
expect(initialLocation).toEqual(location);
history.goForward();
},
function (location) {
const nextLocationPop = { ...nextLocation, action: POP };
expect(nextLocationPop).toEqual(location);
done()
}
];
function execNextStep() {
try {
steps.shift().apply(this, arguments);
} catch (error) {
done(error);
}
}
unlisten = history.listen(execNextStep);
});
});
}
export default describeHistory;
|
JavaScript
| 0.999999 |
@@ -101,16 +101,182 @@
ions';%0A%0A
+function execSteps(steps, done) %7B%0A return function () %7B%0A try %7B%0A steps.shift().apply(this, arguments);%0A %7D catch (error) %7B%0A done(error);%0A %7D%0A %7D;%0A%7D%0A%0A
function
@@ -4768,170 +4768,8 @@
%5D;%0A%0A
- function execNextStep() %7B%0A try %7B%0A steps.shift().apply(this, arguments);%0A %7D catch (error) %7B%0A done(error);%0A %7D%0A %7D%0A%0A
@@ -4796,32 +4796,42 @@
.listen(exec
-Next
Step
+s(steps, done)
);%0A %7D);%0A
@@ -6068,170 +6068,8 @@
%5D;%0A%0A
- function execNextStep() %7B%0A try %7B%0A steps.shift().apply(this, arguments);%0A %7D catch (error) %7B%0A done(error);%0A %7D%0A %7D%0A%0A
@@ -6104,16 +6104,26 @@
exec
-Next
Step
+s(steps, done)
);%0A
|
44b9ce2bdf46e20c412f56e6c1c8ed06354debc8
|
modify JS example to avoid coredumps when run for awhile
|
examples/javascript/mma7660.js
|
examples/javascript/mma7660.js
|
/*jslint node:true, vars:true, bitwise:true, unparam:true */
/*jshint unused:true */
/*
* Author: Zion Orent <[email protected]>
* Copyright (c) 2015 Intel Corporation.
*
* 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 digitalAccelerometer = require('jsupm_mma7660');
// Instantiate an MMA7660 on I2C bus 0
var myDigitalAccelerometer = new digitalAccelerometer.MMA7660(
digitalAccelerometer.MMA7660_I2C_BUS,
digitalAccelerometer.MMA7660_DEFAULT_I2C_ADDR
);
// place device in standby mode so we can write registers
myDigitalAccelerometer.setModeStandby();
// enable 64 samples per second
myDigitalAccelerometer.setSampleRate(digitalAccelerometer.MMA7660.AUTOSLEEP_64);
// place device into active mode
myDigitalAccelerometer.setModeActive();
var myInterval = setInterval(function()
{
var x, y, z;
x = digitalAccelerometer.new_intp();
y = digitalAccelerometer.new_intp();
z = digitalAccelerometer.new_intp();
myDigitalAccelerometer.getRawValues(x, y, z);
var outputStr = "Raw values: x = " + digitalAccelerometer.intp_value(x) +
" y = " + digitalAccelerometer.intp_value(y) +
" z = " + digitalAccelerometer.intp_value(z);
console.log(outputStr);
var ax, ay, az;
ax = digitalAccelerometer.new_floatp();
ay = digitalAccelerometer.new_floatp();
az = digitalAccelerometer.new_floatp();
myDigitalAccelerometer.getAcceleration(ax, ay, az);
outputStr = "Acceleration: x = " + roundNum(digitalAccelerometer.floatp_value(ax), 6) +
"g y = " + roundNum(digitalAccelerometer.floatp_value(ay), 6) +
"g z = " + roundNum(digitalAccelerometer.floatp_value(az), 6) + "g";
console.log(outputStr);
}, 500);
// round off output to match C example, which has 6 decimal places
function roundNum(num, decimalPlaces)
{
var extraNum = (1 / (Math.pow(10, decimalPlaces) * 1000));
return (Math.round((num + extraNum) * (Math.pow(10, decimalPlaces))) / Math.pow(10, decimalPlaces));
}
// When exiting: clear interval and print message
process.on('SIGINT', function()
{
clearInterval(myInterval);
console.log("Exiting...");
process.exit(0);
});
|
JavaScript
| 0 |
@@ -1380,25 +1380,24 @@
A7660(%0A%09%09%09%09%09
-%09
digitalAccel
@@ -1423,17 +1423,16 @@
C_BUS, %0A
-%09
%09%09%09%09%09dig
@@ -1477,15 +1477,8 @@
ADDR
-%0A%09%09%09%09%09%09
);%0A%0A
@@ -1773,61 +1773,146 @@
var
-myInterval = setInterval(function()%0A%7B%0A%09
+x, y, z;%0Ax = digitalAccelerometer.new_intp();%0Ay = digitalAccelerometer.new_intp();%0Az = digitalAccelerometer.new_intp();%0A%0A
var
+a
x,
+a
y,
+a
z;%0A
-%09
+a
x =
@@ -1936,25 +1936,27 @@
ter.new_
-in
+floa
tp();%0A
-%09
+a
y = digi
@@ -1980,17 +1980,19 @@
new_
-in
+floa
tp();%0A
-%09
+a
z =
@@ -2016,25 +2016,85 @@
ter.new_
-in
+floa
tp();%0A%0A
+var outputStr;%0A%0Avar myInterval = setInterval(function()%0A%7B%0A
%09myDigit
@@ -2133,20 +2133,16 @@
y, z);%0A%09
-var
outputSt
@@ -2328,149 +2328,8 @@
);%0A%0A
-%09var ax, ay, az;%0A%09ax = digitalAccelerometer.new_floatp();%0A%09ay = digitalAccelerometer.new_floatp();%0A%09az = digitalAccelerometer.new_floatp();%0A%0A
%09myD
@@ -2407,24 +2407,27 @@
tion: x = %22
+%0A%09%09
+ roundNum(d
@@ -2466,20 +2466,21 @@
(ax), 6)
- +
%0A%09
+%09+
%22g y = %22
@@ -2533,19 +2533,21 @@
ay), 6)
-+
%0A%09
+%09+
%22g z = %22
@@ -2846,16 +2846,19 @@
traNum)
+%0A%09%09
* (Math.
@@ -3029,16 +3029,319 @@
erval);%0A
+%0A%09// clean up memory%0A%09digitalAccelerometer.delete_intp(x);%0A%09digitalAccelerometer.delete_intp(y);%0A%09digitalAccelerometer.delete_intp(z);%0A%0A%09digitalAccelerometer.delete_floatp(ax);%0A%09digitalAccelerometer.delete_floatp(ay);%0A%09digitalAccelerometer.delete_floatp(az);%0A%0A%09myDigitalAccelerometer.setModeStandby();%0A%0A
%09console
|
6b1635fc615e4303848f3811c01dd0876f9bd54a
|
use computed sort since the sortablemixin was deprecated
|
app/application/controller.js
|
app/application/controller.js
|
import Ember from 'ember';
export default Ember.Controller.extend(Ember.SortableMixin, {
sortAscending: true,
sortProperties: ['name']
});
|
JavaScript
| 0 |
@@ -64,81 +64,104 @@
end(
-Ember.SortableMixin, %7B%0A sortAscending: true,%0A sortProperties: %5B'name'%5D
+%7B%0A centresSorted: %5B'name'%5D,%0A arrangedContent: Ember.computed.sort('model', 'centresSorted'),
%0A%7D);%0A
+%0A
|
0370ea7a2d37068aa59da9d639341aca6a304cdb
|
Add seeTheFLightMap js function in app.js - seeTheFlightMap adds the map to the one page site and scrolls all the way to it - Test page is working. Styling on the test page is looking good. Design responsive.
|
app/assets/javascripts/app.js
|
app/assets/javascripts/app.js
|
$(document).ready(function() {
enterTheSite();
submitCurateFlight();
});
var enterTheSite = function() {
$('#homepage-box').on('click', 'button', function(e){
e.preventDefault();
$.ajax({
url: 'flights/search',
success: successCallback
});
function successCallback(response) {
$('header').removeClass('hidden');
$('main').html(response);
}
});
}
var submitCurateFlight = function() {
$('main').on('click', '#new_search_form button', function(e){
e.preventDefault();
$.ajax({
url: 'flights/search_results',
method: 'POST',
data: $('#new_search_form').serialize(),
success: successCallback,
error: errorCallback
});
function successCallback(response) {
$('#search-results-container').html(response);
$(window).scrollTop($('#search-results-section').offset().top);
}
function errorCallback(response) {
// Need to write the code in order to display the error message on the search form
debugger;
}
});
}
|
JavaScript
| 0 |
@@ -66,16 +66,37 @@
ight();%0A
+ seeTheFlightMap();%0A
%7D);%0A%0Avar
@@ -1043,24 +1043,600 @@
debugger;%0A %7D%0A %7D);%0A%7D%0A
+%0Avar seeTheFlightMap = function() %7B%0A $('main').on('click', '#search-results-box a', function(e)%7B%0A e.preventDefault();%0A var flightUrl;%0A%0A flightUrl = $(this).attr('href');%0A%0A $.ajax(%7B%0A url: flightUrl,%0A success: successCallback,%0A error: errorCallback%0A %7D);%0A%0A function successCallback(response) %7B%0A $('#business-results-container').html(response);%0A $(window).scrollTop($('#map-display-section').offset().top);%0A %7D%0A%0A function errorCallback(response) %7B%0A // Need to write the code if there is an error%0A debugger;%0A %7D%0A %7D);%0A%7D%0A
|
81e7b4444ffd65cb5ace4ea21cfa8ce76aeb5939
|
use slidetoggle
|
app/assets/javascripts/nav.js
|
app/assets/javascripts/nav.js
|
$(document).ready(function(){
$('.menu-toggle').on('mouseenter',function() {
$('.nav-list').css('display', 'inline')
});
$('.menu-toggle').bind('mouseleave', function(){
$('.nav-list').css('display', 'inline')
$('.nav-list').hide();
});
});
|
JavaScript
| 0.000001 |
@@ -47,12 +47,8 @@
e').
-on('
mous
@@ -53,18 +53,17 @@
useenter
-',
+(
function
@@ -68,17 +68,16 @@
on()
-
%7B%0A $(
'.na
@@ -64,33 +64,33 @@
nction()%7B%0A $(
-'
+%22
.nav-list').css(
@@ -86,43 +86,38 @@
list
-').css('display', 'inline')
+%22).slideToggle(%22fast%22);
%0A %7D);%0A
-%0A
$(
@@ -136,14 +136,8 @@
e').
-bind('
mous
@@ -142,19 +142,17 @@
useleave
-',
+(
function
@@ -157,25 +157,25 @@
on()%7B%0A $(
-'
+%22
.nav-list').
@@ -175,60 +175,29 @@
list
-').css('display', 'inline')%0A $('.nav-list').hide(
+%22).slideToggle(%22fast%22
);%0A
|
fc10ebea9686e8eab01434710d4bc490b1d98b01
|
Fix empty image when navigating to new editor from an editor with image
|
app/components/gh-uploader.js
|
app/components/gh-uploader.js
|
import Ember from 'ember';
import uploader from 'ghost/assets/lib/uploader';
export default Ember.Component.extend({
classNames: ['image-uploader', 'js-post-image-upload'],
config: Ember.inject.service(),
imageSource: Ember.computed('image', function () {
return this.get('image') || '';
}),
/**
* Sets up the uploader on render
*/
setup: function () {
var $this = this.$(),
self = this;
// this.set('uploaderReference', uploader.call($this, {
// editor: true,
// fileStorage: this.get('config.fileStorage')
// }));
$this.on('uploadsuccess', function (event, result) {
if (result && result !== '' && result !== 'http://') {
self.sendAction('uploaded', result);
}
});
$this.on('imagecleared', function () {
self.sendAction('canceled');
});
},
// removes event listeners from the uploader
removeListeners: function () {
var $this = this.$();
$this.off();
$this.find('.js-cancel').off();
},
// didInsertElement: function () {
// Ember.run.scheduleOnce('afterRender', this, this.setup());
// },
didInsertElement: function () {
this.send('initUploader');
},
willDestroyElement: function () {
this.removeListeners();
},
actions: {
initUploader: function () {
var ref,
el,
self = this;
el = this.$();
ref = uploader.call(el, {
editor: true,
fileStorage: this.get('config.fileStorage')
});
el.on('uploadsuccess', function (event, result) {
if (result && result !== '' && result !== 'http://') {
self.sendAction('uploaded', result);
}
});
el.on('imagecleared', function () {
self.sendAction('canceled');
});
this.sendAction('initUploader', ref);
}
}
});
|
JavaScript
| 0.000006 |
@@ -1389,24 +1389,1214 @@
();%0A %7D,%0A%0A
+ // NOTE: because the uploader is sometimes in the same place in the DOM%0A // between transitions Glimmer will re-use the existing elements including%0A // those that arealready decorated by jQuery. The following works around%0A // situations where the image is changed without a full teardown/rebuild%0A didReceiveAttrs: function (attrs) %7B%0A var oldValue = attrs.oldAttrs && Ember.get(attrs.oldAttrs, 'image.value'),%0A newValue = attrs.newAttrs && Ember.get(attrs.newAttrs, 'image.value'),%0A self = this;%0A%0A // always reset when we receive a blank image%0A // - handles navigating to populated image from blank image%0A if (Ember.isEmpty(newValue) && !Ember.isEmpty(oldValue)) %7B%0A self.$()%5B0%5D.uploaderUi.reset();%0A %7D%0A%0A // re-init if we receive a new image but the uploader is blank%0A // - handles back button navigating from blank image to populated image%0A if (!Ember.isEmpty(newValue) && this.$()) %7B%0A if (this.$('.js-upload-target').attr('src') === '') %7B%0A this.$()%5B0%5D.uploaderUi.reset();%0A this.$()%5B0%5D.uploaderUi.initWithImage();%0A %7D%0A %7D%0A %7D,%0A%0A
actions:
|
f519614963a86a08c7ba079b63afe1b9a3b1b5e5
|
remove extra line
|
app/controllers/es/landsat.js
|
app/controllers/es/landsat.js
|
'use strict';
var ejs = require('elastic.js');
var client = require('../../services/elasticsearch.js');
var queries = require('./queries.js');
var Boom = require('boom');
module.exports = function (params, request, cb) {
var err;
// Build Elastic Search Query
var q = ejs.Request();
// Do legacy search
if (Object.keys(params).length > 0) {
q = queries(params, q, request.limit);
} else {
q.query(ejs.MatchAllQuery()).sort('acquisitionDate', 'desc');
}
// Legacy support for skip parameter
if (params.skip) {
request.page = Math.floor(parseInt(params.skip, 10) / request.limit);
}
// Decide from
var from = (request.page - 1) * request.limit;
var search_params = {
index: process.env.ES_INDEX || 'landsat',
body: q
};
if (!params.count) {
search_params.from = from;
search_params.size = request.limit;
}
client.search(search_params).then(function (body) {
var response = [];
var count = 0;
// Process Facets
if (params.count) {
// Term facet count
response = body.facets.count.terms;
count = body.facets.count.total;
// Process search
} else {
count = body.hits.total;
for (var i = 0; i < body.hits.hits.length; i++) {
response.push(body.hits.hits[i]._source);
}
}
return cb(err, response, count);
}, function (err) {
return cb(Boom.badRequest(err));
});
};
|
JavaScript
| 0.018303 |
@@ -1152,17 +1152,16 @@
else %7B%0A
-%0A
co
|
0e27a0f6c559fd8bff86e79d4b6e55f59ae6d367
|
set min date to 0
|
app/controllers/task_table.js
|
app/controllers/task_table.js
|
/**
* Created by Q on 6/6/2015.
*/
'use strict';
angular.module('taskowl.task_table',['ngRoute','ui.bootstrap']);
angular.module('taskowl.task_table').config(['$routeProvider', function($routeProvider){
$routeProvider.when('/tasks',{
templateUrl: 'views/task_table.html',
controller: 'TaskTableCtrl'
});
}]);
angular.module('taskowl.task_table').controller("TaskTableCtrl",
['$scope','Tasks','$cookies','Courses','$modal','$log','Enrollments',
function($scope,Tasks,$cookies,Courses,$modal,$log, Enrollments){
$scope.user_id = $cookies.get('user_id');
$scope.username = $cookies.get('username');
$scope.animationsEnabled = true;
$scope.loaded = false;
$scope.tasks = null;
$scope.success = null;
$scope.message = null;
//The shows
$scope.show = {
assignment:false,
test:false,
reading:false,
presentation: false,
misc: false,
meeting : false,
show_all : true
};
$scope.courses = Enrollments.getUserEnrollments($scope.user_id);
$scope.courses.$promise.then(function(courses){
$scope.courses=courses;
});
$scope.refreshTasks = function(){
Tasks.getTasks($scope.user_id).$promise.then(function(tasks){
$scope.tasks=tasks;
$scope.loaded = true;
});
};
$scope.refreshTasks();
$scope.getCourseCode = function(course_id){
//Just iterating for now because I want to only search the user's courses eventually
var found = false;
var i =0;
var code = '';
while(found==false && i<$scope.courses.length){
if( course_id == $scope.courses[i].id){
found =true;
code = $scope.courses[i].code;
}
i++;
}
return code;
};
$scope.showTask = function(type){
var string_type =type.trim().toLowerCase().toString();
return !$scope.show[string_type];
};
$scope.updateTask =function(task){
Tasks.updateTask($scope.user_id, task).$promise.then(
function(success) {
$scope.success = true;
$scope.message = "Task was successfully changed.";
if(task.share==true){
Courses.createMasterTask(task.id_course, task);
}
},function(error) {
$scope.message = error.data.message;
$scope.success = false;
}
);
};
$scope.deleteTask = function(task){
Tasks.deleteTask($scope.user_id, task.id).$promise.then(
function(success) {
$scope.success = true;
$scope.message = success.message;
$scope.remove(task);
},function(error) {
$scope.message = error.data.message;
console.log(error);
$scope.success = false;
}
);
};
$scope.remove = function(item) {
var index = $scope.tasks.indexOf(item);
$scope.tasks.splice(index, 1);
};
$scope.addTask =function(task){
//TODO remove duplication
task.complete = false;
$scope.task = task;
$scope.task.type = $scope.task.type.trim();
Tasks.createTask($scope.user_id,task).$promise.then(
function(success) {
$scope.success = true;
$scope.message = "Task was successfully added.";
if(task.share==true){
Courses.createMasterTask(task.id_course, task);
}
$scope.refreshTasks();
},function(error) {
$scope.message = error.data.message;
$scope.success = false;
}
);
};
$scope.completeTask = function(task){
task.complete = !task.complete;
$scope.updateTask(task);
};
$scope.openModal = function (task, title, size) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'edit_task.html',
controller: 'TaskModalInstanceCtrl',
size:size,
resolve: {
task: function () {
return task;
},
courses: function(){
return $scope.courses;
},
page_title: function(){
return title;
}
}
});
modalInstance.result.then(function (data) {
if(data.is_new){
$scope.addTask(data.task);
}else{
$scope.updateTask(data.task);
}
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.toggleAnimation = function () {
$scope.animationsEnabled = !$scope.animationsEnabled;
};
}]);
angular.module('taskowl.task_table').controller('TaskModalInstanceCtrl',
function ($scope, $modalInstance, task, courses, TYPES, page_title) {
$scope.types = TYPES;
$scope.courses = courses;
$scope.page_title = page_title;
$scope.is_modal = true;
$scope.openend = false;
if(task != null){
$scope.task = task;
task.type = task.type.trim();
$scope.is_new = false;
}else{
$scope.task = {
in_class : true,
due_date : new Date(),
due_time : new Date()
};
$scope.is_new = true;
}
$scope.submitTask = function (isValid) {
if(isValid){
var data = {is_new: $scope.is_new, task:$scope.task};
$modalInstance.close(data);
}
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.today = function() {
$scope.task.due_date = new Date();
};
$scope.clear = function () {
$scope.task.due_date = null;
};
// Disable weekend selection
$scope.disabled = function(date, mode) {
return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
};
$scope.toggleMin = function() {
$scope.minDate = $scope.minDate ? null : new Date();
};
$scope.toggleMin();
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date();
afterTomorrow.setDate(tomorrow.getDate() + 2);
$scope.events =
[
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
$scope.getDayClass = function(date, mode) {
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0,0,0,0);
for (var i=0;i<$scope.events.length;i++){
var currentDay = new Date($scope.events[i].date).setHours(0,0,0,0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
}
return '';
};
$scope.hstep = 1;
$scope.mstep = 15;
$scope.options = {
hstep: [1, 2, 3],
mstep: [1, 5, 10, 15, 25, 30]
};
$scope.ismeridian = true;
$scope.changed = function () {
};
});
|
JavaScript
| 0.999996 |
@@ -5782,16 +5782,54 @@
= false;
+%0A $scope.minDate = new Date(0);
%0A%0A
|
9cce4a63966515ae814129152bec3b95a883609b
|
Define some functions to implement based on php-sdk
|
lib/facebook.js
|
lib/facebook.js
|
var https = require('https');
var url = require('url');
var crypto = require('crypto');
var DOMAIN_MAP = {
api : 'https://api.facebook.com/',
apiVideo : 'https://api-video.facebook.com/',
apiRead : 'https://api-read.facebook.com/',
graph : 'https://graph.facebook.com/',
graphVideo : 'https://graph-video.facebook.com/',
www : 'https://www.facebook.com/',
};
var appId;
var appSecret;
var user;
var signedRequest;
var state;
var accessToken;
|
JavaScript
| 0.000011 |
@@ -386,16 +386,17 @@
Secret;%0A
+%0A
var user
@@ -416,16 +416,36 @@
equest;%0A
+/* session bound */%0A
var stat
@@ -464,9 +464,212 @@
sToken;%0A
-%0A
+var code;%0A%0A/**%0A * auth(config):function(req, res, next)%0A * %0A * setPersistentData(key, value):void%0A * getPersistentData(key, default):*%0A * clearPersistentData(key):void%0A * clearAllPersistentData():void%0A */
|
b7bae3980e96d4e4228f943b5ce2f94f7ddbcf6a
|
Use protocol-relative url for api call - wasn't working from https: #210
|
static/js/event-form.js
|
static/js/event-form.js
|
var animationTime = 200; // ms
$(function() {
// Register event to show event group forms
$('#id_event-group-enabled').on('change', function(ev) {
if (ev.target.checked) {
$('#id_event-group').prop('disabled', false)
$('.event-group').slideDown(animationTime);
} else {
$('.event-group').slideUp(animationTime);
$('#id_event-group').prop('disabled', true)
}
});
// Initialise datetimepicker's
$('.js-datetimepicker').datetimepicker({
format: 'dd/mm/yyyy hh:ii',
autoclose: true,
});
$('#event-start.js-datetimepicker').on('changeDate', function(ev) {
//set the end time to 1 hour later
hours = ev.date.getHours();
var date = new Date(ev.date);
date.setHours(date.getHours()+1, date.getMinutes());
$('#event-end.js-datetimepicker').data('datetimepicker').setDate(date);
});
$('#create-group-button').data('successCallback', function(newGroup) {
$('<option>').attr('value', newGroup.id).text(newGroup.title).appendTo('#id_event-group').prop('selected', true);
//update the event's department, if the newly created group has it set
if (newGroup.department_organiser != null) {
updateEventDepartment(newGroup.department_organiser);
}
})
$('.js-create-person-control').each( function() {
//reveal the form panel on clicking the reveal link
$(this).find('.js-create-person').on('click', function(ev) {
ev.preventDefault();
var $control = $(ev.target).parent().parent();
$control.find('.js-person-panel').slideDown(animationTime);
})
//capture the click on 'Add' and update the relevant control
$(this).find('.js-submit-person').on('click', function(ev) {
var $control = $(ev.target).parent().parent();
var namefield = $control.find('#id_name');
var biofield = $control.find('#id_bio');
var csrftoken = $.cookie('csrftoken');
var $errorMessage = $control.find('.js-person-form-errors');
var target = $(this).attr('data-input-target');
var $target = $(target);
$.ajax({
type: 'POST',
url: '/api/persons/new',
headers: {
"X-CSRFToken": csrftoken,
},
data: {
name: namefield.val(),
bio: biofield.val()
},
success: function(response) {
$target.trigger("addPerson", response);
namefield.val("");
biofield.val("");
//clear error classes
setErrorStateForInput($control, 'name', false);
setErrorStateForInput($control, 'bio', false);
//clear and hide error message
$errorMessage.addClass("hidden");
},
error: function(response) {
setErrorStateForInput($control, 'name', false);
setErrorStateForInput($control, 'bio', false)
for(key in response.responseJSON) {
setErrorStateForInput($control, key, true)
}
$errorMessage.removeClass("hidden");
$errorMessage.html("Missing required field");
}
}
);
})
});
function setErrorStateForInput(control, id, on) {
var el = control.find("#id_"+id).parent().parent();
if(on) {
el.addClass("has-error");
}
else {
el.removeClass("has-error");
}
}
function updateEventDepartment(location_id) {
if(!location_id) { return; }
$.ajax({
type:'GET',
url: 'http://api.m.ox.ac.uk/places/' + location_id,
success: function(response) {
$('#id_event-department_organiser').trigger("eventGroupChanged", response);
},
error: function(err) {
console.log(err);
}
})
}
//On picking a new event group, retrieve the information and set the value of the department organiser field
$('#id_event-group').change( function() {
var groupID = this.value;
if(!groupID) {
//User has probably selected the 'Please select' option
return;
}
var url = '/api/series/id/' + groupID
//retrieve the ID of the event organiser and apply that to the department field of the form
$.ajax({
type: 'GET',
url: url,
success: function(response) {
//retrieve the name of the location in question
updateEventDepartment(response.department_organiser);
},
error: function(err) {
console.log(err);
}
});
})
});
|
JavaScript
| 0.000001 |
@@ -4071,13 +4071,8 @@
l: '
-http:
//ap
|
fd59c4e0e6cbed832346cc9560d6bed77df0df2b
|
Update muster parser
|
app/helpers/musters_parser.js
|
app/helpers/musters_parser.js
|
'use strict';
const Utils = require('./utils');
const D3 = require('d3');
exports.block = function(rows) {
var cardsResponse = D3.values(rows[0]);
var stateResponse = D3.values(rows[1]);
var stateCode = stateResponse[0].state_code;
// Nest the cards response
var cards = D3.nest()
.key(function(d) {
return d.block_code + d.block_name;
})
.key(function(d) {
return d.staff_id;
})
.rollup(function(v) {
return {
'staff_id': v[0].staff_id,
'name': v[0].name,
'designation': Utils.getDesignation(v[0].task_assign, stateCode),
'mobile': v[0].mobile_no,
'current_total': v[0].current_total,
'delayed_total': v[0].delayed_total,
'delayed_musters': v.filter(function(d) {
return d.type === 'delayed_musters';
}).map(function(d) {
return {
'msr_no': d.msr_no,
'panchayat_name': d.panchayat_name,
'work_name': d.work_name,
'work_code': d.work_code,
'closure_date': d.end_date,
'days_pending': d.days_pending
};
}),
'current_musters': v.filter(function(d) {
return d.type === 'current_musters';
}).map(function(d) {
return {
'msr_no': d.msr_no,
'panchayat_name': d.panchayat_name,
'work_name': d.work_name,
'work_code': d.work_code,
'closure_date': d.end_date
};
})
};
})
.entries(cardsResponse)
.map(function(d) {
return {
'region_type': 'block',
'region_code': d.key.substr(0,7),
'region_name': d.key.substr(7),
'cards': d.values.map(function(e) {
return e.values;
}).sort(function (a, b){
var aActive = a.current_total + a.delayed_total > 0 ? 1 : 0;
var bActive = b.current_total + b.delayed_total > 0 ? 1 : 0;
var aUnmapped = a.name === 'Unmapped' ? 1 : 0;
var bUnmapped = b.name === 'Unmapped' ? 1 : 0;
// ORDER BY active DESC, unmapped, delayed_total DESC, current_total DESC, name;"
if (aActive < bActive) return 1;
if (aActive > bActive) return -1;
if (aUnmapped < bUnmapped) return -1;
if (aUnmapped > bUnmapped) return 1;
if (a.delayed_total < b.delayed_total) return 1;
if (a.delayed_total > b.delayed_total) return -1;
if (a.current_total < b.current_total) return 1;
if (a.current_total > b.current_total) return -1;
if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
return 0;
})
};
});
var data = {
'musters': cards
};
return data;
};
exports.district = function(rows) {
var cardsResponse = rows;
// Nest the cards response
var cards = D3.nest()
.key(function(d) {
return d.district_code + d.district_name;
})
.key(function(d) {
return d.block_code;
})
.rollup(function(v) {
return {
'officers': v.map(function(d) {
return {
officer_id: d.block_code + '_' + d.designation_id,
name: d.firstname == null && d.lastname == null ? 'No Data' : d.firstname.toUpperCase() + ' ' + d.lastname.toUpperCase(),
designation: d.designation,
designation_id: d.designation_id,
mobile: d.mobile
};
}).sort(function(a,b) {
return a.designation_id - b.designation_id;
}),
'block_code': v[0].block_code,
'block_name': v[0].block_name,
'current_total': v[0].current_total,
'delayed_total': v[0].delayed_total,
'days_to_payment': v[0].days_to_payment,
't2_total': v[0].t2_total,
't2_avg': v[0].t2_avg,
't5_total': v[0].t5_total,
't5_avg': v[0].t5_avg,
't6_total': v[0].t6_total,
't6_avg': v[0].t6_avg,
't7_total': v[0].t7_total,
't7_avg': v[0].t7_avg,
't8_total': v[0].t8_total,
't8_avg': v[0].t8_avgw
};
})
.entries(cardsResponse)
.map(function(d) {
return {
'region_type': 'district',
'region_code': d.key.substr(0,4),
'region_name': d.key.substr(4),
'cards': d.values.map(function(e) {
return e.values;
}).sort(function (a, b){
if (a.block_name.toLowerCase() < b.block_name.toLowerCase()) return -1;
if (a.block_name.toLowerCase() > b.block_name.toLowerCase()) return 1;
return 0;
})
};
});
var data = {
'musters': cards
};
return data;
};
|
JavaScript
| 0.000001 |
@@ -621,29 +621,8 @@
n':
-Utils.getDesignation(
v%5B0%5D
@@ -638,20 +638,8 @@
ign,
- stateCode),
%0A
|
f2998ef288f09152fc2d2ff5581afc1229d9caa8
|
add conditional for systems to hide dropdown
|
static/scripts/login.js
|
static/scripts/login.js
|
import './pwd.js';
/* global introJs */
$(document).ready(function() {
// reset localStorage when new version is Published
const newVersion = 1;
const currentVersion = parseInt(localStorage.getItem('homepageVersion') || '0', 10);
if(currentVersion < newVersion){
localStorage.clear();
localStorage.setItem('homepageVersion', newVersion.toString());
}
try {
console.log(`
__ __ ____ ______ _____ __ ___ _____ ___ __
/\\ \\/\\ \\/\\ _\`\\ /\\__ _\\ /\\ __\`\\ /\\ \\ /\\_ \\ /\\ __\`\\/\\_ \\ /\\ \\
\\ \\ \\_\\ \\ \\ \\_\\ \\/_/\\ \\/ \\ \\,\\_\\_\\ ___\\ \\ \\___ __ __\\//\\ \\ \\ \\ \\/\\_\\//\\ \\ ___ __ __ \\_\\ \\
\\ \\ _ \\ \\ ,__/ \\ \\ \\ \\/_\\___ \\ /'___\\ \\ _ \`\\/\\ \\/\\ \\ \\ \\ \\ ______\\ \\ \\/_/_\\ \\ \\ / __\`\\/\\ \\/\\ \\ /'_\` \\
\\ \\ \\ \\ \\ \\ \\/ \\_\\ \\__ /\\ \\_\\ \\/\\ \\__/\\ \\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\_/\\_____\\\\ \\ \\_\\ \\\\_\\ \\_/\\ \\_\\ \\ \\ \\_\\ \\/\\ \\_\\ \\
\\ \\_\\ \\_\\ \\_\\ /\\_____\\ \\ \`\\____\\ \\____\\\\ \\_\\ \\_\\ \\____/ /\\____\\/_____/ \\ \\____//\\____\\ \\____/\\ \\____/\\ \\___,_\\
\\/_/\\/_/\\/_/ \\/_____/ \\/_____/\\/____/ \\/_/\\/_/\\/___/ \\/____/ \\/___/ \\/____/\\/___/ \\/___/ \\/__,_ /
`);
console.log("Mit Node, React und Feathers verknüpfst du eher die Sprache Javascript als Englisch? Du suchst ein junges Team, lockere Atmosphäre und flache Hierarchien? Dann schau dir unsere Stellen an: https://schul-cloud.org/community#jobs");
} catch(e) {
// no log
}
var $btnToggleProviers = $('.btn-toggle-providers');
var $btnHideProviers = $('.btn-hide-providers');
var $btnLogin = $('.btn-login');
var $loginProviders = $('.login-providers');
var $school = $('.school');
var $systems = $('.system');
var $modals = $('.modal');
var $pwRecoveryModal = $('.pwrecovery-modal');
var $submitButton = $('#submit-login');
var incTimer = function(){
setTimeout (function(){
if(countdownNum != 1){
countdownNum--;
$submitButton.val('Bitte ' + countdownNum + ' Sekunden warten');
incTimer();
} else {
$submitButton.val('Anmelden');
}
},1000);
};
if($submitButton.data('timeout')){
setTimeout (function(){
$submitButton.prop('disabled', false);
},$submitButton.data('timeout')*1000);
var countdownNum = $submitButton.data('timeout');
incTimer();
}
var loadSystems = function(schoolId) {
$systems.empty();
$.getJSON('/login/systems/' + schoolId, function(systems) {
systems.forEach(function(system) {
var systemAlias = system.alias ? ' (' + system.alias + ')' : '';
let selected;
if(localStorage.getItem('loginSystem') == system._id) {
selected = true;
}
$systems.append('<option ' + (selected ? 'selected': '') + ' value="' + system._id + '">' + system.type + systemAlias + '</option>');
});
$systems.trigger('chosen:updated');
systems.length == 1 ? $systems.parent().hide() : $systems.parent().show();
});
};
$btnToggleProviers.on('click', function(e) {
e.preventDefault();
$btnToggleProviers.hide();
$loginProviders.show();
});
$btnHideProviers.on('click', function(e) {
e.preventDefault();
$btnToggleProviers.show();
$loginProviders.hide();
$school.val('');
$school.trigger('chosen:updated');
$systems.val('');
$systems.trigger('chosen:updated');
});
$btnLogin.on('click', function(e) {
const school = $school.val();
const system = $systems.val();
if(school){
localStorage.setItem('loginSchool', school);
}
if(system){
localStorage.setItem('loginSystem', system);
}
});
$school.on('change', function() {
const id = $(this).val();
loadSystems( id );
$school.find("option").not("[value='"+id+"']").removeAttr('selected');
$school.find("option[value='"+id+"']").attr('selected',true);
$school.trigger('chosen:updated');
});
$('.submit-pwrecovery').on('click', function(e) {
e.preventDefault();
populateModalForm($pwRecoveryModal, {
title: 'Passwort Zurücksetzen',
closeLabel: 'Abbrechen',
submitLabel: 'Abschicken'
});
$pwRecoveryModal.appendTo('body').modal('show');
});
$modals.find('.close, .btn-close').on('click', function() {
$modals.modal('hide');
});
// if stored login system - use that
if(localStorage.getItem('loginSchool')) {
$btnToggleProviers.hide();
$loginProviders.show();
$school.val(localStorage.getItem('loginSchool'));
$school.trigger('chosen:updated');
$school.trigger('change');
}
});
window.startIntro = function startIntro() {
introJs()
.setOptions({
nextLabel: "Weiter",
prevLabel: "Zurück",
doneLabel: "Nächste Seite",
skipLabel: "Überspringen",
hidePrev: true, //hide previous button in the first step
hideNext: true //hide next button in the last step
})
.start()
.oncomplete(function() {
localStorage.setItem('Tutorial', true);
document.querySelector("#demologin").click();
});
};
if ('serviceWorker' in navigator){
navigator.serviceWorker.getRegistrations().then(function(registrations) {
for(let registration of registrations) {
if(registration.active && registration.active.scriptURL.endsWith('/sw.js')){
registration.unregister();
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
return cacheName.startsWith('workbox') | cacheName.startsWith('images')
| cacheName.startsWith('pages') | cacheName.startsWith('vendors');
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
});
}
}
});
}
|
JavaScript
| 0 |
@@ -2795,24 +2795,140 @@
(systems) %7B%0A
+ if (systems.length %3C 2)%7B%0A $systems.parent().hide()%0A return;%0A %7D%0A
|
08aed6cc61b49921ce4d6438c77744af47ee6f82
|
Add better watchword, picture, instead of selfie
|
modules/recognizer/recognizer.js
|
modules/recognizer/recognizer.js
|
Module.register("recognizer",{
start() {
console.log("Recognizer started");
this.sendSocketNotification("RECOGNIZER_STARTUP");
return;
},
socketNotificationReceived: function(notification) {
console.log("Recognizer recieved a notification: " + notification)
if (notification === "RECOGNIZER_CONNECTED"){
console.log("Recognizer initialized, awaiting Activation");
return;
}
if(notification === "selfie") {
console.log("=============================");
console.log("recieved request for picture!")
sendSocketNotification("TAKE_SELFIE");
return;
}
}
});
|
JavaScript
| 0.999809 |
@@ -441,13 +441,14 @@
== %22
-selfi
+pictur
e%22)
|
031dd0cb0a45959db07783a3bb55ac37d10e4a48
|
Fix parse error
|
js/foam/u2/md/OverlayDropdown.js
|
js/foam/u2/md/OverlayDropdown.js
|
/**
* @license
* Copyright 2016 Google Inc. 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.
*/
CLASS({
package: 'foam.u2.md',
name: 'OverlayDropdown',
extends: 'foam.u2.Element',
imports: [
'document',
'window',
],
exports: [
'as dropdown',
],
documentation: 'A popup overlay that grows from the top-right corner of ' +
'its container. Useful for e.g. "..." overflow menus in action bars. ' +
'Just $$DOC{ref:".add"} things to this container.',
properties: [
{
type: 'Float',
name: 'height',
defaultValue: 0,
// TODO(braden): Style should react to this property. Remember to guard
// against negative.
},
{
type: 'Boolean',
name: 'opened',
documentation: 'True when the overlay has been commanded to be open. ' +
'It might still be animating; see $$DOC{ref:".animationComplete"}.',
defaultValue: false,
},
{
type: 'Boolean',
name: 'animationComplete',
documentation: 'True when an animation is running. The overlay hasn\'t ' +
'really reached the state commanded by $$DOC{ref:".opened"} until ' +
'this is true.',
defaultValue: true
},
{
name: 'dropdownE_',
factory: function() {
// This needs to be created early so it's safe to add() things to it.
return this.E('dropdown');
}
},
{
name: 'addToSelf_',
defaultValue: false
},
],
methods: [
function add() {
if (this.addToSelf_) this.SUPER.apply(this, arguments);
else this.dropdownE_.add.apply(this.dropdownE_, arguments);
return this;
},
function open() {
if (this.opened) return;
this.opened = true;
this.height = -1;
this.animationComplete = false;
},
function close() {
if (!this.opened) return;
this.height = 0;
this.opened = false;
},
function getFullHeight() {
if (this.state !== this.LOADED) return;
var myStyle = this.window.getComputedStyle(this.dropdownE_.el());
var border = 0;
['border-top', 'border-bottom'].forEach(function(name) {
var match = myStyle[name].match(/^([0-9]+)px/);
if (match) border += parseInt(match[1]);
});
var last = this.dropdownE_.children[this.dropdownE_.children.length - 1].el();
var margin = parseInt(this.window.getComputedStyle(last))['margin-bottom']);
if (Number.isNaN(margin)) margin = 0;
return Math.min(border + last.offsetTop + last.offsetHeight + margin,
this.window.innerHeight - this.dropdownE_.el().getBoundingClientRect().top);
},
function initE() {
this.addToSelf_ = true;
this.cls(this.myCls('container'));
this.style({
display: this.dynamic(function(open) {
return open ? 'block' : 'none';
}, this.opened$)
});
var overlayStyle = this.dynamic(function(open) {
return open ? '0' : 'initial';
}, this.opened$);
this.start('dropdown-overlay')
.cls(this.myCls('overlay'))
.style({
top: overlayStyle,
bottom: overlayStyle,
left: overlayStyle,
right: overlayStyle
})
.on('click', this.onCancel)
.end();
this.dropdownE_.cls(this.myCls())
.cls(this.dynamic(function(open, complete) {
return open && complete ? this.myCls('open') : '';
}.bind(this), this.opened$, this.animationComplete$))
.on('transitionend', this.onTransitionEnd)
.on('mouseleave', this.onMouseLeave)
.on('click', this.onClick);
this.dropdownE_.dynamic(this.onHeightChange, this.height$);
this.add(this.dropdownE_);
this.addToSelf_ = false;
},
],
templates: [
function CSS() {/*
^overlay {
position: fixed;
z-index: 1009;
}
^container {
position: absolute;
right: 0;
top: 0;
z-index: 100;
}
^ {
background: white;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.38);
display: block;
font-size: 13px;
font-weight: 400;
overflow-x: hidden;
overflow-y: hidden;
position: absolute;
right: 3px;
top: 4px;
transition: height 0.25s cubic-bezier(0, .3, .8, 1);
z-index: 1010;
}
^open {
overflow-y: auto;
}
*/},
],
listeners: [
function onCancel() {
this.close();
},
function onTransitionEnd() {
this.animationComplete = true;
},
function onMouseLeave(e) {
console.assert(e.target === this.dropdownE_.el(),
'mouseleave should only fire on this, not on children');
this.close();
},
function onClick(e) {
// Prevent clicks inside the dropdown from closing it.
// Block them before they reach the overlay.
e.stopPropagation();
},
function onHeightChange() {
var height = this.height < 0 ? this.getFullHeight() : this.height;
this.dropdownE_.style({ height: height + 'px' });
},
]
});
|
JavaScript
| 0.000001 |
@@ -2946,17 +2946,16 @@
le(last)
-)
%5B'margin
|
69346609bcc3e47323a347e697c958415897e589
|
Add bug 1081850.
|
js/jsfunfuzz/avoid-known-bugs.js
|
js/jsfunfuzz/avoid-known-bugs.js
|
function whatToTestSpidermonkeyTrunk(code)
{
/* jshint laxcomma: true */
// regexps can't match across lines, so replace whitespace with spaces.
var codeL = code.replace(/\s/g, " ");
return {
allowParse: true,
allowExec: unlikelyToHang(code)
&& (jsshell || code.indexOf("nogeckoex") == -1)
,
allowIter: true,
// Ideally we'd detect whether the shell was compiled with --enable-more-deterministic
expectConsistentOutput: true
&& (gcIsQuiet || code.indexOf("gc") == -1)
&& code.indexOf("Date") == -1 // time marches on
&& code.indexOf("random") == -1
&& code.indexOf("dumpObject") == -1 // shows heap addresses
&& code.indexOf("oomAfterAllocations") == -1
&& code.indexOf("reducePar") == -1 // only deterministic for associative elemental-reducers
&& code.indexOf("scanPar") == -1 // only deterministic for associative elemental-reducers
&& code.indexOf("scatterPar") == -1 // only deterministic for associative conflict-resolvers
,
expectConsistentOutputAcrossIter: true
&& code.indexOf("options") == -1 // options() is per-cx, and the js shell doesn't create a new cx for each sandbox/compartment
,
expectConsistentOutputAcrossJITs: true
&& code.indexOf("/*NODIFF*/") == -1 // Ignore diff testing on these labels
&& code.indexOf("'strict") == -1 // see bug 743425
&& code.indexOf("Object.seal") == -1 // bug 937922
&& code.indexOf("length") == -1 // bug 1027846
&& code.indexOf("buildPar") == -1 // bug 1066496
&& code.indexOf("Math.round") == -1 // bug 1073910
&& code.indexOf("Math.fround") == -1 // bug 1073910, bug 1073928
&& code.indexOf("Math.imul") == -1 // bug 1073910
&& code.indexOf("Math.atan2") == -1 // bug 1073928
&& code.indexOf("Math.hypot") == -1 // bug 1073928
&& !( codeL.match(/\/.*[\u0000\u0080-\uffff]/)) // doesn't stay valid utf-8 after going through python (?)
};
}
function whatToTestSpidermonkeyMozilla31(code)
{
/* jshint laxcomma: true */
// regexps can't match across lines, so replace whitespace with spaces.
var codeL = code.replace(/\s/g, " ");
return {
allowParse: true,
allowExec: unlikelyToHang(code)
&& (jsshell || code.indexOf("nogeckoex") == -1)
,
allowIter: true,
// Ideally we'd detect whether the shell was compiled with --enable-more-deterministic
expectConsistentOutput: true
&& (gcIsQuiet || code.indexOf("gc") == -1)
&& code.indexOf("Date") == -1 // time marches on
&& code.indexOf("random") == -1
&& code.indexOf("dumpObject") == -1 // shows heap addresses
&& code.indexOf("oomAfterAllocations") == -1
&& code.indexOf("reducePar") == -1 // only deterministic for associative elemental-reducers
&& code.indexOf("scanPar") == -1 // only deterministic for associative elemental-reducers
&& code.indexOf("scatterPar") == -1 // only deterministic for associative conflict-resolvers
,
expectConsistentOutputAcrossIter: true
&& code.indexOf("options") == -1 // options() is per-cx, and the js shell doesn't create a new cx for each sandbox/compartment
,
expectConsistentOutputAcrossJITs: true
&& code.indexOf("/*NODIFF*/") == -1 // Ignore diff testing on these labels
&& code.indexOf("'strict") == -1 // see bug 743425
&& code.indexOf("Object.seal") == -1 // bug 937922 (31 branch)
&& code.indexOf("buildPar") == -1 // bug 998262 (31 branch)
&& code.indexOf("with") == -1 // bug 998580 (31 branch)
&& code.indexOf("use asm") == -1 // bug 999790 (31 branch)
&& code.indexOf("Math.round") == -1 // bug 1000606 (31 branch)
&& code.indexOf("Math.fround") == -1 // bug 1000606 (31 branch)
&& code.indexOf("Math.asinh") == -1 // bug 1007213 (31 branch)
&& code.indexOf("Math.ceil") == -1 // bug 1000605, bug 1015656 (31 branch)
&& code.indexOf("arguments") == -1 // bug 1024444 (31 branch)
&& code.indexOf("use strict") == -1 // bug 1008818, bug 1025587 (31 branch)
&& code.indexOf("length") == -1 // bug 998059, bug 1027846 (31 branch)
&& code.indexOf("enumerable") == -1 // bug 1054545 (31 branch)
&& code.indexOf("buildPar") == -1 // bug 1066496 (31 branch)
&& !( codeL.match(/\/.*[\u0000\u0080-\uffff]/)) // doesn't stay valid utf-8 after going through python (?)
};
}
function whatToTestJavaScriptCore(code)
{
return {
allowParse: true,
allowExec: unlikelyToHang(code),
allowIter: false, // JavaScriptCore does not support |yield| and |Iterator|
expectConsistentOutput: false,
expectConsistentOutputAcrossIter: false,
expectConsistentOutputAcrossJITs: false
};
}
function whatToTestGeneric(code)
{
return {
allowParse: true,
allowExec: unlikelyToHang(code),
allowIter: (typeof Iterator == "function"),
expectConsistentOutput: false,
expectConsistentOutputAcrossIter: false,
expectConsistentOutputAcrossJITs: false
};
}
var whatToTest;
if (engine == ENGINE_SPIDERMONKEY_TRUNK)
whatToTest = whatToTestSpidermonkeyTrunk;
else if (engine == ENGINE_SPIDERMONKEY_MOZILLA24)
whatToTest = whatToTestSpidermonkeyMozilla24;
else if (engine == ENGINE_JAVASCRIPTCORE)
whatToTest = whatToTestJavaScriptCore;
else
whatToTest = whatToTestGeneric;
function unlikelyToHang(code)
{
var codeL = code.replace(/\s/g, " ");
// Things that are likely to hang in all JavaScript engines
return true
&& code.indexOf("infloop") == -1
&& !( codeL.match( /const.*for/ )) // can be an infinite loop: function() { const x = 1; for each(x in ({a1:1})) dumpln(3); }
&& !( codeL.match( /for.*const/ )) // can be an infinite loop: for each(x in ...); const x;
&& !( codeL.match( /for.*in.*uneval/ )) // can be slow to loop through the huge string uneval(this), for example
&& !( codeL.match( /for.*for.*for/ )) // nested for loops (including for..in, array comprehensions, etc) can take a while
&& !( codeL.match( /for.*for.*gc/ ))
;
}
|
JavaScript
| 0 |
@@ -2023,32 +2023,99 @@
// bug 1073928%0A
+ && code.indexOf(%22prototype%22) == -1 // bug 1081850%0A
&& !( cod
|
164ced5c70d40f2688ebb0759a9446d349eac953
|
Add quotes around undefined when checking for type
|
js/maze_generators/random-dfs.js
|
js/maze_generators/random-dfs.js
|
'use strict'
var _ = require('underscore')
/**
* Given a maze, position to start at, and a visited set, apply a randomized
* depth-first-search algorithm to the maze.
*
* @param {type} maze Maze to apply the random dfs algorithm to
* @param {type} position Current position to consider
* @param {type} visited Object containing visited maze cells
*/
var randomDfs = function (maze, position, visited) {
visited = typeof visited !== undefined ? visited : {}
visited[getPositionString(position)] = true
var positions = _.shuffle(maze.getAdjacentPositionsTo(position))
positions.forEach(function (nextPosition) {
if (!visited[getPositionString(nextPosition)]) {
maze.setWallBetween(position, nextPosition, false)
randomDfs(maze, nextPosition, visited)
}
})
}
/**
* Given a position, return a string representing it.
*
* @param {Position} position description
* @return {String} A string representing position
*/
var getPositionString = function (position) {
return position.x.toString() + ',' + position.y.toString()
}
module.exports = randomDfs
|
JavaScript
| 0 |
@@ -435,16 +435,17 @@
ted !==
+'
undefine
@@ -445,16 +445,17 @@
ndefined
+'
? visit
|
d2982902669ecfa0ec4603886d09b2f05c0338c0
|
Add new line after a .gitignore template
|
lib/generate.js
|
lib/generate.js
|
import fs from 'fs'
import { join } from 'path'
const templatesDir = join(__dirname, '..', 'templates')
const readFile = async (file) => {
return new Promise((resolve, reject) => {
fs.readFile(file, 'utf8', (err, text) => {
if (err) {
reject(err)
} else {
resolve(text)
}
})
})
}
/**
* Asynchronously iterate over a list of template pairs to generate a string
* containing all corrspondent .gitignore files contents
*
* @example
* generate([{name: 'Node.js', template: 'Node'}])
* .then(gi => { console.log(gi) })
* // outputs the following string
* // ### Node.js ###
* // # Logs
* // logs
* // .log
* // ...
*
* @param {Array} tempaltesList of {name, template} pairs of target templates
* @return {Promise} with the full .gitignore string
*/
const generate = async (tempaltesList) => {
let gitignore = ''
for (let tmpl of tempaltesList) {
const { name, template, global } = tmpl
// calculate template file path (.gitignore file)
const globalDir = global ? 'Global' : ''
const templateFile = join(templatesDir, globalDir, `${template}.gitignore`)
// Read .gitignore file
let text = await readFile(templateFile)
// Add a header
gitignore += `### ${name} ###\n\n`
gitignore += text
}
return gitignore
}
export default generate
|
JavaScript
| 0 |
@@ -1296,20 +1296,27 @@
nore +=
+%60$%7B
text
+%7D%5Cn%60
%0A %7D%0A%0A
|
4f36f3676d13b10d645aedf2658491b00423fd18
|
Fix evaluation of post content by m.trust() (#24)
|
js/src/forum/addStickyExcerpt.js
|
js/src/forum/addStickyExcerpt.js
|
import { extend } from 'flarum/extend';
import DiscussionListState from 'flarum/states/DiscussionListState';
import DiscussionListItem from 'flarum/components/DiscussionListItem';
import DiscussionPage from 'flarum/components/DiscussionPage';
import IndexPage from 'flarum/components/IndexPage';
import { truncate } from 'flarum/utils/string';
export default function addStickyControl() {
extend(DiscussionListState.prototype, 'requestParams', function(params) {
if (app.current.matches(IndexPage) || app.current.matches(DiscussionPage)) {
params.include.push('firstPost');
}
});
extend(DiscussionListItem.prototype, 'infoItems', function(items) {
const discussion = this.attrs.discussion;
if (discussion.isSticky() && !this.attrs.params.q && !discussion.lastReadPostNumber()) {
const firstPost = discussion.firstPost();
if (firstPost) {
const excerpt = truncate(firstPost.contentPlain(), 175);
items.add('excerpt', m.trust(excerpt), -100);
}
}
});
}
|
JavaScript
| 0.000005 |
@@ -937,24 +937,96 @@
n(), 175);%0A%0A
+ // Wrapping in %3Cdiv%3E because ItemList entries need to be vnodes%0A
item
@@ -1046,24 +1046,28 @@
t',
-m.trust(excerpt)
+%3Cdiv%3E%7Bexcerpt%7D%3C/div%3E
, -1
|
7bd26a1ae47b252e7483a39da3c2a2df4760c935
|
fix accidentally deleted line
|
js/utils/validateMediumEditor.js
|
js/utils/validateMediumEditor.js
|
function checkVal($field) {
var fVal = $($field.val()).text().trim();
$field.val('');
}
if (!$field[0].checkValidity()) {
$field.parent().addClass('invalid');
} else {
$field.parent().removeClass('invalid');
}
}
module.exports = {
checkVal: checkVal
};
|
JavaScript
| 0 |
@@ -65,16 +65,85 @@
trim();%0A
+ if (!fVal.length %7C%7C fVal == %22%3Cp%3E %3C/p%3E%22 %7C%7C fVal == %22 %22) %7B%0A
$fie
|
579a91ebe43e88ebd9d63b6cb11dd776972e7e29
|
fix path error
|
lib/handlers.js
|
lib/handlers.js
|
var math = require('mathjs');
var childProcess = require('child_process');
var Attachment = require('./attachment');
var formatter = require('./formatter');
var freshStart = true;
var mathjsScope = math.parser().scope;
var mathjsChildOptions = {
stdio: 'ipc',
//timeout: 5 * 1000
};
module.exports = {
evalGet: function(req, resp) {
resp.send('/eval only currently accept POST requests.');
},
evalPost: function(req, resp) {
var result = {};
var attachments = [], att; // att is for temporarily storing an attachment
var post = req.body;
var expr = post.text;
var trigger = post.trigger_word;
// do not respond to bot-users (including itself)
if(post.user_name == 'slackbot'){
resp.end();
return;
}
if (!expr) {
result.ok = false;
result.text = 'No message sent.';
resp.json(result);
return;
}
if (trigger) {
//truncate trigger word
expr = expr.slice(trigger.length);
}
var dispName = '@' + post.user_name;
result.text = '\00';
if (freshStart) {
att = new Attachment('Welcome to MathJS v' + math.version + '! \n Configurations:');
att.pretext = 'MathJS server had restarted. (last commit: ' + '2015/4/27 409d9e0' + ')';
att.fields = [];
var config = math.config();
for (var x in config) {
att.fields.push({
title: x,
value: config[x],
short: true
});
}
attachments.push(att);
freshStart = false;
}
result.ok = true;
// var child = childProcess.spawnSync('node', ['./children/math.js'], mathjsChildOptions);
var child = childProcess.fork('./children/math.js', mathjsChildOptions);
child.on('exit', function(code, sig) {
if (sig) {
console.log('timeout, killed');
att = new Attachment('timeout, killed');
att.color = 'warning';
attachments.push(att);
}
sendAttachments();
});
var timer = setTimeout(function() {
child.kill();
}, 5 * 1000);
child.send({
type: 'eval',
scope: mathjsScope,
expr: expr
});
child.on('message', function(message) {
var status = message.type;
if (status == 'success') {
successHandler(message);
sendAttachments();
} else if (status == 'error') {
errorHandler(message);
sendAttachments();
}
});
function successHandler(message) {
var answer = message.answer;
var outGuide = formatter(answer);
var outRaw = outGuide.output;
var output = outRaw;
if (outGuide.newl)
output = '\n' + output;
else
output = '*' + output + '*';
if (answer == null) {
att = new Attachment(dispName + ': ' + output);
att.fallback = dispName + ': ' + outRaw;
} else {
att = new Attachment(dispName + ': ans = ' + output);
att.fallback = dispName + ': ans = ' + outRaw;
mathParser.set('ans', answer);
}
att.color = 'good';
attachments.push(att);
}
function errorHandler(message) {
result.ok = false;
var err = message.err;
if (err.message.indexOf('(char 1)') >= 0){
// fail silently
result.text = '';
} else {
att = new Attachment();
att.color = 'danger';
att.fallback = dispName + ' ' + err.toString();
att.text = dispName + ' *' + err.name + '*: ' + err.message;
attachments.push(att);
}
result.error = {
type: err.name,
message: err.message
};
}
function sendAttachments() {
if (attachments.length)
result.attachments = attachments;
return resp.json(result);
}
// try {
// result.ok = true;
// var answer = mathParser.eval(expr);
// var outGuide = formatter(answer);
// var outRaw = outGuide.output;
// var output = outRaw;
// if (outGuide.newl)
// output = '\n' + output;
// else
// output = '*' + output + '*';
// if (answer == null) {
// att = new Attachment(dispName + ': ' + output);
// att.fallback = dispName + ': ' + outRaw;
// } else {
// att = new Attachment(dispName + ': ans = ' + output);
// att.fallback = dispName + ': ans = ' + outRaw;
// mathParser.set('ans', answer);
// }
// att.color = 'good';
// attachments.push(att);
// } catch (err) {
// result.ok = false;
// if (err.message.indexOf('(char 1)') >= 0){
// // fail silently
// result.text = '';
// } else {
// att = new Attachment();
// att.color = 'danger';
// att.fallback = dispName + ' ' + err.toString();
// att.text = dispName + ' *' + err.name + '*: ' + err.message;
// attachments.push(att);
// }
// result.error = {
// type: err.name,
// message: err.message
// };
// }
// if (attachments.length)
// result.attachments = attachments;
// resp.json(result);
},
scopeReadGet: function(req, resp) {
resp.json(mathParser.scope);
}
};
|
JavaScript
| 0.000003 |
@@ -1691,16 +1691,20 @@
fork('./
+lib/
children
|
83021cf0acadd9ca0349310cf3a9b517d2e195d7
|
Fix #195: Support port in connect command
|
src/plugins/inputs/connect.js
|
src/plugins/inputs/connect.js
|
exports.commands = ["connect", "server"];
exports.input = function(network, chan, cmd, args) {
if (args.length !== 0) {
var client = this;
client.connect({
host: args[0]
});
}
return true;
};
|
JavaScript
| 0 |
@@ -110,9 +110,9 @@
gth
-!
+=
== 0
@@ -121,35 +121,125 @@
%7B%0A%09%09
-var client = this;%0A%09%09client
+return;%0A%09%7D%0A%0A%09var port = args%5B1%5D %7C%7C %22%22;%0A%09var tls = port%5B0%5D === %22+%22;%0A%0A%09if (tls) %7B%0A%09%09port = port.substring(1);%0A%09%7D%0A%0A%09this
.con
@@ -247,17 +247,16 @@
ect(%7B%0A%09%09
-%09
host: ar
@@ -264,17 +264,40 @@
s%5B0%5D
+,
%0A%09%09
-%7D);
+port: port,%0A%09%09tls: tls,
%0A%09%7D
+);
%0A%0A%09r
|
5272a03f798daa50687805b52e6bd8acdd8638dd
|
refactor of the week
|
app/javascripts/navigation.js
|
app/javascripts/navigation.js
|
// UI for the Navigation Bar in the sidebar
NavigationBar = {
detectSelectedSection: function() {
// Direct match
var link = $$('.nav_links a').select(function(e) {
return e.getAttribute('href') == window.location.pathname
}).last()
if (link) link.up('.el').addClassName('selected')
// Close enough
if (link == undefined) {
var link = $$('.nav_links a').sortBy(function(e) {
return e.getAttribute('href').length
}).select(function(e) {
return (window.location.pathname.search(e.getAttribute('href')) > -1 && e.getAttribute('href') != '/')
}).last()
if (link) link.up('.el').addClassName('children-selected')
}
if(link) return link.up('.el')
},
showContainers: function(current) {
var container = current.up('.contained')
if (container) {
container.show().previous('.el').addClassName('expanded')
while (container = container.up('.contained')) {
container.show().previous('.el').addClassName('expanded')
}
}
},
scroll: function() {
var sidebar = $('column')
if (document.viewport.getHeight() > sidebar.getHeight() && document.viewport.getScrollOffsets()[1] >= NavigationBar.initial_offest) {
sidebar.style.position = 'fixed'
sidebar.style.top = 0
}
else
{
sidebar.style.position = 'absolute'
sidebar.style.top = 'auto'
}
},
scrollToTopIfNeeded: function() {
var sidebar = $('column')
if (document.viewport.getHeight() < sidebar.getHeight()) {
NavigationBar.scroll()
Effect.ScrollTo('container', { duration: '0.4' })
}
},
toggleElement: function(el, effect) {
var contained = el.next()
// if next element is an expanded area..
if (contained && contained.hasClassName('contained')) {
if (el.hasClassName('expanded')) {
// contract it if it's open
el.removeClassName('expanded')
contained.setStyle({height: ''})
contained.blindUp({ duration: 0.2 })
} else {
// contract others if open
var visible_containers = el.up().select('.contained').select( function(e) { return e.visible() })
effect ? visible_containers.invoke("blindUp", { duration: 0.2 }) : visible_containers.invoke('hide')
el.up().select('.el').invoke('removeClassName', 'expanded')
// expand the selected one
el.addClassName('expanded')
contained.setStyle({height: ''})
effect ? contained.blindDown({ duration: 0.2 }) : contained.show()
setTimeout(function() { NavigationBar.scrollToTopIfNeeded() }, 100)
}
// Stop the event and don't follow the link
return true
}
// Stop the event if it's selected (don't follow the link)
return el.hasClassName('selected')
},
selectElement: function(el) {
$$('.nav_links .el.selected').invoke('removeClassName', 'selected').invoke('removeClassName', 'children-selected')
el.addClassName('selected')
}
}
document.on("dom:loaded", function() {
$$('.nav_links .contained').invoke('hide')
NavigationBar.initial_offest = window.$('column').viewportOffset().top
// Select and expand the current element
var current = NavigationBar.detectSelectedSection()
if (current) {
// If it's hidden in the "Show more" options
if(!current.visible()) {
$('show_more').insert({before: current})
current.show()
}
NavigationBar.toggleElement(current)
NavigationBar.showContainers(current)
}
// If we're on All Projects, then expand the recent projects list
var elements = $$('.nav_links .el')
if (elements[0] && elements[0].hasClassName('selected')) {
NavigationBar.toggleElement(elements[1])
}
})
document.on('click', '.nav_links .el', function(e,el) {
if (e.isMiddleClick()) return
var clicked = Event.element(e)
if (clicked.id == 'open_my_tasks') {
window.location = clicked.readAttribute("href")
e.stop()
} else {
NavigationBar.toggleElement(el, true) && e.stop()
}
})
document.on('click', '.nav_links .el#show_all_projects', function(e,el) {
if (e.isMiddleClick()) return
e.stop()
Projects.showAllProjects()
})
document.on('click', '.nav_links .el .show_more', function(e,el) {
e.stop()
$$('.el#show_more').invoke('hide')
$$('.el.extra').invoke('show')
})
document.on('click', '.nav_links .el .show_less', function(e,el) {
e.stop()
$$('.el#show_more').invoke('show')
$$('.el.extra').invoke('hide')
})
window.onscroll = function() { NavigationBar.scroll() }
|
JavaScript
| 0.000207 |
@@ -3884,21 +3884,8 @@
f%22)%0A
- e.stop()%0A
%7D
@@ -3932,19 +3932,22 @@
l, true)
- &&
+%0A %7D%0A
e.stop(
@@ -3948,20 +3948,16 @@
.stop()%0A
- %7D%0A
%7D)%0A%0Adocu
|
475780e211589b4ca39eb8f3dc1f0635b01af8db
|
remove useless casts (for ++ coverage)
|
apis/job.js
|
apis/job.js
|
import validate from 'validate.js';
import { endpoints } from './config';
export default {
createJob(job) {
if (typeof job !== 'object') {
throw new Error('Missing job!');
}
if (typeof job.recordingId === 'number') {
job.recordingId = job.recordingId + '';
}
const validation = {
tasks: {
presence: true
}
};
const validationErrors = validate(job, validation);
if (validationErrors) {
throw new Error('Invalid job object!');
}
return {
method: 'post',
path: endpoints.job,
data: job
};
},
getJobs({ limit, offset } = {}) {
return {
method: 'get',
path: endpoints.job,
query: { limit, offset }
};
},
getJobsForRecording(options) {
if (typeof options === 'string') {
options = {
recordingId: options
};
} else if (typeof options !== 'object') {
throw new Error('Missing options!');
}
if (typeof options.recordingId === 'number') {
options.recordingId = options.recordingId + '';
}
if (typeof options.recordingId !== 'string' || options.recordingId === '') {
throw new Error('Missing options.recordingId!');
}
return {
method: 'get',
path: `${endpoints.job}/recording/${options.recordingId}`,
query: { offset: options.offset, limit: options.limit }
};
},
getJob(jobId) {
if (typeof jobId !== 'string' || jobId === '') {
throw new Error('Missing jobId!');
}
return {
method: 'get',
path: `${endpoints.job}/${jobId}`
};
},
restartJob(jobId) {
if (typeof jobId !== 'string' || jobId === '') {
throw new Error('Missing jobId!');
}
return {
method: 'put',
path: `${endpoints.job}/${jobId}/restart`
};
},
retryJob(jobId) {
if (typeof jobId !== 'string' || jobId === '') {
throw new Error('Missing jobId!');
}
return {
method: 'put',
path: `${endpoints.job}/${jobId}/retry`
};
},
cancelJob(jobId) {
if (typeof jobId !== 'string' || jobId === '') {
throw new Error('Missing jobId!');
}
return {
method: 'delete',
path: `${endpoints.job}/${jobId}`
};
}
};
|
JavaScript
| 0 |
@@ -179,100 +179,8 @@
%0A%09%09%7D
-%0A%09%09if (typeof job.recordingId === 'number') %7B%0A%09%09%09job.recordingId = job.recordingId + '';%0A%09%09%7D
%0A%0A%09%09
@@ -779,111 +779,8 @@
%09%09%7D%0A
-%09%09if (typeof options.recordingId === 'number') %7B%0A%09%09%09options.recordingId = options.recordingId + '';%0A%09%09%7D
%0A%09%09i
|
ab46bbf47f1b41a45c186a362ed43ce66d8b17a2
|
Fix `purs bundle` output
|
src/Database/PostgreSQL/Value.js
|
src/Database/PostgreSQL/Value.js
|
'use strict';
// pg does strange thing converting DATE
// value to js Date, so we have
// to prevent this craziness
var pg = require('pg');
var DATE_OID = 1082;
pg.types.setTypeParser(DATE_OID, function(dateString) { return dateString; });
exports['null'] = null;
exports.instantToString = function(i) {
return new Date(i).toUTCString();
};
exports.instantFromString = function(Left) {
return function(Right) {
return function(s) {
try {
return Right(Date.parse(s));
} catch(e) {
return Left("Date string parsing failed: \"" + s + "\", with: " + e);
}
};
};
};
exports.unsafeIsBuffer = function(x) {
return x instanceof Buffer;
};
|
JavaScript
| 0 |
@@ -138,28 +138,8 @@
');%0A
-var DATE_OID = 1082;
%0Apg.
@@ -162,16 +162,24 @@
ser(
+1082 /*
DATE_OID
, fu
@@ -174,16 +174,19 @@
DATE_OID
+ */
, functi
|
8f1b14dacb1a3cbfda31ada80dc9a7222bf05d84
|
throw error if result from lockfile server has a message
|
lib/lockfile.js
|
lib/lockfile.js
|
const request = require('request-promise')
const promiseRetry = require('promise-retry')
const Log = require('gk-log')
const dbs = require('../lib/dbs')
const errorCodes = require('../lib/network-error-codes')
const env = require('./env')
module.exports = {
getNewLockfile
}
// # getNewLockfile
// find next server
// send data to server
// increase in/flight job count for server
// if network error
// -> try next server
// else
// -> return result
// decrease in-flight jon count for server
// # find next server
// get doc from couchdb: config
// sort list by least jobs in flight
// return least busy server
let jobCountByServer = {}
async function findNextServer () {
const { config } = await dbs()
let servers
try {
// { servers: [....] }
const doc = await config.get('exec-servers')
servers = doc.servers
} catch (e) {
servers = [env.EXEC_SERVER_URL]
}
const sortedServers = servers.sort((a, b) => {
const jobsA = jobCountByServer[a] || 0
const jobsB = jobCountByServer[b] || 0
return jobsA < jobsB ? -1 : 1
})
return sortedServers[0]
}
async function getNewLockfile ({ packageJson, lock, type, repositoryTokens }) {
const logs = dbs.getLogsDb()
const log = Log({
logsDb: logs,
accountId: 'lockfile',
repoSlug: null,
context: 'lockfile'
})
const nextServer = await findNextServer()
jobCountByServer[nextServer] = jobCountByServer[nextServer] ? jobCountByServer[nextServer] + 1 : 1
return promiseRetry((retry, number) => {
return request({
uri: nextServer,
method: 'POST',
json: true,
body: {
type,
packageJson,
lock,
repositoryTokens
}
})
.then(result => {
jobCountByServer[nextServer]--
if (result instanceof Error) {
// it is an error!
const error = result
throw error
} else {
return result
}
})
.catch(error => {
if (number >= 3) {
log.error(`could not get lockfile from ${nextServer}, attempt #${number}: giving up`)
jobCountByServer[nextServer]--
throw error
}
const type = error.statusCode ? error.statusCode : error.error.code
if (errorCodes.includes(type)) {
log.warn(`could not get lockfile, attempt #${number}: retrying`)
jobCountByServer[nextServer]--
retry(error)
} else {
log.warn(`could not get lockfile, attempt #${number}: stopping because of ${error}`)
jobCountByServer[nextServer]--
throw error
}
})
}, {
retries: 3,
minTimeout: 3000
})
}
|
JavaScript
| 0.000001 |
@@ -1760,16 +1760,17 @@
if
+(
(result
@@ -1791,38 +1791,129 @@
or)
-%7B%0A // it is an error!
+%7C%7C result.message) %7B%0A // result is either %60error%60, %60%7Bok: false%7D%60, %60%7Bok: false, error%7D%60 or %60%7Bok: true, contents%7D%60
%0A
|
3976e1d6f334ca246bf2bf224a13a6baa4ae0b34
|
optimise log file usage
|
app/hero.js
|
app/hero.js
|
var fs = require('fs');
var Practitioner = require(__dirname + '/practitioner');
var Location = require(__dirname + '/location');
var Organisation = require(__dirname + '/organisation');
var runDir = __dirname + '/../run';
var cacheFile = runDir + '/contacts.json';
var Config = require(__dirname + '/config');
var config = new Config();
function writeToCache(contacts) {
fs.writeFileSync(cacheFile, JSON.stringify(contacts));
}
function readFromCache() {
var rawJson = fs.readFileSync(cacheFile);
return JSON.parse(rawJson);
}
function postContactToRapidPro(rapidProContactEndPoint, contact) {
var request = require('request');
function logFailure(body) {
process.stdout.write('E');
fs.appendFileSync(runDir + '/push.log', '============\n');
fs.appendFileSync(runDir + '/push.log', '--> pushing data\n');
fs.appendFileSync(runDir + '/push.log', JSON.stringify(contact) + '\n');
fs.appendFileSync(runDir + '/push.log', '<-- getting response\n');
fs.appendFileSync(runDir + '/push.log', body + '\n');
}
request.post({
headers: {
'content-type': 'application/json',
Authorization: 'Token ' + config.rapidProAuthorisationToken
},
url: rapidProContactEndPoint,
body: JSON.stringify(contact)
}, function (error, response, body) {
try {
var responseContact = JSON.parse(body);
if(responseContact.phone) {
process.stdout.write('.');
} else {
logFailure(body);
}
} catch (error) {
logFailure(body);
}
});
}
var Hero = function () {
this.pull = function () {
var practitionerEndPoint = config.practitionerEndPoint;
var locationEndPoint = config.locationEndPoint;
var organisationEndPoint = config.organisationEndPoint;
return Practitioner.loadAll(practitionerEndPoint).then(function (allPractitioners) {
return Location.loadAll(locationEndPoint).then(function (allLocations) {
return Organisation.loadAll(organisationEndPoint).then(function (allOrganisations) {
var mergedPractitioners = Practitioner.merge(allPractitioners, allLocations, allOrganisations);
console.log(mergedPractitioners.length.toString() + ' practitioners downloaded from HWR');
var allContacts = Practitioner.formatForRapidPro(mergedPractitioners);
writeToCache(allContacts);
console.log(allContacts.length.toString() + ' contacts put into cache');
});
});
});
};
this.push = function () {
var rapidProContactEndPoint = config.rapidProContactEndPoint;
var allContacts = readFromCache();
allContacts.forEach(function (contact) {
postContactToRapidPro(rapidProContactEndPoint, contact);
});
};
};
module.exports = Hero;
|
JavaScript
| 0.000001 |
@@ -759,16 +759,32 @@
sh.log',
+%0A
'======
@@ -792,18 +792,16 @@
=====%5Cn'
-);
%0A
@@ -805,47 +805,17 @@
-fs.appendFileSync(runDir + '/push.log',
+ +
'--
@@ -831,18 +831,16 @@
data%5Cn'
-);
%0A
@@ -844,47 +844,17 @@
-fs.appendFileSync(runDir + '/push.log',
+ +
JSO
@@ -876,26 +876,24 @@
tact) + '%5Cn'
-);
%0A fs.
@@ -893,47 +893,17 @@
-fs.appendFileSync(runDir + '/push.log',
+ +
'%3C-
@@ -923,18 +923,16 @@
ponse%5Cn'
-);
%0A
@@ -936,47 +936,17 @@
-fs.appendFileSync(runDir + '/push.log',
+ +
bod
@@ -1330,16 +1330,17 @@
if
+
(respons
|
f3c5efaf06478dee60c44807d5d91ed31c4969a5
|
Invert the color of the circles
|
app/main.js
|
app/main.js
|
var counter;
function setup() {
var canvas = createCanvas(400, 400);
canvas.parent('play');
counter = new Counter();
counter.new();
}
function draw() {
background(233, 0, 0);
counter.draw();
}
function keyTyped() {
if (key === ' ') {
counter.new();
}
if (keyCode == ENTER) {
if (counter.isValid()) {
var div = select('#solution');
div.html("Right");
counter.new();
}
else{
var div = select('#solution');
div.html("Wrong");
}
}
var numbers = ["1","2","3","4","5","6","7","8","9","0"];
if (numbers.indexOf(key) > - 1) {
counter.guess(key);
var div = select('#solution');
div.html(key);
}
}
function touchStarted() {
if (touches.length > 0) {
var touch = touches[0];
if (
touch.x >= 0 && touch.x < 400 &&
touch.y >= 0 && touch.y < 400
)
{
counter.new();
}
}
}
function Counter () {
this.objects = [];
this.number = 0;
this.new = function () {
this.objects = [];
this.number = floor(random(1, 10));
while(this.objects.length < this.number) {
var newObject = createVector(random(45,355), random(45,355));
if (this.objects.every(function(item){
return p5.Vector.sub(item, newObject).mag() > 85;
}))
{
this.objects.push(newObject);
}
}
var div = select('#solution');
div.html("Count the circles and press ENTER!");
}
this.draw = function() {
for(var i = 0; i < this.objects.length; i++) {
var object = this.objects[i];
ellipse(object.x, object.y, 80);
}
}
this.guess = function(guess) {
this.lastGuess = guess;
}
this.isValid = function() {
return this.lastGuess == this.number;
}
}
|
JavaScript
| 0.999999 |
@@ -183,16 +183,20 @@
nd(2
-33, 0, 0
+55, 255, 255
);%0A
@@ -1761,16 +1761,43 @@
cts%5Bi%5D;%0A
+ fill(255,0,0);%0A
|
ac99d53daf057cd68775426fc616125e5b133852
|
Add date to response body
|
app/main.js
|
app/main.js
|
var os = require( "os" );
var throng = require( "throng" );
var connections = require( "./shared/connections" );
var utils = require( "./shared/utils" );
var logger = connections.logger( [ "Pi-System-RPC-Service" ] );
var run = function () {
logger.log( "Starting Pi-System-RPC-Service" );
var broker = connections.jackrabbit();
var handleMessage = function ( message, ack ) {
utils.readCPUTemperature( function ( err, data ) {
if ( err ) {
logger.log( "Error with: 'utils.readCPUTemperature'" );
process.exit();
}
ack( JSON.stringify( {
cpu_temp_c: data.celsius,
cpu_temp_f: data.fahrenheit
} ) );
} );
};
var serve = function () {
logger.log( "Broker ready" );
broker.handle( "system.get", handleMessage );
};
var create = function () {
logger.log( "Broker connected" );
broker.create( "system.get", { prefetch: 5 }, serve );
};
process.once( "uncaughtException", function ( err ) {
logger.log( "Stopping Pi-System-RPC-Service" );
logger.log( err );
process.exit();
} );
broker.once( "connected", create );
};
throng( run, {
workers: os.cpus().length,
lifetime: Infinity
} );
|
JavaScript
| 0.000305 |
@@ -625,16 +625,50 @@
gify( %7B%0A
+ date: new Date(),%0A
|
3d0a458b8e7c9bf6cb91f33cd55077fde9b9e6e4
|
Remove debug logging
|
app/main.js
|
app/main.js
|
var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require('menu');
var MenuItem = require('menu-item');
var Shell = require('shell');
var ConfigStore = require('configstore');
console.log(app.getLocale());
var mainWindow = null;
const config = new ConfigStore('IRCCloud', {
'width': 1024,
'height': 768
});
function openMainWindow() {
mainWindow = new BrowserWindow({'width': config.get('width'),
'height': config.get('height'),
'allowDisplayingInsecureContent': true,
'preload': __dirname + '/preload.js',
'title': 'IRCCloud'});
mainWindow.loadURL('https://www.irccloud.com');
mainWindow.on('closed', function() {
mainWindow = null;
});
mainWindow.on('resize', function() {
size = mainWindow.getSize();
config.set({'width': size[0],
'height': size[1]});
});
mainWindow.on('page-title-updated', function(event) {
var title = mainWindow.getTitle();
if (title) {
var unread = "";
var matches = title.match(/^\((\d+)\)/);
if (matches) {
unread = matches[1];
}
app.dock.setBadge(unread);
}
});
mainWindow.webContents.on('new-window', function(event, url, frameName, disposition) {
event.preventDefault();
Shell.openExternal(url);
});
}
app.on('ready', openMainWindow);
app.on('activate-with-no-open-windows', openMainWindow);
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
app.once('ready', function() {
var template = [{
label: 'IRCCloud',
submenu: [
{
label: 'About IRCCloud',
click: function() {
var win = new BrowserWindow({ width: 915, height: 600, show: false });
win.on('closed', function() {
win = null;
});
win.webContents.on('will-navigate', function (e, url) {
e.preventDefault();
Shell.openExternal(url);
});
win.loadURL('https://www.irccloud.com/about');
win.show();
}
},
{
type: 'separator'
},
{
label: 'Services',
submenu: []
},
{
type: 'separator'
},
{
label: 'Hide IRCCloud',
accelerator: 'Command+H',
selector: 'hide:'
},
{
label: 'Hide Others',
accelerator: 'Command+Shift+H',
selector: 'hideOtherApplications:'
},
{
label: 'Show All',
selector: 'unhideAllApplications:'
},
{
type: 'separator'
},
{
label: 'Quit',
accelerator: 'Command+Q',
click: function() { app.quit(); }
},
]
},
{
label: 'Edit',
submenu: [
{
label: 'Undo',
accelerator: 'Command+Z',
selector: 'undo:'
},
{
label: 'Redo',
accelerator: 'Shift+Command+Z',
selector: 'redo:'
},
{
type: 'separator'
},
{
label: 'Cut',
accelerator: 'Command+X',
selector: 'cut:'
},
{
label: 'Copy',
accelerator: 'Command+C',
selector: 'copy:'
},
{
label: 'Paste',
accelerator: 'Command+V',
selector: 'paste:'
},
{
label: 'Select All',
accelerator: 'Command+A',
selector: 'selectAll:'
},
]
},
{
label: 'View',
submenu: [
{
label: 'Reload',
accelerator: 'Command+R',
click: function() { BrowserWindow.getFocusedWindow().webContents.reloadIgnoringCache(); }
},
{
label: 'Toggle DevTools',
accelerator: 'Alt+Command+I',
click: function() { BrowserWindow.getFocusedWindow().toggleDevTools(); }
},
]
},
{
label: 'Window',
submenu: [
{
label: 'Minimize',
accelerator: 'Command+M',
selector: 'performMiniaturize:'
},
{
label: 'Close',
accelerator: 'Command+W',
selector: 'performClose:'
},
{
type: 'separator'
},
{
label: 'Bring All to Front',
selector: 'arrangeInFront:'
},
]
}];
menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
});
|
JavaScript
| 0.000002 |
@@ -208,39 +208,8 @@
);%0A%0A
-console.log(app.getLocale());%0A%0A
var
|
d806075e5c218d76365318cab552a6577eea7ba9
|
Use apply to forward call to registry.
|
app/main.js
|
app/main.js
|
exports = module.exports = function(registry) {
var api = {};
api.resolve = function(type, domain, rrtype, cb) {
registry.resolve(type, domain, rrtype, function(err, records) {
cb(err, records);
});
};
api.resolveSrv = function(type, domain, cb) {
registry.resolveSrv(type, domain, function(err, records) {
cb(err, records);
});
};
return api;
};
exports['@implements'] = 'http://i.bixbyjs.org/sd';
exports['@singleton'] = true;
exports['@require'] = [
'./registry',
];
|
JavaScript
| 0 |
@@ -137,85 +137,34 @@
olve
-(type, domain, rrtype, function(err, records) %7B%0A cb(err, records);%0A %7D
+.apply(registry, arguments
);%0A
@@ -245,77 +245,34 @@
eSrv
-(type, domain, function(err, records) %7B%0A cb(err, records);%0A %7D
+.apply(registry, arguments
);%0A
|
43ebec9f73ef25f96c25df9a368a4dbc5d3b45b6
|
Add another function
|
lib/nojQuery.js
|
lib/nojQuery.js
|
// jQUERY: $(window).width() / parseFloat($("body").css("font-size"));
function elementWidthAsEm(doc, id) {
let bb = null;
if(typeof id=='string') { bb= doc.getElementById(id); }
else { bb=doc.getElementsByTagName('body')[0]; }
let stl = window.getComputedStyle(bb,null);
return parseInt(stl.width) / parseInt(stl['fontSize'])
}
|
JavaScript
| 0.000476 |
@@ -331,10 +331,455 @@
e'%5D)%0A%7D%0A%0A
+// $(document).ready(function() %7B...%7D);%0A// ripped from https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery%0Afunction ready(callback) %7B%0A if (document.readyState!='loading') callback();%0A else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);%0A else document.attachEvent('onreadystatechange', function()%7B%0A if (document.readyState=='complete') callback();%0A %7D);%0A%7D
%0A%0A
|
a38248539b8c9a8f225c38b57e813f5a05e0bbd5
|
Remove test that checks for an application directory.
|
packages/truffle/test/init.js
|
packages/truffle/test/init.js
|
var assert = require("chai").assert;
var Init = require("../lib/init");
var fs = require("fs");
var path = require('path');
describe('init', function() {
var config;
before("Create a sandbox", function(done) {
this.timeout(5000);
Init.sandbox(function(err, result) {
if (err) return done(err);
config = result;
done();
});
});
it('copies example configuration', function(done) {
assert.isTrue(fs.existsSync(path.join(config.working_directory, "app")), "app directory not created successfully");
assert.isTrue(fs.existsSync(path.join(config.working_directory, "contracts")), "contracts directory not created successfully");
assert.isTrue(fs.existsSync(path.join(config.working_directory, "test")), "tests directory not created successfully");
done();
});
});
|
JavaScript
| 0 |
@@ -417,128 +417,8 @@
) %7B%0A
- assert.isTrue(fs.existsSync(path.join(config.working_directory, %22app%22)), %22app directory not created successfully%22);%0A
|
d6a0ef30d45615b2c2aceccf1bf70cca57a7ec02
|
comment added
|
WebContent/AngularFaces-4/mandelbrotController.js
|
WebContent/AngularFaces-4/mandelbrotController.js
|
needsServer=false;
function mandelbrotController($scope) {
$scope.showGlobeDemo=true;
$scope.$watch('resolution', function() {
needsServer=true;
if ($scope.resolution >= 512) {
if ($scope.quality > 2) {
$scope.quality = 2;
PrimeFaces.widgets.qualityWidget.selectValue(2);
PrimeFaces.widgets.qualitySliderWidget.setValue(2);
}
}
if ($scope.resolution >= 768) {
if ($scope.quality > 1) {
$scope.quality = 1;
PrimeFaces.widgets.qualityWidget.selectValue(1);
PrimeFaces.widgets.qualitySliderWidget.setValue(1);
}
}
});
$scope.$watch('showGlobeDemo', function() {
if ($scope.showGlobeDemo) {
activateGlobeDemo();
} else {
activatePlaneDemo();
}
});
$scope.$watch('xMin', function() {
needsServer=true;
});
$scope.$watch('xMax', function() {
needsServer=true;
});
$scope.$watch('yMin', function() {
needsServer=true;
});
$scope.$watch('yMax', function() {
needsServer=true;
});
$scope.init = function()
{
needsServer=false;
};
$scope.clientAction = function() {
if(needsServer)
document.getElementById('mandelbrot').innerHTML='calculating data on the server...';
else
initPlane($scope.aperture, $scope.resolution, $scope.quality);
};
}
function noServerActionRequired() {
return !needsServer;
};
var app = angular.module('mandelbrotApp', []);
var INTEGER_REGEXP = /^\-?\d*$/;
app.directive('integer', function() {
return {
require : 'ngModel',
link : function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (INTEGER_REGEXP.test(viewValue)) {
// it is valid
ctrl.$setValidity('integer', true);
return viewValue;
} else {
// it is invalid, return undefined (no model update)
ctrl.$setValidity('integer', false);
return undefined;
}
});
}
};
});
|
JavaScript
| 0 |
@@ -1,24 +1,101 @@
+// This variable keeps track of changes requiring server side recalculations%0A
needsServer=false;%0A%0Afunc
@@ -90,16 +90,17 @@
false;%0A%0A
+%0A
function
|
a63aea1ce3d7d112ab7df9e6918047f51ce40dfd
|
Make glob glob dotfiles
|
nin/backend/init.js
|
nin/backend/init.js
|
const chalk = require('chalk');
const child_process = require('child_process');
const fs = require('fs');
const generate = require('./generate/generate');
const glob = require('glob');
const path = require('path');
const projectSettings = require('./projectSettings');
function init(dirname) {
const projectPath = path.join(process.cwd(), dirname);
try {
fs.mkdirSync(projectPath);
} catch (e) {
console.error(chalk.red(e));
process.exit(1);
}
child_process.execSync(
`git init ${projectPath}`,
{stdio: 'inherit'});
glob(path.join(__dirname, 'blank-project/*'), function(error, files) {
// As globs don't expand to include dotfiles,
// we need to add the .gitignore manually
files.push(path.join(__dirname, 'blank-project/.gitignore'));
let numberOfRemainingFiles = files.length;
function end() {
if(--numberOfRemainingFiles == 0) {
generate.generate(projectPath, 'node', 'SpinningCube', {
connectedTo: {
render: 'root.screen'
}
});
projectSettings.init(projectPath);
console.log(chalk.green(`${projectPath} is now a nin project. Run`),
chalk.cyan('nin run'),
chalk.green('to get started!'));
}
}
files.map(function(file) {
child_process.execFile('cp', ['-r', file, path.join(projectPath, '/')],
function(error, stdout, stderr) {
if(error) {
console.log(chalk.red(stderr));
process.exit(1);
}
end();
}
);
});
});
}
module.exports = {init: init};
|
JavaScript
| 0.999976 |
@@ -593,16 +593,29 @@
ect/*'),
+ %7Bdot: true%7D,
functio
@@ -636,170 +636,8 @@
) %7B%0A
- // As globs don't expand to include dotfiles,%0A // we need to add the .gitignore manually%0A files.push(path.join(__dirname, 'blank-project/.gitignore'));%0A
@@ -1090,22 +1090,36 @@
en('
-to get started
+inside to serve your project
!'))
|
6e95ad0da56c60caa561d9f19002e0ccbd4121d0
|
fix limit restrictions of data export
|
app/search/query.prototype.js
|
app/search/query.prototype.js
|
'use strict';
angular.module('arachne.services')
/**
* represents a search query
* handles conversion between string representation for frontend URLs
* and flat object representation for backend requests
*
* @author: Sebastian Cuy
*/
.factory('Query', ['arachneSettings', function(arachneSettings) {
function Query() {
this.facets = [];
this.offset = 0;
this.limit = arachneSettings.limit || 50;
this.fl = arachneSettings.facetLimit || 20;
}
Query.prototype = {
// constructs a new query object from this query
// and adds or replaces a parameter, returns the new query
setParam: function(key,value) {
var newQuery = angular.copy(this);
newQuery[key] = value;
return newQuery;
},
// constructs a new query object from this query
// and removes a parameter, returns the new query
removeParam: function(key) {
var newQuery = angular.copy(this);
delete newQuery[key];
return newQuery;
},
// constructs a new query object from this query
// and removes parameters, returns the new query
removeParams: function(keys) {
var newQuery = angular.copy(this);
for (var i = 0; i < keys.length; i++) {
delete newQuery[keys[i]];
}
return newQuery;
},
// return a copy of param, always return an array, even
// if it has one or zero elements
getArrayParam: function(key) {
var value = this[key];
if (angular.isArray(value)) {
return angular.copy(value);
} else if (value !== undefined) {
return [angular.copy(value)];
} else {
return [];
}
},
// constructs a new query object from this query
// and adds an additional facet, returns the new query
addFacet: function(facetName,facetValue) {
var newQuery = angular.copy(this);
newQuery.facets.push({key:facetName, value:facetValue});
return newQuery;
},
// constructs a new query object from this query
// and removes a facet, returns the new query
removeFacet: function(facetName) {
var newQuery = angular.copy(this);
newQuery.facets = newQuery.facets.filter(function(facet) {
return facet.key !== facetName;
});
return newQuery;
},
// check if query has any particular facet filter attached
hasFacet: function(facetName) {
return this.facets.some(function(facet) {
return (facet.key == facetName);
});
},
// check if query has any facet filters attached
hasFacets: function() {
return this.facets.length > 0;
},
/**
* returns a COPY of this, extended by that
* @param that
* @returns {Query}
*/
extend: function(that) {
var extendedQuery = angular.copy(this);
for(var key in that) {
if (key === 'facets') {
extendedQuery.facets = extendedQuery.facets.concat(that.facets);
} else if (key === 'restrict') {
extendedQuery[key] = that[key]; //??
} else if (key === 'q') {
extendedQuery.q += ' ' + that.q;
} else if (key === 'catalogIds') {
extendedQuery[key] = that[key]; //??
} else if (['fl','limit','sort','desc','ghprec','bbox','sf','fo','facet','offset'].indexOf(key) !== -1) {
extendedQuery[key] = that[key];
}
}
return extendedQuery;
},
// returns a representation of this query as GET parameters
// If a paramter is given as an array, mutiple GET-Paramters with
// the same name are constructed (conforming to $location)
toString: function() {
var params = [];
for(var key in this) {
if (key == 'facets') {
for(var i in this.facets) {
var facetString = this.facets[i].key + ":\"" + this.facets[i].value + "\"";
params.push("fq=" + encodeURIComponent(facetString));
}
} else if (angular.isString(this[key]) || angular.isNumber(this[key])) {
if(!(key == 'limit') && (this[key] || key == 'resultIndex')) {
params.push(key + "=" + encodeURIComponent(this[key]));
}
} else if (angular.isArray(this[key])) {
for (var i = 0; i < this[key].length; i++) {
params.push(key + "=" + encodeURIComponent(this[key][i]));
}
}
}
if (params.length > 0) {
return "?" + params.join("&");
} else {
return "";
}
},
// return a representation of this query as a flat object
// that can be passed as a params object to $resource and $http
toFlatObject: function() {
var object = {};
var queries = [];
for(var key in this) {
if (key == 'facets') {
object.fq = [];
for(var i in this.facets) {
var facetString = this.facets[i].key + ":\"" + this.facets[i].value + "\"";
object.fq.push(facetString);
}
} else if (key == 'restrict') {
queries.push("_exists_:" + this[key]);
} else if (key == 'catalogIds') {
queries.push("catalogIds:" + this[key]);
} else if (key == 'q') {
queries.push(this[key]);
} else if (['fl','limit','sort','desc','ghprec','bbox','sf','fo','facet','offset'].indexOf(key) != -1) {
object[key] = this[key];
}
}
object.q = queries.join(' AND ');
return object;
}
};
// factory for building query from angular search object
Query.fromSearch = function(search) {
var newQuery = new Query();
for(var key in search) {
if (key == 'fq') {
if (angular.isString(search['fq'])) {
var facet = search['fq'].split(':');
if (facet.length == 2)
newQuery.facets.push({key:facet[0], value: facet[1].substr(1,facet[1].length-2)});
} else if (angular.isArray(search['fq'])) {
search['fq'].forEach(function(facetString) {
var facet = facetString.split(':');
newQuery.facets.push({key:facet[0], value: facet[1].substr(1,facet[1].length-2)});
})
}
} else {
newQuery[key] = search[key];
}
}
return newQuery;
};
return Query;
}]);
|
JavaScript
| 0 |
@@ -4391,29 +4391,8 @@
if
-(!(key == 'limit') &&
(th
@@ -4423,17 +4423,16 @@
tIndex')
-)
%7B%0A
|
5421e3143c9e97f2994a74bd6dc6e9bd8ae79fcd
|
Implement Media model
|
redux/src/main/domain/models/Media.js
|
redux/src/main/domain/models/Media.js
|
export default class Media {
static get IMAGE_FILE_EXTENSIONS() {
return ['jpg', 'png', 'gif'];
}
}
|
JavaScript
| 0.000003 |
@@ -1,8 +1,30 @@
+import fs from 'fs';%0A%0A
export d
@@ -45,18 +45,16 @@
edia %7B%0A%0A
-
static
@@ -84,20 +84,16 @@
ONS() %7B%0A
-
retu
@@ -102,16 +102,24 @@
%5B'jpg',
+ 'jpeg',
'png',
@@ -128,15 +128,396 @@
if'%5D;%0A
+%7D%0A%0A static build(filePath) %7B%0A const buffer = fs.readFileSync(filePath);%0A const extension = filePath.split('.').pop();%0A // Media.IMAGE_FILE_EXTENSIONS.includes(extension)%0A return new Media(buffer, extension);%0A %7D%0A%0A constructor(buffer, extension) %7B%0A this.buffer = buffer;%0A this.extension = extension;%0A %7D%0A%0A toBase64() %7B%0A return this.buffer.toString('base64')%0A
%7D%0A%0A%7D%0A
|
532ad5dfc0641ce599df3f6989cb201229149780
|
Fix local participant was not shown on large video after merge
|
features/largeVideo/reducer.js
|
features/largeVideo/reducer.js
|
import { ReducerRegistry } from '../base/redux';
import { LARGE_VIDEO_PARTICIPANT_CHANGED } from './actionTypes';
const INITIAL_STATE = {
participantId: undefined
};
ReducerRegistry.register('features/largeVideo',
(state = INITIAL_STATE, action) => {
switch (action.type) {
case LARGE_VIDEO_PARTICIPANT_CHANGED:
return {
...state,
participantId: action.participantId
};
default:
return state;
}
});
|
JavaScript
| 0 |
@@ -1,16 +1,166 @@
+import %7B%0A CONFERENCE_JOINED,%0A CONFERENCE_LEFT%0A%7D from '../base/conference';%0Aimport %7B LOCAL_PARTICIPANT_DEFAULT_ID %7D from '../base/participants';%0A
import %7B Reducer
@@ -436,16 +436,974 @@
type) %7B%0A
+ /**%0A * When conference is joined, we update ID of local participant from%0A * default 'local' to real ID. However in large video we might have%0A * already selected 'local' as participant on stage. So in this case%0A * we must update ID of participant on stage to match ID in%0A * 'participants' state to avoid additional changes in state and%0A * rerenders.%0A */%0A case CONFERENCE_JOINED:%0A if (state.participantId === LOCAL_PARTICIPANT_DEFAULT_ID) %7B%0A let id = action.conference.myUserId();%0A%0A return %7B%0A ...state,%0A participantId: id%0A %7D;%0A %7D%0A%0A return state;%0A /**%0A * Reverse operation to CONFERENCE_JOINED.%0A */%0A case CONFERENCE_LEFT:%0A return %7B%0A ...state,%0A participantId: LOCAL_PARTICIPANT_DEFAULT_ID%0A %7D;%0A%0A
|
e51f60da3cab6c2c929f91db0d6cb6238c8d8bbf
|
Check the manifest has the valid format
|
lib/platform.js
|
lib/platform.js
|
'use strict';
var path = require('path'),
util = require('util');
var manifoldjsLib = require('manifoldjs-lib');
var PlatformBase = manifoldjsLib.PlatformBase,
manifestTools = manifoldjsLib.manifestTools,
fileTools = manifoldjsLib.fileTools;
var constants = require('./constants'),
manifest = require('./manifest');
function Platform (packageName, platforms) {
var self = this;
PlatformBase.call(this, constants.platform.id, constants.platform.name, packageName, __dirname);
// save platform list
self.platforms = platforms;
// override create function
self.create = function (w3cManifestInfo, rootDir, options, callback) {
self.info('Generating the ' + constants.platform.name + ' app...');
var platformDir = path.join(rootDir, constants.platform.id);
// convert the W3C manifest to a platform-specific manifest
var platformManifestInfo;
return manifest.convertFromBase(w3cManifestInfo)
// if the platform dir doesn't exist, create it
.then(function (manifestInfo) {
platformManifestInfo = manifestInfo;
self.debug('Creating the ' + constants.platform.name + ' app folder...');
return fileTools.mkdirp(platformDir);
})
// download icons to the app's folder
.then(function () {
return self.downloadIcons(platformManifestInfo.content, w3cManifestInfo.content.start_url, platformDir);
})
// copy the documentation
.then(function () {
return self.copyDocumentation(platformDir);
})
// write generation info (telemetry)
.then(function () {
return self.writeGenerationInfo(w3cManifestInfo, platformDir);
})
// persist the platform-specific manifest
.then(function () {
self.debug('Copying the ' + constants.platform.name + ' manifest to the app folder...');
var manifestFilePath = path.join(platformDir, 'manifest.json');
return manifestTools.writeToFile(platformManifestInfo, manifestFilePath);
})
.nodeify(callback);
};
}
util.inherits(Platform, PlatformBase);
module.exports = Platform;
|
JavaScript
| 0.001222 |
@@ -65,16 +65,39 @@
('util')
+,%0D%0A Q = require('q')
;%0D%0A %0D
@@ -151,16 +151,62 @@
%0D%0A%0D%0Avar
+CustomError = manifoldjsLib.CustomError,%0D%0A
Platform
@@ -750,24 +750,246 @@
callback) %7B%0D
+%0A if (w3cManifestInfo.format !== manifoldjsLib.constants.BASE_MANIFEST_FORMAT) %7B%0D%0A return Q.reject(new CustomError('The %5C'' + w3cManifestInfo.format + '%5C' manifest format is not valid for this platform.'));%0D%0A %7D%0D
%0A%0D%0A self.
|
26030829d35242abb1084108fa8147b4912ec363
|
Add support for Bluebird 3
|
lib/provider.js
|
lib/provider.js
|
'use strict'
var request = require('request')
, extend = require('extend')
var Promise = null
try {
Promise = require('bluebird')
} catch (e) {}
var debug = null
try {
debug = require('request-debug')
} catch (e) {}
var config = require('./config')
, utils = require('./utils')
var Query = require('./query')
, Url = require('./url')
var providers = require('../config/providers')
, hooks = require('../config/hooks')
function Provider (options) {
if (!options || !options.provider) {
throw new Error('Purest: provider option is required!')
}
// provider
var provider = {}
, name = options.provider
// config
if (options.config) {
// existing
if (providers[name]) {
// extend
if (options.config[name]) {
extend(true, provider, providers[name], options.config[name])
} else {
provider = providers[name]
}
} else {
// custom
provider = options.config[name]
}
} else {
provider = providers[name]
}
if (!provider) {
throw new Error('Purest: non existing provider!')
}
// key & secret
if (options.consumerKey||options.key) {
this.key = options.consumerKey||options.key
}
if (options.consumerSecret||options.secret) {
this.secret = options.consumerSecret||options.secret
}
// request
this._request = Provider.request
// promise
if (options.promise) {
if (!Promise) {
throw new Error('Purest: bluebird is not installed!')
} else {
this._request = Promise.promisify(Provider.request)
}
}
// debug
if (options.debug) {
if (!debug) {
throw new Error('Purest: request-debug is not installed!')
} else {
debug(this._request)
}
}
// defaults
if (options.defaults) {
this._request = this._request.defaults(options.defaults)
}
// url modifiers
this.subdomain = options.subdomain
this.subpath = options.subpath
this.version = options.version
this.type = options.type
// api - path alias
this.apis = config.aliases(provider)
if (options.api) {
if (!this.apis || !this.apis[options.api]) {
throw new Error('Purest: non existing API!')
} else {
this.api = options.api
}
} else {
this.api = '__default'
}
// shortcuts
this.name = options.provider
this[options.provider] = true
// classes
this.url = new Url(this)
// method aliases
if (options.methods) {
this._query = new Query(this, options.methods)
} else {
this._query = new Query(this)
}
// hooks
this.before = {}
if (hooks[this.name]) {
this.before = hooks[this.name]
}
if (options.before) {
this.before = options.before
}
}
function prepare (method, uri, options, callback) {
var params = request.initParams(uri, options, callback)
var endpoint = params.uri||''
, options = params
, callback = params.callback
options.method = options.method||(method=='del'?'delete':method).toUpperCase()
// path config
var cfg = this.apis[options.api||this.api||'__default']
if (!cfg) {
throw new Error('Purest: non existing API!')
}
// check for endpoint specific options
options = config.options(endpoint, options, method, cfg.endpoints)
if (method != 'put') {
if (options.json === undefined && options.encoding === undefined) {
options.json = true
}
}
// oauth option transformations
utils.oauth.call(this, options)
// hooks
if (this.before.all) {
this.before.all.call(this, endpoint, options, cfg)
}
if (this.before[method]) {
this.before[method].call(this, endpoint, options, cfg)
}
// create absolute url
var url = endpoint.indexOf('http') == -1
? this.url.get(endpoint, options, cfg)
: endpoint
// start
if (callback) {
return this._request(url, options, utils.response(callback))
} else {
return this._request(url, options)
}
}
Provider.prototype.get = function (uri, options, callback) {
return prepare.call(this, 'get', uri, options, callback)
}
Provider.prototype.post = function (uri, options, callback) {
return prepare.call(this, 'post', uri, options, callback)
}
Provider.prototype.put = function (uri, options, callback) {
return prepare.call(this, 'put', uri, options, callback)
}
Provider.prototype.del = function (uri, options, callback) {
return prepare.call(this, 'del', uri, options, callback)
}
Provider.prototype.patch = function (uri, options, callback) {
return prepare.call(this, 'patch', uri, options, callback)
}
Provider.prototype.head = function (uri, options, callback) {
return prepare.call(this, 'head', uri, options, callback)
}
Provider.prototype.config = function (name) {
this._query._init(name)
return this._query
}
Provider.prototype.query = function (name) {
this._query._init(name)
return this._query
}
Provider.request = request
Provider.extend = extend
exports = module.exports = Provider
|
JavaScript
| 0.000001 |
@@ -1535,24 +1535,42 @@
ider.request
+, %7BmultiArgs:true%7D
)%0A %7D%0A %7D%0A
|
38b95a5571d02a56d3dcdcb577303f484f547d94
|
fix typo
|
lib/reporter.js
|
lib/reporter.js
|
'use strict';
const print = require('./fn').formatTime;
const fmt = require('./fmt');
const evts = {
add: 'added',
change: 'changed',
unlink: 'removed'
};
module.exports = function () {
const $ = this.$;
return this
.on('fly_run', file => {
$.log(`Flying with ${fmt.path(file)}`);
})
.on('flyfile_not_found', () => {
process.exitCode = 1;
$.log('Flyfile not found!');
})
.on('fly_watch', () => {
$.log(fmt.warn('Watching files...'));
})
.on('fly_watch_event', obj => {
$.log(`File ${evts[obj.type] || obj.type.trim()}: ${fmt.warn(obj.file)}`);
})
.on('globs_no_match', (globs, opts) => {
let str = `${fmt.warn('Warning:')} Source did not match any files!`;
str += `\n\t Patterns: ${JSON.stringify(globs)}`;
opts && (str += `\n\t Options: ${JSON.stringify(opts)}`);
$.log(str);
})
.on('plugin_load', obj => {
$.log(`Loading plugin ${fmt.title(obj.plugin)}`);
})
.on('plugin_load_error', str => {
$.log(`Problem loading plugin: ${fmt.title(obj.name)}`);
})
.on('plugin_rename', obj => {
$.log(`${fmt.title(obj.o)} was renamed to ${fmt.title(obj.n)} because its name was taken`);
})
.on('plugin_error', obj => {
process.exitCode = 1;
$.log(`${fmt.error(obj.plugin)} failed due to ${fmt.error(obj.error)}`);
})
.on('tasks_force_object', () => {
process.exitCode = 1;
$.error('Invalid Tasks!');
$.log('Custom `tasks` must be an `object`.');
})
.on('task_error', obj => {
process.exitCode = 1;
$.trace(obj.error);
$.log(`${fmt.error(obj.task)} failed due to ${fmt.error(obj.error)}`);
})
.on('task_start', obj => {
$.log(`Starting ${fmt.title(obj.task)}`);
})
.on('task_complete', obj => {
const t = print(obj.time);
$.log(`Finished ${fmt.complete(obj.task)} in ${fmt.time(t)}`);
})
.on('task_not_found', obj => {
process.exitCode = 1;
$.log(`${fmt.error(obj.task)} not found in Flyfile.`);
})
.on('serial_error', e => {
process.exitCode = 1;
console.log('this was serials error', e);
$.error(`Task sequence was aborted!`);
});
};
|
JavaScript
| 0.999991 |
@@ -1016,16 +1016,11 @@
tle(
-obj.name
+str
)%7D%60)
|
9e3fec61bcf64fb9bea49c3560a7d850dfc46ce7
|
apply chalk defs to 'task_complete' message
|
lib/reporter.js
|
lib/reporter.js
|
var fmt = require('./fmt')
var log = require('./utils').log
var trace = require('./utils').trace
var evts = {
add: 'added',
change: 'changed',
unlink: 'removed'
}
module.exports = function () {
return this
.on('fly_run', function (obj) {
log('Flying with ' + fmt.path + '...', obj.path)
})
.on('flyfile_not_found', function () {
process.exitCode = 1
log('Flyfile not found')
})
.on('fly_watch', function () {
log(fmt.warn.toString(), 'Watching files...')
})
.on('fly_watch_event', function (obj) {
log('File ' + (evts[obj.type] || obj.type.trim()) + ': ' + fmt.warn, obj.file)
})
.on('plugin_load', function (obj) {
log('Loading plugin ' + fmt.title, obj.plugin)
})
.on('plugin_error', function (obj) {
process.exitCode = 1
log(
fmt.error + ' failed due to ' + fmt.error,
obj.plugin, obj.error
)
})
.on('task_error', function (obj) {
process.exitCode = 1
trace(obj.error)
log(
fmt.error + ' failed due to ' + fmt.error,
obj.task, obj.error
)
})
.on('task_start', function (obj) {
log('Starting ' + fmt.start, obj.task)
})
.on('task_complete', function (obj) {
var time = formatTime(obj.duration)
log(
'Finished ' + fmt.complete + ' in ' + fmt.secs,
obj.task, time.duration, time.scale
)
})
.on('task_not_found', function (obj) {
process.exitCode = 1
log(fmt.error + ' not found in Flyfile.', obj.task)
})
}
/**
* Format the task's time duration
* @param {Integer} time The task's duration, in ms
* @param {String} unit The unit of time measurement
* @return {String}
*/
function formatTime(time, unit) {
unit = unit || 'ms'
if (time >= 1000) {
time = Math.round((time / 1000) * 10) / 10
unit = 's'
}
return `${time}${unit}`;
}
|
JavaScript
| 0.017612 |
@@ -1146,36 +1146,27 @@
e',
-function (obj) %7B%0A%09%09%09var time
+obj =%3E %7B%0A%09%09%09const t
= f
@@ -1188,24 +1188,25 @@
uration)
+;
%0A%09%09%09log(
%0A%09%09%09%09'Fi
@@ -1201,14 +1201,9 @@
log(
-%0A%09%09%09%09'
+%60
Fini
@@ -1207,20 +1207,18 @@
inished
-' +
+$%7B
fmt.comp
@@ -1225,74 +1225,40 @@
lete
- + ' in ' + fmt.secs,%0A%09%09%09%09obj.task, time.duration, time.scale%0A%09%09%09)
+(obj.task)%7D in $%7Bfmt.time(t)%7D%60);
%0A%09%09%7D
|
d5d5940b301fab1fc6a3d4f28b31a6d126ff228e
|
add built files
|
lib/rxToMost.js
|
lib/rxToMost.js
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.rxToMost = rxToMost;
var _mostSubject = require('most-subject');
var _mostSubject2 = _interopRequireDefault(_mostSubject);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function rxToMost(rxSubject) {
var _subject = (0, _mostSubject2.default)();
var sink = _subject.sink;
var stream = _subject.stream;
rxSubject.subscribe(function (x) {
return sink.add(x);
}, function (e) {
throw new Error(e);
}, function () {
return sink.end();
});
var dispose = function dispose() {
rxSubject.complete();
};
dispose.observe = stream.observe.bind(stream);
return dispose;
}
|
JavaScript
| 0.000001 |
@@ -112,23 +112,16 @@
ar _most
-Subject
= requi
@@ -132,426 +132,171 @@
most
--subject');%0A%0Avar _mostSubject2 = _interopRequireDefault(_mostSubject);%0A%0Afunction _interopRequireDefault(obj) %7B return obj && obj.__esModule ? obj : %7B default: obj %7D; %7D%0A%0Afunction rxToMost(rxSubject) %7B%0A var _subject = (0, _mostSubject2.default)();%0A%0A var sink = _subject.sink;%0A var stream = _subject.stream;%0A%0A rxSubject.subscribe(function (x) %7B%0A return sink.add(x);%0A %7D, function (e) %7B%0A throw new Error(e);%0A %7D,
+');%0A%0Afunction rxToMost(rxSubject) %7B%0A return (0, _most.create)(function (add, end, error) %7B%0A var subscription = rxSubject.subscribe(add, error, end);%0A return
fun
@@ -314,16 +314,18 @@
+
return s
ink.
@@ -324,157 +324,42 @@
rn s
-ink.end();%0A %7D);%0A var dispose = function dispose() %7B%0A rxSubject.complete();%0A %7D;%0A dispose.observe = stream.observe.bind(stream);%0A return dispose
+ubscription.complete();%0A %7D;%0A %7D)
;%0A%7D
|
79e164084ba60bf5b7cd1fdda7a875893c1c8ad5
|
fix proxy has return value
|
src/runtime/instance/proxy.js
|
src/runtime/instance/proxy.js
|
import { warn, makeMap } from '../util/index'
let hasProxy, proxyHandlers, initProxy
if (process.env.NODE_ENV !== 'production') {
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl'
)
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has (target, key) {
const has = key in target
if (!has && !allowedGlobals(key)) {
warn(
`Trying to access non-existent property "${key}" while rendering.`,
target
)
}
return has
}
}
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
export { initProxy }
|
JavaScript
| 0.000002 |
@@ -538,24 +538,74 @@
y in target%0A
+ const isAllowedGlobal = allowedGlobals(key)%0A
if (!h
@@ -611,17 +611,19 @@
has && !
-a
+isA
llowedGl
@@ -626,22 +626,16 @@
edGlobal
-s(key)
) %7B%0A
@@ -770,19 +770,32 @@
return
-has
+!isAllowedGlobal
%0A %7D%0A
|
45f8abcc7bf3ba85c864720a13b35ce5a90ec60d
|
fix steps not defined issue
|
lib/steps/if.js
|
lib/steps/if.js
|
module.exports = {
spec : function() {
return {
name : 'if',
desc : '',
fields : [
{type:'string',name:'var',description:'',required:true},
{type:'string',name:'if',description:'',required:true},
{type:'string',name:'pattern',description:'',required:true},
{type:'string',name:'yes_subflow',description:''},
{type:'string',name:'no_subflow',description:''}
]
}
}
,
process : function(ctx, step, checkNext) {
var val = ctx.vars[step.var];
var validated = false;
if(step.if === 'contains') {
validated = val.indexOf(step.pattern) !== -1;
}
else if(step.if === 'equal') {
//console.log('execute if [' + val + '] = [' + step.pattern + ']');
validated = val === step.pattern;
}
else if(step.if === 'eq') {
//console.log('execute if [' + val + '] = [' + step.pattern + ']');
validated = val === step.pattern;
}
else if(step.if === 'neq') {
//console.log('execute if [' + val + '] = [' + step.pattern + ']');
validated = val !== step.pattern;
}
if(validated) {
if(step.yes_subflow !== null) {
var inputVars = ctx.vars;
for(var i in step) {
if(!Object.prototype.hasOwnProperty.call(step,i)) continue;
inputVars[i] = step[i];
}
inputVars['inputall'] = true;
inputVars['outputall'] = true;
//console.log('execute yes subflow ' + step.yes_subflow)
ctx.executeWorkFlow(ctx.config.workFlows[step.yes_subflow], {inputVars:inputVars,outputVars:step.yes_outputVars}, function(outputOpts) {
if(outputOpts.outputVars) {
for(var j in outputOpts.outputVars) {
if(!Object.prototype.hasOwnProperty.call(outputOpts.outputVars,j)) continue;
ctx.vars[j] = outputOpts.outputVars[j];
}
}
process.nextTick(checkNext);
});
}
else {
process.nextTick(checkNext);
}
}
else {
if(step.no_subflow !== null) {
var inputVars = ctx.vars;
for(var i in step) {
if(!Object.prototype.hasOwnProperty.call(step,i)) continue;
inputVars[i] = step[i];
}
inputVars['inputall'] = true;
inputVars['outputall'] = true;
//console.log('execute no subflow ' + step.yes_subflow)
ctx.executeWorkFlow(ctx.config.workFlows[step.no_subflow], {inputVars:inputVars,outputVars:step.no_outputVars}, function(outputOpts) {
if(outputOpts.outputVars) {
for(var j in outputOpts.outputVars) {
if(!Object.prototype.hasOwnProperty.call(outputOpts.outputVars,j)) continue;
ctx.vars[j] = outputOpts.outputVars[j];
}
}
process.nextTick(checkNext);
});
}
else {
process.nextTick(checkNext);
}
}
}
}
|
JavaScript
| 0.000004 |
@@ -1042,33 +1042,32 @@
p.yes_subflow !=
-=
null) %7B%0A%09%09%09%09var
@@ -1840,17 +1840,16 @@
bflow !=
-=
null) %7B
|
88845e3134ce20aa266889e48dac37d3831ce8aa
|
add to pull diff screen
|
src/screens/PullDiffScreen.js
|
src/screens/PullDiffScreen.js
|
import React, {Component, PropTypes} from 'react';
import { Text } from 'react-native';
import Parse from 'parse-diff';
import ViewContainer from '../components/ViewContainer';
class PullDiff extends Component {
componentDidMount() {
const files = Parse(this.props.navigation.state.params.diff);
console.log(files.length);
files.forEach(function(file) {
console.log(file.chunks.length); // number of hunks
console.log(file.chunks[0].changes.length) // hunk added/deleted/context lines
// each item in changes is a string
console.log(file.deletions); // number of deletions in the patch
console.log(file.additions); // number of additions in the patch
});
}
render() {
const {navigation} = this.props;
const filesChanged = Parse(navigation.state.params.diff);
return (
<ViewContainer>
<Text>{navigation.state.params.diff}</Text>
</ViewContainer>
)
}
}
PullDiff.propTypes = {
diff: PropTypes.string,
};
export default PullDiff;
|
JavaScript
| 0 |
@@ -81,16 +81,71 @@
ative';%0A
+import %7BCard, ListItem%7D from 'react-native-elements';%0A%0A
import P
@@ -227,16 +227,79 @@
iner';%0A%0A
+const files = Parse(this.props.navigation.state.params.diff);%0A%0A
class Pu
@@ -1018,16 +1018,677 @@
%7D%3C/Text%3E
+%0A%0A %7Bfiles.map((file, i) =%3E (%0A %3CCard containerStyle=%7B%7Bpadding: 0%7D%7D %3E%0A %7B%0A file.chunks.map((chunk, i) =%3E (%0A %3CListItem%0A leftIcon=%7B%7B'git-pull-request', color: colors.grey, type: 'octicon'%7D%7D%0A key=%7Bi%7D%0A title=%7Bchunk.name%7D /%3E%0A%0A %7B%0A chunk.changes.map((change, i) =%3E (%0A %3CListItem%0A key=%7Bi%7D%0A title=%7B%60Content: $%7Bchange.content%7D, Type: $%7Bchange.type%7D%60%7D /%3E%0A ))%0A %7D%0A ))%0A %7D%0A %3C/Card%3E%0A ))%7D
%0A %3C
|
83a447c2989ed2a598f7256d7a0a89e2df5c46cf
|
Allow any content tags besides 'img'
|
lib/tdf-live.js
|
lib/tdf-live.js
|
var colors = require('colors')
, cheerio = require('cheerio')
, striptags = require('striptags')
, moment = require('moment')
, Entities = require('html-entities').Html5Entities;
var entities = new Entities();
// metadata container
exports.meta = {};
// function to build a text update string out of the HTML update body
exports.build = function(str, text) {
text = text || '';
if (str) {
// we want just the text out of the HTML
// but we also want to turn <br> tags into newlines
// and we want the html special chars translated
str = striptags(str, '<br>');
str = str.replace(/<br( \/)?>/g, '\n');
str = str.replace(/\t/g, ' ');
str = entities.decode(str);
// split into chunks so lines don't exceed 80 chars
// (there is a 14 char space at the beginning that has the timestamp)
// add a period to the end of a line that ends with a word character
// (i.e. letter or number). This is because the regexp that we use
// to split the string tries to split it on a boundary by looking for
// a space or punctuation
if (/\w$/.test(str)) {
str = str + '.';
}
var chunks = str.match(/.{1,65}[ \.,\?\!:;)\]\}>'"\n]/g)
.map(function(chunk) { return chunk.trim() });
if (text.length) {
text += '\n ';
}
text += chunks.join('\n ') + '\n';
}
return text;
};
// function to display an update message
exports.display = function(update) {
var meta = exports.meta;
// build them message
var msg = update.timestamp.yellow
+ ' '
+ update.text;
if (update.distance) {
var dist = '\n' + update.distance + meta.units + ' remain of '
+ meta.distance + meta.units + ' total\n';
msg += dist.underline.green;
}
console.log(msg);
};
exports.parse = function(body) {
var $ = cheerio.load(body)
, liveReport = $('#liveReportConsolePreview')
, meta = exports.meta;
// pull some metadata from the feed container
meta.timezone = liveReport.data('timezone');
meta.offset = liveReport.data('timezoneOffset');
// distance and unit metadata
meta.distance = liveReport.data('distance');
meta.units = liveReport.data('distanceUnits');
// is the feed done?
meta.complete = !!liveReport.data('complete');
var updates = [];
// now pull all of the past updates to get us to current time
liveReport.children().each(function(i, element) {
var data = $(this).data('liveEntry')
, entry = $(this).children().first()
, timestamp = '', text = '';
timestamp = entry.find('h3').text().trim()
// entry.attr('class') contains a hint at the type of entry
// These i've seen so far: none, twitter, quote
entry.find('.contents').children().filter(function() {
// only process <p> tags that contain some content
return $(this)[0].name === 'p' && $(this).text().trim();
}).each(function(i, element) {
text = exports.build($(this).html().trim(), text);
});
updates.push({
distance: data.distance,
timestamp: timestamp,
text: text
});
});
return updates.reverse();
};
exports.timestamp = function(unixtime) {
// so this is kinda dirty but I don't feel like messing with
// timestamps. so we know everything is based off of BST, which
// is 1 hour ahead of UTC/GMT. So we'll just manually hack that
// offset
var timestamp = moment.unix(unixtime).utc()
.add(1, 'hour') // BST offset
.add(exports.meta.offset, 'seconds') // stage offset
.format('HH:mm:ss');
return timestamp + ' ' + exports.meta.timezone;
};
|
JavaScript
| 0.000001 |
@@ -1124,17 +1124,18 @@
str + '
-.
+%5Cn
';%0A %7D
@@ -2885,14 +2885,16 @@
ame
-=
+!
== '
-p
+img
' &&
|
0029435a3830959f6300dbc6b8b74048074c6e55
|
Add missing flow definitions for mocha
|
flow-typed/npm/mocha_v3.1.x.js
|
flow-typed/npm/mocha_v3.1.x.js
|
// flow-typed signature: 6b82cf8c1da27b4f0fa7a58e5ed5babf
// flow-typed version: edf70dde46/mocha_v3.1.x/flow_>=v0.22.x
type TestFunction = ((done: () => void) => void | Promise<mixed>);
declare var describe : {
(name:string, spec:() => void): void;
only(description:string, spec:() => void): void;
skip(description:string, spec:() => void): void;
timeout(ms:number): void;
};
declare var context : typeof describe;
declare var it : {
(name:string, spec?:TestFunction): void;
only(description:string, spec:TestFunction): void;
skip(description:string, spec:TestFunction): void;
timeout(ms:number): void;
};
declare function before(method : TestFunction):void;
declare function beforeEach(method : TestFunction):void;
declare function after(method : TestFunction):void;
declare function afterEach(method : TestFunction):void;
|
JavaScript
| 0 |
@@ -835,28 +835,647 @@
ethod : TestFunction):void;%0A
+%0A/****************************************************************************/%0A/* TODO: Contribute missing definitions upstream */%0A/****************************************************************************/%0A%0Adeclare function before(desc: string, method: TestFunction):void;%0Adeclare function beforeEach(desc: string, method: TestFunction):void;%0Adeclare function after(desc: string, method: TestFunction):void;%0Adeclare function afterEach(desc: string, method: TestFunction):void;%0A%0Adeclare var xdescribe : typeof describe;%0Adeclare var xcontext : typeof context;%0Adeclare var xit : typeof it;%0A
|
c5acab6b03a63171b8c59e9bd07b46ed067a702c
|
Make requests only when a job has finished
|
src/semprebeta-client-side.js
|
src/semprebeta-client-side.js
|
require('angular') /*global angular*/
require('comp-pool')
angular.module('SemprebetaApp', ['CompPoolClient'])
.factory('compPoolRoot', ['$log', function ($log) {
var rootDefault = 'http://localhost:7070/'
$log.debug('Getting value for comp-pool root %s (fall back to %s)', process.env.COMP_POOL_ROOT, rootDefault)
return process.env.COMP_POOL_ROOT || rootDefault
}])
.controller('JobsCtrl', ['$scope', '$http', '$timeout', '$log', '$q', 'compPoolClient',
function ($scope, $http, $timeout, $log, $q, compPoolClient) {
$scope.job = {}
$scope.statuses = {
ok: 'OK',
idle: 'IDLE',
connecting: 'CONNECTING',
error: 'ERROR'
}
$scope.status = $scope.statuses.idle
$scope.stats = {}
$scope.stats.results = 0
var jobLoop = function (job) {
$log.debug('Rolling job %j', job)
job.getVariablesRoot().then(function (variablesRoot) {
$log.debug('Getting random variable with %j', variablesRoot)
return variablesRoot.getRandomVariable()
}).then(function (variable) {
$log.debug('Computing with variable %j', variable)
return variable.compute()
}).then(function (variableWithResult) {
$log.debug('Saving variable %j', variableWithResult)
$scope.stats.results++
$scope.stats.timeSpent = (new Date().getTime() - $scope.firstJob.getTime()) / 1000
$scope.stats.resultsPerSecond = $scope.stats.results / $scope.stats.timeSpent
variableWithResult.saveResult({asVariableToo: true})
})
if ($scope.status === $scope.statuses.ok) {
$timeout(jobLoop, 100, true, job)
}
}
$scope.deactivate = function () {
$log.debug('Deactivating')
$scope.status = $scope.statuses.idle
}
$scope.activate = function () {
$log.debug('Activating %j', compPoolClient)
var pq = compPoolClient.getJobsRoot().then(function (root) {
$log.debug('Got root %j', root)
$scope.status = $scope.statuses.ok
return root.getRandomJob()
}).then(function (job) {
$log.debug('Got job %j', job)
$scope.firstJob = new Date()
jobLoop(job)
return job
}).catch(function (err) {
$log.error('Something happened! %j', err)
$scope.status = $scope.statuses.error
})
$log.debug('Activated %j', pq)
}
}
])
|
JavaScript
| 0 |
@@ -1575,28 +1575,19 @@
true%7D)%0A
+%0A
- %7D)%0A%0A
@@ -1644,51 +1644,244 @@
-$timeout(jobLoop, 100, true, job)%0A %7D
+ $log.debug('Calling a new job')%0A $timeout(jobLoop, 100, true, job)%0A %7D%0A %7D).catch(function (err) %7B%0A $log.error('Something happened! %25j', err)%0A $scope.status = $scope.statuses.error%0A %7D)
%0A
|
dbf1145d2514682ca80fb721ebf9f50d701c3455
|
Update schemas
|
src/server/dbconfig/schema.js
|
src/server/dbconfig/schema.js
|
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
username: String,
password: String,
restaurants: [{
name: String,
visits: Number
}],
preferences: [String],
locations: [String],
addresses: [{
type: Number,
ref: 'Address'
}]
});
var restaurantSchema = new mongoose.Schema({
name: String,
rating: String,
tags: [String],
address: String,
hours: String,
priceRange: {
min: String,
max: String
},
visits: Number
});
var addressSchema = new mongoose.Schema({
user: {
type: Number,
ref: 'User'
},
label: String,
lineOne: String,
lineTwo: String,
lineThree: String
});
var User = mongoose.model('User', userSchema);
var Restaurant = mongoose.model('Restaurant', restaurantSchema);
var Address = mongoose.model('Address', addressSchema);
module.exports = {
User: User,
Restaurant: Restaurant,
Address: Address
}
|
JavaScript
| 0.000001 |
@@ -236,38 +236,62 @@
s: %5B%7B%0A type:
-Number
+mongoose.Schema.Types.ObjectId
,%0A ref: 'Addr
@@ -576,22 +576,46 @@
type:
-Number
+mongoose.Schema.Types.ObjectId
,%0A re
@@ -652,63 +652,25 @@
,%0A
-lineOne: String,%0A lineTwo
+address
:
+%5B
String
-,%0A lineThree: String
+%5D
%0A%7D);
|
cead0afbbe3e57f13b3b776efdb051e5c7b85491
|
fix rm arg parsing
|
node/lib/cmd/rm.js
|
node/lib/cmd/rm.js
|
/*
* Copyright (c) 2018, Two Sigma Open Source
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of git-meta nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
const co = require("co");
/**
* This module contains methods for implementing the `rm` command.
*/
/**
* help text for the `rm` command
* @property {String}
*/
exports.helpText = `Remove files or submodules from the mono-repo.`;
/**
* description of the `rm` command
* @property {String}
*/
exports.description =`
This command updates the (logical) mono-repo index using the current content
found in the working tree, to prepare the content staged for the next commit.
If the path specified is a submodule, this command will stage the removal of
the submodule entirely (including removing it from .gitmodules). Otherwise,
its removal will be staged in the index.
`;
exports.configureParser = function (parser) {
parser.addArgument(["-f", "--force"], {
required: false,
action: "storeConst",
constant: true,
help: "Force removal of a commit with stated changes.",
defaultValue:false
});
parser.addArgument(["-r", "--recursive"], {
required: false,
action: "storeConst",
constant: true,
help: "Remove a directory recursively",
defaultValue:false
});
parser.addArgument(["--cached"], {
required: false,
action: "storeConst",
constant: true,
help: `
Remove the file from the index, but not from disk. In the case of a
submodule, edits to .gitmodules will staged (but the on-disk version
will not be affected)`,
defaultValue: false,
});
parser.addArgument(["paths"], {
nargs: "+",
type: "string",
help: "the paths to rm",
});
};
/**
* Execute the `rm` command according to the specified `args`.
*
* @async
* @param {Object} args
* @param {String[]} args.paths
*/
exports.executeableSubcommand = co.wrap(function *(args) {
const Rm = require("../util/rm");
const GitUtil = require("../util/git_util");
const repo = yield GitUtil.getCurrentRepo();
const workdir = repo.workdir();
const cwd = process.cwd();
const paths = yield args.paths.map(filename => {
return GitUtil.resolveRelativePath(workdir, cwd, filename);
});
yield Rm.rmPaths(repo, paths, args.recursive, args.cached, args.force);
});
|
JavaScript
| 0.000004 |
@@ -3811,43 +3811,8 @@
args
-.recursive, args.cached, args.force
);%0A%7D
|
e6d74d537139c3896aa5a61921bdf4ce80e20c8c
|
Make it work by default
|
tasks/parallel-behat.js
|
tasks/parallel-behat.js
|
'use strict';
var glob = require('glob'),
_ = require('underscore'),
ParallelExec = require('./lib/ParallelExec'),
BehatTask = require('./lib/BehatTask'),
defaults = {
src: './**/*.feature',
bin: './bin/behat',
cwd: './',
config: './behat.yml',
flags: '',
maxProcesses: 10000,
baseDir: './',
debug: false,
numRetries: 0,
timeout: 600000
};
/**
* Grunt task for executing behat feature files in parallel
*
* @param {Grunt} grunt
*/
function GruntTask (grunt) {
var options = _.defaults(grunt.config('behat'), defaults),
executor = new ParallelExec(options.maxProcesses, {cwd: options.cwd, timeout: options.timeout}),
behat;
grunt.registerTask('behat', 'Parallel behat', function () {
var done = this.async();
glob(options.src, function (err, files) {
options.files = files;
options.done = done;
options.executor = executor;
options.log = grunt.log.writeln;
behat = new BehatTask(options);
behat.run();
});
});
}
module.exports = GruntTask;
|
JavaScript
| 0.000039 |
@@ -610,16 +610,22 @@
'behat')
+ %7C%7C %7B%7D
, defaul
@@ -1173,8 +1173,9 @@
untTask;
+%0A
|
145962fd8a3f3da97e2e572494440f2eb1b2425f
|
Use `exec` instead of wp-cli, since WP doesn’t know about our custom command.
|
tasks/wp_theme_check.js
|
tasks/wp_theme_check.js
|
/*
* grunt-wp-theme-check
* https://github.com/ryelle/grunt-wp-theme-check
*
* Copyright (c) 2014 ryelle
* Licensed under the MIT license.
*/
'use strict';
var WP = require('wp-cli'),
Table = require('cli-table'),
_ = require('underscore');
module.exports = function(grunt) {
function run_check( options, done ){
grunt.log.debug( 'Checking theme: ' + options.theme );
grunt.event.once('wpThemeCheck', function( result, err ){
grunt.log.debug( 'Results: ' + JSON.stringify( result ) );
});
WP.load({ path: options.path }, function( WP ) {
grunt.event.emit( 'wpReady', WP );
WP.trt.check( options.theme, function( err, result ){ //get CLI info
grunt.event.emit( 'wpThemeCheck', result, err );
});
});
}
function list_themes( options, done ){
grunt.event.once('wpThemeList', function( themes, err ){
if ( err ){
grunt.log.debug( err );
grunt.log.error( 'WordPress encountered an error, check your WP install.' );
done( false );
} else {
// Display theme list.
var table = new Table({ head: ['name', 'status', 'update', 'version'] });
_.each(themes, function(theme){
table.push([ theme.name, theme.status, theme.update, theme.version ]);
})
grunt.log.writeln( table.toString() );
grunt.log.error( 'The theme to check should be one of the above themes.' );
done( false );
}
});
WP.load({ path: options.path }, function( WP ) {
grunt.event.emit( 'wpReady', WP );
WP.theme.list( function( err, themes ){ //get CLI info
grunt.event.emit( 'wpThemeList', themes, err );
});
});
}
grunt.registerMultiTask('wp_theme_check', 'Grunt plugin to run Theme Check', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
theme: null,
path: null,
});
var done = this.async();
grunt.log.debug( 'options: ' + JSON.stringify( options ) );
if ( ! options.path ){
grunt.log.error( 'Please define the path to your WordPress install.' );
done(false);
}
if ( ! options.theme ) {
list_themes( options, done );
} else {
run_check( options, done );
}
});
};
|
JavaScript
| 0 |
@@ -248,16 +248,58 @@
rscore')
+,%0A exec = require('child_process').exec
;%0A%0Amodul
@@ -376,190 +376,553 @@
-grunt.log.debug( 'Checking theme: ' + options.theme );%0A%0A grunt.event.once('wpThemeCheck', function( result, err )%7B%0A grunt.log.debug( 'Results: ' + JSON.stringify( result ) );
+var command = %22wp theme review check %22 + options.theme + %22 --path=%22 + options.path;%0A%0A grunt.log.debug( 'Running: ' + command );%0A%0A grunt.event.once('wpThemeCheck', function( result, err )%7B%0A if ( err )%7B%0A grunt.log.debug( err );%0A grunt.log.error( 'WordPress encountered an error, check your WP install.' );%0A done( false );%0A %7D else %7B%0A if ( result.indexOf( 'Success' ) === 0 ) %7B%0A grunt.log.ok( result );%0A %7D else %7B%0A grunt.log.write( result );%0A %7D%0A done( true );%0A %7D
%0A
@@ -1025,27 +1025,28 @@
);%0A
+%0A
-WP.trt.check(
+// Check that
opt
@@ -1059,50 +1059,77 @@
heme
-, function( err, result )%7B //get CLI info%0A
+ is a theme.%0A%0A exec( command, function( err, stdout, stderr )%7B%0A
@@ -1165,24 +1165,27 @@
Check',
-result,
+stdout, std
err );%0A
@@ -1185,32 +1185,33 @@
rr );%0A %7D);%0A
+%0A
%7D);%0A%0A %7D%0A%0A
|
a3c081f2cb4bde6ecaf04e966e747b1233968796
|
fix to treat all ids in a changeset create block as a placeholder
|
lib/xml_diff.js
|
lib/xml_diff.js
|
var parsexml = require('xml-parser')
var xtend = require('xtend')
var randombytes = require('randombytes')
var has = require('has')
var hex2dec = require('./hex2dec.js')
module.exports = function (str) {
var xml = parsexml(str)
var ops = { create: [], modify: [], delete: [] }
var ids = { way: {}, node: {}, relation: {} }
if (xml.root.name !== 'osmChange') return ops
xml.root.children.forEach(function (c) {
c.children.forEach(function (ch) {
var doc = xtend(ch.attributes, { type: ch.name })
if (doc.id) doc.oldId = doc.id
if (doc.id && Number(doc.id) < 0) {
if (has(ids, ch.name)) {
ids[ch.name][doc.id] = hex2dec(randombytes(8).toString('hex'))
doc.id = ids[ch.name][doc.oldId]
}
}
if (ch.name === 'way') {
doc.refs = []
ch.children.forEach(function (nd) {
if (nd.name === 'nd' && nd.attributes.ref) {
doc.refs.push(nd.attributes.ref)
}
})
} else if (ch.name === 'member') {
doc.members = []
ch.children.forEach(function (m) {
if (m.name === 'member' && m.attributes.ref) {
doc.members.push(xtend(m.attributes, { type: 'member' }))
}
})
}
;(ch.children || []).forEach(function (c) {
if (c.name !== 'tag' || !c.attributes.k || !c.attributes.v) return
if (!doc.tags) doc.tags = {}
doc.tags[c.attributes.k] = c.attributes.v
})
if (/^(create|modify|delete)$/.test(c.name)) {
ops[c.name].push(doc)
}
})
})
updateRefs(ops.create)
updateRefs(ops.modify)
updateRefs(ops.delete)
return ops
function updateRefs (ops) {
ops.forEach(function (op) {
if (op.refs) {
op.refs = op.refs.map(function (ref) {
return has(ids.node, ref) ? ids.node[ref] : ref
})
} else if (op.members) {
op.members.forEach(function (m) {
if (has(ids.node, m.ref)) m.ref = ids.node[m.ref]
if (has(ids.way, m.ref)) m.ref = ids.way[m.ref]
if (has(ids.relation, m.ref)) m.ref = ids.relation[m.ref]
})
}
})
}
}
|
JavaScript
| 0 |
@@ -570,26 +570,27 @@
&&
-Number(doc.id) %3C 0
+c.name === 'create'
) %7B%0A
|
567b751d5522e831cfe0853c8a7a90f3e51a3c58
|
Fix Artifact Page after ObservableData#start
|
src/app/UI/lib/managers/artifacts/client/components/Page.js
|
src/app/UI/lib/managers/artifacts/client/components/Page.js
|
import React from "react";
import { AppMenu } from "ui-components/app_menu";
import LightComponent from "ui-lib/light_component";
import {
LoadIndicator as TALoadIndicator
} from "ui-components/type_admin";
import ArtifactRepositories from "../observables/artifact_repositories";
import { States as ObservableDataStates } from "ui-lib/observable_data";
class Page extends LightComponent {
constructor(props) {
super(props);
this.repositoryList = new ArtifactRepositories();
this.state = {
list: this.repositoryList.value.getValue(),
state: this.repositoryList.state.getValue()
};
}
componentDidMount() {
this.addDisposable(this.repositoryList.value.subscribe((list) => this.setState({ list })));
this.addDisposable(this.repositoryList.state.subscribe((state) => this.setState({ state })));
}
render() {
this.log("render", this.props, this.state);
let loadIndicator;
if (this.state.state === ObservableDataStates.LOADING) {
loadIndicator = (
<TALoadIndicator/>
);
}
const pathname = this.getPathname();
const items = this.state.list.toJS().map((item) => {
const pn = `${pathname}/${item._id}`;
const active = this.context.router.location.pathname.startsWith(pn);
return {
label: item._id,
pathname: pn,
active: active
};
});
return (
<div>
{loadIndicator}
<AppMenu
primaryText="Artifacts"
icon="extension"
items={items}
/>
<div className={this.props.theme.content}>
{this.props.children && React.cloneElement(this.props.children, { theme: this.props.theme })}
</div>
</div>
);
}
}
Page.propTypes = {
theme: React.PropTypes.object,
children: React.PropTypes.node,
route: React.PropTypes.object.isRequired
};
Page.contextTypes = {
router: React.PropTypes.object.isRequired
};
export default Page;
|
JavaScript
| 0 |
@@ -670,24 +670,81 @@
idMount() %7B%0A
+ this.addDisposable(this.repositoryList.start());%0A
this
|
c01379dd3129b237b5fba80df1638c1c78a23d34
|
Remove reference to cache manager from RelayEnvironment code comment
|
src/store/RelayEnvironment.js
|
src/store/RelayEnvironment.js
|
/**
* Copyright (c) 2013-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.
*
* @providesModule RelayEnvironment
* @flow
*/
'use strict';
const GraphQLStoreQueryResolver = require('GraphQLStoreQueryResolver');
import type RelayMutation from 'RelayMutation';
import type RelayMutationTransaction from 'RelayMutationTransaction';
import type {MutationCallback, QueryCallback} from 'RelayNetworkLayer';
import type RelayQuery from 'RelayQuery';
import type RelayQueryTracker from 'RelayQueryTracker';
const RelayQueryResultObservable = require('RelayQueryResultObservable');
const RelayStoreData = require('RelayStoreData');
import type {TaskScheduler} from 'RelayTaskQueue';
import type {ChangeSubscription, NetworkLayer} from 'RelayTypes';
const forEachRootCallArg = require('forEachRootCallArg');
const readRelayQueryData = require('readRelayQueryData');
const relayUnstableBatchedUpdates = require('relayUnstableBatchedUpdates');
const warning = require('warning');
import type {
Abortable,
Observable,
RelayMutationTransactionCommitCallbacks,
ReadyStateChangeCallback,
StoreReaderData,
StoreReaderOptions,
} from 'RelayTypes';
import type {
DataID,
RelayQuerySet,
} from 'RelayInternalTypes';
export type FragmentResolver = {
dispose: () => void,
resolve: (
fragment: RelayQuery.Fragment,
dataIDs: DataID | Array<DataID>
) => ?(StoreReaderData | Array<?StoreReaderData>),
};
export interface RelayEnvironmentInterface {
forceFetch(
querySet: RelayQuerySet,
onReadyStateChange: ReadyStateChangeCallback
): Abortable,
getFragmentResolver(
fragment: RelayQuery.Fragment,
onNext: () => void
): FragmentResolver,
getStoreData(): RelayStoreData,
primeCache(
querySet: RelayQuerySet,
onReadyStateChange: ReadyStateChangeCallback
): Abortable,
read(
node: RelayQuery.Node,
dataID: DataID,
options?: StoreReaderOptions
): ?StoreReaderData,
}
/**
* @public
*
* `RelayEnvironment` is the public API for Relay core. Each instance provides
* an isolated environment with:
* - Methods for fetching and updating data.
* - An in-memory cache of fetched data.
* - A configurable network layer for resolving queries/mutations.
* - A configurable task scheduler to control when internal tasks are executed.
* - A configurable cache manager for persisting data between sessions.
*
* No data or configuration is shared between instances. We recommend creating
* one `RelayEnvironment` instance per user: client apps may share a single
* instance, server apps may create one instance per HTTP request.
*/
class RelayEnvironment {
applyUpdate: (
mutation: RelayMutation<any>,
callbacks?: RelayMutationTransactionCommitCallbacks
) => RelayMutationTransaction;
commitUpdate: (
mutation: RelayMutation<any>,
callbacks?: RelayMutationTransactionCommitCallbacks
) => RelayMutationTransaction;
_storeData: RelayStoreData;
constructor() {
this._storeData = new RelayStoreData();
this._storeData.getChangeEmitter().injectBatchingStrategy(
relayUnstableBatchedUpdates
);
this.applyUpdate = this.applyUpdate.bind(this);
this.commitUpdate = this.commitUpdate.bind(this);
}
/**
* @internal
*/
getStoreData(): RelayStoreData {
return this._storeData;
}
/**
* @internal
*/
injectDefaultNetworkLayer(networkLayer: ?NetworkLayer) {
this._storeData.getNetworkLayer().injectDefaultImplementation(networkLayer);
}
injectNetworkLayer(networkLayer: ?NetworkLayer) {
this._storeData.getNetworkLayer().injectImplementation(networkLayer);
}
/**
* @internal
*/
injectQueryTracker(queryTracker: ?RelayQueryTracker) {
this._storeData.injectQueryTracker(queryTracker);
}
addNetworkSubscriber(
queryCallback?: ?QueryCallback,
mutationCallback?: ?MutationCallback
): ChangeSubscription {
return this._storeData.getNetworkLayer().addNetworkSubscriber(
queryCallback,
mutationCallback
);
}
injectTaskScheduler(scheduler: ?TaskScheduler): void {
this._storeData.injectTaskScheduler(scheduler);
}
/**
* Primes the store by sending requests for any missing data that would be
* required to satisfy the supplied set of queries.
*/
primeCache(
querySet: RelayQuerySet,
callback: ReadyStateChangeCallback
): Abortable {
return this._storeData.getQueryRunner().run(querySet, callback);
}
/**
* Forces the supplied set of queries to be fetched and written to the store.
* Any data that previously satisfied the queries will be overwritten.
*/
forceFetch(
querySet: RelayQuerySet,
callback: ReadyStateChangeCallback
): Abortable {
return this._storeData.getQueryRunner().forceFetch(querySet, callback);
}
/**
* Reads query data anchored at the supplied data ID.
*/
read(
node: RelayQuery.Node,
dataID: DataID,
options?: StoreReaderOptions
): ?StoreReaderData {
return readRelayQueryData(this._storeData, node, dataID, options).data;
}
/**
* Reads query data anchored at the supplied data IDs.
*/
readAll(
node: RelayQuery.Node,
dataIDs: Array<DataID>,
options?: StoreReaderOptions
): Array<?StoreReaderData> {
return dataIDs.map(
dataID => readRelayQueryData(this._storeData, node, dataID, options).data
);
}
/**
* Reads query data, where each element in the result array corresponds to a
* root call argument. If the root call has no arguments, the result array
* will contain exactly one element.
*/
readQuery(
root: RelayQuery.Root,
options?: StoreReaderOptions
): Array<?StoreReaderData> {
const queuedStore = this._storeData.getQueuedStore();
const storageKey = root.getStorageKey();
const results = [];
forEachRootCallArg(root, ({identifyingArgKey}) => {
let data;
const dataID = queuedStore.getDataID(storageKey, identifyingArgKey);
if (dataID != null) {
data = this.read(root, dataID, options);
}
results.push(data);
});
return results;
}
/**
* Reads and subscribes to query data anchored at the supplied data ID. The
* returned observable emits updates as the data changes over time.
*/
observe(
fragment: RelayQuery.Fragment,
dataID: DataID
): Observable<?StoreReaderData> {
return new RelayQueryResultObservable(this._storeData, fragment, dataID);
}
/**
* @internal
*
* Returns a fragment "resolver" - a subscription to the results of a fragment
* and a means to access the latest results. This is a transitional API and
* not recommended for general use.
*/
getFragmentResolver(
fragment: RelayQuery.Fragment,
onNext: () => void
): FragmentResolver {
return new GraphQLStoreQueryResolver(
this._storeData,
fragment,
onNext
);
}
/**
* Adds an update to the store without committing it. The returned
* RelayMutationTransaction can be committed or rolled back at a later time.
*/
applyUpdate(
mutation: RelayMutation<any>,
callbacks?: RelayMutationTransactionCommitCallbacks
): RelayMutationTransaction {
mutation.bindEnvironment(this);
return this._storeData.getMutationQueue()
.createTransaction(mutation, callbacks)
.applyOptimistic();
}
/**
* Adds an update to the store and commits it immediately. Returns
* the RelayMutationTransaction.
*/
commitUpdate(
mutation: RelayMutation<any>,
callbacks?: RelayMutationTransactionCommitCallbacks
): RelayMutationTransaction {
return this
.applyUpdate(mutation, callbacks)
.commit();
}
/**
* @deprecated
*
* Method renamed to commitUpdate
*/
update(
mutation: RelayMutation<any>,
callbacks?: RelayMutationTransactionCommitCallbacks
): void {
warning(
false,
'`Relay.Store.update` is deprecated. Please use' +
' `Relay.Store.commitUpdate` or `Relay.Store.applyUpdate` instead.'
);
this.commitUpdate(mutation, callbacks);
}
}
module.exports = RelayEnvironment;
|
JavaScript
| 0.000014 |
@@ -2520,80 +2520,8 @@
ed.%0A
- * - A configurable cache manager for persisting data between sessions.%0A
*%0A
|
75c32a2f025408681a43f226f281154f99d8d5ac
|
Fix a bug where the icons need to be clicked twice after reload
|
src/stores/RightPanelStore.js
|
src/stores/RightPanelStore.js
|
/*
Copyright 2019 The Matrix.org Foundation C.I.C.
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.
*/
import dis from '../dispatcher';
import {Store} from 'flux/utils';
import SettingsStore, {SettingLevel} from "../settings/SettingsStore";
import {RIGHT_PANEL_PHASES, RIGHT_PANEL_PHASES_NO_ARGS} from "./RightPanelStorePhases";
const INITIAL_STATE = {
// Whether or not to show the right panel at all. We split out rooms and groups
// because they're different flows for the user to follow.
showRoomPanel: SettingsStore.getValue("showRightPanelInRoom"),
showGroupPanel: SettingsStore.getValue("showRightPanelInGroup"),
// The last phase (screen) the right panel was showing
lastRoomPhase: SettingsStore.getValue("lastRightPanelPhaseForRoom"),
lastGroupPhase: SettingsStore.getValue("lastRightPanelPhaseForGroup"),
};
const GROUP_PHASES = Object.keys(RIGHT_PANEL_PHASES).filter(k => k.startsWith("Group"));
/**
* A class for tracking the state of the right panel between layouts and
* sessions.
*/
export default class RightPanelStore extends Store {
static _instance;
constructor() {
super(dis);
// Initialise state
this._state = INITIAL_STATE;
}
get isOpenForRoom(): boolean {
return this._state.showRoomPanel;
}
get isOpenForGroup(): boolean {
return this._state.showGroupPanel;
}
get roomPanelPhase(): string {
return this._state.lastRoomPhase;
}
get groupPanelPhase(): string {
return this._state.lastGroupPhase;
}
get visibleRoomPanelPhase(): string {
return this.isOpenForRoom ? this.roomPanelPhase : null;
}
get visibleGroupPanelPhase(): string {
return this.isOpenForGroup ? this.groupPanelPhase : null;
}
_setState(newState) {
this._state = Object.assign(this._state, newState);
SettingsStore.setValue(
"showRightPanelInRoom",
null,
SettingLevel.DEVICE,
this._state.showRoomPanel,
);
SettingsStore.setValue(
"showRightPanelInGroup",
null,
SettingLevel.DEVICE,
this._state.showGroupPanel,
);
if (RIGHT_PANEL_PHASES_NO_ARGS.includes(this._state.lastRoomPhase)) {
SettingsStore.setValue(
"lastRightPanelPhaseForRoom",
null,
SettingLevel.DEVICE,
this._state.lastRoomPhase,
);
}
if (RIGHT_PANEL_PHASES_NO_ARGS.includes(this._state.lastGroupPhase)) {
SettingsStore.setValue(
"lastRightPanelPhaseForGroup",
null,
SettingLevel.DEVICE,
this._state.lastGroupPhase,
);
}
this.__emitChange();
}
__onDispatch(payload) {
if (payload.action !== 'set_right_panel_phase') return;
const targetPhase = payload.phase;
if (!RIGHT_PANEL_PHASES[targetPhase]) {
console.warn(`Tried to switch right panel to unknown phase: ${targetPhase}`);
return;
}
if (GROUP_PHASES.includes(targetPhase)) {
if (targetPhase === this._state.lastGroupPhase) {
this._setState({
showGroupPanel: !this._state.showGroupPanel,
});
} else {
this._setState({
lastGroupPhase: targetPhase,
});
}
} else {
if (targetPhase === this._state.lastRoomPhase) {
this._setState({
showRoomPanel: !this._state.showRoomPanel,
});
} else {
this._setState({
lastRoomPhase: targetPhase,
});
}
}
// Let things like the member info panel actually open to the right member.
dis.dispatch({
action: 'after_right_panel_phase_change',
phase: targetPhase,
...(payload.refireParams || {}),
});
}
static getSharedInstance(): RightPanelStore {
if (!RightPanelStore._instance) {
RightPanelStore._instance = new RightPanelStore();
}
return RightPanelStore._instance;
}
}
|
JavaScript
| 0 |
@@ -3933,32 +3933,74 @@
e: targetPhase,%0A
+ showGroupPanel: true,%0A
@@ -4305,32 +4305,73 @@
e: targetPhase,%0A
+ showRoomPanel: true,%0A
|
f86e9147cf6101cfd07858440ab7b31667ccf8d0
|
update stream: Fix stream name is not updated on editing.
|
src/streams/streamsActions.js
|
src/streams/streamsActions.js
|
/* @flow */
import type { GetState, Dispatch, Stream, InitStreamsAction } from '../types';
import { createStream, updateStream, getStreams, toggleMuteStream, togglePinStream } from '../api';
import { INIT_STREAMS } from '../actionConstants';
import { getAuth } from '../selectors';
export const initStreams = (streams: Stream[]): InitStreamsAction => ({
type: INIT_STREAMS,
streams,
});
export const fetchStreams = () => async (dispatch: Dispatch, getState: GetState) =>
dispatch(initStreams(await getStreams(getAuth(getState()))));
export const createNewStream = (
name: string,
description: string,
principals: string[],
isPrivate: boolean,
) => async (dispatch: Dispatch, getState: GetState) => {
await createStream(getAuth(getState()), name, description, principals, isPrivate);
};
export const updateExistingStream = (
id: number,
initialValues: Object,
newValues: Object,
) => async (dispatch: Dispatch, getState: GetState) => {
if (initialValues.name !== newValues.name) {
await updateStream(getAuth(getState()), id, 'name', newValues.name);
}
if (initialValues.description !== newValues.description) {
await updateStream(getAuth(getState()), id, 'description', newValues.description);
}
if (initialValues.invite_only !== newValues.isPrivate) {
await updateStream(getAuth(getState()), id, 'is_private', newValues.isPrivate);
}
};
export const doTogglePinStream = (streamId: number, value: boolean) => async (
dispatch: Dispatch,
getState: GetState,
) => {
await togglePinStream(getAuth(getState()), streamId, value);
};
export const doToggleMuteStream = (streamId: number, value: boolean) => async (
dispatch: Dispatch,
getState: GetState,
) => {
await toggleMuteStream(getAuth(getState()), streamId, value);
};
|
JavaScript
| 0 |
@@ -997,24 +997,104 @@
ues.name) %7B%0A
+ // Stream names might contain unsafe characters so we must encode it first.%0A
await up
@@ -1134,15 +1134,34 @@
d, '
+new_
name',
+JSON.stringify(
newV
@@ -1171,16 +1171,17 @@
es.name)
+)
;%0A %7D%0A
|
9471b9aa7be9dc04b6e2c4d9684b2078dcf39312
|
Update class name for jsdoc
|
src/ScheduleAPI/ScheduleTypes.js
|
src/ScheduleAPI/ScheduleTypes.js
|
/**
* Created by kgrube on 3/13/2017.
*/
/**
* @private
*/
var Q = require('q'),
inherits = require('util').inherits,
ConnectWise = require('../ConnectWise.js');
/**
* @typedef {object} ScheduleType
* @property {number} id
* @property {string} name - required
* @property {string} identifier - required
* @property {ChargeCodeHref} chargeCode
* @property {ServiceLocationHref} where
* @property {boolean} systemFlag
*
*/
/**
*
* @param {CWOptions} options
* @inherits {ConnectWise}
* @constructor
*/
function ScheduleType(options) {
ConnectWise.apply(this, Array.prototype.slice.call(arguments));
}
inherits(ScheduleType, ConnectWise);
/**
* @param {Params} params
* @returns {Promise<ScheduleType[]>}
*/
ScheduleType.prototype.getScheduleTypes = function (params) {
return this.api('/schedule/types', 'GET', params);
};
/**
*
* @param {ScheduleEntry} scheduleType
* @returns {Promise<ScheduleType>}
*/
ScheduleType.prototype.createScheduleType = function (scheduleType) {
return this.api('/schedule/types', 'POST', scheduleType);
};
/**
*
* @param {ParamsConditions} params
* @returns {Promise<Count>}
*/
ScheduleType.prototype.getScheduleTypesCount = function (params) {
return this.api('/schedule/types/count', 'GET', params);
};
/**
*
* @param scheduleTypeId
* @returns {Promise<ScheduleType>}
*/
ScheduleType.prototype.getScheduleTypeById = function(scheduleTypeId) {
return this.api('/schedule/types/' + scheduleTypeId, 'GET');
};
/**
*
* @param scheduleTypeId
* @returns {Promise<DeleteResponse>}
*/
ScheduleType.prototype.deleteScheduleTypeById = function(scheduleTypeId) {
return this.api('/schedule/types/' + scheduleTypeId, 'DELETE');
};
/**
*
* @param scheduleTypeId
* @param {ScheduleType} scheduleType
* @returns {Promise<ScheduleType>}
*/
ScheduleType.prototype.replaceScheduleType = function(scheduleTypeId, scheduleType) {
return this.api('/schedule/types/' + scheduleTypeId, 'PUT', scheduleType);
};
/**
* @param scheduleTypeId
* @param {Operations} ops
* @returns {Promise<ScheduleType>}
*/
ScheduleType.prototype.updateScheduleType = function(scheduleTypeId, ops) {
return this.api('/schedule/types/' + scheduleTypeId, 'PATCH', ops);
};
/**
*
* @type {ScheduleType}
*/
module.exports = ScheduleType;
|
JavaScript
| 0 |
@@ -538,16 +538,17 @@
duleType
+s
(options
@@ -640,16 +640,17 @@
duleType
+s
, Connec
@@ -734,32 +734,33 @@
*/%0AScheduleType
+s
.prototype.getSc
@@ -940,32 +940,33 @@
*/%0AScheduleType
+s
.prototype.creat
@@ -1151,32 +1151,33 @@
*/%0AScheduleType
+s
.prototype.getSc
@@ -1354,32 +1354,33 @@
*/%0AScheduleType
+s
.prototype.getSc
@@ -1568,32 +1568,33 @@
*/%0AScheduleType
+s
.prototype.delet
@@ -1824,32 +1824,33 @@
*/%0AScheduleType
+s
.prototype.repla
@@ -2096,16 +2096,17 @@
duleType
+s
.prototy
@@ -2265,16 +2265,17 @@
duleType
+s
%7D%0A */%0Amo
@@ -2301,10 +2301,11 @@
duleType
+s
;%0A
|
1fd94e643cd8760611aebc436378ba5d49b84a1c
|
Add ParticleSystem.perturb utility
|
src/systems/ParticleSystem.js
|
src/systems/ParticleSystem.js
|
lib.ParticleSystem = ParticleSystem;
function ParticleSystem(particles, iterations) {
var isCount = typeof particles === 'number';
var length = isCount ? particles * 3 : particles.length;
var count = length / 3;
var positions = isCount ? length : particles;
this.positions = new Float32Array(positions);
this.positionsPrev = new Float32Array(positions);
this.accumulatedForces = new Float32Array(length);
this.weights = new Float32Array(count);
this.setWeights(1);
this._iterations = iterations || 1;
this._count = count;
this._globalConstraints = [];
this._localConstraints = [];
this._pinConstraints = [];
this._forces = [];
}
ParticleSystem.create = lib.ctor(ParticleSystem);
ParticleSystem.prototype.setPosition = function (i, x, y, z) {
lib.Vec3.set(this.positions, i, x, y, z);
lib.Vec3.set(this.positionsPrev, i, x, y, z);
};
ParticleSystem.prototype.getPosition = function (i, out) {
return lib.Vec3.get(this.positions, i, out);
};
ParticleSystem.prototype.getDistance = function (a, b) {
return lib.Vec3.distance(this.positions, a, b);
};
ParticleSystem.prototype.getAngle = function (a, b, c) {
return lib.Vec3.angle(this.positions, a, b, c);
};
ParticleSystem.prototype.setWeight = function (i, w) {
this.weights[i] = w;
};
ParticleSystem.prototype.setWeights = function (w) {
var weights = this.weights;
for (var i = 0, il = weights.length; i < il; i ++) {
weights[i] = w;
}
};
ParticleSystem.prototype.each = function (iterator, context) {
context = context || this;
for (var i = 0, il = this._count; i < il; i ++) {
iterator.call(context, i, this);
}
};
// Verlet integration
// ------------------
function ps_integrateParticle(i, p0, p1, f0, d2) {
var pt = p0[i];
p0[i] += pt - p1[i] + f0[i] * d2;
p1[i] = pt;
}
ParticleSystem.prototype.integrate = function (delta) {
var d2 = delta * delta;
var p0 = this.positions;
var p1 = this.positionsPrev;
var f0 = this.accumulatedForces;
for (var i = 0, il = this._count * 3; i < il; i += 3) {
ps_integrateParticle(i, p0, p1, f0, d2);
ps_integrateParticle(i + 1, p0, p1, f0, d2);
ps_integrateParticle(i + 2, p0, p1, f0, d2);
}
};
// Constraints
// -----------
ParticleSystem.prototype._getConstraintBuffer = function (constraint) {
return constraint._isGlobal ? this._globalConstraints : this._localConstraints;
};
ParticleSystem.prototype.addConstraint = function (constraint) {
this._getConstraintBuffer(constraint).push(constraint);
};
ParticleSystem.prototype.removeConstraint = function (constraint) {
lib.Collection.removeAll(this._getConstraintBuffer(constraint), constraint);
};
ParticleSystem.prototype.addPinConstraint = function (constraint) {
this._pinConstraints.push(constraint);
};
ParticleSystem.prototype.removePinConstraint = function (constraint) {
lib.Collection.removeAll(this._pinConstraints, constraint);
};
ParticleSystem.prototype.satisfyConstraints = function () {
var iterations = this._iterations;
var global = this._globalConstraints;
var local = this._localConstraints;
var pins = this._pinConstraints;
var p0 = this.positions;
var p1 = this.positionsPrev;
var w0 = this.weights;
var i, il, j, jl, k;
for (k = 0; k < iterations; k ++) {
// Global
for (i = 0, il = this._count * 3; i < il; i += 3) {
for (j = 0, jl = global.length; j < jl; j ++) {
global[j].applyConstraint(i, p0, p1, w0);
}
}
// Local
for (i = 0, il = local.length; i < il; i ++) {
local[i].applyConstraint(p0, p1, w0);
}
// Pins
if (!pins.length) { continue; }
for (i = 0, il = pins.length; i < il; i ++) {
pins[i].applyConstraint(p0, p1, w0);
}
}
};
// Forces
// ------
ParticleSystem.prototype.addForce = function (force) {
this._forces.push(force);
};
ParticleSystem.prototype.removeForce = function (force) {
lib.Collection.removeAll(this._forces, force);
};
ParticleSystem.prototype.accumulateForces = function (delta) {
var forces = this._forces;
var f0 = this.accumulatedForces;
var p0 = this.positions;
var p1 = this.positionsPrev;
var w0 = this.weights;
var ix, w;
for (var i = 0, il = this._count; i < il; i ++) {
ix = i * 3;
w = w0[i];
f0[ix] = f0[ix + 1] = f0[ix + 2] = 0;
for (var j = 0, jl = forces.length; j < jl; j ++) {
forces[j].applyForce(ix, f0, p0, p1, w);
}
}
};
ParticleSystem.prototype.tick = function (delta) {
this.accumulateForces(delta);
this.integrate(delta);
this.satisfyConstraints();
};
|
JavaScript
| 0 |
@@ -1635,16 +1635,314 @@
%7D%0A%7D;%0A%0A
+ParticleSystem.prototype.perturb = function (scale) %7B%0A var positions = this.positions;%0A var positionsPrev = this.positionsPrev;%0A var dist;%0A%0A for (var i = 0, il = positions.length; i %3C il; i ++) %7B%0A dist = Math.random() * scale;%0A positions%5Bi%5D += dist;%0A positionsPrev%5Bi%5D += dist;%0A %7D%0A%7D;%0A%0A
// Verle
|
38852cc9482c2e5225c253a860caa17c1ea819c8
|
Support touch devices
|
player/slitherlink2/applet.js
|
player/slitherlink2/applet.js
|
function Applet(canvas, controller, board) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.controller = controller;
this.board = board;
var self = this;
if (canvas.addEventListener) {
canvas.addEventListener("mousedown", function (event) {
var x = event.clientX, y = event.clientY, button = (event.button == 2);
var rect = event.target.getBoundingClientRect();
self.mouseDown(x - rect.left, y - rect.top, button);
});
canvas.addEventListener("mousemove", function (event) {
var x = event.clientX, y = event.clientY, button = (event.button == 2);
var rect = event.target.getBoundingClientRect();
self.mouseMove(x - rect.left, y - rect.top, button);
});
canvas.addEventListener("mouseup", function (event) {
var x = event.clientX, y = event.clientY, button = (event.button == 2);
var rect = event.target.getBoundingClientRect();
self.mouseUp(x - rect.left, y - rect.top, button);
});
canvas.addEventListener("contextmenu", function (e) { e.preventDefault(); });
}
controller.setCanvas(canvas);
controller.setApplet(this);
controller.drawPanel();
board.setCanvas(canvas);
board.setApplet(this);
board.drawPanel();
}
Applet.prototype.resize = function (width, height) {
if (this.canvas.width != width || this.canvas.height != height) {
this.canvas.width = width;
this.canvas.height = height;
this.controller.drawPanel();
this.board.drawPanel();
}
}
Applet.prototype.mouseDown = function (x, y, b) {
if (y < this.controller.height) this.controller.mouseDown(x, y, b);
else this.board.mouseDown(x, y - this.controller.height, b);
}
Applet.prototype.mouseMove = function (x, y, b) {
if (y < this.controller.height) this.controller.mouseMove(x, y, b);
else this.board.mouseMove(x, y - this.controller.height, b);
}
Applet.prototype.mouseUp = function (x, y, b) {
if (y < this.controller.height) this.controller.mouseUp(x, y, b);
else this.board.mouseUp(x, y - this.controller.height, b);
}
|
JavaScript
| 0 |
@@ -492,363 +492,1267 @@
er(%22
-mousemove%22, function (event) %7B%0D%0A%09%09%09var x = event.clientX, y = event.clientY, button = (event.button == 2);%0D%0A%09%09%09var rect = event.target.getBoundingClientRect();%0D%0A%09%09%09self.mouseMove(x - rect.left, y - rect.top, button);%0D%0A%09%09%7D);%0D%0A%09%09canvas.addEventListener(%22mouseup%22, function (event) %7B%0D%0A%09%09%09var x = event.clientX, y = event.clientY, button = (event.button == 2)
+touchstart%22, function (event) %7B%0D%0A%09%09%09event.preventDefault();%0D%0A%09%09%09var x = event.changedTouches%5B0%5D.clientX, y = event.changedTouches%5B0%5D.clientY, button = false;%0D%0A%09%09%09var rect = event.target.getBoundingClientRect();%0D%0A%09%09%09self.mouseDown(x - rect.left, y - rect.top, button);%0D%0A%09%09%7D);%0D%0A%09%09canvas.addEventListener(%22mousemove%22, function (event) %7B%0D%0A%09%09%09var x = event.clientX, y = event.clientY, button = (event.button == 2);%0D%0A%09%09%09var rect = event.target.getBoundingClientRect();%0D%0A%09%09%09self.mouseMove(x - rect.left, y - rect.top, button);%0D%0A%09%09%7D);%0D%0A%09%09canvas.addEventListener(%22touchmove%22, function (event) %7B%0D%0A%09%09%09event.preventDefault();%0D%0A%09%09%09var x = event.changedTouches%5B0%5D.clientX, y = event.changedTouches%5B0%5D.clientY, button = false;%0D%0A%09%09%09var rect = event.target.getBoundingClientRect();%0D%0A%09%09%09self.mouseMove(x - rect.left, y - rect.top, button);%0D%0A%09%09%7D);%0D%0A%09%09canvas.addEventListener(%22mouseup%22, function (event) %7B%0D%0A%09%09%09var x = event.clientX, y = event.clientY, button = (event.button == 2);%0D%0A%09%09%09var rect = event.target.getBoundingClientRect();%0D%0A%09%09%09self.mouseUp(x - rect.left, y - rect.top, button);%0D%0A%09%09%7D);%0D%0A%09%09canvas.addEventListener(%22touchend%22, function (event) %7B%0D%0A%09%09%09event.preventDefault();%0D%0A%09%09%09var x = event.changedTouches%5B0%5D.clientX, y = event.changedTouches%5B0%5D.clientY, button = false
;%0D%0A%09
|
0ea85ca5255be4021d6fca470219d8a7567c40e1
|
Fix rowData overrite bug
|
plugins/ng-grid-csv-export.js
|
plugins/ng-grid-csv-export.js
|
// Todo:
// 1) Make the button prettier
// 2) add a config option for IE users which takes a URL. That URL should accept a POST request with a
// JSON encoded object in the payload and return a CSV. This is necessary because IE doesn't let you
// download from a data-uri link
//
// Notes: This has not been adequately tested and is very much a proof of concept at this point
function ngGridCsvExportPlugin (opts) {
var self = this;
self.grid = null;
self.scope = null;
self.services = null;
opts = opts || {};
opts.containerPanel = opts.containerPanel || '.ngFooterPanel';
opts.linkClass = opts.linkCss || 'csv-data-link-span';
opts.linkLabel = opts.linkLabel || 'CSV Export';
opts.fileName = opts.fileName || 'Export.csv';
self.init = function(scope, grid, services) {
self.grid = grid;
self.scope = scope;
self.services = services;
function showDs() {
function csvStringify(str) {
if (str == null) { // we want to catch anything null-ish, hence just == not ===
return '';
}
if (typeof(str) === 'number') {
return '' + str;
}
if (typeof(str) === 'boolean') {
return (str ? 'TRUE' : 'FALSE') ;
}
if (typeof(str) === 'string') {
return str.replace(/"/g,'""');
}
return JSON.stringify(str).replace(/"/g,'""');
}
var keys = [];
var csvData = '';
for (var f in grid.config.columnDefs) {
if (grid.config.columnDefs.hasOwnProperty(f))
{
keys.push(grid.config.columnDefs[f].field);
csvData += '"' ;
if(typeof grid.config.columnDefs[f].displayName !== 'undefined'){/** moved to reduce looping and capture the display name if it exists**/
csvData += csvStringify(grid.config.columnDefs[f].displayName);
}
else{
csvData += csvStringify(grid.config.columnDefs[f].field);
}
csvData += '",';
}
}
function swapLastCommaForNewline(str) {
var newStr = str.substr(0,str.length - 1);
return newStr + "\n";
}
csvData = swapLastCommaForNewline(csvData);
var gridData = grid.data;
for (var gridRow in gridData) {
var rowData = '';
for ( var k in keys) {
var curCellRaw;
if (opts != null && opts.columnOverrides != null && opts.columnOverrides[keys[k]] != null) {
curCellRaw = opts.columnOverrides[keys[k]](
self.services.UtilityService.evalProperty(gridData[gridRow], keys[k]));
} else {
curCellRaw = self.services.UtilityService.evalProperty(gridData[gridRow], keys[k]);
}
rowData += '"' + csvStringify(curCellRaw) + '",';
}
csvData = swapLastCommaForNewline(rowData);
}
var fp = grid.$root.find(opts.containerPanel);
var csvDataLinkPrevious = grid.$root.find(opts.containerPanel + ' .' + opts.linkClass);
if (csvDataLinkPrevious != null) {csvDataLinkPrevious.remove() ; }
var csvDataLinkHtml = '<span class="' + opts.linkClass + '">';
csvDataLinkHtml += '<br><a href="data:text/csv;charset=UTF-8,';
csvDataLinkHtml += encodeURIComponent(csvData);
csvDataLinkHtml += '" download="' + opts.fileName + '">' + opts.linkLabel + '</a></br></span>' ;
fp.append(csvDataLinkHtml);
}
setTimeout(showDs, 0);
scope.catHashKeys = function() {
var hash = '';
for (var idx in scope.renderedRows) {
hash += scope.renderedRows[idx].$$hashKey;
}
return hash;
};
if (opts && opts.customDataWatcher) {
scope.$watch(opts.customDataWatcher, showDs);
} else {
scope.$watch(scope.catHashKeys, showDs);
}
};
}
|
JavaScript
| 0 |
@@ -3293,32 +3293,33 @@
csvData
++
= swapLastCommaF
|
dd9f16a3c6d219cb642b9e7e419b8eb45fb752b4
|
Update index.js
|
src/traces/indicator/index.js
|
src/traces/indicator/index.js
|
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
moduleType: 'trace',
name: 'indicator',
basePlotModule: require('./base_plot'),
categories: ['svg', 'noOpacity', 'noHover'],
animatable: true,
attributes: require('./attributes'),
supplyDefaults: require('./defaults').supplyDefaults,
calc: require('./calc').calc,
plot: require('./plot'),
meta: {
description: [
'An indicator is used to visualize single a `value` along with some',
'contextual information such as `steps` or a `threshold`, using a',
'combination of three visual elements: a number, a delta, and/or a gauge.',
'Deltas are taken with respect to a `reference`.',
'Gauges can be either angular or bullet (aka linear) gauges.'
].join(' ')
}
};
|
JavaScript
| 0.000002 |
@@ -635,17 +635,17 @@
ize
+a
single
-a
%60val
|
e02ab03f2c022d4915fcacbd70c40128f0074f31
|
fix full storage changes
|
src/ui/FullStoragesChanges.js
|
src/ui/FullStoragesChanges.js
|
'use strict'
var DropdownPanel = require('./DropdownPanel')
var yo = require('yo-yo')
function FullStoragesChanges (_parent, _traceManager) {
this.parent = _parent
this.traceManager = _traceManager
this.addresses = []
this.view
this.traceLength
this.basicPanel = new DropdownPanel('Full Storages Changes')
this.init()
}
FullStoragesChanges.prototype.render = function () {
var view = yo`<div id='fullstorageschangespanel' >${this.basicPanel.render()}</div>`
if (!this.view) {
this.view = view
}
return view
}
FullStoragesChanges.prototype.init = function () {
var self = this
this.parent.event.register('newTraceLoaded', this, function (length) {
self.panels = []
self.traceManager.getAddresses(function (error, addresses) {
if (!error) {
self.addresses = addresses
self.basicPanel.update({})
}
})
self.traceManager.getLength(function (error, length) {
if (!error) {
self.traceLength = length
}
})
})
this.parent.event.register('indexChanged', this, function (index) {
if (index < 0) return
if (self.parent.currentStepIndex !== index) return
if (index === self.traceLength - 1) {
var storageJSON = {}
for (var k in self.addresses) {
self.traceManager.getStorageAt(index, null, function (error, result) {
if (!error) {
storageJSON[self.addresses[k]] = result
self.basicPanel.update(storageJSON)
}
}, self.addresses[k])
}
}
})
}
module.exports = FullStoragesChanges
|
JavaScript
| 0.000001 |
@@ -1308,12 +1308,22 @@
ex,
-null
+this.parent.tx
, fu
|
9509b14005683280a02a7bd7a394a5710d55bff0
|
Add support to words with uppercase letters
|
src/utils/ExtractWordsUtil.js
|
src/utils/ExtractWordsUtil.js
|
var addWord = function (words, word) {
if (word.length > 0) {
words.push(word);
}
};
var ExtractWordsUtil = {
getAllWordsInContent: function (content) {
var used = {
// Always include html and body.
html: true,
body: true
};
var word = '';
for (var i = 0; i < content.length; i++) {
var chr = content[i];
if (chr.match(/[a-z]+/)) {
word += chr;
} else {
used[word] = true;
word = '';
}
}
used[word] = true;
return used;
},
getAllWordsInSelector: function (selector) {
// Remove attr selectors. "a[href...]"" will become "a".
selector = selector.replace(/\[(.+?)\]/g, '').toLowerCase();
// If complex attr selector (has a bracket in it) just leave
// the selector in. ¯\_(ツ)_/¯
if (selector.indexOf('[') !== -1 || selector.indexOf(']') !== -1) {
return [];
}
var words = [];
var word = '';
var skipNextWord = false;
for (var i = 0; i < selector.length; i++) {
var letter = selector[i];
if (skipNextWord && (letter !== '.' || letter !== '#' || letter !== ' ')) {
continue;
}
// If pseudoclass or universal selector, skip the next word
if (letter === ':' || letter === '*') {
addWord(words, word);
word = '';
skipNextWord = true;
continue;
}
if (letter.match(/[a-z]+/)) {
word += letter;
} else {
addWord(words, word);
word = '';
skipNextWord = false;
}
}
addWord(words, word);
return words;
}
};
module.exports = ExtractWordsUtil;
|
JavaScript
| 0.000053 |
@@ -348,16 +348,30 @@
ntent%5Bi%5D
+.toLowerCase()
;%0A%0A
@@ -1059,16 +1059,30 @@
ector%5Bi%5D
+.toLowerCase()
;%0A%0A
|
7302ad10418ba5a20442dbd6555e496dd77ba487
|
apply rotation and parent transform
|
src/tilemaps/staticlayer/StaticTilemapLayerWebGLRenderer.js
|
src/tilemaps/staticlayer/StaticTilemapLayerWebGLRenderer.js
|
/**
* @author Richard Davey <[email protected]>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Renders this Game Object with the WebGL Renderer to the given Camera.
*
* The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera.
* This method should not be called directly. It is a utility function of the Render module.
*
* A Static Tilemap Layer renders immediately and does not use any batching.
*
* @method Phaser.Tilemaps.StaticTilemapLayer#renderWebGL
* @since 3.0.0
* @private
*
* @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer.
* @param {Phaser.Tilemaps.StaticTilemapLayer} src - The Game Object being rendered in this call.
* @param {number} interpolationPercentage - Reserved for future use and custom pipelines.
* @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object.
*/
var StaticTilemapLayerWebGLRenderer = function (renderer, src, interpolationPercentage, camera)
{
var tilesets = src.tileset;
var pipeline = src.pipeline;
var pipelineVertexBuffer = pipeline.vertexBuffer;
renderer.setPipeline(pipeline);
pipeline.modelIdentity();
pipeline.modelTranslate(src.x - (camera.scrollX * src.scrollFactorX), src.y - (camera.scrollY * src.scrollFactorY), 0);
pipeline.modelScale(src.scaleX, src.scaleY, 1);
pipeline.viewLoad2D(camera.matrix.matrix);
for (var i = 0; i < tilesets.length; i++)
{
src.upload(camera, i);
if (src.vertexCount[i] > 0)
{
if (renderer.currentPipeline && renderer.currentPipeline.vertexCount > 0)
{
renderer.flush();
}
pipeline.vertexBuffer = src.vertexBuffer[i];
renderer.setPipeline(pipeline);
renderer.setTexture2D(tilesets[i].glTexture, 0);
renderer.gl.drawArrays(pipeline.topology, 0, src.vertexCount[i]);
}
}
// Restore the pipeline
pipeline.vertexBuffer = pipelineVertexBuffer;
pipeline.viewIdentity();
pipeline.modelIdentity();
};
module.exports = StaticTilemapLayerWebGLRenderer;
|
JavaScript
| 0 |
@@ -1027,16 +1027,151 @@
Object.%0A
+ * @param %7BPhaser.GameObjects.Components.TransformMatrix%7D parentMatrix - This transform matrix is defined if the game object is nested%0A
*/%0Avar
@@ -1260,16 +1260,30 @@
, camera
+, parentMatrix
)%0A%7B%0A
@@ -1444,71 +1444,731 @@
-pipeline.modelIdentity(
+var camMatrix = renderer._tempMatrix1;%0A var layerMatrix = renderer._tempMatrix2;%0A var calcMatrix = renderer._tempMatrix3;%0A%0A layerMatrix.applyITRS(src.x, src.y, src.rotation, src.scaleX, src.scaleY);%0A%0A camMatrix.copyFrom(camera.matrix
);%0A
+%0A
-pipeline.modelTranslate(src.x - (
+if (parentMatrix)%0A %7B%0A // Multiply the camera by the parent matrix%0A camMatrix.multiplyWithOffset(parentMatrix, -camera.scrollX * src.scrollFactorX, -camera.scrollY * src.scrollFactorY);%0A%0A // Undo the camera scroll%0A layerMatrix.e = src.x;%0A layerMatrix.f = src.y;%0A%0A // Multiply by the layer matrix, store result in calcMatrix%0A camMatrix.multiply(layerMatrix, calcMatrix);%0A %7D%0A else%0A %7B%0A layerMatrix.e -=
came
@@ -2201,20 +2201,35 @@
torX
-), src.y - (
+;%0A layerMatrix.f -=
came
@@ -2262,66 +2262,412 @@
torY
-), 0);%0A pipeline.modelScale(src.scaleX, src.scaleY, 1);
+;%0A%0A // Multiply by the layer matrix, store result in calcMatrix%0A camMatrix.multiply(layerMatrix, calcMatrix);%0A %7D%0A%0A var modelMatrix = pipeline.modelIdentity().modelMatrix;%0A modelMatrix%5B0%5D = calcMatrix.a;%0A modelMatrix%5B1%5D = calcMatrix.b;%0A modelMatrix%5B4%5D = calcMatrix.c;%0A modelMatrix%5B5%5D = calcMatrix.d;%0A modelMatrix%5B12%5D = calcMatrix.e;%0A modelMatrix%5B13%5D = calcMatrix.f;%0A
%0A
|
1bdde269d73f3fe97499d0f3bf80e5e678e7b393
|
fix speech
|
public/js/index.controller.js
|
public/js/index.controller.js
|
//Speech recognition for search input field
if (!('webkitSpeechRecognition' in window)) {
// handling if the browser doesn´t support speech recognition
function startSpeechRecognition (event) {
speechImage.src = '/static/img/mic-slash.gif';
alert("Speech recognition is not enabled in your Browser! Please use the latest Version of Chrome!");
}
} else {
var recognition = new webkitSpeechRecognition();
var recognizing = false;
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = 'de-DE';
recognition.onstart = function() {
recognizing = true;
speechImage.src = '/static/img/mic-animate.gif';
}
recognition.onresult = function(event) {
searchText.text = "result";
alert(event);
}
//error handling
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
alert('No speech was detected. You may need to adjust your microphone settings!');
}
if (event.error == 'audio-capture') {
alert(' No microphone was found. Ensure that a microphone is installed and that microphone settings are configured correctly!');
}
if (event.error == 'not-allowed') {
alert('Permission to use microphone is blocked. To change, go to chrome://settings/contentExceptions#media-stream');
}
speechImage.src = '/static/img/mic.gif';
};
recognition.onend = function() {
recognizing = false;
speechImage.src = '/static/img/mic.gif';
}
function startSpeechRecognition (event) {
//check if speech recognition is already running
if (true) {
speechImage.src = '/static/img/mic-slash.gif';
alert('Spracheingabe gestartet!');
recognition.start();
};
}
}
//**********************************************************************************
//Drag and Drop Event Handling
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var id = ev.dataTransfer.getData("text");
requestPlayerDetail(id);
}
//****************************************************************************************
//make httpRequest to get the list of all players and create the list to choose from
//at the moment a list of buttons is created
var httpRequest;
var playerList;
//start httpRequest to server
function requestPlayerList() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
//call function to handle the returned data
httpRequest.onreadystatechange = createPlayerList;
//path where JSON data is provided on server
httpRequest.open('GET', '/playerdata/general/playerData.pd');
httpRequest.send();
}
//function to handle the returned JSON file
function createPlayerList() {
//check if httpRequest was successful
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
//put received JSON file into variable and parse it
if(playerList == undefined) {
playerList = JSON.parse(httpRequest.responseText);
}
//create a string with HTML code, which will turn into a List of all Players from the JSON
//start of the List
var out = "<ul style='list-style: none;padding:0;margin:0;'>";
// get search string
var searchString = document.getElementById('searchText').value;
//loop through the players in the JSON file
for (var player in playerList) {
if ((playerList[player].playername.toUpperCase().match(searchString.toUpperCase().replace(" ", "(.)*")))) {
//create a button with id and onclick for each player ( the function called by onclick will get you detailed info on the player of the button)
out += "<li><div class= 'playerBox'><img src=" + playerList[player].imageurl + " id=" + playerList[player].filename + " draggable='true' ondragstart='drag(event)' ></img><p>" + playerList[player].playername + "</p></div></li>";
}
};
//end the list
out += "</ul>"
//bring the code to create the List of Buttons into the HTML-Webpage
document.getElementById("playerColumn").innerHTML = out;
} else {
alert('There was a problem with the get playerList request.');
}
}
}
requestPlayerList();
//**************************************************************************************
//make httpRequest to server to get detail information JSON for a specific player
function requestPlayerDetail(filename) {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = writePlayerDetail;
//path where the detail JSON is provided
httpRequest.open('GET', '/playerdata/' + filename + '.pd');
httpRequest.send();
}
//handle Detail JSON file, when it is returned
function writePlayerDetail() {
//check if httpRequest was successful
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
//put JSON into var and parse it
var player = JSON.parse(httpRequest.responseText);
//write JSON content into Element on Webpage as a table
document.getElementById("textDetails").innerHTML =
"<img src="+player.PictureURL+" style='width:160px;height:200;'><img>"+
"<table style='margin-left:auto; margin-right:auto;'>"+
"<tr><td>Spielername:</td><td>" + player.Name +
"</td></tr><tr><td>Größe:</td><td>" + player.Groesse +
"</td></tr><tr><td>Nationalität:</td><td>" + player.Nationalitaet +
"</td></tr><tr><td>Verein:</td><td>" + player.Verein +
"</td></tr><tr><td>Im Team seit:</td><td>" + player.ImTeamSeit +
"</td></tr><tr><td>Schuhgrösse:</td><td>" + player.Schuhgroesse +
"</td></tr><tr><td>Schuhmodell:</td><td>" + player.Schuhmodell +
"</td></tr><tr><td>Position:</td><td>" + player.Position +
"</td></tr><tr><td>Vertrag bis:</td><td>" + player.VertragBis +
"</td></tr><tr><td>Aktueller Marktwert:</td><td>" + player.AktuellerMarktwert +
"</td></tr><tr><td>Geburtsdatum:</td><td>" + player.Geburtsdatum +
"</td></tr><tr><td>Schussfuss:</td><td>" + player.Schussfuss +
"</td></tr><tr><td>Alter:</td><td>" + player.Alter +
"</td></tr><tr><td>Höchster Marktwert:</td><td>" + player.HoechsterMarktwert +
"</td></tr><tr><td>Geburtsort:</td><td>" + player.Geburtsort +
"</td></tr><tr><td>Spielerberater:</td><td>" + player.Spielerberater +
"</td></tr><tr><td>Ausruester:</td><td>" + player.Ausruester +
"</td></tr></table>";
} else {
alert('There was a problem with the playerInfo request.');
}
}
}
|
JavaScript
| 0.000262 |
@@ -720,20 +720,21 @@
rchText.
-text
+value
= %22resu
|
5f5b3149674b48674b6c0a6b7ac5844df281734a
|
Test non-null uri passed to onOpenStart from cache
|
test/BranchSubscriber.test.js
|
test/BranchSubscriber.test.js
|
import { NativeModules } from 'react-native'
const { RNBranch } = NativeModules
import { BranchSubscriber } from 'react-native-branch'
test('default initializes with no options', () => {
const subscriber = new BranchSubscriber(null)
expect(subscriber.options).toEqual({})
})
test('stores options passed to the constructor', () => {
const subscriber = new BranchSubscriber({
checkCachedEvents: false
})
expect(subscriber.options).toEqual({ checkCachedEvents: false })
})
test('subscribes to init session start events', () => {
const subscriber = new BranchSubscriber({
checkCachedEvents: false,
onOpenStart: ({uri}) => {},
})
subscriber._nativeEventEmitter.addListener = jest.fn((eventType, listener) => {})
subscriber.subscribe()
expect(subscriber._nativeEventEmitter.addListener.mock.calls.length).toBe(1)
expect(subscriber._nativeEventEmitter.addListener.mock.calls[0][0]).toBe(RNBranch.INIT_SESSION_START)
expect(subscriber._nativeEventEmitter.addListener.mock.calls[0][1]).toBe(subscriber.options.onOpenStart)
})
test('subscribes to init session success & error events', () => {
const subscriber = new BranchSubscriber({
checkCachedEvents: false,
onOpenComplete: ({params, error, uri}) => {},
})
subscriber._nativeEventEmitter.addListener = jest.fn((eventType, listener) => {})
subscriber.subscribe()
expect(subscriber._nativeEventEmitter.addListener.mock.calls.length).toBe(2)
// This comparison ignores the call order.
const mockArgs = subscriber._nativeEventEmitter.addListener.mock.calls.map(call => call[0]).sort()
expect(mockArgs).toEqual([
RNBranch.INIT_SESSION_ERROR,
RNBranch.INIT_SESSION_SUCCESS,
])
expect(subscriber._nativeEventEmitter.addListener.mock.calls[0][1]).toBe(subscriber.options.onOpenComplete)
expect(subscriber._nativeEventEmitter.addListener.mock.calls[1][1]).toBe(subscriber.options.onOpenComplete)
})
// async test
test('will return a cached event when appropriate', done => {
const mockResult = {
params: {
'+clicked_branch_link': false,
'+is_first_session': false,
},
error: null,
uri: null,
}
//* Mock promise from redeemInitSessionResult
RNBranch.redeemInitSessionResult.mockReturnValueOnce(Promise.resolve(mockResult))
// */
// Set up subscriber, mocking the callbacks
const subscriber = new BranchSubscriber({
checkCachedEvents: true,
onOpenStart: jest.fn(({uri}) => {}),
onOpenComplete: jest.fn(({params, error, uri}) => {}),
})
// mock subscriber._nativeEventEmitter.addListener.
// TODO: Brittle test
// Expect first onOpenStart, then onOpenComplete, then _nativeEventEmitter.addListener three times,
// with INIT_SESSION_ERROR last.
subscriber._nativeEventEmitter.addListener = (eventType, listener) => {
if (eventType !== RNBranch.INIT_SESSION_ERROR) return
// --- Check results ---
// Expect onOpenStart and onOpenComplete both to be called
// uri passed to onOpenStart
expect(subscriber.options.onOpenStart.mock.calls.length).toBe(1)
expect(subscriber.options.onOpenStart.mock.calls[0][0]).toEqual({uri: null})
// full result passed to onOpenComplete
expect(subscriber.options.onOpenComplete.mock.calls.length).toBe(1)
expect(subscriber.options.onOpenComplete.mock.calls[0][0]).toEqual(mockResult)
// state cleared
expect(subscriber._checkCachedEvents).toBe(false)
done()
}
expect(subscriber._checkCachedEvents).toBe(true)
// --- Code under test ---
subscriber.subscribe()
})
|
JavaScript
| 0 |
@@ -2141,17 +2141,16 @@
%7D%0A%0A //
-*
Mock pr
@@ -2184,16 +2184,16 @@
nResult%0A
+
RNBran
@@ -2271,16 +2271,8 @@
lt))
-%0A // */
%0A%0A
@@ -3342,16 +3342,16 @@
cleared%0A
-
expe
@@ -3517,12 +3517,1289 @@
scribe()%0A%7D)%0A
+%0Atest('passes a non-null uri to onOpenStart when available', () =%3E %7B%0A const mockResult = %7B%0A params: %7B%0A '+clicked_branch_link': true,%0A '+is_first_session': false,%0A %7D,%0A error: null,%0A uri: 'https://abcd.app.link/xyz',%0A %7D%0A%0A // Mock promise from redeemInitSessionResult%0A RNBranch.redeemInitSessionResult.mockReturnValueOnce(Promise.resolve(mockResult))%0A%0A // Set up subscriber, mocking the callbacks%0A const subscriber = new BranchSubscriber(%7B%0A checkCachedEvents: true,%0A onOpenStart: jest.fn((%7Buri%7D) =%3E %7B%7D),%0A %7D)%0A%0A // mock subscriber._nativeEventEmitter.addListener.%0A%0A // TODO: Brittle test%0A // Expect first onOpenStart, then onOpenComplete, then _nativeEventEmitter.addListener three times,%0A // with INIT_SESSION_ERROR last.%0A subscriber._nativeEventEmitter.addListener = (eventType, listener) =%3E %7B%0A if (eventType !== RNBranch.INIT_SESSION_ERROR) return%0A%0A // --- Check results ---%0A%0A // Expect onOpenStart to be called%0A // uri passed to onOpenStart%0A expect(subscriber.options.onOpenStart.mock.calls.length).toBe(1)%0A expect(subscriber.options.onOpenStart.mock.calls%5B0%5D%5B0%5D).toEqual(%7Buri: mockResult.uri%7D)%0A%0A done()%0A %7D%0A expect(subscriber._checkCachedEvents).toBe(true)%0A%0A // --- Code under test ---%0A subscriber.subscribe()%0A%7D)%0A
|
aa9368d04f5b64be57bada039014fc5aed55deed
|
Refactor removeSpecialCharacters tests
|
amaranth-chrome-ext/test/AmaranthUtil.test.js
|
amaranth-chrome-ext/test/AmaranthUtil.test.js
|
const AmaranthUtil = require('../src/AmaranthUtil');
test('removeSpecialCharacters: removes space from "hello there!"', () => {
expect(AmaranthUtil.removeSpecialCharacters('hello there!', ' '))
.toBe('hellothere!');
});
test('removeSpecialCharacters: removes spaces from " hello there ! "',
() => {
expect(AmaranthUtil.removeSpecialCharacters(' hello there ! ', ' '))
.toBe('hellothere!');
});
test(`removeSpecialCharacters: removes special characters from
"!@#t$#[(<e#@!*&^()s$#(}]>)*t"`,
() => {
expect(AmaranthUtil
.removeSpecialCharacters('!@#t$#[(<e#@!*&^()s$#(}]>)*t'))
.toBe('test');
});
test('padArray: pads [1,2,3] to [1,2,3,0,0,0,0,0,0,0]', () => {
expect(AmaranthUtil.padArray([1, 2, 3], 10, 0))
.toStrictEqual([1, 2, 3, 0, 0, 0, 0, 0, 0, 0]);
});
test('padArray: pads ["1","2","3"] to ["1","2","3","",""]', () => {
expect(AmaranthUtil.padArray(['1', '2', '3'], 5, ''))
.toStrictEqual(['1', '2', '3', '', '']);
});
test('padArray: pads [] to [{}, {}, {}]', () => {
expect(AmaranthUtil.padArray([], 3, {})).toStrictEqual([{}, {}, {}]);
});
test('padArray: does not pad [1,2,3,4,5] which is longer than desired length',
() => {
expect(AmaranthUtil.padArray([1, 2, 3, 4, 5], 3, 0))
.toStrictEqual([1, 2, 3, 4, 5]);
});
|
JavaScript
| 0 |
@@ -92,195 +92,31 @@
s sp
-ace from %22hello there!%22', () =%3E %7B%0A expect(AmaranthUtil.removeSpecialCharacters('hello there!', ' '))%0A .toBe('hellothere!');%0A%7D);%0A%0Atest('removeSpecialCharacters: removes space
+ecial character
s from %22
he
@@ -111,36 +111,29 @@
s from %22
-
hello
-
+$#@
there
- !
%22',%0A
@@ -195,33 +195,21 @@
rs('
-
hello
- there ! ', '
+$#@there
'))%0A
@@ -235,17 +235,16 @@
llothere
-!
');%0A
@@ -253,17 +253,17 @@
;%0A%0Atest(
-%60
+'
removeSp
@@ -310,21 +310,26 @@
ers from
+ ' +
%0A
+'
%22!@#t$#%5B
@@ -354,9 +354,9 @@
)*t%22
-%60
+'
,%0A()
@@ -382,23 +382,16 @@
anthUtil
-%0A
.removeS
|
ee5d8bc2469580a78430a3340fa6f19e05d81e35
|
Remove unused code from line graph view
|
app/common/views/visualisations/line-graph.js
|
app/common/views/visualisations/line-graph.js
|
define([
'extensions/views/graph/graph',
'extensions/views/graph/linelabel'
],
function (Graph, LineLabel) {
var LineGraph = Graph.extend({
components: function () {
var labelComponent, labelOptions, yAxisOptions;
if (this.isOneHundredPercent()) {
labelComponent = LineLabel;
labelOptions = {
showValues: true,
showValuesPercentage: true,
isLineGraph: true,
showOriginalValues: true,
showSummary: false
};
yAxisOptions = {
tickFormat: function () {
return function (d) {
return d * 100 + '%';
};
}
};
} else {
labelComponent = this.sharedComponents.linelabel;
}
labelComponent = this.sharedComponents.linelabel;
return {
axis: { view: this.sharedComponents.xaxis },
yaxis: {
view: this.sharedComponents.yaxis,
options: yAxisOptions
},
linelabel: {
view: labelComponent,
options: labelOptions
},
line: {
view: this.sharedComponents.line,
options: {
interactive: function (e) {
return e.slice % 3 !== 2;
}
}
},
callout: {
view: this.sharedComponents.callout,
options: {
showPercentage: this.isOneHundredPercent()
}
},
hover: { view: this.sharedComponents.hover }
};
}
});
return LineGraph;
});
|
JavaScript
| 0 |
@@ -38,46 +38,8 @@
aph'
-,%0A 'extensions/views/graph/linelabel'
%0A%5D,%0A
@@ -57,19 +57,8 @@
raph
-, LineLabel
) %7B%0A
@@ -130,32 +130,16 @@
var
- labelComponent,
labelOp
@@ -159,16 +159,17 @@
ptions;%0A
+%0A
if
@@ -204,44 +204,8 @@
) %7B%0A
- labelComponent = LineLabel;%0A
@@ -577,138 +577,8 @@
%7D
- else %7B%0A labelComponent = this.sharedComponents.linelabel;%0A %7D%0A%0A labelComponent = this.sharedComponents.linelabel;
%0A%0A
@@ -789,22 +789,39 @@
ew:
-labelComponent
+this.sharedComponents.linelabel
,%0A
|
9e73f55c5a231f8e59f943b13c859a5c73ae8d07
|
add test examples for component methods
|
app/components/navigation/tests/right.test.js
|
app/components/navigation/tests/right.test.js
|
import React from 'react';
import { mount } from 'enzyme';
import { Nav, NavItem } from 'react-bootstrap';
import NavigationRight from 'components/navigation/right';
import session from 'services/session';
describe('NavigationLeft', () => {
describe('when user is signed in', () => {
beforeEach(() => {
spyOn(session, 'loggedIn').and.returnValue(true);
});
it('renders NavigationRight with Nav and NavItem', () => {
const navigationRightComponent = mount(<NavigationRight />);
const navs = navigationRightComponent.find(Nav);
const navItems = navigationRightComponent.find(NavItem);
expect(navs.length).toEqual(1);
expect(navItems.length).toEqual(2);
expect(navItems.at(0).text()).toEqual('New Task');
expect(navItems.at(1).text()).toEqual('Sign out');
});
});
describe('when user is not signed in', () => {
it('renders NavigationRight with Nav and NavItem', () => {
const navigationRightComponent = mount(<NavigationRight />);
const navs = navigationRightComponent.find(Nav);
const navItems = navigationRightComponent.find(NavItem);
expect(navs.length).toEqual(1);
expect(navItems.length).toEqual(2);
expect(navItems.at(0).text()).toEqual('Sign up');
expect(navItems.at(1).text()).toEqual('Sign in');
});
});
});
|
JavaScript
| 0 |
@@ -198,16 +198,190 @@
ession';
+%0Aimport TodoActions from 'actions/todo';%0Aimport SessionActions from 'actions/session';%0Aimport SigninActions from 'actions/signin';%0Aimport SignupActions from 'actions/signup';
%0A%0Adescri
@@ -997,502 +997,1612 @@
%7D);%0A
- %7D);%0A%0A describe('when user is not signed in', () =%3E %7B%0A it('renders NavigationRight with Nav and NavItem', () =%3E %7B%0A const navigationRightComponent = mount(%3CNavigationRight /%3E);%0A const navs = navigationRightComponent.find(Nav);%0A const navItems = navigationRightComponent.find(NavItem);%0A%0A expect(navs.length).toEqual(1);%0A expect(navItems.length).toEqual(2);%0A expect(navItems.at(0).text()).toEqual('Sign up');%0A expect(navItems.at(1).text()).toEqual('Sign in'
+%0A it('calls TodoActions.show()', () =%3E %7B%0A spyOn(TodoActions, 'show');%0A const navigationRightComponent = mount(%3CNavigationRight /%3E);%0A navigationRightComponent.find('a').at(0).simulate('click');%0A%0A expect(TodoActions.show).toHaveBeenCalled();%0A %7D);%0A%0A it('calls SessionActions.delete', () =%3E %7B%0A spyOn(SessionActions, 'delete');%0A const navigationRightComponent = mount(%3CNavigationRight /%3E);%0A navigationRightComponent.find('a').at(1).simulate('click');%0A%0A expect(SessionActions.delete).toHaveBeenCalled();%0A %7D);%0A %7D);%0A%0A describe('when user is not signed in', () =%3E %7B%0A it('renders NavigationRight with Nav and NavItem', () =%3E %7B%0A const navigationRightComponent = mount(%3CNavigationRight /%3E);%0A const navs = navigationRightComponent.find(Nav);%0A const navItems = navigationRightComponent.find(NavItem);%0A%0A expect(navs.length).toEqual(1);%0A expect(navItems.length).toEqual(2);%0A expect(navItems.at(0).text()).toEqual('Sign up');%0A expect(navItems.at(1).text()).toEqual('Sign in');%0A %7D);%0A%0A it('calls SignupActions.show()', () =%3E %7B%0A spyOn(SignupActions, 'show');%0A const navigationRightComponent = mount(%3CNavigationRight /%3E);%0A navigationRightComponent.find('a').at(0).simulate('click');%0A%0A expect(SignupActions.show).toHaveBeenCalled();%0A %7D);%0A%0A it('calls SessionActions.delete', () =%3E %7B%0A spyOn(SigninActions, 'show');%0A const navigationRightComponent = mount(%3CNavigationRight /%3E);%0A navigationRightComponent.find('a').at(1).simulate('click');%0A%0A expect(SigninActions.show).toHaveBeenCalled(
);%0A
|
9af8b8472cbab4a7a389fe9e546ee48816fdff14
|
add support for .env files
|
app/react/src/server/config/webpack.config.js
|
app/react/src/server/config/webpack.config.js
|
import path from 'path';
import webpack from 'webpack';
import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
import WatchMissingNodeModulesPlugin from './WatchMissingNodeModulesPlugin';
import { includePaths, excludePaths, nodeModulesPaths, loadEnv, nodePaths } from './utils';
import babelLoaderConfig from './babel';
export default function() {
const config = {
devtool: 'cheap-module-source-map',
entry: {
manager: [require.resolve('./polyfills'), require.resolve('../../client/manager')],
preview: [
require.resolve('./polyfills'),
require.resolve('./globals'),
`${require.resolve('webpack-hot-middleware/client')}?reload=true`,
],
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'static/[name].bundle.js',
publicPath: '/',
},
plugins: [
new webpack.DefinePlugin(loadEnv()),
new webpack.HotModuleReplacementPlugin(),
new CaseSensitivePathsPlugin(),
new WatchMissingNodeModulesPlugin(nodeModulesPaths),
new webpack.ProgressPlugin(),
],
module: {
rules: [
{
test: /\.jsx?$/,
loader: require.resolve('babel-loader'),
query: babelLoaderConfig,
include: includePaths,
exclude: excludePaths,
},
],
},
resolve: {
// Since we ship with json-loader always, it's better to move extensions to here
// from the default config.
extensions: ['.js', '.json', '.jsx'],
// Add support to NODE_PATH. With this we could avoid relative path imports.
// Based on this CRA feature: https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules'].concat(nodePaths),
},
performance: {
hints: false,
},
};
return config;
}
|
JavaScript
| 0 |
@@ -49,16 +49,53 @@
bpack';%0A
+import Dotenv from 'dotenv-webpack';%0A
import C
@@ -1113,24 +1113,44 @@
ssPlugin(),%0A
+ new Dotenv(),%0A
%5D,%0A m
|
5801c3eba1c3599ca3817aa7454a795abcfa7efe
|
fix for dino layer
|
app/scripts/lizard/layers/custom/DinoLayer.js
|
app/scripts/lizard/layers/custom/DinoLayer.js
|
// Class for layers for Dinoloket (www.dinoloket.nl)
//
//
Lizard.geo.Layers.Custom = {};
Lizard.geo.Layers.Custom.DinoLayer = Lizard.geo.Layers.WMSLayer.extend({
defaults: {
display_name: '',
visibility: false,
opacity: 100,
order: 0,
//extra info and links
description: null,
metadata: null,
legend_url: null,
enable_search: true,
//program settings
type: 'dino', //='wms'
subtype: null,
addedToMap: false,
proxyForWms: false,//todo: add support
proxyForGetInfo: true,
//specific settings for wms overlays
layer_name: '',
styles: null,
format: 'png32',
height: null,
width: null,
tiled: null,
transparent: true,
wms_url: ''
},
initialize: function () {
this.set('type', 'dino');
this.set('subtype', this.get('options').subtype);
this.set('proxyForGetInfo', true);
},
_getNewLeafletLayer: function() {
var extra_settings = "/export?dpi=256&_ts=1362253889361&bboxSR=3857&imageSR=3857&f=image";
if (this.get('subtype') === 'sondering') {
extra_settings += "&layerDefs=0:(INFORMATION_TYPE = 'DATA' OR INFORMATION_TYPE ='BOTH');1:(INFORMATION_TYPE = 'DATA' OR INFORMATION_TYPE = 'BOTH')";
}
return L.tileLayer.wms(this.get('wms_url') + extra_settings, {
zIndex: 100 - this.attributes.order,
layers: 'test',
format: 'png32',
transparent: true,
attribution: "dinodata"
});
},
_getFeatureInfoRequestUrl: function(event, map) {
var base_url = this.get('wms_url') + "/identify?";
var bound_sw = map.getBounds().getSouthWest();
var bound_ne = map.getBounds().getNorthEast();
//Transform
var source = new Proj4js.Proj('EPSG:4326'); //source coordinates will be in Longitude/Latitude
var dest = new Proj4js.Proj('EPSG:28992'); //destination coordinates in RDS
// transforming point coordinates
var p = new Proj4js.Point(event.latlng.lng,event.latlng.lat,0);
Proj4js.transform(source, dest, p);
var bound_sw = new Proj4js.Point(bound_sw.lng, bound_sw.lat, 0);
Proj4js.transform(source, dest, bound_sw);
var bound_ne = new Proj4js.Point(bound_ne.lng, bound_ne.lat, 0);
Proj4js.transform(source, dest, bound_ne);
param = {
geometry:'{"x":'+ p.x +',"y":'+ p.y +'}',
layers:'top:0',
f:'json',
returnGeometry:true,
mapExtent: bound_sw.x + ',' + bound_sw.y + ',' + bound_ne.x + ',' + bound_ne.y,
geometryType:'esriGeometryPoint',
sr: '28992',
imageDisplay: map.getSize().x + ',' + map.getSize().y + ',256',
tolerance:'15',
layerDefs:'{}'
};
if (this.get('subtype') === 'sondering') {
param.layerDefs = "0:(INFORMATION_TYPE = 'DATA' OR INFORMATION_TYPE ='BOTH');1:(INFORMATION_TYPE = 'DATA' OR INFORMATION_TYPE = 'BOTH')";
}
var url = base_url + $.param(param);
return url;
},
getPopupContent: function(data) {
var objects = $.evalJSON(data).results;
if (objects.length > 0) {
return this.getContent(objects[0]);
} else {
return false;
}
},
getContent: function(object) {
if (this.get('subtype')==='boorprofiel'){
return "<b>" + object.value +
"</b><br><img src='http://www.dinoloket.nl/ulkbrh-web/rest/brh/mpcolumn/"+ object.value +"?width=200&height=400' style='width:200px;height:400px'></img>";
} else if (this.get('subtype')==='sondering') {
return "<b>" + object.value +
"</b><br><img src='//www.dinoloket.nl/ulkcpt-web/rest/cpt/cptchart/"+ object.value +"/4?width=300&height=300' style='width:300px;height:300px'></img>";
} else {
return "<b>" + object.value +
"</b><br><img src='http://www.dinoloket.nl/ulkgws-web/rest/gws/gwstchart/"+ object.value +"001?width=300&height=300' style='width:300px;height:300px'></img>";
}
//http://www.dinoloket.nl/ulkbrh-web/rest/brh/mpcolumn/B38E1380?height=365&width=200
},
getModalPopupContent: function() {
return 'todo'; //todo
}
});
//add type to type index
LAYER_CLASSES['dino'] = Lizard.geo.Layers.Custom.DinoLayer;
|
JavaScript
| 0 |
@@ -2951,12 +2951,13 @@
= $.
-eval
+parse
JSON
|
24462680c528a8b0b5a0e488cd069532eb187c16
|
Allow usernames with colon during login
|
app/scripts/modules/session/models/session.js
|
app/scripts/modules/session/models/session.js
|
"use strict";
var _ = require('lodash');
var $ = require('jquery');
var CryptoJS = require('crypto-js');
var Backbone = require('backbone');
var ValidationMixins = require('../../../shared/mixins/models/validation_mixin');
var adminDispatcher = require('../../../dispatchers/admin-dispatcher');
var sessionConfigActions = require('../config.json').actions;
var UserModel = require('../../../modules/users/models/user');
Backbone.$ = $;
var Session = Backbone.Model.extend({
defaults: {
gatewaydUrl: '',
sessionKey: '',
lastLogin: 0,
credentials: 'ABC' // Base64
},
validationRules: {
gatewaydUrl: {
validators: ['isRequired', 'isString', 'minLength:4']
},
sessionKey: {
validators: ['isRequired', 'isString', 'minLength:1']
},
credentials: {
validators: ['isRequired', 'isString']
}
},
initialize: function() {
_.bindAll(this);
this.set('userModel', new UserModel());
adminDispatcher.register(this.dispatchCallback);
},
dispatchCallback: function(payload) {
var handleAction = {};
handleAction[sessionConfigActions.login] = this.login;
handleAction[sessionConfigActions.logout] = this.logout;
handleAction[sessionConfigActions.restore] = this.restore;
if (!_.isUndefined(handleAction[payload.actionType])) {
handleAction[payload.actionType](payload.data);
}
},
updateSession: function(gatewaydUrl, sessionKey) {
this.set({
gatewaydUrl: gatewaydUrl,
sessionKey: sessionKey,
lastLogin: Date.now()
});
},
createCredentials: function(name, sessionKey) {
var encodedString = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(name + ':' + sessionKey));
this.set('credentials', 'Basic ' + encodedString);
},
setUrl: function() {
this.url = this.get('gatewaydUrl') + '/v1/users/login';
},
login: function(payload) {
var _this = this;
this.updateSession(payload.gatewaydUrl, payload.sessionKey);
this.createCredentials(payload.name, payload.sessionKey);
this.get('userModel').update(payload.name);
this.set(payload);
this.setUrl();
this.save(null, {
wait: true,
contentType: 'application/json',
data: JSON.stringify({
name: this.get('userModel').get('name'),
password: this.get('sessionKey')
}),
headers: {
'Authorization': this.get('credentials')
},
success: function() {
_this.get('userModel').set({isLoggedIn: true});
sessionStorage.setItem('session', JSON.stringify(_this.toJSON()));
}
});
},
restore: function() {
var oldSession, oldUser, restoredUser;
if (sessionStorage.length === 0) {
return;
}
oldSession = sessionStorage.getItem('session');
this.set(JSON.parse(oldSession));
oldUser = this.get('userModel');
restoredUser = new UserModel(oldUser);
this.set('userModel', restoredUser);
},
logout: function() {
var resetUser;
this.get('userModel').reset();
resetUser = this.get('userModel');
this.set('userModel', resetUser);
this.set(this.defaults);
sessionStorage.clear();
this.trigger('logout');
},
isLoggedIn: function() {
return this.get('userModel').get('isLoggedIn');
}
});
//add validation mixin
_.extend(Session.prototype, ValidationMixins);
module.exports = new Session();
|
JavaScript
| 0 |
@@ -1660,16 +1660,23 @@
ringify(
+%0A
CryptoJS
@@ -1691,20 +1691,40 @@
8.parse(
+encodeURIComponent(
name
+)
+ ':' +
|
af2f2639cfee462d6195939e93b3bb0f8211d000
|
fix wallaby runner
|
.wallaby.js
|
.wallaby.js
|
'use strict';
module.exports = function wallabyConfig() {
return {
files: [
'lib/**/*.js'
],
tests: [
{
pattern: 'test/**/*.spec.js',
instrument: true
},
{
pattern: 'test/**/suites/*.js',
instrument: false
}
],
env: {
type: 'node'
},
testFramework: 'mocha',
bootstrap: function bootstrap(wallaby) {
var path = require('path');
require(path.join(wallaby.localProjectDir, 'test', 'fixture'));
}
};
};
|
JavaScript
| 0.000002 |
@@ -307,16 +307,38 @@
type:
+ 'node',%0A runner:
'node'%0A
|
b7790d1c1c657cdc620c7b5132027c61d599351b
|
use boxa() method instead of box() for arrays
|
src/main/javascript/drone/fort.js
|
src/main/javascript/drone/fort.js
|
load(__folder + "drone.js");
//
// constructs a medieval fort
//
Drone.extend('fort', function(side, height)
{
if (typeof side == "undefined")
side = 18;
if (typeof height == "undefined")
height = 6;
// make sure side is even
if (side%2)
side++;
if (height < 4 || side < 10)
throw new java.lang.RuntimeException("Forts must be at least 10 wide X 4 tall");
var brick = 98;
//
// build walls.
//
this.chkpt('fort').box0(brick,side,height-1,side);
//
// build battlements
//
this.up(height-1);
for (i = 0;i <= 3;i++){
var turret = [];
this.box(brick) // solid brick corners
.up().box('50:5').down() // light a torch on each corner
.fwd();
turret.push('109:'+ Drone.PLAYER_STAIRS_FACING[this.dir]);
turret.push('109:'+ Drone.PLAYER_STAIRS_FACING[(this.dir+2)%4]);
this.box(turret,1,1,side-2).fwd(side-2).turn();
}
//
// build battlement's floor
//
this.move('fort');
this.up(height-2).fwd().right().box('126:0',side-2,1,side-2);
var battlementWidth = 3;
if (side <= 12)
battlementWidth = 2;
this.fwd(battlementWidth).right(battlementWidth)
.box(0,side-((1+battlementWidth)*2),1,side-((1+battlementWidth)*2));
//
// add door
//
var torch = '50:' + Drone.PLAYER_TORCH_FACING[this.dir];
this.move('fort').right((side/2)-1).door2() // double doors
.back().left().up().box(torch) // left torch
.right(3).box(torch); // right torch
//
// add ladder up to battlements
//
var ladder = '65:' + Drone.PLAYER_SIGN_FACING[(this.dir+2)%4];
this.move('fort').right((side/2)-3).fwd(1) // move inside fort
.box(ladder, 1,height-1,1);
return this.move('fort');
});
|
JavaScript
| 0.000006 |
@@ -899,24 +899,41 @@
dir+2)%254%5D);%0A
+ try%7B%0A
this
@@ -936,16 +936,17 @@
this.box
+a
(turret,
@@ -977,16 +977,101 @@
turn();%0A
+ %7Dcatch(e)%7B%0A self.sendMessage(%22ERROR: %22 + e.toString());%0A %7D%0A
%7D%0A
@@ -1594,24 +1594,33 @@
.left().up()
+%0A
.box(torch)
@@ -1650,16 +1650,25 @@
right(3)
+%0A
.box(tor
|
5c92b75cf5d017af2b0d266cd7a342a9701f43af
|
include validations in order model test
|
db/models/order.test.js
|
db/models/order.test.js
|
'use strict'
const db = require('APP/db'),
{ Order } = db,
{ expect } = require('chai'),
Promise = require('bluebird')
describe('The `Order` model', () => {
/**
* First we clear the database and recreate the tables before beginning a run
*/
before('Await database sync', () => db.didSync)
/**
* Next, we create an (un-saved!) order instance before every spec
*/
let order
beforeEach(() => {
order = Order.build({
status: 'Pending',
})
})
/**
* Also, we empty the tables after each spec
*/
afterEach(function() {
return Promise.all([
Order.truncate({ cascade: true })
])
})
describe('attributes definition', function() {
it('included `status` fields', function() {
return order.save()
.then(function(savedOrder) {
expect(savedOrder.status).to.equal('Pending')
})
})
it('requires `status`', function() {
order.status = null
return order.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('content cannot be null')
})
})
})
})
|
JavaScript
| 0.000146 |
@@ -550,26 +550,21 @@
terEach(
-function()
+() =%3E
%7B%0A r
@@ -871,16 +871,55 @@
%0A %7D)%0A
+ %7D)%0A%0A describe('Validations', () =%3E %7B
%0A it(
@@ -939,26 +939,21 @@
atus%60',
-function()
+() =%3E
%7B%0A
@@ -1175,18 +1175,442 @@
)%0A %7D)
+%0A%0A it('errors when status is not Pending or Completed', () =%3E %7B%0A // Use in a feasible alternative status%0A order.status = 'Shipping'%0A return order.validate()%0A .then(function(result) %7B%0A expect(result).to.be.an.instanceOf(Error)%0A // Please review the Sequelize Error and uncomment/correct below%0A // expect(result.message).to.contain('content cannot be null')%0A %7D)%0A %7D)
%0A %7D)%0A
-%0A
%7D)%0A
|
511c61d2cbfef2a1df28d60739f10724c307b204
|
fix img
|
app/akademonai/ad.directives/ad.blasphemer.drv.js
|
app/akademonai/ad.directives/ad.blasphemer.drv.js
|
angular.module('SatanApp.directives').directive('blasphemer', function() {
return {
scope: {},
templateUrl: '/akademonai/ad.directives/ad.blasphemer.drv.html',
controller: ['$scope', 'blasphemerSrv', function($scope, blasphemerSrv) {
$scope.posts = [];
$scope.form = {};
$scope.error = null;
$scope.limit = 5;
$scope.more = function () {
$scope.limit += 5;
getBlasphemes();
};
var getBlasphemes = function () {
blasphemerSrv.getBlasphemes($scope.limit, 0).success(function (data) {
$scope.posts = data;
$scope.error = null;
}).error(function (error) {
console.log(error);
$scope.error = 'Could not contact satan!';
});
};
getBlasphemes();
$scope.blaspheme = function () {
if ($scope.form.message < 3 && $scope.form.username < 3) {
$scope.error = 'You don`t play with Satan!';
return;
} else {
$scope.error = null;
}
blasphemerSrv.message = $scope.form.message;
blasphemerSrv.username = $scope.form.username;
blasphemerSrv.post().success(function (data) {
$scope.form.message = '';
$scope.form.username = '';
$scope.keistiSnuki();
$scope.error = null;
getBlasphemes();
}).error(function (error) {
console.log(error);
$scope.error = 'Could not contact satan!';
});
};
$scope.basePathAvatars = 'assets/avatars/';
$scope.basePathBots = 'assets/avatars/bots/';
$scope.avatars = [
"Japanese_Demon_MOCK__37974_std.png",
"Wl2_portrait_dog.png",
"Y-Gu7qpK.png",
"Zai952bu.png",
"aparatas.png",
"avatar_0b3c7c56f712_128.png",
"avatar_108e6bb7fc3d_128.png",
"avatar_125615824933_128.png",
"avatar_2197684cd711_128.png",
"avatar_2d4a37b998b3_128.png",
"avatar_2f5ab9dd289f_96.png",
"avatar_8b817384b116_128.png",
"avatar_a5cd5df5054e_128.png",
"avatar_bf0c4e6ef8d0_128.png",
"avatar_d703f0fbf2c0_128.png",
"avatar_f69048063872_128.png",
"cat_skull.png",
"good_boy_____by_saffronpanther-d8d1lf4.png",
"grinic_kreign_mq.png",
"satanHead.png",
"skeleton_PNG5552.png",
"star-256.png",
"succubus_pic.png",
"title119589078.png",
"title200181995.png",
"title297197317.png",
"title379341139.png",
"title393518232.png",
"title420932873.png",
"title441294333.png",
"title454856223.png",
"title475208221.png",
"title49856557.png",
"title498587187.png",
"title501097291.png",
"title516556465.png",
"title568578088.png",
"title572800711.png",
"title605077739.png",
"title636991968.png",
"title648354040.png",
"title685663863.png",
"title69751520.png",
"title699567984.png",
"title711406535.png",
"title738642826.png",
"title801924374.png",
"title817636211.png",
"title819932945.png",
"title829860852.png",
"title835297423.png",
"title855529559.png",
"title930821348.png",
"title993922740.png",
"trump.png",
"yBuDxvGl.png"
];
$scope.bots = [
"ZamolskiuRomas.png",
"aparatas2.png",
"augustus.png",
"cool.png",
"doctor.png",
"files.js",
"grazulis.png",
"henyte.png",
"jonka.png",
"morda.png",
"rasputin.jpg",
"vytas.png",
"yesferatu.png",
"zukauskas.png"
];
$scope.keistiSnuki = function () {
$scope.form.snukis = $scope.basePathAvatars + $scope.avatars [Math.round(Math.random()*($scope.avatars.length-1))];
blasphemerSrv.avatar = $scope.form.snukis;
};
$scope.keistiSnuki();
}]
}
});
|
JavaScript
| 0.000075 |
@@ -3706,50 +3706,8 @@
g%22,%0A
- %22title699567984.png%22,%0A
|
d620dfd730bab581556751faaded27f2d015c9c6
|
add support for $ in addition to $j for jquery
|
app/assets/javascripts/rails_admin/application.js
|
app/assets/javascripts/rails_admin/application.js
|
if (typeof($j) === "undefined" && typeof(jQuery) !== "undefined") {
var $j = jQuery.noConflict();
}
$j.ajaxSetup({
timeout: 600000 //set request timeout to 10 minnutes
});
$j(document).ready(function($){
$(".ra-button").not(".ui-button").button({});
if ($("#submit-buttons").length > 0 && $("#submit-buttons").children().length == 0){
var form = $(".remove-for-form.ra-block-toolbar.ui-state-highlight.clearfix input[type='submit']").parents('form:first');
$("ul.submit").clone(true).appendTo("#submit-buttons");
$("#submit-buttons input[type='submit']").click(function(){
form.append('<input type="hidden" name="' + $(this).attr('name') + '"/>');
form.submit();
})
}
});
|
JavaScript
| 0 |
@@ -93,16 +93,30 @@
lict();%0A
+ var $ = $j;%0A
%7D%0A%0A$j.aj
|
7a4f3b4eb5e0faa2c1d164b55359c3f88c2f1114
|
fix item type category
|
app/components/offlinePageView/offlinePageView.js
|
app/components/offlinePageView/offlinePageView.js
|
'use strict';
var isInit = true,
helpers = require('../../utils/widgets/helper'),
navigationProperty = require('../../utils/widgets/navigation-property'),
// additional requires
viewModel = require('./offlinePageView-view-model'),
modOfflinePage = require('../../lib/modOfflinePage/modOfflinePage.js'),
modBrowser = require('../../lib/modBrowser/modBrowser.js'),
actionBarModule = require("ui/action-bar"),
buttonModule = require("ui/button"),
util = require('../../utils/MyUtil')
;
// additional functions
function pageLoaded(args) {
var page = args.object;
helpers.platformInit(page);
page.bindingContext = viewModel;
// additional pageLoaded
if (isInit) {
isInit = false;
// additional pageInit
}
loadItems();
// NAVBUTTON - start
var navButton = new actionBarModule.NavigationButton();
navButton.text = 'Edit'
navButton.height = 44;
navButton.on(buttonModule.Button.tapEvent, function() {
if(!editMode)
navButton.text = 'Done';
else
navButton.text = 'Edit';
editMode = !editMode;
})
util.setRightNavButton(page, navButton);
// NAVBUTTON - end
}
function loadItems() {
modOfflinePage.getList(function(items) {
var menuItems = [];
for(var i = 0; i < items.length; i++) {
var item = items[i];
menuItems.push({
"title": "[" + item.title + "]",
"item" : item,
"icon": "\ue903"
},);
}
viewModel.set('menuItems', menuItems);
});
}
// START_CUSTOM_CODE_homeView
// Add custom code here. For more information about custom code, see http://docs.telerik.com/platform/screenbuilder/troubleshooting/how-to-keep-custom-code-changes
var view = require("ui/core/view");
function menuItemTap(args) {
var sender = args.object;
var parent = sender.parent;
var menuItems = viewModel.get('menuItems');
var menuItem = menuItems[args.index];
var item = menuItem.item;
if(item.type == 'cat') {
var browser = modBrowser.createBrowser();
browser.open(item.cat);
}
else if(item.type == 'item') {
var browser = modBrowser.createBrowser();
browser.open(item.item);
}
}
// END_CUSTOM_CODE_homeView
var editMode = false;
exports.menuItemTap = menuItemTap;
exports.pageLoaded = pageLoaded;
|
JavaScript
| 0.001266 |
@@ -1982,16 +1982,54 @@
m.item;%0A
+%09//console.log(JSON.stringify(item));%0A
%09if(item
@@ -2041,16 +2041,21 @@
== 'cat
+egory
') %7B%0A%09%09v
|
0b3546ac2d2975205a6b10381a3d8baa385a5635
|
Handle 1 registered user in RegisteredSummary
|
app/routes/events/components/RegisteredSummary.js
|
app/routes/events/components/RegisteredSummary.js
|
// @flow
import styles from './Registrations.css';
import React from 'react';
import { Link } from 'react-router';
import Tooltip from 'app/components/Tooltip';
import { Flex } from 'app/components/Layout';
import type { EventRegistration } from 'app/models';
type RegistrationProps = {
registration: EventRegistration
};
const Registration = ({ registration }: RegistrationProps) => (
<Tooltip content={registration.user.fullName}>
<Link
to={`/users/${registration.user.username}`}
style={{ color: 'inherit' }}
>
{registration.user.firstName.split(' ')[0]}
</Link>
</Tooltip>
);
const renderNameList = registrations => {
const registrationsList = registrations.slice(0, 14);
return (
<Flex column>
{registrationsList.map(reg => (
<Flex key={reg.id}>{reg.user.fullName}</Flex>
))}
{registrations.length > 10 && (
<Flex>{`og ${registrations.length - 12} andre`}</Flex>
)}
</Flex>
);
};
type RegistrationListProps = {
registrations: Array<EventRegistration>,
onClick: () => any
};
const RegistrationList = ({
registrations,
onClick
}: RegistrationListProps) => (
<Tooltip
content={renderNameList(registrations)}
list
className={styles.registrationList}
onClick={onClick}
>
{`${registrations.length} ${registrations.length === 1
? 'annen'
: 'andre'}`}
</Tooltip>
);
type RegisteredSummaryProps = {
registrations: Array<EventRegistration>,
toggleModal?: number => void
};
const RegisteredSentence = ({
registrations,
toggleModal
}: RegisteredSummaryProps) => {
if (registrations.length === 0) {
return 'Ingen';
}
// For more than 2 registrations we add a clickable `more` link:
if (registrations.length > 2) {
return (
<Flex>
<Registration registration={registrations[0]} />
{', '}
<Registration registration={registrations[1]} />
{' og '}
<RegistrationList
registrations={registrations.slice(2)}
onClick={() => toggleModal && toggleModal(0)}
/>
</Flex>
);
}
return (
<Flex>
<Registration registration={registrations[0]} />
{' og '}
<Registration registration={registrations[1]} />
</Flex>
);
};
const RegisteredSummary = (props: RegisteredSummaryProps) => {
return (
<Flex className={styles.summary}>
<RegisteredSentence {...props} /> er påmeldt.
</Flex>
);
};
export default RegisteredSummary;
|
JavaScript
| 0 |
@@ -1604,18 +1604,22 @@
=%3E %7B%0A
-if
+switch
(regist
@@ -1636,18 +1636,26 @@
ngth
- === 0
) %7B%0A
+ case 0:%0A
@@ -1676,116 +1676,99 @@
;%0A
-%7D%0A%0A // For more than 2 registrations we add a clickable %60more%60 link:%0A if (registrations.length %3E 2) %7B
+ case 1:%0A return %3CRegistration registration=%7Bregistrations%5B0%5D%7D /%3E;%0A case 2:
%0A
+
retu
@@ -1774,31 +1774,35 @@
urn (%0A
+
%3CFlex%3E%0A
+
%3CReg
@@ -1858,15 +1858,21 @@
-%7B',
+ %7B' og
'%7D%0A
+
@@ -1936,167 +1936,133 @@
-%7B' og '%7D%0A
+%3C/Flex%3E%0A
+);%0A
-%3CRegistrationList%0A registrations=%7Bregistrations.slice(2)%7D%0A onClick=%7B() =%3E toggleModal && toggleModal(0)%7D%0A /%3E
+default:%0A // For more than 2 registrations we add a clickable %60more%60 link:%0A return (
%0A
+
%3C
-/
Flex
@@ -2071,38 +2071,84 @@
-);%0A %7D%0A%0A return (%0A %3CFlex%3E%0A
+ %3CRegistration registration=%7Bregistrations%5B0%5D%7D /%3E%0A %7B', '%7D%0A
@@ -2187,31 +2187,35 @@
gistrations%5B
-0
+1
%5D%7D /%3E%0A
+
%7B' og
@@ -2219,24 +2219,28 @@
og '%7D%0A
+
+
%3CRegistratio
@@ -2232,32 +2232,48 @@
%3CRegistration
+List%0A
registration=%7Br
@@ -2261,32 +2261,33 @@
registration
+s
=%7Bregistrations%5B
@@ -2289,32 +2289,118 @@
ions
-%5B1%5D%7D /%3E%0A %3C/Flex%3E%0A );
+.slice(2)%7D%0A onClick=%7B() =%3E toggleModal && toggleModal(0)%7D%0A /%3E%0A %3C/Flex%3E%0A );%0A %7D
%0A%7D;%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.