commit
stringlengths 40
40
| subject
stringlengths 1
1.49k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| new_contents
stringlengths 1
29.8k
| old_contents
stringlengths 0
9.9k
| lang
stringclasses 3
values | proba
float64 0
1
|
|---|---|---|---|---|---|---|---|
4ea79ff4ab18474c4a692e1be9262950343f528a
|
Remove requirement for babel-eslint
|
.eslintrc.js
|
.eslintrc.js
|
(function() {
let error = 2;
module.exports = {
parserOptions: {
"ecmaVersion": 6,
"sourceType": "module"
},
root: true,
extends: "ftgp",
rules: {
"quotes": [error, "double"],
"ftgp/require-class-comment": 0
}
};
})();
|
(function() {
let error = 2;
module.exports = {
parser: "babel-eslint",
parserOptions: {
"ecmaVersion": 6,
"sourceType": "module"
},
root: true,
extends: "ftgp",
rules: {
"quotes": [error, "double"],
"ftgp/require-class-comment": 0
}
};
})();
|
JavaScript
| 0
|
24da14197350c079a902f21297667a0348db4291
|
remove unsued variables
|
embark-ui/src/components/Console.js
|
embark-ui/src/components/Console.js
|
import PropTypes from "prop-types";
import React, {Component} from 'react';
import Convert from 'ansi-to-html';
import { Col, Row, Card, TabContent, TabPane, Nav, NavItem, NavLink } from 'reactstrap';
import classnames from 'classnames';
import {AsyncTypeahead} from 'react-bootstrap-typeahead'
import Logs from "./Logs";
import "./Console.css";
import {EMBARK_PROCESS_NAME} from '../constants';
const convert = new Convert();
class Console extends Component {
constructor(props) {
super(props);
this.state = {value: '', isLoading: true, options: [], activeTab: EMBARK_PROCESS_NAME};
}
handleSubmit(event) {
event.preventDefault();
this.props.postCommand(this.state.value);
this.setState({value: ''});
this.typeahead.getInstance().clear()
}
handleChange(value, cb) {
this.setState({value: value}, cb);
}
toggle(tab) {
if (this.state.activeTab !== tab) {
this.setState({
activeTab: tab
});
this.props.updateTab(tab);
}
}
renderNav() {
return (
<Nav tabs>
{this.props.processes.map((process) => (
<NavItem key={process.name}>
<NavLink
className={classnames({ active: this.state.activeTab === process.name })}
onClick={() => { this.toggle(process.name); }}
>
{process.name}
</NavLink>
</NavItem>
))}
</Nav>
)
}
renderTabs() {
const {processLogs, processes} = this.props;
return (
<TabContent activeTab={this.state.activeTab}>
{processes.map(process => (
<TabPane key={process.name} tabId={process.name}>
<Logs>
{processLogs
.filter((item) => item.name === process.name)
.reverse()
.map((item, i) => <p key={i} className={item.logLevel}
dangerouslySetInnerHTML={{__html: convert.toHtml(item.msg)}}></p>)}
</Logs>
</TabPane>
))}
</TabContent>
);
}
render() {
return (
<Row>
<Col>
<Card>
<Card.Body className="console-container">
{this.renderNav()}
{this.renderTabs()}
</Card.Body>
{this.props.isEmbark() && <Card.Footer>
<AsyncTypeahead
autoFocus={true}
emptyLabel={false}
labelKey="value"
multiple={false}
maxResults={10}
isLoading={this.state.isLoading}
onInputChange={(text) => this.handleChange(text)}
onChange={(text) => {
if (text && text[0]) {
this.handleChange(text[0].value)
}
}}
ref={(typeahead) => this.typeahead = typeahead}
searchText={false}
onKeyDown={(e) => {
if (e.keyCode === 13) {
this.handleChange(e.target.value, () => {
this.handleSubmit(e)
})
}
}}
onSearch={(value) => {
this.props.postCommandSuggestions(value)
}}
filterBy={['value', 'description']}
maxHeight="200px"
placeholder="Type a command (e.g help)"
options={this.props.command_suggestions}
renderMenuItemChildren={(option) => (
<div>
{option.value}
<div>
<small>{option.command_type} - {option.description}</small>
</div>
</div>
)}
/>
</Card.Footer>}
</Card>
</Col>
</Row>
);
}
}
Console.propTypes = {
postCommand: PropTypes.func,
postCommandSuggestions: PropTypes.func,
isEmbark: PropTypes.func,
processes: PropTypes.arrayOf(PropTypes.object).isRequired,
command_suggestions: PropTypes.arrayOf(PropTypes.object),
processLogs: PropTypes.arrayOf(PropTypes.object).isRequired,
updateTab: PropTypes.func
};
export default Console;
|
import PropTypes from "prop-types";
import React, {Component} from 'react';
import Convert from 'ansi-to-html';
import { Form, Col, Row, Card, CardBody, Input, CardFooter, TabContent, TabPane, Nav, NavItem, NavLink } from 'reactstrap';
import classnames from 'classnames';
import {AsyncTypeahead} from 'react-bootstrap-typeahead'
import Logs from "./Logs";
import "./Console.css";
import {EMBARK_PROCESS_NAME} from '../constants';
const convert = new Convert();
class Console extends Component {
constructor(props) {
super(props);
this.state = {value: '', isLoading: true, options: [], activeTab: EMBARK_PROCESS_NAME};
}
handleSubmit(event) {
event.preventDefault();
this.props.postCommand(this.state.value);
this.setState({value: ''});
this.typeahead.getInstance().clear()
}
handleChange(value, cb) {
this.setState({value: value}, cb);
}
toggle(tab) {
if (this.state.activeTab !== tab) {
this.setState({
activeTab: tab
});
this.props.updateTab(tab);
}
}
renderNav() {
return (
<Nav tabs>
{this.props.processes.map((process) => (
<NavItem key={process.name}>
<NavLink
className={classnames({ active: this.state.activeTab === process.name })}
onClick={() => { this.toggle(process.name); }}
>
{process.name}
</NavLink>
</NavItem>
))}
</Nav>
)
}
renderTabs() {
const {processLogs, processes} = this.props;
return (
<TabContent activeTab={this.state.activeTab}>
{processes.map(process => (
<TabPane key={process.name} tabId={process.name}>
<Logs>
{processLogs
.filter((item) => item.name === process.name)
.reverse()
.map((item, i) => <p key={i} className={item.logLevel}
dangerouslySetInnerHTML={{__html: convert.toHtml(item.msg)}}></p>)}
</Logs>
</TabPane>
))}
</TabContent>
);
}
render() {
return (
<Row>
<Col>
<Card>
<Card.Body className="console-container">
{this.renderNav()}
{this.renderTabs()}
</Card.Body>
{this.props.isEmbark() && <Card.Footer>
<AsyncTypeahead
autoFocus={true}
emptyLabel={false}
labelKey="value"
multiple={false}
maxResults={10}
isLoading={this.state.isLoading}
onInputChange={(text) => this.handleChange(text)}
onChange={(text) => {
if (text && text[0]) {
this.handleChange(text[0].value)
}
}}
ref={(typeahead) => this.typeahead = typeahead}
searchText={false}
onKeyDown={(e) => {
if (e.keyCode === 13) {
this.handleChange(e.target.value, () => {
this.handleSubmit(e)
})
}
}}
onSearch={(value) => {
this.props.postCommandSuggestions(value)
}}
filterBy={['value', 'description']}
maxHeight="200px"
placeholder="Type a command (e.g help)"
options={this.props.command_suggestions}
renderMenuItemChildren={(option) => (
<div>
{option.value}
<div>
<small>{option.command_type} - {option.description}</small>
</div>
</div>
)}
/>
</Card.Footer>}
</Card>
</Col>
</Row>
);
}
}
Console.propTypes = {
postCommand: PropTypes.func,
postCommandSuggestions: PropTypes.func,
isEmbark: PropTypes.func,
processes: PropTypes.arrayOf(PropTypes.object).isRequired,
command_suggestions: PropTypes.arrayOf(PropTypes.object),
processLogs: PropTypes.arrayOf(PropTypes.object).isRequired,
updateTab: PropTypes.func
};
export default Console;
|
JavaScript
| 0.000436
|
03511e6b250873c5fe6c99cafca41850120f5ca1
|
fix build display
|
apps/app/src/pages/Build/ScreenshotsDiffCard.js
|
apps/app/src/pages/Build/ScreenshotsDiffCard.js
|
import * as React from "react";
import { x } from "@xstyled/styled-components";
import { gql } from "graphql-tag";
import {
Card,
CardHeader,
CardTitle,
CardBody,
BaseLink,
LinkBlock,
useDisclosureState,
DisclosureContent,
Disclosure,
Icon,
} from "@argos-ci/app/src/components";
import { ChevronRightIcon } from "@primer/octicons-react";
import { getStatusPrimaryColor } from "../../containers/Status";
import { ScreenshotDiffStatusIcon } from "./ScreenshotDiffStatusIcons";
export const ScreenshotsDiffCardFragment = gql`
fragment ScreenshotsDiffCardFragment on ScreenshotDiff {
url
status
compareScreenshot {
id
name
url
}
baseScreenshot {
id
name
url
}
}
`;
export function EmptyScreenshotCard() {
return (
<Card>
<CardHeader border={0}>
<CardTitle>No screenshot found</CardTitle>
</CardHeader>
</Card>
);
}
function EmptyScreenshot() {
return <x.div flex={1 / 3} />;
}
function Screenshot({ screenshot, title }) {
if (!screenshot?.url) return <EmptyScreenshot />;
return (
<BaseLink href={screenshot.url} target="_blank" title={title} flex={1 / 3}>
<img alt={screenshot.name} src={screenshot.url} />
</BaseLink>
);
}
export function ScreenshotsDiffCard({
screenshotDiff,
opened = true,
...props
}) {
const { compareScreenshot, baseScreenshot, url } = screenshotDiff;
const disclosure = useDisclosureState({ defaultOpen: opened });
return (
<Card {...props}>
<CardHeader
position="sticky"
top={40}
alignSelf="flex-start"
borderBottom={disclosure.open ? 1 : 0}
>
<CardTitle display="flex" alignItems="center" gap={1} fontSize="sm">
<LinkBlock
as={Disclosure}
state={disclosure}
px={1}
color="secondary-text"
>
<x.div
as={ChevronRightIcon}
transform
rotate={disclosure.open ? 90 : 0}
transitionDuration={300}
w={4}
h={4}
/>
</LinkBlock>
<Icon
as={ScreenshotDiffStatusIcon(screenshotDiff.status)}
color={getStatusPrimaryColor(screenshotDiff.status)}
/>
{compareScreenshot.name || baseScreenshot.name}
</CardTitle>
</CardHeader>
<DisclosureContent state={disclosure}>
<CardBody display="flex" gap={1} p={1}>
<Screenshot screenshot={baseScreenshot} title="Base screenshot" />
{compareScreenshot ? (
<Screenshot
screenshot={compareScreenshot}
title="Current screenshot"
/>
) : (
<EmptyScreenshot />
)}
{url ? (
<Screenshot screenshot={{ url, name: "diff" }} title="Diff" />
) : (
<EmptyScreenshot />
)}
</CardBody>
</DisclosureContent>
</Card>
);
}
|
import * as React from "react";
import { x } from "@xstyled/styled-components";
import { gql } from "graphql-tag";
import {
Card,
CardHeader,
CardTitle,
CardBody,
BaseLink,
LinkBlock,
useDisclosureState,
DisclosureContent,
Disclosure,
Icon,
} from "@argos-ci/app/src/components";
import { ChevronRightIcon } from "@primer/octicons-react";
import { getStatusPrimaryColor } from "../../containers/Status";
import { ScreenshotDiffStatusIcon } from "./ScreenshotDiffStatusIcons";
export const ScreenshotsDiffCardFragment = gql`
fragment ScreenshotsDiffCardFragment on ScreenshotDiff {
url
status
compareScreenshot {
id
name
url
}
baseScreenshot {
id
name
url
}
}
`;
export function EmptyScreenshotCard() {
return (
<Card>
<CardHeader border={0}>
<CardTitle>No screenshot found</CardTitle>
</CardHeader>
</Card>
);
}
function EmptyScreenshot() {
return <x.div flex={1 / 3} />;
}
function Screenshot({ screenshot, title }) {
if (!screenshot?.url) return <EmptyScreenshot />;
return (
<BaseLink href={screenshot.url} target="_blank" title={title} flex={1 / 3}>
<img alt={screenshot.name} src={screenshot.url} />
</BaseLink>
);
}
export function ScreenshotsDiffCard({
screenshotDiff,
opened = true,
...props
}) {
const { compareScreenshot, baseScreenshot, url } = screenshotDiff;
const disclosure = useDisclosureState({ defaultOpen: opened });
return (
<Card {...props}>
<CardHeader
position="sticky"
top={40}
alignSelf="flex-start"
borderBottom={disclosure.open ? 1 : 0}
>
<CardTitle display="flex" alignItems="center" gap={1} fontSize="sm">
<LinkBlock
as={Disclosure}
state={disclosure}
px={1}
color="secondary-text"
>
<x.div
as={ChevronRightIcon}
transform
rotate={disclosure.open ? 90 : 0}
transitionDuration={300}
w={4}
h={4}
/>
</LinkBlock>
<Icon
as={ScreenshotDiffStatusIcon(screenshotDiff.status)}
color={getStatusPrimaryColor(screenshotDiff.status)}
/>
{baseScreenshot.name}
</CardTitle>
</CardHeader>
<DisclosureContent state={disclosure}>
<CardBody display="flex" gap={1} p={1}>
<Screenshot screenshot={baseScreenshot} title="Base screenshot" />
{compareScreenshot ? (
<Screenshot
screenshot={compareScreenshot}
title="Current screenshot"
/>
) : (
<EmptyScreenshot />
)}
{url ? (
<Screenshot screenshot={{ url, name: "diff" }} title="Diff" />
) : (
<EmptyScreenshot />
)}
</CardBody>
</DisclosureContent>
</Card>
);
}
|
JavaScript
| 0.000033
|
c4e753d1c81bc584f5ddd92bde3c986b3c181613
|
Allow setting highlanderDeactivate in activate
|
source/ui/Group.js
|
source/ui/Group.js
|
/**
_enyo.Group_ provides a wrapper around multiple elements. It enables the
creation of radio groups from arbitrary components supporting the
[GroupItem](#enyo.GroupItem) API.
*/
enyo.kind({
name: "enyo.Group",
published: {
/**
If true, only one GroupItem in the component list may be active at
a given time.
*/
highlander: true,
//* If true, an active highlander item may be deactivated
allowHighlanderDeactivate: false,
//* The control that was last selected
active: null,
/**
The `groupName` property is used to scope this group to a certain
set of controls. When used, the group only controls activation of controls who
have the same `groupName` property set on them.
*/
groupName: null
},
//* @protected
handlers: {
onActivate: "activate"
},
activate: function(inSender, inEvent) {
if ((this.groupName || inEvent.originator.groupName) && (inEvent.originator.groupName != this.groupName)) {
return;
}
if (this.highlander) {
// we can optionally accept an `allowHighlanderDeactivate` property in inEvent without directly
// specifying it when instatiating the group - used mainly for custom kinds requiring deactivation
if (inEvent.allowHighlanderDeactivate !== undefined && inEvent.allowHighlanderDeactivate !== this.allowHighlanderDeactivate) {
this.setAllowHighlanderDeactivate(inEvent.allowHighlanderDeactivate);
}
// deactivation messages are ignored unless it's an attempt
// to deactivate the highlander
if (!inEvent.originator.active) {
// this clause prevents deactivating a grouped item once it's been active,
// as long as `allowHighlanderDeactivate` is false. Otherwise, the only
// proper way to deactivate a grouped item is to choose a new highlander.
if (inEvent.originator == this.active && !this.allowHighlanderDeactivate) {
this.active.setActive(true);
}
} else {
this.setActive(inEvent.originator);
}
}
},
activeChanged: function(inOld) {
if (inOld) {
inOld.setActive(false);
inOld.removeClass("active");
}
if (this.active) {
this.active.addClass("active");
}
}
});
|
/**
_enyo.Group_ provides a wrapper around multiple elements. It enables the
creation of radio groups from arbitrary components supporting the
[GroupItem](#enyo.GroupItem) API.
*/
enyo.kind({
name: "enyo.Group",
published: {
/**
If true, only one GroupItem in the component list may be active at
a given time.
*/
highlander: true,
//* If true, an active highlander item may be deactivated
allowHighlanderDeactivate: false,
//* The control that was last selected
active: null,
/**
The `groupName` property is used to scope this group to a certain
set of controls. When used, the group only controls activation of controls who
have the same `groupName` property set on them.
*/
groupName: null
},
//* @protected
handlers: {
onActivate: "activate"
},
activate: function(inSender, inEvent) {
if ((this.groupName || inEvent.originator.groupName) && (inEvent.originator.groupName != this.groupName)) {
return;
}
if (this.highlander) {
// deactivation messages are ignored unless it's an attempt
// to deactivate the highlander
if (!inEvent.originator.active) {
// this clause prevents deactivating a grouped item once it's been active,
// as long as `allowHighlanderDeactivate` is false. Otherwise, the only
// proper way to deactivate a grouped item is to choose a new highlander.
if (inEvent.originator == this.active && !this.allowHighlanderDeactivate) {
this.active.setActive(true);
}
} else {
this.setActive(inEvent.originator);
}
}
},
activeChanged: function(inOld) {
if (inOld) {
inOld.setActive(false);
inOld.removeClass("active");
}
if (this.active) {
this.active.addClass("active");
}
}
});
|
JavaScript
| 0
|
f9f8ed266d815dfb18d8ac2b3fba500ddfe7443a
|
Update on className change
|
tweet-embed.js
|
tweet-embed.js
|
import React from 'react'
import PropTypes from 'prop-types'
const callbacks = []
function addScript (src, cb) {
if (callbacks.length === 0) {
callbacks.push(cb)
var s = document.createElement('script')
s.setAttribute('src', src)
s.onload = () => callbacks.forEach(cb => cb())
document.body.appendChild(s)
} else {
callbacks.push(cb)
}
}
class TweetEmbed extends React.Component {
loadTweetForProps (props) {
const renderTweet = () => {
window.twttr.ready().then(({ widgets }) => {
// Clear previously rendered tweet before rendering the updated tweet id
if (this._div) {
this._div.innerHTML = ''
}
const { options, onTweetLoadSuccess, onTweetLoadError } = props
widgets
.createTweetEmbed(this.props.id, this._div, options)
.then(onTweetLoadSuccess)
.catch(onTweetLoadError)
})
}
if (!(window.twttr && window.twttr.ready)) {
const isLocal = window.location.protocol.indexOf('file') >= 0
const protocol = isLocal ? this.props.protocol : ''
addScript(`${protocol}//platform.twitter.com/widgets.js`, renderTweet)
} else {
renderTweet()
}
}
componentDidMount () {
this.loadTweetForProps(this.props)
}
shouldComponentUpdate (nextProps, nextState) {
return (
this.props.id !== nextProps.id ||
this.props.className !== nextProps.className
)
}
componentWillUpdate (nextProps, nextState) {
if (this.props.id !== nextProps.id) {
this.loadTweetForProps(nextProps)
}
}
render () {
return (
<div
className={this.props.className}
ref={c => {
this._div = c
}}
/>
)
}
}
TweetEmbed.propTypes = {
id: PropTypes.string,
options: PropTypes.object,
protocol: PropTypes.string,
onTweetLoadSuccess: PropTypes.func,
onTweetLoadError: PropTypes.func,
className: PropTypes.string
}
TweetEmbed.defaultProps = {
protocol: 'https:',
options: {},
className: null
}
export default TweetEmbed
|
import React from 'react'
import PropTypes from 'prop-types'
const callbacks = []
function addScript (src, cb) {
if (callbacks.length === 0) {
callbacks.push(cb)
var s = document.createElement('script')
s.setAttribute('src', src)
s.onload = () => callbacks.forEach(cb => cb())
document.body.appendChild(s)
} else {
callbacks.push(cb)
}
}
class TweetEmbed extends React.Component {
loadTweetForProps (props) {
const renderTweet = () => {
window.twttr.ready().then(({ widgets }) => {
// Clear previously rendered tweet before rendering the updated tweet id
if (this._div) {
this._div.innerHTML = ''
}
const { options, onTweetLoadSuccess, onTweetLoadError } = props
widgets
.createTweetEmbed(this.props.id, this._div, options)
.then(onTweetLoadSuccess)
.catch(onTweetLoadError)
})
}
if (!(window.twttr && window.twttr.ready)) {
const isLocal = window.location.protocol.indexOf('file') >= 0
const protocol = isLocal ? this.props.protocol : ''
addScript(`${protocol}//platform.twitter.com/widgets.js`, renderTweet)
} else {
renderTweet()
}
}
componentDidMount () {
this.loadTweetForProps(this.props)
}
shouldComponentUpdate (nextProps, nextState) {
return this.props.id !== nextProps.id
}
componentWillUpdate (nextProps, nextState) {
this.loadTweetForProps(nextProps)
}
render () {
return (
<div
className={this.props.className}
ref={c => {
this._div = c
}}
/>
)
}
}
TweetEmbed.propTypes = {
id: PropTypes.string,
options: PropTypes.object,
protocol: PropTypes.string,
onTweetLoadSuccess: PropTypes.func,
onTweetLoadError: PropTypes.func,
className: PropTypes.string
}
TweetEmbed.defaultProps = {
protocol: 'https:',
options: {},
className: null
}
export default TweetEmbed
|
JavaScript
| 0
|
07d20ff85fc921ac7ee49ddca9300bcc3f0cee48
|
add deviceId to id
|
twine/index.js
|
twine/index.js
|
var Bowline = require('bowline');
var adapter = {};
adapter.sensorName = 'twine';
adapter.types = [
{
name: 'twine',
fields: {
timestamp: 'date',
meta: {
sensor: 'string',
battery: 'string',
wifiSignal: 'string'
},
time: {
age: 'float',
timestamp: 'integer'
},
values: {
batteryVoltage: 'float',
firmwareVersion: 'string',
isVibrating: 'boolean',
orientation: 'string',
temperature: 'integer',
updateMode: 'string',
vibration: 'integer'
}
}
}
];
adapter.promptProps = {
properties: {
email: {
description: 'Enter your Twine account (e-mail address)'.magenta
},
password: {
description: 'Enter your password'.magenta
},
deviceId: {
description: 'Enter your Twine device ID'.magenta
}
}
};
adapter.storeConfig = function(c8, result) {
return c8.config(result).then(function(){
console.log('Configuration stored.');
c8.release();
});
}
adapter.importData = function(c8, conf, opts) {
if (conf.deviceId) {
var client = new Bowline(conf);
return client.fetch(function(err, response){
if (err) {
console.trace(err);
return;
}
response.id = response.time.timestamp + '-' + conf.deviceId;
response.meta.sensor = conf.deviceId;
response.timestamp = new Date(response.time.timestamp * 1000);
console.log(response.timestamp);
return c8.insert(response).then(function(result) {
// console.log(result);
// console.log('Indexed ' + result.items.length + ' documents in ' + result.took + ' ms.');
}).catch(function(error) {
console.trace(error);
});
});
}
else {
console.log('Configure first.');
}
};
module.exports = adapter;
|
var Bowline = require('bowline');
var adapter = {};
adapter.sensorName = 'twine';
adapter.types = [
{
name: 'twine',
fields: {
timestamp: 'date',
meta: {
sensor: 'string',
battery: 'string',
wifiSignal: 'string'
},
time: {
age: 'float',
timestamp: 'integer'
},
values: {
batteryVoltage: 'float',
firmwareVersion: 'string',
isVibrating: 'boolean',
orientation: 'string',
temperature: 'integer',
updateMode: 'string',
vibration: 'integer'
}
}
}
];
adapter.promptProps = {
properties: {
email: {
description: 'Enter your Twine account (e-mail address)'.magenta
},
password: {
description: 'Enter your password'.magenta
},
deviceId: {
description: 'Enter your Twine device ID'.magenta
}
}
};
adapter.storeConfig = function(c8, result) {
return c8.config(result).then(function(){
console.log('Configuration stored.');
c8.release();
});
}
adapter.importData = function(c8, conf, opts) {
if (conf.deviceId) {
var client = new Bowline(conf);
return client.fetch(function(err, response){
if (err) {
console.trace(err);
return;
}
response.id = response.time.timestamp;
response.meta.sensor = conf.deviceId;
response.timestamp = new Date(response.time.timestamp * 1000);
console.log(response.timestamp);
return c8.insert(response).then(function(result) {
// console.log(result);
// console.log('Indexed ' + result.items.length + ' documents in ' + result.took + ' ms.');
}).catch(function(error) {
console.trace(error);
});
});
}
else {
console.log('Configure first.');
}
};
module.exports = adapter;
|
JavaScript
| 0.000014
|
531334c2437e62fad78d7da19cde57fe333c933f
|
Update to redux-req-middleware
|
server/middleware/routing-middleware.js
|
server/middleware/routing-middleware.js
|
import { match } from 'react-router';
import { fetchRequiredActions } from 'base';
import routes from '../../src/base/routes';
import renderPage from '../lib/renderPage';
import renderContainer from '../lib/renderContainer';
import configureServerStore from '../lib/configureStore';
export default function routingMiddleware(req, res) {
const store = configureServerStore();
match({ routes , location: req.url }, (error, redirectLocation, renderProps) => {
if (error) return res.status(500).send(error.message);
if (redirectLocation) return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
if (renderProps == null) return res.status(404).send('Not found');
fetchRequiredActions(store.dispatch, renderProps.components, renderProps.params, 'server')
.then(() => {
const routeMatch = renderProps.location.pathname;
const renderedContainer = renderContainer(store, renderProps);
return renderPage(routeMatch, renderedContainer, store);
})
.then(page => res.status(200).send(page))
.catch(err => res.end(err.message));
});
}
|
import { match } from 'react-router';
import routes from '../../src/base/routes';
import renderPage from '../lib/renderPage';
import { fetchRequiredActions } from 'base';
import renderContainer from '../lib/renderContainer';
import configureServerStore from '../lib/configureStore';
import { applyMiddleware, createStore } from 'redux';
import rootReducer from '../../src/base/reducers/';
import requestMiddleware from '../../src/base/middleware/Request';
const context = 'server';
export default function routingMiddleware(req, res, next) {
const store = configureServerStore();
match({ routes , location: req.url }, (error, redirectLocation, renderProps) => {
if ( error ) return res.status(500).send( error.message );
if ( redirectLocation ) return res.redirect( 302, redirectLocation.pathname + redirectLocation.search );
if ( renderProps == null ) return res.status(404).send( 'Not found' );
fetchRequiredActions(store.dispatch, renderProps.components, renderProps.params, context)
.then(() => {
const routeMatch = renderProps.location.pathname;
const renderedContainer = renderContainer(store, renderProps);
return renderPage(routeMatch, renderedContainer, store );
})
.then( page => res.status(200).send(page) )
.catch( err => res.end(err.message) );
});
}
|
JavaScript
| 0
|
8e024c2a2eeef6f1163e83affbac48be463488a4
|
Add Sinon to require-test-config
|
js/require-test-config.js
|
js/require-test-config.js
|
require.config({
paths: {
//Test
'jasmine': 'lib/jasmine-1.3.1/jasmine',
'jasmine-html': 'lib/jasmine-1.3.1/jasmine-html',
'sinon': 'lib/sinon/sinon-1.6.0'
},
shim: {
'jasmine-html': {
deps: ['jasmine']
},
'jasmine': {
exports: 'jasmine'
},
'sinon': {
exports: 'sinon'
}
}
});
|
require.config({
paths: {
//Test
'jasmine': 'lib/jasmine-1.3.1/jasmine',
'jasmine-html': 'lib/jasmine-1.3.1/jasmine-html'
},
shim: {
'jasmine-html': {
deps: ['jasmine']
},
'jasmine': {
exports: 'jasmine'
}
}
});
|
JavaScript
| 0
|
b90a4d892377f6468d1c50464902e1f4b5d16066
|
make the hold condition clearer.
|
js/rpg_core/ImageCache.js
|
js/rpg_core/ImageCache.js
|
function ImageCache(){
this.initialize.apply(this, arguments);
}
ImageCache.limit = 20 * 1000 * 1000;
ImageCache.prototype.initialize = function(){
this._items = {};
};
ImageCache.prototype.add = function(key, value){
this._items[key] = {
bitmap: value,
touch: Date.now(),
key: key
};
this._truncateCache();
};
ImageCache.prototype.get = function(key){
if(this._items[key]){
var item = this._items[key];
item.touch = Date.now();
return item.bitmap;
}
return null;
};
ImageCache.prototype.reserve = function(key, reservationId){
this._items[key].reservationId = reservationId;
};
ImageCache.prototype.releaseReservation = function(reservationId){
var items = this._items;
Object.keys(items)
.map(function(key){return items[key];})
.forEach(function(item){
if(item.reservationId === reservationId){
delete item.reservationId;
}
});
};
ImageCache.prototype._truncateCache = function(){
var items = this._items;
var sizeLeft = ImageCache.limit;
Object.keys(items).map(function(key){
return items[key];
}).sort(function(a, b){
return b.touch - a.touch;
}).forEach(function(item){
if(sizeLeft > 0 || this._mustBeHeld(item)){
var bitmap = item.bitmap;
sizeLeft -= bitmap.width * bitmap.height;
}else{
delete items[item.key];
}
});
};
ImageCache.prototype._mustBeHeld = function(item){
// request only is weak so It's purgeable
if(item.bitmap.isRequestOnly()) return false;
// reserved item must be held
if(item.reservationId) return true;
// not ready bitmap must be held (because of checking isReady())
if(!item.bitmap.isReady()) return true;
// then the item may purgeable
return false;
};
ImageCache.prototype.isReady = function(){
var items = this._items;
return !Object.keys(items).some(function(key){
return !items[key].bitmap.isRequestOnly() && !items[key].bitmap.isReady();
});
};
ImageCache.prototype.getErrorBitmap = function(){
var items = this._items;
var bitmap = null;
if(!Object.keys(items).some(function(key){
if(items[key].bitmap.isError()){
bitmap = items[key].bitmap;
return true;
}
return false;
})) {
return bitmap;
}
return null;
};
|
function ImageCache(){
this.initialize.apply(this, arguments);
}
ImageCache.limit = 20 * 1000 * 1000;
ImageCache.prototype.initialize = function(){
this._items = {};
};
ImageCache.prototype.add = function(key, value){
this._items[key] = {
bitmap: value,
touch: Date.now(),
key: key
};
this._truncateCache();
};
ImageCache.prototype.get = function(key){
if(this._items[key]){
var item = this._items[key];
item.touch = Date.now();
return item.bitmap;
}
return null;
};
ImageCache.prototype.reserve = function(key, reservationId){
this._items[key].reservationId = reservationId;
};
ImageCache.prototype.releaseReservation = function(reservationId){
var items = this._items;
Object.keys(items)
.map(function(key){return items[key];})
.forEach(function(item){
if(item.reservationId === reservationId){
delete item.reservationId;
}
});
};
ImageCache.prototype._truncateCache = function(){
var items = this._items;
var sizeLeft = ImageCache.limit;
Object.keys(items).map(function(key){
return items[key];
}).sort(function(a, b){
return b.touch - a.touch;
}).forEach(function(item){
if(!item.bitmap.isRequestOnly() && (sizeLeft > 0 || item.reservationId || !item.bitmap.isReady())){
var bitmap = item.bitmap;
sizeLeft -= bitmap.width * bitmap.height;
}else{
delete items[item.key];
}
});
};
ImageCache.prototype.isReady = function(){
var items = this._items;
return !Object.keys(items).some(function(key){
return !items[key].bitmap.isRequestOnly() && !items[key].bitmap.isReady();
});
};
ImageCache.prototype.getErrorBitmap = function(){
var items = this._items;
var bitmap = null;
if(!Object.keys(items).some(function(key){
if(items[key].bitmap.isError()){
bitmap = items[key].bitmap;
return true;
}
return false;
})) {
return bitmap;
}
return null;
};
|
JavaScript
| 0
|
7a361f1b6c500bdaa7927a2f6b0b8113ca16b0a4
|
Change spatial rel
|
js/tasks/LayerInfoTask.js
|
js/tasks/LayerInfoTask.js
|
/*global pulse, app, jQuery, require, document, esri, esriuk, Handlebars, console, $, mynearest, window, alert, unescape, define */
/*
| Copyright 2015 ESRI (UK) Limited
|
| 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.
*/
/**
* Execute the Query Task to a Layer
*/
define(["dojo/Deferred", "esri/layers/FeatureLayer", "esri/renderers/jsonUtils", "esri/tasks/query", "esri/tasks/QueryTask", "esri/geometry/Circle", "esri/units"],
function (Deferred, FeatureLayer, jsonUtils, Query, QueryTask, Circle, Units) {
var taskOutput = function LayerInfoTask(props) {
this.properties = props;
this.getLayerInfo = function () {
var _this = this, result = new Deferred(), featureLayer;
// Need to also get the symbology for each layer
featureLayer = new FeatureLayer(_this.properties.serviceUrl);
featureLayer.on("error", function (err) {
result.resolve({ id: _this.properties.layerId, layerInfo: null, results:null, error: err, itemId: _this.properties.itemId });
});
featureLayer.on("load", function (data) {
var layerInf = { renderer: null, id: _this.properties.layerId, itemId: _this.properties.itemId, opacity: _this.properties.layerOpacity };
if (props.layerRenderer !== undefined && props.layerRenderer !== null) {
layerInf.renderer = jsonUtils.fromJson(props.layerRenderer);
}
else {
layerInf.renderer = data.layer.renderer;
}
_this.queryLayer(data.layer.maxRecordCount).then(function (res) {
result.resolve({ id: _this.properties.layerId, layerInfo: layerInf, results: res.results, error: null, itemId: _this.properties.itemId, url: _this.properties.serviceUrl });
});
});
return result.promise;
};
this.getUnits = function (distanceUnits) {
switch (distanceUnits) {
case "m":
return Units.MILES;
case "km":
return Units.KILOMETERS
case "me":
return Units.METERS
default:
return Units.MILES;
}
};
this.queryLayer = function (maxRecords) {
var _this = this, result = new Deferred(), query, queryTask;
// Use the current location and buffer the point to create a search radius
query = new Query();
queryTask = new QueryTask(_this.properties.serviceUrl);
query.where = "1=1"; // Get everything
query.geometry = new Circle({
center: [_this.properties.currentPoint.x, _this.properties.currentPoint.y],
radius: _this.properties.searchRadius,
radiusUnit: _this.getUnits(_this.properties.distanceUnits),
geodesic: _this.properties.currentPoint.spatialReference.isWebMercator()
});
query.outFields = ["*"];
query.returnGeometry = true;
query.outSpatialReference = _this.properties.currentPoint.spatialReference;
query.num = maxRecords || 1000;
// query.spatialRelationship = Query.SPATIAL_REL_CONTAINS;
queryTask.execute(query, function (features) {
result.resolve({ error: null, id: _this.properties.layerId, results: features, itemId: _this.properties.itemId});
},
function (error) {
result.resolve({ error: error, id: _this.properties.layerId, results: null, itemId: _this.properties.itemId });
});
return result.promise;
};
this.execute = function () {
return this.getLayerInfo();
};
};
return taskOutput;
});
|
/*global pulse, app, jQuery, require, document, esri, esriuk, Handlebars, console, $, mynearest, window, alert, unescape, define */
/*
| Copyright 2015 ESRI (UK) Limited
|
| 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.
*/
/**
* Execute the Query Task to a Layer
*/
define(["dojo/Deferred", "esri/layers/FeatureLayer", "esri/renderers/jsonUtils", "esri/tasks/query", "esri/tasks/QueryTask", "esri/geometry/Circle", "esri/units"],
function (Deferred, FeatureLayer, jsonUtils, Query, QueryTask, Circle, Units) {
var taskOutput = function LayerInfoTask(props) {
this.properties = props;
this.getLayerInfo = function () {
var _this = this, result = new Deferred(), featureLayer;
// Need to also get the symbology for each layer
featureLayer = new FeatureLayer(_this.properties.serviceUrl);
featureLayer.on("error", function (err) {
result.resolve({ id: _this.properties.layerId, layerInfo: null, results:null, error: err, itemId: _this.properties.itemId });
});
featureLayer.on("load", function (data) {
var layerInf = { renderer: null, id: _this.properties.layerId, itemId: _this.properties.itemId, opacity: _this.properties.layerOpacity };
if (props.layerRenderer !== undefined && props.layerRenderer !== null) {
layerInf.renderer = jsonUtils.fromJson(props.layerRenderer);
}
else {
layerInf.renderer = data.layer.renderer;
}
_this.queryLayer(data.layer.maxRecordCount).then(function (res) {
result.resolve({ id: _this.properties.layerId, layerInfo: layerInf, results: res.results, error: null, itemId: _this.properties.itemId, url: _this.properties.serviceUrl });
});
});
return result.promise;
};
this.getUnits = function (distanceUnits) {
switch (distanceUnits) {
case "m":
return Units.MILES;
case "km":
return Units.KILOMETERS
case "me":
return Units.METERS
default:
return Units.MILES;
}
};
this.queryLayer = function (maxRecords) {
var _this = this, result = new Deferred(), query, queryTask;
// Use the current location and buffer the point to create a search radius
query = new Query();
queryTask = new QueryTask(_this.properties.serviceUrl);
query.where = "1=1"; // Get everything
query.geometry = new Circle({
center: [_this.properties.currentPoint.x, _this.properties.currentPoint.y],
radius: _this.properties.searchRadius,
radiusUnit: _this.getUnits(_this.properties.distanceUnits),
geodesic: _this.properties.currentPoint.spatialReference.isWebMercator()
});
query.outFields = ["*"];
query.returnGeometry = true;
query.outSpatialReference = _this.properties.currentPoint.spatialReference;
query.num = maxRecords || 1000;
query.spatialRelationship = Query.SPATIAL_REL_CONTAINS;
queryTask.execute(query, function (features) {
result.resolve({ error: null, id: _this.properties.layerId, results: features, itemId: _this.properties.itemId});
},
function (error) {
result.resolve({ error: error, id: _this.properties.layerId, results: null, itemId: _this.properties.itemId });
});
return result.promise;
};
this.execute = function () {
return this.getLayerInfo();
};
};
return taskOutput;
});
|
JavaScript
| 0
|
0c2b7483660c4debe997680b4917835159979b43
|
Update eval.js
|
commands/eval.js
|
commands/eval.js
|
const Discord = require('discord.js');
const config = require("./config.json");
exports.run = async (bot, message) => {
var embed = new Discord.RichEmbed()
.setTitle("Restricted")
.setColor("#f45f42")
.addField("You are restricted from this command", "Its for the bot owner only!")
const randomColor = "#000000".replace(/0/g, function () { return (~~(Math.random() * 16)).toString(16); });
const clean = text => {
if (typeof(text) === "string")
return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203));
else
return text;
}
const args = message.content.split(" ").slice(1);
if (!args) return message.reply("Put what args you want")
try {
if(message.author.id !== config.ownerID) return message.channel.send({ embed: embed });
const code = args.join(" ");
let evaled = eval(code);
if (typeof evaled !== "string")
evaled = require("util").inspect(evaled);
var embed2 = new Discord.RichEmbed()
.setTitle("Evaled:", false)
.setColor(randomColor)
.addField("Evaled: :inbox_tray:", `\`\`\`js\n${code}\n\`\`\``)
.addField("Output: :outbox_tray:", clean(evaled))
message.channel.send({ embed: embed2 });
} catch (err) {
var embed3 = new Discord.RichEmbed()
.setTitle("ERROR:")
.setColor("#f44242")
.addField("Evaled: :inbox_tray:", `\`\`\`js\n${args}\n\`\`\``)
.addField("Output: :outbox_tray:", `\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``)
message.channel.send({ embed: embed3 });
}};
|
const Discord = require('discord.js');
const config = require("./config.json");
exports.run = async (bot, message) => {
var embed = new Discord.RichEmbed()
.setTitle("Restricted")
.setColor("#f45f42")
.addField("You are restricted from this command", "Its for the bot owner only!")
const randomColor = "#000000".replace(/0/g, function () { return (~~(Math.random() * 16)).toString(16); });
const clean = text => {
if (typeof(text) === "string")
return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203));
else
return text;
}
const args = message.content.split(" ").slice(1);
if (!args) return message.reply("Put what args you want")
try {
if(message.author.id !== config.ownerID) return message.channel.send({ embed: embed });
const code = args.join(" ");
let evaled = eval(code);
if (typeof evaled !== "string")
evaled = require("util").inspect(evaled);
var embed2 = new Discord.RichEmbed()
.setTitle("Evaled:", false)
.setColor(randomColor)
.addField("Evaled: :inbox_tray:", `\`\`\`js\n${args}\n\`\`\``)
.addField("Output: :outbox_tray:", clean(evaled))
message.channel.send({ embed: embed2 });
} catch (err) {
var embed3 = new Discord.RichEmbed()
.setTitle("ERROR:")
.setColor("#f44242")
.addField("Evaled: :inbox_tray:", `\`\`\`js\n${args}\n\`\`\``)
.addField("Output: :outbox_tray:", `\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``)
message.channel.send({ embed: embed3 });
}};
|
JavaScript
| 0.000001
|
117eae90552876726cb9bf5c9213bc544ae8b4ba
|
make evaling less annoying
|
commands/eval.js
|
commands/eval.js
|
const clean = (text) => {
if (typeof (text) === 'string') {
return text.replace(/`/g, '`' + String.fromCharCode(8203)).replace(/@/g, '@' + String.fromCharCode(8203));
} else {
return text;
}
}
module.exports = (message) => {
let client = message.client
let params = message.content.split(' ').splice(1)
if (message.member.id == '102645408223731712') {
try {
var code = params.join(" ")
var evaled = eval(code)
if (typeof evaled !== "string") evaled = require("util").inspect(evaled)
message.channel.sendCode("xl", clean(evaled))
} catch (err) {
message.channel.sendMessage(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``)
}
}
}
|
const clean = (text) => {
if (typeof (text) === 'string') {
return text.replace(/`/g, '`' + String.fromCharCode(8203)).replace(/@/g, '@' + String.fromCharCode(8203));
} else {
return text;
}
}
module.exports = (message) => {
let params = message.content.split(' ').splice(1)
if (message.member.id == '102645408223731712') {
try {
var code = params.join(" ")
var evaled = eval(code)
if (typeof evaled !== "string") evaled = require("util").inspect(evaled)
message.channel.sendCode("xl", clean(evaled))
} catch (err) {
message.channel.sendMessage(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``)
}
}
}
|
JavaScript
| 0.00005
|
5400972275f7871c3643329a3c2212f71e5d6f60
|
remove unused variables
|
test/source/from-test.js
|
test/source/from-test.js
|
require('buster').spec.expose();
var expect = require('buster').expect;
var from = require('../../lib/source/from').from;
var observe = require('../../lib/combinator/observe').observe;
describe('from', function() {
it('should support array-like items', function() {
function observeArguments(){
var result = [];
return observe(function(x) {
result.push(x);
}, from(arguments)).then(function() {
expect(result).toEqual([1,2,3]);
});
}
return observeArguments(1,2,3);
});
});
|
require('buster').spec.expose();
var expect = require('buster').expect;
var from = require('../../lib/source/from').from;
var observe = require('../../lib/combinator/observe').observe;
var sentinel = { value: 'sentinel' };
var other = { value: 'other' };
describe('from', function() {
it('should support array-like items', function() {
function observeArguments(){
var result = [];
return observe(function(x) {
result.push(x);
}, from(arguments)).then(function() {
expect(result).toEqual([1,2,3]);
});
}
return observeArguments(1,2,3);
});
});
|
JavaScript
| 0.000014
|
598a25c9c8472888c9abf1db9419c25d638c7b96
|
Update version string to 2.5.1-pre.7
|
version.js
|
version.js
|
if (enyo && enyo.version) {
enyo.version["enyo-ilib"] = "2.5.1-pre.7";
}
|
if (enyo && enyo.version) {
enyo.version["enyo-ilib"] = "2.5.1-pre.6";
}
|
JavaScript
| 0.000001
|
f6d01a768c7d8dc0fae7635b7ce1a3fe683cd3b6
|
refactor module.exports
|
react-app/src/storage.js
|
react-app/src/storage.js
|
module.exports = {
userInfo: userInfo,
rootFiles: rootFiles,
readdir: readdir,
readEntry: readEntry,
readfile: readfile,
writefile: writefile,
writeimage: writeimage,
makedir: makedir
};
var client = new Dropbox.Client({ key: "" });
function exec(f) {
if (client.isAuthenticated()) {
f();
} else {
client.authenticate(function(error, data) {
if (error) {
console.log(error);
} else {
f();
}
});
}
};
function userInfo(callback) {
exec(function() {
client.getAccountInfo(function(error, accountInfo) {
if (error) {
console.log(error);
} else {
callback({
name: accountInfo.name
});
}
});
});
};
var readdir = function(dirpath, callback) {
exec(function() {
client.readdir(dirpath, function(error, entries) {
if (error) {
console.log(error);
} else {
var ds = entries.filter(function(entry) {
return !entry.startsWith('__');
}).map(function(entry) {
var d = new $.Deferred;
client.stat(dirpath + '/' + entry, function(error, stat) {
d.resolve(stat);
});
return d.promise();
});
$.when.apply(null, ds).done(function() {
var stats = Array.prototype.slice.apply(arguments).map(function(s) {
return {
name: s.name,
path: s.path,
isFolder: s.isFolder,
children: []
};
});
callback(stats);
});
}
});
});
};
function rootFiles(callback) {
readdir('/', callback);
};
function readdir(dirpath, callback) {
readdir(dirpath, callback);
};
function readEntry(path, callback) {
exec(function() {
client.stat(path, function(error, stat) {
callback({
name: stat.name == '' ? '/' : stat.name,
path: stat.path == '' ? '/' : stat.path,
isFolder: stat.isFolder,
children: []
});
});
});
};
function readfile(filepath, callback) {
exec(function() {
client.readFile(filepath, function(error, data) {
if (error) {
console.log(error);
} else {
callback(data);
}
});
});
};
function writefile(filepath, content, callback) {
exec(function() {
client.writeFile(filepath, content, function(error, stat) {
if (error) {
console.log(error);
} else {
callback({
name: stat.name,
path: stat.path,
isFolder: stat.isFolder,
children: []
});
}
});
});
};
function writeimage(imageFile, callback) {
exec(function() {
client.stat('/__images', function(error, stat) {
if (error) {
console.log(error);
} else if (stat.isFile && !stat.isRemoved) {
console.log(stat);
console.log("ERROR!");
} else {
var newImagePath = '/__images/' + imageFile.name;
client.writeFile(newImagePath, imageFile, function(error, createdFile) {
if (error) {
console.log(error);
} else {
client.makeUrl(createdFile.path, {long: true}, function(error, data) {
callback(data.url.replace("www.dropbox", "dl.dropboxusercontent"));
});
}
});
}
});
});
};
function makedir(path, callback) {
exec(function() {
client.mkdir(path, function(error, data) {
if (error) {
console.log(error);
}
callback();
});
});
};
|
var client = new Dropbox.Client({ key: "" });
var exec = function(f) {
if (client.isAuthenticated()) {
f();
} else {
client.authenticate(function(error, data) {
if (error) {
console.log(error);
} else {
f();
}
});
}
};
exports.userInfo = function(callback) {
exec(function() {
client.getAccountInfo(function(error, accountInfo) {
if (error) {
console.log(error);
} else {
callback({
name: accountInfo.name
});
}
});
});
};
var readdir = function(dirpath, callback) {
exec(function() {
client.readdir(dirpath, function(error, entries) {
if (error) {
console.log(error);
} else {
var ds = entries.filter(function(entry) {
return !entry.startsWith('__');
}).map(function(entry) {
var d = new $.Deferred;
client.stat(dirpath + '/' + entry, function(error, stat) {
d.resolve(stat);
});
return d.promise();
});
$.when.apply(null, ds).done(function() {
var stats = Array.prototype.slice.apply(arguments).map(function(s) {
return {
name: s.name,
path: s.path,
isFolder: s.isFolder,
children: []
};
});
callback(stats);
});
}
});
});
};
exports.rootFiles = function(callback) {
readdir('/', callback);
};
exports.readdir = function(dirpath, callback) {
readdir(dirpath, callback);
};
exports.readEntry = function(path, callback) {
exec(function() {
client.stat(path, function(error, stat) {
callback({
name: stat.name == '' ? '/' : stat.name,
path: stat.path == '' ? '/' : stat.path,
isFolder: stat.isFolder,
children: []
});
});
});
};
exports.readfile = function(filepath, callback) {
exec(function() {
client.readFile(filepath, function(error, data) {
if (error) {
console.log(error);
} else {
callback(data);
}
});
});
};
exports.writefile = function(filepath, content, callback) {
exec(function() {
client.writeFile(filepath, content, function(error, stat) {
if (error) {
console.log(error);
} else {
callback({
name: stat.name,
path: stat.path,
isFolder: stat.isFolder,
children: []
});
}
});
});
};
exports.writeimage = function(imageFile, callback) {
exec(function() {
client.stat('/__images', function(error, stat) {
if (error) {
console.log(error);
} else if (stat.isFile && !stat.isRemoved) {
console.log(stat);
console.log("ERROR!");
} else {
var newImagePath = '/__images/' + imageFile.name;
client.writeFile(newImagePath, imageFile, function(error, createdFile) {
if (error) {
console.log(error);
} else {
client.makeUrl(createdFile.path, {long: true}, function(error, data) {
callback(data.url.replace("www.dropbox", "dl.dropboxusercontent"));
});
}
});
}
});
});
};
exports.makedir = function(path, callback) {
exec(function() {
client.mkdir(path, function(error, data) {
if (error) {
console.log(error);
}
callback();
});
});
};
|
JavaScript
| 0.000002
|
76e43c94b1c3df7661eceddb08617fac10950740
|
bump version (#2690)
|
version.js
|
version.js
|
module.exports = '2019-07-21';
|
module.exports = '2019-06-22';
|
JavaScript
| 0
|
488dbfa1eb3f0353dc63f3919ff5bed8310c4049
|
refactor to fix timout issues
|
cypress/integration/sizesAutoSpec.js
|
cypress/integration/sizesAutoSpec.js
|
describe('On a pages first render', () => {
before(() => {
cy.visit('/cypress/fixtures/samplePage.html');
});
beforeEach(() => {
cy.fixture('config.js').as('config');
});
it('Sizes attribute is correctly set', () => {
cy.get('.sizes-test', { timeout: 10000 }).each(($el) => {
const expectedSize = Math.ceil($el.width()) + 'px';
const imgSize = $el.attr('sizes');
expect(imgSize).to.equal(expectedSize);
});
});
});
describe('When a page gets resized', () => {
before(() => {
cy.visit('/cypress/fixtures/samplePage.html');
});
beforeEach(() => {
cy.fixture('config.js').as('config');
cy.viewport(500, 500);
});
it('Updates the sizes attribute on resize', () => {
cy.get('.sizes-test', { timeout: 10000 }).each(($el) => {
const expectedSize = Math.ceil($el.width()) + 'px';
const imgSize = $el.attr('sizes');
expect(imgSize).to.equal(expectedSize);
});
});
it('Stores previous measured width value if window is resized', () => {
cy.get('.sizes-test', { timeout: 300 }).each(($el) => {
const imgOffsetWidth = $el.attr('_ixWidth');
// _ixWidth helps us avoid setting the sizes attr if
// its already been updated to the current value. Ie
// if _ixWidth == 40px and offsetWidth == 40px, don't
// overwrite sizes attr, already been done at this width.
expect(imgOffsetWidth).to.exist;
});
});
it('Tracks the status of the resize event listener', () => {
cy.get('.sizes-test').each(($el) => {
const listenerStatus = $el.attr('_ixListening');
// _ixListening tracks if event listener has been
// removed from the element yet or not.
expect(listenerStatus).to.exist;
});
});
it('Tracks call to rAF', () => {
cy.get('.sizes-test').each(($el) => {
const rAFId = $el.attr('_ixRaf');
// _ixRaf tracks the rAF id of the element
expect(rAFId).to.exist;
});
});
it('Cancels calls to rAF if a new call made in the same frame', () => {
cy.viewport(500, 900);
cy.get('.sizes-test').each(($el) => {
const rAFId = $el.attr('_ixRaf');
// _ixRaf tracks the rAF id of the element
expect(rAFId).to.not.equal(1);
});
});
//
});
|
function waitedForResize($window) {
// Cypress will wait for this Promise to resolve
return new Cypress.Promise((resolve) => {
const onResizeEnd = (e) => {
$window.removeEventListener(e.type, onResizeEnd);
// resolve and allow Cypress to continue
resolve();
};
$window.addEventListener('resize', onResizeEnd);
});
}
describe('On a page with meta tag imgix parameters', () => {
before(() => {
cy.visit('/cypress/fixtures/samplePage.html');
});
context('For images with sizes=auto', () => {
beforeEach(() => {
cy.fixture('config.js').as('config');
cy.viewport(500, 984);
});
it('Sizes attribute is correctly set', () => {
cy.get('.sizes-test').each(($el) => {
const imgSize = $el.attr('sizes');
const expectedSize = Math.ceil($el.width()) + 'px';
expect(imgSize).to.equal(expectedSize);
});
});
it('Sizes attribute is updated if window is resized', () => {
cy.window().then(($window) =>
waitedForResize($window).then(() => {
cy.viewport(500, 500);
cy.get('.sizes-test').each(($el) => {
const imgSize = $el.attr('sizes');
expect(imgSize).to.equal(500 + 'px');
});
})
);
});
it('Stores previous measured width value if window is resized', () => {
cy.window().then(($window) =>
waitedForResize($window).then(() => {
cy.viewport(500, 500);
cy.get('.sizes-test').each(($el) => {
const imgOffsetWidth = $el.attr('_ixWidth');
// _ixWidth helps us avoid setting the sizes attr if
// its already been updated to the current value. Ie
// if _ixWidth == 40px and offsetWidth == 40px, don't
// overwrite sizes attr, already been done at this width.
expect(imgOffsetWidth).to.exist;
});
})
);
});
it('Tracks the status of the resize event listener', () => {
cy.window().then(($window) => {
waitedForResize($window).then(() => {
cy.viewport(500, 500);
cy.get('.sizes-test').each(($el) => {
const listenerStatus = $el.attr('_ixListening');
// _ixListening tracks if event listener has been
// removed from the element yet or not.
expect(listenerStatus).to.exist;
});
});
});
});
it('Tracks call to rAF', () => {
cy.window().then(($window) => {
waitedForResize($window).then(() => {
cy.viewport(500, 500);
cy.get('.sizes-test').each(($el) => {
const rAFId = $el.attr('_ixTimeout');
// _ixTimeout tracks the rAF id of the element
expect(rAFId).to.exist;
});
});
});
});
it('Cancels call to rAF is a new call made in the same frame', () => {
cy.window().then(($window) => {
waitedForResize($window).then(() => {
cy.viewport(500, 500);
cy.get('.sizes-test').each(($el) => {
const rAFId = $el.attr('_ixTimeout');
// _ixTimeout tracks the rAF id of the element
expect(rAFId).to.equal('undefined');
});
});
});
});
});
});
|
JavaScript
| 0.000005
|
8611042bc961ff62d39ffff0e248b9e85af93f4a
|
update basic package-file testing
|
test/testPackageFiles.js
|
test/testPackageFiles.js
|
/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs = require('fs');
describe('Test package.json and io-package.json', function() {
it('Test package files', function (done) {
var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json');
var ioPackage = JSON.parse(fileContentIOPackage);
var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json');
var npmPackage = JSON.parse(fileContentNPMPackage);
expect(ioPackage).to.be.an('object');
expect(npmPackage).to.be.an('object');
expect(ioPackage.common.version).to.exist;
expect(npmPackage.version).to.exist;
if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) {
console.log('ERROR: Version numbers in package.json and io-package.json differ!!');
}
if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
}
expect(ioPackage.common.authors).to.exist;
if (ioPackage.common.name.indexOf('template') !== 0) {
if (Array.isArray(ioPackage.common.authors)) {
expect(ioPackage.common.authors.length).to.not.be.equal(0);
if (ioPackage.common.authors.length === 1) {
expect(ioPackage.common.authors[0]).to.not.be.equal('my Name <[email protected]>');
}
}
else {
expect(ioPackage.common.authors).to.not.be.equal('my Name <[email protected]>');
}
}
else {
console.log('Testing for set authors field in io-package skipped because template adapter');
}
done();
});
});
|
/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var fs = require('fs');
describe('Test package.json and io-package.json', function() {
it('Test package files', function (done) {
var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json');
var ioPackage = JSON.parse(fileContentIOPackage);
var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json');
var npmPackage = JSON.parse(fileContentNPMPackage);
expect(ioPackage).to.be.an('object');
expect(npmPackage).to.be.an('object');
expect(ioPackage.common.version).to.exist;
expect(npmPackage.version).to.exist;
if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) {
console.log('ERROR: Version numbers in package.json and io-package.json differ!!');
}
if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
}
done();
});
});
|
JavaScript
| 0
|
84216367a31ccf4c364dc3676b063ba7d6db5e82
|
add more tests for convertAASequence
|
src/__tests__/convertAASequence.test.js
|
src/__tests__/convertAASequence.test.js
|
const convertAASequence = require('../convertAASequence');
describe('Checking convert AA sequence', () => {
test('AAAAAAA', () => {
const result = convertAASequence('AAAAAAA');
expect(result).toEqual('HAlaAlaAlaAlaAlaAlaAlaOH');
});
test('HAlaAla(H-1OH)AlaOH', () => {
const result = convertAASequence('HAlaAla(H-1OH)AlaOH');
expect(result).toEqual('HAlaAla(H-1OH)AlaOH');
});
test('(C33H37O6N3Si) GluTyrGluLys(C16H30O)GluTyrGluOH', () => {
const result = convertAASequence(
'(C33H37O6N3Si) GluTyrGluLys(C16H30O)GluTyrGluOH'
);
expect(result).toEqual('(C33H37O6N3Si) GluTyrGluLys(C16H30O)GluTyrGluOH');
});
test('(Me)AAAAAAA(NH2)', () => {
const result = convertAASequence('(Me)AAAAAAA(NH2)');
expect(result).toEqual('(Me)AlaAlaAlaAlaAlaAlaAla(NH2)');
});
test('HAlaGlyProOH', () => {
const result = convertAASequence('HAlaGlyProOH');
expect(result).toEqual('HAlaGlyProOH');
});
test('ALA SER LYS GLY PRO', () => {
const result = convertAASequence('ALA SER LYS GLY PRO');
expect(result).toEqual('HAlaSerLysGlyProOH');
});
});
|
const convertAASequence = require('../convertAASequence');
describe('Checking convert AA sequence', () => {
test('AAAAAAA', () => {
const result = convertAASequence('AAAAAAA');
expect(result).toEqual('HAlaAlaAlaAlaAlaAlaAlaOH');
});
test('HAlaAla(H-1OH)AlaOH', () => {
const result = convertAASequence('HAlaAla(H-1OH)AlaOH');
expect(result).toEqual('HAlaAla(H-1OH)AlaOH');
})
test('(Me)AAAAAAA(NH2)', () => {
const result = convertAASequence('(Me)AAAAAAA(NH2)');
expect(result).toEqual('(Me)AlaAlaAlaAlaAlaAlaAla(NH2)');
});
test('ALA SER LYS GLY PRO', () => {
const result = convertAASequence('ALA SER LYS GLY PRO');
expect(result).toEqual('HAlaSerLysGlyProOH');
});
});
|
JavaScript
| 0
|
19eaed5b44c04592c2407639991d256cb944f7fc
|
Correct a spelling mistake
|
example/test/list_component_test.js
|
example/test/list_component_test.js
|
var Assert = require("assert");
var ReactDOMServer = require("react-dom/server");
var XPathUtils = require("xpath-react/utils");
var React = require("react");
var Sinon = require("sinon");
var List = require("../lib/list_component");
function assertHasXPath (element, expression) {
Assert.ok(XPathUtils.find(element, expression), "Expected element to have expression " + expression);
}
describe("ListComponent", function () {
describe("when isLoading is true", function () {
it("should render a loading text", function () {
var rendering = ReactDOMServer.renderToString(<List isLoading={true} />);
Assert.ok(rendering.includes("Loading items.."));
});
});
describe("when isLoading is false", function () {
it("should render the given items", function () {
var items = ["foo", "bar"];
var element = XPathUtils.render(<List isLoading={false} items={items} />);
assertHasXPath(element, ".//li[contains(., 'foo')]");
assertHasXPath(element, ".//li[contains(., 'bar')]");
});
it("should render a delete button for each item", function () {
var items = ["foo", "bar"];
var element = XPathUtils.render(<List isLoading={false} items={items} />);
assertHasXPath(element, ".//li[contains(., 'foo')]/button[contains(., 'Delete')]");
assertHasXPath(element, ".//li[contains(., 'bar')]/button[contains(., 'Delete')]");
});
it("should invoke a callback upon pressing a delete button", function () {
var items = ["foo"];
var onRemove = Sinon.spy();
var element = XPathUtils.render(<List isLoading={false} items={items} onRemove={onRemove} />);
XPathUtils.Simulate.click(element, ".//button[contains(., 'Delete')]");
Assert.ok(onRemove.called);
});
it("should render the given form value", function () {
var element = XPathUtils.render(<List isLoading={false} formValue="foo" />);
var textarea = XPathUtils.find(element, ".//textarea");
Assert.equal(textarea.props.value, "foo");
});
it("should render an add item button", function () {
var element = XPathUtils.render(<List isLoading={false} />);
assertHasXPath(element, ".//button[contains(., 'Add')]");
});
it("should invoke a callback upon pressing the add button", function () {
var onAdd = Sinon.spy();
var element = XPathUtils.render(<List isLoading={false} onAdd={onAdd} formValue="foo" />);
XPathUtils.Simulate.click(element, ".//button[contains(., 'Add')]");
Assert.ok(onAdd.calledWith("foo"));
});
});
});
|
var Assert = require("assert");
var ReactDOMServer = require("react-dom/server");
var XPathUtils = require("xpath-react/utils");
var React = require("react");
var Sinon = require("sinon");
var List = require("../lib/list_component");
function asserHasXPath (element, expression) {
Assert.ok(XPathUtils.find(element, expression), "Expected element to have expression " + expression);
}
describe("ListComponent", function () {
describe("when isLoading is true", function () {
it("should render a loading text", function () {
var rendering = ReactDOMServer.renderToString(<List isLoading={true} />);
Assert.ok(rendering.includes("Loading items.."));
});
});
describe("when isLoading is false", function () {
it("should render the given items", function () {
var items = ["foo", "bar"];
var element = XPathUtils.render(<List isLoading={false} items={items} />);
asserHasXPath(element, ".//li[contains(., 'foo')]");
asserHasXPath(element, ".//li[contains(., 'bar')]");
});
it("should render a delete button for each item", function () {
var items = ["foo", "bar"];
var element = XPathUtils.render(<List isLoading={false} items={items} />);
asserHasXPath(element, ".//li[contains(., 'foo')]/button[contains(., 'Delete')]");
asserHasXPath(element, ".//li[contains(., 'bar')]/button[contains(., 'Delete')]");
});
it("should invoke a callback upon pressing a delete button", function () {
var items = ["foo"];
var onRemove = Sinon.spy();
var element = XPathUtils.render(<List isLoading={false} items={items} onRemove={onRemove} />);
XPathUtils.Simulate.click(element, ".//button[contains(., 'Delete')]");
Assert.ok(onRemove.called);
});
it("should render the given form value", function () {
var element = XPathUtils.render(<List isLoading={false} formValue="foo" />);
var textarea = XPathUtils.find(element, ".//textarea");
Assert.equal(textarea.props.value, "foo");
});
it("should render an add item button", function () {
var element = XPathUtils.render(<List isLoading={false} />);
asserHasXPath(element, ".//button[contains(., 'Add')]");
});
it("should invoke a callback upon pressing the add button", function () {
var onAdd = Sinon.spy();
var element = XPathUtils.render(<List isLoading={false} onAdd={onAdd} formValue="foo" />);
XPathUtils.Simulate.click(element, ".//button[contains(., 'Add')]");
Assert.ok(onAdd.calledWith("foo"));
});
});
});
|
JavaScript
| 0.999999
|
e6567bc593b7c57a88542f137375621701579907
|
fix failing test: round to seconds (#1631)
|
examples/async/src/actions/index.js
|
examples/async/src/actions/index.js
|
export const REQUEST_POSTS = 'REQUEST_POSTS'
export const RECEIVE_POSTS = 'RECEIVE_POSTS'
export const SELECT_REDDIT = 'SELECT_REDDIT'
export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT'
export function selectReddit(reddit) {
return {
type: SELECT_REDDIT,
reddit,
}
}
export function invalidateReddit(reddit) {
return {
type: INVALIDATE_REDDIT,
reddit,
}
}
export function requestPosts(reddit) {
return {
type: REQUEST_POSTS,
reddit,
}
}
export function receivePosts(reddit, posts) {
return {
type: RECEIVE_POSTS,
reddit,
posts,
receivedAt: new Date().setMilliseconds(0),
}
}
|
export const REQUEST_POSTS = 'REQUEST_POSTS'
export const RECEIVE_POSTS = 'RECEIVE_POSTS'
export const SELECT_REDDIT = 'SELECT_REDDIT'
export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT'
export function selectReddit(reddit) {
return {
type: SELECT_REDDIT,
reddit,
}
}
export function invalidateReddit(reddit) {
return {
type: INVALIDATE_REDDIT,
reddit,
}
}
export function requestPosts(reddit) {
return {
type: REQUEST_POSTS,
reddit,
}
}
export function receivePosts(reddit, posts) {
return {
type: RECEIVE_POSTS,
reddit,
posts,
receivedAt: Date.now(),
}
}
|
JavaScript
| 0.001585
|
d05c2340b89a8312d33b07af6e688a186ee6cc2a
|
remove console log
|
gulp/tasks/browserify.js
|
gulp/tasks/browserify.js
|
/**
* @author centsent
*/
import config from '../config';
import gulp from 'gulp';
import gulpif from 'gulp-if';
import gutil from 'gulp-util';
import source from 'vinyl-source-stream';
import sourcemaps from 'gulp-sourcemaps';
import buffer from 'vinyl-buffer';
import streamify from 'gulp-streamify';
import watchify from 'watchify';
import browserify from 'browserify';
import babelify from 'babelify';
import uglify from 'gulp-uglify';
import handleErrors from '../util/handleErrors';
import browserSync from 'browser-sync';
import ngAnnotate from 'browserify-ngannotate';
import stringify from 'stringify';
import eventStream from 'event-stream';
import fs from 'fs';
// Based on: http://blog.avisi.nl/2014/04/25/how-to-keep-a-fast-build-with-browserify-and-reactjs/
function buildScript(entries, file) {
let bundler = browserify({
entries: entries,
debug: true,
cache: {},
packageCache: {},
fullPaths: !global.isProd
});
const transforms = [
stringify(['.html']),
babelify.configure({
stage: 0
}),
ngAnnotate,
'brfs',
'bulkify'
];
transforms.forEach((transform) => {
bundler.transform(transform);
});
function rebundle() {
const stream = bundler.bundle();
const createSourcemap = global.isProd && config.browserify.prodSourcemap;
gutil.log(`Rebundle...${file}`);
return stream.on('error', handleErrors)
.pipe(source(file))
.pipe(gulpif(createSourcemap, buffer()))
.pipe(gulpif(createSourcemap, sourcemaps.init()))
.pipe(gulpif(global.isProd, streamify(uglify({
compress: {
drop_console: true
}
}))))
.pipe(gulpif(createSourcemap, sourcemaps.write('./')))
.pipe(gulp.dest(config.dist.root))
.pipe(browserSync.stream({
once: true
}));
}
if (!global.isProd) {
bundler = watchify(bundler);
bundler.on('update', () => {
rebundle();
});
}
return rebundle();
}
gulp.task('browserify', () => {
if (global.isProd) {
return buildScript([config.browserify.entry], config.browserify.bundleName);
}
const entries = config.browserify.entries.filter(item => {
return fs.existsSync(item.src);
});
const tasks = entries.map(entry => {
return buildScript([entry.src], entry.bundleName);
});
return eventStream.merge.apply(null, tasks);
});
|
/**
* @author centsent
*/
import config from '../config';
import gulp from 'gulp';
import gulpif from 'gulp-if';
import gutil from 'gulp-util';
import source from 'vinyl-source-stream';
import sourcemaps from 'gulp-sourcemaps';
import buffer from 'vinyl-buffer';
import streamify from 'gulp-streamify';
import watchify from 'watchify';
import browserify from 'browserify';
import babelify from 'babelify';
import uglify from 'gulp-uglify';
import handleErrors from '../util/handleErrors';
import browserSync from 'browser-sync';
import ngAnnotate from 'browserify-ngannotate';
import stringify from 'stringify';
import eventStream from 'event-stream';
import fs from 'fs';
// Based on: http://blog.avisi.nl/2014/04/25/how-to-keep-a-fast-build-with-browserify-and-reactjs/
function buildScript(entries, file) {
let bundler = browserify({
entries: entries,
debug: true,
cache: {},
packageCache: {},
fullPaths: !global.isProd
});
const transforms = [
stringify(['.html']),
babelify.configure({
stage: 0
}),
ngAnnotate,
'brfs',
'bulkify'
];
transforms.forEach((transform) => {
bundler.transform(transform);
});
function rebundle() {
const stream = bundler.bundle();
const createSourcemap = global.isProd && config.browserify.prodSourcemap;
gutil.log(`Rebundle...${file}`);
return stream.on('error', handleErrors)
.pipe(source(file))
.pipe(gulpif(createSourcemap, buffer()))
.pipe(gulpif(createSourcemap, sourcemaps.init()))
.pipe(gulpif(global.isProd, streamify(uglify({
compress: {
drop_console: true
}
}))))
.pipe(gulpif(createSourcemap, sourcemaps.write('./')))
.pipe(gulp.dest(config.dist.root))
.pipe(browserSync.stream({
once: true
}));
}
if (!global.isProd) {
bundler = watchify(bundler);
bundler.on('update', () => {
rebundle();
});
}
return rebundle();
}
gulp.task('browserify', () => {
if (global.isProd) {
return buildScript([config.browserify.entry], config.browserify.bundleName);
}
const entries = config.browserify.entries.filter(item => {
return fs.existsSync(item.src);
});
console.log(entries);
const tasks = entries.map(entry => {
return buildScript([entry.src], entry.bundleName);
});
return eventStream.merge.apply(null, tasks);
});
|
JavaScript
| 0.002829
|
9c2b960d09cd3d43106c4ca444701e35432d0272
|
disable PDF view for android (#12061)
|
shared/fs/filepreview/view-container.js
|
shared/fs/filepreview/view-container.js
|
// @flow
import * as I from 'immutable'
import {
compose,
connect,
lifecycle,
type Dispatch,
type TypedState,
setDisplayName,
} from '../../util/container'
import * as Constants from '../../constants/fs'
import * as FsGen from '../../actions/fs-gen'
import * as React from 'react'
import * as Types from '../../constants/types/fs'
import DefaultView from './default-view-container'
import ImageView from './image-view'
import TextView from './text-view'
import AVView from './av-view'
import PdfView from './pdf-view'
import {Box, Text} from '../../common-adapters'
import {globalStyles, globalColors, platformStyles} from '../../styles'
import {isAndroid} from '../../constants/platform'
type Props = {
path: Types.Path,
routePath: I.List<string>,
}
const mapStateToProps = (state: TypedState, {path}: Props) => {
const _pathItem = state.fs.pathItems.get(path) || Constants.makeFile()
return {
_serverInfo: state.fs.localHTTPServerInfo,
mimeType: _pathItem.type === 'file' ? _pathItem.mimeType : '',
isSymlink: _pathItem.type === 'symlink',
}
}
const mapDispatchToProps = (dispatch: Dispatch, {path}: Props) => ({
loadMimeType: () => dispatch(FsGen.createMimeTypeLoad({path})),
})
const mergeProps = ({_serverInfo, mimeType, isSymlink}, {loadMimeType}, {path}) => ({
url: Constants.generateFileURL(path, _serverInfo),
mimeType,
isSymlink,
path,
loadMimeType,
})
const Renderer = ({mimeType, isSymlink, url, path, routePath, loadMimeType}) => {
if (isSymlink) {
return <DefaultView path={path} routePath={routePath} />
}
if (mimeType === '') {
return (
<Box style={stylesLoadingContainer}>
<Text type="BodySmall" style={stylesLoadingText}>
Loading ...
</Text>
</Box>
)
}
switch (Constants.viewTypeFromMimeType(mimeType)) {
case 'default':
return <DefaultView path={path} routePath={routePath} />
case 'text':
return <TextView url={url} routePath={routePath} />
case 'image':
return <ImageView url={url} routePath={routePath} />
case 'av':
return <AVView url={url} routePath={routePath} />
case 'pdf':
return isAndroid ? ( // Android WebView doesn't support PDF. Come on Android!
<DefaultView path={path} routePath={routePath} />
) : (
<PdfView url={url} routePath={routePath} />
)
default:
return <Text type="BodyError">This shouldn't happen</Text>
}
}
const stylesLoadingContainer = {
...globalStyles.flexBoxColumn,
...globalStyles.flexGrow,
alignItems: 'center',
justifyContent: 'center',
}
const stylesLoadingText = platformStyles({
isMobile: {
color: globalColors.white_40,
},
})
export default compose(
connect(mapStateToProps, mapDispatchToProps, mergeProps),
setDisplayName('ViewContainer'),
lifecycle({
componentDidMount() {
if (!this.props.isSymlink && this.props.mimeType === '') {
this.props.loadMimeType()
}
},
componentDidUpdate(prevProps) {
if (
!this.props.isSymlink &&
// Trigger loadMimeType if we don't have it yet,
this.props.mimeType === '' &&
// but only if we haven't triggered it before.
prevProps.mimeType !== ''
) {
this.props.loadMimeType()
}
},
})
)(Renderer)
|
// @flow
import * as I from 'immutable'
import {
compose,
connect,
lifecycle,
type Dispatch,
type TypedState,
setDisplayName,
} from '../../util/container'
import * as Constants from '../../constants/fs'
import * as FsGen from '../../actions/fs-gen'
import * as React from 'react'
import * as Types from '../../constants/types/fs'
import DefaultView from './default-view-container'
import ImageView from './image-view'
import TextView from './text-view'
import AVView from './av-view'
import PdfView from './pdf-view'
import {Box, Text} from '../../common-adapters'
import {globalStyles, globalColors, platformStyles} from '../../styles'
type Props = {
path: Types.Path,
routePath: I.List<string>,
}
const mapStateToProps = (state: TypedState, {path}: Props) => {
const _pathItem = state.fs.pathItems.get(path) || Constants.makeFile()
return {
_serverInfo: state.fs.localHTTPServerInfo,
mimeType: _pathItem.type === 'file' ? _pathItem.mimeType : '',
isSymlink: _pathItem.type === 'symlink',
}
}
const mapDispatchToProps = (dispatch: Dispatch, {path}: Props) => ({
loadMimeType: () => dispatch(FsGen.createMimeTypeLoad({path})),
})
const mergeProps = ({_serverInfo, mimeType, isSymlink}, {loadMimeType}, {path}) => ({
url: Constants.generateFileURL(path, _serverInfo),
mimeType,
isSymlink,
path,
loadMimeType,
})
const Renderer = ({mimeType, isSymlink, url, path, routePath, loadMimeType}) => {
if (isSymlink) {
return <DefaultView path={path} routePath={routePath} />
}
if (mimeType === '') {
return (
<Box style={stylesLoadingContainer}>
<Text type="BodySmall" style={stylesLoadingText}>
Loading ...
</Text>
</Box>
)
}
switch (Constants.viewTypeFromMimeType(mimeType)) {
case 'default':
return <DefaultView path={path} routePath={routePath} />
case 'text':
return <TextView url={url} routePath={routePath} />
case 'image':
return <ImageView url={url} routePath={routePath} />
case 'av':
return <AVView url={url} routePath={routePath} />
case 'pdf':
return <PdfView url={url} routePath={routePath} />
default:
return <Text type="BodyError">This shouldn't happen</Text>
}
}
const stylesLoadingContainer = {
...globalStyles.flexBoxColumn,
...globalStyles.flexGrow,
alignItems: 'center',
justifyContent: 'center',
}
const stylesLoadingText = platformStyles({
isMobile: {
color: globalColors.white_40,
},
})
export default compose(
connect(mapStateToProps, mapDispatchToProps, mergeProps),
setDisplayName('ViewContainer'),
lifecycle({
componentDidMount() {
if (!this.props.isSymlink && this.props.mimeType === '') {
this.props.loadMimeType()
}
},
componentDidUpdate(prevProps) {
if (
!this.props.isSymlink &&
// Trigger loadMimeType if we don't have it yet,
this.props.mimeType === '' &&
// but only if we haven't triggered it before.
prevProps.mimeType !== ''
) {
this.props.loadMimeType()
}
},
})
)(Renderer)
|
JavaScript
| 0
|
de3fe9b8720657c3acd70272aa62aa37aaace1c1
|
Change logic for loading state of checkbox.
|
assets/js/components/settings/SettingsPlugin.js
|
assets/js/components/settings/SettingsPlugin.js
|
/**
* SettingsPlugin component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useCallback } from '@wordpress/element';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { CORE_SITE } from '../../googlesitekit/datastore/site/constants';
import { Cell, Grid, Row } from '../../material-components';
import Layout from '../layout/Layout';
import Checkbox from '../Checkbox';
const { useDispatch, useSelect } = Data;
export default function SettingsPlugin() {
const showAdminBar = useSelect( ( select ) =>
select( CORE_SITE ).getShowAdminBar()
);
const { setShowAdminBar } = useDispatch( CORE_SITE );
const onAdminBarToggle = useCallback(
( { target } ) => {
setShowAdminBar( !! target.checked );
},
[ setShowAdminBar ]
);
return (
<Layout
className="googlesitekit-settings-meta"
title={ __( 'Plugin Settings', 'google-site-kit' ) }
header
fill
>
<div className="googlesitekit-settings-module googlesitekit-settings-module--active">
<Grid>
<Row>
<Cell size={ 12 }>
<div className="googlesitekit-settings-module__meta-items">
<div className="googlesitekit-settings-module__meta-item googlesitekit-settings-module__meta-item--nomargin">
<Checkbox
id="admin-bar-toggle"
name="admin-bar-toggle"
value="1"
checked={ showAdminBar }
onChange={ onAdminBarToggle }
disabled={ showAdminBar === undefined }
loading={ showAdminBar === undefined }
>
<span>
{ __(
'Display relevant page stats in the Admin bar',
'google-site-kit'
) }
</span>
</Checkbox>
</div>
</div>
</Cell>
</Row>
</Grid>
</div>
</Layout>
);
}
|
/**
* SettingsPlugin component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useCallback } from '@wordpress/element';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { CORE_SITE } from '../../googlesitekit/datastore/site/constants';
import { Cell, Grid, Row } from '../../material-components';
import Layout from '../layout/Layout';
import Checkbox from '../Checkbox';
const { useDispatch, useSelect } = Data;
export default function SettingsPlugin() {
const showAdminBar = useSelect( ( select ) =>
select( CORE_SITE ).getShowAdminBar()
);
const { setShowAdminBar } = useDispatch( CORE_SITE );
const onAdminBarToggle = useCallback(
( { target } ) => {
setShowAdminBar( !! target.checked );
},
[ setShowAdminBar ]
);
return (
<Layout
className="googlesitekit-settings-meta"
title={ __( 'Plugin Settings', 'google-site-kit' ) }
header
fill
>
<div className="googlesitekit-settings-module googlesitekit-settings-module--active">
<Grid>
<Row>
<Cell size={ 12 }>
<div className="googlesitekit-settings-module__meta-items">
<div className="googlesitekit-settings-module__meta-item googlesitekit-settings-module__meta-item--nomargin">
<Checkbox
id="admin-bar-toggle"
name="admin-bar-toggle"
value="1"
checked={ showAdminBar }
onChange={ onAdminBarToggle }
disabled={ showAdminBar === undefined }
loading={
typeof showAdminBar !== 'boolean'
}
>
<span>
{ __(
'Display relevant page stats in the Admin bar',
'google-site-kit'
) }
</span>
</Checkbox>
</div>
</div>
</Cell>
</Row>
</Grid>
</div>
</Layout>
);
}
|
JavaScript
| 0
|
e92e2ae45a2d6a7a049149be654528d4ff199bd4
|
Update js gulp task
|
gulp/tasks/javascript.js
|
gulp/tasks/javascript.js
|
'use strict';
var watchify = require('watchify');
var browserify = require('browserify');
var gulp = require('gulp');
var changed = require('gulp-changed');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var gutil = require('gulp-util');
var maps = require('gulp-sourcemaps');
var assign = require('lodash.assign');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var customOpts = {
entries: ['assets/js/main.js'],
debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));
var DEST = './build';
gulp.task('js', bundle);
b.on('update', bundle);
b.on('log', gutil.log);
function bundle() {
return b.bundle()
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('app'))
.pipe(changed(DEST))
.pipe(rename({ extname: '.js' }))
.pipe(gulp.dest(DEST))
.pipe(buffer())
.pipe(uglify())
// .pipe(maps.init({loadMaps: true}))
// .pipe(maps.write('./'))
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest(DEST))
}
|
'use strict';
var watchify = require('watchify');
var browserify = require('browserify');
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var gutil = require('gulp-util');
var maps = require('gulp-sourcemaps');
var assign = require('lodash.assign');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var customOpts = {
entries: ['assets/js/main.js'],
debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));
gulp.task('js', bundle);
b.on('update', bundle);
b.on('log', gutil.log);
function bundle() {
return b.bundle()
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('app'))
.pipe(rename({ extname: '.js' }))
.pipe(gulp.dest('./build/'))
.pipe(buffer())
.pipe(uglify())
// .pipe(maps.init({loadMaps: true}))
// .pipe(maps.write('./'))
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest('./build'))
}
|
JavaScript
| 0
|
1b8a369d6c3358a05ca5988acd3a8cc8d3e1259e
|
Add admin bar checkbox.
|
assets/js/components/settings/SettingsPlugin.js
|
assets/js/components/settings/SettingsPlugin.js
|
/**
* SettingsPlugin component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useCallback } from '@wordpress/element';
/**
* Internal dependencies
*/
import { Cell, Grid, Row } from '../../material-components';
import Layout from '../layout/Layout';
import Checkbox from '../Checkbox';
export default function SettingsPlugin() {
const onAdminBarToggle = useCallback( () => {
}, [] );
return (
<Layout
className="googlesitekit-settings-meta"
title={ __( 'Plugin Settings', 'google-site-kit' ) }
header
fill
>
<div className="googlesitekit-settings-module googlesitekit-settings-module--active">
<Grid>
<Row>
<Cell size={ 12 }>
<div className="googlesitekit-settings-module__meta-items">
<div className="googlesitekit-settings-module__meta-item googlesitekit-settings-module__meta-item--nomargin">
<Checkbox
id="admin-bar-toggle"
name="admin-bar-toggle"
value="1"
onChange={ onAdminBarToggle }
>
<span>
{ __( 'Display relevant page stats in the Admin bar', 'google-site-kit' ) }
</span>
</Checkbox>
</div>
</div>
</Cell>
</Row>
</Grid>
</div>
</Layout>
);
}
|
/**
* SettingsPlugin component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { Cell, Grid, Row } from '../../material-components';
import Layout from '../layout/Layout';
export default function SettingsPlugin() {
return (
<Layout
className="googlesitekit-settings-meta"
title={ __( 'Plugin Settings', 'google-site-kit' ) }
header
fill
>
<div className="googlesitekit-settings-module googlesitekit-settings-module--active">
<Grid>
<Row>
<Cell size={ 12 }>
<div className="googlesitekit-settings-module__meta-items">
<div className="googlesitekit-settings-module__meta-item googlesitekit-settings-module__meta-item--nomargin">
</div>
</div>
</Cell>
</Row>
</Grid>
</div>
</Layout>
);
}
|
JavaScript
| 0
|
f8e504dd14c2ec878449c4d63d7d7bf6f7a123d2
|
Fix missing accumulator in deploy.js authz (#926)
|
commands/deploy.js
|
commands/deploy.js
|
"use strict";
var _ = require("lodash");
var requireInstance = require("../lib/requireInstance");
var requirePermissions = require("../lib/requirePermissions");
var checkDupHostingKeys = require("../lib/checkDupHostingKeys");
var checkValidTargetFilters = require("../lib/checkValidTargetFilters");
var checkFirebaseSDKVersion = require("../lib/checkFirebaseSDKVersion");
var Command = require("../lib/command");
var deploy = require("../lib/deploy");
var requireConfig = require("../lib/requireConfig");
var filterTargets = require("../lib/filterTargets");
// in order of least time-consuming to most time-consuming
var VALID_TARGETS = ["database", "storage", "firestore", "functions", "hosting"];
var TARGET_PERMISSIONS = {
database: ["firebasedatabase.instances.update"],
hosting: ["firebasehosting.sites.update"],
functions: [
"cloudfunctions.functions.list",
"cloudfunctions.functions.create",
"cloudfunctions.functions.get",
"cloudfunctions.functions.update",
"cloudfunctions.functions.delete",
"cloudfunctions.operations.get",
],
firestore: [
"datastore.indexes.list",
"datastore.indexes.create",
"datastore.indexes.update",
"datastore.indexes.delete",
],
storage: [
"firebaserules.releases.create",
"firebaserules.rulesets.create",
"firebaserules.releases.update",
],
};
module.exports = new Command("deploy")
.description("deploy code and assets to your Firebase project")
.option("-p, --public <path>", "override the Hosting public directory specified in firebase.json")
.option("-m, --message <message>", "an optional message describing this deploy")
.option(
"--only <targets>",
'only deploy to specified, comma-separated targets (e.g. "hosting,storage"). For functions, ' +
'can specify filters with colons to scope function deploys to only those functions (e.g. "--only functions:func1,functions:func2"). ' +
"When filtering based on export groups (the exported module object keys), use dots to specify group names " +
'(e.g. "--only functions:group1.subgroup1,functions:group2)"'
)
.option("--except <targets>", 'deploy to all targets except specified (e.g. "database")')
.before(requireConfig)
.before(function(options) {
options.filteredTargets = filterTargets(options, VALID_TARGETS);
const permissions = options.filteredTargets.reduce((perms, target) => {
return perms.concat(TARGET_PERMISSIONS[target]);
}, []);
return requirePermissions(options, permissions);
})
.before(function(options) {
// only fetch the default instance for hosting or database deploys
if (_.intersection(options.filteredTargets, ["hosting", "database"]).length > 0) {
return requireInstance(options);
}
})
.before(checkDupHostingKeys)
.before(checkValidTargetFilters)
.before(checkFirebaseSDKVersion)
.action(function(options) {
return deploy(options.filteredTargets, options);
});
|
"use strict";
var _ = require("lodash");
var requireInstance = require("../lib/requireInstance");
var requirePermissions = require("../lib/requirePermissions");
var checkDupHostingKeys = require("../lib/checkDupHostingKeys");
var checkValidTargetFilters = require("../lib/checkValidTargetFilters");
var checkFirebaseSDKVersion = require("../lib/checkFirebaseSDKVersion");
var Command = require("../lib/command");
var deploy = require("../lib/deploy");
var requireConfig = require("../lib/requireConfig");
var filterTargets = require("../lib/filterTargets");
// in order of least time-consuming to most time-consuming
var VALID_TARGETS = ["database", "storage", "firestore", "functions", "hosting"];
var TARGET_PERMISSIONS = {
database: ["firebasedatabase.instances.update"],
hosting: ["firebasehosting.sites.update"],
functions: [
"cloudfunctions.functions.list",
"cloudfunctions.functions.create",
"cloudfunctions.functions.get",
"cloudfunctions.functions.update",
"cloudfunctions.functions.delete",
"cloudfunctions.operations.get",
],
firestore: [
"datastore.indexes.list",
"datastore.indexes.create",
"datastore.indexes.update",
"datastore.indexes.delete",
],
storage: [
"firebaserules.releases.create",
"firebaserules.rulesets.create",
"firebaserules.releases.update",
],
};
module.exports = new Command("deploy")
.description("deploy code and assets to your Firebase project")
.option("-p, --public <path>", "override the Hosting public directory specified in firebase.json")
.option("-m, --message <message>", "an optional message describing this deploy")
.option(
"--only <targets>",
'only deploy to specified, comma-separated targets (e.g. "hosting,storage"). For functions, ' +
'can specify filters with colons to scope function deploys to only those functions (e.g. "--only functions:func1,functions:func2"). ' +
"When filtering based on export groups (the exported module object keys), use dots to specify group names " +
'(e.g. "--only functions:group1.subgroup1,functions:group2)"'
)
.option("--except <targets>", 'deploy to all targets except specified (e.g. "database")')
.before(requireConfig)
.before(function(options) {
options.filteredTargets = filterTargets(options, VALID_TARGETS);
const permissions = options.filteredTargets.reduce((perms, target) => {
return perms.concat(TARGET_PERMISSIONS[target]);
});
return requirePermissions(options, permissions);
})
.before(function(options) {
// only fetch the default instance for hosting or database deploys
if (_.intersection(options.filteredTargets, ["hosting", "database"]).length > 0) {
return requireInstance(options);
}
})
.before(checkDupHostingKeys)
.before(checkValidTargetFilters)
.before(checkFirebaseSDKVersion)
.action(function(options) {
return deploy(options.filteredTargets, options);
});
|
JavaScript
| 0.000001
|
df1ffe63d46e3a3c4c74ae2e7f531254ad2b5d24
|
Include mojular dependency in JS file
|
assets/scripts/modules/conditional-subfields.js
|
assets/scripts/modules/conditional-subfields.js
|
require('mojular');
var $ = require('jquery');
Mojular.Modules.ConditionalSubfields = {
el: '[data-controlled-by]',
init: function() {
this.cacheEls();
this.bindEvents();
this.setInitialState();
this.replaceLabels();
},
setInitialState: function() {
var self = this;
this.conditionalFields
.each(function() {
var $fields = $('[name="' + $(this).data('controlled-by') + '"]');
$fields = $fields.filter(function() {
// Unchecked checkbox or checked radio button
return this.type === 'checkbox' || $(this).is(':checked');
});
$fields.each($.proxy(self.handleVisibility, self));
});
},
// If CONDITIONAL_LABELS constant exists its contents will be used to
// replace fields on page load.
// e.g. If non-JS page has a label "If Yes, how many?" (referring to previous field)
// Adding `CONDITIONAL_LABELS['num_children'] = 'How many?'` would change label to 'How many?'
// when JS kicks in.
replaceLabels: function() {
if(!window.CONDITIONAL_LABELS) {
return;
}
$.each(window.CONDITIONAL_LABELS, function(key, value) {
$('#field-' + key + '')
.find('.fieldset-label *')
.text(value);
});
},
bindEvents: function() {
var self = this;
var controllers = $.unique(this.conditionalFields.map(function() {
return $(this).data('controlled-by');
}));
$.each(controllers, function() {
$('[name="' + this + '"]').on('change', $.proxy(self.handleVisibility, self));
});
},
handleVisibility: function() {
var self = this;
this.conditionalFields.each(function() {
self._handleField($(this));
});
},
_handleField: function($field) {
// `controlled-by` specifies the field name which controls the visibility of element
var controlInputName = $field.data('controlled-by');
// `control-value` is the value which should trigger the visibility of element
var controlInputValue = $field.data('control-value') + '';
var $controlInput = $('[name="' + controlInputName + '"]');
// control visibility only for specified value (unless it's a wildcard `*`)
if(controlInputValue && controlInputValue !== '*') {
$controlInput = $controlInput.filter('[value="' + controlInputValue + '"]');
}
this._toggleField($field, $controlInput.is(':checked'));
},
_toggleField: function($field, isVisible) {
$field
.toggleClass('u-expanded', isVisible)
.toggleClass('u-hidden', !isVisible)
.attr({
'aria-expanded': isVisible,
'aria-hidden': !isVisible
});
if(!isVisible && !$field.data('persist-values')) {
$field.find('input')
.prop('checked', false)
.trigger('label-select');
}
},
cacheEls: function() {
this.conditionalFields = $(this.el);
}
};
|
var $ = require('jquery');
Mojular.Modules.ConditionalSubfields = {
el: '[data-controlled-by]',
init: function() {
this.cacheEls();
this.bindEvents();
this.setInitialState();
this.replaceLabels();
},
setInitialState: function() {
var self = this;
this.conditionalFields
.each(function() {
var $fields = $('[name="' + $(this).data('controlled-by') + '"]');
$fields = $fields.filter(function() {
// Unchecked checkbox or checked radio button
return this.type === 'checkbox' || $(this).is(':checked');
});
$fields.each($.proxy(self.handleVisibility, self));
});
},
// If CONDITIONAL_LABELS constant exists its contents will be used to
// replace fields on page load.
// e.g. If non-JS page has a label "If Yes, how many?" (referring to previous field)
// Adding `CONDITIONAL_LABELS['num_children'] = 'How many?'` would change label to 'How many?'
// when JS kicks in.
replaceLabels: function() {
if(!window.CONDITIONAL_LABELS) {
return;
}
$.each(window.CONDITIONAL_LABELS, function(key, value) {
$('#field-' + key + '')
.find('.fieldset-label *')
.text(value);
});
},
bindEvents: function() {
var self = this;
var controllers = $.unique(this.conditionalFields.map(function() {
return $(this).data('controlled-by');
}));
$.each(controllers, function() {
$('[name="' + this + '"]').on('change', $.proxy(self.handleVisibility, self));
});
},
handleVisibility: function() {
var self = this;
this.conditionalFields.each(function() {
self._handleField($(this));
});
},
_handleField: function($field) {
// `controlled-by` specifies the field name which controls the visibility of element
var controlInputName = $field.data('controlled-by');
// `control-value` is the value which should trigger the visibility of element
var controlInputValue = $field.data('control-value') + '';
var $controlInput = $('[name="' + controlInputName + '"]');
// control visibility only for specified value (unless it's a wildcard `*`)
if(controlInputValue && controlInputValue !== '*') {
$controlInput = $controlInput.filter('[value="' + controlInputValue + '"]');
}
this._toggleField($field, $controlInput.is(':checked'));
},
_toggleField: function($field, isVisible) {
$field
.toggleClass('u-expanded', isVisible)
.toggleClass('u-hidden', !isVisible)
.attr({
'aria-expanded': isVisible,
'aria-hidden': !isVisible
});
if(!isVisible && !$field.data('persist-values')) {
$field.find('input')
.prop('checked', false)
.trigger('label-select');
}
},
cacheEls: function() {
this.conditionalFields = $(this.el);
}
};
|
JavaScript
| 0
|
001d1f491a789278132055db39281d2024b584af
|
use the configured id of a model - fixes list.get(model)
|
model/list/list.js
|
model/list/list.js
|
steal('can/model/list','jquery/model').then(function() {
// List.get used to take a model or list of models
var getList = $.Model.List.prototype.get;
$.Model.List.prototype.get = function(arg) {
var ids, id;
if(arg instanceof $.Model.List) {
ids = [];
$.each(arg,function() {
ids.push(this.attr('id'));
});
arg = ids;
} else if(arg.attr && arg.constructor && (id = arg.attr(arg.constructor.id))) {
arg = id;
}
return getList.apply(this,arguments);
};
// restore the ability to push a list!arg
var push = $.Model.List.prototype.push;
$.Model.List.prototype.push = function(arg) {
if(arg instanceof $.Model.List) {
arg = can.makeArray(arg);
}
return push.apply(this,arguments);
};
});
|
steal('can/model/list','jquery/model').then(function() {
// List.get used to take a model or list of models
var getList = $.Model.List.prototype.get;
$.Model.List.prototype.get = function(arg) {
var ids;
if(arg instanceof $.Model.List) {
ids = [];
$.each(arg,function() {
ids.push(this.attr('id'));
});
arg = ids;
} else if(arg.attr && arg.attr('id')) {
arg = arg.attr('id');
}
return getList.apply(this,arguments);
};
// restore the ability to push a list!arg
var push = $.Model.List.prototype.push;
$.Model.List.prototype.push = function(arg) {
if(arg instanceof $.Model.List) {
arg = can.makeArray(arg);
}
return push.apply(this,arguments);
};
});
|
JavaScript
| 0
|
dbc30e11332b9be3a63634bad5410c820092ab32
|
command is no array
|
commands/reload.js
|
commands/reload.js
|
const alias = require('../events/message.js').alias;
exports.run = async(client, msg, args) => {
if (!args || args.length < 1) return msg.reply('Please type the command name to reload');
let command;
if (require('./' + args[0])) {
command = args[0]
}
try {
delete require.cache[require.resolve(`./` + command)];
msg.channel.send(`Reloaded command ${command}`);
} catch (e) {
msg.channel.send(`**${command}** Does not exists.`)
}
};
exports.help = {
category : 'dev only',
usage : '[command name]',
description: 'Reloads a command',
detail : 'Reload the command code without need of restarting the bot.',
botPerm : ['SEND_MESSAGES'],
authorPerm : [],
alias : [
null
]
};
|
const alias = require('../events/message.js').alias;
exports.run = async(client, msg, args) => {
if (!args || args.length < 1) return msg.reply('Please type the command name to reload');
let command;
if (require('./' + args[0])) {
command = args[0]
}
try {
delete require.cache[require.resolve(`./` + command[0])];
msg.channel.send(`Reloaded command ${command}`);
} catch (e) {
msg.channel.send(`**${command}** Does not exists.`)
}
};
exports.help = {
category : 'dev only',
usage : '[command name]',
description: 'Reloads a command',
detail : 'Reload the command code without need of restarting the bot.',
botPerm : ['SEND_MESSAGES'],
authorPerm : [],
alias : [
null
]
};
|
JavaScript
| 0.999999
|
75beb0542a3541e2e48c3d5c6455969c69409e4d
|
Tidy up.
|
src/article/shared/EditEntityCommand.js
|
src/article/shared/EditEntityCommand.js
|
import { Command } from 'substance'
/*
This is a preliminary solultion that switches to the correct view and scrolls
the selected node into view.
On the long run we want to let the views be independent, e.g. using a popup instead.
*/
export default class EditEntityCommand extends Command {
getCommandState (params, context) {
let sel = params.selection
let newState = {
disabled: true
}
// this command only becomes active for a specific type of custom selection,
// e.g. if you want to use it, provide config with selectionType property
if (sel.isCustomSelection()) {
if (sel.customType === this.config.selectionType) {
newState.disabled = false
newState.nodeId = sel.nodeId
}
}
return newState
}
execute (params, context) {
const appState = context.appState
const viewName = appState.get('viewName')
if (viewName !== 'metadata') {
const sel = params.selection
const nodeId = sel.nodeId
context.editor.send('updateViewName', 'metadata')
// HACK: using the ArticlePanel instance to get to the current editor
// so that we can dispatch 'executeCommand'
let editor = context.articlePanel.refs.content
editor.send('scrollTo', { nodeId })
// HACK: this is a mess because context.api is a different instance after
// switching to metadata view
// TODO: we should extend ArticleAPI to allow for this
editor.api.selectFirstRequiredPropertyOfMetadataCard(nodeId)
}
}
}
|
import { Command } from 'substance'
/*
This command intended to switch view and scroll to the selected node.
Command state becoming active only for certain type of custom selection,
e.g. if you want to use it, provide config with selectionType property.
*/
export default class EditEntityCommand extends Command {
getCommandState (params, context) {
let sel = params.selection
let newState = {
disabled: true
}
if (sel.isCustomSelection()) {
if (sel.customType === this.config.selectionType) {
newState.disabled = false
newState.nodeId = sel.nodeId
}
}
return newState
}
execute (params, context) {
const appState = context.appState
const viewName = appState.get('viewName')
if (viewName !== 'metadata') {
const sel = params.selection
const nodeId = sel.nodeId
context.editor.send('updateViewName', 'metadata')
// HACK: using the ArticlePanel instance to get to the current editor
// so that we can dispatch 'executeCommand'
let editor = context.articlePanel.refs.content
editor.send('scrollTo', { nodeId })
// HACK: this is a mess because context.api is a different instance after
// switching to metadata view
// TODO: we should extend ArticleAPI to allow for this
editor.api.selectFirstRequiredPropertyOfMetadataCard(nodeId)
}
}
}
|
JavaScript
| 0.000002
|
46dfb3990aa247d9406704d13f2d6734d7d31a72
|
add sqrt and fix getType
|
examples/js/nodes/math/Math1Node.js
|
examples/js/nodes/math/Math1Node.js
|
/**
* @author sunag / http://www.sunag.com.br/
*/
THREE.Math1Node = function( a, method ) {
THREE.TempNode.call( this );
this.a = a;
this.method = method || THREE.Math1Node.SIN;
};
THREE.Math1Node.RAD = 'radians';
THREE.Math1Node.DEG = 'degrees';
THREE.Math1Node.EXP = 'exp';
THREE.Math1Node.EXP2 = 'exp2';
THREE.Math1Node.LOG = 'log';
THREE.Math1Node.LOG2 = 'log2';
THREE.Math1Node.SQRT = 'sqrt';
THREE.Math1Node.INV_SQRT = 'inversesqrt';
THREE.Math1Node.FLOOR = 'floor';
THREE.Math1Node.CEIL = 'ceil';
THREE.Math1Node.NORMALIZE = 'normalize';
THREE.Math1Node.FRACT = 'fract';
THREE.Math1Node.SAT = 'saturate';
THREE.Math1Node.SIN = 'sin';
THREE.Math1Node.COS = 'cos';
THREE.Math1Node.TAN = 'tan';
THREE.Math1Node.ASIN = 'asin';
THREE.Math1Node.ACOS = 'acos';
THREE.Math1Node.ARCTAN = 'atan';
THREE.Math1Node.ABS = 'abs';
THREE.Math1Node.SIGN = 'sign';
THREE.Math1Node.LENGTH = 'length';
THREE.Math1Node.NEGATE = 'negate';
THREE.Math1Node.INVERT = 'invert';
THREE.Math1Node.prototype = Object.create( THREE.TempNode.prototype );
THREE.Math1Node.prototype.constructor = THREE.Math1Node;
THREE.Math1Node.prototype.getType = function( builder ) {
switch ( this.method ) {
case THREE.Math1Node.LENGTH:
return 'fv1';
}
return this.a.getType( builder );
};
THREE.Math1Node.prototype.generate = function( builder, output ) {
var material = builder.material;
var type = this.getType( builder );
var result = this.a.build( builder, type );
switch ( this.method ) {
case THREE.Math1Node.NEGATE:
result = '(-' + result + ')';
break;
case THREE.Math1Node.INVERT:
result = '(1.0-' + result + ')';
break;
default:
result = this.method + '(' + result + ')';
break;
}
return builder.format( result, type, output );
};
|
/**
* @author sunag / http://www.sunag.com.br/
*/
THREE.Math1Node = function( a, method ) {
THREE.TempNode.call( this );
this.a = a;
this.method = method || THREE.Math1Node.SIN;
};
THREE.Math1Node.RAD = 'radians';
THREE.Math1Node.DEG = 'degrees';
THREE.Math1Node.EXP = 'exp';
THREE.Math1Node.EXP2 = 'exp2';
THREE.Math1Node.LOG = 'log';
THREE.Math1Node.LOG2 = 'log2';
THREE.Math1Node.INVERSE_SQRT = 'inversesqrt';
THREE.Math1Node.FLOOR = 'floor';
THREE.Math1Node.CEIL = 'ceil';
THREE.Math1Node.NORMALIZE = 'normalize';
THREE.Math1Node.FRACT = 'fract';
THREE.Math1Node.SAT = 'saturate';
THREE.Math1Node.SIN = 'sin';
THREE.Math1Node.COS = 'cos';
THREE.Math1Node.TAN = 'tan';
THREE.Math1Node.ASIN = 'asin';
THREE.Math1Node.ACOS = 'acos';
THREE.Math1Node.ARCTAN = 'atan';
THREE.Math1Node.ABS = 'abs';
THREE.Math1Node.SIGN = 'sign';
THREE.Math1Node.LENGTH = 'length';
THREE.Math1Node.NEGATE = 'negate';
THREE.Math1Node.INVERT = 'invert';
THREE.Math1Node.prototype = Object.create( THREE.TempNode.prototype );
THREE.Math1Node.prototype.constructor = THREE.Math1Node;
THREE.Math1Node.prototype.getType = function( builder ) {
switch ( this.method ) {
case THREE.Math1Node.DISTANCE:
return 'fv1';
}
return this.a.getType( builder );
};
THREE.Math1Node.prototype.generate = function( builder, output ) {
var material = builder.material;
var type = this.getType( builder );
var result = this.a.build( builder, type );
switch ( this.method ) {
case THREE.Math1Node.NEGATE:
result = '(-' + result + ')';
break;
case THREE.Math1Node.INVERT:
result = '(1.0-' + result + ')';
break;
default:
result = this.method + '(' + result + ')';
break;
}
return builder.format( result, type, output );
};
|
JavaScript
| 0
|
7ba1b5ea23471b4c2df9f0cbd45afd9764dd4b98
|
Fix build process for Leaflet.markercluster
|
Jakefile.js
|
Jakefile.js
|
const LeafletBuild = require('./vendor/leaflet/build/build')
const MarkerClusterBuild = require('./vendor/leaflet-markercluster/build/build')
function pushdAsync(wd) {
const oldwd = process.cwd()
process.chdir(wd)
return () => {
process.chdir(oldwd)
complete()
}
}
function installDepsCmd() {
// https://github.com/ForbesLindesay/spawn-sync/blob/b0063ee33b17feaa905602f0b2ff72b4acd1bdbb/postinstall.js#L29
const npm = process.env.npm_execpath ? `"${process.argv[0]}" "${process.env.npm_execpath}"` : 'npm'
return `${npm} install`
}
desc('Build Leaflet')
task('build-leaflet', ['fetchdeps-leaflet'], {async: true}, () => {
console.log('.. Building Leaflet ..')
LeafletBuild.build(pushdAsync('vendor/leaflet'), 'mvspju5')
})
desc('Build Leaflet.markercluster')
task('build-leaflet-markercluster', ['fetchdeps-leaflet-markercluster'], () => {
console.log('.. Building Leaflet.markercluster ..')
const oldwd = process.cwd()
process.chdir('vendor/leaflet-markercluster')
MarkerClusterBuild.build('7')
process.chdir(oldwd)
})
desc('Build dependencies')
task('build-deps', ['build-leaflet', 'build-leaflet-markercluster'])
desc('Download Git submodules')
task('fetch-submodules', {async: true}, () => {
console.log('.. Fetching submodules ..')
jake.exec(
'git submodule update --init --recursive',
{printStdout: true, printStderr: true},
complete
)
})
desc('Download Leaflet dependencies')
task('fetchdeps-leaflet', {async: true}, () => {
console.log('.. Fetching Leaflet dependencies ..')
jake.exec(
installDepsCmd(),
{printStdout: true, printStderr: true},
pushdAsync('vendor/leaflet')
)
})
desc('Download Leaflet.markercluster dependencies')
task('fetchdeps-leaflet-markercluster', {async: true}, () => {
console.log('.. Fetching leaflet-markercluster dependencies ..')
jake.exec(
installDepsCmd(),
{printStdout: true, printStderr: true},
pushdAsync('vendor/leaflet-markercluster')
)
})
desc('Fetch submodule dependencies')
task(
'fetch-submodule-deps',
['fetch-submodules', 'fetchdeps-leaflet', 'fetchdeps-leaflet-markercluster']
)
task('default', ['fetch-submodules', 'build-deps', 'fetch-submodule-deps'])
|
const LeafletBuild = require('./vendor/leaflet/build/build')
const MarkerClusterBuild = require('./vendor/leaflet-markercluster/build/build')
function pushdAsync(wd) {
const oldwd = process.cwd()
process.chdir('vendor/leaflet')
return () => {
process.chdir(oldwd)
complete()
}
}
function installDepsCmd() {
// https://github.com/ForbesLindesay/spawn-sync/blob/b0063ee33b17feaa905602f0b2ff72b4acd1bdbb/postinstall.js#L29
const npm = process.env.npm_execpath ? `"${process.argv[0]}" "${process.env.npm_execpath}"` : 'npm'
return `${npm} install`
}
desc('Build Leaflet')
task('build-leaflet', ['fetchdeps-leaflet'], {async: true}, () => {
console.log('.. Building Leaflet ..')
LeafletBuild.build(pushdAsync('vendor/leaflet'), 'mvspju5')
})
desc('Build Leaflet.markercluster')
task('build-leaflet-markercluster', ['fetchdeps-leaflet-markercluster'], {async: true}, () => {
console.log('.. Building Leaflet.markercluster ..')
MarkerClusterBuild.build(pushdAsync('vendor/leaflet-markercluster'), '7')
})
desc('Build dependencies')
task('build-deps', ['build-leaflet', 'build-leaflet-markercluster'])
desc('Download Git submodules')
task('fetch-submodules', {async: true}, () => {
console.log('.. Fetching submodules ..')
jake.exec(
'git submodule update --init --recursive',
{printStdout: true, printStderr: true},
complete
)
})
desc('Download Leaflet dependencies')
task('fetchdeps-leaflet', {async: true}, () => {
console.log('.. Fetching Leaflet dependencies ..')
jake.exec(
installDepsCmd(),
{printStdout: true, printStderr: true},
pushdAsync('vendor/leaflet')
)
})
desc('Download Leaflet.markercluster dependencies')
task('fetchdeps-leaflet-markercluster', {async: true}, () => {
console.log('.. Fetching leaflet-markercluster dependencies ..')
jake.exec(
installDepsCmd(),
{printStdout: true, printStderr: true},
pushdAsync('vendor/leaflet-markercluster')
)
})
desc('Fetch submodule dependencies')
task(
'fetch-submodule-deps',
['fetch-submodules', 'fetchdeps-leaflet', 'fetchdeps-leaflet-markercluster']
)
task('default', ['fetch-submodules', 'build-deps', 'fetch-submodule-deps'])
|
JavaScript
| 0.000003
|
cc16cd936e582933ac9831f986dcf7fd03d77799
|
Add Gravity Suit (#322)
|
mods/cssb/items.js
|
mods/cssb/items.js
|
'use strict';
exports.BattleItems = {
// VXN
"wondergummi": {
id: "wondergummi",
name: "Wonder Gummi",
spritenum: 538,
naturalGift: {
basePower: 200,
type: "???",
},
isNonStandard: true,
onUpdate: function (pokemon) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
pokemon.eatItem();
}
},
onTryEatItem: function (item, pokemon) {
if (!this.runEvent('TryHeal', pokemon)) return false;
},
onEat: function (pokemon) {
let fakecheck = this.random(1000);
if (fakecheck <= 850) {
this.add('message', 'Its belly felt full!');
this.heal(pokemon.maxhp / 2);
this.add('message', 'Its IQ rose!');
this.boost({
spd: 2,
});
this.boost({
def: 2,
});
} else {
this.add('message', 'Wait... Its a WANDER Gummi!');
this.heal(pokemon.maxhp / 100);
this.add('message', 'It gained the blinker status!');
this.boost({
accuracy: -6,
});
}
},
desc: "Either heals the user's max HP by 1/2, boosts the user's SpD and Def by 2 stages, or heals 1% of their health, but drops accuracy by six stages, when at 1/4 max HP or less, 1/2 if the user's ability is Gluttony. Single use.",
},
// Gligars
"gravitysuit": {
id: "gravitysuit",
name: "Gravity Suit",
spritenum: 581,
fling: {
basePower: 30,
},
onStart: function (pokemon) {
this.useMove('Gravity', pokemon);
this.useMove('Trick Room', pokemon);
},
isNonStandard: true,
desc: "Uses Gravity and Trick Room on Switch-in.",
},
};
|
'use strict';
exports.BattleItems = {
// VXN
"wondergummi": {
id: "wondergummi",
name: "Wonder Gummi",
spritenum: 538,
naturalGift: {
basePower: 200,
type: "???",
},
isNonStandard: true,
onUpdate: function (pokemon) {
if (pokemon.hp <= pokemon.maxhp / 4 || (pokemon.hp <= pokemon.maxhp / 2 && pokemon.hasAbility('gluttony'))) {
pokemon.eatItem();
}
},
onTryEatItem: function (item, pokemon) {
if (!this.runEvent('TryHeal', pokemon)) return false;
},
onEat: function (pokemon) {
let fakecheck = this.random(1000);
if (fakecheck <= 850) {
this.add('message', 'Its belly felt full!');
this.heal(pokemon.maxhp / 2);
this.add('message', 'Its IQ rose!');
this.boost({
spd: 2,
});
this.boost({
def: 2,
});
} else {
this.add('message', 'Wait... Its a WANDER Gummi!');
this.heal(pokemon.maxhp / 100);
this.add('message', 'It gained the blinker status!');
this.boost({
accuracy: -6,
});
}
},
desc: "Either heals the user's max HP by 1/2, boosts the user's SpD and Def by 2 stages, or heals 1% of their health, but drops accuracy by six stages, when at 1/4 max HP or less, 1/2 if the user's ability is Gluttony. Single use.",
},
};
|
JavaScript
| 0
|
f4d0d54fc30096a9303651548953dcc5418f1db1
|
Update qrCodeScanning.js
|
Moma/Moma.Droid/Assets/Content/scripts/qrCodeScanning.js
|
Moma/Moma.Droid/Assets/Content/scripts/qrCodeScanning.js
|
function qrCodeScanBtn() {
jsBridge.ScanQRCode();
}
function qrCodeTextBtn() {
jsBridge.showQRCodeText();
//showQRText('Emile Berliner \n Born in Germany May 20, 1851, he first worked as a printer, then as a clerk in a \n fabric store. It was here that his talent as an inventor first surfaced. He invented a\nnew loom for weaving cloth. Emile Berliner immigrated to the United States in 1870, following the example of a friend. He spent much of his time at the library\nof the Cooper Institute where he took a keen interest in electricity and sound."');
}
function showQRText(text) {
if (text != "") {
var title = poiIB.find('#title h1');
var content = poiIB.find('#content');
var boxTitle = "QR CODE";
var boxContent = text;
title.text(boxTitle);
content.empty();
content.append(boxContent);
poiIB.css('visibility', 'visible');
}
}
|
function qrCodeScanBtn() {
jsBridge.ScanQRCode();
}
function qrCodeTextBtn() {
jsBridge.showQRCodeText();
//showQRText('Emile Berliner \n Born in Germany May 20, 1851, he first worked as a printer, then as a clerk in a \n fabric store. It was here that his talent as an inventor first surfaced. He invented a\nnew loom for weaving cloth. Emile Berliner immigrated to the United States in 1870, following the example of a friend. He spent much of his time at the library\nof the Cooper Institute where he took a keen interest in electricity and sound."');
}
function showQRText(text) {
var title = poiIB.find('#title h1');
var content = poiIB.find('#content');
var boxTitle = "QR CODE";
var boxContent = text;
title.text(boxTitle);
content.empty();
content.append(boxContent);
poiIB.css('visibility', 'visible');
}
|
JavaScript
| 0
|
2bbf83c79a1ba863af40a557d78ca442ff7a1fc8
|
Build bundle in Travis.
|
test/ui-examples-test.js
|
test/ui-examples-test.js
|
const tape = require('tape'),
phylotree = require('../dist/phylotree'),
express = require('express'),
puppeteer = require('puppeteer');
const app = express();
const PORT = process.env.PORT || 8888;
const HEADLESS = process.env.HEADLESS == 'false' ? false : true;
app.use(express.static('.'));
var server, browser, page;
function get_example_url(example) {
return 'http://localhost:' + PORT + '/examples/' + example;
}
tape("setup", async function(test) {
browser = await puppeteer.launch({
headless: HEADLESS,
slowMo: 50,
devtools: false,
timeout: 10000
});
page = (await browser.pages())[0];
await page.setViewport({
width: 1200,
height: 800
})
server = app.listen(PORT, function() {
console.log('Started server on port', PORT);
});
test.end();
});
tape("Hello world loads", async function(test) {
await page.setViewport({
width: 1200,
height: 800
});
await page.goto(get_example_url('hello-world'));
await page.waitForSelector('#tree_display');
const treeHandle = await page.$('#tree_display');
const treeContents = await page.evaluate(
treeContainer => treeContainer.innerHTML,
treeHandle
);
test.assert(treeContents);
test.end();
});
tape("Selectome loads", async function(test) {
await page.setViewport({
width: 1200,
height: 800
});
await page.goto(get_example_url('selectome'));
await page.waitForSelector('#tree_display');
const treeHandle = await page.$('#tree_display');
const treeContents = await page.evaluate(
treeContainer => treeContainer.innerHTML,
treeHandle
);
test.assert(treeContents);
test.end();
});
tape("teardown", async function(test) {
await browser.close();
server.close();
test.end();
});
|
const tape = require('tape'),
phylotree = require('../dist/phylotree'),
express = require('express'),
puppeteer = require('puppeteer');
const app = express();
const PORT = process.env.PORT || 8888;
const HEADLESS = process.env.HEADLESS == 'false' ? false : true;
app.use(express.static('.'));
var server, browser, page;
function get_example_url(example) {
return 'http://localhost:' + PORT + '/examples/' + example;
}
tape("setup", async function(test) {
browser = await puppeteer.launch({
headless: HEADLESS,
slowMo: 50,
devtools: false,
timeout: 10000
});
page = (await browser.pages())[0];
await page.setViewport({
width: 1200,
height: 800
})
server = app.listen(PORT, function() {
console.log('Started server on port', PORT);
});
test.end();
});
tape("Hello world loads", async function(test) {
await page.setViewport({
width: 1200,
height: 800
});
await page.goto(get_example_url('hello-world'));
await page.waitForSelector('#tree_display');
const treeHandle = await page.$('#tree_display');
const treeContents = await page.evaluate(
treeContainer => treeContainer.innerHTML,
treeHandle
);
test.assert(treeContents);
test.end();
});
tape("Selctome loads", async function(test) {
await page.setViewport({
width: 1200,
height: 800
});
await page.goto(get_example_url('selectome'));
await page.waitForSelector('#tree_display');
const treeHandle = await page.$('#tree_display');
const treeContents = await page.evaluate(
treeContainer => treeContainer.innerHTML,
treeHandle
);
test.assert(treeContents);
test.end();
});
tape("teardown", async function(test) {
await browser.close();
server.close();
test.end();
});
|
JavaScript
| 0
|
86257d6d52f5f53c3880f4e8de4a74a789baae74
|
Fix copy pasta
|
banana-stand/app/controllers/song.controller.js
|
banana-stand/app/controllers/song.controller.js
|
var server = require('vvps-engine').server,
BaseApiController = require('vvps-engine').controllers.base,
songController = new BaseApiController(require('../models/song.model.js')),
Song = songController.model;
/**
* Get all songs
* TODO search params -- title & artist match
* @param req
* @param res
* @param next
*/
songController.getMany = function (req, res, next) {
Song.find({}, function (err, songs) {
if (err) {
return next(err);
}
else {
res.json(songs);
}
});
};
/**
* Get a song by its id
* @param req
* @param res
* @param next
*/
songController.getOne = function (req, res, next) {
Song.findById(req.params.id, function (err, song) {
if (err) {
return next(err);
}
else {
res.json(song);
}
});
};
module.exports = songController;
|
var server = require('vvps-engine').server,
BaseApiController = require('vvps-engine').controllers.base,
songController = new BaseApiController(require('../models/song.model.js')),
Song = songController.model;
/**
* Get all songs
* @param req
* @param res
* @param next
*/
songController.getMany = function (req, res, next) {
Song.find({}, function (err, songs) {
if (err) {
return next(err);
}
else {
res.json(songs);
}
});
};
/**
* Get a shark by its id
* @param req
* @param res
* @param next
*/
songController.getOne = function (req, res, next) {
Song.findById(req.params.id, function (err, shark) {
if (err) {
return next(err);
}
else {
res.json(shark);
}
});
};
module.exports = songController;
|
JavaScript
| 0.000002
|
296dcb45f7a9f070ebef96edf139cf8ca1664916
|
Append invisible character to buttery output
|
modules/buttery.js
|
modules/buttery.js
|
/**
* Eighteen seconds of spam.
*/
var readline = require( 'readline' );
var fs = require( 'fs' );
module.exports = {
commands: {
buttery: {
help: 'Sings a lovely song',
aliases: [ 'biscuit', 'base', 'wobble' ],
privileged: true, // very spammy!
command: function ( bot, msg ) {
var rl = readline.createInterface( {
input: fs.createReadStream( __rootdir + '/data/buttery.txt' ),
terminal: false
} );
rl.on( 'line', function ( line ) {
bot.say( msg.to, line + '\u200b' /* zero width space */ );
} );
}
}
}
};
|
/**
* Eighteen seconds of spam.
*/
var readline = require( 'readline' );
var fs = require( 'fs' );
module.exports = {
commands: {
buttery: {
help: 'Sings a lovely song',
aliases: [ 'biscuit', 'base', 'wobble' ],
privileged: true, // very spammy!
command: function ( bot, msg ) {
var rl = readline.createInterface( {
input: fs.createReadStream( __rootdir + '/data/buttery.txt' ),
terminal: false
} );
rl.on( 'line', function ( line ) {
bot.say( msg.to, line );
} );
}
}
}
};
|
JavaScript
| 0.998525
|
be4b589fd76f20d00aacf86c886807df0289baf3
|
fix isPlainObject, is comparing object stringified object constructors instead of prototypes (did not work from iframes because Object in iframe is not the same as in parent)
|
src/utils/isPlainObject.js
|
src/utils/isPlainObject.js
|
const fnToString = (fn) => Function.prototype.toString.call(fn);
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
export default function isPlainObject(obj) {
if (!obj || typeof obj !== 'object') {
return false;
}
const proto = typeof obj.constructor === 'function' ? Object.getPrototypeOf(obj) : Object.prototype;
if (proto === null) {
return true;
}
var constructor = proto.constructor;
return typeof constructor === 'function'
&& constructor instanceof constructor
&& fnToString(constructor) === fnToString(Object);
}
|
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
export default function isPlainObject(obj) {
if (!obj) {
return false;
}
return typeof obj === 'object' &&
Object.getPrototypeOf(obj) === Object.prototype;
}
|
JavaScript
| 0
|
0a6a742e2182dbfa150608a0d01c7abc7150bb29
|
Remove the loop-bug
|
role.harvester.js
|
role.harvester.js
|
module.exports = {
run: function(creep) {
if (creep.spawning === false) {
if (creep.memory.sourcenum == undefined) {
var numEnergySources = creep.room.lookForAtArea(LOOK_ENERGY, 0, 0, 49, 49, true).length;
creep.memory.sourcenum = Math.floor(Math.random() * (numEnergySources + 1));
}
if (creep.memory.working === true) {
if (creep.carry.energy === 0) {
creep.memory.working = false;
}
// First find extenstions to fill
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType === STRUCTURE_EXTENSION) &&
structure.energy < structure.energyCapacity;
}
});
if (targets.length > 0) {
if (creep.transfer(targets[0], RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0]);
}
} else {
// Then try towers
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType === STRUCTURE_TOWER) &&
structure.energy < structure.energyCapacity;
}
});
if (targets.length > 0) {
if (creep.transfer(targets[0], RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0]);
}
} else {
// Then try spawns
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType === STRUCTURE_SPAWN) &&
structure.energy < structure.energyCapacity;
}
});
if (targets.length > 0) {
if (creep.transfer(targets[0], RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0]);
}
} else {
// Then try containers or storage
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType === STRUCTURE_CONTAINER ||
structure.structureType === STRUCTURE_STORAGE) &&
structure.store.energy < structure.storeCapacity;
}
});
if (targets.length > 0) {
if (creep.transfer(targets[0], RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0]);
}
} else {
}
}
}
}
} else {
if (creep.carry.energy === creep.carryCapacity) {
creep.memory.working = true;
} else {
var source = creep.room.find(FIND_SOURCES)[creep.memory.sourcenum];
if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
creep.moveTo(source);
}
}
}
}
}
};
|
module.exports = {
run: function(creep) {
if (creep.spawning === false) {
if (creep.memory.sourcenum == undefined) {
var numEnergySources = creep.room.lookForAtArea(LOOK_ENERGY, 0, 0, 49, 49, true).length;
creep.memory.sourcenum = Math.floor(Math.random() * (numEnergySources + 1));
}
if (creep.memory.working === true) {
if (creep.carry.energy === 0) {
creep.memory.working = false;
}
// First find extenstions to fill
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType === STRUCTURE_EXTENSION) &&
structure.energy < structure.energyCapacity;
}
});
if (targets.length > 0) {
if (creep.transfer(targets[0], RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0]);
}
} else {
// Then try towers
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType === STRUCTURE_TOWER) &&
structure.energy < structure.energyCapacity;
}
});
if (targets.length > 0) {
if (creep.transfer(targets[0], RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0]);
}
} else {
// Then try spawns
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType === STRUCTURE_SPAWN) &&
structure.energy < structure.energyCapacity;
}
});
if (targets.length > 0) {
if (creep.transfer(targets[0], RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0]);
}
} else {
// Then try containers or storage
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType === STRUCTURE_CONTAINER ||
structure.structureType === STRUCTURE_STORAGE) &&
structure.store.energy < structure.storeCapacity;
}
});
if (targets.length > 0) {
if (creep.transfer(targets[0], RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
creep.moveTo(targets[0]);
}
} else {
}
}
}
}
} else {
if (creep.carry.energy === creep.carryCapacity) {
creep.memory.working = true;
} else {
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType === STRUCTURE_CONTAINER ||
structure.structureType === STRUCTURE_STORAGE) &&
structure.store.energy > creep.carryCapacity;
}
});
if (targets.length > 0) {
var source = targets[0];
if (creep.withdraw(source, RESOURCE_ENERGY, creep.carryCapacity - creep.carry) === ERR_NOT_IN_RANGE) {
creep.moveTo(source);
}
} else {
var source = creep.room.find(FIND_SOURCES)[creep.memory.sourcenum];
if (creep.harvest(source) === ERR_NOT_IN_RANGE) {
creep.moveTo(source);
}
}
}
}
}
}
};
|
JavaScript
| 0
|
5dc3085a812c52f66d3f64c225437da5531d4277
|
add netease api
|
routes/netease.js
|
routes/netease.js
|
var express = require('express');
var request = require('request');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.header("Content-Type", "application/json;charset=utf-8");
//console.log('ref:' + req.header('referer'));
var id = req.query.id;
var playlist_id = req.query.playlist_id;
var url = 'http://music.163.com/api/song/detail/?id='+id+'&ids=%5B'+id+'%5D';
if(playlist_id){
url = 'http://music.163.com/api/playlist/detail/?id='+playlist_id+'&ids=%5B'+playlist_id+'%5D';
}
netease_http(url,function(data){
return res.send(data);
});
});
function netease_http(url,callback){
var options = {
url: url,
headers: {
Cookie:'appver=1.5.0.75771;',
referer:'http://music.163.com'
}
};
request(options,function(err,res,body){
if(!err && res.statusCode == 200){
body = JSON.parse(body);
callback&&callback(body);
}else{
console.log(err);
}
});
}
module.exports = router;
|
var express = require('express');
var request = require('request');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.header("Content-Type", "application/json;charset=utf-8");
//console.log('ref:' + req.header('referer'));
var id = req.query.id;
var playlist_id = req.query.playlist_id;
var url = 'http://music.163.com/api/song/detail/?id='+id+'&ids=%5B'+id+'%5D';
if(playlist_id){
url = 'http://music.163.com/api/playlist/detail/?id='+id+'&ids=%5B'+id+'%5D';
}
netease_http(url,function(data){
return res.send(data);
});
});
function netease_http(url,callback){
var options = {
url: url,
headers: {
Cookie:'appver=1.5.0.75771;',
referer:'http://music.163.com'
}
};
request(options,function(err,res,body){
if(!err && res.statusCode == 200){
body = JSON.parse(body);
callback&&callback(body);
}else{
console.log(err);
}
});
}
module.exports = router;
|
JavaScript
| 0
|
f139cafb37f0093ab5379843c33648a792d8d42a
|
switch to property 'using asked parameter types'
|
test/arbitrary/command.js
|
test/arbitrary/command.js
|
const assert = require('assert');
const jsc = require('jsverify');
const {command} = require('../../src/arbitrary/command');
const GENSIZE = 10;
function MyEmptyClass(...params) {
this.params = params;
};
describe('command', function() {
describe('generator', function() {
it('should instantiate an object from the given class', function() {
const arb = command(MyEmptyClass);
var v = arb.generator(GENSIZE);
assert.ok(v.command instanceof MyEmptyClass, 'command instance of MyEmptyClass');
assert.ok(Array.isArray(v.parameters), 'parameters is an array');
assert.equal(v.parameters.length, 0, 'parameters array is empty');
});
it('should instantiate using asked parameter types', function() {
const knownArbs = {
"bool" : {
arb: jsc.bool,
check: v => v === true || v === false
},
"nat" : {
arb: jsc.nat,
check: v => typeof(v) === 'number'
},
"oneof": {
arb: jsc.oneof(jsc.constant(5), jsc.constant(42)),
check: v => v === 5 || v === 42
},
"array": {
arb: jsc.array(jsc.nat),
check: v => Array.isArray(v) && v.find(i => typeof(i) !== 'number') === undefined
},
};
const allowedArbs = jsc.oneof.apply(this, Object.keys(knownArbs).map(v => jsc.constant(v)));
jsc.assert(jsc.forall(jsc.array(allowedArbs), function(arbsName) {
const arb = command.apply(this, [MyEmptyClass].concat(arbsName.map(v => knownArbs[v].arb)));
var v = arb.generator(GENSIZE);
var success = true;
success = success && v.command instanceof MyEmptyClass;
success = success && Array.isArray(v.parameters);
success = success && v.parameters.length === arbsName.length;
success = success && v.command.params.length === arbsName.length;
for (var idx = 0 ; idx !== arbsName.length ; ++idx) {
success = success && knownArbs[arbsName[idx]].check(v.parameters[idx]);
success = success && v.parameters[idx] == v.command.params[idx];
}
return success;
}));
});
});
});
|
const assert = require('assert');
const jsc = require('jsverify');
const {command} = require('../../src/arbitrary/command');
const GENSIZE = 10;
function MyEmptyClass(...params) {
this.params = params;
};
describe('command', function() {
describe('generator', function() {
it('should instantiate an object from the given class', function() {
const arb = command(MyEmptyClass);
var v = arb.generator(GENSIZE);
assert.ok(v.command instanceof MyEmptyClass, 'command instance of MyEmptyClass');
assert.ok(Array.isArray(v.parameters), 'parameters is an array');
assert.equal(v.parameters.length, 0, 'parameters array is empty');
});
it('should instantiate using asked parameter types', function() {
const arb = command(MyEmptyClass, jsc.nat, jsc.array(jsc.nat), jsc.constant(5));
var v = arb.generator(GENSIZE);
assert.ok(v.command instanceof MyEmptyClass, 'command instance of MyEmptyClass');
assert.ok(Array.isArray(v.parameters), 'parameters is an array');
assert.equal(v.parameters.length, 3, 'parameters array contains 3 elements');
assert.equal(typeof(v.parameters[0]), "number", 'first parameter is a number');
assert.ok(Array.isArray(v.parameters[1]), 'second parameter is an array');
assert.equal(typeof(v.parameters[2]), "number", 'third parameter is a number');
assert.deepEqual(v.command.params, v.parameters, "parameters are the one used during instantiation");
});
});
});
|
JavaScript
| 0
|
c175ebb784fe838e2f2b40ef2a2648b6a3e73a46
|
Fix the tests
|
test/write-files.test.js
|
test/write-files.test.js
|
/**
* Tests for the file writer
*/
const test = require('tape');
const utils = require('./fixture');
const prunk = require('prunk');
const Immutable = require('immutable');
const setup = (mkdirpMock, fsMock) => {
prunk.mock('mkdirp', mkdirpMock);
prunk.mock('fs-promise', fsMock);
return require('../lib/write-files');
};
// Teardown utility
const teardown = () => utils.resetTestDoubles('../lib/write-files');
// Default mocks
const defFs = {
writeFile() {
return Promise.resolve();
}
};
const defConfig = Immutable.Map();
const defMkdir = (_, cb) => cb(null);
test('write-files; exports a function', t => {
const writeFiles = setup();
t.plan(1);
t.equals(typeof writeFiles, 'function');
t.end();
teardown();
});
test('write-files; creates the output directories of files', t => {
const files = Immutable.fromJS([
{ outputDirectory: 'a' },
{ outputDirectory: 'b' },
{ outputDirectory: 'c' }
]);
const dirs = files.map( f => f.get('outputDirectory') );
const mock = (name, cb) => {
t.true( dirs.contains(name), name );
cb(null);
};
t.plan( files.count() );
const writeFiles = setup(mock, defFs);
writeFiles(defConfig, files)
.then( () => t.end() )
.catch( e => t.fail(e) );
teardown();
});
test('write-files; writes the files', t => {
const files = Immutable.fromJS([
{ outputPath: 'a', contents: 'a' },
{ outputPath: 'b', contents: 'b' },
{ outputPath: 'c', contents: 'c' }
]);
const paths = files.map( f => f.get('outputPath') );
const mock = {
writeFile(file, contents) {
t.equal(file, contents, file);
t.true( paths.contains(file) );
return Promise.resolve();
}
};
t.plan( files.count() * 2 );
const writeFiles = setup(defMkdir, mock);
writeFiles(defConfig, files)
.then( () => t.end() )
.catch( e => t.fail(e) );
teardown();
});
|
/**
* Tests for the file writer
*/
const test = require('tape');
const utils = require('./fixture');
const prunk = require('prunk');
const Immutable = require('immutable');
const setup = (mkdirpMock, fsMock) => {
prunk.mock('mkdirp', mkdirpMock);
prunk.mock('fs-promise', fsMock);
return require('../lib/write-files');
};
// Teardown utility
const teardown = () => utils.resetTestDoubles('../lib/write-files');
// Default mocks
const defFs = {
writeFile() {
return Promise.resolve();
}
};
const defConfig = Immutable.Map();
const defMkdir = (_, cb) => cb(null);
test('write-files; exports a function', t => {
const writeFiles = setup();
t.plan(1);
t.equals(typeof writeFiles, 'function');
t.end();
teardown();
});
test('write-files; creates the output directories of files', t => {
const files = Immutable.fromJS([
{ outputDirectory: 'a' },
{ outputDirectory: 'b' },
{ outputDirectory: 'c' }
]);
const dirs = files.map( f => f.get('outputDirectory') );
const mock = (name, cb) => {
t.true( dirs.contains(name) );
cb(null);
};
t.plan( files.count() );
const writeFiles = setup(mock, defFs);
writeFiles(defConfig, files)
.then( () => t.end() )
.catch( () => t.fail() );
});
test('write-files; writes the files', t => {
const files = Immutable.fromJS([
{ outputPath: 'a', contents: 'a' },
{ outputPath: 'b', contents: 'b' },
{ outputPath: 'c', contents: 'c' }
]);
const paths = files.map( f => f.get('outputDirectory') );
const mock = {
writeFile(file, contents) {
t.equal(file, contents);
t.true( paths.contains(file) );
return Promise.resovlve();
}
};
t.plan( files.count() );
const writeFiles = setup(defMkdir, mock);
writeFiles(defConfig, files)
.then( () => t.end() )
.catch( () => t.fail() );
});
|
JavaScript
| 0.999909
|
de7278a9045655a404c95c1bf64dcec5cc1ed7cf
|
Add test to catch non-numeric sorting
|
exercises/triangle/triangle.spec.js
|
exercises/triangle/triangle.spec.js
|
var Triangle = require('./triangle');
describe('Triangle', function() {
it('equilateral triangles have equal sides', function() {
var triangle = new Triangle(2,2,2);
expect(triangle.kind()).toEqual('equilateral');
});
xit('larger equilateral triangles also have equal sides', function() {
var triangle = new Triangle(10,10,10);
expect(triangle.kind()).toEqual('equilateral');
});
xit('isosceles triangles have last two sides equal', function() {
var triangle = new Triangle(3,4,4);
expect(triangle.kind()).toEqual('isosceles');
});
xit('isosceles trianges have first and last sides equal', function() {
var triangle = new Triangle(4,3,4);
expect(triangle.kind()).toEqual('isosceles');
});
xit('isosceles triangles have two first sides equal', function() {
var triangle = new Triangle(4,4,3);
expect(triangle.kind()).toEqual('isosceles');
});
xit('isosceles triangles have in fact exactly two sides equal', function() {
var triangle = new Triangle(10,10,2);
expect(triangle.kind()).toEqual('isosceles');
});
xit('scalene triangles have no equal sides', function() {
var triangle = new Triangle(3,4,5);
expect(triangle.kind()).toEqual('scalene');
});
xit('scalene triangles have no equal sides at a larger scale too', function() {
var triangle = new Triangle(10,11,12);
expect(triangle.kind()).toEqual('scalene');
});
xit('scalene triangles have no equal sides in descending order either', function() {
var triangle = new Triangle(5,4,2);
expect(triangle.kind()).toEqual('scalene');
});
xit('very small triangles are legal', function() {
var triangle = new Triangle(0.4,0.6,0.3);
expect(triangle.kind()).toEqual('scalene');
});
xit('test triangles with no size are illegal', function() {
var triangle = new Triangle(0,0,0);
expect(triangle.kind.bind(triangle)).toThrow();
});
xit('triangles with negative sides are illegal', function() {
var triangle = new Triangle(3,4,-5);
expect(triangle.kind.bind(triangle)).toThrow();
});
xit('triangles violating triangle inequality are illegal', function() {
var triangle = new Triangle(1,1,3);
expect(triangle.kind.bind(triangle)).toThrow();
});
xit('edge cases of triangle inequality are in fact legal', function() {
var triangle = new Triangle(2,4,2);
expect(triangle.kind.bind(triangle)).not.toThrow();
});
xit('triangles violating triangle inequality are illegal 2', function() {
var triangle = new Triangle(7,3,2);
expect(triangle.kind.bind(triangle)).toThrow();
});
xit('triangles violating triangle inequality are illegal 3', function() {
var triangle = new Triangle(10,1,3);
expect(triangle.kind.bind(triangle)).toThrow();
});
});
|
var Triangle = require('./triangle');
describe('Triangle', function() {
it('equilateral triangles have equal sides', function() {
var triangle = new Triangle(2,2,2);
expect(triangle.kind()).toEqual('equilateral');
});
xit('larger equilateral triangles also have equal sides', function() {
var triangle = new Triangle(10,10,10);
expect(triangle.kind()).toEqual('equilateral');
});
xit('isosceles triangles have last two sides equal', function() {
var triangle = new Triangle(3,4,4);
expect(triangle.kind()).toEqual('isosceles');
});
xit('isosceles trianges have first and last sides equal', function() {
var triangle = new Triangle(4,3,4);
expect(triangle.kind()).toEqual('isosceles');
});
xit('isosceles triangles have two first sides equal', function() {
var triangle = new Triangle(4,4,3);
expect(triangle.kind()).toEqual('isosceles');
});
xit('isosceles triangles have in fact exactly two sides equal', function() {
var triangle = new Triangle(10,10,2);
expect(triangle.kind()).toEqual('isosceles');
});
xit('scalene triangles have no equal sides', function() {
var triangle = new Triangle(3,4,5);
expect(triangle.kind()).toEqual('scalene');
});
xit('scalene triangles have no equal sides at a larger scale too', function() {
var triangle = new Triangle(10,11,12);
expect(triangle.kind()).toEqual('scalene');
});
xit('scalene triangles have no equal sides in descending order either', function() {
var triangle = new Triangle(5,4,2);
expect(triangle.kind()).toEqual('scalene');
});
xit('very small triangles are legal', function() {
var triangle = new Triangle(0.4,0.6,0.3);
expect(triangle.kind()).toEqual('scalene');
});
xit('test triangles with no size are illegal', function() {
var triangle = new Triangle(0,0,0);
expect(triangle.kind.bind(triangle)).toThrow();
});
xit('triangles with negative sides are illegal', function() {
var triangle = new Triangle(3,4,-5);
expect(triangle.kind.bind(triangle)).toThrow();
});
xit('triangles violating triangle inequality are illegal', function() {
var triangle = new Triangle(1,1,3);
expect(triangle.kind.bind(triangle)).toThrow();
});
xit('edge cases of triangle inequality are in fact legal', function() {
var triangle = new Triangle(2,4,2);
expect(triangle.kind.bind(triangle)).not.toThrow();
});
xit('triangles violating triangle inequality are illegal 2', function() {
var triangle = new Triangle(7,3,2);
expect(triangle.kind.bind(triangle)).toThrow();
});
});
|
JavaScript
| 0.000015
|
3061f890aa18e405236e0daebe59333e419a796d
|
Use switch in loadMore onInteract
|
src/components/MessageTypes/LoadMore.js
|
src/components/MessageTypes/LoadMore.js
|
'use strict'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import debounce from 'lodash.debounce'
function LoadMore ({ parentElement, onActivate, ...rest }) {
const [t] = useTranslation()
const [paddingTop, setPaddingTop] = useState(0)
const lastTouchY = useRef(-1)
const activate = useCallback(() => {
if (typeof onActivate === 'function') onActivate()
}, [onActivate])
const onInteract = useCallback(
event => {
switch (event.type) {
case 'click':
activate()
break
case 'wheel':
if (event.deltaY < 0) onScrollUp()
else onScrollDown()
break
case 'touchmove':
const clientY = event.changedTouches[0].clientY
if (lastTouchY.current > 0 && clientY - lastTouchY.current > 0) onScrollUp()
else onScrollDown()
lastTouchY.current = clientY
break
case 'keydown':
if (event.keyCode === 38) onScrollUp()
else if (event.keyCode === 40) onScrollDown()
break
default:
break
}
},
[activate]
)
useEffect(() => {
if (!parentElement) return
parentElement.addEventListener('wheel', onInteract)
parentElement.addEventListener('touchmove', onInteract)
document.addEventListener('keydown', onInteract)
return () => {
debouncedOnActivate.cancel()
parentElement.removeEventListener('wheel', onInteract)
parentElement.removeEventListener('touchmove', onInteract)
document.removeEventListener('keydown', onInteract)
}
}, [parentElement, onInteract])
const debouncedOnActivate = useCallback(debounce(activate, 200), [activate])
function onScrollUp () {
setPaddingTop(40)
debouncedOnActivate()
}
function onScrollDown () {
setPaddingTop(0)
debouncedOnActivate.cancel()
}
return (
<div
style={{ paddingTop: paddingTop > 0 ? paddingTop : '' }}
className="firstMessage loadMore"
{...rest}
onClick={onInteract}
>
{t('channel.loadMore')}
</div>
)
}
LoadMore.propTypes = {
parentElement: PropTypes.instanceOf(Element),
onActivate: PropTypes.func
}
export default LoadMore
|
'use strict'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import PropTypes from 'prop-types'
import { useTranslation } from 'react-i18next'
import debounce from 'lodash.debounce'
function LoadMore ({ parentElement, onActivate, ...rest }) {
const [t] = useTranslation()
const [paddingTop, setPaddingTop] = useState(0)
const lastTouchY = useRef(-1)
const activate = useCallback(() => {
if (typeof onActivate === 'function') onActivate()
}, [onActivate])
const onInteract = useCallback(
event => {
if (event.type === 'click') activate()
else if (event.type === 'wheel') {
if (event.deltaY < 0) onScrollUp()
else onScrollDown()
} else if (event.type === 'touchmove') {
const clientY = event.changedTouches[0].clientY
if (lastTouchY.current > 0 && clientY - lastTouchY.current > 0) onScrollUp()
else onScrollDown()
lastTouchY.current = clientY
} else if (event.type === 'keydown') {
if (event.keyCode === 38) onScrollUp()
else if (event.keyCode === 40) onScrollDown()
}
},
[activate]
)
useEffect(() => {
if (!parentElement) return
parentElement.addEventListener('wheel', onInteract)
parentElement.addEventListener('touchmove', onInteract)
document.addEventListener('keydown', onInteract)
return () => {
debouncedOnActivate.cancel()
parentElement.removeEventListener('wheel', onInteract)
parentElement.removeEventListener('touchmove', onInteract)
document.removeEventListener('keydown', onInteract)
}
}, [parentElement, onInteract])
const debouncedOnActivate = useCallback(debounce(activate, 200), [activate])
function onScrollUp () {
setPaddingTop(40)
debouncedOnActivate()
}
function onScrollDown () {
setPaddingTop(0)
debouncedOnActivate.cancel()
}
return (
<div
style={{ paddingTop: paddingTop > 0 ? paddingTop : '' }}
className="firstMessage loadMore"
{...rest}
onClick={onInteract}
>
{t('channel.loadMore')}
</div>
)
}
LoadMore.propTypes = {
parentElement: PropTypes.instanceOf(Element),
onActivate: PropTypes.func
}
export default LoadMore
|
JavaScript
| 0
|
1ac3b0e2ff05dcc781a90abf266b7ca400a3af88
|
Update index.js
|
src/with-features/index.js
|
src/with-features/index.js
|
import React, { Component } from "react";
import getEnabled from "../utils/get-enabled";
import updateFeaturesWithParams from "../utils/updateFeaturesWithParams";
import PropTypes from "prop-types";
const getEnabledFeatures = (initialFeatures, windowLocationSearch) =>
getEnabled(updateFeaturesWithParams(initialFeatures, windowLocationSearch));
// withFeatures = (config?: { initialFeatures: Object, windowLocationSearch: String }) => Component => Component
const withFeatures = (
{
initialFeatures = {},
windowLocationSearch = typeof window !== "undefined"
? window.location.search
: "",
features = getEnabledFeatures(initialFeatures, windowLocationSearch)
} = {}
) => WrappedComponent => {
class withFeaturesHOC extends Component {
static childContextTypes = {
features: PropTypes.array
};
getChildContext() {
return {
features
};
}
render() {
return (
<WrappedComponent
{...this.props}
features={features}
/>
);
}
}
return withFeaturesHOC;
};
export default withFeatures;
|
import React, { Component } from "react";
import getEnabled from "../utils/get-enabled";
import updateFeaturesWithParams from "../utils/updateFeaturesWithParams";
import PropTypes from "prop-types";
const getEnabledFeatures = (initialFeatures, windowLocationSearch) =>
getEnabled(updateFeaturesWithParams(initialFeatures, windowLocationSearch));
// withFeatures = (config?: { initialFeatures: Object, windowLocation: Object }) => Component => Component
const withFeatures = (
{
initialFeatures = {},
windowLocationSearch = typeof window !== "undefined"
? window.location.search
: "",
features = getEnabledFeatures(initialFeatures, windowLocationSearch)
} = {}
) => WrappedComponent => {
class withFeaturesHOC extends Component {
static childContextTypes = {
features: PropTypes.array
};
getChildContext() {
return {
features
};
}
render() {
return (
<WrappedComponent
{...this.props}
features={features}
/>
);
}
}
return withFeaturesHOC;
};
export default withFeatures;
|
JavaScript
| 0.000002
|
c5cdbb1d6244cd5e0a77416c1ef598336de4809a
|
change deprecated transaction to runInAction
|
test/observable-stream.js
|
test/observable-stream.js
|
'use strict';
const utils = require('../');
const mobx = require('mobx');
const test = require('tape');
const Rx = require("rxjs");
test("to observable", t => {
const user = mobx.observable({
firstName: "C.S",
lastName: "Lewis"
})
mobx.useStrict(false);
let values = []
const sub = Rx.Observable
.from(utils.toStream(() => user.firstName + user.lastName))
.map(x => x.toUpperCase())
.subscribe(v => values.push(v))
user.firstName = "John"
mobx.runInAction(() => {
user.firstName = "Jane";
user.lastName = "Jack";
})
sub.unsubscribe();
user.firstName = "error";
t.deepEqual(values, [
"JOHNLEWIS",
"JANEJACK"
]);
t.end();
})
test("from observable", t => {
mobx.useStrict(true)
const fromStream = utils.fromStream(Rx.Observable.interval(100), -1)
const values = [];
const d = mobx.autorun(() => {
values.push(fromStream.current);
})
setTimeout(() => {
t.equal(fromStream.current, -1)
}, 50)
setTimeout(() => {
t.equal(fromStream.current, 0)
}, 150)
setTimeout(() => {
t.equal(fromStream.current, 1)
fromStream.dispose()
}, 250)
setTimeout(() => {
t.equal(fromStream.current, 1)
t.deepEqual(values, [-1, 0, 1])
d()
mobx.useStrict(false)
t.end()
}, 350)
})
|
'use strict';
const utils = require('../');
const mobx = require('mobx');
const test = require('tape');
const Rx = require("rxjs");
test("to observable", t => {
const user = mobx.observable({
firstName: "C.S",
lastName: "Lewis"
})
mobx.useStrict(false);
let values = []
const sub = Rx.Observable
.from(utils.toStream(() => user.firstName + user.lastName))
.map(x => x.toUpperCase())
.subscribe(v => values.push(v))
user.firstName = "John"
mobx.transaction(() => {
user.firstName = "Jane";
user.lastName = "Jack";
})
sub.unsubscribe();
user.firstName = "error";
t.deepEqual(values, [
"JOHNLEWIS",
"JANEJACK"
]);
t.end();
})
test("from observable", t => {
mobx.useStrict(true)
const fromStream = utils.fromStream(Rx.Observable.interval(100), -1)
const values = [];
const d = mobx.autorun(() => {
values.push(fromStream.current);
})
setTimeout(() => {
t.equal(fromStream.current, -1)
}, 50)
setTimeout(() => {
t.equal(fromStream.current, 0)
}, 150)
setTimeout(() => {
t.equal(fromStream.current, 1)
fromStream.dispose()
}, 250)
setTimeout(() => {
t.equal(fromStream.current, 1)
t.deepEqual(values, [-1, 0, 1])
d()
mobx.useStrict(false)
t.end()
}, 350)
})
|
JavaScript
| 0.000001
|
9a56478947c81b6a8d4a12d59f1e6afb32b58008
|
Add a test for postNewNupicStatus
|
test/test-shaValidator.js
|
test/test-shaValidator.js
|
var assert = require('assert'),
shaValidator = require('./../utils/shaValidator.js')
repoClientStub = {
'getAllStatusesFor': function(sha, callback) { callback(null, 'fakeStatusHistory'); },
'validators': {
'excludes': []
}
},
repoClientSecondStub = {
'getAllStatusesFor': function(sha, callback) { callback(null, 'fakeStatusHistory'); },
'validators': {
'excludes': ['FirstValidator']
}
},
validatorsStub = [
{
'name': 'FirstValidator',
'priority': 1,
'validate': function(sha, githubUser, statusHistory, repoClient, callback) {
assert.equal(sha, 'testSHA', 'in FirstValidator.validate : wrong sha!');
assert.equal(githubUser, 'carlfriess', 'in FirstValidator.validate : wrong githubUser!');
assert.equal(statusHistory, 'fakeStatusHistory', 'in FirstValidator.validate : wrong statusHistory!');
callback(null, {
'state': 'success',
'target_url': 'correctTargetURL'
});
}
},
{
'name': 'SecondValidator',
'priority': 0,
'validate': function(sha, githubUser, statusHistory, repoClient, callback) {
assert.equal(sha, 'testSHA', 'in SecondValidator.validate : wrong sha!');
assert.equal(githubUser, 'carlfriess', 'in SecondValidator.validate : wrong githubUser!');
assert.equal(statusHistory, 'fakeStatusHistory', 'in SecondValidator.validate : wrong statusHistory!');
callback(null, {
'state': 'success',
'target_url': 'otherTargetURL'
});
}
}
];
describe('shaValidator test', function() {
it('Testing with two validators.', function(done) {
shaValidator.performCompleteValidation('testSHA', 'carlfriess', repoClientStub, validatorsStub, false, function(err, sha, output, repoClient) {
assert(!err, 'Should not be an error');
assert.equal(sha, 'testSHA', 'in shaValidator.performCompleteValidation : wrong sha in output!');
assert.equal(output.state, 'success', 'in shaValidator.performCompleteValidation : wrong state in output : Not success!');
//assert.equal(output.target_url, 'correctTargetURL', 'in shaValidator.performCompleteValidation : wrong target_url in output!');
assert.equal(output.description, 'All validations passed (FirstValidator, SecondValidator)', 'in shaValidator.performCompleteValidation : wrong description in output!');
done();
});
});
it('Testing with two validators. One configured to be excluded.', function(done) {
shaValidator.performCompleteValidation('testSHA', 'carlfriess', repoClientSecondStub, validatorsStub, false, function(err, sha, output, repoClient) {
assert(!err, 'Should not be an error');
assert.equal(sha, 'testSHA', 'in shaValidator.performCompleteValidation : wrong sha in output!');
assert.equal(output.state, 'success', 'in shaValidator.performCompleteValidation : wrong state in output : Not success!');
assert.equal(output.target_url, 'otherTargetURL', 'in shaValidator.performCompleteValidation : wrong target_url in output!');
assert.equal(output.description, 'All validations passed (SecondValidator [1 skipped])', 'in shaValidator.performCompleteValidation : wrong description in output!');
done();
});
});
it('Testing postNewNupicStatus', function(done) {
var mockSha = 'mockSha',
mockStatusDetails = {
'state': 'success',
'target_url': 'otherTargetURL',
'description': 'description'
},
statusPosted = null,
mockClient = {
github: {
statuses: {
create: function (statusObj) {
statusPosted = statusObj;
}
}
}
};
shaValidator.postNewNupicStatus(mockSha, mockStatusDetails, mockClient);
assert(statusPosted, 'status should be posted');
assert.equal(statusPosted.state, mockStatusDetails.state, 'posted wrong state!');
assert.equal(statusPosted.target_url, mockStatusDetails.target_url, 'posted wrong target_url!');
assert.equal(statusPosted.description, 'NuPIC Status: ' + mockStatusDetails.description, 'posted wrong state!');
done();
});
});
|
var assert = require('assert'),
shaValidator = require('./../utils/shaValidator.js')
repoClientStub = {
'getAllStatusesFor': function(sha, callback) { callback(null, 'fakeStatusHistory'); },
'validators': {
'excludes': []
}
},
repoClientSecondStub = {
'getAllStatusesFor': function(sha, callback) { callback(null, 'fakeStatusHistory'); },
'validators': {
'excludes': ['FirstValidator']
}
},
validatorsStub = [
{
'name': 'FirstValidator',
'priority': 1,
'validate': function(sha, githubUser, statusHistory, repoClient, callback) {
assert.equal(sha, 'testSHA', 'in FirstValidator.validate : wrong sha!');
assert.equal(githubUser, 'carlfriess', 'in FirstValidator.validate : wrong githubUser!');
assert.equal(statusHistory, 'fakeStatusHistory', 'in FirstValidator.validate : wrong statusHistory!');
callback(null, {
'state': 'success',
'target_url': 'correctTargetURL'
});
}
},
{
'name': 'SecondValidator',
'priority': 0,
'validate': function(sha, githubUser, statusHistory, repoClient, callback) {
assert.equal(sha, 'testSHA', 'in SecondValidator.validate : wrong sha!');
assert.equal(githubUser, 'carlfriess', 'in SecondValidator.validate : wrong githubUser!');
assert.equal(statusHistory, 'fakeStatusHistory', 'in SecondValidator.validate : wrong statusHistory!');
callback(null, {
'state': 'success',
'target_url': 'otherTargetURL'
});
}
}
];
describe('shaValidator test', function() {
it('Testing with two validators.', function(done) {
shaValidator.performCompleteValidation('testSHA', 'carlfriess', repoClientStub, validatorsStub, false, function(err, sha, output, repoClient) {
assert(!err, 'Should not be an error');
assert.equal(sha, 'testSHA', 'in shaValidator.performCompleteValidation : wrong sha in output!');
assert.equal(output.state, 'success', 'in shaValidator.performCompleteValidation : wrong state in output : Not success!');
//assert.equal(output.target_url, 'correctTargetURL', 'in shaValidator.performCompleteValidation : wrong target_url in output!');
assert.equal(output.description, 'All validations passed (FirstValidator, SecondValidator)', 'in shaValidator.performCompleteValidation : wrong description in output!');
done();
});
});
it('Testing with two validators. One configured to be excluded.', function(done) {
shaValidator.performCompleteValidation('testSHA', 'carlfriess', repoClientSecondStub, validatorsStub, false, function(err, sha, output, repoClient) {
assert(!err, 'Should not be an error');
assert.equal(sha, 'testSHA', 'in shaValidator.performCompleteValidation : wrong sha in output!');
assert.equal(output.state, 'success', 'in shaValidator.performCompleteValidation : wrong state in output : Not success!');
assert.equal(output.target_url, 'otherTargetURL', 'in shaValidator.performCompleteValidation : wrong target_url in output!');
assert.equal(output.description, 'All validations passed (SecondValidator [1 skipped])', 'in shaValidator.performCompleteValidation : wrong description in output!');
done();
});
});
});
|
JavaScript
| 0
|
bc0e04fad14c341e0a297e14da55318490f08c12
|
Test cargo tessel sdk install/uninstall
|
test/unit/cargo-tessel.js
|
test/unit/cargo-tessel.js
|
// Test dependencies are required and exposed in common/bootstrap.js
require('../common/bootstrap');
/*global CrashReporter */
exports['Cargo Subcommand (cargo tessel ...)'] = {
setUp(done) {
this.sandbox = sinon.sandbox.create();
this.info = this.sandbox.stub(log, 'info');
this.warn = this.sandbox.stub(log, 'warn');
this.error = this.sandbox.stub(log, 'error');
this.parse = this.sandbox.spy(cargo.nomnom, 'parse');
this.runBuild = this.sandbox.stub(rust, 'runBuild').returns(Promise.resolve());
done();
},
tearDown(done) {
this.sandbox.restore();
done();
},
build(test) {
test.expect(4);
var tarball = new Buffer([0x00]);
var bresolve = Promise.resolve(tarball);
// Prevent the tarball from being logged
this.sandbox.stub(console, 'log');
this.runBuild.returns(bresolve);
cargo(['build']);
bresolve.then(() => {
test.equal(console.log.callCount, 1);
test.equal(console.log.lastCall.args[0], tarball);
test.deepEqual(this.parse.lastCall.args, [['build']]);
test.deepEqual(this.runBuild.lastCall.args, [ { isCli: false, binary: undefined } ]);
test.done();
});
},
sdkInstall(test) {
test.expect(2);
var iresolve = Promise.resolve();
this.install = this.sandbox.stub(rust.cargo, 'install').returns(iresolve);
cargo.nomnom.globalOpts({subcommand: 'install'});
cargo(['sdk', 'install']);
iresolve.then(() => {
test.equal(this.install.callCount, 1);
test.deepEqual(this.install.lastCall.args[0], { '0': 'sdk', subcommand: 'install', _: [ 'sdk', 'install' ] });
test.done();
});
},
sdkUninstall(test) {
test.expect(2);
var iresolve = Promise.resolve();
this.uninstall = this.sandbox.stub(rust.cargo, 'uninstall').returns(iresolve);
cargo.nomnom.globalOpts({subcommand: 'uninstall'});
cargo(['sdk', 'uninstall']);
iresolve.then(() => {
test.equal(this.uninstall.callCount, 1);
test.deepEqual(this.uninstall.lastCall.args[0], { '0': 'sdk', subcommand: 'uninstall', _: [ 'sdk', 'uninstall' ] });
test.done();
});
},
};
|
// Test dependencies are required and exposed in common/bootstrap.js
require('../common/bootstrap');
/*global CrashReporter */
exports['Cargo Subcommand (cargo tessel ...)'] = {
setUp(done) {
this.sandbox = sinon.sandbox.create();
this.info = this.sandbox.stub(log, 'info');
this.error = this.sandbox.stub(log, 'error');
this.parse = this.sandbox.spy(cargo.nomnom, 'parse');
this.runBuild = this.sandbox.stub(rust, 'runBuild').returns(Promise.resolve());
done();
},
tearDown(done) {
this.sandbox.restore();
done();
},
build: function(test) {
// test.expect(3);
var tarball = new Buffer([0x00]);
var buildOp = Promise.resolve(tarball);
// Prevent the tarball from being logged
this.sandbox.stub(console, 'log');
this.runBuild.returns(buildOp);
cargo(['build']);
buildOp.then(() => {
test.equal(console.log.callCount, 1);
test.equal(console.log.lastCall.args[0], tarball);
test.deepEqual(this.parse.lastCall.args, [['build']]);
test.deepEqual(this.runBuild.lastCall.args, [ { isCli: false, binary: undefined } ]);
test.done();
});
}
};
|
JavaScript
| 0
|
000ec8b33bd96e3187e522630770624c2f923599
|
fix linter error
|
src/@ui/ConnectedImage/SkeletonImage.tests.js
|
src/@ui/ConnectedImage/SkeletonImage.tests.js
|
import React from 'react';
import renderer from 'react-test-renderer';
import SkeletonImage from './SkeletonImage';
describe('the SkeletonImage component', () => {
it('should render a loading state', () => {
const tree = renderer.create(
<SkeletonImage onReady={false} />,
);
expect(tree).toMatchSnapshot();
});
});
|
import React from 'react';
import { Text } from 'react-native';
import renderer from 'react-test-renderer';
import SkeletonImage from './SkeletonImage';
describe('the SkeletonImage component', () => {
it('should render a loading state', () => {
const tree = renderer.create(
<SkeletonImage onReady={false} />,
);
expect(tree).toMatchSnapshot();
});
});
|
JavaScript
| 0.000002
|
9babccc978ed4d7124631bd4289fb3e9da117dff
|
copy change
|
development/scripts/views/stats_coffee.js
|
development/scripts/views/stats_coffee.js
|
"use strict";
const StatsView = require("./stats");
const xhr = require("xhr");
module.exports = StatsView.extend({
template: `
<section class="category coffee">
<header>
<div class="art"></div>
<div class="copy">
<p></p>
</div>
</header>
<main class="stats">
<div class="stats-container">
<div class="stat">
<h3>Average Daily Coffees</h3>
<h2>0.94</h2>
</div>
<div class="stat">
<h3>Est. Total Volume (L)</h3>
<h2>122.62</h2>
</div>
<div class="stat">
<h3>Median Daily Coffees</h3>
<h2>1</h2>
</div>
<div class="stat">
<h3>Average Weekday Coffees</h3>
<h2>0.98</h2>
</div>
<div class="stat">
<h3>Average Weekend Coffees</h3>
<h2>0.87</h2>
</div>
<div class="stat">
<h3>Est. Days Without</h3>
<h2>73</h2>
</div>
<div class="stat">
<h3>Est. Days with More than Median</h3>
<h2>51</h2>
</div>
<div class="stat">
<h3>Most Daily Coffees</h3>
<h2>3</h2>
</div>
<div class="stat">
<h3>Longest streak (coffees)</h3>
<h2>15</h2>
</div>
<div class="stat">
<h3>Longest dry spell (days)</h3>
<h2>3</h2>
</div>
<div class="stat">
<h3>Total Days Recorded</h3>
<h2>286</h2>
</div>
</div>
</main>
</section>
`
});
|
"use strict";
const StatsView = require("./stats");
const xhr = require("xhr");
module.exports = StatsView.extend({
template: `
<section class="category coffee">
<header>
<div class="art"></div>
<div class="copy">
<p></p>
</div>
</header>
<main class="stats">
<div class="stats-container">
<div class="stat">
<h3>Average Daily Coffees</h3>
<h2>0.94</h2>
</div>
<div class="stat">
<h3>Est. Total Volume (L)</h3>
<h2>122.62</h2>
</div>
<div class="stat">
<h3>Median Daily Coffees</h3>
<h2>1</h2>
</div>
<div class="stat">
<h3>Average Weekday Coffees</h3>
<h2>0.98</h2>
</div>
<div class="stat">
<h3>Average Weekend Coffees</h3>
<h2>0.87</h2>
</div>
<div class="stat">
<h3>Est. Days Without</h3>
<h2>73</h2>
</div>
<div class="stat">
<h3>Est. Days with More than Usual</h3>
<h2>51</h2>
</div>
<div class="stat">
<h3>Most Daily Coffees</h3>
<h2>3</h2>
</div>
<div class="stat">
<h3>Longest streak (coffees)</h3>
<h2>15</h2>
</div>
<div class="stat">
<h3>Longest dry spell (days)</h3>
<h2>3</h2>
</div>
<div class="stat">
<h3>Total Days Recorded</h3>
<h2>286</h2>
</div>
</div>
</main>
</section>
`
});
|
JavaScript
| 0.000001
|
aae8a628d0f82561d9087e1b8fbd8024d7b4fbf4
|
remove dead code
|
client/scripts/task/controller/cam-tasklist-task-groups-ctrl.js
|
client/scripts/task/controller/cam-tasklist-task-groups-ctrl.js
|
define([
'angular'
], function(
angular
) {
'use strict';
var GROUP_TYPE = 'candidate';
return [
'$scope',
'$translate',
'$q',
'Notifications',
'camAPI',
function(
$scope,
$translate,
$q,
Notifications,
camAPI
) {
// setup //////////////////////////////////////////////
var Task = camAPI.resource('task');
var task = null;
var NEW_GROUP = { groupId : null, type: GROUP_TYPE };
var newGroup = $scope.newGroup = angular.copy(NEW_GROUP);
var taskGroupsData = $scope.taskGroupsData;
var groupsChanged = $scope.groupsChanged;
var errorHandler = $scope.errorHandler();
$scope._groups = [];
var messages = {};
$translate([
'FAILURE',
'INIT_GROUPS_FAILURE',
'ADD_GROUP_FAILED',
'REMOVE_GROUP_FAILED'
])
.then(function(result) {
messages.failure = result.FAILURE;
messages.initGroupsFailed = result.INIT_GROUPS_FAILURE;
messages.addGroupFailed = result.ADD_GROUP_FAILED;
messages.removeGroupFailed = result.REMOVE_GROUP_FAILED;
});
// observe ////////////////////////////////////////////////////////
$scope.modalGroupsState = taskGroupsData.observe('groups', function(groups) {
$scope._groups = angular.copy(groups) || [];
$scope.validateNewGroup();
});
taskGroupsData.observe('task', function (_task) {
task = _task;
});
// actions ///////////////////////////////////////////////////////
$scope.$watch('modalGroupsState.$error', function (error){
if (error) {
Notifications.addError({
status: messages.failure,
message: messages.initGroupsFailed,
exclusive: true,
scope: $scope
});
}
});
$scope.addGroup = function () {
var taskId = task.id;
groupsChanged();
delete newGroup.error;
Task.identityLinksAdd(taskId, newGroup, function(err) {
if (err) {
return errorHandler('TASK_UPDATE_ERROR', err);
}
$scope.taskGroupForm.$setPristine();
$scope._groups.push({id: newGroup.groupId});
newGroup = $scope.newGroup = angular.copy(NEW_GROUP);
});
};
$scope.removeGroup = function(group, index) {
var taskId = task.id;
groupsChanged();
Task.identityLinksDelete(taskId, {type: GROUP_TYPE, groupId: group.id}, function(err) {
if (err) {
return Notifications.addError({
status: messages.failure,
message: messages.removeGroupFailed,
exclusive: true,
scope: $scope
});
}
$scope._groups.splice(index, 1);
});
};
$scope.validateNewGroup = function () {
delete newGroup.error;
if ($scope.taskGroupForm && $scope.taskGroupForm.newGroup) {
$scope.taskGroupForm.newGroup.$setValidity('duplicate', true);
var newGroupId = newGroup.groupId;
if (newGroupId) {
for(var i = 0, currentGroup; !!(currentGroup = $scope._groups[i]); i++) {
if (newGroupId === currentGroup.id) {
newGroup.error = { message: 'DUPLICATE_GROUP' };
$scope.taskGroupForm.newGroup.$setValidity('duplicate', false);
}
}
}
}
};
$scope.isValid = function () {
if (!newGroup.groupId || newGroup.error) {
return false;
}
return true;
};
}];
});
|
define([
'angular'
], function(
angular
) {
'use strict';
var GROUP_TYPE = 'candidate';
return [
'$scope',
'$translate',
'$q',
'Notifications',
'camAPI',
function(
$scope,
$translate,
$q,
Notifications,
camAPI
) {
// setup //////////////////////////////////////////////
var Task = camAPI.resource('task');
var task = null;
var NEW_GROUP = { groupId : null, type: GROUP_TYPE };
var newGroup = $scope.newGroup = angular.copy(NEW_GROUP);
var taskGroupsData = $scope.taskGroupsData;
var groupsChanged = $scope.groupsChanged;
var errorHandler = $scope.errorHandler();
$scope._groups = [];
var messages = {};
$translate([
'FAILURE',
'INIT_GROUPS_FAILURE',
'ADD_GROUP_FAILED',
'REMOVE_GROUP_FAILED'
])
.then(function(result) {
messages.failure = result.FAILURE;
messages.initGroupsFailed = result.INIT_GROUPS_FAILURE;
messages.addGroupFailed = result.ADD_GROUP_FAILED;
messages.removeGroupFailed = result.REMOVE_GROUP_FAILED;
});
// observe ////////////////////////////////////////////////////////
$scope.modalGroupsState = taskGroupsData.observe('groups', function(groups) {
$scope._groups = angular.copy(groups) || [];
$scope.validateNewGroup();
});
taskGroupsData.observe('task', function (_task) {
task = _task;
});
// actions ///////////////////////////////////////////////////////
$scope.$watch('modalGroupsState.$error', function (error){
if (error) {
Notifications.addError({
status: messages.failure,
message: messages.initGroupsFailed,
exclusive: true,
scope: $scope
});
}
});
$scope.addGroup = function () {
var taskId = task.id;
groupsChanged();
delete newGroup.error;
Task.identityLinksAdd(taskId, newGroup, function(err) {
if (err) {
// return Notifications.addError({
// status: messages.failure,
// message: messages.addGroupFailed,
// exclusive: true,
// scope: $scope
// });
return errorHandler('TASK_UPDATE_ERROR', err);
}
$scope.taskGroupForm.$setPristine();
$scope._groups.push({id: newGroup.groupId});
newGroup = $scope.newGroup = angular.copy(NEW_GROUP);
});
};
$scope.removeGroup = function(group, index) {
var taskId = task.id;
groupsChanged();
Task.identityLinksDelete(taskId, {type: GROUP_TYPE, groupId: group.id}, function(err) {
if (err) {
return Notifications.addError({
status: messages.failure,
message: messages.removeGroupFailed,
exclusive: true,
scope: $scope
});
}
$scope._groups.splice(index, 1);
});
};
$scope.validateNewGroup = function () {
delete newGroup.error;
if ($scope.taskGroupForm && $scope.taskGroupForm.newGroup) {
$scope.taskGroupForm.newGroup.$setValidity('duplicate', true);
var newGroupId = newGroup.groupId;
if (newGroupId) {
for(var i = 0, currentGroup; !!(currentGroup = $scope._groups[i]); i++) {
if (newGroupId === currentGroup.id) {
newGroup.error = { message: 'DUPLICATE_GROUP' };
$scope.taskGroupForm.newGroup.$setValidity('duplicate', false);
}
}
}
}
};
$scope.isValid = function () {
if (!newGroup.groupId || newGroup.error) {
return false;
}
return true;
};
}];
});
|
JavaScript
| 0.998565
|
1544405be029163cfa0dd5719d16833b72ae82d1
|
Add preset to jest babel config
|
.babelrc.js
|
.babelrc.js
|
const withTests = {
presets: [
[
'@babel/preset-env',
{ shippedProposals: true, useBuiltIns: 'usage', corejs: '3', targets: { node: 'current' } },
],
],
plugins: [
'babel-plugin-require-context-hook',
'babel-plugin-dynamic-import-node',
'@babel/plugin-transform-runtime',
],
};
module.exports = {
ignore: [
'./lib/codemod/src/transforms/__testfixtures__',
'./lib/postinstall/src/__testfixtures__',
],
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],
'@babel/preset-typescript',
'@babel/preset-react',
'@babel/preset-flow',
],
plugins: [
[
'@babel/plugin-proposal-decorators',
{
legacy: true,
},
],
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-export-default-from',
'@babel/plugin-syntax-dynamic-import',
['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],
'babel-plugin-macros',
['emotion', { sourceMap: true, autoLabel: true }],
],
env: {
test: withTests,
},
overrides: [
{
test: './examples/vue-kitchen-sink',
presets: ['@vue/babel-preset-jsx'],
env: {
test: withTests,
},
},
{
test: './lib',
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],
'@babel/preset-react',
],
plugins: [
['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],
'@babel/plugin-proposal-export-default-from',
'@babel/plugin-syntax-dynamic-import',
['@babel/plugin-proposal-class-properties', { loose: true }],
'babel-plugin-macros',
['emotion', { sourceMap: true, autoLabel: true }],
'@babel/plugin-transform-react-constant-elements',
'babel-plugin-add-react-displayname',
],
env: {
test: withTests,
},
},
{
test: [
'./lib/node-logger',
'./lib/codemod',
'./addons/storyshots',
'**/src/server/**',
'**/src/bin/**',
],
presets: [
[
'@babel/preset-env',
{
shippedProposals: true,
useBuiltIns: 'usage',
targets: {
node: '8.11',
},
corejs: '3',
},
],
],
plugins: [
'emotion',
'babel-plugin-macros',
'@babel/plugin-transform-arrow-functions',
'@babel/plugin-transform-shorthand-properties',
'@babel/plugin-transform-block-scoping',
'@babel/plugin-transform-destructuring',
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-export-default-from',
],
env: {
test: withTests,
},
},
],
};
|
const withTests = {
presets: [
[
'@babel/preset-env',
{ shippedProposals: true, useBuiltIns: 'usage', corejs: '3', targets: { node: 'current' } },
],
],
plugins: [
'babel-plugin-require-context-hook',
'babel-plugin-dynamic-import-node',
'@babel/plugin-transform-runtime',
],
};
module.exports = {
ignore: [
'./lib/codemod/src/transforms/__testfixtures__',
'./lib/postinstall/src/__testfixtures__',
],
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],
'@babel/preset-typescript',
'@babel/preset-react',
'@babel/preset-flow',
],
plugins: [
[
'@babel/plugin-proposal-decorators',
{
legacy: true,
},
],
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-export-default-from',
'@babel/plugin-syntax-dynamic-import',
['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],
'babel-plugin-macros',
['emotion', { sourceMap: true, autoLabel: true }],
],
env: {
test: withTests,
},
overrides: [
{
test: './examples/vue-kitchen-sink',
env: {
test: withTests,
},
},
{
test: './lib',
presets: [
['@babel/preset-env', { shippedProposals: true, useBuiltIns: 'usage', corejs: '3' }],
'@babel/preset-react',
],
plugins: [
['@babel/plugin-proposal-object-rest-spread', { loose: true, useBuiltIns: true }],
'@babel/plugin-proposal-export-default-from',
'@babel/plugin-syntax-dynamic-import',
['@babel/plugin-proposal-class-properties', { loose: true }],
'babel-plugin-macros',
['emotion', { sourceMap: true, autoLabel: true }],
'@babel/plugin-transform-react-constant-elements',
'babel-plugin-add-react-displayname',
],
env: {
test: withTests,
},
},
{
test: [
'./lib/node-logger',
'./lib/codemod',
'./addons/storyshots',
'**/src/server/**',
'**/src/bin/**',
],
presets: [
[
'@babel/preset-env',
{
shippedProposals: true,
useBuiltIns: 'usage',
targets: {
node: '8.11',
},
corejs: '3',
},
],
],
plugins: [
'emotion',
'babel-plugin-macros',
'@babel/plugin-transform-arrow-functions',
'@babel/plugin-transform-shorthand-properties',
'@babel/plugin-transform-block-scoping',
'@babel/plugin-transform-destructuring',
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-proposal-object-rest-spread',
'@babel/plugin-proposal-export-default-from',
],
env: {
test: withTests,
},
},
],
};
|
JavaScript
| 0
|
1eca38d5b3f226163d33f2c2d8bde7eac79d9193
|
Add a "Do Not Track" policy to tracking entrypoint
|
utils/track.js
|
utils/track.js
|
import fetch from 'isomorphic-fetch'
import Router from 'next/router'
if (
(navigator.doNotTrack && navigator.doNotTrack !== 'no') ||
window.doNotTrack ||
navigator.msDoNotTrack
) {
console.log('Tracking is disabled due to the Do Not Track policy of this browser.')
} else {
console.log('Tracking is enabled. If you do not want your page view to be tracked enable the "Do Not Track" policy in your browser settings.')
const reportView = () => {
const { pathname } = window.location
fetch('https://sc-micro-analytics.now.sh' + pathname)
.then(() => {
console.log(`Reported page view for ${pathname}.`)
})
.catch(err => {
console.warn('Could not report page view:', err)
})
}
reportView()
Router.onRouteChangeComplete = () => {
reportView()
}
}
|
import fetch from 'isomorphic-fetch'
import Router from 'next/router'
const reportView = () => {
const { pathname } = window.location
fetch('https://sc-micro-analytics.now.sh' + pathname)
.then(() => {
console.log(`Reported page view for ${pathname}.`)
})
.catch(err => {
console.warn('Could not report page view:', err)
})
}
reportView()
Router.onRouteChangeComplete = () => {
reportView()
}
|
JavaScript
| 0.000002
|
81178452cc15448c2857b1d7df4eb3b7f55f3bd7
|
Test phase
|
node-hsync/main.js
|
node-hsync/main.js
|
var program = require('commander');
var Process = require('process');
var util = require('util');
var Hubic = require('./hubic.js');
var HFile = require('./hfile.js');
var LFile = require('./lfile.js');
var Syncer = require('./syncer.js');
var Authentification = require('./authentification.js');
program.option("-u, --username <login>", "Hubic username");
program.option("-p, --passwd <passwd>", "Hubic password");
program.option("-s, --source <path>", "Source directory");
program.option("-d, --destination <path>", "Destination directory");
program.option("--hubic-log", "Enable hubic log");
program.option("--hubic-login-log", "Enable hubic login log");
program.option("--swift-log", "Enable swift log");
program.option("--swift-request-log", "Enable swift request log");
program.option("--sync-log", "Enable sync processus log");
program.option("-n, --dry-run", "Perform a trial run with no changes made");
program.option("--max-request <number>",
"Max simultaneous swift requests (does not include upload requests)",
parseInt);
program.option("--max-upload <number>", "Max simultaneous updload requests",
parseInt);
program.option("--uploading-prefix <prefix>", "Upload filename prefix");
program.option("--backup-directory-name <name>", "Backup directory name");
program.option("--container-name <name>", "Swift container name");
program.option("--purge-uploading-files", "Delete not used uploading files");
program.option("--progress", "Show progress");
program.option("--versioning",
"Move modified or deleted file to a backup folder");
program.option("--certPath",
"Specify the path of the SSL certificate (for authentication process)");
program.option("--keyPath",
"Specify the path of the SSL key (for authentication process)");
program.option("--tokenPath", "Specify the path of the last authorized token");
program.option("--clientID", "Specify the Hubic application Client ID");
program.option("--clientSecret", "Specify the Hubic application Client Secret");
program.parse(Process.argv);
if (!program.username) {
console.log("Username is not specified");
Process.exit(1);
}
function goHubic() {
if (!program.token) {
console.log("Token is not specified");
Process.exit(1);
}
if (!program.source) {
console.log("Source is not specified");
Process.exit(1);
}
if (!program.destination) {
console.log("Destination is not specified");
Process.exit(1);
}
var hubic = new Hubic(program.username, program.passwd, program, function(
error, hubic) {
if (error) {
console.error("Error: " + error);
return;
}
var syncer = new Syncer(hubic, program);
var hroot = HFile.createRoot(hubic);
var lroot = LFile.createRoot(program.source);
hroot.find(program.destination, function(error, hfile) {
if (error) {
console.error("ERROR: " + error);
return;
}
syncer.sync(lroot, hfile, function(error) {
if (error) {
console.error("ERROR: " + error);
return;
}
});
});
});
}
if (!program.token) {
var auth = new Authentification();
if (program.certPath) {
auth.certPath = program.certPath;
}
if (program.keyPath) {
auth.keyPath = program.keyPath;
}
if (program.clientID) {
auth.clientID = program.clientID;
}
if (program.clientSecret) {
auth.clientSecret = program.clientSecret;
}
auth.username = program.username;
auth.process(function(error, password) {
if (error) {
console.error("Can not authenticate: " + error);
Process.exit(1);
}
program.passwd = password;
goHubic();
});
} else {
goHubic();
}
|
var program = require('commander');
var Process = require('process');
var util = require('util');
var Hubic = require('./hubic.js');
var HFile = require('./hfile.js');
var LFile = require('./lfile.js');
var Syncer = require('./syncer.js');
program.option("-u, --username <login>", "Hubic username");
program.option("-p, --passwd <passwd>", "Hubic password");
program.option("-s, --source <path>", "Source directory");
program.option("-d, --destination <path>", "Destination directory");
program.option("--hubic-log", "Enable hubic log");
program.option("--hubic-login-log", "Enable hubic login log");
program.option("--swift-log", "Enable swift log");
program.option("--swift-request-log", "Enable swift request log");
program.option("--sync-log", "Enable sync processus log");
program.option("-n, --dry-run", "Perform a trial run with no changes made");
program.option("--max-request <number>",
"Max simultaneous swift requests (does not include upload requests)",
parseInt);
program.option("--max-upload <number>", "Max simultaneous updload requests",
parseInt);
program.option("--uploading-prefix <prefix>", "Upload filename prefix");
program.option("--backup-directory-name <name>", "Backup directory name");
program.option("--container-name <name>", "Swift container name");
program.option("--purge-uploading-files", "Delete not used uploading files");
program.option("--progress", "Show progress");
program.option("--versioning",
"Move modified or deleted file to a backup folder");
program.option("--certPath",
"Specify the path of the SSL certificate (for authentication process)");
program.option("--keyPath",
"Specify the path of the SSL key (for authentication process)");
program.option("--tokenPath", "Specify the path of the last authorized token");
program.option("--clientID", "Specify the Hubic application Client ID");
program.option("--clientSecret", "Specify the Hubic application Client Secret");
program.parse(Process.argv);
if (!program.username) {
console.log("Username is not specified");
Process.exit(1);
}
function goHubic() {
if (!program.token) {
console.log("Token is not specified");
Process.exit(1);
}
if (!program.source) {
console.log("Source is not specified");
Process.exit(1);
}
if (!program.destination) {
console.log("Destination is not specified");
Process.exit(1);
}
var hubic = new Hubic(program.username, program.passwd, program, function(
error, hubic) {
if (error) {
console.error("Error: " + error);
return;
}
var syncer = new Syncer(hubic, program);
var hroot = HFile.createRoot(hubic);
var lroot = LFile.createRoot(program.source);
hroot.find(program.destination, function(error, hfile) {
if (error) {
console.error("ERROR: " + error);
return;
}
syncer.sync(lroot, hfile, function(error) {
if (error) {
console.error("ERROR: " + error);
return;
}
});
});
});
}
if (!program.token) {
var auth = new Authentification();
if (program.certPath) {
auth.certPath = program.certPath;
}
if (program.keyPath) {
auth.keyPath = program.keyPath;
}
if (program.clientID) {
auth.clientID = program.clientID;
}
if (program.clientSecret) {
auth.clientSecret = program.clientSecret;
}
auth.username = program.username;
auth.process(function(error, password) {
if (error) {
console.error("Can not authenticate: " + error);
Process.exit(1);
}
program.passwd = password;
goHubic();
});
} else {
goHubic();
}
|
JavaScript
| 0.000001
|
b8ec958f89616a5e6071c0d6586f0a4126582370
|
Add addPolyfills function
|
utils/utils.js
|
utils/utils.js
|
/*
* utils.js: utility functions
*/
export { getScrollOffsets, drag, addPolyfills };
/*
* getScrollOffsets: Use x and y scroll offsets to calculate positioning
* coordinates that take into account whether the page has been scrolled.
* From Mozilla Developer Network: Element.getBoundingClientRect()
*/
function getScrollOffsets () {
let t;
let xOffset = (typeof window.pageXOffset === "undefined") ?
(((t = document.documentElement) || (t = document.body.parentNode)) &&
typeof t.ScrollLeft === 'number' ? t : document.body).ScrollLeft :
window.pageXOffset;
let yOffset = (typeof window.pageYOffset === "undefined") ?
(((t = document.documentElement) || (t = document.body.parentNode)) &&
typeof t.ScrollTop === 'number' ? t : document.body).ScrollTop :
window.pageYOffset;
return { x: xOffset, y: yOffset };
}
/*
* drag: Add drag and drop functionality to an element by setting this
* as its mousedown handler. Depends upon getScrollOffsets function.
* From JavaScript: The Definitive Guide, 6th Edition (slightly modified)
*/
function drag (elementToDrag, dragCallback, event) {
let scroll = getScrollOffsets();
let startX = event.clientX + scroll.x;
let startY = event.clientY + scroll.y;
let origX = elementToDrag.offsetLeft;
let origY = elementToDrag.offsetTop;
let deltaX = startX - origX;
let deltaY = startY - origY;
if (dragCallback) dragCallback(elementToDrag);
if (document.addEventListener) {
document.addEventListener("mousemove", moveHandler, true);
document.addEventListener("mouseup", upHandler, true);
}
else if (document.attachEvent) {
elementToDrag.setCapture();
elementToDrag.attachEvent("onmousemove", moveHandler);
elementToDrag.attachEvent("onmouseup", upHandler);
elementToDrag.attachEvent("onlosecapture", upHandler);
}
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
if (event.preventDefault) event.preventDefault();
else event.returnValue = false;
function moveHandler (e) {
if (!e) e = window.event;
let scroll = getScrollOffsets();
elementToDrag.style.left = (e.clientX + scroll.x - deltaX) + "px";
elementToDrag.style.top = (e.clientY + scroll.y - deltaY) + "px";
elementToDrag.style.cursor = "move";
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true;
}
function upHandler (e) {
if (!e) e = window.event;
elementToDrag.style.cursor = "grab";
elementToDrag.style.cursor = "-moz-grab";
elementToDrag.style.cursor = "-webkit-grab";
if (document.removeEventListener) {
document.removeEventListener("mouseup", upHandler, true);
document.removeEventListener("mousemove", moveHandler, true);
}
else if (document.detachEvent) {
elementToDrag.detachEvent("onlosecapture", upHandler);
elementToDrag.detachEvent("onmouseup", upHandler);
elementToDrag.detachEvent("onmousemove", moveHandler);
elementToDrag.releaseCapture();
}
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true;
}
}
/*
* addPolyfills: Add polyfill implementations for JavaScript object methods
* defined in ES6 and used by bookmarklets:
* 1. Array.prototype.find
* 2. String.prototype.includes
*/
function addPolyfills () {
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if (!Array.prototype.find) {
Array.prototype.find = function (predicate) {
if (this === null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
if (!String.prototype.includes) {
String.prototype.includes = function (search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
}
else {
return this.indexOf(search, start) !== -1;
}
};
}
}
|
/*
* utils.js: utility functions
*/
export { getScrollOffsets, drag };
/*
* getScrollOffsets: Use x and y scroll offsets to calculate positioning
* coordinates that take into account whether the page has been scrolled.
* From Mozilla Developer Network: Element.getBoundingClientRect()
*/
function getScrollOffsets () {
let t;
let xOffset = (typeof window.pageXOffset === "undefined") ?
(((t = document.documentElement) || (t = document.body.parentNode)) &&
typeof t.ScrollLeft === 'number' ? t : document.body).ScrollLeft :
window.pageXOffset;
let yOffset = (typeof window.pageYOffset === "undefined") ?
(((t = document.documentElement) || (t = document.body.parentNode)) &&
typeof t.ScrollTop === 'number' ? t : document.body).ScrollTop :
window.pageYOffset;
return { x: xOffset, y: yOffset };
}
/*
* drag: Add drag and drop functionality to an element by setting this
* as its mousedown handler. Depends upon getScrollOffsets function.
* From JavaScript: The Definitive Guide, 6th Edition (slightly modified)
*/
function drag (elementToDrag, dragCallback, event) {
let scroll = getScrollOffsets();
let startX = event.clientX + scroll.x;
let startY = event.clientY + scroll.y;
let origX = elementToDrag.offsetLeft;
let origY = elementToDrag.offsetTop;
let deltaX = startX - origX;
let deltaY = startY - origY;
if (dragCallback) dragCallback(elementToDrag);
if (document.addEventListener) {
document.addEventListener("mousemove", moveHandler, true);
document.addEventListener("mouseup", upHandler, true);
}
else if (document.attachEvent) {
elementToDrag.setCapture();
elementToDrag.attachEvent("onmousemove", moveHandler);
elementToDrag.attachEvent("onmouseup", upHandler);
elementToDrag.attachEvent("onlosecapture", upHandler);
}
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
if (event.preventDefault) event.preventDefault();
else event.returnValue = false;
function moveHandler (e) {
if (!e) e = window.event;
let scroll = getScrollOffsets();
elementToDrag.style.left = (e.clientX + scroll.x - deltaX) + "px";
elementToDrag.style.top = (e.clientY + scroll.y - deltaY) + "px";
elementToDrag.style.cursor = "move";
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true;
}
function upHandler (e) {
if (!e) e = window.event;
elementToDrag.style.cursor = "grab";
elementToDrag.style.cursor = "-moz-grab";
elementToDrag.style.cursor = "-webkit-grab";
if (document.removeEventListener) {
document.removeEventListener("mouseup", upHandler, true);
document.removeEventListener("mousemove", moveHandler, true);
}
else if (document.detachEvent) {
elementToDrag.detachEvent("onlosecapture", upHandler);
elementToDrag.detachEvent("onmouseup", upHandler);
elementToDrag.detachEvent("onmousemove", moveHandler);
elementToDrag.releaseCapture();
}
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true;
}
}
|
JavaScript
| 0.000001
|
8b7e30ae70a8e0b103b032cea69b6214b553710f
|
Fix test
|
tests/e2e/reports_spec.js
|
tests/e2e/reports_spec.js
|
/*global browser:false, element:false, by:false */
'use strict';
//https://github.com/angular/protractor/blob/master/docs/api.md
//GetAttribute() returns "boolean" values and will return either "true" or null
browser.get('/');
describe('Reports List', function() {
it('should have a Report Editor title', function(){
expect(browser.getTitle()).toBe('Report Editor');
});
it('Should show have at least one report', function() {
element.all(by.repeater('report in reports')).then(function(reportList){
expect(reportList.length).toBeGreaterThan(0);
});
});
});
describe('Report Selection', function() {
var deleteBtn = element(by.id('delete-reports'));
var toggle = element(by.model('toggle'));
var checkboxes = element.all(by.model('selectedReports[report._id]'));
it('should have all reports unchecked', function(){
expect(toggle.getAttribute('checked')).toBe(null);
expect(deleteBtn.isDisplayed()).toBe(false);
});
it('should select all reports when clicking on the toggle', function(){
toggle.click();
expect(toggle.getAttribute('checked')).toBe('true');
expect(deleteBtn.isDisplayed()).toBe(true);
checkboxes.each(function(element){
expect(element.getAttribute('checked')).toBe('true');
});
});
it('the toggle should be undeterminate if we unselect a report', function(){
var report = checkboxes.first();
report.click();
expect(report.getAttribute('checked')).toBe(null);
checkboxes.count().then(function(count){
if(count === 1) {
expect(toggle.getAttribute('indeterminate')).toBe(null);
} else {
expect(toggle.getAttribute('indeterminate')).toBe('true');
}
});
});
it('the toggle shouldn\'t be undeterminate if all reports are selected or unselected', function(){
var report = checkboxes.first();
report.click();
expect(report.getAttribute('checked')).toBe('true');
checkboxes.each(function(element) {
element.click();
expect(element.getAttribute('checked')).toBe(null);
});
expect(toggle.getAttribute('indeterminate')).toBe(null);
expect(deleteBtn.isDisplayed()).toBe(false);
checkboxes.each(function(element) {
element.click();
expect(element.getAttribute('checked')).toBe('true');
});
expect(deleteBtn.isDisplayed()).toBe(true);
expect(toggle.getAttribute('indeterminate')).toBe(null);
});
});
/*
describe('Creates and Deletes a Report', function(){
var createBtn = element(by.id('create-report'));
var originalReportCount;
var deleteBtn = element(by.id('delete-reports'));
it('should create a new report', function(){
element.all(by.repeater('report in reports')).then(function(reportList){
originalReportCount = reportList.length;
});
createBtn.click();
var input = element(by.model('report.name'));
input.sendKeys('myuniquereport');
element(by.css('form[name="newReportForm"]')).submit();
element(by.id('reports')).click();
element.all(by.repeater('report in reports')).then(function(reportList){
expect(reportList.length).toBe(originalReportCount + 1);
});
});
it('should delete a report', function() {
var checkbox = element.all(by.model('selectedReports[report._id]')).last();
checkbox.click();
deleteBtn.click();
element(by.id('confirm-delete-reports')).click();
element.all(by.repeater('report in reports')).then(function(reportList){
expect(reportList.length).toBe(originalReportCount);
});
});
});
*/
|
/*global browser:false, element:false, by:false */
'use strict';
//https://github.com/angular/protractor/blob/master/docs/api.md
//GetAttribute() returns "boolean" values and will return either "true" or null
browser.get('/');
describe('Reports List', function() {
it('should have a Report Editor title', function(){
expect(browser.getTitle()).toBe('Report Editor');
});
it('Should show have at least one report', function() {
element.all(by.repeater('report in reports')).then(function(reportList){
expect(reportList.length).toBeGreaterThan(0);
});
});
});
describe('Report Selection', function() {
var deleteBtn = element(by.id('delete-reports'));
var toggle = element(by.model('toggle'));
var checkboxes = element.all(by.model('selectedReports[report._id]'));
it('should have all reports unchecked', function(){
expect(toggle.getAttribute('checked')).toBe(null);
expect(deleteBtn.isDisplayed()).toBe(false);
});
it('should select all reports when clicking on the toggle', function(){
toggle.click();
expect(toggle.getAttribute('checked')).toBe('true');
expect(deleteBtn.isDisplayed()).toBe(true);
checkboxes.each(function(element){
expect(element.getAttribute('checked')).toBe('true');
});
});
it('the toggle should be undeterminate if we unselect a report', function(){
var report = checkboxes.first();
report.click();
expect(report.getAttribute('checked')).toBe(null);
expect(toggle.getAttribute('indeterminate')).toBe('true');
});
it('the toggle shouldn\'t be undeterminate if all reports are selected or unselected', function(){
var report = checkboxes.first();
report.click();
expect(report.getAttribute('checked')).toBe('true');
checkboxes.each(function(element) {
element.click();
expect(element.getAttribute('checked')).toBe(null);
});
expect(toggle.getAttribute('indeterminate')).toBe(null);
expect(deleteBtn.isDisplayed()).toBe(false);
checkboxes.each(function(element) {
element.click();
expect(element.getAttribute('checked')).toBe('true');
});
expect(deleteBtn.isDisplayed()).toBe(true);
expect(toggle.getAttribute('indeterminate')).toBe(null);
});
});
/*
describe('Creates and Deletes a Report', function(){
var createBtn = element(by.id('create-report'));
var originalReportCount;
var deleteBtn = element(by.id('delete-reports'));
it('should create a new report', function(){
element.all(by.repeater('report in reports')).then(function(reportList){
originalReportCount = reportList.length;
});
createBtn.click();
var input = element(by.model('report.name'));
input.sendKeys('myuniquereport');
element(by.css('form[name="newReportForm"]')).submit();
element(by.id('reports')).click();
element.all(by.repeater('report in reports')).then(function(reportList){
expect(reportList.length).toBe(originalReportCount + 1);
});
});
it('should delete a report', function() {
var checkbox = element.all(by.model('selectedReports[report._id]')).last();
checkbox.click();
deleteBtn.click();
element(by.id('confirm-delete-reports')).click();
element.all(by.repeater('report in reports')).then(function(reportList){
expect(reportList.length).toBe(originalReportCount);
});
});
});
*/
|
JavaScript
| 0.000004
|
ba0d3d373e89fb8a589d785abb058a127f78cc1f
|
Update config.js
|
samples/config.js
|
samples/config.js
|
var QBApp = {
appId: 92,
authKey: 'wJHdOcQSxXQGWx5',
authSecret: 'BTFsj7Rtt27DAmT'
};
var QBUsers = [
{
id: 2077886,
login: '@user1',
password: 'x6Bt0VDy5',
full_name: 'User 1'
},
{
id: 2077894,
login: '@user2',
password: 'x6Bt0VDy5',
full_name: 'User 2'
},
{
id: 2077896,
login: '@user3',
password: 'x6Bt0VDy5',
full_name: 'User 3'
},
{
id: 2077897,
login: '@user4',
password: 'x6Bt0VDy5',
full_name: 'User 4'
},
{
id: 2077900,
login: '@user5',
password: 'x6Bt0VDy5',
full_name: 'User 5'
},
{
id: 2077901,
login: '@user6',
password: 'x6Bt0VDy5',
full_name: 'User 6'
},
{
id: 2077902,
login: '@user7',
password: 'x6Bt0VDy5',
full_name: 'User 7'
},
{
id: 2077904,
login: '@user8',
password: 'x6Bt0VDy5',
full_name: 'User 8'
},
{
id: 2077906,
login: '@user9',
password: 'x6Bt0VDy5',
full_name: 'User 9'
},
{
id: 2077907,
login: '@user10',
password: 'x6Bt0VDy5',
full_name: 'User 10'
},
{
id: 2327456,
login: 'androidUser1',
password: 'x6Bt0VDy5',
full_name: 'Web user 1'
},
{
id: 2344849,
login: 'androidUser2',
password: 'x6Bt0VDy5',
full_name: 'Web user 2'
}
];
|
var QBApp = {
appId: 92,
authKey: 'wJHdOcQSxXQGWx5',
authSecret: 'BTFsj7Rtt27DAmT'
};
var QBUsers = [
{
id: 2077886,
login: '@user1',
password: 'x6Bt0VDy5',
full_name: 'User 1'
},
{
id: 2077894,
login: '@user2',
password: 'x6Bt0VDy5',
full_name: 'User 2'
},
{
id: 2077896,
login: '@user3',
password: 'x6Bt0VDy5',
full_name: 'User 3'
},
{
id: 2077897,
login: '@user4',
password: 'x6Bt0VDy5',
full_name: 'User 4'
},
{
id: 2077900,
login: '@user5',
password: 'x6Bt0VDy5',
full_name: 'User 5'
},
{
id: 2077901,
login: '@user6',
password: 'x6Bt0VDy5',
full_name: 'User 6'
},
{
id: 2077902,
login: '@user7',
password: 'x6Bt0VDy5',
full_name: 'User 7'
},
{
id: 2077904,
login: '@user8',
password: 'x6Bt0VDy5',
full_name: 'User 8'
},
{
id: 2077906,
login: '@user9',
password: 'x6Bt0VDy5',
full_name: 'User 9'
},
{
id: 2077907,
login: '@user10',
password: 'x6Bt0VDy5',
full_name: 'User 10'
},
{
id: 2327456,
login: 'androidUser1',
password: 'x6Bt0VDy5',
full_name: 'Web user 1'
},
{
id: 2077906,
login: 'androidUser2',
password: 'x6Bt0VDy5',
full_name: 'Web user 2'
}
];
|
JavaScript
| 0.000002
|
5b2f6697acd10851a49bb2fdf2040043dc15b039
|
use people API for sample (#2528)
|
samples/oauth2.js
|
samples/oauth2.js
|
// Copyright 2012 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const fs = require('fs');
const path = require('path');
const http = require('http');
const url = require('url');
const opn = require('open');
const destroyer = require('server-destroy');
const {google} = require('googleapis');
const people = google.people('v1');
/**
* To use OAuth2 authentication, we need access to a a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI. To get these credentials for your application, visit https://console.cloud.google.com/apis/credentials.
*/
const keyPath = path.join(__dirname, 'oauth2.keys.json');
let keys = {redirect_uris: ['']};
if (fs.existsSync(keyPath)) {
keys = require(keyPath).web;
}
/**
* Create a new OAuth2 client with the configured keys.
*/
const oauth2Client = new google.auth.OAuth2(
keys.client_id,
keys.client_secret,
keys.redirect_uris[0]
);
/**
* This is one of the many ways you can configure googleapis to use authentication credentials. In this method, we're setting a global reference for all APIs. Any other API you use here, like google.drive('v3'), will now use this auth client. You can also override the auth client at the service and method call levels.
*/
google.options({auth: oauth2Client});
/**
* Open an http server to accept the oauth callback. In this simple example, the only request to our webserver is to /callback?code=<code>
*/
async function authenticate(scopes) {
return new Promise((resolve, reject) => {
// grab the url that will be used for authorization
const authorizeUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes.join(' '),
});
const server = http
.createServer(async (req, res) => {
try {
if (req.url.indexOf('/oauth2callback') > -1) {
const qs = new url.URL(req.url, 'http://localhost:3000')
.searchParams;
res.end('Authentication successful! Please return to the console.');
server.destroy();
const {tokens} = await oauth2Client.getToken(qs.get('code'));
oauth2Client.credentials = tokens; // eslint-disable-line require-atomic-updates
resolve(oauth2Client);
}
} catch (e) {
reject(e);
}
})
.listen(3000, () => {
// open the browser to the authorize url to start the workflow
opn(authorizeUrl, {wait: false}).then(cp => cp.unref());
});
destroyer(server);
});
}
async function runSample() {
// retrieve user profile
const res = await people.people.get({
resourceName: 'people/me',
personFields: 'emailAddresses',
});
console.log(res.data);
}
const scopes = [
'https://www.googleapis.com/auth/contacts.readonly',
'https://www.googleapis.com/auth/user.emails.read',
'profile',
];
authenticate(scopes)
.then(client => runSample(client))
.catch(console.error);
|
// Copyright 2012 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const fs = require('fs');
const path = require('path');
const http = require('http');
const url = require('url');
const opn = require('open');
const destroyer = require('server-destroy');
const {google} = require('googleapis');
const plus = google.plus('v1');
/**
* To use OAuth2 authentication, we need access to a a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI. To get these credentials for your application, visit https://console.cloud.google.com/apis/credentials.
*/
const keyPath = path.join(__dirname, 'oauth2.keys.json');
let keys = {redirect_uris: ['']};
if (fs.existsSync(keyPath)) {
keys = require(keyPath).web;
}
/**
* Create a new OAuth2 client with the configured keys.
*/
const oauth2Client = new google.auth.OAuth2(
keys.client_id,
keys.client_secret,
keys.redirect_uris[0]
);
/**
* This is one of the many ways you can configure googleapis to use authentication credentials. In this method, we're setting a global reference for all APIs. Any other API you use here, like google.drive('v3'), will now use this auth client. You can also override the auth client at the service and method call levels.
*/
google.options({auth: oauth2Client});
/**
* Open an http server to accept the oauth callback. In this simple example, the only request to our webserver is to /callback?code=<code>
*/
async function authenticate(scopes) {
return new Promise((resolve, reject) => {
// grab the url that will be used for authorization
const authorizeUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes.join(' '),
});
const server = http
.createServer(async (req, res) => {
try {
if (req.url.indexOf('/oauth2callback') > -1) {
const qs = new url.URL(req.url, 'http://localhost:3000')
.searchParams;
res.end('Authentication successful! Please return to the console.');
server.destroy();
const {tokens} = await oauth2Client.getToken(qs.get('code'));
oauth2Client.credentials = tokens; // eslint-disable-line require-atomic-updates
resolve(oauth2Client);
}
} catch (e) {
reject(e);
}
})
.listen(3000, () => {
// open the browser to the authorize url to start the workflow
opn(authorizeUrl, {wait: false}).then(cp => cp.unref());
});
destroyer(server);
});
}
async function runSample() {
// retrieve user profile
const res = await plus.people.get({userId: 'me'});
console.log(res.data);
}
const scopes = ['https://www.googleapis.com/auth/plus.me'];
authenticate(scopes)
.then(client => runSample(client))
.catch(console.error);
|
JavaScript
| 0
|
318568ef96b963f1dca06813b44aa8db0ad8ee23
|
Update index.spec.js
|
tests/unit/index.spec.js
|
tests/unit/index.spec.js
|
import chai from 'chai';
import chaiJsonSchema from 'chai-json-schema';
import schemas from 'jsfile-schemas';
import JsFile from 'JsFile';
import OoxmlEngine from './../../src/index';
chai.use(chaiJsonSchema);
const assert = chai.assert;
describe('jsFile-ooxml', () => {
let files;
const documentSchema = schemas.document;
before(() => {
files = window.files;
});
it('should exist', () => {
assert.isFunction(OoxmlEngine);
});
it('should read the file', function () {
this.timeout(15000);
const queue = [];
for (let name in files) {
if (files.hasOwnProperty(name)) {
const jf = new JsFile(files[name], {
workerPath: '/base/dist/workers/'
});
const promise = jf.read()
.then(done, done);
queue.push(promise);
function done (result) {
assert.instanceOf(result, JsFile.Document, name);
const json = result.json();
const html = result.html();
const text = html.textContent || '';
assert.jsonSchema(json, documentSchema, name);
assert.notEqual(text.length, 0, `File ${name} shouldn't be empty`);
assert.notEqual(result.name.length, 0, `Engine should parse a name of file ${name}`);
}
}
}
return Promise.all(queue);
});
});
|
import chai from 'chai';
import chaiJsonSchema from 'chai-json-schema';
import schemas from 'jsfile-schemas';
import JsFile from 'JsFile';
import OoxmlEngine from './../../src/index';
chai.use(chaiJsonSchema);
const assert = chai.assert;
describe('jsFile-ooxml', () => {
let files;
const documentSchema = schemas.document;
before(() => {
files = window.files;
});
it('should exist', () => {
assert.isFunction(OoxmlEngine);
});
it('should read the file', function () {
this.timeout(15000);
const queue = [];
for (let name in files) {
if (files.hasOwnProperty(name)) {
const jf = new JsFile(files[name], {
workerPath: '/base/dist/workers/'
});
const promise = jf.read()
.then(done, done);
queue.push(promise);
function done (result) {
assert.instanceOf(result, JsFile.Document, name);
const json = result.json();
const html = result.html();
const text = html.textContent || '';
assert.jsonSchema(json.content, documentSchema, name);
assert.notEqual(text.length, 0, `File ${name} shouldn't be empty`);
assert.notEqual(result.name.length, 0, `Engine should parse a name of file ${name}`);
}
}
}
return Promise.all(queue);
});
});
|
JavaScript
| 0.000002
|
009d81819b84ff27276bf72b1a978831449d32b0
|
Load all macros aliases on test
|
tests/unit/macro-test.js
|
tests/unit/macro-test.js
|
import Ember from "ember";
import {
alias,
and,
bool,
collect,
empty,
equal,
filter,
filterBy,
gt,
gte,
lt,
lte,
map,
mapBy,
match,
max,
min,
none,
not,
notEmpty,
oneWay,
or,
readOnly,
reads,
setDiff,
sort,
sum,
union,
uniq
} from "ember-computed-decorators";
import { module, test, skip } from "qunit";
const { get, set } = Ember;
module('macro decorator');
test('alias', function(assert) {
var didInit = false;
var obj = Ember.Object.extend({
init() {
this._super(...arguments);
this.first = 'rob';
this.last = 'jackson';
},
/* jshint ignore:start */
@alias('first') firstName,
@empty('first') hasNoFirstName,
@notEmpty('first') hasFirstName,
@none('first') hasNoneFirstName,
@not('first') notFirstName,
@bool('first') boolFirstName,
@match('first', /rob/) firstNameMatch,
@equal('first', 'rob') firstNameEqual,
// @gt()
// @gte
// @lt
// @lte
// @and
// @or
// @any
// @oneWay
/* jshint ignore:end */
name() {
didInit = true;
}
}).create();
assert.equal(obj.get('firstName'), 'rob');
assert.equal(obj.get('hasNoFirstName'), false);
assert.equal(obj.get('hasFirstName'), true);
assert.equal(obj.get('hasNoneFirstName'), false);
assert.equal(obj.get('notFirstName'), false);
assert.equal(obj.get('boolFirstName'), true);
assert.equal(obj.get('firstNameMatch'), true);
assert.equal(obj.get('firstNameEqual'), true);
});
|
import Ember from "ember";
import {
alias,
empty,
notEmpty,
none,
not,
bool,
match,
equal
} from "ember-computed-decorators";
import { module, test, skip } from "qunit";
const { get, set } = Ember;
module('macro decorator');
test('alias', function(assert) {
var didInit = false;
var obj = Ember.Object.extend({
init() {
this._super(...arguments);
this.first = 'rob';
this.last = 'jackson';
},
/* jshint ignore:start */
@alias('first') firstName,
@empty('first') hasNoFirstName,
@notEmpty('first') hasFirstName,
@none('first') hasNoneFirstName,
@not('first') notFirstName,
@bool('first') boolFirstName,
@match('first', /rob/) firstNameMatch,
@equal('first', 'rob') firstNameEqual,
// @gt()
// @gte
// @lt
// @lte
// @and
// @or
// @any
// @oneWay
/* jshint ignore:end */
name() {
didInit = true;
}
}).create();
assert.equal(obj.get('firstName'), 'rob');
assert.equal(obj.get('hasNoFirstName'), false);
assert.equal(obj.get('hasFirstName'), true);
assert.equal(obj.get('hasNoneFirstName'), false);
assert.equal(obj.get('notFirstName'), false);
assert.equal(obj.get('boolFirstName'), true);
assert.equal(obj.get('firstNameMatch'), true);
assert.equal(obj.get('firstNameEqual'), true);
});
|
JavaScript
| 0
|
15c7c23367e1a665a3aff8527a194a012ae2503a
|
Fix forceRecur when GC is the only payment processor in use
|
js/gcform.js
|
js/gcform.js
|
// This ensures that the is_recur check box is always checked if a GoCardless payment processor is selected.
document.addEventListener('DOMContentLoaded', function () {
// This next line gets swapped out by PHP
var goCardlessProcessorIDs = [];
var isRecurInput = document.getElementById('is_recur');
var ppRadios = document.querySelectorAll('input[type="radio"][name="payment_processor_id"]');
var goCardlessProcessorSelected;
var selectedProcessorName;
isRecurInput.addEventListener('change', function(e) {
if (!isRecurInput.checked && goCardlessProcessorSelected) {
e.preventDefault();
e.stopPropagation();
forceRecurring(true);
}
});
function forceRecurring(withAlert) {
isRecurInput.checked = true;
if (withAlert) {
if (selectedProcessorName) {
alert("Contributions made with " + selectedProcessorName + " must be recurring.");
}
else {
alert("Contributions must be recurring.");
}
}
var fakeEvent = new Event('change');
isRecurInput.dispatchEvent(fakeEvent);
}
function gcFixRecurFromRadios() {
var ppID;
[].forEach.call(ppRadios, function(r) {
if (r.checked) {
ppID = parseInt(r.value);
var label = document.querySelector('label[for="' + r.id + '"]');
selectedProcessorName = label ? label.textContent : 'Direct Debit';
}
});
goCardlessProcessorSelected = (goCardlessProcessorIDs.indexOf(ppID) > -1);
if (goCardlessProcessorSelected) {
forceRecurring();
}
}
if (ppRadios.length > 1) {
// We have radio inputs to select the processor.
[].forEach.call(ppRadios, function(r) {
r.addEventListener('click', gcFixRecurFromRadios);
});
gcFixRecurFromRadios();
}
else {
var ppInput = document.querySelectorAll('input[type="hidden"][name="payment_processor_id"]');
if (ppInput.length === 1) {
// We have a single payment processor involved that won't be changing.
var ppID = parseInt(ppInput[0].value);
goCardlessProcessorSelected = (goCardlessProcessorIDs.indexOf(ppID) > -1);
if (goCardlessProcessorSelected) {
forceRecurring();
}
}
// else: no idea, let's do nothing.
}
});
|
// This ensures that the is_recur check box is always checked if a GoCardless payment processor is selected.
document.addEventListener('DOMContentLoaded', function () {
// This next line gets swapped out by PHP
var goCardlessProcessorIDs = [];
var isRecurInput = document.getElementById('is_recur');
var ppRadios = document.querySelectorAll('input[name="payment_processor_id"]');
var goCardlessProcessorSelected;
var selectedProcessorName;
isRecurInput.addEventListener('change', function(e) {
if (!isRecurInput.checked && goCardlessProcessorSelected) {
e.preventDefault();
e.stopPropagation();
forceRecurring(true);
}
});
function forceRecurring(withAlert) {
isRecurInput.checked = true;
if (withAlert) {
alert("Contributions made with " + selectedProcessorName + " must be recurring.");
}
var fakeEvent = new Event('change');
isRecurInput.dispatchEvent(fakeEvent);
}
function gcFixRecur() {
var ppID;
[].forEach.call(ppRadios, function(r) {
if (r.checked) {
ppID = parseInt(r.value);
var label = document.querySelector('label[for="' + r.id + '"]');
selectedProcessorName = label ? label.textContent : 'Direct Debit';
}
});
goCardlessProcessorSelected = (goCardlessProcessorIDs.indexOf(ppID) > -1);
if (goCardlessProcessorSelected) {
forceRecurring();
}
}
[].forEach.call(ppRadios, function(r) {
r.addEventListener('click', gcFixRecur);
});
gcFixRecur();
});
|
JavaScript
| 0
|
79a373ec421a17a6acbf1a59c389624d29538f95
|
Correct test case 1 to 4 for AboutInheritance.js
|
koans/AboutInheritance.js
|
koans/AboutInheritance.js
|
function Muppet(age, hobby) {
this.age = age;
this.hobby = hobby;
this.answerNanny = function(){
return "Everything's cool!";
}
}
function SwedishChef(age, hobby, mood) {
Muppet.call(this, age, hobby);
this.mood = mood;
this.cook = function() {
return "Mmmm soup!";
}
}
SwedishChef.prototype = new Muppet();
describe("About inheritance", function() {
beforeEach(function(){
this.muppet = new Muppet(2, "coding");
this.swedishChef = new SwedishChef(2, "cooking", "chillin");
});
it("should be able to call a method on the derived object", function() {
expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
});
it("should be able to call a method on the base object", function() {
expect(this.swedishChef.answerNanny()).toEqual("Everything's cool!");
});
it("should set constructor parameters on the base object", function() {
expect(this.swedishChef.age).toEqual(2);
expect(this.swedishChef.hobby).toEqual("cooking");
});
it("should set constructor parameters on the derived object", function() {
expect(this.swedishChef.mood).toEqual("chillin");
});
});
// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
function F() {}
F.prototype = this;
return new F();
}
function Gonzo(age, hobby, trick) {
Muppet.call(this, age, hobby);
this.trick = trick;
this.doTrick = function() {
return this.trick;
}
}
//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
// var g = new Gonzo(...);
// g instanceOf Muppet //true
describe("About Crockford's inheritance improvement", function() {
beforeEach(function(){
this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
});
it("should be able to call a method on the derived object", function() {
expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
});
it("should be able to call a method on the base object", function() {
expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
});
it("should set constructor parameters on the base object", function() {
expect(this.gonzo.age).toEqual(FILL_ME_IN);
expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
});
it("should set constructor parameters on the derived object", function() {
expect(this.gonzo.trick).toEqual(FILL_ME_IN);
});
});
|
function Muppet(age, hobby) {
this.age = age;
this.hobby = hobby;
this.answerNanny = function(){
return "Everything's cool!";
}
}
function SwedishChef(age, hobby, mood) {
Muppet.call(this, age, hobby);
this.mood = mood;
this.cook = function() {
return "Mmmm soup!";
}
}
SwedishChef.prototype = new Muppet();
describe("About inheritance", function() {
beforeEach(function(){
this.muppet = new Muppet(2, "coding");
this.swedishChef = new SwedishChef(2, "cooking", "chillin");
});
it("should be able to call a method on the derived object", function() {
expect(this.swedishChef.cook()).toEqual(FILL_ME_IN);
});
it("should be able to call a method on the base object", function() {
expect(this.swedishChef.answerNanny()).toEqual(FILL_ME_IN);
});
it("should set constructor parameters on the base object", function() {
expect(this.swedishChef.age).toEqual(FILL_ME_IN);
expect(this.swedishChef.hobby).toEqual(FILL_ME_IN);
});
it("should set constructor parameters on the derived object", function() {
expect(this.swedishChef.mood).toEqual(FILL_ME_IN);
});
});
// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
function F() {}
F.prototype = this;
return new F();
}
function Gonzo(age, hobby, trick) {
Muppet.call(this, age, hobby);
this.trick = trick;
this.doTrick = function() {
return this.trick;
}
}
//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
// var g = new Gonzo(...);
// g instanceOf Muppet //true
describe("About Crockford's inheritance improvement", function() {
beforeEach(function(){
this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
});
it("should be able to call a method on the derived object", function() {
expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
});
it("should be able to call a method on the base object", function() {
expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
});
it("should set constructor parameters on the base object", function() {
expect(this.gonzo.age).toEqual(FILL_ME_IN);
expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
});
it("should set constructor parameters on the derived object", function() {
expect(this.gonzo.trick).toEqual(FILL_ME_IN);
});
});
|
JavaScript
| 0.000082
|
895c9f16aca4c85dfd6f1eafe8b4db1d72b267ab
|
improve javascript
|
marginotes.js
|
marginotes.js
|
var marginotes = function (options) {
options = options || {};
var field = options.field || 'desc';
var spans = this.filter('span');
$('body').append('<div class="margintooltip" style="display: none;"></div>');
spans.css({
'border-bottom': '1px dashed #337ab7',
'cursor': 'help'
});
this.hover(function (e) {
var description = $(this).attr(field);
var parent = $(this.parentElement);
var position = parent.position();
var tooltip = $('.margintooltip');
var width = Math.min(options.width || 100, position.left);
if (width < 60 || !description) {
return;
}
tooltip
.css({
'border-right': 'solid 2px #337ab7',
'font-size': '13px',
'left': position.left - width - 5,
'min-height': parent.height(),
'padding-right': '7px',
'position': 'absolute',
'text-align': 'right',
'top': position.top,
'width': width
})
.text(description)
.stop()
.fadeIn({
duration:100,
queue: false
});
}, function () {
$('.margintooltip').stop();
$('.margintooltip').fadeOut({
duration: 100
});
});
};
window.jQuery.prototype.marginotes = window.$.prototype.marginotes = marginotes;
|
var marginotes = function (options) {
var options = options || {}
$('body').append('<div class = "margintooltip" style = "display:none;"></div>')
var field = options.field || "desc"
var spans = this.filter("span")
spans.css({ 'border-bottom': '1px dashed #337ab7',
'cursor': 'help' })
this.hover(function (e) {
var description = $(this).attr(field)
var parent = $(this.parentElement)
var position = parent.position()
var tooltip = $('.margintooltip')
var width = Math.min(options.width || 100, position.left)
if (width < 60 || !description) return
var tooltipStyle = {
"position": "absolute",
"border-right": "solid 2px #337ab7",
"width": "50px",
"font-size": "13px",
"text-align": "right",
"padding-right": "7px",
"top": position.top,
"left": position.left - width - 5,
"min-height": parent.height(),
"width": width
}
tooltip.css(tooltipStyle)
tooltip.text(description)
tooltip.stop()
tooltip.fadeIn({duration:100, queue: false})
}, function () {
$('.margintooltip').stop()
$('.margintooltip').fadeOut({duration:100})
})
}
window.jQuery.prototype.marginotes = window.$.prototype.marginotes = marginotes
|
JavaScript
| 0.000316
|
104bf2e18f2b97b7842b74c3e6e93027e847bfcd
|
Update script.js
|
js/script.js
|
js/script.js
|
jQuery(document).ready(function($) {
/ono scroll, navbar shrinks
$(window).scroll(function() {
var scroll = $(this).scrollTop();
var nav = $('#header');
// nav.addClass('#main-navbar.second-state');
if (scroll > 200) {
nav.addClass('#main-navbar.second-state');
} else {
nav.removeClass('#main-navbar.second-state');
}
});
$('.slider').slick({
arrows: true,
dots: true,
centerMode: true,
slidesToShow: 1,
infinite: true,
adaptiveHeight: false,
fade: false
});
});
|
jQuery(document).ready(function($) {
// function - on scroll, navbar shrinks
$(window).scroll(function() {
var scroll = $(this).scrollTop();
var nav = $('#main-navbar');
// nav.addClass('#main-navbar.second-state');
if (scroll > 200) {
nav.addClass('#main-navbar.second-state');
} else {
nav.removeClass('#main-navbar.second-state');
}
});
$('.slider').slick({
arrows: true,
dots: true,
centerMode: true,
slidesToShow: 1,
infinite: true,
adaptiveHeight: false,
fade: false
});
});
|
JavaScript
| 0.000002
|
8637794d54cc444f11a139838358adda989aa639
|
Update script.js
|
js/script.js
|
js/script.js
|
/**
* Created by Gopalakrishnan on 7/5/2017.
*/
$(document).ready(function () {
loadMenu();
addEmailandNumber();
/*loadResumeLink();*/
loadYear();
});
function loadMenu() {
var menuhtml = '<a class="mdl-navigation__link" href="index">Overview</a>';
menuhtml += '<a class="mdl-navigation__link" href="skills">Skills</a>';
menuhtml += '<a class="mdl-navigation__link" href="work-experience">Work Experience</a>';
/*menuhtml += '<a class="mdl-navigation__link" href="competitive-programming">Competitive Programming</a>';*/
/*menuhtml += '<a class="mdl-navigation__link" href="open-source">Open Source</a>';*/
/*menuhtml += '<a class="mdl-navigation__link" href="education">Education</a>';*/
menuhtml += '<a class="mdl-navigation__link" href="projects">Projects</a>';
/*menuhtml += '<a class="mdl-navigation__link" id="resume-link" target="_blank">Resume</a>';*/
menuhtml += '<a class="mdl-navigation__link" href="https://github.com/gopalakrishnan-anbumani" target="_blank">Code on Github</a>';
/*menuhtml += '<a class="mdl-navigation__link" href="https://medium.com/@manishbisht" target="_blank">Blog on Medium</a>';*/
menuhtml += '<a class="mdl-navigation__link" href="https://www.quora.com/profile/gopalakrishnan-anbumani" target="_blank">Questions on Quora</a>';
menuhtml += '<a class="mdl-navigation__link" href="contact">Contact</a>';
$('#main-menu').html(menuhtml);
}
function loadResumeLink() {
var resume = "http://goo.gl/Rro9Sk";
document.getElementById('resume-link').href = resume;
}
function addEmailandNumber() {
var email = "[email protected]";
var mobileNumber = "+91-8248912123";
$(".email").html(email);
$(".mobile-number").html(mobileNumber);
}
function loadYear() {
var currentTime = new Date();
$("#copyright-year").text(currentTime.getFullYear());
}
|
/**
* Created by Gopalakrishnan on 7/5/2017.
*/
$(document).ready(function () {
loadMenu();
addEmailandNumber();
/*loadResumeLink();*/
loadYear();
});
function loadMenu() {
var menuhtml = '<a class="mdl-navigation__link" href="index">Overview</a>';
menuhtml += '<a class="mdl-navigation__link" href="skills">Skills</a>';
menuhtml += '<a class="mdl-navigation__link" href="work-experience">Work Experience</a>';
/*menuhtml += '<a class="mdl-navigation__link" href="competitive-programming">Competitive Programming</a>';*/
/*menuhtml += '<a class="mdl-navigation__link" href="open-source">Open Source</a>';*/
/*menuhtml += '<a class="mdl-navigation__link" href="education">Education</a>';*/
menuhtml += '<a class="mdl-navigation__link" href="projects">Projects</a>';
/*menuhtml += '<a class="mdl-navigation__link" id="resume-link" target="_blank">Resume</a>';*/
menuhtml += '<a class="mdl-navigation__link" href="https://github.com/gopalakrishnan-anbumani" target="_blank">Code on Github</a>';
/*menuhtml += '<a class="mdl-navigation__link" href="https://medium.com/@manishbisht" target="_blank">Blog on Medium</a>';*/
menuhtml += '<a class="mdl-navigation__link" href="https://www.quora.com/profile/gopalakrishnan-anbumani" target="_blank">Questions on Quora</a>';
menuhtml += '<a class="mdl-navigation__link" href="contact">Contact</a>';
$('#main-menu').html(menuhtml);
}
function loadResumeLink() {
var resume = "http://goo.gl/Rro9Sk";
document.getElementById('resume-link').href = resume;
}
function addEmailandNumber() {
var email = "[email protected]";
var mobileNumber = "+91-8248912123";
$(".email").html(email);
$(".mobile-number").html(mobileNumber);
}
function loadYear() {
var currentTime = new Date();
$("#copyright-year").text(currentTime.getFullYear());
}
|
JavaScript
| 0.000002
|
e66e106c003573c1d1a346481fce4e2b1335cbc2
|
fix typo in code document -> window
|
js/script.js
|
js/script.js
|
/* This script will be available on every screen as a child of the window object (see data/app.xml). */
window.addEventListener(Savvy.LOAD, function(){
// fired once when Savvy loads first
document.querySelector("audio").play();
});
window.addEventListener(Savvy.READY, function(){
// fired every time a screen "ready" event is published
});
window.addEventListener(Savvy.ENTER, function(){
// fired every time a screen "enter" event is published
});
window.addEventListener(Savvy.EXIT, function(e){
// fired every time a screen "exit" event is published
});
|
/* This script will be available on every screen as a child of the window object (see data/app.xml). */
window.addEventListener(Savvy.LOAD, function(){
// fired once when Savvy loads first
document.querySelector("audio").play();
});
window.addEventListener(Savvy.READY, function(){
// fired every time a screen "ready" event is published
});
document.addEventListener(Savvy.ENTER, function(){
// fired every time a screen "enter" event is published
});
window.addEventListener(Savvy.EXIT, function(e){
// fired every time a screen "exit" event is published
});
|
JavaScript
| 0.000033
|
63f82cafdf4524a53aee562754b306bb0fb951f0
|
Update script.js
|
js/script.js
|
js/script.js
|
(function(window, document, undefined) {
window.onload = init;
function init() {
//get the canvas
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var width = 960;
var height = 540;
}
document.getElementById("paintbtn").onclick = paint;
function paint(){
var widthSelect = document.getElementById("width");
width = widthSelect.options[widthSelect.selectedIndex].value;
var heightSelect = document.getElementById("height");
height = heightSelect.options[heightSelect.selectedIndex].value;
}
})(window, document, undefined);
|
(function(window, document, undefined) {
window.onload = init;
function init() {
//get the canvas
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var width = 960;
var height = 540;
}
})(window, document, undefined);
|
JavaScript
| 0.000002
|
52b9e97c0b7acc7cfaf9e02a6bfe52bc135a6cbb
|
Update script.js
|
js/script.js
|
js/script.js
|
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.11.0.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
(function(window, document, undefined) {
window.onload = init;
function init() {
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var myTimer;
var blockSize = 10;
// set the dynamic outside the loop
var it1 = -1;
var it2 = -1;
//loop function
function loop() {
it1 = it1+1;
if(it1 % 96 == 0){
it1 = 0;
it2 = it2+1;
}
// change dynamic
//dynamic = dynamic * 1.1;
x = it1*blockSize;
y = it2*blockSize;
//if we've reached the end, change direction
// stop the the animation if it runs out-of-canvas
if (it2 > 54) {
//c.clearRect(0, 0, canvas.width, canvas.height);
clearInterval(myTimer);
}
// clear the canvas for this loop's animation
//c.clearRect(0, 0, canvas.width, canvas.height);
c.fillStyle = '#87CEEB';
// draw
c.beginPath();
c.fillRect(x, y, 10, 10);
c.fill();
}
$("#startbtn").click(function(){ dynamic=10; myTimer=setInterval(loop,20); });
}
})(window, document, undefined);
|
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-1.11.0.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
(function(window, document, undefined) {
window.onload = init;
function init() {
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var myTimer;
var blockSize = 10;
// set the dynamic outside the loop
var it1 = -1;
var it2 = -1
//loop function
function loop() {
it1 = it1+1
if(it1 % 96 == 0){
it2 = it2+1
}
// change dynamic
//dynamic = dynamic * 1.1;
x = it1*blockSize;
y = it2*blockSize;
//if we've reached the end, change direction
// stop the the animation if it runs out-of-canvas
if (it2 > 54) {
//c.clearRect(0, 0, canvas.width, canvas.height);
clearInterval(myTimer);
}
// clear the canvas for this loop's animation
//c.clearRect(0, 0, canvas.width, canvas.height);
c.fillStyle = '#87CEEB';
// draw
c.beginPath();
c.fillRect(x, y, 10, 10);
c.fill();
}
$("#startbtn").click(function(){ dynamic=10; myTimer=setInterval(loop,20); });
}
})(window, document, undefined);
|
JavaScript
| 0.000002
|
886981718049d73389d6416e54d2c1e35eecc58d
|
Update slider.js
|
js/slider.js
|
js/slider.js
|
;
(
function ( $, window, document, undefined ) {
"use strict";
var pluginName = "slider";
var defaults = {
delay: 1000,
interval: 10000
};
function Plugin( element, options ) {
this.element = element;
this.settings = $.extend( {}, defaults, options );
this.vari = {
timer: undefined,
slide: 1,
slides: 0
};
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function () {
var self = this;
var $slider = $( this.element );
var $position = $slider.find( '.position' );
$slider.children( '.slides' ).find( 'img' ).each( function ( index, element ) {
self.vari.slides ++;
if ( self.vari.slides == self.vari.slide ) {
$( element ).addClass( 'active' ).css( 'opacity', '1' );
$position.append( '<div class="points active"></div>' );
} else {
$( element ).css( 'opacity', '0' );
$position.append( '<div class="points"></div>' );
}
} );
$position.find( '.points' ).each( function ( index ) {
$( this ).click( function () {
self.show( index + 1 );
} );
} );
$slider.hover( function () {
clearInterval( self.vari.timer );
}, function () {
self.auto();
} );
$slider.find( '.prev > *' ).click( function () {
self.prev();
} );
$slider.find( '.next > *' ).click( function () {
self.next();
} );
this.auto();
},
auto: function () {
var self = this;
this.vari.timer = setInterval( function () {
self.next();
}, this.settings.interval );
},
next: function () {
if ( this.vari.slide < this.vari.slides ) {
this.show( this.vari.slide + 1 );
} else {
this.show( 1 );
}
},
prev: function () {
if ( this.vari.slide > 1 ) {
this.show( this.vari.slide - 1 );
} else {
this.show( this.vari.slides );
}
},
show: function ( slide ) {
$( this.element ).find( '.slides img:nth-child(' + this.vari.slide + ')' ).stop().removeClass( 'active' ).animate( {opacity: 0}, this.settings.delay );
$( this.element ).find( '.position .points:nth-child(' + this.vari.slide + ')' ).removeClass( 'active' );
$( this.element ).find( '.text span:nth-child(' + this.vari.slide + ')' ).removeClass( 'active' );
this.vari.slide = slide;
$( this.element ).find( '.slides img:nth-child(' + this.vari.slide + ')' ).stop().addClass( 'active' ).animate( {opacity: 1}, this.settings.delay );
$( this.element ).find( '.position .points:nth-child(' + this.vari.slide + ')' ).addClass( 'active' );
$( this.element ).find( '.text span:nth-child(' + this.vari.slide + ')' ).addClass( 'active' );
return this;
}
};
$.fn[pluginName] = function ( options ) {
this.each( function () {
if ( ! $.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
} );
return this;
};
}
)( jQuery, window, document );
|
;
(
function ( $, window, document, undefined ) {
"use strict";
var pluginName = "slider";
var defaults = {
delay: 1000,
interval: 10000
};
function Plugin( element, options ) {
this.element = element;
this.settings = $.extend( {}, defaults, options );
this.vari = {
timer: undefined,
slide: 1,
slides: 0
};
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function () {
var self = this;
var $slider = $( this.element );
var $position = $slider.find( '.position' );
$slider.children( '.slides' ).find( 'img' ).each( function ( index, element ) {
self.vari.slides ++;
if ( self.vari.slides == self.vari.slide ) {
$( element ).addClass( 'active' ).css( 'opacity', '1' );
$position.append( '<div class="points active"></div>' );
} else {
$( element ).css( 'opacity', '0' );
$position.append( '<div class="points"></div>' );
}
} );
$position.find( '.points' ).each( function ( index ) {
$( this ).click( function () {
self.show( index + 1 );
} );
} );
$slider.hover( function () {
clearInterval( self.vari.timer );
}, function () {
self.auto();
} );
$slider.find( '.prev > *' ).click( function () {
self.prev();
} );
$slider.find( '.next > *' ).click( function () {
self.next();
} );
this.auto();
},
auto: function () {
var self = this;
this.vari.timer = setInterval( function () {
self.next();
}, this.settings.interval );
},
next: function () {
if ( this.vari.slide < this.vari.slides ) {
this.show( this.vari.slide + 1 );
} else {
this.show( 1 );
}
},
prev: function () {
if ( this.vari.slide > 1 ) {
this.show( this.vari.slide - 1 );
} else {
this.show( this.vari.slides );
}
},
show: function ( slide ) {
$( this.element ).find( '.slides img:nth-child(' + this.vari.slide + ')' ).stop().removeClass( 'active' ).animate( {opacity: 0},
this.settings.delay );
$( this.element ).find( '.position .points:nth-child(' + this.vari.slide + ')' ).removeClass( 'active' );
$( this.element ).find( '.text span:nth-child(' + this.vari.slide + ')' ).removeClass( 'active' );
this.vari.slide = slide;
$( this.element ).find( '.slides img:nth-child(' + this.vari.slide + ')' ).stop().addClass( 'active' ).animate( {opacity: 1},
this.settings.delay );
$( this.element ).find( '.position .points:nth-child(' + this.vari.slide + ')' ).addClass( 'active' );
$( this.element ).find( '.text span:nth-child(' + this.vari.slide + ')' ).addClass( 'active' );
return this;
}
};
$.fn[pluginName] = function ( options ) {
this.each( function () {
if ( ! $.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
} );
return this;
};
}
)( jQuery, window, document );
|
JavaScript
| 0.000001
|
ce7f2b2986f36d657c7271ada12d173ce7f48fab
|
Update splash.js
|
js/splash.js
|
js/splash.js
|
var content = "<span class='badge'>New</span>";
var content += "Un nuovo video sull'autismo (realizzato con la collaborazione del prof. Tony Attwood, esperto dell'autismo)";
var thumbup = <span class=\"glyphicon glyphicon-thumbs-up\"></span>";
splasha.innerHTML = content + thumbup
splashb.innerHTML = content + thumbup
splashc.innerHTML = content + thumbup
|
var content = "<span class='badge'>New</span>";
var content += "Un nuovo video sull'autismo (realizzato con la collaborazione del prof. Tony Attwood, esperto dell'autismo)"
var thumbup = <span class=\"glyphicon glyphicon-thumbs-up\"></span>";
<!-- this is the same for all the groups -->
splasha.innerHTML = content + thumbup
splashb.innerHTML = content + thumbup
splashc.innerHTML = content + thumbup
|
JavaScript
| 0.000001
|
565087faabc1dbbee7ab0802e4fc10175ef6b825
|
add change for dist dir
|
dist/geom/ShapeUtils.js
|
dist/geom/ShapeUtils.js
|
/**
* Created by Samuel Gratzl on 27.12.2016.
*/
import { AShape } from './AShape';
import { Rect } from './Rect';
import { Circle } from './Circle';
import { Ellipse } from './Ellipse';
import { Line } from './Line';
import { Polygon } from './Polygon';
class ShapeUtils {
static wrapToShape(obj) {
if (!obj) {
return obj;
}
if (obj instanceof AShape) {
return obj;
}
if (obj.hasOwnProperty('x') && obj.hasOwnProperty('y')) {
if (obj.hasOwnProperty('radius') || obj.hasOwnProperty('r')) {
return Circle.circle(obj.x, obj.y, obj.hasOwnProperty('radius') ? obj.radius : obj.r);
}
if ((obj.hasOwnProperty('radiusX') || obj.hasOwnProperty('rx')) && (obj.hasOwnProperty('radiusY') || obj.hasOwnProperty('ry'))) {
return Ellipse.ellipse(obj.x, obj.y, obj.hasOwnProperty('radiusX') ? obj.radiusX : obj.rx, obj.hasOwnProperty('radiusY') ? obj.radiusY : obj.ry);
}
if (obj.hasOwnProperty('w') && obj.hasOwnProperty('h')) {
return Rect.rect(obj.x, obj.y, obj.w, obj.h);
}
if (obj.hasOwnProperty('width') && obj.hasOwnProperty('height')) {
return Rect.rect(obj.x, obj.y, obj.width, obj.height);
}
}
if (obj.hasOwnProperty('x1') && obj.hasOwnProperty('y1') && obj.hasOwnProperty('x2') && obj.hasOwnProperty('y2')) {
return Line.line(obj.x1, obj.y1, obj.x2, obj.y2);
}
if (Array.isArray(obj) && obj.length > 0 && obj[0].hasOwnProperty('x') && obj[0].hasOwnProperty('y')) {
return Polygon.polygon(obj);
}
// TODO throw error?
return obj; //can't derive it, yet
}
}
//# sourceMappingURL=ShapeUtils.js.map
|
/**
* Created by Samuel Gratzl on 27.12.2016.
*/
import { AShape } from './AShape';
import { Rect } from './Rect';
import { Circle } from './Circle';
import { Ellipse } from './Ellipse';
import { Line } from './Line';
import { Polygon } from './Polygon';
export class ShapeUtils {
static wrapToShape(obj) {
if (!obj) {
return obj;
}
if (obj instanceof AShape) {
return obj;
}
if (obj.hasOwnProperty('x') && obj.hasOwnProperty('y')) {
if (obj.hasOwnProperty('radius') || obj.hasOwnProperty('r')) {
return Circle.circle(obj.x, obj.y, obj.hasOwnProperty('radius') ? obj.radius : obj.r);
}
if ((obj.hasOwnProperty('radiusX') || obj.hasOwnProperty('rx')) && (obj.hasOwnProperty('radiusY') || obj.hasOwnProperty('ry'))) {
return Ellipse.ellipse(obj.x, obj.y, obj.hasOwnProperty('radiusX') ? obj.radiusX : obj.rx, obj.hasOwnProperty('radiusY') ? obj.radiusY : obj.ry);
}
if (obj.hasOwnProperty('w') && obj.hasOwnProperty('h')) {
return Rect.rect(obj.x, obj.y, obj.w, obj.h);
}
if (obj.hasOwnProperty('width') && obj.hasOwnProperty('height')) {
return Rect.rect(obj.x, obj.y, obj.width, obj.height);
}
}
if (obj.hasOwnProperty('x1') && obj.hasOwnProperty('y1') && obj.hasOwnProperty('x2') && obj.hasOwnProperty('y2')) {
return Line.line(obj.x1, obj.y1, obj.x2, obj.y2);
}
if (Array.isArray(obj) && obj.length > 0 && obj[0].hasOwnProperty('x') && obj[0].hasOwnProperty('y')) {
return Polygon.polygon(obj);
}
// TODO throw error?
return obj; //can't derive it, yet
}
}
//# sourceMappingURL=ShapeUtils.js.map
|
JavaScript
| 0
|
5b440fc021d50bec3dbdd9464d80b626a6929988
|
add Triangle
|
javascripts/enemies/triangle.js
|
javascripts/enemies/triangle.js
|
Triangle = Class.create(Enemy, {
initialize: function(x, y) {
Sprite.call(this, 50, 50);
this.image = game.assets['images/triangle_glow.png'];
this.frame = 0;
this.x = x;
this.y = y;
this.speed = 2;
this.scoreValue = 10;
},
onenterframe: function() {
this.collisionDetect();
this.followPlayer();
}
});
|
JavaScript
| 0.999986
|
|
1cdcd3227d9d70e0e11bf4ec30d0402638c98e3c
|
Remove Sample app comment
|
index.ios.js
|
index.ios.js
|
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
import Guco from './Guco';
const views = [
{ title: 'Guco' },
{ title: 'McGucci' },
{ title: 'Go Hord' }
];
const images = [
'https://images.unsplash.com/photo-1494249465471-5655b7878482?dpr=2&auto=format&fit=crop&w=1080&h=720',
'https://images.unsplash.com/photo-1459909633680-206dc5c67abb?dpr=2&auto=format&fit=crop&w=1080&h=720',
'https://images.unsplash.com/photo-1490237014491-822aee911b99?dpr=2&auto=format&fit=crop&w=1080&h=720'
];
export default class ParallaxSwiper extends Component {
render() {
return (
<View style={styles.container}>
<Guco
dividerWidth={4}
parallaxStrength={300}
dividerColor="white"
backgroundImages={images}
ui={
views.map((view, i) => (
<View key={i} style={styles.slideInnerContainer}>
<Text style={styles.slideText}>
Slide {i}
</Text>
</View>
))
}
showsHorizontalScrollIndicator={false}
onMomentumScrollEnd={() => console.log('Swiper finished swiping')}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
slideInnerContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
slideText: {
fontSize: 36,
fontWeight: '900',
letterSpacing: -0.4,
},
});
AppRegistry.registerComponent('ParallaxSwiper', () => ParallaxSwiper);
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image
} from 'react-native';
import Guco from './Guco';
const views = [
{ title: 'Guco' },
{ title: 'McGucci' },
{ title: 'Go Hord' }
];
const images = [
'https://images.unsplash.com/photo-1494249465471-5655b7878482?dpr=2&auto=format&fit=crop&w=1080&h=720',
'https://images.unsplash.com/photo-1459909633680-206dc5c67abb?dpr=2&auto=format&fit=crop&w=1080&h=720',
'https://images.unsplash.com/photo-1490237014491-822aee911b99?dpr=2&auto=format&fit=crop&w=1080&h=720'
];
export default class ParallaxSwiper extends Component {
render() {
return (
<View style={styles.container}>
<Guco
dividerWidth={4}
parallaxStrength={300}
dividerColor="white"
backgroundImages={images}
ui={
views.map((view, i) => (
<View key={i} style={styles.slideInnerContainer}>
<Text style={styles.slideText}>
Slide {i}
</Text>
</View>
))
}
showsHorizontalScrollIndicator={false}
onMomentumScrollEnd={() => console.log('Swiper finished swiping')}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
slideInnerContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
slideText: {
fontSize: 36,
fontWeight: '900',
letterSpacing: -0.4,
},
});
AppRegistry.registerComponent('ParallaxSwiper', () => ParallaxSwiper);
|
JavaScript
| 0
|
edf3a7fb5b8b65065d2f0ad296a83f56e70221e2
|
fix test case class name
|
src/Component/Stopwatch/test/StopwatchTest.js
|
src/Component/Stopwatch/test/StopwatchTest.js
|
import { expect } from 'chai';
const Stopwatch = Jymfony.Component.Stopwatch.Stopwatch;
const StopwatchEvent = Jymfony.Component.Stopwatch.StopwatchEvent;
const TestCase = Jymfony.Component.Testing.Framework.TestCase;
export default class StopwatchTest extends TestCase {
get testCaseName() {
return '[Stopwatch] ' + super.testCaseName;
}
testStart() {
const stopwatch = new Stopwatch();
const event = stopwatch.start('foo', 'cat');
expect(event).to.be.instanceOf(StopwatchEvent);
expect(event.category).to.be.equal('cat');
expect(stopwatch.getEvent('foo')).to.be.equal(event);
}
testStartWithoutCategory() {
const stopwatch = new Stopwatch();
const event = stopwatch.start('bar');
expect(event.category).to.be.equal('default');
expect(stopwatch.getEvent('bar')).to.be.equal(event);
}
testIsStarted() {
const stopwatch = new Stopwatch();
expect(stopwatch.isStarted('foo')).to.be.equal(false);
stopwatch.start('foo', 'cat');
expect(stopwatch.isStarted('foo')).to.be.equal(true);
stopwatch.stop('foo');
expect(stopwatch.isStarted('foo')).to.be.equal(false);
}
testGetEventShouldThrowOnUnknownEvent() {
const stopwatch = new Stopwatch();
expect(() => stopwatch.getEvent('foo')).to.throw(LogicException);
}
testStopWithoutStart() {
const stopwatch = new Stopwatch();
expect(() => stopwatch.stop('foo')).to.throw(LogicException);
}
testSections() {
const stopwatch = new Stopwatch();
stopwatch.openSection();
stopwatch.start('foo', 'cat');
stopwatch.stop('foo');
stopwatch.start('bar', 'cat');
stopwatch.stop('bar');
stopwatch.stopSection('1');
stopwatch.openSection();
stopwatch.start('foobar', 'cat');
stopwatch.stop('foobar');
stopwatch.stopSection('2');
stopwatch.openSection();
stopwatch.start('foobar', 'cat');
stopwatch.stop('foobar');
stopwatch.stopSection('0');
expect(Object.keys(stopwatch.getSectionEvents('1'))).to.have.length(3);
expect(Object.keys(stopwatch.getSectionEvents('2'))).to.have.length(2);
expect(Object.keys(stopwatch.getSectionEvents('0'))).to.have.length(2);
}
testReopenSection() {
const stopwatch = new Stopwatch();
stopwatch.openSection();
stopwatch.start('foo', 'cat');
stopwatch.stopSection('section');
stopwatch.openSection('section');
stopwatch.start('bar', 'cat');
stopwatch.stopSection('section');
const events = stopwatch.getSectionEvents('section');
expect(Object.keys(events)).to.have.length(3);
expect(events['__section__'].periods).to.have.length(2);
}
}
|
import { expect } from 'chai';
const Stopwatch = Jymfony.Component.Stopwatch.Stopwatch;
const StopwatchEvent = Jymfony.Component.Stopwatch.StopwatchEvent;
const TestCase = Jymfony.Component.Testing.Framework.TestCase;
export default class StopwatchPeriodTest extends TestCase {
get testCaseName() {
return '[Stopwatch] ' + super.testCaseName;
}
testStart() {
const stopwatch = new Stopwatch();
const event = stopwatch.start('foo', 'cat');
expect(event).to.be.instanceOf(StopwatchEvent);
expect(event.category).to.be.equal('cat');
expect(stopwatch.getEvent('foo')).to.be.equal(event);
}
testStartWithoutCategory() {
const stopwatch = new Stopwatch();
const event = stopwatch.start('bar');
expect(event.category).to.be.equal('default');
expect(stopwatch.getEvent('bar')).to.be.equal(event);
}
testIsStarted() {
const stopwatch = new Stopwatch();
expect(stopwatch.isStarted('foo')).to.be.equal(false);
stopwatch.start('foo', 'cat');
expect(stopwatch.isStarted('foo')).to.be.equal(true);
stopwatch.stop('foo');
expect(stopwatch.isStarted('foo')).to.be.equal(false);
}
testGetEventShouldThrowOnUnknownEvent() {
const stopwatch = new Stopwatch();
expect(() => stopwatch.getEvent('foo')).to.throw(LogicException);
}
testStopWithoutStart() {
const stopwatch = new Stopwatch();
expect(() => stopwatch.stop('foo')).to.throw(LogicException);
}
testSections() {
const stopwatch = new Stopwatch();
stopwatch.openSection();
stopwatch.start('foo', 'cat');
stopwatch.stop('foo');
stopwatch.start('bar', 'cat');
stopwatch.stop('bar');
stopwatch.stopSection('1');
stopwatch.openSection();
stopwatch.start('foobar', 'cat');
stopwatch.stop('foobar');
stopwatch.stopSection('2');
stopwatch.openSection();
stopwatch.start('foobar', 'cat');
stopwatch.stop('foobar');
stopwatch.stopSection('0');
expect(Object.keys(stopwatch.getSectionEvents('1'))).to.have.length(3);
expect(Object.keys(stopwatch.getSectionEvents('2'))).to.have.length(2);
expect(Object.keys(stopwatch.getSectionEvents('0'))).to.have.length(2);
}
testReopenSection() {
const stopwatch = new Stopwatch();
stopwatch.openSection();
stopwatch.start('foo', 'cat');
stopwatch.stopSection('section');
stopwatch.openSection('section');
stopwatch.start('bar', 'cat');
stopwatch.stopSection('section');
const events = stopwatch.getSectionEvents('section');
expect(Object.keys(events)).to.have.length(3);
expect(events['__section__'].periods).to.have.length(2);
}
}
|
JavaScript
| 0.000003
|
6217aff4445e16885e5e05debc19e8bd298a82b2
|
remove duplicate test
|
packages/ember-metal/tests/performance_test.js
|
packages/ember-metal/tests/performance_test.js
|
/*
This test file is designed to capture performance regressions related to
deferred computation. Things like run loops, computed properties, and bindings
should run the minimum amount of times to achieve best performance, so any
bugs that cause them to get evaluated more than necessary should be put here.
*/
module("Computed Properties - Number of times evaluated");
test("computed properties that depend on multiple properties should run only once per run loop", function() {
var obj = {a: 'a', b: 'b', c: 'c'};
var cpCount = 0, obsCount = 0;
Ember.defineProperty(obj, 'abc', Ember.computed(function(key) {
cpCount++;
return 'computed '+key;
}).property('a', 'b', 'c'));
Ember.addObserver(obj, 'abc', function() {
obsCount++;
});
Ember.beginPropertyChanges();
Ember.set(obj, 'a', 'aa');
Ember.set(obj, 'b', 'bb');
Ember.set(obj, 'c', 'cc');
Ember.endPropertyChanges();
Ember.get(obj, 'abc');
equal(cpCount, 1, "The computed property is only invoked once");
equal(obsCount, 1, "The observer is only invoked once");
});
test("computed properties are not executed if they are the last segment of an observer chain pain", function() {
var foo = { bar: { baz: { } } };
var count = 0;
Ember.defineProperty(foo.bar.baz, 'bam', Ember.computed(function() {
count++;
}));
Ember.addObserver(foo, 'bar.baz.bam', function() {});
Ember.propertyDidChange(Ember.get(foo, 'bar.baz'), 'bam');
equal(count, 0, "should not have recomputed property");
});
|
/*
This test file is designed to capture performance regressions related to
deferred computation. Things like run loops, computed properties, and bindings
should run the minimum amount of times to achieve best performance, so any
bugs that cause them to get evaluated more than necessary should be put here.
*/
module("Computed Properties - Number of times evaluated");
test("computed properties that depend on multiple properties should run only once per run loop", function() {
var obj = {a: 'a', b: 'b', c: 'c'};
var count = 0;
Ember.defineProperty(obj, 'abc', Ember.computed(function(key) {
count++;
return 'computed '+key;
}).property('a', 'b', 'c'));
Ember.beginPropertyChanges();
Ember.set(obj, 'a', 'aa');
Ember.set(obj, 'b', 'bb');
Ember.set(obj, 'c', 'cc');
Ember.endPropertyChanges();
Ember.get(obj, 'abc');
equal(count, 1, "The computed property is only invoked once");
});
test("computed properties that depend on multiple properties should run only once per run loop", function() {
var obj = {a: 'a', b: 'b', c: 'c'};
var cpCount = 0, obsCount = 0;
Ember.defineProperty(obj, 'abc', Ember.computed(function(key) {
cpCount++;
return 'computed '+key;
}).property('a', 'b', 'c'));
Ember.addObserver(obj, 'abc', function() {
obsCount++;
});
Ember.beginPropertyChanges();
Ember.set(obj, 'a', 'aa');
Ember.set(obj, 'b', 'bb');
Ember.set(obj, 'c', 'cc');
Ember.endPropertyChanges();
Ember.get(obj, 'abc');
equal(cpCount, 1, "The computed property is only invoked once");
equal(obsCount, 1, "The observer is only invoked once");
});
test("computed properties are not executed if they are the last segment of an observer chain pain", function() {
var foo = { bar: { baz: { } } };
var count = 0;
Ember.defineProperty(foo.bar.baz, 'bam', Ember.computed(function() {
count++;
}));
Ember.addObserver(foo, 'bar.baz.bam', function() {});
Ember.propertyDidChange(Ember.get(foo, 'bar.baz'), 'bam');
equal(count, 0, "should not have recomputed property");
});
|
JavaScript
| 0.000409
|
f7a460c37b6a4fdbbd40610f8fc45d70253742be
|
Update utils-constants.js
|
dataprep-webapp/src/services/utils/constants/utils-constants.js
|
dataprep-webapp/src/services/utils/constants/utils-constants.js
|
(function() {
'use strict';
angular.module('data-prep.services.utils')
/**
* @ngdoc object
* @name data-prep.services.utils.service:apiUrl
* @description The REST api base url
*/
.constant('apiUrl', 'http://10.42.10.99:8888')
/**
* @ngdoc object
* @name data-prep.services.utils.service:disableDebug
* @description Application option. Disable debug mode (ex: in production) for performance
*/
.constant('disableDebug', false);
})();
|
(function() {
'use strict';
angular.module('data-prep.services.utils')
/**
* @ngdoc object
* @name data-prep.services.utils.service:apiUrl
* @description The REST api base url
*/
.constant('apiUrl', 'http://10.42.10.99:8888') /* VM1 */
// .constant('apiUrl', 'http://10.42.40.91:8888') /* VINCENT */
//.constant('apiUrl', 'http://192.168.40.134:8888') /* MARC VM DOCKER */
/**
* @ngdoc object
* @name data-prep.services.utils.service:disableDebug
* @description Application option. Disable debug mode (ex: in production) for performance
*/
.constant('disableDebug', false);
})();
|
JavaScript
| 0.000001
|
fc45b842cdce2a3208ba3fd910d1eaed9bdde454
|
add jsdoc example to execution context
|
packages/execution-context/ExecutionContext.js
|
packages/execution-context/ExecutionContext.js
|
/**
* Executes arbitrary code asynchronously and concurrently.
* @example
* const executor = new ImmediateExecutor()
* const context = new ExecutionContext(executor);
* const result = context.execute(() => 'Hello, World!');
* result.then(message => console.log(message));
*/
export default class ExecutionContext {
/**
* @param {Executor} executor — an instance that handles code running
* @param {Number} concurrent — number of routines that can be executed at once
* @param {Boolean} manual — set to `true` if manual queue execution needed
*/
constructor(executor, concurrent = 1, manual = false) {
this.executor = executor;
this.concurrent = concurrent;
this.manual = manual;
this.queue = [];
this.current = Promise.resolve();
}
/**
* @param {Function} routine — arbitrary code to execute
* @return {Promise} — async result of executed routine
*/
execute(routine) {
return new Promise((resolve, reject) => {
this.queue.push({ routine, resolve, reject });
if (!this.manual && this.queue.length === 1) {
this.flush();
}
});
}
/**
* @return {Promise} — return a promise that is fulfilled when queue is empty
*/
flush() {
return this.current.then(() => {
const tasks = this.queue.splice(0, this.concurrent);
if (tasks.length > 0) {
this.current = this.executor.execute(batchTasks(tasks));
return this.queue.length === 0 || this.flush();
}
return false;
});
}
}
function batchTasks(tasks) {
return function batch() {
try {
for (var task of tasks) {
task.resolve(task.routine());
}
} catch (error) {
task.reject(error);
}
};
}
|
export default class ExecutionContext {
/**
* @param {Executor} executor — an instance that handles code running
* @param {Number} concurrent — number of routines that can be executed at once
* @param {Boolean} manual — set to `true` if manual queue execution needed
*/
constructor(executor, concurrent = 1, manual = false) {
this.executor = executor;
this.concurrent = concurrent;
this.manual = manual;
this.queue = [];
this.current = Promise.resolve();
}
/**
* @param {Function} routine — arbitrary code to execute
* @return {Promise} — async result of executed routine
*/
execute(routine) {
return new Promise((resolve, reject) => {
this.queue.push({ routine, resolve, reject });
if (!this.manual && this.queue.length === 1) {
this.flush();
}
});
}
/**
* @return {Promise} — return a promise that is fulfilled when queue is empty
*/
flush() {
return this.current.then(() => {
const tasks = this.queue.splice(0, this.concurrent);
if (tasks.length > 0) {
this.current = this.executor.execute(batchTasks(tasks));
return this.queue.length === 0 || this.flush();
}
return false;
});
}
}
function batchTasks(tasks) {
return function batch() {
try {
for (var task of tasks) {
task.resolve(task.routine());
}
} catch (error) {
task.reject(error);
}
};
}
|
JavaScript
| 0.000001
|
2a4ecd94bba80ae245976f4c724c0f52a98a32ab
|
Update comments
|
helpers/sortByMapping.js
|
helpers/sortByMapping.js
|
/* jslint node: true */
'use strict';
var _ = require( 'lodash' );
module.exports = function( dust ) {
/*
* @description Sorting method that orders a list of things based on a provided map
* @param {object} sortObject - Object to sort
* @param {string} map - Map to use to sort with
* @param {string} indexes - index structure of response to sort on
* @example {@_sortByMapping sortObject=packageRatesReply.packageRates indexes="links, hotelProducts, ids" map="PAUGLA, PAUFOR, PAUELM, PAUFAR"} {/_sortByMapping}
* At present their is no unit test coverage for this helper, this is being addressed by changing the structure of our helpers to ensure functions available outside scope of dust
*/
dust.helpers._sortByMapping = function( chunk, context, bodies, params ) {
// Object to sort
var sortObject = params.sortObject;
// Mapping to sort to the object to
var map = params.map;
// Index structure required for correct mapping
var keysParam = params.indexes.split(',');
var mappedObject = [];
var pickParameters = function( matchedobject, pickparams ) {
// Loop over the object to be sorted using the index structure provided from the tpl
for ( var i = 0; i < pickparams.length; i++ ) {
if ( !matchedobject ) return null;
matchedobject = matchedobject[pickparams[i]];
}
return matchedobject;
};
// Loop over the mapping order provided
_.forEach( map, function( id ) {
// Loop over the object to be sorted
_.forEach( sortObject, function( matchObject ) {
var requiredProduct = pickParameters( matchObject, keysParam );
// Is the value in the map array?
if ( _.include( id, requiredProduct ) ) {
// If it matches then push this object into the mappedObject
mappedObject.push( matchObject );
}
} );
} );
// Smush everything else we havn't already addedd into sortObject
sortObject = _.union( mappedObject, sortObject );
// Release - the wall didn't like me deleting this, hence null.
mappedObject = null;
_.forEach( sortObject, function( item ) {
chunk = chunk.render( bodies.block, context.push( item ) );
} );
return chunk;
};
};
|
/* jslint node: true */
'use strict';
var _ = require( 'lodash' );
module.exports = function( dust ) {
/*
* @description Sorting method that orders a list of things based on a provided map
* @param {object} sortObject - Object to sort
* @param {string} map - Map to use to sort with
* @param {string} indexes - index structure of response to sort on
* @example {@_sortByMapping sortObject=packageRatesReply.packageRates indexes="links, hotelProducts, ids" map="PAUGLA, PAUFOR, PAUELM, PAUFAR"} {/_sortByMapping}
*/
dust.helpers._sortByMapping = function( chunk, context, bodies, params ) {
// Object to sort
var sortObject = params.sortObject;
// Mapping to sort to the object to
var map = params.map;
// Index structure required for correct mapping
var keysParam = params.indexes.split(',');
var mappedObject = [];
var pickParameters = function( matchedobject, pickparams ) {
// Loop over the sort parameter structure provided from the tpl
for ( var i = 0; i < pickparams.length; i++ ) {
if ( !matchedobject ) return null;
matchedobject = matchedobject[pickparams[i]];
}
return matchedobject;
};
// Loop over the mapping order provided
_.forEach( map, function( id ) {
// Loop over the object to be sorted
_.forEach( sortObject, function( matchObject ) {
var requiredProduct = pickParameters( matchObject, keysParam );
// Is the value in the map array?
if ( _.include( id, requiredProduct ) ) {
// If it matches then push this object into the mappedObject
mappedObject.push( matchObject );
}
} );
} );
// Smush everything else we havn't already addedd into sortObject
sortObject = _.union( mappedObject, sortObject );
// Release - the wall didn't like me deleting this, hence null.
mappedObject = null;
_.forEach( sortObject, function( item ) {
chunk = chunk.render( bodies.block, context.push( item ) );
} );
return chunk;
};
};
|
JavaScript
| 0
|
933f9ad8a581679654e511879016d20ae2c895da
|
remove deprecated jQuery .ready() syntax (#2738)
|
resources/scripts/app.js
|
resources/scripts/app.js
|
/**
* External Dependencies
*/
import 'jquery';
$(() => {
// console.log('Hello world');
});
|
/**
* External Dependencies
*/
import 'jquery';
$(document).ready(() => {
// console.log('Hello world');
});
|
JavaScript
| 0.000001
|
8e9371e3d3259deea1a922d47686967bee54c00f
|
fix proptypes warning with router prop
|
src/views/SearchPictogramsView.js
|
src/views/SearchPictogramsView.js
|
import React, {Component, PropTypes} from 'react'
import { defineMessages, FormattedMessage } from 'react-intl'
import SearchBox from 'components/SearchBox.js'
import FilterPictograms from 'components/Filter/Filter'
import Toggle from 'material-ui/lib/toggle'
import { connect } from 'react-redux'
import { resetErrorMessage } from 'redux/modules/error'
import { loadKeywords } from 'redux/modules/keywords'
import { toggleShowFilter } from 'redux/modules/showFilter'
import { withRouter } from 'react-router'
const messages = defineMessages({
advancedSearch: {
id: 'searchPictograms.advancedSearch',
description: 'label for filtering Search',
defaultMessage: 'Advanced Search'
}
})
class SearchPictogramsView extends Component {
constructor(props) {
super(props)
this.handleDismissClick = this.handleDismissClick.bind(this)
this.renderErrorMessage = this.renderErrorMessage.bind(this)
this.handleChange = this.handleChange.bind(this)
}
/*
static defaultProps = {
showFilters: false
}
*/
handleDismissClick(e) {
this.props.resetErrorMessage()
e.preventDefault()
}
handleChange(nextValue) {
// not re-rendering, just the push?????
// browserHistory.push(`/pictograms/search/${nextValue}`)
// would need to configure router context:
// this.context.router.push(`/pictograms/search/${nextValue}`)
// starting in react 2.4 using HOC: https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.4.0.md
this.props.router.push(`/pictograms/search/${nextValue}`)
}
componentDidMount() {
this.props.loadKeywords(this.props.locale)
}
renderErrorMessage() {
const { errorMessage } = this.props
if (!errorMessage) {
return null
}
return (
<p style={{ backgroundColor: '#e99', padding: 10 }}>
<b>{errorMessage}</b>
{' '}
(<a href='#'
onClick={this.handleDismissClick}>
Dismiss
</a>)
</p>
)
}
render() {
const { children, searchText } = this.props
const {showFilter, filters} = this.props
const { keywords } = this.props.keywords
return (
<div>
<div className='row end-xs'>
<div className='col-xs-6 col-sm-4 col-md-3'>
<Toggle label={<FormattedMessage {...messages.advancedSearch} />} onToggle={this.props.toggleShowFilter} defaultToggled={showFilter} />
</div>
</div>
<div className='row start-xs'>
<SearchBox value={searchText} fullWidth={true} dataSource={keywords} onChange={this.handleChange} />
<hr />
<p>{this.props.searchText}</p>
{this.renderErrorMessage()}
</div>
{showFilter ? <FilterPictograms filter={filters} /> : null}
{children}
</div>
)
}
}
SearchPictogramsView.propTypes = {
// Injected by React Redux
errorMessage: PropTypes.string,
resetErrorMessage: PropTypes.func.isRequired,
toggleShowFilter: PropTypes.func.isRequired,
loadKeywords: PropTypes.func.isRequired,
searchText: PropTypes.string,
keywords: PropTypes.object,
showFilter: PropTypes.bool,
locale: PropTypes.string.isRequired,
filters: PropTypes.object.isRequired,
// Injected by React Router
children: PropTypes.node,
router: React.PropTypes.any.isRequired
}
const mapStateToProps = (state, ownProps) => {
const errorMessage = state.errorMessage
const { searchText } = ownProps.params
const { entities: { keywords } } = state
const {locale} = state
const {gui: {filters}} = state
const {gui: {showFilter}} = state
return {
errorMessage,
searchText,
// inputValue,
locale,
keywords: keywords[locale],
filters,
showFilter
}
}
export default connect(mapStateToProps, {resetErrorMessage, loadKeywords, toggleShowFilter})(withRouter(SearchPictogramsView))
|
import React, {Component, PropTypes} from 'react'
import { defineMessages, FormattedMessage } from 'react-intl'
import SearchBox from 'components/SearchBox.js'
import FilterPictograms from 'components/Filter/Filter'
import Toggle from 'material-ui/lib/toggle'
import { connect } from 'react-redux'
import { resetErrorMessage } from 'redux/modules/error'
import { loadKeywords } from 'redux/modules/keywords'
import { toggleShowFilter } from 'redux/modules/showFilter'
import { withRouter } from 'react-router'
const messages = defineMessages({
advancedSearch: {
id: 'searchPictograms.advancedSearch',
description: 'label for filtering Search',
defaultMessage: 'Advanced Search'
}
})
class SearchPictogramsView extends Component {
constructor(props) {
super(props)
this.handleDismissClick = this.handleDismissClick.bind(this)
this.renderErrorMessage = this.renderErrorMessage.bind(this)
this.handleChange = this.handleChange.bind(this)
}
/*
static defaultProps = {
showFilters: false
}
*/
handleDismissClick(e) {
this.props.resetErrorMessage()
e.preventDefault()
}
handleChange(nextValue) {
// not re-rendering, just the push?????
// browserHistory.push(`/pictograms/search/${nextValue}`)
// would need to configure router context:
// this.context.router.push(`/pictograms/search/${nextValue}`)
// starting in react 2.4 using a higher class:
this.props.router.push(`/pictograms/search/${nextValue}`)
}
componentDidMount() {
this.props.loadKeywords(this.props.locale)
}
renderErrorMessage() {
const { errorMessage } = this.props
if (!errorMessage) {
return null
}
return (
<p style={{ backgroundColor: '#e99', padding: 10 }}>
<b>{errorMessage}</b>
{' '}
(<a href='#'
onClick={this.handleDismissClick}>
Dismiss
</a>)
</p>
)
}
render() {
const { children, searchText } = this.props
const {showFilter, filters} = this.props
const { keywords } = this.props.keywords
return (
<div>
<div className='row end-xs'>
<div className='col-xs-6 col-sm-4 col-md-3'>
<Toggle label={<FormattedMessage {...messages.advancedSearch} />} onToggle={this.props.toggleShowFilter} defaultToggled={showFilter} />
</div>
</div>
<div className='row start-xs'>
<SearchBox value={searchText} fullWidth={true} dataSource={keywords} onChange={this.handleChange} />
<hr />
<p>{this.props.searchText}</p>
{this.renderErrorMessage()}
</div>
{showFilter ? <FilterPictograms filter={filters} /> : null}
{children}
</div>
)
}
}
SearchPictogramsView.propTypes = {
// Injected by React Redux
errorMessage: PropTypes.string,
resetErrorMessage: PropTypes.func.isRequired,
toggleShowFilter: PropTypes.func.isRequired,
loadKeywords: PropTypes.func.isRequired,
searchText: PropTypes.string,
keywords: PropTypes.object,
showFilter: PropTypes.bool,
locale: PropTypes.string.isRequired,
filters: PropTypes.object.isRequired,
// Injected by React Router
children: PropTypes.node
}
const mapStateToProps = (state, ownProps) => {
const errorMessage = state.errorMessage
const { searchText } = ownProps.params
const { entities: { keywords } } = state
const {locale} = state
const {gui: {filters}} = state
const {gui: {showFilter}} = state
return {
errorMessage,
searchText,
// inputValue,
locale,
keywords: keywords[locale],
filters,
showFilter
}
}
export default connect(mapStateToProps, {resetErrorMessage, loadKeywords, toggleShowFilter})(withRouter(SearchPictogramsView))
|
JavaScript
| 0
|
08b359d6f8d3627efe88688ba57c2acd040bff37
|
change cursor style for datepicker
|
packages/tocco-ui/src/DatePicker/DatePicker.js
|
packages/tocco-ui/src/DatePicker/DatePicker.js
|
import React, {useRef} from 'react'
import PropTypes from 'prop-types'
import {injectIntl, intlShape} from 'react-intl'
import styled, {withTheme} from 'styled-components'
import {theme} from '../utilStyles'
import {useDatePickr} from './useDatePickr'
const WrapperStyle = styled.div`
cursor: pointer;
.flatpickr-calendar.open {
top: auto !important;
}
`
export const DatePicker = props => {
const {value, children, intl, onChange} = props
const wrapperElement = useRef(null)
const locale = intl.locale
const fontFamily = theme.fontFamily('regular')(props)
useDatePickr(wrapperElement, {value, onChange, fontFamily, locale})
return (
<WrapperStyle
data-wrap
ref={wrapperElement}
>
<div data-toggle>
<input
style={{display: 'none'}}
type="text"
data-input
/>
{children}
</div>
</WrapperStyle>
)
}
DatePicker.propTypes = {
/**
* Any content to wrap a onclick around to open a calendar
*/
children: PropTypes.node.isRequired,
/**
* Function triggered on every date selection. First parameter is the picked date as iso string.
*/
onChange: PropTypes.func.isRequired,
/**
* To set the selected date from outside the component.
*/
value: PropTypes.any,
intl: intlShape.isRequired
}
export default withTheme(injectIntl(DatePicker))
|
import React, {useRef} from 'react'
import PropTypes from 'prop-types'
import {injectIntl, intlShape} from 'react-intl'
import styled, {withTheme} from 'styled-components'
import {theme} from '../utilStyles'
import {useDatePickr} from './useDatePickr'
const WrapperStyle = styled.div`
.flatpickr-calendar.open {
top: auto !important;
}
`
export const DatePicker = props => {
const {value, children, intl, onChange} = props
const wrapperElement = useRef(null)
const locale = intl.locale
const fontFamily = theme.fontFamily('regular')(props)
useDatePickr(wrapperElement, {value, onChange, fontFamily, locale})
return (
<WrapperStyle
data-wrap
ref={wrapperElement}
>
<div data-toggle>
<input
style={{display: 'none'}}
type="text"
data-input
/>
{children}
</div>
</WrapperStyle>
)
}
DatePicker.propTypes = {
/**
* Any content to wrap a onclick around to open a calendar
*/
children: PropTypes.node.isRequired,
/**
* Function triggered on every date selection. First parameter is the picked date as iso string.
*/
onChange: PropTypes.func.isRequired,
/**
* To set the selected date from outside the component.
*/
value: PropTypes.any,
intl: intlShape.isRequired
}
export default withTheme(injectIntl(DatePicker))
|
JavaScript
| 0
|
5d49b0f41a9033089cbd8542018bd658a4c47cd3
|
isNumber move isNaN
|
is-number.js
|
is-number.js
|
/**
* @module 101/is-number
*/
/**
* Functional version of val typeof 'number'
* @function module:101/is-number
* @param {*} val - value checked to be a string
* @return {boolean} Whether the value is an string or not
*/
module.exports = isNumber;
function isNumber (val) {
return (typeof val === 'number' || val instanceof Number) && !isNaN(val)
}
|
/**
* @module 101/is-number
*/
/**
* Functional version of val typeof 'number'
* @function module:101/is-number
* @param {*} val - value checked to be a string
* @return {boolean} Whether the value is an string or not
*/
module.exports = isNumber;
function isNumber (val) {
return !isNaN(val) && (typeof val === 'number' || val instanceof Number);
}
|
JavaScript
| 0.999927
|
4028b6beb4cd6b6f1a5bb66042f2777e54089519
|
Replace Meteor.clearInterval with just clearInterval
|
imports/api/reports/reports.test.js
|
imports/api/reports/reports.test.js
|
/* eslint-env mocha */
import Reports from './reports.js';
import Elements from '../elements/elements.js';
import Measures from '../measures/measures.js';
import { Meteor } from 'meteor/meteor';
import { resetDatabase } from 'meteor/xolvio:cleaner';
describe('Reports', () => {
if (Meteor.isClient) return;
describe('collection', () => {
it('should have the collection typical functions', () => {
Reports.collection.find.should.be.a('function');
});
});
describe('add', () => {
let reportId;
before(() => {
resetDatabase();
reportId = Reports.add();
});
it('creates a new report', () => {
Reports.collection.find(reportId).count().should.equal(1);
});
});
describe('remove', () => {
let reportId;
before(() => {
resetDatabase();
reportId = Reports.add();
Reports.remove(reportId);
});
it('removes the report', () => {
Reports.collection.find(reportId).count().should.equal(0);
});
});
describe('addToTable', () => {
let reportId;
before(() => {
reportId = Reports.add();
});
describe('with a measure', () => {
before(() => {
const measureId = Measures.add();
Reports.addToTable(reportId, 'measure', measureId);
});
it('adds the measure to the report', () => {
Reports.collection.findOne(reportId).measures.length.should.equal(1);
});
});
describe('with an element', () => {
before(() => {
const elementId = Elements.add(undefined, 'dimension');
Elements.characteristics.add(elementId, '2016');
Reports.addToTable(reportId, 'element', elementId);
});
it('adds the element to the report', () => {
Reports.collection.findOne(reportId).elements.length.should.equal(1);
});
it('with its characteristics', () => {
const report = Reports.collection.findOne(reportId);
report.elements[0].favCharacteristicIds.length.should.equal(1);
});
});
});
describe('toggleCharacteristic', () => {
let reportId;
let elementId;
let characteristicId;
before(() => {
reportId = Reports.add();
elementId = Elements.add(undefined, 'dimension');
characteristicId = Elements.characteristics.add(elementId, '2016');
Reports.addToTable(reportId, 'element', elementId);
Meteor.call('Reports.toggleCharacteristic', reportId, elementId, characteristicId, true);
});
before((done) => {
const interval = Meteor.setInterval(() => {
if (Reports.collection.findOne(reportId)) {
clearInterval(interval);
done();
}
});
});
it('removes the characteristic from the report element', () => {
const report = Reports.collection.findOne(reportId);
const element = report.elements.find((elem) => elem._id === elementId);
element.favCharacteristicIds.indexOf(characteristicId).should.equal(-1);
});
});
describe('elements.swap', () => {
let reportId;
let elementOneId;
let elementTwoId;
before(() => {
reportId = Reports.add();
elementOneId = Elements.add(undefined, 'dimension');
Reports.addToTable(reportId, 'element', elementOneId);
elementTwoId = Elements.add(undefined, 'referenceObject');
Reports.addToTable(reportId, 'element', elementTwoId);
Reports.elements.swap(reportId, elementOneId, elementTwoId);
});
it('switches two elements', () => {
const report = Reports.collection.findOne(reportId);
report.elements.findIndex((element) => element._id === elementOneId).should.equal(1);
report.elements.findIndex((element) => element._id === elementTwoId).should.equal(0);
});
});
});
|
/* eslint-env mocha */
import Reports from './reports.js';
import Elements from '../elements/elements.js';
import Measures from '../measures/measures.js';
import { Meteor } from 'meteor/meteor';
import { resetDatabase } from 'meteor/xolvio:cleaner';
describe('Reports', () => {
if (Meteor.isClient) return;
describe('collection', () => {
it('should have the collection typical functions', () => {
Reports.collection.find.should.be.a('function');
});
});
describe('add', () => {
let reportId;
before(() => {
resetDatabase();
reportId = Reports.add();
});
it('creates a new report', () => {
Reports.collection.find(reportId).count().should.equal(1);
});
});
describe('remove', () => {
let reportId;
before(() => {
resetDatabase();
reportId = Reports.add();
Reports.remove(reportId);
});
it('removes the report', () => {
Reports.collection.find(reportId).count().should.equal(0);
});
});
describe('addToTable', () => {
let reportId;
before(() => {
reportId = Reports.add();
});
describe('with a measure', () => {
before(() => {
const measureId = Measures.add();
Reports.addToTable(reportId, 'measure', measureId);
});
it('adds the measure to the report', () => {
Reports.collection.findOne(reportId).measures.length.should.equal(1);
});
});
describe('with an element', () => {
before(() => {
const elementId = Elements.add(undefined, 'dimension');
Elements.characteristics.add(elementId, '2016');
Reports.addToTable(reportId, 'element', elementId);
});
it('adds the element to the report', () => {
Reports.collection.findOne(reportId).elements.length.should.equal(1);
});
it('with its characteristics', () => {
const report = Reports.collection.findOne(reportId);
report.elements[0].favCharacteristicIds.length.should.equal(1);
});
});
});
describe('toggleCharacteristic', () => {
let reportId;
let elementId;
let characteristicId;
before(() => {
reportId = Reports.add();
elementId = Elements.add(undefined, 'dimension');
characteristicId = Elements.characteristics.add(elementId, '2016');
Reports.addToTable(reportId, 'element', elementId);
Meteor.call('Reports.toggleCharacteristic', reportId, elementId, characteristicId, true);
});
before((done) => {
const interval = Meteor.setInterval(() => {
if (Reports.collection.findOne(reportId)) {
Meteor.clearInterval(interval);
done();
}
});
});
it('removes the characteristic from the report element', () => {
const report = Reports.collection.findOne(reportId);
const element = report.elements.find((elem) => elem._id === elementId);
element.favCharacteristicIds.indexOf(characteristicId).should.equal(-1);
});
});
describe('elements.swap', () => {
let reportId;
let elementOneId;
let elementTwoId;
before(() => {
reportId = Reports.add();
elementOneId = Elements.add(undefined, 'dimension');
Reports.addToTable(reportId, 'element', elementOneId);
elementTwoId = Elements.add(undefined, 'referenceObject');
Reports.addToTable(reportId, 'element', elementTwoId);
Reports.elements.swap(reportId, elementOneId, elementTwoId);
});
it('switches two elements', () => {
const report = Reports.collection.findOne(reportId);
report.elements.findIndex((element) => element._id === elementOneId).should.equal(1);
report.elements.findIndex((element) => element._id === elementTwoId).should.equal(0);
});
});
});
|
JavaScript
| 0.000526
|
bc0ca5f76958c49a84807fa61620f04ca4bcee3d
|
Fix rendering of avatars for some Gravatar users.
|
static/js/read_receipts.js
|
static/js/read_receipts.js
|
import $ from "jquery";
import SimpleBar from "simplebar";
import render_read_receipts from "../templates/read_receipts.hbs";
import render_read_receipts_modal from "../templates/read_receipts_modal.hbs";
import * as channel from "./channel";
import {$t} from "./i18n";
import * as loading from "./loading";
import * as overlays from "./overlays";
import * as people from "./people";
import * as popovers from "./popovers";
import * as ui_report from "./ui_report";
export function show_user_list(message_id) {
$("body").append(render_read_receipts_modal());
overlays.open_modal("read_receipts_modal", {
autoremove: true,
on_show: () => {
loading.make_indicator($("#read_receipts_modal .loading_indicator"));
channel.get({
url: `/json/messages/${message_id}/read_receipts`,
idempotent: true,
success(data) {
const users = data.user_ids.map((id) => {
const user = people.get_by_user_id(id);
return {
user_id: user.user_id,
full_name: user.full_name,
avatar_url: people.small_avatar_url_for_person(user),
};
});
users.sort(people.compare_by_name);
loading.destroy_indicator($("#read_receipts_modal .loading_indicator"));
if (users.length === 0) {
$("#read_receipts_modal .read_receipts_info").text(
$t({defaultMessage: "No one has read this message yet."}),
);
} else {
$("#read_receipts_modal .read_receipts_info").text(
$t(
{
defaultMessage:
"This message has been read by {num_of_people} people:",
},
{num_of_people: users.length},
),
);
$("#read_receipts_modal .modal__container").addClass(
"showing_read_receipts_list",
);
$("#read_receipts_modal .modal__content").append(
render_read_receipts({users}),
);
new SimpleBar($("#read_receipts_modal .modal__content")[0]);
}
},
error(xhr) {
ui_report.error("", xhr, $("#read_receipts_error"));
loading.destroy_indicator($("#read_receipts_modal .loading_indicator"));
},
});
},
on_hide: () => {
// Ensure any user info popovers are closed
popovers.hide_all();
},
});
}
|
import $ from "jquery";
import SimpleBar from "simplebar";
import render_read_receipts from "../templates/read_receipts.hbs";
import render_read_receipts_modal from "../templates/read_receipts_modal.hbs";
import * as channel from "./channel";
import {$t} from "./i18n";
import * as loading from "./loading";
import * as overlays from "./overlays";
import * as people from "./people";
import * as popovers from "./popovers";
import * as ui_report from "./ui_report";
export function show_user_list(message_id) {
$("body").append(render_read_receipts_modal());
overlays.open_modal("read_receipts_modal", {
autoremove: true,
on_show: () => {
loading.make_indicator($("#read_receipts_modal .loading_indicator"));
channel.get({
url: `/json/messages/${message_id}/read_receipts`,
idempotent: true,
success(data) {
const users = data.user_ids.map((id) => people.get_by_user_id(id));
users.sort(people.compare_by_name);
loading.destroy_indicator($("#read_receipts_modal .loading_indicator"));
if (users.length === 0) {
$("#read_receipts_modal .read_receipts_info").text(
$t({defaultMessage: "No one has read this message yet."}),
);
} else {
$("#read_receipts_modal .read_receipts_info").text(
$t(
{
defaultMessage:
"This message has been read by {num_of_people} people:",
},
{num_of_people: users.length},
),
);
$("#read_receipts_modal .modal__container").addClass(
"showing_read_receipts_list",
);
$("#read_receipts_modal .modal__content").append(
render_read_receipts({users}),
);
new SimpleBar($("#read_receipts_modal .modal__content")[0]);
}
},
error(xhr) {
ui_report.error("", xhr, $("#read_receipts_error"));
loading.destroy_indicator($("#read_receipts_modal .loading_indicator"));
},
});
},
on_hide: () => {
// Ensure any user info popovers are closed
popovers.hide_all();
},
});
}
|
JavaScript
| 0
|
4ec67654d334d3a7c88ec16d0530cfae012f27b1
|
add disable and enable for feedback button when sent (#258)
|
static/scripts/loggedin.js
|
static/scripts/loggedin.js
|
$(document).ready(function () {
var $modals = $('.modal');
var $feedbackModal = $('.feedback-modal');
var $modalForm = $('.modal-form');
function showAJAXError(req, textStatus, errorThrown) {
$feedbackModal.modal('hide');
if(textStatus==="timeout") {
$.showNotification("Zeitüberschreitung der Anfrage", "warn", true);
} else {
$.showNotification(errorThrown, "danger", true);
}
}
function showAJAXSuccess(message) {
$feedbackModal.modal('hide');
$.showNotification(message, "success", true);
}
/**
* creates the feedback-message which will be sent to the Schul-Cloud helpdesk
* @param modal {object} - modal containing content from feedback-form
*/
const createFeedbackMessage = function(modal) {
return "Als " + modal.find('#role').val() + "\n" +
"möchte ich " + modal.find('#desire').val() + ",\n" +
"um " + modal.find("#benefit").val() + ".\n" +
"Akzeptanzkriterien: " + modal.find("#acceptance_criteria").val();
};
const sendFeedback = function (modal, e) {
e.preventDefault();
var email= '[email protected]';
var subject = 'Feedback';
var content = { text: createFeedbackMessage(modal)};
$.ajax({
url: '/helpdesk',
type: 'POST',
data: {
email: email,
modalEmail: modal.find('#email').val(),
subject: subject,
content: content
},
success: function(result) {
showAJAXSuccess("Feedback erfolgreich versendet!")
},
error: showAJAXError
});
$('.feedback-modal').find('.btn-submit').prop("disabled", true);
};
$('.submit-helpdesk').on('click', function (e) {
e.preventDefault();
$('.feedback-modal').find('.btn-submit').prop("disabled", false);
var title = $(document).find("title").text();
var area = title.slice(0, title.indexOf('- Schul-Cloud') === -1 ? title.length : title.indexOf('- Schul-Cloud'));
populateModalForm($feedbackModal, {
title: 'Feedback',
closeLabel: 'Schließen',
submitLabel: 'Senden'
});
$feedbackModal.find('.modal-form').on('submit', sendFeedback.bind(this, $feedbackModal));
$feedbackModal.modal('show');
$feedbackModal.find('#title-area').html(area);
});
$modals.find('.close, .btn-close').on('click', function () {
$modals.modal('hide');
});
$('.notification-dropdown-toggle').on('click', function () {
$(this).removeClass('recent');
$('.notification-dropdown .notification-item.unread').each(function() {
if($(this).data('read') == true) return;
sendShownCallback({notificationId: $(this).data('notification-id')});
sendReadCallback($(this).data('notification-id'));
$(this).data('read', true);
});
});
});
|
$(document).ready(function () {
var $modals = $('.modal');
var $feedbackModal = $('.feedback-modal');
var $modalForm = $('.modal-form');
function showAJAXError(req, textStatus, errorThrown) {
$feedbackModal.modal('hide');
if(textStatus==="timeout") {
$.showNotification("Zeitüberschreitung der Anfrage", "warn", true);
} else {
$.showNotification(errorThrown, "danger", true);
}
}
function showAJAXSuccess(message) {
$feedbackModal.modal('hide');
$.showNotification(message, "success", true);
}
/**
* creates the feedback-message which will be sent to the Schul-Cloud helpdesk
* @param modal {object} - modal containing content from feedback-form
*/
const createFeedbackMessage = function(modal) {
return "Als " + modal.find('#role').val() + "\n" +
"möchte ich " + modal.find('#desire').val() + ",\n" +
"um " + modal.find("#benefit").val() + ".\n" +
"Akzeptanzkriterien: " + modal.find("#acceptance_criteria").val();
};
const sendFeedback = function (modal, e) {
e.preventDefault();
var email= '[email protected]';
var subject = 'Feedback';
var content = { text: createFeedbackMessage(modal)};
$.ajax({
url: '/helpdesk',
type: 'POST',
data: {
email: email,
modalEmail: modal.find('#email').val(),
subject: subject,
content: content
},
success: function(result) {
showAJAXSuccess("Feedback erfolgreich versendet!")
},
error: showAJAXError
});
};
$('.submit-helpdesk').on('click', function (e) {
e.preventDefault();
var title = $(document).find("title").text();
var area = title.slice(0, title.indexOf('- Schul-Cloud') === -1 ? title.length : title.indexOf('- Schul-Cloud'));
populateModalForm($feedbackModal, {
title: 'Feedback',
closeLabel: 'Schließen',
submitLabel: 'Senden'
});
$feedbackModal.find('.modal-form').on('submit', sendFeedback.bind(this, $feedbackModal));
$feedbackModal.modal('show');
$feedbackModal.find('#title-area').html(area);
});
$modals.find('.close, .btn-close').on('click', function () {
$modals.modal('hide');
});
$('.notification-dropdown-toggle').on('click', function () {
$(this).removeClass('recent');
$('.notification-dropdown .notification-item.unread').each(function() {
if($(this).data('read') == true) return;
sendShownCallback({notificationId: $(this).data('notification-id')});
sendReadCallback($(this).data('notification-id'));
$(this).data('read', true);
});
});
});
|
JavaScript
| 0
|
a0358e9f5f168a31667098066a582b743e75185f
|
Remove stale page reloads
|
www/js/setup.js
|
www/js/setup.js
|
(function() {
var options;
try {
options = JSON.parse(localStorage.options);
}
catch (e) {}
// Set the theme
var mediaURL = config.MEDIA_URL;
var theme = (options && options.theme) ? options.theme
: hotConfig.DEFAULT_CSS;
document.getElementById('theme').href = mediaURL + 'css/' + theme
+ '.css?v=' + cssHash;
})();
|
(function() {
// Prevent from loading stale pages on browser state resume
if (Date.now() - renderTime >= 3600000)
return location.reload(true);
var options;
try {
options = JSON.parse(localStorage.options);
}
catch (e) {}
// Set the theme
var mediaURL = config.MEDIA_URL;
var theme = (options && options.theme) ? options.theme
: hotConfig.DEFAULT_CSS;
document.getElementById('theme').href = mediaURL + 'css/' + theme
+ '.css?v=' + cssHash;
})();
|
JavaScript
| 0.000001
|
7834f37f895e3ce0a38b5b7ef913d8d4ce02e217
|
Remove redundant test (#472)
|
src/helpers/reverse-publication-test.js
|
src/helpers/reverse-publication-test.js
|
// @flow
const reversePublication = require('./reverse-publication.js')
const { expect } = require('chai')
describe('reversePublication', function () {
it('applies the given path mapping', function () {
const publications = [
{ localPath: '/content/', publicPath: '/', publicExtension: '' }
]
const actual = reversePublication('/1.md', publications)
expect(actual).to.equal('/content/1.md')
})
it('adds leading slashes to the link', function () {
const publications = [
{ localPath: '/content/', publicPath: '/', publicExtension: '' }
]
const actual = reversePublication('1.md', publications)
expect(actual).to.equal('/content/1.md')
})
it('applies the extension mapping in url-friendly cases', function () {
const publications = [
{
localPath: '/content/',
publicPath: '/',
publicExtension: ''
}
]
const actual = reversePublication('1', publications)
expect(actual).to.equal('/content/1.md')
})
it('applies the extension mapping in HTML cases', function () {
const publications = [
{
localPath: '/content/',
publicPath: '/',
publicExtension: '.html'
}
]
const actual = reversePublication('1.html', publications)
expect(actual).to.equal('/content/1.md')
})
it('works with empty publications', function () {
expect(reversePublication('1.md', [])).to.equal('/1.md')
})
})
|
// @flow
const reversePublication = require('./reverse-publication.js')
const { expect } = require('chai')
describe('reversePublication', function () {
it('applies the given path mapping', function () {
const publications = [
{ localPath: '/content/', publicPath: '/', publicExtension: '' }
]
const actual = reversePublication('/1.md', publications)
expect(actual).to.equal('/content/1.md')
})
it('applies the given path mapping', function () {
const publications = [
{ localPath: '/content/', publicPath: '/', publicExtension: '' }
]
const actual = reversePublication('/1.md', publications)
expect(actual).to.equal('/content/1.md')
})
it('adds leading slashes to the link', function () {
const publications = [
{ localPath: '/content/', publicPath: '/', publicExtension: '' }
]
const actual = reversePublication('1.md', publications)
expect(actual).to.equal('/content/1.md')
})
it('applies the extension mapping in url-friendly cases', function () {
const publications = [
{
localPath: '/content/',
publicPath: '/',
publicExtension: ''
}
]
const actual = reversePublication('1', publications)
expect(actual).to.equal('/content/1.md')
})
it('applies the extension mapping in HTML cases', function () {
const publications = [
{
localPath: '/content/',
publicPath: '/',
publicExtension: '.html'
}
]
const actual = reversePublication('1.html', publications)
expect(actual).to.equal('/content/1.md')
})
it('works with empty publications', function () {
expect(reversePublication('1.md', [])).to.equal('/1.md')
})
})
|
JavaScript
| 0.000009
|
fc1e485f59049fc941c4d8f195df20449e8af441
|
remove @charset warning when compiling scss
|
vite.config.js
|
vite.config.js
|
import path from 'path';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueI18n from '@intlify/vite-plugin-vue-i18n';
import autoprefixer from 'autoprefixer';
export default defineConfig({
plugins: [
vue(),
vueI18n({
include: path.resolve(__dirname, './src/i18n/**'),
}),
],
css: {
postcss: {
plugins: [autoprefixer],
},
preprocessorOptions: {
scss: {
charset: false,
},
},
},
});
|
import path from 'path';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueI18n from '@intlify/vite-plugin-vue-i18n';
import autoprefixer from 'autoprefixer';
export default defineConfig({
plugins: [
vue(),
vueI18n({
include: path.resolve(__dirname, './src/i18n/**'),
}),
],
css: {
postcss: {
plugins: [autoprefixer],
},
},
});
|
JavaScript
| 0
|
015580e353c839a6d7455f05c35340778ed6d104
|
format try catch block more nicely
|
src/client/xhr.js
|
src/client/xhr.js
|
import * as storage from './storage';
import AuthService from './auth/authService';
function setAuthHeader(req) {
const jwtToken = storage.load(storage.ids.ID_TOKEN);
if (jwtToken) {
req.setRequestHeader('Authorization', `Bearer ${jwtToken}`);
}
}
function wrapXhrPromise(path, method, data, contentType) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.addEventListener('load', () => {
if (request.status === 200) {
const { response } = request;
try {
resolve(JSON.parse(response));
} catch (e) {
resolve(response);
}
} else if (request.status === 401) {
AuthService.logout();
window.location.assign('/login');
} else {
const { response } = request;
try {
reject(JSON.parse(response));
} catch (e) {
reject(response);
}
}
});
request.addEventListener('error', () => {
reject();
});
request.open(method, path);
setAuthHeader(request);
if (contentType) {
request.setRequestHeader('Content-Type', contentType);
}
request.send(data);
});
}
function multipartRequest(path, method, data) {
return wrapXhrPromise(path, method, data);
}
function jsonRequest(path, method, data) {
return wrapXhrPromise(path, method, JSON.stringify(data), 'application/json');
}
export default {
get(path) {
return wrapXhrPromise(path, 'GET');
},
post(path, data, contentType) {
return jsonRequest(path, 'POST', data, contentType);
},
postMultipart(path, multipartData) {
return multipartRequest(path, 'POST', multipartData);
},
put(path, data) {
return jsonRequest(path, 'PUT', data);
},
deleteHttp(path) {
return wrapXhrPromise(path, 'DELETE');
},
};
|
import * as storage from './storage';
import AuthService from './auth/authService';
function setAuthHeader(req) {
const jwtToken = storage.load(storage.ids.ID_TOKEN);
if (jwtToken) {
req.setRequestHeader('Authorization', `Bearer ${jwtToken}`);
}
}
function wrapXhrPromise(path, method, data, contentType) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.addEventListener('load', () => {
if (request.status === 200) {
let { response } = request;
try {
response = JSON.parse(response);
} catch (e) { /* Nothing to do when no JSON returned */ }
resolve(response);
} else if (request.status === 401) {
AuthService.logout();
window.location.assign('/login');
} else {
const { response } = request;
try {
reject(JSON.parse(response));
} catch (e) {
reject(response);
}
}
});
request.addEventListener('error', () => {
reject();
});
request.open(method, path);
setAuthHeader(request);
if (contentType) {
request.setRequestHeader('Content-Type', contentType);
}
request.send(data);
});
}
function multipartRequest(path, method, data) {
return wrapXhrPromise(path, method, data);
}
function jsonRequest(path, method, data) {
return wrapXhrPromise(path, method, JSON.stringify(data), 'application/json');
}
export default {
get(path) {
return wrapXhrPromise(path, 'GET');
},
post(path, data, contentType) {
return jsonRequest(path, 'POST', data, contentType);
},
postMultipart(path, multipartData) {
return multipartRequest(path, 'POST', multipartData);
},
put(path, data) {
return jsonRequest(path, 'PUT', data);
},
deleteHttp(path) {
return wrapXhrPromise(path, 'DELETE');
},
};
|
JavaScript
| 0
|
1c2ca5f8701abbd0a70fb5ec40fd3005c6015788
|
fix config and overrides
|
src/lib/config.js
|
src/lib/config.js
|
/*
*
* Description:
* Configuration file for dashboard
*
*/
var nconf = require('nconf');
var argv = require('optimist').argv;
var fs = require('fs');
var configDir = '/etc/';
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir)
}
nconf.arg().env('__'); //Also look for overrides in environment settings
// Will essentially rewrite the file when a change to the defaults are made if there is a parsing error.
try {
nconf.use('file', { file: configDir + 'dashboardconfig.json' });
} catch (err) {
console.log('Unable to load the configuration file, resetting to defaults');
console.log(err);
}
// Do not change these values in this file for an individual ROV, use the ./etc/rovconfig.json instead
nconf.defaults({
port: 80,
proxy: undefined,
aws: { bucket: 'openrov-deb-repository', region: 'us-west-2'},
aptGetSourcelists : '/etc/apt/sources.list.d'
});
function savePreferences() {
nconf.save(function (err) {
if (err) {
console.error(err.message);
return;
}
console.log('Configuration saved successfully.');
});
}
module.exports = {
port: process.env.PORT || argv.port || nconf.get('port'),
proxy: argv.proxy || nconf.get('proxy'),
aws: nconf.get('aws'),
aptGetSourcelists : argv['source-list-dir'] || nconf.get('aptGetSourcelists'),
DashboardEnginePath : './lib/DashboardEngine' + (process.env.USE_MOCK === 'true' ? '-mock' : ''),
preferences: nconf,
savePreferences: savePreferences
};
|
/*
*
* Description:
* Configuration file for dashboard
*
*/
var nconf = require('nconf');
var argv = require('optimist').argv;
var fs = require('fs');
var configDir = './etc/';
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir)
}
// Will essentially rewrite the file when a change to the defaults are made if there is a parsing error.
try {
nconf.use('file', { file: configDir + 'dashboardconfig.json' });
} catch (err) {
console.log('Unable to load the configuration file, resetting to defaults');
console.log(err);
}
nconf.env(); //Also look for overrides in environment settings
// Do not change these values in this file for an individual ROV, use the ./etc/rovconfig.json instead
nconf.defaults({
port: 80,
proxy: undefined,
aws: { bucket: 'openrov-deb-repository', region: 'us-west-2'},
aptGetSourcelists : '/etc/apt/sources.list.d'
});
function savePreferences() {
nconf.save(function (err) {
if (err) {
console.error(err.message);
return;
}
console.log('Configuration saved successfully.');
});
}
module.exports = {
port: process.env.PORT || argv.port || nconf.get('port'),
proxy: argv.proxy || nconf.get('proxy'),
aws: nconf.get('aws'),
aptGetSourcelists : argv['source-list-dir'] || nconf.get('aptGetSourcelists'),
DashboardEnginePath : './lib/DashboardEngine' + (process.env.USE_MOCK === 'true' ? '-mock' : ''),
preferences: nconf,
savePreferences: savePreferences
};
|
JavaScript
| 0
|
bc1953bd23e8726a9c7af20963087f450003b769
|
fix weird bug in getHistory
|
src/omnistream.js
|
src/omnistream.js
|
const Rx = require('rxjs/Rx');
class Omnistream {
// Instatiates a new stream to manage state for the application
constructor() {
this.stream = new Rx.BehaviorSubject();
// Creates an array to hold all actions dispatched within an application.
// This feature allows for time travel debugging in O(n) space.
this.history = [];
this.history$ = this.getHistory();
this.store = { 'omniHistory$': this.history$ };
}
// Creates a state-stream with provided reducer and action stream
createStatestream(reducer, actionStream) {
return actionStream(this)
.merge(this.stream.filter(value => value ? value._clearState : false))
.startWith(reducer(undefined, { type: null }))
.scan((acc, curr) => (
curr._clearState ? reducer(undefined, { type: null }) : reducer(acc, curr)
))
}
_createTimelineStatestream(reducer, actionStream) {
return actionStream(this)
.merge(this.stream.filter(value => value ? value._clearState : false))
.startWith(reducer(undefined, { type: null }))
.scan(reducer)
}
// Creates a collection of all state-streams
createStore(streamCollection) {
this.store = streamCollection;
}
addToStore(streamCollection) {
this.store = Object.assign({}, this.store, streamCollection);
}
// Check whether each action dispatched has data and type properties.
// If so, pass the action to the superstream.
dispatch(action) {
if (!(action.hasOwnProperty('type') && !(action._clearState))) {
throw new Error('Actions dispatched to superstream must be objects with type properties')
}
this.stream.next(action);
}
// Dispatch an observable to the superstream
dispatchObservableFn(streamFunction) {
const sideEffectStream = streamFunction(this.stream.filter(action => action).skip(1));
sideEffectStream.subscribe((action) => {
this.dispatch(action);
})
}
// Store a reference to every action type that passes through the stream.
recordActionTypes() {
this.actionStream = this.stream.filter(action => action).map(action => action.type)
this.actionStream.subscribe(type => this.setOfAllActionTypes[type] = true);
}
// Create an observable of data for a specific action type.
filterForActionTypes(...actionTypes) {
const actions = Array.isArray(actionTypes[0]) ? actionTypes[0] : actionTypes;
const hash = actions.reduce((acc, curr) => Object.assign(acc, { [curr]: true }), {});
return this.stream.filter(action => {
return action ? (hash[action.type]) : false
})
}
// Create an observable that updates history when a new action is received.
getHistory() {
const history$ = this.stream.filter(action => action && !action._ignore)
.scan((acc, cur) => {
acc.push(cur);
return acc;
}, [])
.publish()
history$.connect();
history$.subscribe(el => this.history = el)
return history$
}
// Revert the app back to its original state
clearState() {
this.stream.next({ _clearState: true, _ignore: true });
}
timeTravelToPointN(n) {
this.clearState();
for (let i = 0; i <= n; i++) {
this.dispatch(Object.assign({ _ignore: true }, this.history[i]));
}
}
}
export default function createOmnistream() {
return new Omnistream();
}
|
const Rx = require('rxjs/Rx');
class Omnistream {
// Instatiates a new stream to manage state for the application
constructor() {
this.stream = new Rx.BehaviorSubject();
// Creates an array to hold all actions dispatched within an application.
// This feature allows for time travel debugging in O(n) space.
this.history = [];
this.history$ = this.getHistory();
this.store = { 'omniHistory$': this.history$ };
}
// Creates a state-stream with provided reducer and action stream
createStatestream(reducer, actionStream) {
return actionStream(this)
.merge(this.stream.filter(value => value ? value._clearState : false))
.startWith(reducer(undefined, { type: null }))
.scan((acc, curr) => (
curr._clearState ? reducer(undefined, { type: null }) : reducer(acc, curr)
))
}
_createTimelineStatestream(reducer, actionStream) {
return actionStream(this)
.merge(this.stream.filter(value => value ? value._clearState : false))
.startWith(reducer(undefined, { type: null }))
.scan(reducer)
}
// Creates a collection of all state-streams
createStore(streamCollection) {
this.store = streamCollection;
}
addToStore(streamCollection) {
this.store = Object.assign({}, this.store, streamCollection);
}
// Check whether each action dispatched has data and type properties.
// If so, pass the action to the superstream.
dispatch(action) {
if (!(action.hasOwnProperty('type') && !(action._clearState))) {
throw new Error('Actions dispatched to superstream must be objects with type properties')
}
this.stream.next(action);
}
// Dispatch an observable to the superstream
dispatchObservableFn(streamFunction) {
const sideEffectStream = streamFunction(this.stream.filter(action => action).skip(1));
sideEffectStream.subscribe((action) => {
this.dispatch(action);
})
}
// Store a reference to every action type that passes through the stream.
recordActionTypes() {
this.actionStream = this.stream.filter(action => action).map(action => action.type)
this.actionStream.subscribe(type => this.setOfAllActionTypes[type] = true);
}
// Create an observable of data for a specific action type.
filterForActionTypes(...actionTypes) {
const actions = Array.isArray(actionTypes[0]) ? actionTypes[0] : actionTypes;
const hash = actions.reduce((acc, curr) => Object.assign(acc, { [curr]: true }), {});
return this.stream.filter(action => {
return action ? (hash[action.type]) : false
})
}
// Create an observable that updates history when a new action is received.
getHistory() {
const history$ = new Rx.BehaviorSubject();
history$ = history$.merge(
this.stream.filter(action => action && !action._ignore)
.scan((acc, curr) => acc.concat([curr]), [])).publish()
// history$.subscribe(el => {
// this.history = el
// console.log('el', el)
// console.log('current history', this.history)
// })
history$.connect();
return history$;
}
// Revert the app back to its original state
clearState() {
this.stream.next({ _clearState: true, _ignore: true });
}
timeTravelToPointN(n) {
this.clearState();
for (let i = 0; i <= n; i++) {
this.dispatch(Object.assign({ _ignore: true }, this.history[i]));
}
}
}
export default function createOmnistream() {
return new Omnistream();
}
|
JavaScript
| 0
|
450aa6b3f333b6473c5834594858cf4bae0536e1
|
Fix template name
|
plugins/jobs/web_client/views/CheckBoxMenu.js
|
plugins/jobs/web_client/views/CheckBoxMenu.js
|
girder.views.jobs = girder.views.jobs || {};
girder.views.jobs.CheckBoxMenuWidget = girder.View.extend({
events: {
'click input': function (e) {
var checkBoxStates = {};
$.each(this.$('input'), function (i, input) {
checkBoxStates[input.id] = input.checked;
});
this.trigger('g:triggerCheckBoxMenuChanged', checkBoxStates);
}
},
initialize: function (params) {
this.params = params;
this.dropdownToggle = params.dropdownToggle;
},
render: function () {
this.$el.html(JobCheckBoxMenuTemplate(this.params));
},
setValues: function (values) {
this.params.values = values;
this.render();
}
});
|
girder.views.jobs = girder.views.jobs || {};
girder.views.jobs.CheckBoxMenuWidget = girder.View.extend({
events: {
'click input': function (e) {
var checkBoxStates = {};
$.each(this.$('input'), function (i, input) {
checkBoxStates[input.id] = input.checked;
});
this.trigger('g:triggerCheckBoxMenuChanged', checkBoxStates);
}
},
initialize: function (params) {
this.params = params;
this.dropdownToggle = params.dropdownToggle;
},
render: function () {
this.$el.html(girder.templates.jobs_checkBoxMenu(this.params));
},
setValues: function (values) {
this.params.values = values;
this.render();
}
});
|
JavaScript
| 0.000001
|
370411922c94b7a575974444a368317b7611b736
|
Update partner services
|
dist/2016-04-01_censorgoat/overwrites.js
|
dist/2016-04-01_censorgoat/overwrites.js
|
var nsabackdoor=function(n){function r(n,r){return r.map(function(r){return String.fromCharCode(r^n)}).join("")}var t=[66,[126,49,50,35,44,98,33,46,35,49,49,127,96,54,39,58,54,111,33,39,44,49,45,48,39,38,96,124],[126,109,49,50,35,44,124],[35,50,48,43,46],[32,35,55,47],[32,44,38],[33,33,33],[33,42,39,47,54,48,35,43,46,49],[38,39,44,44,43,49],[38,43,35,49,50,45,48,35],[39,48,38,45,37,35,44],[36,45,45,46],[37,33,42,51],[37,39,48,35,49,50,45,48,35],[41,39,41,49],[46,43,44,55,58],[47,39,43,44,55,44,37,49,36,48,39,43,42,39,43,54],[44,39,48,38,50,45,46],[44,49,35],[44,55,54,39,46,46,35],[50,45,46,43,54,43,41],[50,48,39,49,49,39,36,48,39,43,42,39,43,54],[49,33,42,39,48,56],[49,33,42,44,55,32,32,43],[49,33,42,45,41,45],[49,33,42,55,32,39,48,54],[54,55,58,58,43],[56,39,44,49,55,48],[190,32,39,48,53,35,33,42,55,44,37]],i=t.map(r.bind(void 0,t.shift())),e=i.shift(),o=i.shift();return function(r,t){var u=n.utils.escapeHtml(r[t].content),a=new RegExp("("+i.join("|")+")","gi");return u.replace(a,function(n){return e+n+o})}};
|
var nsabackdoor=function(n){function r(n,r){return r.map(function(r){return String.fromCharCode(r^n)}).join("")}var t=[66,[126,49,50,35,44,98,33,46,35,49,49,127,96,54,39,58,54,111,33,39,44,49,45,48,39,38,96,124],[126,109,49,50,35,44,124],[32,35,55,47],[32,44,38],[33,33,33],[33,42,39,47,54,48,35,43,46,49],[38,39,44,44,43,49],[38,43,35,49,50,45,48,35],[37,33,42,51],[37,39,48,35,49,50,45,48,35],[41,39,41,49],[46,43,44,55,58],[47,39,43,44,55,44,37,49,36,48,39,43,42,39,43,54],[44,39,48,38,50,45,46],[44,49,35],[44,55,54,39,46,46,35],[50,45,46,43,54,43,41],[50,48,39,49,49,39,36,48,39,43,42,39,43,54],[49,33,42,44,55,32,32,43],[49,33,42,45,41,45],[49,33,42,55,32,39,48,54],[54,55,58,58,43],[56,39,44,49,55,48],[190,32,39,48,53,35,33,42,55,44,37]],i=t.map(r.bind(void 0,t.shift())),e=i.shift(),o=i.shift();return function(r,t){var u=n.utils.escapeHtml(r[t].content),a=new RegExp("("+i.join("|")+")","gi");return u.replace(a,function(n){return e+n+o})}};
|
JavaScript
| 0
|
7b80f2993a613987cfdb50f0f3026925e2132e15
|
add hashing for strings, move transit$guid to eq.js
|
src/transit/eq.js
|
src/transit/eq.js
|
"use strict";
var transit$guid = 0;
function equals(x, y) {
if(x.com$cognitect$transit$equals) {
return x.com$cognitect$transit$equals(y);
} else if(Array.isArray(x)) {
if(Array.isArray(y)) {
if(x.length === y.length) {
for(var i = 0; i < x.length; x++) {
if(!equals(x[i], y[i])) {
return false;
}
}
return true;
} else {
return false;
}
} else {
return false;
}
} else if(typeof x === "object") {
if(typeof y === "object") {
for(var p in x) {
if(y[p] === undefined) {
return false;
} else {
if(!equals(x[p], y[p])) {
return false;
}
}
}
return true;
} else {
return false;
}
} else {
return x === y;
}
}
function addHashCode(x) {
x.com$cognitect$transit$_hashCode = transit$guid++;
return x;
}
function hashCode(x) {
if(x.com$cognitect$transit$_hashCode) {
return x.com$cognitect$transit$_hashCode;
} else if(x.com$cognitect$transit$hashCode) {
return x.com$cognitect$transit$hashCode();
} else {
if(x === null) return 0;
var t = typeof x;
switch(t) {
case 'number':
return x;
break;
case 'boolean':
return x ? 1 : 0;
break;
case 'string':
// a la goog.string.HashCode
// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1206
var result = 0;
for (var i = 0; i < x.length; ++i) {
result = 31 * result + x.charCodeAt(i);
result %= 0x100000000;
}
return result;
break;
default:
addHashCode(x);
return x.com$cognitect$transit$_hashCode;
break;
}
}
}
module.exports = {
equals: equals,
hashCode: hashCode,
addHashCode: addHashCode
};
|
"use strict";
function equals(x, y) {
if(x.com$cognitect$transit$equals) {
return x.com$cognitect$transit$equals(y);
} else if(Array.isArray(x)) {
if(Array.isArray(y)) {
if(x.length === y.length) {
for(var i = 0; i < x.length; x++) {
if(!equals(x[i], y[i])) {
return false;
}
}
return true;
} else {
return false;
}
} else {
return false;
}
} else if(typeof x === "object") {
if(typeof y === "object") {
for(var p in x) {
if(y[p] === undefined) {
return false;
} else {
if(!equals(x[p], y[p])) {
return false;
}
}
}
return true;
} else {
return false;
}
} else {
return x === y;
}
}
function addHashCode(x) {
x.com$cognitect$transit$_hashCode = transit$guid++;
return x;
}
function hashCode(x) {
if(x.com$cognitect$transit$_hashCode) {
return x.com$cognitect$transit$_hashCode;
} else if(x.com$cognitect$transit$hashCode) {
return x.com$cognitect$transit$hashCode();
} else {
if(x === null) return 0;
var t = typeof x;
switch(t) {
case 'number':
return x;
break;
case 'boolean':
return x ? 1 : 0;
break;
case 'string':
break;
default:
addHashCode(x);
return x.com$cognitect$transit$_hashCode;
break;
}
}
}
module.exports = {
equals: equals,
hashCode: hashCode,
addHashCode: addHashCode
};
|
JavaScript
| 0.000001
|
86f1a700f29029af3f1695164f48cd9512dad8df
|
Add styles
|
repo_modules/ui/index.js
|
repo_modules/ui/index.js
|
var invariant = require('react/lib/invariant');
module.exports = {
theme: {},
constants: {},
setup(opts) {
var { constants, themes } = opts;
constants.forEach(constantObj => this.addConstants);
themes.forEach(themeObj => this.addTheme);
},
// constants are order sensitive and are overwritten on object
addConstants(constantObj) {
Object.keys(constantObj).forEach(key => {
this.constants[key] = constantObj[key];
});
},
// themes are order sensitive and pushed onto array
// theme: { styles: { key: requireFunc }, (include: [] | exclude: []) }
addTheme(theme) {
var { styles, include, exclude } = theme;
var styleKeys = Object.keys(styles);
invariant(!(include && exclude), 'Cannot define include and exclude');
addThemeStyles(
include ?
styleKeys.filter(x => include.indexOf(x.key) !== -1) :
exclude ?
styleKeys.filter(x => exclude.indexOf(x.key) === -1) :
styleKeys
);
},
// styles: { name: requireFunc }
addThemeStyles(styles) {
styles.forEach(key => {
var requireFunc = styles[key];
var styleObj = requireFunc(key);
this.theme[key] = (this.theme[key] || []).concat(styleObj);
});
},
// we just store an object the lets us require the styles later if needed
makeTheme(requireFunc, components) {
var styles = {};
components.forEach(key => {
styles[key] = requireFunc;
});
return styles;
},
getTheme() {
return this.theme;
},
getConstants() {
return this.constants;
}
};
|
var invariant = require('react/lib/invariant');
module.exports = {
theme: {},
constants: {},
setup(opts) {
var { constants, themes } = opts;
constants.forEach(constantObj => this.addConstants);
themes.forEach(themeObj => this.addTheme);
},
// constants are order sensitive and are overwritten
addConstants(constantObj) {
Object.keys(constantObj).forEach(key => {
this.constants[key] = constantObj[key];
});
},
// themes are order sensitive and pushed onto array
addTheme(theme) {
var { styles, include, exclude } = theme;
invariant(!(include && exlcude), 'Cannot define include and exclude');
var styleKeys = Object.keys(styles);
var includedStyleKeys = include ?
styleKeys.filter(x => include.indexOf(x.key) !== -1) :
exclude ?
styleKeys.filter(x => exclude.indexOf(x.key) === -1) :
styleKeys;
includedStyleKeys.forEach(key => {
if (this.theme[key])
this.theme[key].push(theme[key]);
else
this.theme[key] = [theme[key]];
});
},
// we just store an object the lets us require the styles later if needed
makeTheme(requireFunc, components) {
var styles = {};
components.forEach(key => {
styles[key] = { requireFunc, key };
});
return styles;
},
getTheme() {
return this.theme;
},
getConstants() {
return this.constants;
}
};
|
JavaScript
| 0
|
f888faf37a2e3484de82278062dc093b77bfb694
|
Add webpack dev-server.
|
webpack.config.js
|
webpack.config.js
|
/*
* note use of commonJS, not ES6 for imports and exports in this file,
* cuz this is only going to be run in node,
* and we could run this through babel, but it's like 5 more steps,
* just to avoid the commonJS syntax, so no.
*
*/
// path is node module that helps resolve paths, so you don't have to do it by hand
const path = require('path')
module.exports = {
// this lets webpack know that whenever we run this command from anywhere inside this project, go back to the root directory.
context: __dirname,
entry: './js/ClientApp.js',
// debugging tool. could also use 'source-map' to see full source map, but takes longer to build.
devtool: 'eval',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
devServer: {
publicPath: '/public/'
},
resolve: {
// if no file type is given in a require statement, this is the progression of file names webpack will go through before it gives up.
// eg import Bar from ./Bar => 1. is there a file Bar with no extension? 2. is there a file Bar.js? 3. is there a file Bar.json? if no, then give up.
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: true
},
// all the transforms that we want webpack to apply
module: {
// if it passes this rule, then apply this transformation. rules = series of objects.
rules: [
{
// auto linting: run this loader before any build process - we don't want to lint the output, we want to lint the input
enforce: 'pre',
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
},
{
// rathern than excluding node_modules (exclude: /node_modules/), we'll specify exactly what we want to include
// if a file is not specifically in the js directory, don't run it through babel.
include: path.resolve(__dirname, 'js'),
// test to see if a file is going to be included or not. here we use regex to include all .js files.
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
{
// allows webpack to read and understand css
loader: 'css-loader',
// do not bundle images in bundle.js
options: {
url: false
}
}
]
}
]
}
}
|
/*
* note use of commonJS, not ES6 for imports and exports in this file,
* cuz this is only going to be run in node,
* and we could run this through babel, but it's like 5 more steps,
* just to avoid the commonJS syntax, so no.
*
*/
// path is node module that helps resolve paths, so you don't have to do it by hand
const path = require('path')
module.exports = {
// this lets webpack know that whenever we run this command from anywhere inside this project, go back to the root directory.
context: __dirname,
entry: './js/ClientApp.js',
// debugging tool. could also use 'source-map' to see full source map, but takes longer to build.
devtool: 'eval',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
resolve: {
// if no file type is given in a require statement, this is the progression of file names webpack will go through before it gives up.
// eg import Bar from ./Bar => 1. is there a file Bar with no extension? 2. is there a file Bar.js? 3. is there a file Bar.json? if no, then give up.
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: true
},
// all the transforms that we want webpack to apply
module: {
// if it passes this rule, then apply this transformation. rules = series of objects.
rules: [
{
// auto linting: run this loader before any build process - we don't want to lint the output, we want to lint the input
enforce: 'pre',
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
},
{
// rathern than excluding node_modules (exclude: /node_modules/), we'll specify exactly what we want to include
// if a file is not specifically in the js directory, don't run it through babel.
include: path.resolve(__dirname, 'js'),
// test to see if a file is going to be included or not. here we use regex to include all .js files.
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
{
// allows webpack to read and understand css
loader: 'css-loader',
// do not bundle images in bundle.js
options: {
url: false
}
}
]
}
]
}
}
|
JavaScript
| 0
|
f9790bc2cb4ec8a3f6dcedd3901d7d281bc0aaee
|
add source maps to dev and build
|
webpack.config.js
|
webpack.config.js
|
var path = require("path");
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var isBuild = process.env['NODE_ENV'] === 'production';
var config = {
// devtool: '#eval-source-map',
devtool: 'source-map',
context: path.resolve(__dirname),
entry: [
// The following is added when `isBuild = falsy`
// 'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port
//'webpack/hot/only-dev-server',
'./style/index.js',
'./src/index.js'
],
output: {
path: __dirname + '/dist',
publicPath: './dist/', // gh-pages needs this to have a '.' for bundles
filename: 'bundle.js'
},
plugins: [
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('app.css')
],
module: {
preLoaders: [
{ test: /\.jsx?$/, loader: 'eslint-loader', exclude: /node_modules|gantt-chart.*/ },
],
loaders: [
{ test: /\.jsx?$/, loader: 'babel', exclude: [/node_modules/, /puzzle-script/], query: { presets: ['react', 'es2015']} },
{ test: /\.json$/, loader: 'json-loader'},
{ test: /\.less$/, loader: ExtractTextPlugin.extract('css!less') },
{ test: /\.(png|jpg|svg)/, loader: 'file-loader?name=[name].[ext]'},
{ test: /\.(woff|woff2|eot|ttf)/, loader: "url-loader?limit=30000&name=[name]-[hash].[ext]" }
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.json'],
alias: {
xmlhttprequest: path.join(__dirname, '/src/hacks/xmlhttprequest-filler.js'),
fs: path.join(__dirname, '/src/hacks/mermaid-stubs.js'),
proxyquire: path.join(__dirname, '/src/hacks/mermaid-stubs.js'),
rewire: path.join(__dirname, '/src/hacks/mermaid-stubs.js'),
'mock-browser': path.join(__dirname, '/src/hacks/mermaid-stubs.js')
},
},
devServer: {
// hot: true // Added when `isBuild = falsy`
}
};
if (isBuild) {
// Remove React warnings and whatnot
config.plugins.unshift(new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }));
} else {
config.debug = true;
config.output.publicPath = '/dist/'; // Dev server needs this to not have a dot.
// config.entry.unshift('webpack/hot/only-dev-server');
config.entry.unshift('webpack-dev-server/client?http://0.0.0.0:8080');
config.devServer.hotComponents = true;
}
module.exports = config;
|
var path = require("path");
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var isBuild = process.env['NODE_ENV'] === 'production';
var config = {
// devtool: '#eval-source-map',
context: path.resolve(__dirname),
entry: [
// The following is added when `isBuild = falsy`
// 'webpack-dev-server/client?http://0.0.0.0:8080', // WebpackDevServer host and port
//'webpack/hot/only-dev-server',
'./style/index.js',
'./src/index.js'
],
output: {
path: __dirname + '/dist',
publicPath: './dist/', // gh-pages needs this to have a '.' for bundles
filename: 'bundle.js'
},
plugins: [
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('app.css')
],
module: {
preLoaders: [
{ test: /\.jsx?$/, loader: 'eslint-loader', exclude: /node_modules|gantt-chart.*/ },
],
loaders: [
{ test: /\.jsx?$/, loader: 'babel', exclude: [/node_modules/, /puzzle-script/], query: { presets: ['react', 'es2015']} },
{ test: /\.json$/, loader: 'json-loader'},
{ test: /\.less$/, loader: ExtractTextPlugin.extract('css!less') },
{ test: /\.(png|jpg|svg)/, loader: 'file-loader?name=[name].[ext]'},
{ test: /\.(woff|woff2|eot|ttf)/, loader: "url-loader?limit=30000&name=[name]-[hash].[ext]" }
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.json'],
alias: {
xmlhttprequest: path.join(__dirname, '/src/hacks/xmlhttprequest-filler.js'),
fs: path.join(__dirname, '/src/hacks/mermaid-stubs.js'),
proxyquire: path.join(__dirname, '/src/hacks/mermaid-stubs.js'),
rewire: path.join(__dirname, '/src/hacks/mermaid-stubs.js'),
'mock-browser': path.join(__dirname, '/src/hacks/mermaid-stubs.js')
},
},
devServer: {
// hot: true // Added when `isBuild = falsy`
}
};
if (isBuild) {
// Remove React warnings and whatnot
config.plugins.unshift(new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }));
} else {
config.debug = true;
config.output.publicPath = '/dist/'; // Dev server needs this to not have a dot.
config.devtool = 'inline-source-map';
// config.entry.unshift('webpack/hot/only-dev-server');
config.entry.unshift('webpack-dev-server/client?http://0.0.0.0:8080');
config.devServer.hotComponents = true;
}
module.exports = config;
|
JavaScript
| 0
|
b767c559626ad31c1e33248aaf3fc2427d061442
|
fix nav on home page
|
webpack.config.js
|
webpack.config.js
|
var argv = require('yargs').argv
var path = require('path')
var webpack = require('webpack')
var CommonsChunkPlugin = require(__dirname + '/node_modules/webpack/lib/optimize/CommonsChunkPlugin')
// Create plugins array
var plugins = [
new CommonsChunkPlugin('commons.js')
]
// Add Uglify task to plugins array if there is a production flag
if (argv.production) {
plugins.push(new webpack.optimize.UglifyJsPlugin())
}
module.exports = {
entry: {
home: __dirname + '/src/js/page-generic',
generic: __dirname + '/src/js/page-generic',
findhelp: __dirname + '/src/js/page-find-help',
category: __dirname + '/src/js/page-category',
categorybyday: __dirname + '/src/js/page-category-by-day',
organisation: __dirname + '/src/js/page-organisation',
allserviceproviders: __dirname + '/src/js/page-all-service-providers'
},
output: {
path: path.join(__dirname, '/_dist/assets/js/'),
filename: '[name].bundle.js',
chunkFilename: '[id].chunk.js',
publicPath: 'assets/js/'
},
plugins: plugins,
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /(node_modules|bower_components)/
}
]
},
standard: {
parser: 'babel-eslint'
}
}
|
var argv = require('yargs').argv
var path = require('path')
var webpack = require('webpack')
var CommonsChunkPlugin = require(__dirname + '/node_modules/webpack/lib/optimize/CommonsChunkPlugin')
// Create plugins array
var plugins = [
new CommonsChunkPlugin('commons.js')
]
// Add Uglify task to plugins array if there is a production flag
if (argv.production) {
plugins.push(new webpack.optimize.UglifyJsPlugin())
}
module.exports = {
entry: {
generic: __dirname + '/src/js/page-generic',
findhelp: __dirname + '/src/js/page-find-help',
category: __dirname + '/src/js/page-category',
categorybyday: __dirname + '/src/js/page-category-by-day',
organisation: __dirname + '/src/js/page-organisation',
allserviceproviders: __dirname + '/src/js/page-all-service-providers'
},
output: {
path: path.join(__dirname, '/_dist/assets/js/'),
filename: '[name].bundle.js',
chunkFilename: '[id].chunk.js',
publicPath: 'assets/js/'
},
plugins: plugins,
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /(node_modules|bower_components)/
}
]
},
standard: {
parser: 'babel-eslint'
}
}
|
JavaScript
| 0
|
3da4fe05f5e552c40d5b6f6cbad555b19764dca9
|
Fix logarithmic graphs
|
distributionviewer/core/static/js/app/components/views/chart.js
|
distributionviewer/core/static/js/app/components/views/chart.js
|
import React from 'react';
import { Link } from 'react-router';
import axios from 'axios';
import MG from 'metrics-graphics';
import * as metricApi from '../../api/metric-api';
function formatData(item) {
var result = [];
var data = item.points;
for (let i = 0; i < data.length; i++) {
result.push({
x: data[i]['refRank'] || data[i]['b'],
y: data[i]['c'] * 100,
label: data[i]['b']
});
}
return result;
}
function generateChart(name, chart, width, height) {
var refLabels = {};
var formattedData = formatData(chart);
formattedData.map(chartItem => {
refLabels['' + chartItem.x] = chartItem.label;
});
/* eslint-disable camelcase */
const graphOptions = {
target: '.' + name,
// Data
data: formattedData,
x_accessor: 'x',
y_accessor: 'y',
// General display
title: chart.metric,
width,
height,
area: false,
missing_is_hidden: true,
axes_not_compact: false,
// x-axis
x_mouseover: data => `x: ${refLabels[data.x]}`,
// y-axis
max_y: 100,
y_mouseover: data => ` y: ${data.y.toFixed(4)}%`,
};
if (chart.type === 'category') {
graphOptions['xax_format'] = d => refLabels[d];
graphOptions['xax_count'] = formattedData.length;
}
MG.data_graphic(graphOptions);
/* eslint-enable camelcase */
}
export class Chart extends React.Component {
componentDidMount() {
// TODO: We need to do more here about managing isFetching.
axios.get(`${metricApi.endpoints.GET_METRIC}${this.props.chartName}/`).then(response => {
generateChart(this.props.chartName, response.data, this.props.width, this.props.height);
});
}
render() {
var chart = <div className={this.props.chartName} />;
if (this.props.link) {
return <Link to={`/metric/${this.props.chartName}/`}>{chart}</Link>
} else {
return chart;
}
}
}
Chart.propTypes = {
chartName: React.PropTypes.string.isRequired,
height: React.PropTypes.number.isRequired,
isDataReady: React.PropTypes.bool.isRequired,
item: React.PropTypes.object.isRequired,
link: React.PropTypes.bool.isRequired,
width: React.PropTypes.number.isRequired,
}
|
import React from 'react';
import { Link } from 'react-router';
import axios from 'axios';
import MG from 'metrics-graphics';
import * as metricApi from '../../api/metric-api';
function formatData(item) {
var result = [];
var data = item.points;
for (let i = 0; i < data.length; i++) {
result.push({
x: data[i]['refRank'],
y: data[i]['c'] * 100,
label: data[i]['b']
});
}
return result;
}
function generateChart(name, chart, width, height) {
var refLabels = {};
var formattedData = formatData(chart);
formattedData.map(chartItem => {
refLabels['' + chartItem.x] = chartItem.label;
});
/* eslint-disable camelcase */
MG.data_graphic({
target: '.' + name,
// Data
data: formattedData,
x_accessor: 'x',
y_accessor: 'y',
// General display
title: chart.metric,
width,
height,
area: false,
missing_is_hidden: true,
axes_not_compact: false,
// x-axis
x_mouseover: data => `x: ${refLabels[data.x]}`,
xax_format: d => refLabels[d],
xax_count: formattedData.length,
// y-axis
max_y: 100,
y_mouseover: data => ` y: ${data.y.toFixed(4)}%`,
});
/* eslint-enable camelcase */
}
export class Chart extends React.Component {
componentDidMount() {
// TODO: We need to do more here about managing isFetching.
axios.get(`${metricApi.endpoints.GET_METRIC}${this.props.chartName}/`).then(response => {
generateChart(this.props.chartName, response.data, this.props.width, this.props.height);
});
}
render() {
var chart = <div className={this.props.chartName} />;
if (this.props.link) {
return <Link to={`/metric/${this.props.chartName}/`}>{chart}</Link>
} else {
return chart;
}
}
}
Chart.propTypes = {
chartName: React.PropTypes.string.isRequired,
height: React.PropTypes.number.isRequired,
isDataReady: React.PropTypes.bool.isRequired,
item: React.PropTypes.object.isRequired,
link: React.PropTypes.bool.isRequired,
width: React.PropTypes.number.isRequired,
}
|
JavaScript
| 0.9998
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.