commit stringlengths 40 40 | subject stringlengths 1 3.25k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | old_contents stringlengths 0 26.3k | lang stringclasses 3
values | proba float64 0 1 | diff stringlengths 0 7.82k |
|---|---|---|---|---|---|---|---|
3f355ce10a4261a8ce07df2939d7c49337292f83 | Fix group size (#21896) | packages/material-ui-lab/src/AvatarGroup/AvatarGroup.js | packages/material-ui-lab/src/AvatarGroup/AvatarGroup.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { isFragment } from 'react-is';
import clsx from 'clsx';
import { withStyles } from '@material-ui/core/styles';
import Avatar from '@material-ui/core/Avatar';
import { chainPropTypes } from '@material-ui/utils';
const SPACINGS = {
small: -16,
medium: null,
};
export const styles = (theme) => ({
/* Styles applied to the root element. */
root: {
display: 'flex',
flexDirection: 'row-reverse',
},
/* Styles applied to the avatar elements. */
avatar: {
border: `2px solid ${theme.palette.background.default}`,
marginLeft: -8,
'&:last-child': {
marginLeft: 0,
},
},
});
const AvatarGroup = React.forwardRef(function AvatarGroup(props, ref) {
const {
children: childrenProp,
classes,
className,
max = 5,
spacing = 'medium',
...other
} = props;
const clampedMax = max < 2 ? 2 : max;
const children = React.Children.toArray(childrenProp).filter((child) => {
if (process.env.NODE_ENV !== 'production') {
if (isFragment(child)) {
console.error(
[
"Material-UI: The AvatarGroup component doesn't accept a Fragment as a child.",
'Consider providing an array instead.',
].join('\n'),
);
}
}
return React.isValidElement(child);
});
const extraAvatars = children.length > clampedMax ? children.length - clampedMax + 1 : 0;
const marginLeft = spacing && SPACINGS[spacing] !== undefined ? SPACINGS[spacing] : -spacing;
return (
<div className={clsx(classes.root, className)} ref={ref} {...other}>
{extraAvatars ? (
<Avatar
className={classes.avatar}
style={{
marginLeft,
}}
>
+{extraAvatars}
</Avatar>
) : null}
{children
.slice(0, children.length - extraAvatars)
.reverse()
.map((child) => {
return React.cloneElement(child, {
className: clsx(child.props.className, classes.avatar),
style: {
marginLeft,
...child.props.style,
},
});
})}
</div>
);
});
AvatarGroup.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The avatars to stack.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Max avatars to show before +x.
*/
max: chainPropTypes(PropTypes.number, (props) => {
if (props.max < 2) {
throw new Error(
[
'Material-UI: The prop `max` should be equal to 2 or above.',
'A value below is clamped to 2.',
].join('\n'),
);
}
}),
/**
* Spacing between avatars.
*/
spacing: PropTypes.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.number]),
};
export default withStyles(styles, { name: 'MuiAvatarGroup' })(AvatarGroup);
| JavaScript | 0 | @@ -604,16 +604,46 @@
ault%7D%60,%0A
+ boxSizing: 'content-box',%0A
marg
|
32db31b449737a0973a977501a31838132865491 | Load relevant content if the hash is specified and matches an existing fragment | docs/luga-docs.js | docs/luga-docs.js | luga.namespace("luga.docs");
(function(){
"use strict";
var Controller = function(){
var CONST = {
SELECTORS: {
CONTENT: "#content"
},
FRAGMENTS_PATH: "fragments/",
FRAGMENTS_SUFFIX: ".inc",
FRAGMENTS: {
INDEX: "index",
API: "/",
CLIENT_SIDE: ".inc",
SERVER_SIDE: ".inc"
}
};
var init = function(){
loadFragment(CONST.FRAGMENTS.INDEX);
initRouter();
};
var initRouter = function(){
var router = new luga.router.Router();
var rootHandler = new luga.router.RouteHandler({
path: "",
enterCallBacks: [function(){
loadFragment(CONST.FRAGMENTS.INDEX);
}]
});
var apiHandler = new luga.router.RouteHandler({
path: "api",
enterCallBacks: [function(){
loadFragment("api");
}]
});
var clientSideHandler = new luga.router.RouteHandler({
path: "client-side",
enterCallBacks: [function(){
loadFragment("client-side");
}]
});
var serverSideHandler = new luga.router.RouteHandler({
path: "server-side",
enterCallBacks: [function(){
loadFragment("server-side");
}]
});
router.add(rootHandler);
router.add(apiHandler);
router.add(clientSideHandler);
router.add(serverSideHandler);
router.start();
};
var loadFragment = function(id){
var fragmentUrl = CONST.FRAGMENTS_PATH + id + CONST.FRAGMENTS_SUFFIX;
jQuery.ajax(fragmentUrl)
.done(function(response, textStatus, jqXHR){
jQuery(CONST.SELECTORS.CONTENT).empty();
jQuery(CONST.SELECTORS.CONTENT).html(jqXHR.responseText);
})
.fail(function(){
alert("error loading fragment");
});
};
init();
};
jQuery(document).ready(function(){
luga.docs.controller = new Controller();
});
}()); | JavaScript | 0 | @@ -343,16 +343,186 @@
tion()%7B%0A
+%09%09%09var currentHash = location.hash.substring(1);%0A%09%09%09if((currentHash !== %22%22) && (CONST.FRAGMENTS%5BcurrentHash%5D !== undefined))%7B%0A%09%09%09%09loadFragment(currentHash);%0A%09%09%09%7D else %7B%0A%09
%09%09%09loadF
@@ -553,16 +553,21 @@
INDEX);%0A
+%09%09%09%7D%0A
%09%09%09initR
|
cf74075defb57a24ddbb111222c4f4ff56d1cd40 | Remove unecessary eslint disable rule | scripts/jsonlint.js | scripts/jsonlint.js | /* eslint strict: ["error", "never"] */
const getJsonFiles = require('./lib/getJsonFiles');
const { execSync } = require('child_process');
const path = require('path');
// eslint-disable-next-line max-statements
const execJsonLint = function execJsonLint(jsonFiles) {
let throwError = false;
for (const file of jsonFiles) {
try {
console.info(`Lint the file ${file}`);
// eslint-disable-next-line max-len
execSync(`${path.resolve('./node_modules/.bin/jsonlint')} ${file} --in-place`);
} catch (error) {
throwError = true;
}
}
if (throwError) {
const exitWithError = 1;
// eslint-disable-next-line no-process-exit
process.exit(exitWithError);
}
};
execJsonLint(getJsonFiles());
| JavaScript | 0.000001 | @@ -168,51 +168,8 @@
);%0A%0A
-// eslint-disable-next-line max-statements%0A
cons
|
b143802716392f8bc29a5cedeaa66356f28690f3 | Add better comment for plugin point | lib/plugins/linker.js | lib/plugins/linker.js | var _ = require('lodash'),
Async = require('async'),
ModuleDependency = require('webpack/lib/dependencies/ModuleDependency'),
NullFactory = require('webpack/lib/NullFactory'),
Path = require('path'),
RawSource = require('webpack-core/lib/RawSource'),
Client = require('../client');
module.exports = exports = function LinkerPlugin() {
this.usedModules = [];
this.componentIdCounter = 0;
};
exports.prototype.apply = function(compiler) {
var plugin = this;
var linkedModules = {};
// Convert the components list to the format that we will use for linking/serializing
_.each(compiler.options.components, function(component, componentName) {
_.each(component.modules, function(module, moduleId) {
linkedModules[module.name] = {
name: module.name,
componentName: componentName,
entry: component.entry
};
if (moduleId === '0' && !linkedModules[componentName]) {
linkedModules[componentName] = linkedModules[module.name];
}
});
});
compiler.plugin('compilation', function(compilation) {
compilation.dependencyFactories.set(LinkedRequireDependency, new NullFactory());
compilation.dependencyTemplates.set(LinkedRequireDependency, new LinkedRequireDependencyTemplate());
compilation.mainTemplate.plugin('local-vars', function(extensions/*, chunk, hash */) {
var buf = [extensions];
if (plugin.usedModules.length) {
var linkedModules = [],
componentNames = [],
componentPaths = [];
plugin.usedModules.forEach(function(used, index) {
/* jscs:disable */
linkedModules[index] = {c/*omponent*/: used.componentId, n/*ame*/: used.name};
componentPaths[used.componentId] = used.entry;
componentNames[used.componentId] = used.componentName;
// Provide a heads up that things are going to fail
if (!used.entry) {
compilation.errors.push(new Error('Component "' + used.componentName + '" referenced and missing entry chunk path'));
}
});
buf.push(
'// Linker variables',
'var linkedModules = ' + JSON.stringify(linkedModules) + ',',
' componentNames = ' + JSON.stringify(componentNames) + ',',
' componentPaths = ' + JSON.stringify(componentPaths) + ';');
}
return this.asString(buf);
});
compilation.mainTemplate.plugin('require-extensions', function(extensions/*, chunk, hash*/) {
var buf = [extensions];
buf.push(
Client.jsLinker({
requireFn: this.requireFn,
exportAMD: this.outputOptions.exportAMD,
exports: this.outputOptions.component && JSON.stringify(this.outputOptions.component),
imports: plugin.usedModules.length
}));
return this.asString(buf);
});
// Wrap the init logic so we can preload any dependencies before we launch
// our entry point.
compilation.mainTemplate.plugin('startup', function(source, chunk, hash) {
var loadEntry = '';
if (chunk.modules.some(function(m) { return m.id === 0; })) {
loadEntry = this.renderRequireFunctionForModule(hash, chunk, '0') + '(0);';
}
if (chunk.linkedDeps && chunk.linkedDeps.length) {
return this.asString([
this.requireFn + '.ec/*ensureComponent*/(' + JSON.stringify(chunk.linkedDeps) + ', function() {',
this.indent([
loadEntry,
'loadComplete();',
source
]),
'})']);
} else {
return this.asString([
loadEntry,
'loadComplete();',
source
]);
}
});
// Annotates the chunks with their external dependencies. This allows us to ensure that
// component dependencies are loaded prior to loading the chunk itself.
compilation.plugin('before-chunk-assets', function() {
compilation.chunks.forEach(function(chunk) {
var chunkDeps = [];
chunk.modules.forEach(function(module) {
module.dependencies.forEach(function(dependency) {
if (dependency instanceof LinkedRequireDependency) {
chunkDeps.push(dependency.linked);
}
});
});
chunk.linkedDeps = _.uniq(chunkDeps);
});
});
compilation.plugin('additional-assets', function(callback) {
var components = _.map(plugin.usedModules, function(module) {
return compilation.options.components[module.componentName];
});
components = _.uniq(components);
Async.forEach(components, function(component, callback) {
var componentFiles = _.filter(component.files || [], function(file) {
return !/(^\/)|\/\//.test(file) && !compilation.assets[file];
});
Async.forEach(componentFiles, function(file, callback) {
var path = Path.join(component.root, file);
compilation.fileDependencies.push(path);
compiler.inputFileSystem.readFile(path, function(err, content) {
/*istanbul ignore if */
if (err) {
compilation.errors.push(err);
} else {
compilation.assets[file] = new RawSource(content);
}
callback();
});
}, callback);
},
callback);
});
});
compiler.parser.plugin('call require:commonjs:item', function(expr, param) {
// Define custom requires for known external modules
var linked = param.isString() && linkedModules[param.string];
if (linked) {
var mappedId = plugin.moduleId(linked);
var dep = new LinkedRequireDependency(mappedId, expr.range);
dep.loc = expr.loc;
this.state.current.addDependency(dep);
return true;
}
});
};
exports.prototype.moduleId = function(linked) {
/*jshint eqnull:true */
var mappedId,
componentId = -1;
_.find(this.usedModules, function(module, index) {
if (module.name === linked.name) {
mappedId = index;
return module;
}
if (module.componentName === linked.componentName) {
// Track the component id, if seen, so we don't generate unnecessary component mappings
componentId = module.componentId;
}
});
if (mappedId == null) {
mappedId = this.usedModules.length;
linked.componentId = componentId < 0 ? this.componentIdCounter++ : componentId;
this.usedModules.push(linked);
}
return mappedId;
};
function LinkedRequireDependency(linked, range) {
ModuleDependency.call(this);
this.Class = LinkedRequireDependency;
this.linked = linked;
this.range = range;
}
LinkedRequireDependency.prototype = Object.create(ModuleDependency.prototype);
LinkedRequireDependency.prototype.type = 'linked require';
function LinkedRequireDependencyTemplate() {}
LinkedRequireDependencyTemplate.prototype.apply = function(dep, source) {
var content = '.l/*ink*/(' + JSON.stringify(dep.linked) + ')';
source.replace(dep.range[0], dep.range[1] - 1, content);
};
| JavaScript | 0 | @@ -4349,24 +4349,163 @@
);%0A %7D);%0A%0A
+ // Copy modules that we are linking to into the build directory, regardless of if the%0A // eventual use will be from the CDN or not.%0A
compilat
|
afc064243427e5a69e63cc896b01bca64aa9b62d | save onChange callback in useEffect (#6313) | packages/react/src/internal/Selection.js | packages/react/src/internal/Selection.js | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useCallback, useEffect, useState, useRef } from 'react';
import PropTypes from 'prop-types';
import isEqual from 'lodash.isequal';
export function useSelection({
disabled,
onChange,
initialSelectedItems = [],
}) {
const isMounted = useRef(false);
const [selectedItems, setSelectedItems] = useState(initialSelectedItems);
const onItemChange = useCallback(
(item) => {
if (disabled) {
return;
}
let selectedIndex;
selectedItems.forEach((selectedItem, index) => {
if (isEqual(selectedItem, item)) {
selectedIndex = index;
}
});
if (selectedIndex === undefined) {
setSelectedItems((selectedItems) => selectedItems.concat(item));
return;
}
setSelectedItems((selectedItems) =>
removeAtIndex(selectedItems, selectedIndex)
);
},
[disabled, selectedItems]
);
const clearSelection = useCallback(() => {
if (disabled) {
return;
}
setSelectedItems([]);
}, [disabled]);
useEffect(() => {
if (isMounted.current === true && onChange) {
onChange({ selectedItems });
}
}, [onChange, selectedItems]);
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
return {
selectedItems,
onItemChange,
clearSelection,
};
}
export default class Selection extends React.Component {
static propTypes = {
initialSelectedItems: PropTypes.array.isRequired,
};
static defaultProps = {
initialSelectedItems: [],
};
constructor(props) {
super(props);
this.state = {
selectedItems: props.initialSelectedItems,
};
}
internalSetState = (stateToSet, callback) =>
this.setState(stateToSet, () => {
if (callback) {
callback();
}
if (this.props.onChange) {
this.props.onChange(this.state);
}
});
handleClearSelection = () => {
if (this.props.disabled) {
return;
}
this.internalSetState({
selectedItems: [],
});
};
handleSelectItem = (item) => {
this.internalSetState((state) => ({
selectedItems: state.selectedItems.concat(item),
}));
};
handleRemoveItem = (index) => {
this.internalSetState((state) => ({
selectedItems: removeAtIndex(state.selectedItems, index),
}));
};
handleOnItemChange = (item) => {
if (this.props.disabled) {
return;
}
const { selectedItems } = this.state;
let selectedIndex;
selectedItems.forEach((selectedItem, index) => {
if (isEqual(selectedItem, item)) {
selectedIndex = index;
}
});
if (selectedIndex === undefined) {
this.handleSelectItem(item);
return;
}
this.handleRemoveItem(selectedIndex);
};
render() {
const { children, render } = this.props;
const { selectedItems } = this.state;
const renderProps = {
selectedItems,
onItemChange: this.handleOnItemChange,
clearSelection: this.handleClearSelection,
};
if (render !== undefined) {
return render(renderProps);
}
if (children !== undefined) {
return children(renderProps);
}
return null;
}
}
// Generic utility for safely removing an element at a given index from an
// array.
const removeAtIndex = (array, index) => {
const result = array.slice();
result.splice(index, 1);
return result;
};
| JavaScript | 0 | @@ -444,16 +444,58 @@
false);%0A
+ const savedOnChange = useRef(onChange);%0A
const
@@ -1249,24 +1249,101 @@
isabled%5D);%0A%0A
+ useEffect(() =%3E %7B%0A savedOnChange.current = onChange;%0A %7D, %5BonChange%5D);%0A%0A
useEffect(
@@ -1388,24 +1388,37 @@
true &&
-o
+savedO
nChange
+.current
) %7B%0A
@@ -1419,24 +1419,37 @@
%7B%0A
-o
+savedO
nChange
+.current
(%7B selec
@@ -1477,18 +1477,8 @@
%7D, %5B
-onChange,
sele
|
720ab27eed63064c6c6bec14df527a33b4feb4af | Add UUID prefix | packages/strapi-generate-new/lib/merge-template.js | packages/strapi-generate-new/lib/merge-template.js | 'use strict';
const path = require('path');
const fse = require('fs-extra');
const fetch = require('node-fetch');
const unzip = require('unzip-stream');
const _ = require('lodash');
// Specify all the files and directories a template can have
const allowChildren = '*';
const allowedTemplateTree = {
// Root template files
'template.json': true,
'README.md': true,
'.gitignore': true,
// Template contents
template: {
'README.md': true,
'.env.example': true,
api: allowChildren,
components: allowChildren,
config: {
functions: allowChildren,
},
data: allowChildren,
plugins: allowChildren,
public: allowChildren,
scripts: allowChildren,
},
};
// Traverse template tree to make sure each file and folder is allowed
async function checkTemplateShape(templatePath) {
// Recursively check if each item in the template is allowed
const checkPathContents = (pathToCheck, parents) => {
const contents = fse.readdirSync(pathToCheck);
contents.forEach(item => {
const nextParents = [...parents, item];
const matchingTreeValue = _.get(allowedTemplateTree, nextParents);
// Treat files and directories separately
const itemPath = path.resolve(pathToCheck, item);
const isDirectory = fse.statSync(itemPath).isDirectory();
if (matchingTreeValue === undefined) {
// Unknown paths are forbidden
throw Error(`Illegal template structure, unknown path ${nextParents.join('/')}`);
}
if (matchingTreeValue === true) {
if (!isDirectory) {
// All good, the file is allowed
return;
}
throw Error(
`Illegal template structure, expected a file and got a directory at ${nextParents.join(
'/'
)}`
);
}
if (isDirectory) {
if (matchingTreeValue === allowChildren) {
// All children are allowed
return;
}
// Check if the contents of the directory are allowed
checkPathContents(itemPath, nextParents);
} else {
throw Error(`Illegal template structure, unknow file ${nextParents.join('/')}`);
}
});
};
checkPathContents(templatePath, []);
}
function getRepoInfo(githubURL) {
// Make sure it's a github url
const address = githubURL.split('://')[1];
if (!address.startsWith('github.com')) {
throw Error('A Strapi template can only be a GitHub URL');
}
// Parse github address into parts
const [, username, name, ...rest] = address.split('/');
const isRepo = username != null && name != null;
if (!isRepo || rest.length > 0) {
throw Error('A template URL must be the root of a GitHub repository');
}
return { username, name };
}
async function downloadGithubRepo(repoInfo, rootPath) {
const { username, name, branch = 'master' } = repoInfo;
const codeload = `https://codeload.github.com/${username}/${name}/zip/${branch}`;
const templatePath = path.resolve(rootPath, 'tmp-template');
const response = await fetch(codeload);
await new Promise(resolve => {
response.body.pipe(unzip.Extract({ path: templatePath })).on('close', resolve);
});
return templatePath;
}
// Merge the template's template.json into the Strapi project's package.json
async function mergePackageJSON(rootPath, templatePath) {
// Import the package.json and template.json templates
const packageJSON = require(path.resolve(rootPath, 'package.json'));
const templateJSON = require(path.resolve(templatePath, 'template.json'));
// Use lodash to deeply merge them
const mergedConfig = _.merge(packageJSON, templateJSON);
// Save the merged config as the new package.json
await fse.writeJSON(path.resolve(rootPath, 'package.json'), mergedConfig, {
spaces: 2,
});
}
// Merge all allowed files and directories
async function mergeFilesAndDirectories(rootPath, templatePath) {
const copyPromises = fse
.readdirSync(path.resolve(templatePath, 'template'))
.map(async fileOrDir => {
// Copy the template contents from the downloaded template to the Strapi project
await fse.copy(
path.resolve(templatePath, 'template', fileOrDir),
path.resolve(rootPath, fileOrDir),
{ overwrite: true, recursive: true }
);
});
await Promise.all(copyPromises);
}
module.exports = async function mergeTemplate(templateUrl, rootPath) {
// Download template repository to a temporary directory
const repoInfo = getRepoInfo(templateUrl);
console.log(`Installing ${repoInfo.username}/${repoInfo.name} template.`);
const templateParentPath = await downloadGithubRepo(repoInfo, rootPath);
const templatePath = path.resolve(templateParentPath, fse.readdirSync(templateParentPath)[0]);
// Make sure the downloaded template matches the required format
await checkTemplateShape(templatePath);
// Merge contents of the template in the project
await mergePackageJSON(rootPath, templatePath);
await mergeFilesAndDirectories(rootPath, templatePath);
// Delete the downloaded template repo
await fse.remove(templateParentPath);
};
| JavaScript | 0.999967 | @@ -3316,32 +3316,42 @@
th, templatePath
+, repoInfo
) %7B%0A // Import
@@ -3640,16 +3640,203 @@
eJSON);%0A
+%0A // Prefix Strapi UUID with starter info%0A const prefix = %60STARTER:$%7BrepoInfo.username%7D/$%7BrepoInfo.name%7D:%60;%0A mergedConfig.strapi = %7B%0A uuid: prefix + mergedConfig.strapi.uuid,%0A %7D;%0A%0A
// Sav
@@ -5144,24 +5144,34 @@
templatePath
+, repoInfo
);%0A await m
|
d38987d8369499711e594920756237dfee5d56e4 | fix children traverse in uniform environment | packages/uniform-environment/UniformEnvironment.js | packages/uniform-environment/UniformEnvironment.js | export default class UniformEnvironment {
constructor(children) {
this.children = children;
this.processes = new Map();
this.id = 0;
}
spawn(routine) {
const address = `ID${this.id++}`;
this.processes.set(address, routine);
setTimeout(routine, 0, this);
return address;
}
post(message) {
for (const child of this.children) {
child.send(message);
}
}
}
| JavaScript | 0 | @@ -352,32 +352,41 @@
of this.children
+.values()
) %7B%0A child.
|
aba3d71fd06496170bd7c017d847235b07178b3c | update markers | webmaps/js/rm10k.js | webmaps/js/rm10k.js | function main() {
var map = new L.Map('map', {
zoomControl: false,
center: [44.908, -75.83],
zoom: 15
});
L.tileLayer(
'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ',
maxZoom: 16
}).addTo(map);
// load 10k course route
$.getJSON("10k.geojson", function(data) {
// add GeoJSON layer to the map once the file is loaded
L.geoJson(data).addTo(map);
});
// Define markers
var startIcon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: 'flag-checkered',
iconColor: 'white',
markerColor: 'cadetblue'
});
var markerIcon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '',
iconColor: 'white',
markerColor: 'cadetblue',
html: '1'
});
// load 10k course route features
$.getJSON("features.geojson", function(data) {
//add GeoJSON layer to the map once the file is loaded
L.geoJson(data, {
pointToLayer: function(feature, latlng) {
if (feature.properties.cng_Meters ==
"0.0") {
var marker = L.marker(latlng, {
icon: startIcon
});
} else {
var marker = L.marker(latlng, {
icon: markerIcon
});
};
return marker;
//return new L.marker(latlng, {
//icon: startIcon
//});
},
//onEachFeature: function(feature, layer) {
//layer.bindPopup(feature.properties.cng_Meters);
//}
}).addTo(map);
});
}
// you could use $(window).load(main);
window.onload = main; | JavaScript | 0.000001 | @@ -1061,11 +1061,13 @@
ml:
-'1'
+(i+1)
%0A
|
5ba080cdf14956799bfe5d8363da4600b60b2078 | refactor clipboard component to include remove method | res/js/transforms/clipboard.js | res/js/transforms/clipboard.js | import { remove } from 'luett'
import Clipboard from 'clipboard'
import browser from 'bowser'
import { success, danger } from '../util/notify'
const isUnsupported = browser.isUnsupportedBrowser({
msie: '9',
firefox: '41',
chrome: '42',
edge: '12',
opera: '29',
safari: '10'
}, window.navigator.userAgent)
export default (el, opts) => {
if (isUnsupported) {
remove(el)
return
}
const clipboard = new Clipboard(el, {
text: opts.conf.text
})
clipboard.on('success', function () {
success('URL wurde kopiert')
})
clipboard.on('error', function () {
danger('URL konnte nicht kopiert werden. Bitte markiere den Text und kopiere ihn per Hand.')
})
}
| JavaScript | 0.000001 | @@ -391,16 +391,42 @@
return
+ %7B%0A remove() %7B%7D%0A %7D
%0A %7D%0A%0A
@@ -712,11 +712,96 @@
.')%0A %7D)
+%0A%0A return %7B%0A remove() %7B%0A clipboard.off()%0A clipboard.destroy()%0A %7D%0A %7D
%0A%7D%0A
|
bf003b244e62adef9d3aebbed5f96ff6e66ccf7a | remove random console log | src/app/orders/orderList/js/orders.controller.js | src/app/orders/orderList/js/orders.controller.js | angular.module('orderCloud')
.controller('OrdersCtrl', OrdersController)
;
function OrdersController($state, $filter, $ocMedia, ocParameters, ocOrders, ocReporting, OrderList, Parameters, GroupAssignments) {
var vm = this;
vm.list = OrderList;
vm.groups = GroupAssignments.Items;
vm.parameters = Parameters;
vm.userGroups = [];
//need this here to display in uib-datepicker (as date obj) but short date (string) in url
vm.fromDate = Parameters.fromDate;
vm.toDate = Parameters.toDate;
vm.orderStatuses = [
{Value: 'Open', Name: 'Open'},
{Value: 'AwaitingApproval', Name: 'Awaiting Approval'},
{Value: 'Completed', Name: 'Completed'},
{Value: 'Declined', Name: 'Declined'}
];
_.each(vm.groups, function(group) {
vm.userGroups.push( {
Name: group.Name,
Value: group.ID
})
});
vm.sortSelection = Parameters.sortBy ? (Parameters.sortBy.indexOf('!') == 0 ? Parameters.sortBy.split('!')[1] : Parameters.sortBy) : null;
vm.filtersApplied = vm.parameters.fromDate || vm.parameters.toDate || ($ocMedia('max-width:767px') && vm.sortSelection); //Check if filters are applied, Sort by is a filter on mobile devices
vm.showFilters = vm.filtersApplied;
vm.searchResults = Parameters.search && Parameters.search.length > 0; //Check if search was used
/*
Filter / Search / Sort / Pagination functions
*/
vm.filter = filter; //Reload the state with new parameters
vm.today = Date.now();
vm.clearFrom = clearFrom; //clears from parameters and resets page
vm.clearTo = clearTo; //clears to parameter and resets page
vm.search = search; //Reload the state with new search parameter & reset the
vm.clearSearch = clearSearch; //Clear the search parameter, reload the state & reset the page
vm.updateSort = updateSort; //Conditionally set, reverse, remove the sortBy parameter & reload the state
vm.reverseSort = reverseSort; //Used on mobile devices
vm.pageChanged = pageChanged; //Reload the state with the incremented page parameter
vm.loadMore = loadMore; //Load the next page of results with all of the same parameters, used on mobile
vm.formatDate = formatDate;
vm.selectTab = selectTab;
vm.goToOrder = goToOrder;
vm.downloadReport = downloadReport;
function downloadReport(){
return ocReporting.ExportOrders(vm.list.Items);
}
function selectTab(tab){
vm.parameters.tab = tab;
vm.parameters.group = null;
vm.parameters.status = null;
vm.parameters.from = null;
vm.parameters.to = null;
vm.filter(true);
}
function goToOrder(order){
if(vm.parameters.tab === 'approvals') {
$state.go('orderDetail.approvals', {orderid: order.ID});
} else {
$state.go('orderDetail', {orderid: order.ID});
}
}
function filter(resetPage) {
formatDate();
$state.go('.', ocParameters.Create(vm.parameters, resetPage));
}
console.log('something')
function clearFrom(){
vm.parameters.from = null;
vm.fromDate = null;
vm.filter(true);
}
function clearTo(){
vm.parameters.to = null;
vm.toDate = null;
vm.filter(true);
}
function formatDate(){
//formats date as string to display in url
if(vm.fromDate) vm.parameters.from = $filter('date')(angular.copy(vm.fromDate), 'MM-dd-yyyy');
if(vm.toDate) vm.parameters.to = $filter('date')(angular.copy(vm.toDate), 'MM-dd-yyyy');
}
function search() {
vm.filter(true);
}
function clearSearch() {
vm.parameters.search = null;
vm.filter(true);
}
function updateSort(value) {
value ? angular.noop() : value = vm.sortSelection;
switch(vm.parameters.sortBy) {
case value:
vm.parameters.sortBy = '!' + value;
break;
case '!' + value:
vm.parameters.sortBy = null;
break;
default:
vm.parameters.sortBy = value;
}
vm.filter(false);
}
function reverseSort() {
Parameters.sortBy.indexOf('!') == 0 ? vm.parameters.sortBy = Parameters.sortBy.split('!')[1] : vm.parameters.sortBy = '!' + Parameters.sortBy;
vm.filter(false);
}
function pageChanged() {
$state.go('.', {page:vm.list.Meta.Page});
}
function loadMore() {
return ocOrders.List(vm.parameters)
.then(function(data){
vm.list.Items = vm.list.Items.concat(data.Items);
vm.list.Meta = data.Meta;
});
}
} | JavaScript | 0.000001 | @@ -3077,38 +3077,8 @@
%7D%0A%0A
- console.log('something')%0A%0A
|
ce1f2e2bd45a5969ec0b24b08ad350f837985b4d | fix broken unit test | services/clsi/test/unit/js/LatexRunnerTests.js | services/clsi/test/unit/js/LatexRunnerTests.js | /* eslint-disable
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const sinon = require('sinon')
require('chai').should()
const modulePath = require('path').join(
__dirname,
'../../../app/js/LatexRunner'
)
const Path = require('path')
describe('LatexRunner', function() {
beforeEach(function() {
let Timer
this.LatexRunner = SandboxedModule.require(modulePath, {
requires: {
'settings-sharelatex': (this.Settings = {
docker: {
socketPath: '/var/run/docker.sock'
}
}),
'logger-sharelatex': (this.logger = {
log: sinon.stub(),
error: sinon.stub()
}),
'./Metrics': {
Timer: (Timer = class Timer {
done() {}
})
},
'./CommandRunner': (this.CommandRunner = {}),
fs: (this.fs = {
writeFile: sinon.stub().callsArg(2)
})
}
})
this.directory = '/local/compile/directory'
this.mainFile = 'main-file.tex'
this.compiler = 'pdflatex'
this.image = 'example.com/image'
this.callback = sinon.stub()
this.project_id = 'project-id-123'
return (this.env = { foo: '123' })
})
return describe('runLatex', function() {
beforeEach(function() {
return (this.CommandRunner.run = sinon.stub().callsArg(6))
})
describe('normally', function() {
beforeEach(function() {
return this.LatexRunner.runLatex(
this.project_id,
{
directory: this.directory,
mainFile: this.mainFile,
compiler: this.compiler,
timeout: (this.timeout = 42000),
image: this.image,
environment: this.env
},
this.callback
)
})
it('should run the latex command', function() {
return this.CommandRunner.run
.calledWith(
this.project_id,
sinon.match.any,
this.directory,
this.image,
this.timeout,
this.env
)
.should.equal(true)
})
it('should record the stdout and stderr', function() {
this.fs.writeFile
.calledWith(this.directory + '/' + 'output.stdout', 'this is stdout')
.should.equal(true)
this.fs.writeFile
.calledWith(this.directory + '/' + 'output.stderr', 'this is stderr')
.should.equal(true)
})
})
describe('with an .Rtex main file', function() {
beforeEach(function() {
return this.LatexRunner.runLatex(
this.project_id,
{
directory: this.directory,
mainFile: 'main-file.Rtex',
compiler: this.compiler,
image: this.image,
timeout: (this.timeout = 42000)
},
this.callback
)
})
return it('should run the latex command on the equivalent .tex file', function() {
const command = this.CommandRunner.run.args[0][1]
const mainFile = command.slice(-1)[0]
return mainFile.should.equal('$COMPILE_DIR/main-file.tex')
})
})
return describe('with a flags option', function() {
beforeEach(function() {
return this.LatexRunner.runLatex(
this.project_id,
{
directory: this.directory,
mainFile: this.mainFile,
compiler: this.compiler,
image: this.image,
timeout: (this.timeout = 42000),
flags: ['-file-line-error', '-halt-on-error']
},
this.callback
)
})
return it('should include the flags in the command', function() {
const command = this.CommandRunner.run.args[0][1]
const flags = command.filter(
arg => arg === '-file-line-error' || arg === '-halt-on-error'
)
flags.length.should.equal(2)
flags[0].should.equal('-file-line-error')
return flags[1].should.equal('-halt-on-error')
})
})
})
})
| JavaScript | 0.000001 | @@ -1655,10 +1655,98 @@
sArg
-(6
+With(6, null, %7B%0A stdout: 'this is stdout',%0A stderr: 'this is stderr'%0A %7D
))%0A
|
a3c04ada8c5b257425ec317f9cf5b2188cf21a03 | update markers | webmaps/js/rm10k.js | webmaps/js/rm10k.js | function main() {
var map = new L.Map('map', {
zoomControl: false,
center: [44.908, -75.83],
zoom: 15
});
L.tileLayer(
'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ',
maxZoom: 16
}).addTo(map);
// load 10k course route
$.getJSON("10k.geojson", function(data) {
// add GeoJSON layer to the map once the file is loaded
L.geoJson(data).addTo(map);
});
// Define markers
var startIcon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: 'flag-checkered',
iconColor: 'white',
markerColor: 'cadetblue'
});
var km1Icon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '1',
iconColor: 'white',
markerColor: 'cadetblue',
html: "1km"
});
var km2Icon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '1',
iconColor: 'white',
markerColor: 'cadetblue',
html: "2km"
});
var km3Icon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '1',
iconColor: 'white',
markerColor: 'cadetblue',
html: "3km"
});
var km4Icon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '1',
iconColor: 'white',
markerColor: 'cadetblue',
html: "4km"
});
var km5Icon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '1',
iconColor: 'white',
markerColor: 'cadetblue',
html: "5km"
});
var km6Icon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '1',
iconColor: 'white',
markerColor: 'cadetblue',
html: "6km"
});
var km7Icon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '1',
iconColor: 'white',
markerColor: 'cadetblue',
html: "7km"
});
var km8Icon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '1',
iconColor: 'white',
markerColor: 'cadetblue',
html: "8km"
});
var km9Icon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '1',
iconColor: 'white',
markerColor: 'cadetblue',
html: "9km"
});
var defaultIcon = L.AwesomeMarkers.icon({
prefix: 'fa',
icon: '1',
iconColor: 'white',
markerColor: 'cadetblue',
html: "1km"
// load 10k course route features
$.getJSON("features.geojson", function(data) {
//add GeoJSON layer to the map once the file is loaded
L.geoJson(data, {
pointToLayer: function(feature, latlng) {
if (feature.properties.cng_Meters ==
"0.0") {
var marker = L.marker(latlng, {
icon: startIcon
});
if (feature.properties.cng_Meters ==
"1000.0") {
var marker = L.marker(latlng, {
icon: km1Icon
});
if (feature.properties.cng_Meters ==
"2000.0") {
var marker = L.marker(latlng, {
icon: km2Icon
});
if (feature.properties.cng_Meters ==
"3000.0") {
var marker = L.marker(latlng, {
icon: km3Icon
});
if (feature.properties.cng_Meters ==
"4000.0") {
var marker = L.marker(latlng, {
icon: km4Icon
});
if (feature.properties.cng_Meters ==
"5000.0") {
var marker = L.marker(latlng, {
icon: km5Icon
});
if (feature.properties.cng_Meters ==
"6000.0") {
var marker = L.marker(latlng, {
icon: km6Icon
});
if (feature.properties.cng_Meters ==
"7000.0") {
var marker = L.marker(latlng, {
icon: km7Icon
});
if (feature.properties.cng_Meters ==
"8000.0") {
var marker = L.marker(latlng, {
icon: km8Icon
});
if (feature.properties.cng_Meters ==
"9000.0") {
var marker = L.marker(latlng, {
icon: km9Icon
});
} else {
var marker = L.marker(latlng, {
icon: defaultIcon
});
};
return marker;
//return new L.marker(latlng, {
//icon: startIcon
//});
},
//onEachFeature: function(feature, layer) {
//layer.bindPopup(feature.properties.cng_Meters);
//}
}).addTo(map);
});
}
// you could use $(window).load(main);
window.onload = main; | JavaScript | 0.000001 | @@ -3279,32 +3279,39 @@
%7D);%0A%09%09%09%09%09
+%7D else
if (feature.prop
@@ -3323,32 +3323,32 @@
s.cng_Meters ==%0A
-
@@ -3494,32 +3494,39 @@
%7D);%0A%09%09%09%09%09
+%7D else
if (feature.prop
@@ -3709,32 +3709,39 @@
%7D);%0A%09%09%09%09%09
+%7D else
if (feature.prop
@@ -3924,32 +3924,39 @@
%7D);%0A%09%09%09%09%09
+%7D else
if (feature.prop
@@ -4139,32 +4139,39 @@
%7D);%0A%09%09%09%09%09
+%7D else
if (feature.prop
@@ -4354,32 +4354,39 @@
%7D);%0A%09%09%09%09%09
+%7D else
if (feature.prop
@@ -4569,32 +4569,39 @@
%7D);%0A%09%09%09%09%09
+%7D else
if (feature.prop
@@ -4784,32 +4784,39 @@
%7D);%0A%09%09%09%09%09
+%7D else
if (feature.prop
@@ -5002,21 +5002,28 @@
%7D);%0A
-
%09%09%09%09%09
+%7D else
if (feat
|
4ba3607dcbb6ad88a9ee6935504f2dadc91dd0de | Fix typo in Pet mongoose model (#16943) | examples/with-mongodb-mongoose/models/Pet.js | examples/with-mongodb-mongoose/models/Pet.js | import mongoose from 'mongoose'
/* PetSchema will correspond to a collection in your MongoDB database. */
const PetSchema = new mongoose.Schema({
name: {
/* The name of this pet */
type: String,
required: [true, 'Please provide a name for this pet.'],
maxlength: [20, 'Name cannot be more than 60 characters'],
},
owner_name: {
/* The owner of this pet */
type: String,
required: [true, "Please provide the pet owner's name"],
maxlength: [20, "Owner's Name cannot be more than 60 characters"],
},
species: {
/* The species of your pet */
type: String,
required: [true, 'Please specify the species of your pet.'],
maxlength: [30, 'Species specified cannot be more than 40 characters'],
},
age: {
/* Pet's age, if applicable */
type: Number,
},
poddy_trained: {
/* Boolean poddy_trained value, if applicable */
type: Boolean,
},
diet: {
/* List of dietary needs, if applicale */
type: Array,
},
image_url: {
/* Url to pet image */
required: [true, 'Please provide an image url for this pet.'],
type: String,
},
likes: {
/* List of things your pet likes to do */
type: Array,
},
dislikes: {
/* List of things your pet does not like to do */
type: Array,
},
})
export default mongoose.models.Pet || mongoose.model('Pet', PetSchema)
| JavaScript | 0.000034 | @@ -960,16 +960,17 @@
applica
+b
le */%0A%0A
|
7a64e5f5e903a27f07dd84a12bdfb8d1b6de549c | remove file when saved to db | services/server/remotes/attachment/saveFile.js | services/server/remotes/attachment/saveFile.js | const Promise = require('bluebird');
const fs = require('fs-extra');
module.exports = function(Model, app) {
Model.__saveFile = function(options) {
console.log(options);
var props;
var relation = options.instance[options.prop];
return fs.readFile(options.file.path)
.then(function(content) {
props = {
name: options.file.originalname,
size: options.file.size,
downloadDisabled: true,
data: app.secrets.encrypt(content)
};
return Promise.promisify(relation)();
})
.then(function(attachment) {
console.log('attachment', attachment);
if (!attachment) {
return relation.create(props);
}
return relation.update(props);
});
};
};
| JavaScript | 0.000001 | @@ -502,16 +502,97 @@
%7D;%0A%0A
+ return fs.remove(options.file.path);%0A%0A %7D)%0A .then(function() %7B%0A%0A
|
6a614d941df19de4acf85d8385abcae51ffd8481 | Add JS for BS tooltips | webroot/js/local.js | webroot/js/local.js | var CrudView = {
bulkActionForm: function (selector) {
var bulkActionForm = $(selector);
if (bulkActionForm.length) {
bulkActionForm.submit(function (e) {
var action = $('.bulk-action-submit select', bulkActionForm).val();
if (!action) {
return e.preventDefault();
}
bulkActionForm.attr('action', action);
});
}
},
flatpickr: function (selector) {
$(selector).flatpickr();
},
selectize: function (selector) {
$(selector).selectize({plugins: ['remove_button']});
},
select2: function (selector) {
$(selector).each(function () {
var $this = $(this),
config = {theme: 'bootstrap4'};
if (!$this.prop('multiple') && $this.find('option:first').val() === '') {
config.allowClear = true;
config.placeholder = '';
}
$(this).select2(config);
});
},
autocomplete: function (selector) {
$(selector).each(function (i, ele) {
var $ele = $(ele);
$ele.select2({
theme: 'bootstrap4',
minimumInputLength: 1,
ajax: {
delay: 250,
url: $ele.data('url'),
dataType: 'json',
data: function (params) {
var query = {};
query[$ele.data('filter-field') || $ele.attr('name')] = params.term;
if ($ele.data('dependent-on') && $('#' + $ele.data('dependent-on')).val()) {
data[$ele.data('dependent-on-field')] = $('#' + $ele.data('dependent-on')).val();
}
return query;
},
processResults: function (data, params) {
var results = [],
inputType = $ele.data('inputType'),
term = params.term.toLowerCase();
if (data.data) {
$.each(data.data, function(id, text) {
if (text.toLowerCase().indexOf(term) > -1) {
results.push({
id: inputType === 'text' ? text : id,
text: text
});
}
});
}
return {
results: results
};
}
}
});
});
},
dirtyForms: function () {
$.DirtyForms.dialog = false;
$('form[data-dirty-check=1]').dirtyForms();
},
dropdown: function () {
$('.dropdown-toggle').dropdown();
// recommended hack to get dropdowns correctly work inside responsive table
$('.table-responsive').on('show.bs.dropdown', function () {
$('.table-responsive').css( "overflow", "inherit" );
});
$('.table-responsive').on('hide.bs.dropdown', function () {
$('.table-responsive').css( "overflow", "auto" );
})
},
initialize: function () {
this.bulkActionForm('.bulk-actions');
this.flatpickr('.flatpickr');
this.select2('select[multiple]:not(.no-select2), .select2');
this.autocomplete('input.autocomplete, select.autocomplete');
this.dirtyForms();
this.dropdown();
}
};
$(function () {
CrudView.initialize();
});
| JavaScript | 0 | @@ -3349,24 +3349,107 @@
%7D)%0A %7D,%0A%0A
+ tooltip: function () %7B%0A $('%5Bdata-toggle=%22tooltip%22%5D').tooltip();%0A %7D,%0A%0A
initiali
@@ -3737,24 +3737,48 @@
dropdown();%0A
+ this.tooltip();%0A
%7D%0A%7D;%0A%0A$(
|
dede05038ccf38df29547ffc3c72233895d2b0b3 | add http:// prefix into the URL text input | scripts/validate.js | scripts/validate.js | $(document).ready(function () {
});
function validateFields() {
// Validate Project Name
if($("#proname").val() == "") {
$("#wproName").text("必填");
$("#proname").parent().addClass("has-error");
$("#proname").parent().removeClass("has-success");
return false;
}
else {
$("#wproName").text("");
$("#proname").parent().removeClass("has-error");
$("#proname").parent().addClass("has-success");
}
// Validate Project Site
if ($("#projsite").val() == "") {
$("#wproSite").text("必填");
$("#proname").parent().addClass("has-error");
return false;
}
else {
if (isValidURL($("#projsite").val()) == false) {
$("#wproSite").text("请输入一个有效的URL");
$("#proname").parent().addClass("has-warning");
return false;
}
else {
$("#wproSite").text("");
$("#proname").parent().addClass("has-success");
}
}
// Validate Master Repo
if ($("#reprou").val() == "") {
$("#wproRepo").text("必填");
$("#proname").parent().addClass("has-error");
return false;
}
else {
if (isValidRepoURL($("#reprou").val()) == false) {
$("#wproRepo").text("请输入一个有效的URL");
$("#proname").parent().addClass("has-warning");
return false;
}
else {
$("#wproRepo").text("");
$("#proname").parent().addClass("has-success");
}
if($('#reprotype').val() == 'github') {
var existense = $('#reprou').val().indexOf('git');
if(existense == -1) {
$("#wproRepo").text("请输入一个有效的Git/GitHub URL");
$("#proname").parent().addClass("has-warning");
return false
}
}
if($('#reprotype').val() == 'svn') {
var existense = $('#reprou').val().indexOf('svn');
if(existense == -1) {
$("#wproRepo").text("请输入一个有效的SVN URL");
$("#proname").parent().addClass("has-warning");
return false
}
}
}
// Validate Verification Code
var vericode = $("#vericode").val().toLowerCase();
var captchavalue = $("#captchavalue").val().toLowerCase();
if(vericode != captchavalue) {
$("#wproVeri").text("验证码错误");
$("#proname").parent().addClass("has-error");
return false;
}
else {
$("#wproVeri").text("");
$("#proname").parent().addClass("has-success");
}
// Validate Checkbox is checked
if($("#term").is(":checked") == false) {
return false
}
$('#overlay').css('visibility', 'visible');
$('#statusdialog').css('visibility', 'visible');
sendStatusRequest(3000);
return true;
}
function sendStatusRequest(interval) {
var sessionID = $("#sessid").val();
var sendData = {sessionid: sessionID};
$.ajax({
type: "POST",
url: "getstatus.php",
data: sendData
})
.done(function (response) {
$("#statusinfo").text(response);
})
.always(function () {
setTimeout(sendStatusRequest, interval);
});
}
function isValidRepoURL(url){
var repoType = $('#reprotype').val();
var RegExp = "";
if (repoType == "github") {
RegExp = /(http|https|git):\/\/\w+/;
}
else {
RegExp = /(http|https|svn):\/\/\w+/;
}
if(RegExp.test(url)){
return true;
}else{
return false;
}
}
function isValidURL(url) {
var RegExp = /(http|https):\/\/\w+/;
if(RegExp.test(url)){
return true;
}else{
return false;
}
} | JavaScript | 0.000175 | @@ -29,9 +29,75 @@
) %7B%0A
-%09
+ $(%22#projsite%22).val('http://');%0A $(%22#reprou%22).val('http://');
%0A%7D);
|
25c5aad3dbeb8672411b30ee16c1fb6be0ad1392 | fix search | www/js/app.js | www/js/app.js | // (function(){
angular.module('profeSearchStarter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
console.log(cordova.plugins.Keyboard)
}
if(window.StatusBar) {
StatusBar.overlaysWebView(false);
// StatusBar.style(1);
StatusBar.backgroundColorByHexString('#0B4F84') //red
}
// if(window.plugins && window.plugins.AdMob) {
var admobid = {};
if( /(android)/i.test(navigator.userAgent) ) { // for android
admobid = {
banner: 'ca-app-pub-3280086563050737/9945801204', // or DFP format "/6253334/dfp_example_ad"
};
} else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) { // for ios
admobid = {
banner: 'ca-app-pub-3280086563050737/7131935603', // or DFP format "/6253334/dfp_example_ad"
};
} else { // for windows phone
admobid = {
banner: 'ca-app-pub-xxx/zzz', // or DFP format "/6253334/dfp_example_ad"
};
}
// if(AdMob != undefined)
// AdMob.createBanner( {
// adId:admobid.banner,
// position:AdMob.AD_POSITION.BOTTOM_CENTER,
// autoShow:false,
// overlap:false,
// isTesting:true
// } );
}
})
})
.config(function($stateProvider, $urlRouterProvider){
//$stateProvider.state('splash', {
// url: '/',
// views: {
// splash: {
// templateUrl: '../templates/base/splash.html'
// }
// }
// });
$stateProvider.state('home', {
url: '/search',
templateUrl: 'templates/professors/index.html',
controller:"professorController"
});
$urlRouterProvider.otherwise('/search');
})
// var app = angular.module("profesors",[])
// })();
| JavaScript | 0.000014 | @@ -1474,24 +1474,26 @@
;%0A%0A %7D
+);
%0A %7D)%0A
@@ -1498,14 +1498,8 @@
-%0A%7D)%0A
.con
|
8eff1025ef9d14e2f2bf461c8d53e1c950da3fef | fix hardcode container name in ZTDockerClient.__isLinkUpInsideContainer | extension/vpnclient/docker/ZTDockerClient.js | extension/vpnclient/docker/ZTDockerClient.js | /* Copyright 2016 - 2021 Firewalla Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
const log = require('../../../net2/logger.js')(__filename);
const fs = require('fs');
const Promise = require('bluebird');
Promise.promisifyAll(fs);
const exec = require('child-process-promise').exec;
const DockerBaseVPNClient = require('./DockerBaseVPNClient.js');
const YAML = require('../../../vendor_lib/yaml/dist');
const _ = require('lodash');
const f = require('../../../net2/Firewalla.js');
const envFilename = "zerotier-client.env";
const yamlJson = {
"version": "3",
"services": {
"zerotier-client": {
"image": "zerotier/zerotier",
"networks": [
"default"
],
"cap_add": [
"NET_ADMIN"
],
"devices": [
"/dev/net/tun"
],
"env_file": [
envFilename
]
}
},
"networks": {
"default": {
}
}
}
class ZTDockerClient extends DockerBaseVPNClient {
async checkAndSaveProfile(value) {
await exec(`mkdir -p ${this._getDockerConfigDirectory()}`);
const config = value && value.config;
const networkId = config && config.networkId;
if (!networkId)
throw new Error("networkId is not specified");
await this.saveJSONConfig(config);
}
async __prepareAssets() {
const config = await this.loadJSONConfig().catch((err) => {
log.error(`Failed to read config of zerotier client ${this.profileId}`, err.message);
return null;
});
if (!config)
return;
yamlJson.services["zerotier-client"].command = [config.networkId];
await fs.writeFileAsync(`${this._getDockerConfigDirectory()}/docker-compose.yaml`, YAML.stringify(yamlJson), {encoding: "utf8"});
const envs = [];
if (config.identityPublic)
envs.push(`ZEROTIER_IDENTITY_PUBLIC=${config.identityPublic}`);
if (config.identitySecret)
envs.push(`ZEROTIER_IDENTITY_SECRET=${config.identitySecret}`);
if (envs.length > 0)
await fs.writeFileAsync(`${this._getDockerConfigDirectory()}/${envFilename}`, envs.join('\n'), {encoding: "utf8"});
}
static getConfigDirectory() {
return `${f.getHiddenFolder()}/run/zerotier_profile`;
}
static getProtocol() {
return "zerotier";
}
static getKeyNameForInit() {
return "ztvpnClientProfiles";
}
async __isLinkUpInsideContainer() {
const config = await this.loadJSONConfig().catch((err) => {
log.error(`Failed to read config of zerotier client ${this.profileId}`, err.message);
return null;
});
if (!config)
return false;
const resultJson = await exec(`sudo docker exec vpn_hahaha zerotier-cli listnetworks -j`).then(result => JSON.parse(result.stdout.trim())).catch((err) => {
log.error(`Failed to run zerotier-cli listnetworks inside container of ${this.profileId}`, err.message);
return null;
});
if (resultJson && _.isArray(resultJson)) {
const network = resultJson.find(r => r.nwid === config.networkId);
return network && network.status === "OK" || false;
} else {
return false;
}
}
}
module.exports = ZTDockerClient;
| JavaScript | 0.99796 | @@ -3216,18 +3216,34 @@
xec
-vpn_hahaha
+$%7Bthis.getContainerName()%7D
zer
|
af3816f789e38989ec39c93307db2dc2c9b5a258 | Refactor js into a jQuery plugin | extensions/fieldtypes/ff_vz_url/ff_vz_url.js | extensions/fieldtypes/ff_vz_url/ff_vz_url.js | // Ajax link validator for VZ URL fieldtype
// by Eli Van Zoeren (http://elivz.com)
jQuery(document).ready(function() {
jQuery('.vz_url_field').blur(function() {
field = $(this);
jQuery.get(
FT_URL+'ff_vz_url/proxy.php',
{ path: field.val() },
function(response) {
if (response) {
field.next().slideUp();
} else {
field.next().slideDown();
}
}
);
});
}); | JavaScript | 0 | @@ -1,10 +1,13 @@
/
-/
+*%0A *
Ajax li
@@ -40,18 +40,18 @@
eldtype%0A
-//
+ *
by Eli
@@ -80,16 +80,21 @@
vz.com)%0A
+ */%0A%0A
jQuery(d
@@ -150,12 +150,85 @@
d').
-blur
+vzCheckUrl();%0A%7D);%0A%0A%0A// jQuery plugin to check the url and display the result%0A
(fun
@@ -237,110 +237,145 @@
ion(
+$
) %7B%0A
-%09%09field = $(this);%0A%09%09jQuery.get( %0A%09%09%09FT_URL+'ff_vz_url/proxy.php', %0A%09%09%09%7B path: field.val() %7D, %0A%09%09%09
+%0A%09$.fn.vzCheckUrl = function (field) %7B%0A%09%09return this.each(function() %7B%0A%09%09%09var $this = $(this);%0A%09%09%09alert($this.val());%0A%09%09%09$this.blur(
func
@@ -379,28 +379,19 @@
unction(
-response
) %7B
-
%0A%09%09%09%09if
@@ -395,16 +395,30 @@
if (
-response
+ checkIt($this.val())
) %7B
@@ -415,37 +415,37 @@
al()) ) %7B %0A%09%09%09%09%09
-field
+$this
.next().slideUp(
@@ -466,21 +466,21 @@
%7B %0A%09%09%09%09%09
-field
+$this
.next().
@@ -506,18 +506,192 @@
%09%09%09%7D
+);
%0A%09%09
+%7D
);%0A%09
-%7D);%0A%7D
+%09%0A%09%7D%0A%0A%09function checkIt (urlToCheck) %7B%0A%09%09jQuery.get( %0A%09%09%09FT_URL+'ff_vz_url/proxy.php', %0A%09%09%09%7B path: urlToCheck %7D, %0A%09%09%09function(response) %7B return response; %7D%0A%09%09);%0A%09%7D;%0A%0A%7D)(jQuery
);
|
e65ad58d2c9a09be9622f8cab5d5f619886d0a8b | Fix undefined filter value error (#8490) (#9603) | packages/strapi-utils/lib/build-query.js | packages/strapi-utils/lib/build-query.js | 'use strict';
//TODO: move to dbal
const _ = require('lodash');
const parseType = require('./parse-type');
const isAttribute = (model, field) =>
_.has(model.allAttributes, field) || model.primaryKey === field || field === 'id';
/**
* Returns the model, attribute name and association from a path of relation
* @param {Object} options - Options
* @param {Object} options.model - Strapi model
* @param {string} options.field - path of relation / attribute
*/
const getAssociationFromFieldKey = ({ model, field }) => {
const fieldParts = field.split('.');
let tmpModel = model;
let association;
let attribute;
for (let i = 0; i < fieldParts.length; i++) {
const part = fieldParts[i];
attribute = part;
const assoc = tmpModel.associations.find(ast => ast.alias === part);
if (assoc) {
association = assoc;
tmpModel = strapi.db.getModelByAssoc(assoc);
continue;
}
if (!assoc && (!isAttribute(tmpModel, part) || i !== fieldParts.length - 1)) {
const err = new Error(
`Your filters contain a field '${field}' that doesn't appear on your model definition nor it's relations`
);
err.status = 400;
throw err;
}
}
return {
association,
model: tmpModel,
attribute,
};
};
/**
* Cast an input value
* @param {Object} options - Options
* @param {string} options.type - type of the atribute
* @param {*} options.value - value tu cast
* @param {string} options.operator - name of operator
*/
const castInput = ({ type, value, operator }) => {
return Array.isArray(value)
? value.map(val => castValue({ type, operator, value: val }))
: castValue({ type, operator, value: value });
};
/**
* Cast basic values based on attribute type
* @param {Object} options - Options
* @param {string} options.type - type of the atribute
* @param {*} options.value - value tu cast
* @param {string} options.operator - name of operator
*/
const castValue = ({ type, value, operator }) => {
if (operator === 'null') return parseType({ type: 'boolean', value });
return parseType({ type, value });
};
/**
*
* @param {Object} options - Options
* @param {string} options.model - The model
* @param {string} options.field - path of relation / attribute
*/
const normalizeFieldName = ({ model, field }) => {
const fieldPath = field.split('.');
return _.last(fieldPath) === 'id'
? _.initial(fieldPath)
.concat(model.primaryKey)
.join('.')
: fieldPath.join('.');
};
const BOOLEAN_OPERATORS = ['or'];
const hasDeepFilters = ({ where = [], sort = [] }, { minDepth = 1 } = {}) => {
// A query uses deep filtering if some of the clauses contains a sort or a match expression on a field of a relation
// We don't use minDepth here because deep sorting is limited to depth 1
const hasDeepSortClauses = sort.some(({ field }) => field.includes('.'));
const hasDeepWhereClauses = where.some(({ field, operator, value }) => {
if (BOOLEAN_OPERATORS.includes(operator)) {
return value.some(clauses => hasDeepFilters({ where: clauses }));
}
return field.split('.').length > minDepth;
});
return hasDeepSortClauses || hasDeepWhereClauses;
};
const normalizeWhereClauses = (whereClauses, { model }) => {
return whereClauses
.filter(({ value }) => !_.isNull(value))
.map(({ field, operator, value }) => {
if (_.isUndefined(value)) {
const err = new Error(
`The value of field: '${field}', in your where filter, is undefined.`
);
err.status = 400;
throw err;
}
if (BOOLEAN_OPERATORS.includes(operator)) {
return {
field,
operator,
value: value.map(clauses => normalizeWhereClauses(clauses, { model })),
};
}
const { model: assocModel, attribute } = getAssociationFromFieldKey({
model,
field,
});
const { type } = _.get(assocModel, ['allAttributes', attribute], {});
// cast value or array of values
const castedValue = castInput({ type, operator, value });
return {
field: normalizeFieldName({ model, field }),
operator,
value: castedValue,
};
});
};
const normalizeSortClauses = (clauses, { model }) => {
const normalizedClauses = clauses.map(({ field, order }) => ({
field: normalizeFieldName({ model, field }),
order,
}));
normalizedClauses.forEach(({ field }) => {
const fieldDepth = field.split('.').length - 1;
if (fieldDepth === 1) {
// Check if the relational field exists
getAssociationFromFieldKey({ model, field });
} else if (fieldDepth > 1) {
const err = new Error(
`Sorting on ${field} is not possible: you cannot sort at a depth greater than 1`
);
err.status = 400;
throw err;
}
});
return normalizedClauses;
};
/**
*
* @param {Object} options - Options
* @param {Object} options.model - The model for which the query will be built
* @param {Object} options.filters - The filters for the query (start, sort, limit, and where clauses)
* @param {Object} options.rest - In case the database layer requires any other params pass them
*/
const buildQuery = ({ model, filters = {}, ...rest }) => {
const { where, sort } = filters;
// Validate query clauses
if ([where, sort].some(Array.isArray)) {
if (hasDeepFilters({ where, sort }, { minDepth: 2 })) {
strapi.log.warn(
'Deep filtering queries should be used carefully (e.g Can cause performance issues).\nWhen possible build custom routes which will in most case be more optimised.'
);
}
if (sort) {
filters.sort = normalizeSortClauses(sort, { model });
}
if (where) {
// Cast where clauses to match the inner types
filters.where = normalizeWhereClauses(where, { model });
}
}
// call the ORM's buildQuery implementation
return strapi.db.connectors.get(model.orm).buildQuery({ model, filters, ...rest });
};
module.exports = {
buildQuery,
hasDeepFilters,
};
| JavaScript | 0.000043 | @@ -3298,16 +3298,23 @@
ilter((%7B
+ field,
value %7D
@@ -3318,17 +3318,28 @@
e %7D) =%3E
-!
+%7B%0A if (
_.isNull
@@ -3350,57 +3350,45 @@
ue))
-%0A .map((%7B field, operator, value %7D) =%3E %7B%0A
+ %7B%0A return false;%0A %7D else
if
@@ -3424,41 +3424,24 @@
-const err = new Error(%0A
+strapi.log.warn(
%60The
@@ -3505,16 +3505,18 @@
efined.%60
+);
%0A
@@ -3520,64 +3520,98 @@
-);%0A err.status = 400
+return false;%0A %7D%0A return true
;%0A
+%7D)%0A
-throw err;%0A %7D%0A
+.map((%7B field, operator, value %7D) =%3E %7B
%0A
|
410826a027ae373d029cc1fce2f0efe100287fb1 | Update googlemap.js | assets/googlemap.js | assets/googlemap.js | /**
* Google Map manager - renders map and put markers
* Address priority - House Number, Street Direction, Street Name, Street Suffix, City, State, Zip, Country
*/
yii.googleMapManager = (function ($) {
var pub = {
nextAddress: 0,
zeroResult: 0,
delay: 100,
bounds: [],
geocoder: [],
infoWindow: [],
infoWindowOptions: [],
containerId: 'map_canvas',
geocodeData: [],
mapOptions: [],
listeners: [],
renderEmptyMap: true,
map: null,
init: function () {
},
// Init function
initModule: function (options) {
initOptions(options);
google.maps.event.addDomListener(window, 'load', pub.initializeMap());
loadMap();
registerListeners();
},
// Initialize map
initializeMap: function () {
var container = document.getElementById(pub.containerId);
container.style.width = '100%';
container.style.height = '100%';
// Set default center if renderEmptyMap property set to true, and empty geocodeData
if (pub.renderEmptyMap && pub.geocodeData.length == false) {
pub.mapOptions.center = new google.maps.LatLng(28.562635, 16.1397892);
}
pub.map = new google.maps.Map(container, pub.mapOptions);
},
/**
* Get address and place it on map
*/
getAddress: function (search, htmlContent, loadMap) {
var search = location.address;
pub.geocoder.geocode({'address': search}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var place = results[0];
var position = place.geometry.location;
pub.bounds.extend(position);
var marker = new google.maps.Marker({
map: pub.map,
position: position
});
bindInfoWindow(marker, pub.map, pub.infoWindow, htmlContent);
pub.map.fitBounds(pub.bounds);
}
else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
pub.nextAddress--;
pub.delay++;
}
else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
//If first query return zero results, then set address the value of the country
if (location.address != location.country) {
location.address = location.country;
pub.getAddress(location, htmlContent, loadMap)
}
}
loadMap();
});
// If for all search address status is ZERO_RESULTS, then render empty map
if ((pub.geocodeData.length - 1) == pub.zeroResult) {
pub.map.setCenter(new google.maps.LatLng(28.562635, 16.1397892));
}
}
};
/**
* Setup googleMapManager properties
*/
function initOptions(options) {
for (var property in options) {
if (pub.hasOwnProperty(property)) {
pub[property] = options[property];
}
}
pub.bounds = new google.maps.LatLngBounds();
pub.geocoder = new google.maps.Geocoder();
pub.infoWindow = new google.maps.InfoWindow(pub.infoWindowOptions);
pub.map = null;
pub.nextAddress = 0;
pub.zeroResult = 0;
}
/**
* Register listeners
*/
function registerListeners() {
for (listener in pub.listeners) {
if (pub.listeners.hasOwnProperty(listener)) {
var object = pub.listeners[listener].object;
var event = pub.listeners[listener].event;
var handler = pub.listeners[listener].handler;
google.maps.event.addListener(pub[object], event, handler);
}
}
}
/**
* Binds a map marker and infoWindow together on click
* @param marker
* @param map
* @param infoWindow
* @param html
*/
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
/**
* Dynamic call fetchPlaces function with delay
*/
function loadMap() {
if (pub.nextAddress < pub.geocodeData.length) {
var location = {
country: pub.geocodeData[pub.nextAddress].country,
address: pub.geocodeData[pub.nextAddress].address
};
var htmlContent = pub.geocodeData[pub.nextAddress].htmlContent;
setTimeout(function () {
pub.getAddress(location, htmlContent, loadMap)
}, pub.delay);
pub.nextAddress++;
}
}
return pub;
})
(jQuery);
| JavaScript | 0.000001 | @@ -1540,20 +1540,16 @@
-var
search =
|
efc18f028ee3937d60e10d00ab036778ed23ace4 | fix the captcha issue to ignore upper and lower characters | scripts/validate.js | scripts/validate.js | $(document).ready(function () {
});
function validateFields() {
// Validate Project Name
if($("#proname").val() == "") {
$("#wproName").text("必填");
$("#proname").parent().addClass("has-error");
$("#proname").parent().removeClass("has-success");
return false;
}
else {
$("#wproName").text("");
$("#proname").parent().removeClass("has-error");
$("#proname").parent().addClass("has-success");
}
// Validate Project Site
if ($("#projsite").val() == "") {
$("#wproSite").text("必填");
$("#proname").parent().addClass("has-error");
return false;
}
else {
if (isValidURL($("#projsite").val()) == false) {
$("#wproSite").text("请输入一个有效的URL");
$("#proname").parent().addClass("has-warning");
return false;
}
else {
$("#wproSite").text("");
$("#proname").parent().addClass("has-success");
}
}
// Validate Master Repo
if ($("#reprou").val() == "") {
$("#wproRepo").text("必填");
$("#proname").parent().addClass("has-error");
return false;
}
else {
if (isValidRepoURL($("#reprou").val()) == false) {
$("#wproRepo").text("请输入一个有效的URL");
$("#proname").parent().addClass("has-warning");
return false;
}
else {
$("#wproRepo").text("");
$("#proname").parent().addClass("has-success");
}
if($('#reprotype').val() == 'github') {
var existense = $('#reprou').val().indexOf('git');
if(existense == -1) {
$("#wproRepo").text("请输入一个有效的Git/GitHub URL");
$("#proname").parent().addClass("has-warning");
return false
}
}
if($('#reprotype').val() == 'svn') {
var existense = $('#reprou').val().indexOf('svn');
if(existense == -1) {
$("#wproRepo").text("请输入一个有效的SVN URL");
$("#proname").parent().addClass("has-warning");
return false
}
}
}
// Validate Verification Code
if($("#vericode").val() != $("#captchavalue").val()) {
$("#wproVeri").text("验证码错误");
$("#proname").parent().addClass("has-error");
return false;
}
else {
$("#wproVeri").text("");
$("#proname").parent().addClass("has-success");
}
// Validate Checkbox is checked
if($("#term").is(":checked") == false) {
return false
}
$('#overlay').css('visibility', 'visible');
$('#statusdialog').css('visibility', 'visible');
sendStatusRequest(3000);
return true;
}
function sendStatusRequest(interval) {
var sessionID = $("#sessid").val();
var sendData = {sessionid: sessionID};
$.ajax({
type: "POST",
url: "getstatus.php",
data: sendData
})
.done(function (response) {
$("#statusinfo").text(response);
})
.always(function () {
setTimeout(sendStatusRequest, interval);
});
}
function isValidRepoURL(url){
var repoType = $('#reprotype').val();
var RegExp = "";
if (repoType == "github") {
RegExp = /(http|https|git):\/\/\w+/;
}
else {
RegExp = /(http|https|svn):\/\/\w+/;
}
if(RegExp.test(url)){
return true;
}else{
return false;
}
}
function isValidURL(url) {
var RegExp = /(http|https):\/\/\w+/;
if(RegExp.test(url)){
return true;
}else{
return false;
}
} | JavaScript | 0.000074 | @@ -2190,27 +2190,39 @@
on Code%0A
-if(
+var vericode =
$(%22#vericode
@@ -2233,36 +2233,118 @@
al()
- != $(%22#captchavalue%22).val()
+.toLowerCase();%0A var captchavalue = $(%22#captchavalue%22).val().toLowerCase();%0A if(vericode != captchavalue
) %7B%0A
|
14523a374ee44bfa133f59a02f89b8f8035e93fa | Change display method to just calculate the compiled sources and emit an event instead of logging directly | packages/truffle-compile/legacy/index.js | packages/truffle-compile/legacy/index.js | const path = require("path");
const Profiler = require("../profiler");
const CompilerSupplier = require("../compilerSupplier");
const expect = require("truffle-expect");
const findContracts = require("truffle-contract-sources");
const Config = require("truffle-config");
const debug = require("debug")("compile"); // eslint-disable-line no-unused-vars
const { run } = require("../run");
const { normalizeOptions } = require("./options");
const { shimOutput } = require("./shims");
// Most basic of the compile commands. Takes a hash of sources, where
// the keys are file or module paths and the values are the bodies of
// the contracts. Does not evaulate dependencies that aren't already given.
//
// Default options:
// {
// strict: false,
// quiet: false,
// logger: console
// }
const compile = function(sources, options, callback) {
if (typeof options === "function") {
callback = options;
options = {};
}
options = normalizeOptions(options);
run(sources, options)
.then(shimOutput)
.then(([...returnVals]) => callback(null, ...returnVals))
.catch(callback);
};
// contracts_directory: String. Directory where .sol files can be found.
// quiet: Boolean. Suppress output. Defaults to false.
// strict: Boolean. Return compiler warnings as errors. Defaults to false.
compile.all = function(options, callback) {
findContracts(options.contracts_directory, function(err, files) {
if (err) return callback(err);
options.paths = files;
compile.with_dependencies(options, callback);
});
};
// contracts_directory: String. Directory where .sol files can be found.
// build_directory: String. Optional. Directory where .sol.js files can be found. Only required if `all` is false.
// all: Boolean. Compile all sources found. Defaults to true. If false, will compare sources against built files
// in the build directory to see what needs to be compiled.
// quiet: Boolean. Suppress output. Defaults to false.
// strict: Boolean. Return compiler warnings as errors. Defaults to false.
compile.necessary = function(options, callback) {
options.logger = options.logger || console;
Profiler.updated(options, function(err, updated) {
if (err) return callback(err);
if (updated.length === 0 && options.quiet !== true) {
return callback(null, [], {});
}
options.paths = updated;
compile.with_dependencies(options, callback);
});
};
compile.with_dependencies = function(options, callback) {
var self = this;
options.logger = options.logger || console;
options.contracts_directory = options.contracts_directory || process.cwd();
expect.options(options, [
"paths",
"working_directory",
"contracts_directory",
"resolver"
]);
var config = Config.default().merge(options);
Profiler.required_sources(
config.with({
paths: options.paths,
base_path: options.contracts_directory,
resolver: options.resolver
}),
(err, allSources, required) => {
if (err) return callback(err);
var hasTargets = required.length;
hasTargets
? self.display(required, options)
: self.display(allSources, options);
options.compilationTargets = required;
compile(allSources, options, callback);
}
);
};
compile.display = function(paths, options) {
if (options.quiet !== true) {
if (!Array.isArray(paths)) {
paths = Object.keys(paths);
}
const blacklistRegex = /^truffle\//;
paths.sort().forEach(contract => {
if (path.isAbsolute(contract)) {
contract =
"." + path.sep + path.relative(options.working_directory, contract);
}
if (contract.match(blacklistRegex)) return;
options.logger.log("> Compiling " + contract);
});
}
};
compile.CompilerSupplier = CompilerSupplier;
module.exports = compile;
| JavaScript | 0 | @@ -3087,23 +3087,40 @@
? self.
-display
+calculateCompiledSources
(require
@@ -3146,23 +3146,40 @@
: self.
-display
+calculateCompiledSources
(allSour
@@ -3312,15 +3312,32 @@
ile.
-display
+calculateCompiledSources
= f
@@ -3366,42 +3366,8 @@
) %7B%0A
- if (options.quiet !== true) %7B%0A
if
@@ -3390,24 +3390,16 @@
(paths))
- %7B%0A
paths =
@@ -3419,25 +3419,17 @@
paths);%0A
- %7D%0A%0A
+%0A
const
@@ -3466,30 +3466,50 @@
%0A%0A
-
+const sources =
paths
+%0A
.sort()
-.forEach
+%0A .map
(con
@@ -3724,66 +3724,146 @@
-options.logger.log(%22%3E Compiling %22 + contract);%0A %7D);%0A %7D
+return contract;%0A %7D)%0A .filter(contract =%3E contract);%0A options.events.emit(%22compile:compiledSources%22, %7B sourceFileNames: sources %7D);
%0A%7D;%0A
|
46c7c3a9fe9d4717d033a0badee7186d532d5afc | Create login functionality in Ally framework | plugins/gui-core/gui-resources/scripts/js/views/auth.js | plugins/gui-core/gui-resources/scripts/js/views/auth.js | define
([
'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
var AuthLogin = function(username, password, logintoken){
var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
authLogin = new $.rest('Authentication');
authLogin.resetData().insert({
UserName: username,
LoginToken: logintoken,
HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
}).done(function(user){
localStorage.setItem('superdesk.login.session', user.Session);
localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.UserName);
localStorage.setItem('superdesk.login.email', user.EMail);
$(authLogin).trigger('success');
});
return $(authLogin);
},
AuthToken = function(username, password) {
var authToken = new $.rest('Authentication');
authToken.resetData().select({ userName: username }).done(
function(data){
authLogin = AuthLogin(username, password, data.Token);
authLogin.on('failed', function(){
$(authToken).trigger('failed', 'authToken');
}).on('success', function(){
$(authToken).trigger('success');
});
}
);
return $(authToken);
},
AuthApp =
});
return $(authToken);
},
AuthApp =
{
success: $.noop,
showed: false,
require: function()
{
if(AuthApp.showed) return;
var self = this; // rest
AuthApp.showed = true;
$.tmpl('auth', null, function(e, o)
{
var dialog = $(o).eq(0).dialog
({
draggable: false,
resizable: false,
modal: true,
width: "40.1709%",
buttons:
[
{ text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
{ text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
]
}),
form = dialog.find('form');
form.off('submit.superdesk')
.on('submit.superdesk', function(event)
{
var username = $(this).find('#username'), password=$(this).find('#password');
AuthToken(username.val(), password.val()).on('failed',function(evt, type){
username.val('');
password.val('')
}).on('success', function(){
AuthApp.success && AuthApp.success.apply();
$(dialog).dialog('close');
self.showed = false;
});
event.preventDefault();
});
});
}
};
return AuthApp;
}); | JavaScript | 0 | @@ -838,19 +838,304 @@
.EMail);
+%0A
%09%09%09
+$.restAuth.prototype.requestOptions.headers.Authorization = localStorage.getItem('superdesk.login.session');%0A%09%09%09superdesk.login = %7BId: localStorage.getItem('superdesk.login.id'), Name: localStorage.getItem('superdesk.login.name'), EMail: localStorage.getItem('superdesk.login.email')%7D
%0A%09%09%09$(au
@@ -2821,16 +2821,18 @@
%09%0A%09%09%09%09%09%09
+//
username
|
9882d6a5a973114cda553d4047f020c5ff859fbc | create report | lib/router/restful.js | lib/router/restful.js | const express = require('express');
const router = express.Router();
const select = require('../models-sqlite3/sql/select');
const deleteAll = require('../models-sqlite3/sql/delete');
const update = require('../models-sqlite3/sql/update');
const insert = require('../models-sqlite3/sql/insert');
const db = require('../models-sqlite3').getdb;
const validateSelect = require('../models-sqlite3/validate').select.validate;
const validateDelete = require('../models-sqlite3/validate').delete.validate;
var io = undefined;
router.get(['/restful/:_tbl/:_where/:_value', '/restful/:_tbl/:_value', '/restful/:_tbl'], function (req, res) {
if (req.params._tbl === 'Log') {
if (req.params._value !== undefined) {
validateSelect({_tbl: 'tblUser', _where: 'id', id: req.params._value}).then((data) => {
select[data._verb](db(), data).then((result)=>{
require('../logger').queryUserLog({account: result.account}).then((logdata)=>{res.json({data: logdata});}).catch((err) => res.status(400).send(err));
}).catch((err)=>res.status(400).send(err));
}).catch( (err) => {
res.status(400).send(err);
});
} else {
require('../logger').queryUserLog({account: req.user.account}).then((logdata)=>{res.json({data: logdata});}).catch((err) => res.status(400).send(err));
}
} else {
if ((req.params._where === undefined) && (req.params._value !== undefined)) {
req.params._where = "id";
}
if (req.params._value !== undefined) {
req.params[req.params._where] = req.params._value;
}
req.params._tbl = "tbl" + req.params._tbl;
validateSelect(req.params).then((data) => {
select[data._verb](db(), data).then((result)=>{
delete result.password;// dont send password anyway
res.json(result);
}).catch((err)=>{res.status(400).send('not exsists')});
}).catch( (err) => {
res.status(400).send(err);
});
}
});
router.delete(['/restful/:_tbl/:_where/:_value', '/restful/:_tbl/:_value', '/restful/:_tbl'], function (req, res, next) {
if ((req.params._where === undefined) && (req.params._value !== undefined)) {
req.params._where = "id";
}
if (req.params._value !== undefined) {
req.params[req.params._where] = req.params._value;
}
var urlobject = req.params._tbl;
req.params._tbl = "tbl" + req.params._tbl;
validateDelete(req.params).then((data) => {
deleteAll[data._verb](db(), data).then((result)=>{
//you can only send text
if (result.changes === 0) {
//conflict
res.status(409).send("cant delete");
} else {
//log a delete
require('../logger').info('delete %s by account=%s from remote ip=%s', JSON.stringify(data), req.user.account, req.connection.remoteAddress);
res.status(200).send({changes: result.changes});
//tell all browsers that a delete query on a table exec
emit(urlobject);
}
}).catch((err)=>{
if (err.code === 'SQLITE_CONSTRAINT') {
//conflict
res.status(409).send('related record exists');
} else {
res.status(400).send(err);
}
});
}).catch( (err) => {
res.status(400).send(err);
});
});
//insert
router.post('/restful/:_tbl', function (req, res, next) {
var data = req.body;
var urlobject = req.params._tbl;
data._tbl = 'tbl' + req.params._tbl;
insert.insertjson(db(), data).then((result)=>{
//log an insert
require('../logger').info('insert %s record_id=%s by account=%s from remote ip=%s', JSON.stringify(data), req.user.account, req.connection.remoteAddress);
res.status(200).send({lastID: result.lastID});
//tell all browsers that an insert query on a table exec
emit(urlobject);
}).catch((err)=>{
res.status(400).send(err);
});
});
//update
router.put('/restful/:_tbl/:_value', function (req, res, next) {
var data = req.body;
//log an update
data._where = 'id';
data._value = req.params._value;
var urlobject = req.params._tbl;
data._tbl = 'tbl' + req.params._tbl;
update.updatemultiple(db(), data).then((result)=>{
//you can only send text
if (result.changes === 0) {
//conflict
res.status(409).send("cant update");
} else {
//log an update
require('../logger').info('update %s record_id=%s by account=%s from remote ip=%s', JSON.stringify(data), result.lastID, data._value, req.connection.remoteAddress);
res.status(200).send({changes: result.changes});
//tell all browsers that a delete query on a table exec
emit(urlobject);
}
}).catch((err)=>{
if (err.code === 'SQLITE_CONSTRAINT') {
//conflict
res.status(409).send('related record exists');
} else {
res.status(400).send(err);
}
});
});
var emit = function(urlobject) {
io.sockets.emit(urlobject);
if(['ReportClassVariable'].includes(urlobject)) {
io.sockets.emit('vVariableDef');
};
};
module.exports = function(io_) {
//socketIO
io = io_;
return router
};
| JavaScript | 0.000005 | @@ -3562,16 +3562,182 @@
s._tbl;%0A
+ if(data._tbl === 'tblReport') %7B%0A insert.createreport(db(), data).then((result)=%3E%7B%0A%0A %7D).catch((err)=%3E%7B%0A res.status(400).send(err);%0A %7D);%0A %7D else %7B%0A
insert
@@ -3779,24 +3779,26 @@
t)=%3E%7B%0A
+
//log an ins
@@ -3803,24 +3803,26 @@
nsert%0A
+
+
require('../
@@ -3966,24 +3966,26 @@
ess);%0A
+
res.status(2
@@ -4015,24 +4015,26 @@
t.lastID%7D);%0A
+
//tell
@@ -4086,24 +4086,26 @@
exec%0A
+
+
emit(urlobje
@@ -4109,16 +4109,18 @@
bject);%0A
+
%7D).cat
@@ -4129,32 +4129,34 @@
((err)=%3E%7B%0A
+
res.status(400).
@@ -4164,28 +4164,34 @@
end(err);%0A
+
+
%7D);%0A
+ %7D%0A
%7D);%0A//update
|
9c5329ef91729f2a70932df0c77d5589bed36971 | Create login functionality in Ally framework | plugins/gui-core/gui-resources/scripts/js/views/auth.js | plugins/gui-core/gui-resources/scripts/js/views/auth.js | define
([
'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
<<<<<<< HEAD
var AuthLogin = function(username, password, logintoken){
=======
var AuthDetails = function(username){
var authDetails = new $.rest('Superdesk/User');
authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){
var user = users.UserList[0];
localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.Name);
localStorage.setItem('superdesk.login.email', user.EMail);
});
return $(authDetails);
},
AuthLogin = function(username, password, logintoken){
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
authLogin = new $.rest('Authentication');
authLogin.resetData().insert({
UserName: username,
LoginToken: logintoken,
HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
}).done(function(user){
localStorage.setItem('superdesk.login.session', user.Session);
localStorage.setItem('superdesk.login.id', user.Id);
localStorage.setItem('superdesk.login.name', user.UserName);
localStorage.setItem('superdesk.login.email', user.EMail);
$(authLogin).trigger('success');
});
return $(authLogin);
},
AuthToken = function(username, password) {
var authToken = new $.rest('Authentication');
authToken.resetData().select({ userName: username }).done(
function(data){
authLogin = AuthLogin(username, password, data.Token);
authLogin.on('failed', function(){
$(authToken).trigger('failed', 'authToken');
}).on('success', function(){
$(authToken).trigger('success');
});
}
);
return $(authToken);
},
AuthApp =
{
success: $.noop,
require: function()
{
if(this.showed) return;
var self = this; // rest
self.showed = true;
$.tmpl('auth', null, function(e, o)
{
var dialog = $(o).eq(0).dialog
({
draggable: false,
resizable: false,
modal: true,
width: "40.1709%",
buttons:
[
{ text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
{ text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
]
}),
form = dialog.find('form');
form.off('submit.superdesk')//
.on('submit.superdesk', function(event)
{
var username = $(this).find('#username'), password=$(this).find('#password');
AuthToken(username.val(), password.val()).on('failed',function(evt, type){
username.val('');
password.val('')
}).on('success', function(){
AuthApp.success && AuthApp.success.apply();
$(dialog).dialog('close');
self.showed = false;
});
event.preventDefault();
});
});
}
};
return AuthApp;
}); | JavaScript | 0 | @@ -174,21 +174,8 @@
)%0A%7B%0A
-%3C%3C%3C%3C%3C%3C%3C HEAD%0A
@@ -236,558 +236,8 @@
n)%7B%0A
-=======%0A var AuthDetails = function(username)%7B%0A%09%09var authDetails = new $.rest('Superdesk/User');%0A%09%09authDetails.resetData().xfilter('Name,Id,EMail').select(%7B name: username %7D).done(function(users)%7B%0A%09%09%09var user = users.UserList%5B0%5D;%0A%09%09%09localStorage.setItem('superdesk.login.id', user.Id);%0A%09%09%09localStorage.setItem('superdesk.login.name', user.Name);%0A%09%09%09localStorage.setItem('superdesk.login.email', user.EMail);%0A%09%09%7D);%0A%09%09return $(authDetails);%0A%09%7D,%0A%09AuthLogin = function(username, password, logintoken)%7B%0A%3E%3E%3E%3E%3E%3E%3E 718d8c014dc7f1c47606de731769286a6bcebb81%0A
%09%09va
|
9f329556cfbb83f3fee630d9ade9184253a8d772 | Update app.js | www/js/app.js | www/js/app.js | "use strict";
angular.module('myApp', ['ionic','ngCordova','myApp.controllers'])
.run(function($ionicPlatform) {
document.addEventListener("deviceready", function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
}, false);
// $cordovaStatusbar.overlaysWebView(true);
// $ionicPlatform.ready(function() {
// if(window.cordova && window.cordova.plugins.Keyboard) {
// cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// }
// if(window.StatusBar) {
// StatusBar.styleDefault();
// }
// });
})
;
| JavaScript | 0.000002 | @@ -108,13 +108,32 @@
form
+, $cordovaStatusbar
) %7B%09%0A
-
@@ -182,24 +182,26 @@
unction() %7B%0A
+//
if(windo
@@ -244,24 +244,26 @@
Keyboard) %7B%0A
+//
cordov
@@ -313,22 +313,26 @@
(true);%0A
+//
%7D%0A
+//
if(w
@@ -350,16 +350,18 @@
sBar) %7B%0A
+//
St
@@ -384,22 +384,70 @@
ault();%0A
+//
%7D%0A
+ $cordovaStatusbar.overlaysWebView(true);%0A%0A
%7D, fa
|
d22f785285267a612d5986f9e0bd8884c8efa688 | remove OneTouchUltra2 from the UI | lib/state/appState.js | lib/state/appState.js | /*
* == BSD2 LICENSE ==
* Copyright (c) 2014, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
var _ = require('lodash');
var mapcat = require('../core/mapcat');
var config = require('../config');
var appState = {};
appState.bindApp = function(app) {
this.app = app;
return this;
};
appState.getInitial = function() {
var uploads = [
{
name: 'Insulet OmniPod',
key: 'omnipod',
source: {type: 'block', driverId: 'InsuletOmniPod', extension: '.ibf'}
},
{
name: 'Dexcom G4 Platinum',
key: 'dexcom',
source: {type: 'device', driverId: 'DexcomG4'}
},
{
name: 'Abbott FreeStyle Precision Xtra',
key: 'precisionxtra',
source: {type: 'device', driverId: 'AbbottFreeStyle'}
},
// {
// name: 'Asante SNAP',
// key: 'asantesnap',
// source: {type: 'device', driverId: 'AsanteSNAP'}
// }
{
name: 'OneTouchUltra2 (In development!)',
key: 'onetouchultra2',
source: {type: 'device', driverId: 'OneTouchUltra2'}
}
];
if (config.CARELINK) {
uploads.unshift({name: 'Medtronic MiniMed (CareLink)', key: 'carelink', source: {type: 'carelink'}});
}
return {
dropMenu: false,
page: 'loading',
user: null,
targetId: null,
targetDevices: [],
uploads: uploads
};
};
appState.isLoggedIn = function() {
return Boolean(this.app.state.user);
};
// For now we only support only one upload at a time,
// so the "current" upload is the first one of the list "in progress"
appState.currentUploadIndex = function() {
return _.findIndex(this.app.state.uploads, this._isUploadInProgress);
};
appState._isUploadInProgress = function(upload) {
if (upload.progress && !upload.progress.finish) {
return true;
}
return false;
};
appState.hasUploadInProgress = function() {
return Boolean(this.currentUploadIndex() !== -1);
};
appState.deviceCount = function() {
return _.filter(this.app.state.uploads, function(upload) {
return upload.source.type === 'device';
}).length;
};
appState.uploadsWithFlags = function() {
var self = this;
var currentUploadIndex = this.currentUploadIndex();
var targetedUploads = _.filter(this.app.state.uploads, function(upload) {
return _.contains(self.app.state.targetDevices, upload.key);
});
return _.map(targetedUploads, function(upload, index) {
upload = _.clone(upload);
var source = upload.source || {};
if (currentUploadIndex !== -1 && currentUploadIndex !== index) {
upload.disabled = true;
}
if (source.type === 'device' &&
source.connected === false) {
upload.disconnected = true;
upload.disabled = true;
}
if (source.type === 'carelink') {
upload.carelink = true;
}
if (self._isUploadInProgress(upload)) {
upload.uploading = true;
if (source.type === 'carelink' && upload.progress.step === 'start') {
upload.fetchingCarelinkData = true;
}
}
if (!upload.uploading && upload.progress) {
upload.completed = true;
var instance = upload.progress;
if (instance.success) {
upload.successful = true;
}
else if (instance.error) {
upload.failed = true;
upload.error = instance.error;
}
}
return upload;
});
};
module.exports = appState;
| JavaScript | 0 | @@ -1489,30 +1489,36 @@
// %7D%0A
+ //
%7B%0A
+ //
name: 'On
@@ -1550,26 +1550,29 @@
ent!)',%0A
+//
+
key: 'onetou
@@ -1581,24 +1581,27 @@
ultra2',%0A
+ //
source: %7B
@@ -1643,24 +1643,27 @@
Ultra2'%7D%0A
+ //
%7D%0A %5D;%0A%0A i
|
5c09f60d9e0f33863809196ea8579b01ad95fbdc | Correct warning for deprecated text/m-objects | lib/transform/html.js | lib/transform/html.js |
var rebase = require("../rebase");
var minifyJavaScript = require("../minify-javascript");
var jshint = require("../jshint").JSHINT;
var File = require("../file");
var transformCss = require("./css");
var domToHtml = require("jsdom/lib/jsdom/browser/domtohtml").domToHtml;
var Node = require("jsdom").level(1).Node;
var URL = require("url2");
var minifyHtml = require("html-minifier").minify;
module.exports = transformHtml;
function transformHtml(file, config) {
// visits the DOM, updating relative URL's that cross package boundaries
transformDocument(file, config);
try {
file.utf8 = minifyHtml(file.utf8, {
removeComments: true,
collapseBooleanLiterals: true,
//collapseWhitespace: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeEmptyAttributes: true
});
} catch (exception) {
config.out.warn("Could not minify " + file.path);
config.out.warn(exception.message);
}
var definedContent = (
'montageDefine(' +
JSON.stringify(file.package.hash) + ',' +
JSON.stringify(file.relativeLocation) + ',' +
JSON.stringify({
text: file.utf8
}) +
')'
);
definedContent = minifyJavaScript(definedContent, file.path);
var definedFile = new File({
utf8: definedContent,
location: file.location + ".load.js",
buildLocation: file.buildLocation + ".load.js",
relativeLocation: file.relativeLocatio + ".load.js",
package: file.package
})
config.files[definedFile.location] = definedFile;
file.package.files[definedFile.relativeLocation] = definedFile;
}
function transformDocument(file, config) {
var appPackage = file.package.getPackage({main: true});
var manifestLocation = URL.resolve(appPackage.buildLocation, "manifest.appcache");
visit(file.document, function (element) {
if (element.nodeType === Node.ELEMENT_NODE) {
rebaseAttribute(element, "href", file, config);
rebaseAttribute(element, "src", file, config);
if (element.tagName === "HTML" && appPackage.packageDescription.manifest) {
var relativeLocation = URL.relative(file.buildLocation, manifestLocation);
element.setAttribute("manifest", relativeLocation);
}
if (element.tagName === "STYLE") {
rebaseStyleTag(element, file, config);
}
if (element.tagName === "SCRIPT") {
rebaseScriptTag(element, file, config);
}
}
});
}
function rebaseStyleTag(element, file, config) {
var input = getText(element);
var output = transformCss.rebase(input, file, config);
setText(element, output, file.document);
}
function rebaseScriptTag(element, file, config) {
var type;
if (element.hasAttribute("type")) {
type = element.getAttribute("type");
} else {
type = "application/javascript";
}
if (type === "application/javascript" || type === "text/javascript") {
if (config.lint && file.package.isMainPackage()) {
// content vs src
if (element.hasAttribute("src") && getText(element).trim() !== "") {
config.out.warn("A script tag must only have either a src or content in " + file.path);
}
// mime type
if (type === "text/javascript") {
config.out.warn("Proper MIME type for JavaScript is application/javascript and should be omitted in " + file.path);
} else if (element.hasAttribute("type")) {
config.out.warn("Script MIME type should be omitted if application/javascript in " + file.path);
}
// content
if (!jshint(getText(element))) {
config.out.warn("JSHints for <script>: " + file.path);
}
}
if (element.hasAttribute("type")) {
element.removeAttribute("type");
}
if (config.minify) {
var minified;
try {
minified = minifyJavaScript(getText(element), file.path);
} catch (exception) {
config.out.warn("JavaScript parse error in " + file.path + ": " + exception.message);
}
if (minified) {
setText(element, minified, file.document);
}
}
} else if (type === "text/m-objects") {
config.out.warn("Deprecated text/m-objects block in " + file.path + ". Use montage/serialization.");
} else if (type === "text/montage-serialization") {
try {
if (config.minify) {
setText(element, JSON.stringify(JSON.parse(getText(element))), file.document);
}
} catch (error) {
if (error instanceof SyntaxError) {
config.out.warn("Syntax Error in Montage Serialization in " + file.path);
} else {
throw error;
}
}
} else if (type === "x-shader/x-fragment") {
} else if (type === "x-shader/x-vertex") {
} else {
config.out.warn("Unrecognized script type " + JSON.stringify(type) + " in " + file.path);
}
}
function visit(element, visitor) {
visitor(element);
element = element.firstChild;
while (element) {
visit(element, visitor);
element = element.nextSibling;
}
}
function rebaseAttribute(element, attribute, file, config) {
if (element.hasAttribute(attribute)) {
var value = element.getAttribute(attribute);
var rebasedValue = rebase(value, file, config)
element.setAttribute(attribute, rebasedValue);
}
}
function getText(element) {
return domToHtml(element._childNodes, true, true);
}
function setText(element, text, document) {
element.innerHTML = "";
element.appendChild(document.createTextNode(text));
}
| JavaScript | 0.000001 | @@ -4617,16 +4617,21 @@
Use
+text/
montage
-/
+-
seri
|
f6ba83db1af7dd0178177806c6dd59dd163ca3b0 | add qio.makeTree before rename | lib/utils/fs-utils.js | lib/utils/fs-utils.js | /**
* Created by elad.benedict on 1/18/2016.
*/
var logger = require('../../common/logger').getLogger('fs-utils');
var config = require('./../../common/Configuration');
var _ = require('underscore');
var qio = require('q-io/fs');
var Q = require('q');
var t = require('tmp');
var path = require('path');
var mkdirp = require('mkdirp');
module.exports = (function(){
var tempNameP = Q.denodeify(t.tmpName);
function writeFileAtomically(targetPath, content){
return tempNameP().then(function(tempPath) {
return qio.write(tempPath, content).then(function () {
return qio.move(tempPath, targetPath);
});
});
}
function cleanFolder(targetPath, newName) {
// 1. Remove folder if exists
return qio.isDirectory(targetPath).then(function (res) {
if (res) {
logger.debug("Removing directory " + targetPath);
var renamedFolderName = path.join(config.get("oldContentFolderPath"), newName + '_' + (new Date()).getTime().toString());
return qio.rename(targetPath, renamedFolderName);
}
}).then(function () {
// 2. Create (clean) folder
logger.debug("Removed directory: %s and recreating it", targetPath);
var mkdirFunc = Q.denodeify(mkdirp);
return mkdirFunc(targetPath);
});
}
function existsAndNonZero(path) {
return qio.stat(path)
.then(function(file) {
return !(file.size === 0);
}, function() {
return false;
});
}
return {
writeFileAtomically : writeFileAtomically,
cleanFolder : cleanFolder,
existsAndNonZero : existsAndNonZero
};
})();
| JavaScript | 0 | @@ -1052,16 +1052,94 @@
ing());%0A
+ return qio.makeTree(renamedFolderName).then(function () %7B%0A
@@ -1196,16 +1196,35 @@
rName);%0A
+ %7D)%0A
|
087d7e55e20407f705d6481e72eacd3cb43b75d1 | Implement image formatting. | lib/writer/xelatex.js | lib/writer/xelatex.js | var assert = require('assert');
var wrap = require('../wrap');
module.exports = function formatText(text, options) {
assert(text.shift() == 'text');
var result = [];
text.forEach(function(block) {
result.push(formatBlock(block));
});
var output = result.join('\n\n') + '\n';
if (options.standalone)
output = header + output + footer;
return output;
};
function formatBlock(block) {
var type = block.shift();
var attr = block.shift();
switch (type) {
case 'divider': return '\\hrulefill';
case 'image': return formatImage(block);
case 'heading': return '\\' + repeat('sub', attr.level-1) + 'section{' + formatSpans(block) + '}';
case 'bulleted': return wordWrap(formatSpans(block), '\\item ');
case 'numbered': return wordWrap(formatSpans(block), '\\item ');
case 'quote': return '\\begin{quotation}\n' + wordWrap(formatSpans(block)) + '\n\\end{quotation}';
case 'link': return null;
case 'note': return null;
case 'verbatim': return '\\begin{verbatim}\n' + formatSpans(block) + '\n\\end{verbatim}';
case 'formula': return '\\begin{equation}\n' + formatSpans(block) + '\n\\end{equation}';
default: return wordWrap(formatSpans(block));
};
};
var formatImage = function(spans) {
return formatSpans(spans);
};
function wordWrap(text, prefix, firstPrefix) {
return wrap(text, prefix, firstPrefix, '\\\\');
};
function formatSpans(spans) {
return spans.map(formatSpan).join('');
}
function formatSpan(span) {
var type = span.shift();
var text = span.shift();
assert(span.length == 0);
switch (type) {
case 'emph': return '\\emph{' + escape(text) + '}';
case 'strong': return '\\textbf{' + escape(text) + '}';
case 'code': return '\\texttt{' + escape(text) + '}';
case 'math': return '$' + escape(text) + '$';
case 'url': return '\\url{' + escape(text) + '}';
case 'linktext': return null;
case 'linkref': return null;
case 'noteref': return null;
default: return escape(text);
};
};
function escape(str) {
return str.
replace(/\\/g,'\\textbackslash').
replace(/{/g,'\\{').
replace(/}/g,'\\}').
replace(/~/g,'\\~{}').
replace(/\$/g,'\\$');
};
function repeat(str, times) {
return new Array(times+1).join(str);
};
var header =
'\\documentclass[10pt]{article}\n' +
'\n' +
'\\begin{document}\n\n';
var footer =
'\n\n\\end{document}\n';
| JavaScript | 0 | @@ -1242,32 +1242,241 @@
nction(spans) %7B%0A
+ if (spans.length %3E 0 && spans%5B0%5D%5B0%5D === 'url') %7B%0A var url = spans%5B0%5D%5B1%5D;%0A var str =%0A'%5C%5Cbegin%7Bfigure%7D%5BH%5D%5Cn' +%0A'%5C%5Ccentering%5Cn' +%0A'%5C%5Cincludegraphics%7B' + url + '%7D%5Cn' +%0A'%5C%5Cend%7Bfigure%7D';%0A return str;%0A %7D%0A
return formatS
|
b5a121aac35a0cbf95ef855a4ced4b6dbb69def6 | Improve rules error handling | src/rules-engine/Property.js | src/rules-engine/Property.js | /**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.*
*/
const assert = require('assert');
const AddonManager = require('../addon-manager');
const Constants = require('../constants');
const Things = require('../models/things');
const EventEmitter = require('events').EventEmitter;
const Events = require('./Events');
/**
* Utility to support operations on Thing's properties
*/
class Property extends EventEmitter {
/**
* Create a Property from a descriptor returned by the WoT API
* @param {PropertyDescription} desc
*/
constructor(desc) {
super();
assert(desc.type);
assert(desc.thing);
assert(desc.id);
this.type = desc.type;
this.thing = desc.thing;
this.id = desc.id;
if (desc.unit) {
this.unit = desc.unit;
}
if (desc.description) {
this.description = desc.description;
}
this.onPropertyChanged = this.onPropertyChanged.bind(this);
}
/**
* @return {PropertyDescription}
*/
toDescription() {
const desc = {
type: this.type,
thing: this.thing,
id: this.id,
};
if (this.unit) {
desc.unit = this.unit;
}
if (this.description) {
desc.description = this.description;
}
return desc;
}
/**
* @return {Promise} resolves to property's value
*/
async get() {
return await Things.getThingProperty(this.thing, this.id);
}
/**
* @param {any} value
* @return {Promise} resolves if property is set to value
*/
async set(value) {
await Things.setThingProperty(this.thing, this.id, value);
}
async start() {
AddonManager.on(Constants.PROPERTY_CHANGED, this.onPropertyChanged);
}
onPropertyChanged(property) {
if (property.device.id !== this.thing) {
return;
}
if (property.name !== this.id) {
return;
}
this.emit(Events.VALUE_CHANGED, property.value);
}
stop() {
AddonManager.removeListener(Constants.PROPERTY_CHANGED,
this.onPropertyChanged);
}
}
module.exports = Property;
| JavaScript | 0 | @@ -1462,24 +1462,36 @@
ync get() %7B%0A
+ try %7B%0A
return a
@@ -1537,24 +1537,90 @@
, this.id);%0A
+ %7D catch (e) %7B%0A console.warn('Rule get failed', e);%0A %7D%0A
%7D%0A%0A /**%0A
@@ -1678,123 +1678,327 @@
ves
-if property is set to
+when set is done%0A */%0A set(
value
+) %7B
%0A
-*/%0A async set(value) %7B%0A await Things.setThingProperty(this.thing, this.id, value
+ return Things.setThingProperty(this.thing, this.id, value).catch((e) =%3E %7B%0A console.warn('Rule set failed, retrying once', e);%0A return Things.setThingProperty(this.thing, this.id, value);%0A %7D).catch((e) =%3E %7B%0A console.warn('Rule set failed completely', e);%0A %7D
);%0A
|
71e5b4a0fcd7e710859f57c1c2a36c6cb6df093a | Fix hint counter | public/static/scripts/mixins.js | public/static/scripts/mixins.js | var Mixins = Mixins || {}
Mixins.commons = {
data: {
flipped: [],
fullscreened: false,
debug: false,
},
methods: {
select: function (index, e) {
if (!this.flipped[index])
return;
if (this.inarr(index, this.selected))
this.selected.splice(this.selected.indexOf(index), 1);
else
if (this.selected.length < 3)
this.selected.push(index)
},
inarr: function (value, array) {
return array.indexOf(value) !== -1
},
clear: function () {
this.selected = []
},
flips: function (obj) {
var vm = this
setTimeout(function () {
vm.flip(obj.cards.slice(0), obj.to, obj.timeout, obj.inorder, obj.callback)
}, obj.delay || 0)
},
flip: function (cards, to, timeout, inorder, callback) {
var vm = this
var i = inorder ? 0 : Math.floor(Math.random() * cards.length)
Vue.set(this.flipped, cards[i], to === undefined ? 1 : to)
cards.splice(i, 1)
if (cards.length)
setTimeout(function () {
vm.flip(cards, to, timeout, inorder, callback)
}, timeout || 130)
else
if (callback)
callback()
},
fullscreen: function () {
if (this.fullscreened)
this.fullscreened = utils.fullscreen_exit()
else
this.fullscreened = utils.fullscreen(document.body)
},
has_set: function () {
return utils.has_set(this.ground)
},
help: function () {
location.href = "/help"
}
}
}
Mixins.local = {
data: {
ground: [],
selected: [],
deck: [],
previous: {
name: '',
cards: []
},
local: true,
amount: 12,
solved: 0,
hints: 2
},
computed: {
deck_amount: function () {
return this.deck.length
}
},
methods: {
set: function (s) {
var selected = (s || this.selected).slice(0)
if (selected.length !== 3)
return
var set = []
var vm = this
for (var i = 0; i < 3; i++)
set[i] = this.ground[selected[i]]
var judge = utils.is_set(set)
console.log(set, judge)
if (this.debug)
judge = true //for debug
if (judge) {
utils.vibrate(100)
this.solved = this.solved + 1
this.previous.cards = set.sort()
this.previous.name = 'Previous'
this.flips({
cards: selected,
to: 0,
callback: function () {
setTimeout(function () {
for (var i = 0; i < 3; i++)
if (selected[i] !== undefined)
Vue.set(vm.ground, selected[i], app.deck.shift())
vm.flips({
cards: selected,
delay: 200
})
vm.expend()
vm.save()
}, 500)
},
})
vm.clear()
} else {
// Failed
utils.vibrate(500)
this.clear()
}
},
expend: function () {
var sol = this.has_set()
console.log(sol)
if (sol)
return true
if (this.amount >= 18 || this.deck_amount <= 0) {
this.gameover()
this.restart()
return false
}
this.amount = this.amount + 3
for (var i = 0; i < 3; i++) {
this.flipped.push(0)
this.ground.push(this.deck.shift())
}
this.flips({
cards: utils.range(this.amount - 3, this.amount - 1),
timeout: 70,
delay: 500
})
return this.expend()
},
gameover: function () {
localStorage.removeItem('set-game-save')
alert('Gameover! ' + this.solved + ' Sets found!')
},
auto: function () {
var sol = this.has_set()
if (sol)
this.set(sol)
},
restart: function () {
localStorage.removeItem('set-game-save')
this.amount = 12
this.flipped = []
for (var i = 0; i < this.amount; i++)
this.flipped.push(0)
this.previous = {
name: '',
cards: []
}
this.deck = utils.make_deck()
this.ground = this.deck.splice(0, this.amount)
this.solved = 0
this.flips({
cards: utils.range(0, this.amount - 1),
timeout: 70,
delay: 500
})
this.expend()
},
save: function () {
var data = {
deck: this.deck,
ground: this.ground,
amount: this.amount,
solved: this.solved,
hints: this.hints,
previous: this.previous,
time: (new Date()).getTime()
}
localStorage.setItem('set-game-save', JSON.stringify(data))
return data
},
load: function () {
var saved = localStorage.getItem('set-game-save')
if (!saved)
return null
var data = JSON.parse(saved)
console.log(data)
this.flipped = []
for (var i = 0; i < this.amount; i++)
this.flipped.push(0)
for (var k in data)
Vue.set(this, k, data[k])
this.flips({
cards: utils.range(0, this.amount - 1),
timeout: 70,
delay: 500
})
this.expend()
return true
},
hint: function () {
if (this.hints) {
this.selected = this.has_set()
this.hints--
}
}
},
created: function () {
if (!this.load())
this.restart()
}
}
Mixins.web = function (url) {
var cache = {}
return {
methods: {
set: {
}
},
created: function () {
//TODO
}
}
}
| JavaScript | 0.000001 | @@ -3991,32 +3991,53 @@
rds: %5B%5D%0A %7D%0A
+ this.hints = 2%0A
this.deck
|
30f49220567753716075018b723710c88791461c | use linclark’s static-pages fork on or after launch day | services/corporate/methods/getPage.js | services/corporate/methods/getPage.js | var request = require('request');
var Joi = require('joi');
var marky = require('marky-markdown');
var fmt = require('util').format;
module.exports = {
static: getPage('static-pages'),
policy: getPage('policies')
};
function getPage (repo) {
return function (name, next) {
Joi.validate(name, Joi.string().regex(/^[a-zA-Z0-9-_]+$/), function (err, validName) {
if (err) {
return next(err, null);
}
var url = fmt('https://raw.githubusercontent.com/npm/' + repo + '/master/%s.md', validName);
request(url, function (err, resp, content) {
if (content === "Not Found") {
err = content;
return next(err, null);
}
if (typeof content === "string") {
content = marky(content, {sanitize: false}).html();
}
return next(err, content);
});
});
};
}
| JavaScript | 0 | @@ -421,24 +421,143 @@
);%0A %7D%0A%0A
+ var org = (new Date() %3E new Date(%222015-04-13T03:30:00-07:00%22)) ? %22linclark%22 : %22npm%22;%0A var branch = %22master%22%0A
var ur
@@ -603,38 +603,42 @@
com/
-npm/' + repo + '/master/%25s.md'
+%25s/%25s/%25s/%25s.md', org, repo, branch
, va
|
af6f20c1f2183d095b227bc90117a684f2c6ed32 | fix it for good | client/app/common/user/auth.factory.js | client/app/common/user/auth.factory.js | 'use strict';
import 'angularfire';
import Firebase from 'firebase';
import { FIREBASEPATH } from '../common';
let AuthFactory = function ($firebaseAuth, $rootScope, $cookies, $location) {
let ref = new Firebase(FIREBASEPATH);
let fail = (err) => console.log(err);
let afterLogin = function (authData) {
if (authData) {
console.log('Logged in as:', authData.uid);
$rootScope.$emit('USER_LOGGED_IN', authData);
$rootScope.currentUser = authData.facebook;
$location.path('/');
} else {
console.log('Authentication failed:', authData);
}
};
let auth = $firebaseAuth(ref);
auth.$onAuth(afterLogin);
/**
* Login
*/
let login = () => {
auth.$authWithOAuthRedirect('facebook', fail);
};
/**
* Logout
*/
let logout = () => {
ref.unauth();
$cookies.remove('user');
$location.path('/login');
};
return { login, logout };
};
export default AuthFactory;
| JavaScript | 0.00229 | @@ -588,16 +588,64 @@
%7D%0A %7D;%0A%0A
+ /**%0A * Login%0A */%0A%0A let login = () =%3E %7B%0A
let au
@@ -669,16 +669,18 @@
h(ref);%0A
+
auth.$
@@ -706,51 +706,100 @@
%0A%0A
-/**%0A * Login%0A */%0A%0A let login = () =%3E %7B
+ // auth.$authWithOAuthPopup('facebook')%0A // .then(afterLogin)%0A // .catch(fail);%0A
%0A
@@ -904,26 +904,8 @@
%3E %7B%0A
- ref.unauth();%0A
|
fe97cace3c3f03def6d25b5b0a7e4720fac63d61 | Set a URL in storybook | .storybook/config.js | .storybook/config.js | import { configure, addParameters } from '@storybook/vue';
// Option defaults:
addParameters({
options: {
name: 'Vue Visual',
}
})
// automatically import all files ending in *.stories.js
const req = require.context('../stories', true, /\.stories\.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
configure(loadStories, module);
| JavaScript | 0.999959 | @@ -126,16 +126,64 @@
isual',%0A
+ url: 'https://github.com/BKWLD/vue-visual',%0A
%7D%0A%7D)%0A%0A
|
46dd549e8005d7d26b446cd68ce5e298216ea97a | change status indicator if value was changed | settings/js/federationsettingsview.js | settings/js/federationsettingsview.js | /* global OC, result, _ */
/**
* Copyright (c) 2016, Christoph Wurst <christoph@owncloud.com>
*
* This file is licensed under the Affero General Public License version 3 or later.
* See the COPYING-README file.
*/
(function(_, $, OC) {
'use strict';
var FederationSettingsView = OC.Backbone.View.extend({
_inputFields: undefined,
/** @var Backbone.Model */
_config: undefined,
initialize: function(options) {
options = options || {};
if (options.config) {
this._config = options.config;
} else {
this._config = new OC.Settings.UserSettings();
}
this._inputFields = [
'displayname',
'phone',
'email',
'website',
'twitter',
'address',
'avatar'
];
var self = this;
_.each(this._inputFields, function(field) {
var scopeOnly = field === 'avatar';
// Initialize config model
if (!scopeOnly) {
self._config.set(field, $('#' + field).val());
}
self._config.set(field + 'Scope', $('#' + field + 'scope').val());
// Set inputs whenever model values change
if (!scopeOnly) {
self.listenTo(self._config, 'change:' + field, function() {
self.$('#' + field).val(self._config.get(field));
});
}
self.listenTo(self._config, 'change:' + field + 'Scope', function() {
self._setFieldScopeIcon(field, self._config.get(field + 'Scope'));
});
});
this._registerEvents();
},
render: function() {
var self = this;
_.each(this._inputFields, function(field) {
var $heading = self.$('#' + field + 'form h2');
var $icon = self.$('#' + field + 'form h2 > span');
var scopeMenu = new OC.Settings.FederationScopeMenu({field: field});
self.listenTo(scopeMenu, 'select:scope', function(scope) {
self._onScopeChanged(field, scope);
});
$heading.append(scopeMenu.$el);
$icon.on('click', _.bind(scopeMenu.show, scopeMenu));
// Restore initial state
self._setFieldScopeIcon(field, self._config.get(field + 'Scope'));
});
},
_registerEvents: function() {
var self = this;
_.each(this._inputFields, function(field) {
if (field === 'avatar') {
return;
}
self.$('#' + field).keyUpDelayedOrEnter(_.bind(self._onInputChanged, self), true);
});
},
_onInputChanged: function(e) {
var self = this;
var $dialog = $('.oc-dialog:visible');
if (OC.PasswordConfirmation.requiresPasswordConfirmation()) {
if($dialog.length === 0) {
OC.PasswordConfirmation.requirePasswordConfirmation(_.bind(this._onInputChanged, this, e));
}
return;
}
var $target = $(e.target);
var value = $target.val();
var field = $target.attr('id');
this._config.set(field, value);
var savingData = this._config.save({
error: function(jqXHR) {
OC.msg.finishedSaving('#personal-settings-container .msg', jqXHR);
}
});
$.when(savingData).done(function() {
//OC.msg.finishedSaving('#personal-settings-container .msg', result)
self._showInputChangeSuccess(field);
});
},
_onScopeChanged: function(field, scope) {
var $dialog = $('.oc-dialog:visible');
if (OC.PasswordConfirmation.requiresPasswordConfirmation()) {
if($dialog.length === 0) {
OC.PasswordConfirmation.requirePasswordConfirmation(_.bind(this._onScopeChanged, this, field, scope));
}
return;
}
this._config.set(field + 'Scope', scope);
$('#' + field + 'scope').val(scope);
// TODO: user loading/success feedback
this._config.save();
this._setFieldScopeIcon(field, scope);
},
_showInputChangeSuccess: function(field) {
var $icon = this.$('#' + field + 'form > span');
$icon.fadeIn(200);
setTimeout(function() {
$icon.fadeOut(300);
}, 2000);
},
_setFieldScopeIcon: function(field, scope) {
var $icon = this.$('#' + field + 'form > h2 > span');
$icon.removeClass('icon-password');
$icon.removeClass('icon-contacts-dark');
$icon.removeClass('icon-link');
switch (scope) {
case 'private':
$icon.addClass('icon-password');
break;
case 'contacts':
$icon.addClass('icon-contacts-dark');
break;
case 'public':
$icon.addClass('icon-link');
break;
}
}
});
OC.Settings = OC.Settings || {};
OC.Settings.FederationSettingsView = FederationSettingsView;
})(_, $, OC);
| JavaScript | 0 | @@ -3615,20 +3615,31 @@
'form %3E
-span
+.icon-checkmark
');%0A%09%09%09$
@@ -3719,16 +3719,562 @@
, 2000);
+%0A%0A%09%09%09if (field === 'twitter' %7C%7C field === 'webpage')%0A%09%09%09%7B%0A%09%09%09%09var verifyStatus = this.$('#' + field + 'form %3E .verify %3E #verify-' + field);%0A%09%09%09%09verifyStatus.attr('title', 'Verify');%0A%09%09%09%09verifyStatus.attr('src', OC.imagePath('core', 'actions/verify.svg'));%0A%09%09%09%09verifyStatus.addClass('verify-action');%0A%09%09%09%7D else if (field === 'email') %7B%0A%09%09%09%09var verifyStatus = this.$('#' + field + 'form %3E .verify %3E #verify-' + field);%0A%09%09%09%09verifyStatus.attr('title', 'Verifying...');%0A%09%09%09%09verifyStatus.attr('src', OC.imagePath('core', 'actions/verifying.svg'));%0A%09%09%09%7D
%0A%09%09%7D,%0A%0A%09
|
9243c645f8836755ae8e46f3330c5eca4bf80fa7 | revert change to storybook stage component | .storybook/config.js | .storybook/config.js | import React from "react";
import { addDecorator, configure } from "@storybook/react";
import styled, { ThemeProvider } from "styled-components";
import { withKnobs, select } from "@storybook/addon-knobs";
import reset from "../src/reset";
import themes from "../src/themes";
import SystemFontStack from "../src/components/SystemFontStack";
const req = require.context("../src", true, /.stories.js$/);
function loadStories() {
req.keys().forEach(filename => req(filename));
}
reset();
const Stage = styled.div`padding: ${props => props.theme.spacingBase()} 0;`;
Stage.displayName = "Stage";
addDecorator(story => {
const selectedTheme = select("Theme", Object.keys(themes), "default");
return (
<ThemeProvider theme={themes[selectedTheme]}>
<Stage>
<SystemFontStack>{story()}</SystemFontStack>
</Stage>
</ThemeProvider>
);
});
addDecorator(withKnobs);
configure(loadStories, module);
| JavaScript | 0.000001 | @@ -560,10 +560,8 @@
e()%7D
- 0
;%60;%0A
|
b3801664445dc0805f0860eda5d6574e94c82c6d | fix header | src/client/components/Header/Header.component.js | src/client/components/Header/Header.component.js | 'use strict';
import React from 'react';
import ProfileStore from '../../stores/Profile.store.js';
export default class Header extends React.Component {
constructor() {
super();
this.state = ProfileStore.getState();
}
componentDidMount() {
this.unsubscribe = [
ProfileStore.listen(() => this.updateProfile())
];
}
componentWillUnmount() {
this.unsubscribe.forEach(
(unsubscriber) => {
unsubscriber();
}
);
}
updateProfile() {
this.setState(ProfileStore.getState());
}
render() {
const isLoggedIn = this.state.userIsLoggedIn;
const buttonData = isLoggedIn ? {url: '/profile/logout', text: 'Log Ud'} : {url: '/profile/login', text: 'Log Ind'};
const profileLink = isLoggedIn ?
<a className='right' href='/profile' >Lånerstatus</a> : '';
return (
<div id="header" >
<div id="topbar" >
<div className="topbar--logo--container row" >
<div className="topbar--logo-container small-17 columns" >
<a href="/" >
<span id="logo" > </span>
</a>
</div>
<div className="topbar--login-btn-container small-7 medium-6 large-6 columns" >
<a className='button tiny right' href={buttonData.url} >{buttonData.text}</a>
</div>
</div>
</div>
<div className="header--topnavigation-container row" >
<div className="header--topnavigation-links small-24 medium-24 large-24 columns" >
<div className="header--topnavigation-links--link" >
{profileLink}
</div>
</div>
</div>
</div>
);
}
}
Header.displayName = 'Header';
| JavaScript | 0.000001 | @@ -1010,16 +1010,35 @@
mall-17
+medium-18 large-18
columns%22
|
928b187464b4e8a1db37c958f6ff920ebbe9b6df | Implement functions to add and remove materials | client/app/services/materialService.js | client/app/services/materialService.js | import 'whatwg-fetch';
import h from '../helpers.js';
let services = {
addMaterialType,
getAllMaterials,
getMaterial,
getTypes,
modifyMaterial,
modifyType,
removeMaterialType
};
function addMaterialType(type) {
return fetch('/a/types/materials', {
method: 'post',
headers: h.headers,
body: JSON.stringify({ type })
}).then(h.checkStatus)
.catch(error => {
console.log('Error adding material type: ', error);
throw error;
});
}
function getAllMaterials() {
return fetch('/a/materials')
.then(h.checkStatus)
.then(h.parseJSON)
.then(data => data.materials)
.catch(error => {
console.log('Error fetching materials: ', error);
throw error;
});
}
function getMaterial(id) {
return fetch('/a/materials/' + id)
.then(h.checkStatus)
.then(h.parseJSON)
.then(data => data.material)
.catch(error => {
console.log('Error fetching material: ', error);
throw error;
});
}
function getTypes() {
return fetch('/a/types/materials')
.then(h.checkStatus)
.then(h.parseJSON)
.then(data => data.types)
.catch(error => {
console.log('Error fetching material types: ', error);
throw error;
});
}
function modifyMaterial(id, field, value) {
return fetch('/a/materials/' + id, {
method: 'put',
headers: h.headers,
body: JSON.stringify({
[field]: value
})
}).then(h.checkStatus)
.then(h.parseJSON)
.then(data => data.material)
.catch(error => {
console.log('Error modifying material: ', error);
throw error;
});
}
function modifyType(id, field, value) {
return fetch('/a/types/materials/' + id, {
method: 'put',
headers: h.headers,
body: JSON.stringify({
[field]: value
})
}).then(h.checkStatus)
.then(h.parseJSON)
.then(data => data.type)
.catch(error => {
console.log('Error modifying material type: ', error);
throw error;
});
}
function removeMaterialType(id) {
return fetch('/a/types/materials/' + id, {
method: 'delete',
headers: h.headers
}).then(h.checkStatus)
.catch(error => {
console.log('Error removing material type: ', error);
throw error;
});
}
export default services;
| JavaScript | 0 | @@ -65,16 +65,31 @@
ces = %7B%0A
+ addMaterial,%0A
addMat
@@ -99,16 +99,16 @@
alType,%0A
-
getAll
@@ -177,16 +177,34 @@
fyType,%0A
+ removeMaterial,%0A
remove
@@ -220,12 +220,283 @@
ype%0A
-
%7D;%0A%0A
+function addMaterial(material) %7B%0A return fetch('/a/materials', %7B%0A method: 'post',%0A headers: h.headers,%0A body: JSON.stringify(%7B material %7D)%0A %7D).then(h.checkStatus)%0A .catch(error =%3E %7B%0A console.log('Error adding material: ', error);%0A throw error;%0A %7D);%0A%7D%0A%0A
func
@@ -2232,32 +2232,270 @@
error;%0A %7D);%0A%7D%0A%0A
+function removeMaterial(id) %7B%0A return fetch('/a/materials/' + id, %7B%0A method: 'delete',%0A headers: h.headers%0A %7D).then(h.checkStatus)%0A .catch(error =%3E %7B%0A console.log('Error removing material: ', error);%0A throw error;%0A %7D);%0A%7D%0A%0A
function removeM
|
395de11d6a43a3d55022c375428642d964023684 | remove first 2 lines | client/components/LandingF/LandingF.js | client/components/LandingF/LandingF.js | import React from 'react'
import styles from './LandingF.scss'
import logoV from '../../images/logo-home-video-copy.png'
import c3nonprofit from '../../images/501-c-3-nonprofit.png'
class Footer extends React.Component {
render () {
return (
<div className={styles.container}>
<div className={styles.column1}>
<img src={logoV} alt="Call to code logo"/>
<p><img src={c3nonprofit} className={styles.nonProfit} /></p>
</div>
<div className={styles.column2}>
<ul className={styles.list}>
<li className={styles.projects}><a href="#" className={styles.link}>Projects</a></li>
</ul>
</div>
<div className={styles.column3}>
<ul className={styles.list}>
<li className={styles.about}><a href="/about" className={styles.link}>About</a></li>
</ul>
</div>
</div>
)
}
}
export default Footer
<li className={styles.company}>Company</li>
<li className={styles.list-items styles.press}><a href="#">Press</a></li>
<li className={styles.list-items}><a href="#">Releases</li>
<li className={styles.list-items}><a href="#">Mission</li>
<li className={styles.list-items}><a href="#">Strategy</li>
<li className={styles.list-items}><a href="#">Works</li>
</ul>
</div>
<div className={styles.column3}>
<p className={styles.FOLLOW-US}>FOLLOW US</p>
<div className={styles.social-media}>
<a href="#"><img src={facebook} alt="facebook logo" className="facebook"></a>
<a href="#"><img src={twitter} alt="twitter logo" className="twitter"></a>
<a href="#"><img src={linked-in} alt="linkedin logo" className="linked-in"></a>
<a href="#"><img src={pininterest} alt="pininterest logo" className="pininterest"></a>
</div>
</div>
</div>
)
}
};
export default LandingF
| JavaScript | 0.999999 | @@ -635,32 +635,1098 @@
ojects%3C/a%3E%3C/li%3E%0A
+import React, %7B Component %7D from 'react'%0Aimport styles from './LandingF.scss'%0Aimport logo from '../../images/logo-home.png'%0Aimport facebook from '../../images/facebook.png'%0Aimport linked-in from '../../images/linked-in.png'%0Aimport pininterest from '../../images/pininterest.png'%0Aimport twitter from '../../images/twitter.png'%0Aimport 501-c-3-nonprofit from '../../images/501-c-3-nonprofit.png'%0A%0A%0Aclass Footer extends React.Component %7B%0A render()%7B%0A return (%0A %3Cdiv className=%7Bstyles.container%7D%3E%0A %3Cdiv className=%7Bstyles.column1%7D%3E%0A %3Cimg src=%7Blogo%7D alt=%22Call to code logo%22 className=%22logo-home%22%3E%0A %3Cp%3E%3Cimg src=%7B501-c-3-nonprofit%7D className=%22non-profit%22%3E%3C/p%3E%0A %3C/div%3E%0A%0A%0A %3Cdiv className=%7Bstyles.column2%7D%3E%0A %3Cul className=%7Bstyles.list%7D%3E%0A %3Cli className=%7Bstyles.product%7D%3EProduct%3C/li%3E%0A %3Cli className=%7Bstyles.list-items styles.popular%7D%3E%3Ca href=%22#%22%3EPopular%3C/li%3E%0A %3Cli className=%7Bstyles.list-items%7D%3E%3Ca href=%22#%22%3ETrending%3C/li%3E%0A %3Cli className=%7Bstyles.list-items%7D%3E%3Ca href=%22#%22%3ECatalog%3C/li%3E%0A
%3C/ul%3E%0A
|
35f0bbce7c6d8221d95b19f365ecb4cb86994fdb | Add break-word property to error messages of long hex strings | client/src/js/jobs/components/Error.js | client/src/js/jobs/components/Error.js | import React from "react";
import { map } from "lodash-es";
import { Alert } from "../../base";
const JobError = ({ error }) => {
if (!error) {
return null;
}
// Traceback from a Python exception.
const tracebackLines = map(error.traceback, (line, index) =>
<div key={index} className="traceback-line">{line}</div>
);
// Only show a colon and exception detail after the exception name if there is detail present.
const details = error.details.length ? <span>: {error.details}</span> : null;
// Content replicates format of Python exceptions shown in Python console.
return (
<Alert bsStyle="danger">
<div>Traceback (most recent call last):</div>
{tracebackLines}
<p>{error.type}{details}</p>
</Alert>
);
};
export default JobError;
| JavaScript | 0.000001 | @@ -494,16 +494,83 @@
ngth
- ? %3Cspan
+%0A ? %3Cspan style=%7B%7Bdisplay: %22inline-block%22, wordBreak: %22break-word%22%7D%7D
%3E: %7B
@@ -590,16 +590,24 @@
%7D%3C/span%3E
+%0A
: null;
|
2007e9bd082f4aa8d9a891297de02e47b405df56 | pass test for whitespace phrase is not palindrome | server/02-palindrome/palindrome.spec.js | server/02-palindrome/palindrome.spec.js | describe('the palindrome canary test', () => {
it('shows the infrastructure works', () => {
true.should.equal(true);
});
const isPalindrome = phrase => {
if (phrase === '') return false;
return phrase.split('').reverse().join('') === phrase;
};
describe('palindrome should be', () => {
it('yes for mom', () => {
isPalindrome('mom').should.equal(true);
});
it('no for dude', () => {
isPalindrome('dude').should.equal(false);
});
it('yes for mom mom', () => {
isPalindrome('mom mom').should.equal(true);
});
it('no for mom dad', () => {
isPalindrome('mom dad').should.equal(false);
});
it('no for empty phrase', () => {
isPalindrome('').should.equal(false);
});
it('no for whitespace only phrase');
});
});
| JavaScript | 0.999999 | @@ -172,16 +172,23 @@
(phrase
+.trim()
=== '')
@@ -797,16 +797,78 @@
phrase'
+, () =%3E %7B%0A isPalindrome(' ').should.equal(false);%0A %7D
);%0A %7D);
|
22e07859bf17f958e5fcb9331ce5f23651576899 | fix jsdoc | rest-on-couch/UserViewPrefs.js | rest-on-couch/UserViewPrefs.js | define(['../util/getViewInfo'], function (getViewInfo) {
class UserViewPrefs {
constructor(roc) {
this.roc = roc;
}
/**
* Retrieves user preferences related to the current view
* @param {*} prefID
* @return preferences
*/
async get(prefID) {
let record = await this.getRecord(prefID);
if (record && record.$content) return record.$content;
return undefined;
}
async getRecord(prefID) {
if (!prefID) prefID = (await getViewInfo())._id;
var user = await this.roc.getUser();
if (!user || !user.username) return undefined;
var firstEntry = (await this.roc.view('entryByOwnerAndId', {
key: [user.username, ['userViewPrefs', prefID]]
}))[0];
return firstEntry;
}
async set(value, prefID) {
if (!prefID) prefID = (await getViewInfo())._id;
let record = await this.getRecord(prefID);
if (record) {
record.$content = value;
return this.roc.update(record);
} else {
return this.roc.create({
$id: ['userViewPrefs', prefID],
$content: value,
$kind: 'userViewPrefs'
});
}
}
}
return UserViewPrefs;
});
| JavaScript | 0.000089 | @@ -234,16 +234,25 @@
@return
+ %7Bobject%7D
prefere
@@ -630,24 +630,33 @@
rstEntry = (
+%0A
await this.r
@@ -694,16 +694,18 @@
+
+
key: %5Bus
@@ -750,18 +750,27 @@
%5D%0A
-%7D)
+ %7D)%0A
)%5B0%5D;%0A
|
0c0c83a5240771cebb121199b1f18a89e26ae585 | fail mom is palindrome test | server/02-palindrome/palindrome.spec.js | server/02-palindrome/palindrome.spec.js | describe('the palindrome canary test', () => {
it('shows the infrastructure works', () => {
true.should.equal(true);
});
describe('palindrome should be', () => {
it('yes for mom');
it('yes for dad');
it('no for dude');
it('yes for mom mom');
it('no for mom dad');
it('no for empty phrase');
it('no for whitespace only phrase');
});
});
| JavaScript | 0.999989 | @@ -182,26 +182,88 @@
yes for mom'
-);
+, () =%3E %7B%0A isPalindrome('mom').should.equal(true);%0A %7D);%0A
%0A it('yes
|
18fb7e0e899090c3a69dfa567887b66494c1e0cb | Fix direct go to issue by url | frontend/app/js/containers/issues/details.js | frontend/app/js/containers/issues/details.js | import React from 'react'
import DetailsView from 'app/components/issues/details'
import rpc from 'app/rpc'
import Flash from 'app/flash'
import {parse_comment, update_issue_multi, update_issue} from './utils'
import {merge} from 'app/utils'
import Loading from 'app/components/loading'
import {i18n} from 'app/utils/i18n'
import event from 'app/utils/event'
class Details extends React.Component{
constructor(props){
super(props)
this.state = {
issue: undefined,
issue_id: this.props.issue_id || this.props.params.id
}
this.handlers = {
onAddComment: this.handleAddComment.bind(this),
onAddCommentAndClose: this.handleAddCommentAndClose.bind(this),
onAddCommentAndReopen: this.handleAddCommentAndReopen.bind(this),
onOpenIssue: this.handleOpenIssue.bind(this),
onCloseIssue: this.handleCloseIssue.bind(this),
onRemoveLabel: this.handleRemoveLabel.bind(this),
onAddLabel: this.handleAddLabel.bind(this),
}
this.maybeUpdateIssueB=this.maybeUpdateIssue.bind(this)
}
componentDidMount(){
rpc.call("issues.get", [this.state.issue_id]).then( (issue) => {
this.setState({issue})
})
event.on("issue.updated", this.maybeUpdateIssueB)
}
componentWillUnmount(){
event.off("issue.updated", this.maybeUpdateIssueB)
}
maybeUpdateIssue({issue}){
if (issue.id == this.state.issue_id){
this.setState({issue})
}
}
handleAddComment(comment){
return update_issue_multi(this.state.issue_id, parse_comment(comment))
.then( () => this.componentDidMount() )
}
handleAddCommentAndClose(comment){
return update_issue_multi(this.state.issue_id, parse_comment(comment).concat( {type: "change_status", data: "closed"} ))
.then( () => {
Flash.info("Added new comment and reopened issue")
this.setState({issue: merge(this.state.issue, {status: "closed"})})
this.componentDidMount()
})
}
handleAddCommentAndReopen(comment){
return update_issue_multi(this.state.issue_id, parse_comment(comment).concat( {type: "change_status", data: "open"} ))
.then( () => {
Flash.info("Added new comment and reopened issue")
this.setState({issue: merge(this.state.issue, {status: "open"})})
this.componentDidMount()
})
}
handleOpenIssue(){
return update_issue_multi(this.state.issue_id, [ {type: "change_status", data: "open"} ] )
.then( () => {
Flash.info("Reopened issue")
this.setState({issue: merge(this.state.issue, {status: "open"})})
this.componentDidMount()
})
}
handleCloseIssue(){
return update_issue_multi(this.state.issue_id, [ {type: "change_status", data: "closed"} ] )
.then( () => {
Flash.info("Closed issue")
this.setState({issue: merge(this.state.issue, {status: "closed"})})
this.componentDidMount()
})
}
handleAddLabel(tag){
return update_issue(this.state.issue_id, {type:"set_labels", data:[tag]})
.then( () => this.componentDidMount() )
}
handleRemoveLabel(tag){
return update_issue(this.state.issue_id, {type:"unset_labels", data:[tag]})
.then( () => this.componentDidMount() )
}
render(){
if (!this.state.issue)
return (
<Loading>{i18n("Issue data")}</Loading>
)
return (
<DetailsView {...this.props} {...this.state} {...this.handlers}/>
)
}
}
export default Details
| JavaScript | 0 | @@ -1091,16 +1091,23 @@
.get%22, %5B
+Number(
this.sta
@@ -1117,16 +1117,17 @@
issue_id
+)
%5D).then(
|
94cc63154ff5c7d27205fc881eba03b164765d00 | Fix duration display in log | server/Prefs/FileScanner/FileScanner.js | server/Prefs/FileScanner/FileScanner.js | const path = require('path')
const debug = require('debug')
const log = debug('app:prefs:fileScanner')
const { promisify } = require('util')
const fs = require('fs')
const stat = promisify(fs.stat)
const musicMeta = require('music-metadata')
const mp4info = require('./lib/mp4info.js')
const getFiles = require('./getFiles')
const parseMeta = require('./parseMeta')
const parseMetaCfg = require('./parseMetaCfg')
const getPerms = require('../../lib/getPermutations')
const Scanner = require('../Scanner')
const Media = require('../../Media')
const videoExts = ['.cdg', '.mp4'].reduce((perms, ext) => perms.concat(getPerms(ext)), [])
const audioTypes = ['m4a', 'mp3']
class FileScanner extends Scanner {
constructor (prefs) {
super()
this.paths = prefs.paths
}
async scan () {
const offlinePaths = [] // pathIds
const validMedia = [] // mediaIds
let files = []
// emit start
this.emitStatus('Gathering file list', 0)
// count files to scan from all paths
for (const pathId of this.paths.result) {
try {
log('Searching path: %s', this.paths.entities[pathId].path)
let list = await getFiles(this.paths.entities[pathId].path)
list = list.filter(file => videoExts.includes(path.extname(file)))
log(' => found %s files with valid extensions (cdg, mp4)', list.length)
files = files.concat(list)
} catch (err) {
log(` => ${err.message} (path offline)`)
offlinePaths.push(pathId)
}
if (this.isCanceling) {
return
}
}
log('Processing %s total files', files.length)
// process files
for (let i = 0; i < files.length; i++) {
const file = files[i]
const pathId = this.paths.result.find(pathId =>
file.indexOf(this.paths.entities[pathId].path) === 0
)
// emit progress
log('[%s/%s] %s', i + 1, files.length, file)
this.emitStatus(`Scanning media files (${i + 1} of ${files.length})`, ((i + 1) / files.length) * 100)
try {
const mediaId = await this.processFile({ file, pathId })
// successfuly processed
validMedia.push(mediaId)
} catch (err) {
log(err)
// try the next file
}
if (this.isCanceling) {
return
}
} // end for
// cleanup
log('Looking for orphaned media entries')
{
const invalidMedia = []
const res = await Media.search()
res.result.forEach(mediaId => {
// was this media item just verified?
if (validMedia.includes(mediaId)) {
return
}
// is media item in an offline path?
if (offlinePaths.includes(res.entities[mediaId].pathId)) {
return
}
// looks like we need to remove it
invalidMedia.push(mediaId)
log(` => ${res.entities[mediaId].file}`)
})
log(`Found ${invalidMedia.length} orphaned media entries`)
if (invalidMedia.length) {
await Media.remove(invalidMedia)
}
}
}
async processFile ({ file, pathId }) {
let stats
const media = {
pathId,
file,
}
{
// already in database with the same path?
const res = await Media.search(media)
log(' => %s result(s) for existing media', res.result.length)
if (res.result.length) {
log(' => media is in library')
return res.result[0]
}
// needs further inspection...
stats = await stat(file)
}
// new media
// -------------------------------
// try getting artist and title from filename
const { artist, title } = parseMeta(path.parse(file).name, parseMetaCfg)
if (!artist || !title) {
throw new Error(` => could not determine artist or title`)
}
media.artist = artist
media.title = title
media.timestamp = new Date(stats.mtime).getTime()
// need to look for an audio file?
if (path.extname(file).toLowerCase() === '.cdg') {
let audioFile
// look for all uppercase and lowercase permutations of each
// file extension since we may be on a case-sensitive fs
for (const type of audioTypes) {
for (const ext of getPerms(type)) {
audioFile = file.substr(0, file.lastIndexOf('.') + 1) + ext
// does file exist?
try {
await stat(audioFile)
log(' => found %s audio', type)
break
} catch (err) {
// try another permutation
audioFile = null
}
} // end for
if (audioFile) {
try {
const meta = await musicMeta.parseFile(audioFile, { duration: true })
media.duration = meta.format.duration
break
} catch (err) {
// try another type
audioFile = null
log(err)
}
}
} // end for
if (!audioFile) {
throw new Error(` => no valid audio file`)
}
} else if (path.extname(file).toLowerCase() === '.mp4') {
// get video duration
const info = await mp4info(file)
media.duration = info.duration
}
if (!media.duration) {
throw new Error(` => could not determine duration`)
}
log(` => duration: ${Math.floor(media.duration / 60)}:${Math.round(media.duration % 60, 10)}`)
// add song
const mediaId = await Media.add(media)
if (!Number.isInteger(mediaId)) {
throw new Error('got invalid lastID')
}
this.emitLibrary()
return mediaId
}
}
// if (typeof song !== 'object') {
// // try parent folder?
// log(` => couldn't parse artist/title from filename; trying parent folder name`)
// song = parseMeta(cdgPathInfo.dir.split(cdgPathInfo.sep).pop())
//
// if (typeof song !== 'object') {
// return Promise.reject(new Error(`couldn't parse artist/title`))
// }
// }
module.exports = FileScanner
| JavaScript | 0.000001 | @@ -5245,25 +5245,25 @@
%7D%0A%0A log(
-%60
+'
=%3E duratio
@@ -5265,18 +5265,30 @@
ration:
-$%7B
+%25s:%25s',%0A
Math.flo
@@ -5314,12 +5314,16 @@
60)
-%7D:$%7B
+,%0A
Math
@@ -5353,18 +5353,49 @@
60, 10)
-%7D%60
+.toString().padStart(2, '0')%0A
)%0A%0A /
|
47194f9bf7d3beb75dc1aa41c7308d5b1a725af6 | add tableName work in queryBuilderFormat | modules/utils/queryBuilderFormat.js | modules/utils/queryBuilderFormat.js | 'use strict';
import Immutable from 'immutable';
import uuid from "./uuid";
import isArray from 'lodash/isArray'
import {defaultValue} from "./stuff";
import {
getFieldConfig, getWidgetForFieldOp, getValueSourcesForFieldOp, getOperatorConfig, getFieldWidgetConfig,
getFieldPath, getFieldPathLabels, fieldWidgetDefinition
} from './configUtils';
import omit from 'lodash/omit';
import pick from 'lodash/pick';
/*
Build tree to http://querybuilder.js.org/ like format
Example:
{
"condition": "AND",
"rules": [
{
"id": "price",
"field": "price",
"type": "double",
"input": "text",
"operator": "less",
"value": "10.25"
},
{
"condition": "OR",
"rules": [
{
"id": "category",
"field": "category",
"type": "integer",
"input": "select",
"operator": "equal",
"value": "2"
},
{
"id": "category",
"field": "category",
"type": "integer",
"input": "select",
"operator": "equal",
"value": "1"
}
]}
]
}
*/
export const queryBuilderFormat = (item, config, rootQuery = null) => {
const type = item.get('type');
const properties = item.get('properties');
const children = item.get('children1');
const id = item.get('id')
var resultQuery = {};
var isRoot = (rootQuery === null);
if (isRoot) {
rootQuery = resultQuery;
rootQuery.usedFields = [];
}
if (type === 'group' && children && children.size) {
const conjunction = properties.get('conjunction');
const conjunctionDefinition = config.conjunctions[conjunction];
const list = children
.map((currentChild) => {
return queryBuilderFormat(currentChild, config, rootQuery)
})
.filter((currentChild) => typeof currentChild !== 'undefined')
if (!list.size)
return undefined;
resultQuery['rules'] = list.toList();
resultQuery['condition'] = conjunction.toUpperCase();
return resultQuery;
} else if (type === 'rule') {
const field = properties.get('field');
const operator = properties.get('operator');
const options = properties.get('operatorOptions');
let value = properties.get('value');
let valueSrc = properties.get('valueSrc');
let valueType = properties.get('valueType');
let hasUndefinedValues = false;
value.map((currentValue, ind) => {
if (currentValue === undefined) {
hasUndefinedValues = true;
return undefined;
}
});
if (field == null || operator == null || hasUndefinedValues)
return undefined;
const fieldDefinition = getFieldConfig(field, config) || {};
const operatorDefinition = getOperatorConfig(config, operator, field) || {};
//const reversedOp = operatorDefinition.reversedOp;
//const revOperatorDefinition = getOperatorConfig(config, reversedOp, field) || {};
const fieldType = fieldDefinition.type || "undefined";
const cardinality = defaultValue(operatorDefinition.cardinality, 1);
const widget = getWidgetForFieldOp(config, field, operator);
const fieldWidgetDefinition = omit(getFieldWidgetConfig(config, field, operator, widget), ['factory']);
const typeConfig = config.types[fieldDefinition.type] || {};
if (value.size < cardinality)
return undefined;
if (rootQuery.usedFields.indexOf(field) == -1)
rootQuery.usedFields.push(field);
value = value.toArray();
valueSrc = valueSrc.toArray();
valueType = valueType.toArray();
let values = [];
for (let i = 0 ; i < value.length ; i++) {
let val = {
type: valueType[i],
value: value[i],
};
values.push(val);
if (valueSrc[i] == 'field') {
let secondField = value[i];
if (rootQuery.usedFields.indexOf(secondField) == -1)
rootQuery.usedFields.push(secondField);
}
}
let operatorOptions = options ? options.toJS() : null;
if (operatorOptions && !Object.keys(operatorOptions).length)
operatorOptions = null;
var ruleQuery = {
id,
field,
type: fieldType,
input: typeConfig.mainWidget,
operator,
};
if (operatorOptions)
ruleQuery.operatorOptions = operatorOptions;
ruleQuery.values = values;
return ruleQuery
}
return undefined;
};
| JavaScript | 0.00061 | @@ -1968,55 +1968,8 @@
) %7B%0A
- const field = properties.get('field');%0A
@@ -2072,24 +2072,69 @@
rOptions');%0A
+ let field = properties.get('field');%0A
let
@@ -3301,16 +3301,240 @@
%7C%7C %7B%7D;%0A%0A
+ //format field%0A if (fieldDefinition.tableName) %7B%0A const regex = new RegExp(field.split(config.settings.fieldSeparator)%5B0%5D)%0A field = field.replace(regex, fieldDefinition.tableName)%0A %7D%0A%0A
|
d885ce126401cc7bc407bdd282f50e12b9111198 | Remove unneeded Text import from Subtitle | frontend/src/components/Subtitle/Subtitle.js | frontend/src/components/Subtitle/Subtitle.js | import React, { Component } from 'react'
import Radium from 'radium'
import colors from '../../styles/colors'
import { Text } from '../../components'
const styles = {
color: colors.gray,
fontStyle: 'italic',
}
class Subtitle extends Component {
render() {
return (
<p {...this.props} style={[styles,this.props.style]}>{this.props.children}</p>
)
}
}
export default Radium(Subtitle)
| JavaScript | 0.000001 | @@ -109,49 +109,8 @@
s'%0A%0A
-import %7B Text %7D from '../../components'%0A%0A
cons
|
71563ce540d2e61d266be4d188027249e587b94f | Update textnode view | src/dom_components/view/ComponentTextNodeView.js | src/dom_components/view/ComponentTextNodeView.js | import ComponentView from './ComponentView';
export default ComponentView.extend({
initialize() {
ComponentView.prototype.initialize.apply(this, arguments);
},
// Clear methods used on Nodes with attributes
_setAttributes() {},
renderAttributes() {},
setAttribute() {},
updateAttributes() {},
initClasses() {},
initComponents() {},
delegateEvents() {},
_createElement() {
return document.createTextNode('');
},
render() {
const { model, el } = this;
if (model.opt.temporary) return this;
el.textContent = model.get('content');
return this;
}
});
| JavaScript | 0 | @@ -260,16 +260,59 @@
s() %7B%7D,%0A
+ updateStatus() %7B%7D,%0A updateClasses() %7B%7D,%0A
setAtt
|
0bb9d9e069e3ffa6da4c8a392bbeed1b3bbd5b9d | Refactor auth in redis connection. | server/config/middlewares/public_api.js | server/config/middlewares/public_api.js | var mongoose = require('mongoose')
, User = mongoose.model('User')
, Vendor = mongoose.model('Vendor')
, Throttle = require('redis-throttle')
, env = process.env.NODE_ENV || 'development'
, config = require('../config')[env]
;
/**
* Validate API key
* -----------------------------------------
* Validates api key by getting key from header, looking up vendor with matching key, and then
* saving vendorId within req.body.vendorId. This allows us to access the vendor in our quote
* controller.
*
* @todo move out of auth and into api file.
*
* -----
*
* @note we might consider saivng the vendor
* @todo this could be a great 'api-module' for NPM, if we add throttle, access count, etc.
* @note module could automatically add fields to mongoose model, as a plugin.
*
*/
exports.validateApiKey = function(req, res, next) {
// get key from the header
var key = req.header('MARLIN-API-KEY');
// require an API key
if(!key) {
return res.failure("An API key is required. Please include 'MARLIN-API-KEY' in your header.", 400);
}
// lookup vendor by API key
Vendor
.findOne({apiKey : key, 'tools.api.enabled' : true})
.exec(function(err, vendor) {
// check for error or no vendor found
if(err) return res.failure(err);
if(!vendor) return res.failure('Not a valid API key', 400);
// @note this should be hooked up to an api access log at some point
console.info("%s successfully authenticated public API with key '%s'", vendor.name, vendor.apiKey);
req.vendor = vendor;
// save vendor for access in quote controller
req.body.vendorId = vendor._id;
// move on to next middleware
next();
});
};
/**
* API THROTTLING using redis
* -----------------------------------------
*
* This method usese a redis server to store connection counts per api key
*
* @note all attempts to connect are counted, even if over limit
*
* limits are reset as defined by `accuracy` where `span` is the time range to check
* within. This means that a 1 minute span, with an accuracy of 10 seconds
*
* -----------------------------------------
*/
// load connection info from config
var connection = config.redis;
var redisConnected = false;
var pass = null;
if(!connection) {
throw Error('REDIS connection details must be included in config.');
}
// workaround for the throttle module not properly authorizing client
// if a password is present, we'll save it locally and delete it from the options
// so that redis won't try to auth again.
if(connection.options && connection.options.auth_pass) {
pass = connection.options.auth_pass;
delete connection.options.auth_pass;
}
// create our Throttle
Throttle.configure(connection);
// if we have a password, authorize
if(pass) {
Throttle.rdb.auth(pass, function() {
console.info('REDIS Server connected');
});
}
// current setting is 2 requests per minute
var rateLimit = 5;
var rateLimitMessage = 'Exceeded limit of 5 requests per minute, try again later';
var rateSpan = 1 * 60 * 1000; // 1 minute
var rateAccuracy = 1 * 60 * 1000; // 1 minute span should be divisible by accuracy
exports.throttle = function(req, res, next) {
// api key from req.vendor
var key = req.vendor.apiKey;
// create throttle instance for this api key
var throttle = new Throttle(key, {
span: rateSpan,
accuracy: rateAccuracy
});
throttle.increment(1, function(err, count) {
if (err) throw err;
console.info('vendor %s with api key %s has accessed api %s times within %s',
req.vendor.name,
throttle.key,
count,
(throttle.span / 60 / 1000) + ' mins'
);
if(count > rateLimit) {
return res.failure(rateLimitMessage, 503);
} else {
next();
}
});
};
| JavaScript | 0 | @@ -1184,16 +1184,46 @@
true%7D)%0A
+ .populate('programs')%0A
@@ -2535,549 +2535,88 @@
%0A%7D%0A%0A
-// workaround for the throttle module not properly authorizing client%0A// if a password is present, we'll save it locally and delete it from the options%0A// so that redis won't try to auth again.%0Aif(connection.options && connection.options.auth_pass) %7B%0A pass = connection.options.auth_pass;%0A delete connection.options.auth_pass;%0A%7D%0A%0A// create our Throttle%0AThrottle.configure(connection);%0A%0A// if we have a password, authorize%0Aif(pass) %7B%0A Throttle.rdb.auth(pass, function() %7B%0A console.info('REDIS Server connected');%0A %7D); %0A%7D
+console.log(connection);%0A%0A// create our Throttle%0AThrottle.configure(connection);
%0A%0A//
|
a2ae198ccbdb41760cbd863cca67a77895123bdc | Update AudioAPI to use ES6 imports. | cmd/tchaik/ui/js/src/utils/AudioAPI.js | cmd/tchaik/ui/js/src/utils/AudioAPI.js | "use strict";
var NowPlayingConstants = require("../constants/NowPlayingConstants.js");
var NowPlayingActions = require("../actions/NowPlayingActions.js");
var NowPlayingStore = require("../stores/NowPlayingStore.js");
var PlayingStatusStore = require("../stores/PlayingStatusStore.js");
var VolumeStore = require("../stores/VolumeStore.js");
class AudioAPI {
constructor() {
this._audio = new Audio();
this._src = null;
this._playing = false;
this.onPlayerEvent = this.onPlayerEvent.bind(this);
this._audio.addEventListener("error", this.onPlayerEvent);
this._audio.addEventListener("progress", this.onPlayerEvent);
this._audio.addEventListener("play", this.onPlayerEvent);
this._audio.addEventListener("pause", this.onPlayerEvent);
this._audio.addEventListener("ended", this.onPlayerEvent);
this._audio.addEventListener("timeupdate", this.onPlayerEvent);
this._audio.addEventListener("loadedmetadata", this.onPlayerEvent);
this._audio.addEventListener("loadstart", this.onPlayerEvent);
this.update = this.update.bind(this);
this._onNowPlayingControl = this._onNowPlayingControl.bind(this);
this._onVolumeChange = this._onVolumeChange.bind(this);
NowPlayingStore.addChangeListener(this.update);
NowPlayingStore.addControlListener(this._onNowPlayingControl);
VolumeStore.addChangeListener(this._onVolumeChange);
}
init() {
this.update();
this._onVolumeChange();
}
buffered() {
return this._audio.buffered;
}
play() {
return this._audio.play();
}
pause() {
return this._audio.pause();
}
load() {
return this._audio.load();
}
src() {
return this._src;
}
setSrc(src) {
this._audio.src = src;
this._src = src;
}
setCurrentTime(t) {
this._audio.currentTime = t;
}
currentTime() {
return this._audio.currentTime;
}
setVolume(v) {
this._audio.volume = v;
}
volume() {
return this._audio.volume;
}
duration() {
return this._audio.duration;
}
onPlayerEvent(evt) {
switch (evt.type) {
case "error":
NowPlayingActions.setError(evt.srcElement.error);
console.log("Error received from Audio component:");
console.error(evt);
break;
case "progress":
var range = this.buffered();
if (range.length > 0) {
NowPlayingActions.setBuffered(range.end(range.length - 1));
}
break;
case "play":
NowPlayingActions.playing(true);
break;
case "pause":
NowPlayingActions.playing(false);
break;
case "ended":
NowPlayingActions.ended(NowPlayingStore.getSource(), NowPlayingStore.getRepeat());
break;
case "timeupdate":
NowPlayingActions.currentTime(this.currentTime());
break;
case "loadedmetadata":
NowPlayingActions.setDuration(this.duration());
this.setCurrentTime(PlayingStatusStore.getTime());
if (this._playing) {
this.play();
}
break;
case "loadstart":
NowPlayingActions.reset();
break;
default:
console.warn("unhandled player event:");
console.warn(evt);
break;
}
}
_onNowPlayingControl(type, value) {
if (type === NowPlayingConstants.SET_CURRENT_TIME) {
this.setCurrentTime(value);
}
}
update() {
var track = NowPlayingStore.getTrack();
if (track) {
var source = `/track/${track.id}`;
var orig = this.src();
if (orig !== source) {
this.setSrc(source);
this.load();
this.play();
}
}
var prevPlaying = this._playing;
this._playing = NowPlayingStore.getPlaying();
if (prevPlaying !== this._playing) {
if (this._playing) {
this.play();
} else {
this.pause();
}
}
}
_onVolumeChange() {
var v = VolumeStore.getVolume();
if (this.volume() !== v) {
this.setVolume(v);
}
}
}
export default new AudioAPI();
| JavaScript | 0 | @@ -8,19 +8,22 @@
rict%22;%0A%0A
-var
+import
NowPlay
@@ -35,26 +35,21 @@
nstants
-= require(
+from
%22../cons
@@ -73,30 +73,32 @@
onstants.js%22
-)
;%0A
-var
+import
NowPlayingA
@@ -104,26 +104,21 @@
Actions
-= require(
+from
%22../acti
@@ -146,14 +146,16 @@
.js%22
-)
;%0A
-var
+import
Now
@@ -163,34 +163,29 @@
layingStore
-= require(
+from
%22../stores/N
@@ -202,23 +202,25 @@
tore.js%22
-)
;%0A%0A
-var
+import
Playing
@@ -227,34 +227,29 @@
StatusStore
-= require(
+from
%22../stores/P
@@ -273,15 +273,17 @@
.js%22
-)
;%0A%0A
-var
+import
Vol
@@ -295,18 +295,13 @@
ore
-= require(
+from
%22../
@@ -322,17 +322,16 @@
tore.js%22
-)
;%0A%0A%0Aclas
|
833d2a404645c074a7788847cb94c4792fb6f3f1 | Fix #174 by returning the promise to prevent warning | server/controllers/list/delete-lists.js | server/controllers/list/delete-lists.js | const List = require('../../models').list;
const ListSubscriber = require('../../models').listsubscriber;
module.exports = (req, res) => {
const userId = req.user.id;
const listIds = req.body.lists;
List.destroy({
where: { userId, id: listIds }
})
.then(() => {
res.send('Lists deleted');
// Deleting list subscribers may take some time.
// Therefore we can respond when we know that the lists were deleted.
// ListSubscribers will only be deleted when lists have themselves been destroyed.
// Lists will only be destroyed if each listId has an id matching the userId
ListSubscriber.destroy({
where: { listId: listIds }
});
})
.catch(() => {
res.status(400).send('Failed to delete lists');
});
};
| JavaScript | 0 | @@ -602,16 +602,23 @@
rId%0A
+return
ListSubs
|
e35fcf5bfc4310e9c9aa151547176d3d85cd6ea2 | Add passwordless mode back into update | plugins/kalabox-core/lib/tasks/update.js | plugins/kalabox-core/lib/tasks/update.js | 'use strict';
/**
* This contains all the core commands that kalabox can run on every machine
*/
module.exports = function(kbox) {
// Grab our installer
var installer = kbox.install;
kbox.tasks.add(function(task) {
task.path = ['update'];
task.description = 'Run this after you update your Kalabox code.';
task.func = function(done) {
return installer.run({nonInteractive: true})
.nodeify(done);
};
});
};
| JavaScript | 0 | @@ -323,40 +323,321 @@
.';%0A
- task.func = function(done) %7B
+%0A // If on posix pass in a password options%0A if (process.platform !== 'win32') %7B%0A task.options.push(%7B%0A name: 'password',%0A kind: 'string',%0A description: 'Sudo password for admin commands.'%0A %7D);%0A %7D%0A%0A task.func = function(done) %7B%0A var password = this.options.password;
%0A
@@ -681,16 +681,36 @@
ve: true
+, password: password
%7D)%0A
|
6df0720dae2cfb546d8722dc741efa4f8e81726e | improve js error message | web/js/index.js | web/js/index.js | function goLive(element) {
var $el = $(element);
var jobId = $el.data('jobId');
var moduleName = $el.data('jobTargetmodule');
var moduleVersion = $el.data('jobTargetversion');
var message = 'Are you sure you want to go live with [' + moduleName + '] version ' + moduleVersion + '?';
var answer = confirm(message);
if (answer == true) {
var url = '/jobs/' + jobId + '/golive';
var $icon = $el.find('i');
$icon.removeAttr('class');
$icon.addClass('fa').addClass('fa-spinner').addClass('fa-spin');
$.get(url)
.done(function() {
location.reload();
})
.fail(function() {
alert("error");
});
}
}
function rollback(element) {
var $el = $(element);
var moduleName = $el.data('jobTargetmodule');
var moduleVersion = $el.data('jobTargetversion');
var jobId = $el.data('jobId');
var message = 'Are you sure you want to rollback [' + moduleName + '] version ' + moduleVersion + '?';
var answer = confirm(message);
if (answer == true) {
var url = '/jobs/' + jobId + '/rollback';
var $icon = $el.find('i');
$icon.removeAttr('class');
$icon.addClass('fa').addClass('fa-spinner').addClass('fa-spin');
$.get(url)
.done(function() {
location.reload();
})
.fail(function() {
alert("error");
});
}
}
$(function() {
$('[data-toggle="tooltip"]').tooltip();
$("[data-job-go-live]").on('click', function(e) {
goLive(this);
return false;
});
$("[data-job-rollback]").on('click', function(e) {
rollback(this);
return false;
});
}); | JavaScript | 0.000001 | @@ -720,37 +720,103 @@
alert(%22
+An
error
+ occurred, if you don't see the job deploying, please try again
%22);%0A
@@ -1589,21 +1589,90 @@
alert(%22
+An
error
+ occurred, if you don't see the job rolling back, please try again
%22);%0A
|
79da511b255f3f9e1681bff25a27a96d787785e3 | Fix the regression by #636 | src/server/models/Channel.js | src/server/models/Channel.js | /**
* @license MIT License
*
* Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
* Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import {ChannelType} from './ChannelType';
const MODES = [
'~',
'&',
'@',
'%',
'+',
].reverse();
let id = 0;
export class Channal {
/**
* @constructor
* @param {Network} network
* @param {?} attr
*/
constructor(network, attr) {
const data = Object.assign({
id: id++,
messages: [],
name: '',
topic: '',
type: ChannelType.CHANNEL,
unread: 0,
users: []
}, attr);
/** @type {number} */
this.id = data.id;
/** @type {string} */
this.name = data.name;
/** @type {string} */
this.topic = data.topic;
/** @type {ChannelType} */
this.type = data.type;
/** @type {Array} */
this.messages = data.messages;
/** @type {number} */
this.unread = data.unread;
/** @type {Array} */
this.users = data.users;
/** @type {Network} */
this.network = network;
}
/**
* @return {void}
*/
sortUsers() {
this.users = this.users.sort(function(a, b) {
const aName = a.name.toLowerCase();
const bName = b.name.toLowerCase();
if (aName < bName) {
return -1;
}
else if (aName > bName) {
return 1;
}
else {
return 0;
}
});
MODES.forEach(function(mode) {
const filtered = [];
const removed = [];
this.users.forEach(function(u) {
if (u.mode === mode) {
removed.push(u);
}
else {
filtered.push(u);
}
});
this.users = removed.concat(filtered);
}, this);
}
/**
* @param {string} name
* @return {string}
*/
getMode(name) {
const user = this.users.find(function(element){
return element.name === name;
});
if (!!user) {
return user.mode;
}
else {
return '';
}
}
/**
* @return {Channal}
*/
toJSON() {
const clone = Object.assign({}, this);
clone.messages = clone.messages.slice(-100);
clone.network = undefined;
return clone;
}
}
| JavaScript | 0.002719 | @@ -1378,17 +1378,17 @@
ss Chann
-a
+e
l %7B%0A%0A
|
6af02847054a506a5b3c6887a4974ddbb95b3a50 | Enable source-maps. | src/server/webpack.config.js | src/server/webpack.config.js | /*
See:
https://github.com/webpack/webpack-dev-middleware
https://www.npmjs.com/package/webpack-hot-middleware
https://github.com/kriasoft/react-starter-kit/blob/master/webpack.config.js
*/
import webpack from 'webpack';
import fsPath from 'path';
export const PORT = 8080;
const NODE_MODULES_PATH = fsPath.join(__dirname, '../../node_modules');
var modulePath = (path) => fsPath.join(NODE_MODULES_PATH, path);
export var compiler = {
entry: [
'webpack/hot/dev-server',
'webpack-hot-middleware/client',
fsPath.join(__dirname, '../client/components/index.js')
],
output: {
filename: 'bundle.js',
path: '/',
publicPath: `http://localhost:${ PORT }/public`
},
plugins: [
// Hot reload plugins:
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
fallback: NODE_MODULES_PATH,
extensions: ['', '.js', '.jsx'],
/*
Aliases
Ensure common libraries are:
- Module code loaded only once (de-duped)
- Single version of modules are loaded.
*/
alias: {
'react': modulePath('react'),
'lodash': modulePath('lodash'),
'immutable': modulePath('immutable'),
'bluebird': modulePath('bluebird')
}
},
resolveLoader: { fallback: NODE_MODULES_PATH },
module: {
loaders: [
// ES6/JSX.
{ test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader' },
{ test: /\.jsx$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader' }
]
}
};
export var options = {
noInfo: true, // Suppress boring information.
quiet: false, // Don’t output anything to the console.
lazy: false,
watchOptions: {
aggregateTimeout: 300,
poll: true
},
publicPath: compiler.output.publicPath,
stats: { colors: true }
};
| JavaScript | 0 | @@ -589,16 +589,17 @@
')%0A %5D,%0A
+%0A
output
@@ -702,16 +702,61 @@
%60%0A %7D,%0A%0A
+ devtool: '#cheap-module-eval-source-map',%0A%0A
plugin
|
aa0ce7097bccee3a0a8e2baf5359ddebceb8b269 | update string/case-paragraph adjust dependencies | src/string/case-paragraph.js | src/string/case-paragraph.js | var toString = require('../lang/toString')
var lowerCase = require('./case-lower')
var upperCase = require('./case-upper')
// UPPERCASE first cha of each sentence and lowercase other chars
function sentenceCase (str) {
str = toString(str)
// replace first char of each sentence (new line or after '.\s+') to
// UPPERCASE
return lowerCase(str).replace(/(^\w)|\.\s+(\w)/gm, upperCase)
}
module.exports = sentenceCase
| JavaScript | 0.000001 | @@ -1,20 +1,21 @@
var
-toS
+s
tring
+ify
= requi
@@ -23,23 +23,18 @@
e('.
-./lang/toS
+/s
tring
+ify
')%0Av
@@ -116,25 +116,23 @@
r')%0A%0A//
-UPPERCASE
+replace
first c
@@ -133,16 +133,17 @@
irst cha
+r
of each
@@ -152,16 +152,59 @@
entence
+(new line or after '.%5Cs+') to%0A// UPPERCASE
and lowe
@@ -256,117 +256,8 @@
) %7B%0A
- str = toString(str)%0A%0A // replace first char of each sentence (new line or after '.%5Cs+') to%0A // UPPERCASE%0A
re
@@ -274,16 +274,27 @@
Case(str
+ingify(str)
).replac
|
aa7a1543b2e48a2deed687d703b521dced4c495d | Remove app specific code. | src/text/simple_text_view.js | src/text/simple_text_view.js | "use strict";
var _ = require("underscore");
var Application = require("substance-application");
var $$ = Application.$$;
var NodeView = require("../node/node_view");
var Fragmenter = require("substance-util").Fragmenter;
var Annotator = require("substance-document").Annotator;
var SimpleTextView = function(node, viewFactory) {
NodeView.call(this, node, viewFactory);
};
SimpleTextView.Prototype = function() {
var __super__ = NodeView.prototype;
this.render = function() {
__super__.render.call(this);
this.content.setAttribute("data-path", "content");
this.renderContent();
return this;
};
this.renderContent = function() {
var annotations = this.node.document.getIndex("annotations").get([this.node.id, "content"]);
this.renderWithAnnotations(annotations);
var br = window.document.createElement("BR");
this.content.appendChild(br);
};
this.createAnnotationElement = function(entry) {
var el;
el = $$('span.annotation.'+entry.type, {
id: entry.id
});
var doc = this.node.document;
if (entry.type === "product_reference") {
var productRef = doc.get(entry.id);
var category_code = doc.external.getProductCategoryCode(productRef.product_id);
el.classList.add("category-"+category_code);
}
return el;
};
this.renderWithAnnotations = function(annotations) {
var self = this;
var text = this.node.content;
var fragment = window.document.createDocumentFragment();
var fragmenter = new Fragmenter(this.node.document.getAnnotationBehavior().levels);
fragmenter.onText = function(context, text) {
var el = window.document.createTextNode(text);
context.appendChild(el);
};
fragmenter.onEnter = function(entry, parentContext) {
var el = self.createAnnotationElement(entry);
parentContext.appendChild(el);
return el;
};
// this calls onText and onEnter in turns...
fragmenter.start(fragment, text, annotations);
// set the content
this.content.innerHTML = "";
this.content.appendChild(fragment);
};
this.onNodeUpdate = function(op) {
if (_.isEqual(op.path, [this.node.id, "content"])) {
this.renderContent();
return true;
}
return false;
};
this.onGraphUpdate = function(op) {
// Call super handler and return if that has processed the operation already
if (__super__.onGraphUpdate.call(this, op)) {
return true;
}
// Otherwise deal with annotation changes
if (Annotator.changesAnnotations(this.node.document, op, [this.node.id, "content"])) {
if (op.type === "create" || op.type === "delete" ||
op.path[1] === "path" || op.path[1] === "range") {
this.renderContent();
return true;
}
}
return false;
};
};
SimpleTextView.Prototype.prototype = NodeView.prototype;
SimpleTextView.prototype = new SimpleTextView.Prototype();
SimpleTextView.prototype.constructor = SimpleTextView;
module.exports = SimpleTextView;
| JavaScript | 0 | @@ -1027,276 +1027,8 @@
%7D);%0A
-%0A var doc = this.node.document;%0A%0A if (entry.type === %22product_reference%22) %7B%0A var productRef = doc.get(entry.id);%0A var category_code = doc.external.getProductCategoryCode(productRef.product_id);%0A el.classList.add(%22category-%22+category_code);%0A %7D%0A%0A
|
19a8015d1e7fe4185e233eff1edb96ca53b6a34c | fix merge conflicts | server/db/controllers/userController.js | server/db/controllers/userController.js | var models = require('../models');
var jwt = require('jwt-simple');
var helpers = require('../../config/helpers.js');
var sendGrid = require('../../email/sendGrid.js');
var data = require('../../data.js');
var _ = require('underscore');
module.exports = {
signup: function(req, res, next) {
var username = req.body.email;
var password = req.body.password;
models.User.findAll({
where: {
username: username
}
})
.spread(function(user) {
if (user) {
if (user.registered) {
res.status(403).send({error: 'User already exist!'});
next(new Error('User already exist!'));
}
else {
user.update({
password: password,
registered: true
})
}
} else {
return models.User.create({
username: username,
password: password,
registered: true
})
}
})
.then(function(user) {
var token = jwt.encode(user, 'secret');
res.json({token: token});
})
.catch(function(error) {
next(error);
});
},
signin: function(req, res, next) {
var username = req.body.email;
var password = req.body.password;
models.User.findAll({
where: {
username: username
}
})
.spread(function(user) {
if (!user) {
res.status(401).send({error: 'User does not exist'});
next(new Error('User does not exist'));
} else {
return user.checkPassword(password)
.then(function(foundUser) {
if (foundUser) {
var token = jwt.encode(user, 'secret');
// compile locations, rooms, reservations
helpers.getAllData(user)
.then(function(result) {
console.log(result[0].length);
var locations = _.map(result[0], function(val, index, list) {
return val.json_build_object;
});
res.json({
username: user.username,
token: token,
data: {locations: locations}
});
});
} else {
res.status(401).send('User or password is incorrect');
next(new Error('User or password is incorrect'));
}
})
.catch(function(error) {
next(error);
});
}
})
},
checkAuth: function(req, res, next) {
var token = req.headers['x-access-token'];
if (!token) {
next(new Error('no token'));
} else {
var user = jwt.decode(token, 'secret');
models.User.findAll({
where: {
username: user.username
}
})
.spread(function(foundUser) {
if (foundUser) {
res.status(200).send();
} else {
res.status(401).send();
}
})
.catch(function(error) {
next(error);
});
}
},
addPendingUser: function(req, res, next) {
var username = req.body.email;
models.User.findAll({
where: {
username: username
}
})
.spread(function(user) {
if (user) {
if (user.registered) {
res.status(403).send({error: 'User is already registered!'});
next(new Error('User already registered!'));
} else {
res.status(403).send({error: 'User is already pending'});
next(new Error('User is already pending'));
}
} else {
models.User.create({
username: username,
registered: false
})
.then(function(user) {
sendGrid.signupEmail(user.username);
})
.catch(function(error) {
next(error);
});
}
})
.catch(function(error) {
next(error);
});
}
}
| JavaScript | 0.000091 | @@ -202,39 +202,8 @@
s');
-%0Avar _ = require('underscore');
%0A%0Amo
@@ -1676,16 +1676,30 @@
+ var allData =
helpers
@@ -1719,53 +1719,10 @@
ser)
+;
%0A
- .then(function(result) %7B%0A
@@ -1731,17 +1731,16 @@
-
console.
@@ -1747,24 +1747,15 @@
log(
-result%5B0%5D.length
+allData
);%0A
@@ -1771,190 +1771,48 @@
-
- var locations = _.map(result%5B0%5D, function(val, index, list) %7B%0A return val.json_build_object;%0A %7D);%0A %0A res.json(%7B%0A
+res.json(%7B%0A id: user.id,%0A
@@ -1840,36 +1840,32 @@
user.username,%0A
-
@@ -1898,45 +1898,29 @@
-
data:
-%7Blocations: locations%7D%0A
+data.user.data%0A
@@ -1933,50 +1933,12 @@
-
%7D);%0A
- %7D);%0A %0A
@@ -3655,10 +3655,9 @@
%7D);%0A %7D%0A
+
%7D
-%0A
|
60175d78ce0e732274ac8e764a0d92277bf758ce | Add user._id to interest document. | server/interests/interestsController.js | server/interests/interestsController.js | var Interests = require('./interests.server.model.js');
var Q = require('q');
module.exports = {
add: function (req, res, next) {
var interest = {};
interest.id = req.body.id;
//interest.user = req.user._id;
var addInterest = Q.nbind(Interests.create, Interests);
addInterest(interest)
.then(function (addedInterest) {
if (addedInterest) {
res.json(addedInterest);
}
})
.fail(function (error) {
next(error);
});
}
}; | JavaScript | 0 | @@ -188,10 +188,8 @@
-//
inte
|
2938138bd8243ab7862029605e7a8ff60a169b24 | Add readByEmail function to PoetsRepository | server/repositories/poets_repository.js | server/repositories/poets_repository.js | var _ = require('underscore');
module.exports = function(dbConfig) {
var db = require('./poemlab_database')(dbConfig);
return {
create: function(user_data, callback) {
var params = _.values(_.pick(user_data, ["username", "email", "password"]));
db.query("insert into poets (name, email, password) values ($1, $2, $3) " +
"returning id, name, email", params,
function(err, result) {
if (err) { return callback(err); }
callback(null, result.rows[0]);
}
);
},
read: function(user_id, callback) {
db.query("select * from poets where id = $1", [user_id], function(err, result) {
if (err) { return callback(err); }
callback(null, result.rows[0]);
});
},
readByUsername: function(username, callback) {
db.query("select * from poets where name = $1", [username], function(err, result) {
if (err) { return callback(err); }
callback(null, result.rows[0]);
});
},
search: function(query, callback) {
db.query("select * from poets where name ilike $1 limit 20", [query + "%"], function(err, result) {
if (err) { return callback(err); }
callback(null, result.rows);
});
},
destroy: function(user_id, callback) {
db.query("delete from poets where id = $1", [user_id], function(err, result) {
callback(err);
});
},
all: function(callback) {
db.query("select * from poets", [], function(err, result) {
if (err) { return callback(err); }
callback(null, result.rows);
});
}
};
};
| JavaScript | 0 | @@ -925,16 +925,232 @@
;%0A%09%09%7D,%0A%0A
+%09%09readByEmail: function(email, callback) %7B%0A%09%09%09db.query(%22select * from poets where email = $1%22, %5Bemail%5D, function(err, result) %7B%0A%09%09%09%09if (err) %7B return callback(err); %7D%0A%09%09%09%09callback(null, result.rows%5B0%5D);%0A%09%09%09%7D);%0A%09%09%7D,%0A%0A
%09%09search
|
f791ce3b55f6e7fdd2bd3a2edeb5674ccee103a3 | fix bug signup | server/data/user.js | server/data/user.js | var util = require("util"),
BaseData = require("./base"),
mongoose = require('mongoose'),
kits = require("../kits");
function UserData(schema) {
this.Schema = schema;
BaseData.call(this, mongoose.model("user", schema));
/**
* add user
* @param name
* @param email
* @param password
* @param callback
*/
this.add = function (name, email, password, callback) {
var salt = kits.utils.short_guid();
var db_password = kits.utils.md5(password + salt);
var user = new this.model({
id : kits.utils.short_guid(),
name : name,
email : email,
password: db_password,
salt : salt,
role : constant.user.role.supper_admin
});
user.save(function (err) {
return callback(err);
});
};
this.update = function (uid, name, desc, callback) {
var update = {
$set: {
name : name,
desc : desc,
update_date: new Date().getTime()
}
};
this.model.update({id: uid}, update, callback);
};
this.update_avatar = function (uid, type, path, callback) {
var update = {
$set: {
avatar : {
type: type,
path: path
},
update_date: new Date().getTime()
}
};
this.model.update({id: uid}, update, callback);
};
this.update_passowrd = function (uid, password, callback) {
var update = {
$set: {
password : password,
update_date: new Date().getTime()
}
};
this.model.update({id: uid}, update, callback);
};
/**
* check user by name and email
* @param name
* @param email
* @param callback
*/
this.check = function (name, email, callback) {
var name_pattern = '^' + name + '$';
var email_pattern = '^' + email + '$';
if (email.indexOf("+") >= 0) {
email_pattern = email_pattern.replace(/\+/i, "\\+");
}
var query = {
"$or" : [
{ name: {$regex: name_pattern, $options: 'i'}},
{ email: {$regex: email_pattern, $options: 'i'}}
],
is_deleted: 0
};
this.model.findOne(query, function (err, user) {
return callback(err, user);
});
};
this.get_list_by_uids = function (uids, callback) {
this.model.find({id: {$in: uids}, is_deleted: kits.constant.is_deleted.no}, callback);
};
this.get_or_create = function (profile, callback) {
callback(null, profile);
}
};
util.inherits(UserData, BaseData);
module.exports = UserData; | JavaScript | 0 | @@ -740,16 +740,21 @@
le :
+kits.
constant
|
425e00ccac4a0d2bdd86fa99f3ad27b99d183be2 | Add typeahead suggestions based on repository names | web/static/js/pick.js | web/static/js/pick.js |
var bloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: repositories,
});
function matchWithDefaults(q, sync) {
if (q === '') {
sync(bloodhound.get(repositories));
} else {
bloodhound.search(q, sync);
}
}
$('.typeahead').typeahead({
hint: true,
minLength: 0,
highlight: true,
}, {
name: 'respositories',
source: matchWithDefaults,
});
| JavaScript | 0 | @@ -1,8 +1,140 @@
+%0A%0Afunction customTokenizer(datum) %7B%0A var repository = datum.substring(datum.indexOf('/') + 1);%0A return %5Bdatum, repository%5D;%0A%7D%0A
%0Avar blo
@@ -184,44 +184,23 @@
er:
-Bloodhound.tokenizers.obj.whitespace
+customTokenizer
,%0A
@@ -281,16 +281,41 @@
s,%0A%7D);%0A%0A
+bloodhound.initialize()%0A%0A
function
@@ -452,16 +452,17 @@
%7D%0A%7D%0A%0A
+%0A
$('.type
@@ -554,17 +554,16 @@
ame: 're
-s
positori
|
25860c27a8a2f059adf9c5371a24e5197afe8a4f | Add JFCustomWidget.sendData when list of files updated | widget/index.js | widget/index.js | /* global JFCustomWidget, uploadcare */
/**
* Resize JotForm widget frame
*
* @param width
* @param height
*/
function resize(width, height) {
JFCustomWidget.requestFrameResize({
width: width,
height: height,
})
}
function cropOption(mode, width, height) {
switch (mode) {
case 'free crop':
return 'free'
break
case 'aspect ratio':
return parseInt(width) + ':' + parseInt(height)
break
case 'downscale':
return parseInt(width) + 'x' + parseInt(height)
break
case 'downscale & upscale':
return parseInt(width) + 'x' + parseInt(height) + ' upscale'
break
case 'downscale & minimum size':
return parseInt(width) + 'x' + parseInt(height) + ' minimum'
break
default:
return 'disabled'
}
}
JFCustomWidget.subscribe('ready', function(data) {
var isMultiple = (JFCustomWidget.getWidgetSetting('multiple') === 'Yes')
var hasEffectsTab = (JFCustomWidget.getWidgetSetting('effectsTab') === 'Yes')
var globalSettings = JFCustomWidget.getWidgetSetting('globalSettings')
if (globalSettings) {
var script = document.createElement('script')
script.innerHTML = globalSettings
document.head.appendChild(script)
}
if (hasEffectsTab) {
var effectsTabScript = document.createElement('script')
var indexScript = document.getElementById('index-script')
effectsTabScript.addEventListener('load', function() {
if (window.uploadcareTabEffects) {
uploadcare.registerTab('preview', window.uploadcareTabEffects)
}
})
effectsTabScript.src = 'https://ucarecdn.com/libs/widget-tab-effects/1.x/uploadcare.tab-effects.min.js'
indexScript.parentNode.insertBefore(effectsTabScript, indexScript)
}
uploadcare.start({
publicKey: JFCustomWidget.getWidgetSetting('publicKey'),
locale: JFCustomWidget.getWidgetSetting('locale') || 'en',
imagesOnly: (JFCustomWidget.getWidgetSetting('imagesOnly') === 'Yes'),
previewStep: (JFCustomWidget.getWidgetSetting('previewStep') === 'Yes'),
multiple: isMultiple,
multipleMin: JFCustomWidget.getWidgetSetting('multipleMin'),
multipleMax: JFCustomWidget.getWidgetSetting('multipleMax'),
crop: cropOption(
JFCustomWidget.getWidgetSetting('crop'),
JFCustomWidget.getWidgetSetting('cropWidth'),
JFCustomWidget.getWidgetSetting('cropHeight')
),
imageShrink: JFCustomWidget.getWidgetSetting('imageShrink'),
effects: JFCustomWidget.getWidgetSetting('effects'),
})
var widget = uploadcare.Widget('[role=uploadcare-uploader]')
widget.onDialogOpen(function(dialog) {
resize(618, 600)
dialog.always(function() {
resize(458, 40)
})
})
var files = (data && data.value) ? data.value.split('\n') : []
if (files.length) {
widget.value(isMultiple ? files : files[0])
}
widget.onChange(function(file) {
files = []
if (file) {
var uploadedFiles = file.files ? file.files() : [file]
uploadedFiles.forEach(function(uploadedFile) {
uploadedFile.done(function(fileInfo) {
files.push(fileInfo.cdnUrl)
})
})
}
})
JFCustomWidget.subscribe('submit', function() {
var msg = {
valid: !!files.length,
value: files.join('\n'),
}
JFCustomWidget.sendSubmit(msg)
})
})
| JavaScript | 0 | @@ -2972,16 +2972,165 @@
%09%7D)%0A%09%09%7D%0A
+%09%09else %7B%0A%09%09%09JFCustomWidget.sendData(%7Bvalue: ''%7D)%0A%09%09%7D%0A%09%7D)%0A%0A%09widget.onUploadComplete(function() %7B%0A%09%09JFCustomWidget.sendData(%7Bvalue: files.join('%5Cn')%7D)%0A
%09%7D)%0A%0A%09JF
|
52f0afac2f844e1071123eb9eb7c7247ec9b4ad7 | test loading on heroku | webpack.dev.config.js | webpack.dev.config.js | var webpack = require('webpack'),
path = require('path'),
autoprefixer = require('autoprefixer'),
precss = require('precss');
module.exports = {
context: __dirname,
entry:[
'webpack-hot-middleware/client',
'./src/js/client.js'
],
output: {
path: '/',// must have some val here
publicPath: '/js/',
filename: '[name].js'
},
devtool: 'source-map',
module: {
loaders: [
{
test: /\.scss$/,
include: /src/,
loader: 'style!css?sourceMap!sass?sourceMap'
},
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015']
}
}
]
},
postcss: function () {
return [autoprefixer({ browsers: ['last 2 versions'] }), precss];
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js', '.json']
}
};
| JavaScript | 0 | @@ -252,16 +252,17 @@
s/client
+2
.js'%0A
|
e57f6ca228de5d2a39a143975e38dfbc88bf2cc6 | remove unused context function | packages/d3fc-series/src/webgl/line.js | packages/d3fc-series/src/webgl/line.js | import xyBase from '../xyBase';
import { glLine, scaleMapper } from '@d3fc/d3fc-webgl';
import { rebindAll, exclude, rebind } from '@d3fc/d3fc-rebind';
export default () => {
const base = xyBase();
let context = null;
const draw = glLine();
const line = (data) => {
const xScale = scaleMapper(base.xScale());
const yScale = scaleMapper(base.yScale());
const accessor = getAccessors();
const x = new Float32Array(data.length);
const y = new Float32Array(data.length);
const defined = new Float32Array(data.length);
data.forEach((d, i) => {
x[i] = xScale.scale(accessor.x(d, i));
y[i] = yScale.scale(accessor.y(d, i));
defined[i] = accessor.defined(d, i);
});
draw.xValues(x)
.yValues(y)
.defined(defined)
.xScale(xScale.glScale)
.yScale(yScale.glScale)
.decorate((program) => {
base.decorate()(program, data, 0);
});
draw(data.length);
};
function getAccessors() {
if (base.orient() === 'vertical') {
return {
x: base.crossValue(),
y: base.mainValue(),
defined: base.defined()
};
} else {
return {
x: base.mainValue(),
y: base.crossValue(),
defined: base.defined()
};
}
}
line.context = (...args) => {
if (!args.length) {
return context;
}
context = args[0];
return line;
};
rebindAll(line, base, exclude('baseValue', 'bandwidth', 'align'));
rebind(line, draw, 'context', 'lineWidth');
return line;
};
| JavaScript | 0.000341 | @@ -199,32 +199,8 @@
e();
-%0A let context = null;
%0A%0A
@@ -1454,164 +1454,8 @@
%7D%0A%0A
- line.context = (...args) =%3E %7B%0A if (!args.length) %7B%0A return context;%0A %7D%0A context = args%5B0%5D;%0A return line;%0A %7D;%0A%0A
|
854f71cc5514793246e3d5eb3e3b3e3f7876c28e | Add client-side routing support to dev server | webpack.dev.config.js | webpack.dev.config.js | var path = require('path');
var webpack = require('webpack');
var config = require('./webpack.config');
config.output = {
path: './dist/',
publicPath: '/',
filename: '[name].bundle.js'
};
config.devServer = {
contentBase: 'dist'
};
config.plugins.push(
new webpack.HotModuleReplacementPlugin()
);
module.exports = config;
| JavaScript | 0 | @@ -230,16 +230,44 @@
: 'dist'
+,%0A historyApiFallback: true
%0A%7D;%0Aconf
|
3048d032445c1a803221b589b959fd8334e096aa | change port to 8081 | webpack.dev.config.js | webpack.dev.config.js | var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ENV = process.env.ENV = process.env.NODE_ENV = 'development';
module.exports = {
context: path.join(__dirname, 'src'),
entry: [
'webpack-dev-server/client?http://0.0.0.0:8080',
'webpack/hot/only-dev-server',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
},
plugins: [
new HtmlWebpackPlugin({ template: './index.html' }),
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(ENV),
'NODE_ENV': JSON.stringify(ENV)
}
})
],
module: {
loaders: [
{
test: /\.js$/,
loader: 'react-hot',
include: path.join(__dirname, 'src')
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'stage-0', 'react'],
}
},
{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
loaders: [ 'style-loader', 'css-loader' ]
},
],
devServer: {
host: '0.0.0.0',
port: 8080
}
}
}; | JavaScript | 0.000025 | @@ -298,17 +298,17 @@
.0.0:808
-0
+1
',%0A '
@@ -1256,8 +1256,9 @@
%7D%0A %7D%0A%7D;
+%0A
|
f6dec0d1557877ba9f323d86b0eba9b862b062a6 | Add HTML/XML syntax highlighting | assets/js/application.js | assets/js/application.js | import hljs from 'highlight.js/lib/highlight'
import apache from 'highlight.js/lib/languages/apache'
import bash from 'highlight.js/lib/languages/bash'
import css from 'highlight.js/lib/languages/css'
import markdown from 'highlight.js/lib/languages/markdown'
import dockerfile from 'highlight.js/lib/languages/dockerfile'
import go from 'highlight.js/lib/languages/go'
import gradle from 'highlight.js/lib/languages/gradle'
import http from 'highlight.js/lib/languages/http'
import java from 'highlight.js/lib/languages/java'
import javascript from 'highlight.js/lib/languages/javascript'
import json from 'highlight.js/lib/languages/json'
import kotlin from 'highlight.js/lib/languages/kotlin'
import nginx from 'highlight.js/lib/languages/nginx'
import php from 'highlight.js/lib/languages/php'
import scss from 'highlight.js/lib/languages/scss'
import swift from 'highlight.js/lib/languages/swift'
import yaml from 'highlight.js/lib/languages/yaml'
import typescript from 'highlight.js/lib/languages/typescript'
hljs.registerLanguage('apache', apache)
hljs.registerLanguage('bash', bash)
hljs.registerLanguage('css', css)
hljs.registerLanguage('markdown', markdown)
hljs.registerLanguage('dockerfile', dockerfile)
hljs.registerLanguage('go', go)
hljs.registerLanguage('gradle', gradle)
hljs.registerLanguage('http', http)
hljs.registerLanguage('java', java)
hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('json', json)
hljs.registerLanguage('kotlin', kotlin)
hljs.registerLanguage('nginx', nginx)
hljs.registerLanguage('php', php)
hljs.registerLanguage('scss', scss)
hljs.registerLanguage('yaml', yaml)
hljs.registerLanguage('typescript', typescript)
hljs.initHighlightingOnLoad()
| JavaScript | 0.000002 | @@ -1008,16 +1008,65 @@
escript'
+%0Aimport xml from 'highlight.js/lib/languages/xml'
%0A%0Ahljs.r
@@ -1720,16 +1720,50 @@
escript)
+%0Ahljs.registerLanguage('xml', xml)
%0A%0Ahljs.i
|
8e18800e9cdb265af16feea42e9687da4f280322 | remove manifest | webpack.dev.config.js | webpack.dev.config.js | const webpack = require("webpack");
const config = require("./webpack.base.config");
config.module.rules.push(
{
enforce: "pre",
test: /\.jsx?$/,
use: ["eslint-loader"],
exclude: /node_modules/
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
include: /node_modules/
},
{
test: /\.less$/,
use: ["style-loader", "css-loader", "less-loader"],
include: /node_modules/
},
{
test: /\.less$/,
use:
[
"style-loader",
{
loader: "css-loader",
options:
{
modules: true,
sourceMap: true,
localIdentName: "[name]-[local]"
}
},
"less-loader"
],
exclude: /node_modules/
}
);
config.plugins.push(
new webpack.SourceMapDevToolPlugin({
filename: "[file].map",
exclude: ["vendor.js", "manifest.js"]
})
);
// HMR.
for (const key of Object.keys(config.entry))
{
config.entry[key].unshift(
"react-hot-loader/patch",
"webpack-hot-middleware/client?quiet=true"
);
}
config.plugins.push(
new webpack.HotModuleReplacementPlugin()
);
module.exports = config;
| JavaScript | 0.000006 | @@ -1,5 +1,4 @@
-%EF%BB%BF
cons
@@ -1016,23 +1016,8 @@
.js%22
-, %22manifest.js%22
%5D%0A
|
4f8c5e1d974224e84db5d02faca54971682143a5 | Implement it so it runs whenever the page loads. fixes #113 | assets/js/change-font.js | assets/js/change-font.js | var isDyslexic = false;
function fontCookieCheck() {
var infoInCookie = readCookie('178fontcookie');
isDyslexic = eval(infoInCookie);
if (!infoInCookie) {
fontAlert1();
} else {
if (isDyslexic == true) {
var font = "Open Dyslexic";
} else {
var font = "Open Sans";
}
setFont(font);
}
}
function fontAlert1() {
if (($(window).height() <= 565 && $(window).width() <= 675) || ($(window).height() <= 420) || ($(window).width() <= 420)) {
isDyslexic = confirm("Would you like to use a Dyslexia friendly font on this website?");
if (isDyslexic == true) {
createFontCookie("true");
alert("The font is now set to Open Dyslexic.\n\nTo change your settings, use the switch at the bottom of the page.")
} else {
createFontCookie("false")
alert("The font is the same font it's always been.\n\nTo change your settings, use the switch at the bottom of the page.")
}
} else {
$(".swal2-modal").css('fontFamily', 'Open Dyslexic');
$("button").css('fontFamily', 'Open Dyslexic');
swal({
title: 'Dyslexia Font',
text: 'To use the dyslexia friendly font <i>Open Dyslexic</i> on this site, select the button below.',
type: 'info',
showCancelButton: true,
confirmButtonText: 'Open Dyslexic',
allowOutsideClick: false,
allowEscapeKey: false,
}).then(function setFont4Cookie(isConfirm) {
if (isConfirm) {
createFontCookie("true");
swal({
title: 'You\'ve set the font!',
text: 'To change your settings, toggle the switch at the bottom of the page.',
showCloseButton: true,
type: 'success',
});
} else if (isConfirm == false) {
createFontCookie("false");
swal({
title: 'You\'ve kept the same font!',
text: 'To change your settings, toggle the switch at the bottom of the page.',
showCloseButton: true,
type: 'success',
});
} else {
swal(
'Uhhhh...',
'So... This shouldn\'t be possible. I\'m not sure why this happened... Email me: timtv25@gmail.com',
'error'
);
}
});
}
}
function createFontCookie(font4Cookie) {
createCookie('178fontcookie',font4Cookie,5475);
isDyslexic = eval(font4Cookie);
fontCookieCheck();
}
function toggleFont() {
if (isDyslexic == true) {
isDyslexic = false;
setFont("Open Sans");
} else {
isDyslexic = true;
setFont("Open Dyslexic");
}
createFontCookie(isDyslexic.toString());
}
function setFont(font) {
if (font != null) {
$("body").css('fontFamily', font);
$(".swal2-modal").css('fontFamily', font);
$("button").css('fontFamily', font);
$("#font-stuff").css('display', 'block');
// TODO: Make things look *more* correct by setting specific styles to be different.
// This part makes everything zoom out to look like it's the right size:
if (isDyslexic == true) {
$('body').css('zoom', .95);
$('.switch-input')[0].checked = true;
} else {
$('.switch-input')[0].checked = false;
$('body').css('zoom', 1);
}
}
}
/*$( window ).load(fontCookieCheck);*/ // Runs the function fontCookieCheck everytime the page loads.
| JavaScript | 0.000009 | @@ -3168,20 +3168,16 @@
%0A%7D%0A%0A
-/*
$(
-
window
-
).lo
@@ -3200,10 +3200,8 @@
ck);
-*/
//
|
841ebb6a92aeb8bc61169ae99e6d6d2fe04818c4 | change js | assets/js/editStudent.js | assets/js/editStudent.js | function saveStudent(studentId) {
var modal = $('#myModal-' + studentId);
modal.find('.errors').html('').removeClass('eroare-edit');
$.post( "/students/update",
$("#form-update-student-" + studentId).serialize()
)
.done(function( data ) {
response = JSON.parse(data);
if (response.status == 'success') {
modal.on('hidden.bs.modal', function () {
$(this).data('bs.modal', null);
});
$('#status-update-student').removeClass('hidden').addClass('reusit').html('Studentul a fost salvat cu succes!');
} else {
var str = "";
for(x in response.errors){
str = str.concat(response.errors[x], "<br>");
}
modal.find('.errors').removeClass('hidden').addClass('eroare-edit').html(str);
}
});
}
| JavaScript | 0.000003 | @@ -334,87 +334,20 @@
dal.
-on('hidden.bs.modal', function () %7B%0A%09%09%09 $(this).data('bs.modal', null);%0A%09%09%09%7D
+modal(%22hide%22
);%0A%09
|
b4f9a625f7184fa07397580c8bde3c305fb7dbee | Update jquery-main.js | assets/js/jquery-main.js | assets/js/jquery-main.js | $("document").ready(function() {
//Add interaction to navbar when mouse hover it's elements.
$(".nav").on({
mouseover: function () {
$("li:hover").addClass("active");
},
mouseout: function () {
$("li").removeClass("active");
}
});
//Smooth scroll
$(".navbar-collapse ul li a[href^='#']").on('click', function(e) {
// Prevent default anchor click behavior
e.preventDefault();
// Store hash
var hash = this.hash;
// Animation
$("html, body").animate({
scrollTop: $(this.hash).offset().top -50
}, 400, function(){
// When done, add hash to url
// (default click behavior)
window.location.hash = hash;
});
});
//Adds Smooth Scrool to Back to Top button
$("#arrow a[href^='#']").on('click', function(e) {
// Prevent default anchor click behavior
e.preventDefault();
// Store hash
var hash = this.hash;
// Animation
$("html, body").animate({
scrollTop: $(this.hash).offset().top -50
}, 400, function(){
// When done, add hash to url
// (default click behavior)
window.location.hash = hash;
});
});
//Adds Smooth Scrool to Back to Top button
$("footer #btt a[href^='#']").on('click', function(e) {
// Prevent default anchor click behavior
e.preventDefault();
// Store hash
var hash = this.hash;
// Animation
$("html, body").animate({
scrollTop: $(this.hash).offset().top -50
}, 400, function(){
// When done, add hash to url
// (default click behavior)
window.location.hash = hash;
});
});
});
| JavaScript | 0.000001 | @@ -734,33 +734,25 @@
rool to
-Back to Top butto
+arrwo dow
n%0A $(%22#
|
ec45da80b0134a8605a7c6404c4a48f792b9df77 | clear session state on session error action | web/static/js/reducers/app_reducer.js | web/static/js/reducers/app_reducer.js | import Constants from "../constants";
const initialState = {
request: {
isFetching: false,
lastUpdated: Date.now()
},
session: {
user: {},
jwt: ""
}
};
function appReducer (state = initialState, action) {
switch (action.type) {
case Constants.ACTIONS.NEW_SESSION_REQUEST:
return Object.assign({}, state, {
request: {
isFetching: true,
lastUpdated: Date.now()
}
})
case Constants.ACTIONS.NEW_SESSION_SUCCESS:
return Object.assign({}, state, {
request: {
isFetching: false,
msg: "Successfully signed in",
lastUpdated: Date.now()
},
session: {
user: action.user,
jwt: action.jwt
}
})
case Constants.ACTIONS.NEW_SESSION_FAILURE:
return Object.assign({}, state, {
request: {
isFetching: false,
msg: action.msg,
lastUpdated: Date.now()
}
})
default:
return state
}
};
export default appReducer
| JavaScript | 0 | @@ -905,23 +905,16 @@
msg:
-action.
msg,%0A
@@ -936,32 +936,100 @@
ted: Date.now()%0A
+ %7D,%0A session: %7B%0A user: %7B%7D,%0A jwt: %22%22%0A
%7D%0A
|
01488dc175727d5f83434a8919800a0735634096 | Update main.js | resources/app/main.js | resources/app/main.js | var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require('menu');
var MenuItem = require('menu-item');
var Tray = require('tray');
var ipc = require('ipc')
var globalShortcut = require('global-shortcut');
var shell = require('shell');
var path = require("path");
var fs = require("fs");
var initPath = path.join(app.getAppPath(), "init.json");
var data;
var dialog = require('dialog');
try {
data = JSON.parse(fs.readFileSync(initPath, 'utf8'));
}
catch(e) {
}
var menu = new Menu();
var minToTray;
minToTray = data.minTray;
var updateReady = false;
var quitForReal = false; // Dirty
app.commandLine.appendSwitch('client-certificate', 'file://' + __dirname + '/assets/comodorsaaddtrustca.crt');
app.commandLine.appendSwitch('ignore-certificate-errors');
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('ready', function() {
updateWindow = new BrowserWindow({width: 300, height: 300, icon: __dirname + '/icon.png', title: "Discord", 'auto-hide-menu-bar': true, frame: false});
updateWindow.setResizable(false);
updateWindow.setAlwaysOnTop(true);
updateWindow.setSkipTaskbar(true);
updateWindow.loadUrl('file://' + __dirname + '/update.html');
//When no updates
//mainWindow = new BrowserWindow((data && data.bounds) ? data.bounds : {width: 1200, height: 900});
mainWindow = new BrowserWindow({width: 900, height: 750, icon: __dirname + '/icon.png', title: "Discord", 'auto-hide-menu-bar': true});
mainWindow.setBounds(data.bounds);
webContents = mainWindow.webContents;
updateWindow.close();
mainWindow.setTitle("Discord");
mainWindow.setMenuBarVisibility(false);
mainWindow.loadUrl('file://' + __dirname + '/index.html');
//Nullify any closed windows.
mainWindow.on('closed', function() {
//updateWindow.close();
mainWindow = null;
});
updateWindow.on('closed', function(){
updateWindow = null;
});
//Save settings when app is closed.
mainWindow.on('close', function(){
var data = {
bounds: mainWindow.getBounds(),
minTray: minToTray
};
fs.writeFileSync(initPath, JSON.stringify(data));
});
var showButton = new MenuItem({
label: 'Show Discord',
type: 'normal',
click: function() {
mainWindow.setSkipTaskbar(false);
mainWindow.show();
}
});
//Minimize to tray. (Only works on some OSs)
var disMinButton = new MenuItem({
label: 'Disable Minimize to Tray',
type: 'checkbox',
checked: !minToTray,
click: function() {
if(disMinButton.checked == true){
minToTray = false;
console.log("Disabled MinToTray");
} else if (disMinButton.checked == false) {
minToTray = true;
console.log("Enabled MinToTray");
}
disMinButton.checked = !minToTray;
}
});
mainWindow.on('close', function(event) {
if(minToTray && !quitForReal){
event.preventDefault();
data.bounds = mainWindow.getBounds();
mainWindow.hide();
mainWindow.setSkipTaskbar(true);
}
});
//Tray Menu
//menu.append(new MenuItem({ label: 'Show Discord', type: 'normal', click: function() { mainWindow.restore(); mainWindow.setSkipTaskbar(false); } }));
//menu.append(showButton); - Depricated. Doesn't work in Ubuntu Unity
menu.append(new MenuItem({label: 'Show Discord', type: 'normal', click: function(){ mainWindow.setSkipTaskbar(false); mainWindow.show(); } }));
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({ label: 'Refresh Discord', type: 'normal', click: function(){ mainWindow.reload(); } }));
menu.append(new MenuItem({ type: 'separator' }));
menu.append(disMinButton);
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({ label: 'Quit Discord', type: 'normal', click: function() { quitForReal = true; app.quit(); } }));
appIcon = new Tray(__dirname + '/tray.png');
appIcon.setToolTip('Discord');
appIcon.setContextMenu(menu);
appIcon.on('clicked', function(event){
mainWindow.setSkipTaskbar(false);
mainWindow.show();
});
//Link fix
webContents.on('new-window', function(event, urlToOpen) {
event.preventDefault();
shell.openExternal(urlToOpen);
});
//Allow refreshing and Show Window
mainWindow.on('focus', function(){
showButton.enabled = false;
globalShortcut.register('ctrl+r', function () {
mainWindow.reload();
});
});
//Disable refresh when not in focus.
mainWindow.on('blur', function(){
showButton.enabled = true;
globalShortcut.unregister('ctrl+r');
});
});
| JavaScript | 0.000001 | @@ -4496,32 +4496,34 @@
tion()%7B%0A
+//
showButton.enabl
@@ -4730,16 +4730,18 @@
+//
showButt
|
1eeb59e3837155f6eb2e1e07829616a00f292f18 | Update callback to work with azk and localhost | sample/express/routes/index.js | sample/express/routes/index.js | var Evernote = require('evernote').Evernote;
require('dotenv').load();
// Remember to set your APP_URL variable inside .env
var callbackUrl = process.env.APP_URL + '/oauth_callback';
// home page
exports.index = function(req, res) {
if (req.session.oauthAccessToken) {
var token = req.session.oauthAccessToken;
var client = new Evernote.Client({
token: token,
sandbox: process.env.SANDBOX
});
var noteStore = client.getNoteStore();
noteStore.listNotebooks(function(err, notebooks) {
req.session.notebooks = notebooks;
res.render('index');
});
} else {
res.render('index');
}
};
// OAuth
exports.oauth = function(req, res) {
var client = new Evernote.Client({
consumerKey: process.env.API_CONSUMER_KEY,
consumerSecret: process.env.API_CONSUMER_SECRET,
sandbox: process.env.SANDBOX
});
client.getRequestToken(callbackUrl, function(error, oauthToken, oauthTokenSecret, results) {
if (error) {
req.session.error = JSON.stringify(error);
res.redirect('/');
}
else {
// store the tokens in the session
req.session.oauthToken = oauthToken;
req.session.oauthTokenSecret = oauthTokenSecret;
// redirect the user to authorize the token
res.redirect(client.getAuthorizeUrl(oauthToken));
}
});
};
// OAuth callback
exports.oauth_callback = function(req, res) {
var client = new Evernote.Client({
consumerKey: process.env.API_CONSUMER_KEY,
consumerSecret: process.env.API_CONSUMER_SECRET,
sandbox: process.env.SANDBOX
});
client.getAccessToken(
req.session.oauthToken,
req.session.oauthTokenSecret,
req.param('oauth_verifier'),
function(error, oauthAccessToken, oauthAccessTokenSecret, results) {
if (error) {
console.log('error');
console.log(error);
res.redirect('/');
} else {
// store the access token in the session
req.session.oauthAccessToken = oauthAccessToken;
req.session.oauthAccessTtokenSecret = oauthAccessTokenSecret;
req.session.edamShard = results.edam_shard;
req.session.edamUserId = results.edam_userId;
req.session.edamExpires = results.edam_expires;
req.session.edamNoteStoreUrl = results.edam_noteStoreUrl;
req.session.edamWebApiUrlPrefix = results.edam_webApiUrlPrefix;
res.redirect('/');
}
});
};
// Clear session
exports.clear = function(req, res) {
req.session.destroy();
res.redirect('/');
};
| JavaScript | 0 | @@ -122,16 +122,81 @@
env%0Avar
+callbackUrl;%0Aif(process.env.APP_URL.indexOf(%22azk.io%22) != -1) %7B%0A
callback
@@ -222,16 +222,22 @@
PP_URL +
+ ':' +
'/oauth
@@ -247,16 +247,109 @@
llback';
+%0A%7D else %7B%0A callbackUrl = process.env.APP_URL + ':' + process.env.PORT + '/oauth_callback';%0A%7D
%0A%0A// hom
|
e7135e82b824c06a163bfccd1fa755920cecc5f5 | fix the roles | routes/users/users.js | routes/users/users.js | var express = require('express'),
saltHash = require('../../modules/saltHash.js'),
getSpecificData = require('../../modules/getSpecificData.js'),
insertData = require('../../modules/insertData.js'),
renderTemplate = require('../../modules/renderTemplate.js'),
paswordStrength = require('../../modules/paswordStrength.js'),
router = express.Router();
router.get('/login', function(req, res) {
var general = {
title: 'Login',
navPosition: 'transparant'
},
postUrls = {
general: '/users/login'
};
renderTemplate(res, 'users/login', {}, general, postUrls, false);
});
router.post('/login', function(req, res) {
var body = req.body,
email = body.email,
password = body.password,
hour = 7200000,
general = {
title: 'Login',
navPosition: 'transparant'
},
postUrls = {
general: '/users/login'
};
req.getConnection(function(err, connection) {
var sql = 'SELECT salt, hash FROM users WHERE email = ?';
getSpecificData(sql, connection, [email, password]).then(function(rows) {
if (rows.length > 0) {
var credentials = saltHash.check(rows[0].salt, rows[0].hash, password);
if (credentials) {
req.session.cookie.expires = new Date(Date.now() + hour);
req.session.email = email;
req.session.role = rows[0].role;
res.redirect('/admin');
} else {
renderTemplate(res, 'users/login', {}, general, postUrls, 'Username or password is false.');
}
} else {
renderTemplate(res, 'users/login', {}, general, postUrls, 'You have filed in a unknown email.');
}
}).catch(function(err) {
throw err;
});
});
});
// Load the register page
router.get('/register', function(req, res) {
var general = {
title: 'Login',
navPosition: 'transparant'
},
postUrls = {
general: '/users/register'
};
renderTemplate(res, 'users/register', {}, general, postUrls, false);
});
// Insert the submitted registration data
router.post('/register', function(req, res) {
var email = req.body.email,
username = req.body.username,
password = req.body.password,
passwordcheck = req.body.passwordcheck,
general = {
title: 'Login',
navPosition: 'transparant'
},
postUrls = {
general: '/users/register'
};
if (username !== '' && username !== '' && password !== '') {
if (password === passwordcheck) {
paswordStrength(password);
req.getConnection(function(err, connection) {
var sqlQuery = 'INSERT INTO users SET name = ?, email = ?, hash = ?, salt = ?';
var credentials = saltHash.get(password);
insertData(sqlQuery, [username, email, credentials.hash, credentials.salt], connection).then(function() {
res.redirect('/users/login');
}).catch(function(err) {
renderTemplate(res, 'users/register', {}, general, postUrls, 'There is a problem with saving your credentials');
throw err;
});
});
} else {
renderTemplate(res, 'users/register', {}, general, postUrls, 'The passwords are not the same.');
}
} else {
renderTemplate(res, 'users/register', {}, general, postUrls, 'Username or pasword are empty.');
}
});
router.get('/logout', function(req, res) {
req.session.destroy(function() {
res.redirect('/');
});
});
module.exports = router;
| JavaScript | 0.999999 | @@ -1060,16 +1060,22 @@
lt, hash
+, role
FROM us
|
7ee4d0d57a3ac38a81776ffd5210c916e6e9a8f2 | Fix example test | example/test/test.js | example/test/test.js | var helper = require('./support/helper');
var external = require('../lib/external');
var deep = require('../lib/deep');
var npm = require('methods');
describe('this example', function() {
it('should import a helper module', function(){
expect(helper).toEqual('helper.js');
});
it('should import an external module', function(){
expect(external).toEqual('external.js');
});
it('should import an external module which imports a module', function(){
expect(deep.another).toEqual('another.js');
});
it('should import an npm module', function(){
expect(npm['propfind']).not.toBe(null);
});
}); | JavaScript | 0.000096 | @@ -222,32 +222,33 @@
ule', function()
+
%7B %0A expect(he
@@ -325,32 +325,33 @@
ule', function()
+
%7B %0A expect(ex
@@ -455,32 +455,33 @@
ule', function()
+
%7B %0A expect(de
@@ -568,16 +568,17 @@
nction()
+
%7B %0A e
@@ -590,35 +590,30 @@
(npm
-%5B'propfind'%5D).not.toBe(null
+).toContain('propfind'
);%0A
|
5c48da97248b85be7592c7b97fe5e12a291c3d12 | fix flow | shared/chat/conversation/input/index.native.js | shared/chat/conversation/input/index.native.js | // @flow
/* eslint-env browser */
import ImagePicker from 'react-native-image-picker'
import React, {Component} from 'react'
import {Box, Icon, Input, Text} from '../../../common-adapters'
import {globalMargins, globalStyles, globalColors} from '../../../styles'
import {isIOS} from '../../../constants/platform'
import type {AttachmentInput} from '../../../constants/chat'
import type {Props} from '.'
// TODO we don't autocorrect the last word on submit. We had a solution using blur but this also dismisses they keyboard each time
// See if there's a better workaround later
class ConversationInput extends Component<Props> {
_setEditing(props: Props) {
if (!props.editingMessage || props.editingMessage.type !== 'Text') {
return
}
this.props.setText(props.editingMessage.message.stringValue())
this.props.inputFocus()
}
componentWillReceiveProps(nextProps: Props) {
if (this.props.editingMessage !== nextProps.editingMessage) {
this._setEditing(nextProps)
}
if (this.props.text !== nextProps.text) {
this.props.onUpdateTyping(!!nextProps.text)
}
}
componentDidMount() {
this._setEditing(this.props)
}
_onBlur = () => {
if (this.props.editingMessage) {
this.props.onShowEditor(null)
this.props.setText('')
}
}
_openFilePicker = () => {
ImagePicker.showImagePicker({}, response => {
if (response.didCancel) {
return
}
if (response.error) {
console.error(response.error)
throw new Error(response.error)
}
const filename = isIOS ? response.uri.replace('file://', '') : response.path
const conversationIDKey = this.props.selectedConversationIDKey
if (!response.didCancel && conversationIDKey) {
const input: AttachmentInput = {
conversationIDKey,
filename,
title: response.fileName,
type: 'Image',
}
this.props.onAttach([input])
}
})
}
_onSubmit = () => {
const text = this.props.text
if (!text) {
return
}
if (this.props.isLoading) {
console.log('Ignoring chat submit while still loading')
return
}
this.props.setText('')
this.props.inputClear()
if (this.props.editingMessage) {
this.props.onEditMessage(this.props.editingMessage, text)
} else {
this.props.onPostMessage(text)
}
}
render() {
// Auto-growing multiline doesn't work smoothly on Android yet.
const multilineOpts = isIOS ? {rowsMax: 3, rowsMin: 1} : {rowsMax: 2, rowsMin: 2}
return (
<Box style={styleContainer}>
<Input
autoCorrect={true}
autoCapitalize="sentences"
autoFocus={false}
hideUnderline={true}
hintText="Write a message"
inputStyle={styleInputText}
multiline={true}
onBlur={this._onBlur}
onChangeText={this.props.setText}
ref={this.props.inputSetRef}
small={true}
style={styleInput}
value={this.props.text}
{...multilineOpts}
/>
{this.props.typing.length > 0 && <Typing typing={this.props.typing} />}
<Action
text={this.props.text}
onSubmit={this._onSubmit}
editingMessage={this.props.editingMessage}
openFilePicker={this._openFilePicker}
isLoading={this.props.isLoading}
/>
</Box>
)
}
}
const Typing = ({typing}) => (
<Box
style={{
...globalStyles.flexBoxRow,
alignItems: 'center',
borderRadius: 10,
height: 20,
justifyContent: 'center',
paddingLeft: globalMargins.tiny,
paddingRight: globalMargins.tiny,
}}
>
<Icon type="icon-typing-24" style={{width: 20}} />
</Box>
)
const Action = ({text, onSubmit, editingMessage, openFilePicker, isLoading}) =>
text
? <Box style={styleActionText}>
<Text
type="BodyBigLink"
style={{...(isLoading ? {color: globalColors.grey} : {})}}
onClick={onSubmit}
>
{editingMessage ? 'Save' : 'Send'}
</Text>
</Box>
: <Icon onClick={openFilePicker} type="iconfont-camera" style={styleActionButton} />
const styleActionText = {
...globalStyles.flexBoxColumn,
alignItems: 'center',
alignSelf: isIOS ? 'flex-end' : 'center',
justifyContent: 'center',
paddingBottom: globalMargins.xtiny,
paddingLeft: globalMargins.tiny,
paddingRight: globalMargins.small,
paddingTop: globalMargins.xtiny,
}
const styleActionButton = {
alignSelf: isIOS ? 'flex-end' : 'center',
paddingBottom: 2,
paddingLeft: globalMargins.tiny,
paddingRight: globalMargins.tiny,
}
const styleInputText = {}
const styleContainer = {
...globalStyles.flexBoxRow,
alignItems: 'center',
borderTopColor: globalColors.black_05,
borderTopWidth: 1,
flexShrink: 0,
minHeight: 48,
...(isIOS
? {
paddingBottom: globalMargins.tiny,
paddingTop: globalMargins.tiny,
}
: {}),
}
const styleInput = {
flex: 1,
marginLeft: globalMargins.tiny,
}
export default ConversationInput
| JavaScript | 0.000001 | @@ -34,16 +34,21 @@
%0Aimport
+%7Bshow
ImagePic
@@ -50,16 +50,17 @@
gePicker
+%7D
from 'r
@@ -1346,20 +1346,8 @@
-ImagePicker.
show
|
9a09535ccbcc26ec1f2fdb0446823545ff1e00de | Add cname to site config (#374) | website/siteConfig.js | website/siteConfig.js | /**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// See https://docusaurus.io/docs/site-config for all the possible
// site configuration options.
const siteConfig = {
title: 'Redex', // Title for your website.
tagline: 'An Android Bytecode Optimizer',
url: 'https://fbredex.com',
baseUrl: '/',
// Used for publishing and more
organizationName: 'facebook',
projectName: 'redex',
// For no header links in the top nav bar -> headerLinks: [],
headerLinks: [
{doc: 'installation', label: 'Docs'},
{doc: 'faq', label: 'FAQ'},
// {blog: true, label: 'Blog'}, // put back when we create a blog folder and add our first blog
{
href: 'https://code.facebook.com/posts/1480969635539475/optimizing-android-bytecode-with-redex',
label: 'Birth',
}
],
/* path to images for header/footer */
headerIcon: 'img/redex.png',
footerIcon: 'img/redex.png',
favicon: 'img/favicon.png',
/* Colors for website */
colors: {
primaryColor: '#75c7a4',
secondaryColor: '#f9f9f9',
},
/* Custom fonts for website */
/*
fonts: {
myFont: [
"Times New Roman",
"Serif"
],
myOtherFont: [
"-apple-system",
"system-ui"
]
},
*/
// This copyright info is used in /core/Footer.js and blog RSS/Atom feeds.
copyright: `Copyright © ${new Date().getFullYear()} Facebook Inc.`,
highlight: {
// Highlight.js theme to use for syntax highlighting in code blocks.
theme: 'default',
},
// Add custom scripts here that would be placed in <script> tags.
scripts: ['https://buttons.github.io/buttons.js'],
// On page navigation for the current documentation page.
onPageNav: 'separate',
// No .html extensions for paths.
cleanUrl: true,
// Open Graph and Twitter card images.
ogImage: 'img/og_image.png',
// Show documentation's last contributor's name.
enableUpdateBy: true,
// Show documentation's last update time.
enableUpdateTime: true,
// You may provide arbitrary config keys to be used as needed by your
// template. For example, if you need your repo's URL...
repoUrl: 'https://github.com/facebook/redex',
};
module.exports = siteConfig;
| JavaScript | 0.000002 | @@ -431,16 +431,40 @@
rl: '/',
+%0A cname: 'fbredex.com',
%0A%0A // U
|
fccde38b3be75eedbc2c5e7744baf4b1cf2db51d | Fix spelling | react-github-battle/app/components/Results.js | react-github-battle/app/components/Results.js | import React, { PropTypes } from 'react'
import { space } from '../styles'
import { Link } from 'react-router'
import UserDetails from './UserDetails'
import UserDetailsWrapper from './UserDetailsWrapper'
import MainContainer from './MainContainer'
import Loading from './Loading'
function StartOver (){
return (
<div className="col-sm-12" styles={space}>
<Link to="/playerOne">
<button type="button" className="btn btn-lg btn-danger">Start Over</button>
</Link>
</div>
)
}
function Results ({isLoading, scores, playersInfo}) {
if (isLoading === true) {
return (<Loading speed={100} text="One Moment" />)
}
if (scores[0] === scores[1]){
return (
<MainContainer>
<h1>It's a tie!</h1>
<StartOver />
</MainContainer>
)
}
const winningIndex = scores[0] > scores[1] ? 0 : 1;
const losingIndex = winningIndex === 0 ? 1 : 0;
return (
<MainContainer>
<h1>Results</h1>
<div className="col-sm-8 col-sm-offset-2">
<UserDetailsWrapper header="Winner">
<UserDetails score={scores[winningIndex]} info={playersInfo[winningIndex]}/>
</UserDetailsWrapper>
<UserDetailsWrapper header="Looser">
<UserDetails score={scores[loosingIndex]} info={playersInfo[loosingIndex]}/>
</UserDetailsWrapper>
</div>
<StartOver />
</MainContainer>
)
}
Results.propTypes = {
isLoading: PropTypes.bool.isRequired,
playersInfo: PropTypes.array.isRequired,
scores: PropTypes.array.isRequired
}
export default Results
| JavaScript | 0.999999 | @@ -1249,17 +1249,16 @@
cores%5Blo
-o
singInde
@@ -1281,17 +1281,16 @@
sInfo%5Blo
-o
singInde
|
b3e9d71375e615a0c3adc6833c36d955fe38d471 | Remove custom flatmap implementation | core/data/generateDictionaryEntries.js | core/data/generateDictionaryEntries.js | // @flow
import pluralize from 'pluralize';
import removeAccents from 'remove-accents';
import type { Card } from '../types';
/*
* Generate all entries to build a dictionary from
* a card list and aliases.
*/
function generateDictionaryEntries(
// The complete list of cards
cardList: Card[],
// All aliases defined for each card
cardAliases: { [CardID]: Array<string> }
): Array<[string, CardID]> {
return cardList.reduce((array: Array<[string, CardID]>, card: Card) => {
const { id } = card;
const aliases = cardAliases[id] || [];
const entries = generateVariants(aliases).map(variant => [variant, id]);
return array.concat(entries);
}, []);
}
/**
* Generate all orthographic variants for the provided card names
*/
function generateVariants(names: string[]): string[] {
const variants = [];
names.forEach(name => {
const cleanName = normalizeName(name);
variants.push(cleanName);
variants.push(pluralize(cleanName));
});
return flatMap(variants, generateSpecialCharactersVariants);
}
/*
* Generate all variants where special characters
* are skipped, or replaced by a space.
*/
function generateSpecialCharactersVariants(name: string): string[] {
const hasSpecialCharacters = /[^\s\w]/.test(name);
if (!hasSpecialCharacters) {
return [name];
}
const variantsOf = (str: string): string[] => {
if (!str) {
return [str];
}
const subvariants = variantsOf(str.slice(1));
const unchanged = subvariants.map(subvariant => str[0] + subvariant);
let variants = [...unchanged];
if (/^[^\s\w]/.test(str)) {
const withSpace = subvariants.map(subvariant => ` ${subvariant}`);
const skipped = subvariants;
variants = variants.concat(withSpace, skipped);
}
// Followed by a space (like in "Speartip: Asleep")
if (/^[^\s\w ]/.test(str)) {
const skipSpaceOnly = variantsOf(str.slice(2)).map(
subvariant => str[0] + subvariant
);
variants = variants.concat(skipSpaceOnly);
}
return variants;
};
return variantsOf(name);
}
/*
* Normalize a card name by removing anything that is not needed
*/
function normalizeName(name: string): string {
return removeAccents(name).toLowerCase();
}
function flatMap(arr: *, fn: any) {
return arr.reduce((acc, x) => acc.concat(fn(x)), []);
}
export default generateDictionaryEntries;
| JavaScript | 0 | @@ -80,16 +80,47 @@
ccents';
+%0Aimport flatmap from 'flatmap';
%0A%0Aimport
@@ -1067,17 +1067,17 @@
urn flat
-M
+m
ap(varia
@@ -2442,105 +2442,8 @@
%0A%7D%0A%0A
-function flatMap(arr: *, fn: any) %7B%0A return arr.reduce((acc, x) =%3E acc.concat(fn(x)), %5B%5D);%0A%7D%0A%0A
expo
|
63af96b45e02e9aa64f8c2055075e9cfb087f6ac | Fix - Added missing semicolon | modules/tooltip/backbone.tooltip.js | modules/tooltip/backbone.tooltip.js | /* global Backbone */
/* global $ */
/* global _ */
(function() {
"use strict";
// private:
var tooltipTemplate =
'<div class="bb-tooltip-arrow <%= "bb-arrow-" + placement %>"></div>' +
'<div class="bb-tooltip-container"></div>';
var getOffset = function(options) {
var width = options.width;
var height = options.height;
var leftOffset = options.triggerEl.offset().left;
var topOffset = options.triggerEl.offset().top;
var outerWidth = options.triggerEl.outerWidth();
var outerHeight = options.triggerEl.outerHeight();
var top = 0;
var left = 0;
switch (options.placement) {
case 'top':
top = topOffset - height;
left = leftOffset + (outerWidth / 2) - (width / 2);
break;
case 'bottom':
top = topOffset + outerHeight;
left = leftOffset + (outerWidth / 2) - (width / 2);
break;
case 'left':
top = topOffset + (outerHeight / 2) - (height / 2);
left = leftOffset - width;
break;
default :
top = topOffset + (outerHeight / 2) - (height / 2);
left = leftOffset + outerWidth;
}
return { top: parseInt(top), left: parseInt(left) };
};
// public:
Backbone.Tooltip = Backbone.View.extend({
defaults: {
placement : 'top',
triggerEl : null,
events : {}
},
initialize: function(args) {
var tip;
var thisref = this;
this.isShown = false
this.options = _.extend({}, this.defaults, args);
if(this.options.triggerEl === null) {
throw "No Trigger Element Specified";
}
this.tooltipId = _.uniqueId("bb-tooltip-");
// tabindex='0' will make element focusable
tip = $('<div>').attr('id', this.tooltipId).attr('tabindex', '0').addClass('bb-tooltip');
$('body').prepend(tip);
this.$el = tip;
this.options.triggerEl.hover(function (ev) { thisref.show(); },
function (ev) { thisref.hide(); });
},
render: function() {
this.$el.html(_.template(tooltipTemplate)(this.options))
.find('.bb-tooltip-container')
.html(_.template(this.options.template)(this.options));
this.options.height = this.$el.outerHeight();
this.options.width = this.$el.outerWidth();
this.$el.offset(getOffset(this.options));
return this;
},
show: function() {
this.isShown = true;
this.render();
this.delegateEvents(this.events);
this.$el.addClass('visible').trigger('tooltip-show')
.find('.bb-tooltip-template').addClass('visible');
return this;
},
hide: function() {
this.isShown = false;
this.$el.trigger('tooltip-hide').removeClass('visible')
.find('.bb-tooltip-template').removeClass('visible');
this.undelegateEvents();
return this;
}
});
})();
| JavaScript | 0 | @@ -1432,16 +1432,17 @@
= false
+;
%0A%0A
|
5877ce79417f6792fbcfe0a04433b610c8c6f0e6 | Rework buildEntries helper | build/helpers.js | build/helpers.js | const paths = require('./paths');
const glob = require('glob');
/**
* Determine base path of provided file path
*
* @param {string} path
* @returns {string}
*/
function getBasePath(path) {
return path.split('/')[0] === '.' ? paths.project : paths.scripts;
}
/**
* Find and return file path
*
* @param {string|Array} filePath
* @returns {Array}
*/
function getPaths(filePaths) {
if (Array.isArray(filePaths)) {
let paths = [];
filePaths.forEach(filePath => {
paths = paths.concat(glob.sync(`${getBasePath(filePath)}/${filePath}`));
});
return paths;
}
return glob.sync(`${getBasePath(filePaths)}/${filePaths}`);
}
/**
* Process entries from wee.json
*
* @param {Object} entries
* @returns {Object}
*/
function buildEntries(entries) {
let result = {};
Object.keys(entries).forEach(entry => {
let paths = getPaths(entries[entry]);
// If single entry point, extract from array
if (paths.length === 1) {
paths = paths[0];
}
result[entry] = paths;
});
return result;
}
/**
* Calculate breakpoints with offset included
*
* @param {Object} breakpoints
* @param {number} offset
* @returns {Object}
*/
function calcBreakpoints(breakpoints, offset) {
let breaks = { ...breakpoints };
for (let breakpoint in breaks) {
breaks[breakpoint] = breakpoints[breakpoint] - offset;
}
return breaks;
}
module.exports = {
calcBreakpoints,
buildEntries
}
| JavaScript | 0 | @@ -758,24 +758,69 @@
(entries) %7B%0A
+%09const firstEntry = Object.keys(entries)%5B0%5D;%0A
%09let result
@@ -869,25 +869,29 @@
=%3E %7B%0A%09%09
-let paths
+result%5Bentry%5D
= getPa
@@ -915,138 +915,214 @@
%5D);%0A
-%0A%09%09// If single entry point, extract from array%0A%09%09if (paths.length === 1) %7B%0A%09%09%09paths = paths%5B0%5D;%0A%09%09%7D%0A%0A%09%09result%5Bentry%5D = paths;%0A%09%7D)
+%09%7D);%0A%0A%09result%5BfirstEntry%5D = %5B%0A%09%09...result%5BfirstEntry%5D,%0A%09%09%60$%7Bpaths.temp%7D/responsive.scss%60,%0A%09%09%60$%7Bpaths.styles%7D/global.scss%60,%0A%09%09%60$%7Bpaths.styles%7D/print.scss%60,%0A%09%09...glob.sync(%60$%7Bpaths.components%7D/**/*.scss%60),%0A%09%5D
;%0A%0A%09
|
f9b512100a4acfbf8e0001ab065441f62c4499d1 | Normalize note | packages/size-limit/create-reporter.js | packages/size-limit/create-reporter.js | let {
bgGreen,
yellow,
bgRed,
black,
green,
bold,
gray,
red
} = require('picocolors')
let { join } = require('path')
let bytes = require('bytes-iec')
function createJsonReporter(process) {
function print(data) {
process.stdout.write(JSON.stringify(data, null, 2) + '\n')
}
return {
error(err) {
print({ error: err.stack })
},
results(plugins, config) {
print(
config.checks.map(i => {
let result = { name: i.name }
if (typeof i.passed !== 'undefined') result.passed = i.passed
if (typeof i.size !== 'undefined') result.size = i.size
if (typeof i.runTime !== 'undefined') result.running = i.runTime
if (typeof i.loadTime !== 'undefined') result.loading = i.loadTime
return result
})
)
}
}
}
function getFixText(prefix, config) {
if (config.configPath) {
if (config.configPath.endsWith('package.json')) {
prefix += ` in ${bold('"size-limit"')} section of `
} else {
prefix += ' at '
}
prefix += bold(config.configPath)
}
return prefix
}
function createHumanReporter(process, isSilentMode = false) {
function print(...lines) {
process.stdout.write(' ' + lines.join('\n ') + '\n')
}
function formatBytes(size) {
return bytes.format(size, { unitSeparator: ' ' })
}
function formatTime(seconds) {
if (seconds >= 1) {
return Math.ceil(seconds * 10) / 10 + ' s'
} else {
return Math.ceil(seconds * 1000) + ' ms'
}
}
return {
error(err) {
if (err.name === 'SizeLimitError') {
let msg = err.message
.split('. ')
.map(i => i.replace(/\*([^*]+)\*/g, yellow('$1')))
.join('.\n ')
process.stderr.write(`${bgRed(black(' ERROR '))} ${red(msg)}\n`)
if (err.example) {
process.stderr.write(
'\n' +
err.example
.replace(/("[^"]+"):/g, green('$1') + ':')
.replace(/: ("[^"]+")/g, ': ' + yellow('$1'))
)
}
} else {
process.stderr.write(`${bgRed(black(' ERROR '))} ${red(err.stack)}\n`)
}
},
results(plugins, config) {
print('')
for (let check of config.checks) {
if (
(check.passed && config.hidePassed && !isSilentMode) ||
(isSilentMode && check.passed !== false)
) {
continue
}
let unlimited = typeof check.passed === 'undefined'
let rows = []
if (config.checks.length > 1) {
print(bold(check.name))
}
if (check.missed) {
print(red(`Size Limit can’t find files at ${check.path}`))
continue
}
let sizeNote
let bundled = plugins.has('webpack') || plugins.has('esbuild')
if (check.config) {
sizeNote = 'with given webpack configuration'
} else if (bundled && check.brotli === true) {
sizeNote = 'with all dependencies, minified and brotli'
} else if (bundled && check.gzip === false) {
sizeNote = 'with all dependencies and minified'
} else if (bundled) {
sizeNote = 'with all dependencies, minified and gzipped'
} else if (plugins.has('file') && check.brotli === true) {
sizeNote = 'brotlied'
} else if (plugins.has('file') && check.gzip !== false) {
sizeNote = 'gzipped'
}
let sizeString = formatBytes(check.size)
if (typeof check.timeLimit !== 'undefined') {
if (check.passed === false) {
print(red('Total time limit has exceeded'))
}
rows.push(['Time limit', formatTime(check.timeLimit)])
}
if (typeof check.sizeLimit !== 'undefined') {
let sizeLimitString = formatBytes(check.sizeLimit)
if (check.passed === false) {
if (sizeLimitString === sizeString) {
sizeLimitString = check.sizeLimit + ' B'
sizeString = check.size + ' B'
}
let diff = formatBytes(check.size - check.sizeLimit)
print(red(`Package size limit has exceeded by ${diff}`))
} else if (check.highlightLess && check.size < check.sizeLimit) {
let diff = formatBytes(check.sizeLimit - check.size)
print(bgGreen(black(`Package size is ${diff} less than limit`)))
}
rows.push(['Size limit', sizeLimitString])
}
if (typeof check.size !== 'undefined') {
rows.push(['Size', sizeString, sizeNote])
}
if (typeof check.loadTime !== 'undefined') {
rows.push(['Loading time', formatTime(check.loadTime), 'on slow 3G'])
}
if (typeof check.runTime !== 'undefined') {
rows.push(
['Running time', formatTime(check.runTime), 'on Snapdragon 410'],
['Total time', formatTime(check.time)]
)
}
let max0 = Math.max(...rows.map(row => row[0].length))
let max1 = Math.max(...rows.map(row => row[1].length))
for (let [name, value, note] of rows) {
let str = (name + ':').padEnd(max0 + 1) + ' '
if (note) value = value.padEnd(max1)
value = bold(value)
if (unlimited || name.includes('Limit')) {
str += value
} else if (check.passed) {
str += green(value)
} else {
str += red(value)
}
if (note) {
str += ' ' + gray(note)
}
print(str)
}
print('')
}
if (config.failed) {
let fix = getFixText('Try to reduce size or increase limit', config)
print(yellow(fix))
}
if (plugins.has('webpack') && config.saveBundle) {
let statsFilepath = join(config.saveBundle, 'stats.json')
print(`Webpack Stats file was saved to ${statsFilepath}`)
print('You can review it using https://webpack.github.io/analyse')
}
}
}
}
module.exports = (process, isJSON, isSilentMode) => {
if (isJSON) {
return createJsonReporter(process)
} else {
return createHumanReporter(process, isSilentMode)
}
}
| JavaScript | 0.000012 | @@ -3024,16 +3024,18 @@
d brotli
+ed
'%0A
|
9eb80ab969270e58b99a443184254d45916424f0 | Fix bug with sentry `dryRun` flag in prod build | build/plugins.js | build/plugins.js | import { exec } from 'child_process'
import { EnvironmentPlugin } from 'webpack'
import ForkTsPlugin from 'fork-ts-checker-webpack-plugin'
import CopyPlugin from 'copy-webpack-plugin'
import HtmlPlugin from 'html-webpack-plugin'
import HtmlIncAssetsPlugin from 'html-webpack-include-assets-plugin'
import HardSourcePlugin from 'hard-source-webpack-plugin'
import StylelintPlugin from 'stylelint-webpack-plugin'
import BuildNotifPlugin from 'webpack-build-notifier'
import CssExtractPlugin from 'mini-css-extract-plugin'
import SentryPlugin from '@sentry/webpack-plugin'
import ZipPlugin from 'zip-webpack-plugin'
import PostCompilePlugin from 'post-compile-webpack-plugin'
// Disabling this for now as it adds 2-4 seconds to inc. build time - look into finding out why
// import WebExtReloadPlugin from 'webpack-chrome-extension-reloader'
import initEnv from './env'
import * as staticFiles from './static-files'
import { output } from './config'
/**
* @param {boolean} tslint Denotes whether or not to enable linting on this thread as well as type checking.
*/
const initTsPlugin = tslint =>
new ForkTsPlugin({
checkSyntacticErrors: true,
async: false,
tslint,
// Hacky workaround for now as this plugin tries to lint imported TS node_modules for some reason
// CI linting will still pick these up
ignoreLints: ['class-name', 'no-shadowed-variable', 'comment-format'],
})
export default function ({
webExtReloadPort = 9090,
mode = 'development',
template,
notifsEnabled = false,
isCI = false,
shouldPackage = false,
packagePath = '../dist',
extPackageName = 'extension.zip',
sourcePackageName = 'source-code.zip',
}) {
const plugins = [
new EnvironmentPlugin(initEnv({ mode })),
new CopyPlugin(staticFiles.copyPatterns),
new HtmlPlugin({
title: 'Popup',
chunks: ['popup'],
filename: 'popup.html',
template,
}),
new HtmlPlugin({
title: 'Settings',
chunks: ['options'],
filename: 'options.html',
template,
}),
new HtmlIncAssetsPlugin({
append: false,
assets: staticFiles.htmlAssets,
}),
new CssExtractPlugin({
filename: '[name].css',
}),
]
if (mode === 'development') {
plugins.push(
new HardSourcePlugin(),
// new WebExtReloadPlugin({
// port: webExtReloadPort,
// }),
)
} else if (mode === 'production') {
plugins.push(
new SentryPlugin({
release: process.env.npm_package_version,
include: output.path,
dryRun: shouldPackage,
}),
)
}
// CI build doesn't need to use linting plugins
if (isCI) {
return [...plugins, initTsPlugin(false)]
}
if (notifsEnabled) {
plugins.push(
new BuildNotifPlugin({
title: 'Memex Build',
}),
)
}
if (shouldPackage) {
plugins.push(
new ZipPlugin({
path: packagePath,
filename: extPackageName,
exclude: [/\.map/],
}),
// TODO: do this in node
new PostCompilePlugin(() => exec('sh package-source-code.sh')),
)
}
return [
...plugins,
initTsPlugin(true),
new StylelintPlugin({
files: 'src/**/*.css',
failOnError: mode === 'production',
}),
]
}
| JavaScript | 0 | @@ -1450,17 +1450,16 @@
function
-
(%7B%0A w
@@ -2766,16 +2766,17 @@
dryRun:
+!
shouldPa
|
8e6b5f0a3df8fe67996914a7cca32fb14a044108 | upgrade build vendors scripts | build/vendors.js | build/vendors.js | #!/usr/bin/env node
'use strict'
const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const sh = require('shelljs')
const basename = path.basename
const dirname = path.dirname
const resolve = path.resolve
const normalize = path.normalize
const join = path.join
const relative = path.relative
const extension = path.extname
const src = 'src/'
const dest = 'dist/'
const base = path.resolve(__dirname, '..')
const walkSync = (dir, filelist = []) => {
fs.readdirSync(dir).forEach(file => {
filelist = fs.statSync(path.join(dir, file)).isDirectory()
? walkSync(path.join(dir, file), filelist)
: filelist.concat(path.join(dir, file))
})
return filelist
}
const vendorName = (path) => {
const nodeModules = Boolean(path.split('/')[0] === 'node_modules')
const subDir = Boolean(path.indexOf('@') >= 0)
let vendor
if (nodeModules) {
if (subDir) {
vendor = `${path.split('/')[1]}/${path.split('/')[2]}`
} else {
vendor = `${path.split('/')[1]}`
}
}
return vendor
}
function removeDuplicates( arr, prop ) {
let obj = {};
return Object.keys(arr.reduce((prev, next) => {
if(!obj[next[prop]]) obj[next[prop]] = next;
return obj;
}, obj)).map((i) => obj[i]);
}
const findVendors = () => {
const vendors = []
// const assets = []
// const vendors = { css: [], js: [], other: [] }
const filenames = walkSync(src)
filenames.forEach((filename) => {
if (extension(filename) === '.html') {
const files = fs.readFileSync(filename, 'ascii').toString().split('\n')
// go through the list of code lines
files.forEach((file) => {
// if the current line matches `/(?:href|src)="(node_modules.*.[css|js])"/`, it will be stored in the variable lines
const nodeModules = file.match(/(?:href|src)="(node_modules.*.[css|js])"/)
if (nodeModules) {
let vendor = []
const src = nodeModules[1]
const name = vendorName(src)
let type
let absolute
vendor['name'] = name
vendor['filetype'] = extension(src).replace('.', '')
vendor['src'] = src
vendor['absolute'] = resolve(src)
if (vendors.findIndex(vendor => vendor.absolute === resolve(src)) === -1) {
vendors.push(vendor)
// Check it CSS file has assets
if (extension(src) === '.css') {
const assets = fs.readFileSync(resolve(src), 'ascii').toString().match(/(?:url)\((.*?)\)/ig)
assets.forEach((asset) => {
const assetPath = asset.match(/(?:url)\((.*?)\)/)[1]
let subVendor = []
if (assetPath !== undefined) {
// console.log(assetPath)
const path = assetPath.replace(/\?.*/, '').replace(/\'|\"/, '')
subVendor['name'] = name
subVendor['filetype'] = 'other'
subVendor['src'] = normalize(`css/${path}`)
subVendor['absolute'] = resolve(dirname(src), path)
vendors.push(subVendor)
}
})
}
}
}
})
}
})
return vendors
}
const copyFiles = (files, dest) => {
files.forEach((file) => {
let dir
file.filetype !== 'other' ? dir = resolve(dest, file.name, file.filetype) : dir = resolve(dest, file.name, dirname(file.src))
mkdirp.sync(dir)
fs.createReadStream(file.absolute).pipe(fs.createWriteStream(resolve(dir, basename(file.src))))
if (fs.existsSync(`${file.absolute}.map`)) {
fs.createReadStream(`${file.absolute}.map`).pipe(fs.createWriteStream(resolve(dir, `${basename(file.src)}.map`)))
}
})
}
const replaceRecursively = (filename, vendor) => {
const original = vendor.src
const replacement = `vendors/${vendor.name}/${vendor.filetype}/${basename(vendor.src)}`
sh.sed('-i', original, replacement, filename)
}
const main = () => {
const vendors = findVendors()
copyFiles(vendors.map((file) => { return file }), './dist/vendors/')
const filenames = walkSync(dest)
filenames.forEach((filename) => {
if (extension(filename) === '.html') {
vendors.map((vendor) => {
if (vendor.filetype !== 'other') {
replaceRecursively(resolve(filename), vendor)
}
})
}
})
}
main()
| JavaScript | 0 | @@ -2572,16 +2572,46 @@
)%5C)/ig)%0A
+ if (assets) %7B%0A
@@ -2640,24 +2640,26 @@
asset) =%3E %7B%0A
+
@@ -2727,24 +2727,26 @@
+
let subVendo
@@ -2760,32 +2760,34 @@
+
+
if (assetPath !=
@@ -2819,16 +2819,18 @@
+
// conso
@@ -2847,16 +2847,18 @@
etPath)%0A
+
@@ -2941,32 +2941,34 @@
+
subVendor%5B'name'
@@ -2968,32 +2968,34 @@
%5B'name'%5D = name%0A
+
@@ -3038,32 +3038,34 @@
+
subVendor%5B'src'%5D
@@ -3092,16 +3092,18 @@
path%7D%60)%0A
+
@@ -3175,32 +3175,34 @@
+
+
vendors.push(sub
@@ -3217,32 +3217,34 @@
+
%7D%0A
@@ -3239,27 +3239,45 @@
+
+
%7D)%0A
+ %7D%0A
@@ -3320,17 +3320,16 @@
%7D%0A %7D)%0A
-%0A
return
@@ -4095,17 +4095,16 @@
() =%3E %7B%0A
-%0A
const
|
3ea8c1d0d9efd62dde3050c29bc06334c3629a2b | Update landline.stateline.js | public/javascripts/landline.stateline.js | public/javascripts/landline.stateline.js | (function() {
// Stateline puts default collections of Landline maps together for you
// Requires jQuery and Raphael
var MapCanvas = Landline.Stateline = function(container, locality) {
this.paper = {};
this.events = {};
this.attrs = {};
this.lookup = {};
this.locality = locality;
this.container = $(container);
this.container.css("position", "relative");
this.container.height(this.container.width() * 0.70);
this.setupHtml();
var that = this;
$(window).resize(function() {
that.container.height(that.container.width() * 0.70);
that.setupHtml();
});
};
MapCanvas.CONTAINERS = {
"continental" : {el : "landline_continental"},
"alaska" : {el : "landline_alaska"},
"hawaii" : {el : "landline_hawaii"}
};
MapCanvas.prototype.on = function(evt, cb) {
this.events[evt] = cb;
};
MapCanvas.prototype.style = function(fips, key, val) {
this.attrs[fips] = (this.attrs[fips] || []);
this.attrs[fips].push([key, val]);
};
MapCanvas.prototype.reLayout = function() {
for (container in MapCanvas.CONTAINERS) {
for (fips in this.attrs) {
var path = this.lookup[fips];
_(this.attrs[fips]).each(function(attr) {
path.attr(attr[0], attr[1]);
});
}
}
};
MapCanvas.prototype.setupHtml = function() {
var that = this;
var containers = MapCanvas.CONTAINERS;
containers["continental"] = _.extend(containers["continental"], {
width : this.container.width(),
height : this.container.height() * 0.85,
top : "0%",
left : 0.0
});
containers["alaska"] = _.extend(containers["alaska"], {
width : this.container.width() * 0.25,
height : this.container.height() * 0.27,
top : "63%",
left : 0.0
});
containers["hawaii"] = _.extend(containers["hawaii"], {
width : this.container.width() * 0.15,
height : this.container.height() * 0.21,
top : "70%",
left : 0.25
});
var setPositions = function(container) {
$("#" + containers[container].el)
.width(containers[container].width)
.height(containers[container].height)
.css("top", containers[container].top)
// calculate how many pixels left the % is,
// so Hawaii doesn't move around when the window is resized
.css("margin-left", that.container.width() * containers[container].left)
.css("position", "absolute");
};
for (container in containers) {
if (this.paper[container]) {
setPositions(container);
this.paper[container].setSize(containers[container].width, containers[container].height);
} else {
this.container.append("<div id='" + containers[container].el + "'></div>");
setPositions(container);
this.paper[container] = Raphael(containers[container].el)
this.paper[container].setViewBox(0, 0, containers[container].width, containers[container].height);
}
}
};
MapCanvas.prototype.createMap = function() {
var data;
var that = this;
var containers = MapCanvas.CONTAINERS;
if (this.locality === "states") data = window.StatelineStates;
if (this.locality === "counties") data = window.StatelineCounties;
for (container in containers) {
var localityMap = new Landline(data[container]).all();
localityMap.asSVG(containers[container].width, containers[container].height, function(svg, it) {
var path = that.paper[container].path(svg);
var fips = it.fips = it.get("c") ? it.get("s") + it.get("c") : it.get("s");
that.lookup[fips] = path;
path.attr("fill", "#cecece")
.attr('stroke-width', 0.5)
.attr('stroke', '#ffffff')
.attr('stroke-linejoin', 'bevel');
if (that.attrs[fips]) {
_(that.attrs[fips]).each(function(attr) {
path.attr(attr[0], attr[1])
});
}
_(that.events).each(function(func, evt) {
path[evt](function(e) {
func(e, path, it);
});
});
});
}
};
}).call(this);
| JavaScript | 0.000002 | @@ -1202,16 +1202,38 @@
%5Bfips%5D;%0A
+ if (path) %7B%0A
@@ -1276,32 +1276,34 @@
tr) %7B%0A
+
path.attr(attr%5B0
@@ -1319,28 +1319,40 @@
%5D);%0A
+
%7D);%0A
+ %7D%0A
%7D%0A
|
59750b605e8b8624ab757ae1c2dda8489415dc0a | Remove debugger. | static/app/app/controller.js | static/app/app/controller.js | //Dependencies
var $ = require('jquery');
var Backbone = require('backbone');
var Marionette = require('backbone.marionette');
var Radio = require('backbone.radio');
var _ = require('underscore');
var moment = require('moment');
//App
var channel = Radio.channel('global');
var Move = require('app/entities').Move;
var LoadingView = require('app/common/views').LoadingView;
var LayoutView = require('app/list/views').LayoutView;
var MoveFormView = require('app/edit/views').MoveFormView;
var NameView = require('app/edit/views').NameView;
var JoinView = require('app/edit/views').JoinView;
var Controller = Marionette.Object.extend({
initialize: function(){
channel.on('call:method', function(methodName, arg){
if (this[methodName]) {
this[methodName](arg);
}
}, this);
},
list: function(){
var move = channel.request('entities:move');
var spots = channel.request('entities:spots');
var mainRegion = channel.request('get:region', 'main');
mainRegion.show(new LoadingView());
var moves = channel.request('entities:moves');
$.when(moves.fetch(), spots.fetch()).done(function(){
var layoutView = new LayoutView({
model: move,
collection: moves.groupBySpot()
});
mainRegion.show(layoutView);
});
},
edit: function(){
var move = channel.request('entities:move');
var spots = channel.request('entities:spots');
var callback = function(){
var ViewClass = move.get('user') ? MoveFormView : NameView;
var view = new ViewClass({model: move});
var mainRegion = channel.request('get:region', 'main');
mainRegion.show(view);
};
if (spots.length) {
callback();
} else {
var mainRegion = channel.request('get:region', 'main');
mainRegion.show(new LoadingView());
spots.fetch().done(callback);
}
},
join: function(moveId) {
var moves = channel.request('entities:moves');
$.when(moves.fetch()).done(function(){
var currentMove = channel.request("entities:move");
var moveToJoin = channel.request('entities:moves').find({id: parseInt(moveId)});
debugger
currentMove.set('time', moveToJoin.get('time').format());
currentMove.set('spot', moveToJoin.get('spot'));
if (currentMove.get('user')) {
currentMove.save({}, {
dataType: 'text',
success: function(model, resp) {
channel.trigger('list');
console.log(model);
},
error: function(model, resp) {
console.log(resp);
}
})
} else {
var mainRegion = channel.request('get:region', 'main');
mainRegion.show(new JoinView);
}
});
}
});
module.exports = Controller;
| JavaScript | 0.000001 | @@ -162,71 +162,8 @@
o');
-%0Avar _ = require('underscore');%0Avar moment = require('moment');
%0A%0A//
@@ -2259,24 +2259,8 @@
%7D);%0A
- debugger
%0A
|
c999425adeb3c656d4429f79133e4db14321e780 | Change language for lua nginx module | static/javascripts/script.js | static/javascripts/script.js | (function ($, undefined) {
var featured = ['lua-nginx-module', 'stapxx', 'SortaSQL'],
exclude = ['circus', 'fpm', 'phantomjs', 'zendesk', 'raven-php', 'go-raft', 'jas', 'twemcache', 'CloudFlare-UI', 'cloudflarejs','cloudflare.github.io'],
customRepos = [{
name : 'stapxx',
html_url : 'http://github.com/agentzh/stapxx',
language : 'Perl',
description : 'Simple macro language extentions to systemtap'
},{
name : 'nginx-systemtap-toolkit',
html_url : 'http://github.com/agentzh/nginx-systemtap-toolkit',
language : 'Perl',
description : 'Real-time analyzing and diagnosing tools for Nginx based on SystemTap'
},{
name : 'lua-nginx-module',
html_url : 'https://github.com/chaoslawful/lua-nginx-module',
language : 'Perl',
description : 'Embed the Power of Lua into NginX'
},{
name : 'ngx_cache_purge',
html_url : 'https://github.com/FRiCKLE/ngx_cache_purge',
language : 'C',
description : 'nginx module which adds ability to purge content from FastCGI, proxy, SCGI and uWSGI caches.'
}],
num = 0;
function addRecentlyUpdatedRepo(repo) {
var $item = $('<li>');
var $name = $('<a>').attr('href', repo.html_url).text(repo.name);
$item.append($('<span>').addClass('name').append($name));
$item.append('<span class="bullet">⋅</span>');
var $time = $('<a>').attr('href', repo.html_url + '/commits').text( repo.pushed_at.toDateString() );
$item.append($('<span>').addClass('time').append($time));
$item.append('<span class="bullet">⋅</span>');
var $watchers = $('<a>').attr('href', repo.html_url + '/watchers').text(repo.watchers + ' stargazers');
$item.append($('<span>').addClass('watchers').append($watchers));
$item.append('<span class="bullet">⋅</span>');
var $forks = $('<a>').attr('href', repo.html_url + '/network').text(repo.forks + ' forks');
$item.append($('<span>').addClass('forks').append($forks));
$('#recently-updated').removeClass('loading').append($item);
}
function addRepo(repo) {
var $item = $('<div>').addClass('column');
var $link = $('<a>').attr('href', repo.html_url).appendTo($item);
$link.addClass('repo lang-'+ (repo.language || '').toLowerCase().replace(/[\+#]/gi, '') );
$link.append($('<h4 class="repo-name">').text(repo.name || 'Unknown'));
$link.append($('<h5 class="repo-lang">').text(repo.language || ''));
$link.append($('<p class="repo-desc">').text(repo.description || ''));
if( featured.indexOf(repo.name) > -1 ){
$link.addClass('featured'+(++num));
$item.prependTo('#repos');
}else{
$item.appendTo('#repos');
}
}
function addRepos(repos, page) {
repos = repos || [];
page = page || 1;
var uri = 'https://api.github.com/orgs/cloudflare/repos?callback=?' + '&per_page=100' + '&page='+page;
$.getJSON(uri, function (result) {
// API Rate limiting catch
if( result.data && result.data.message ){
$('<p class="text-error">')
.text('Your IP has hit github\'s rate limit per hour.')
.appendTo('.hero-block');
return;
}
repos = repos.concat(result.data);
if( result.data && result.data.length == 100 ){
addRepos(repos, page + 1);
}else{
repos = $.grep(repos, function(value) {
return exclude.indexOf(value.name) === -1;
});
$('#repo-count').text(repos.length).removeClass('loading');
// Convert pushed_at to Date.
$.each(repos, function (i, repo) {
repo.pushed_at = new Date(repo.pushed_at || null);
});
// Sort by most-recently pushed to.
// or is featured
repos.sort(function (a, b) {
if (a.pushed_at < b.pushed_at) return 1;
if (b.pushed_at < a.pushed_at) return -1;
return 0;
});
$.each(repos, function (i, repo) {
addRepo(repo);
if( i < 3 ) addRecentlyUpdatedRepo(repo);
});
}
});
}
function addMember( member ){
var $item = $('<div>').addClass('column');
var $link = $('<a>').attr('href', member.html_url).appendTo($item);
var $deets = $('<div>').addClass('member-info').appendTo($link);
$link.addClass('member');
$link.prepend($('<img height="90" width="90">').attr('src', member.avatar_url).addClass('member-avatar'));
$deets.append( $('<h4 class="user-name">').text(member.login));
$item.appendTo('#members');
}
function addMembers(){
$.getJSON('https://api.github.com/orgs/cloudflare/members?callback=?', function (result) {
// API Rate limiting catch
if( result.data && result.data.message ){ return; }
var members = result.data;
$('#member-count').text(members.length).removeClass('loading');
$.each( members, function(idx, member){ addMember( member ); });
});
}
addRepos(customRepos);
addMembers();
$('#activate-mobile-menu').on('click', function( evt ){
evt.preventDefault();
$('#header').toggleClass('mobile-menu-active');
})
})(jQuery);
| JavaScript | 0.000001 | @@ -740,36 +740,33 @@
%0A%09%09%09language : '
-Perl
+C
',%0A%09%09%09descriptio
|
7a4dadb2de8061ac5950dec1ceb4e5c67cc4edac | Fix conflicting addon status enabled (#1107) | static/js/installed-addon.js | static/js/installed-addon.js | /**
* InstalledAddon.
*
* Represents an existing, installed add-on.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
const API = require('./api');
const Utils = require('./utils');
const page = require('./lib/page');
/**
* InstalledAddon constructor.
*
* @param {Object} metadata InstalledAddon metadata object.
* @param {Object} installedAddonsMap Handle to the installedAddons map from
* SettingsScreen.
* @param {Object} availableAddonsMap Handle to the availableAddons map from
* SettingsScreen.
* @param {String} updateUrl URL for updated add-on package
* @param {String} updateVersion Version of updated add-on package
* @param {String} updateChecksum Checksum of the updated add-on package
*/
const InstalledAddon = function(metadata, installedAddonsMap,
availableAddonsMap, updateUrl, updateVersion,
updateChecksum) {
this.name = metadata.name;
this.description = metadata.description;
this.author = metadata.author;
this.homepage = metadata.homepage;
this.version = metadata.version;
this.enabled = metadata.moziot.enabled;
this.config = metadata.moziot.config;
this.schema = metadata.moziot.schema;
this.updateUrl = updateUrl;
this.updateVersion = updateVersion;
this.updateChecksum = updateChecksum;
this.container = document.getElementById('installed-addons-list');
this.installedAddonsMap = installedAddonsMap;
this.availableAddonsMap = availableAddonsMap;
this.render();
};
/**
* HTML view for InstalledAddon.
*/
InstalledAddon.prototype.view = function() {
let toggleButtonText, toggleButtonClass;
if (this.enabled) {
toggleButtonText = 'Disable';
toggleButtonClass = 'addon-settings-disable';
} else {
toggleButtonText = 'Enable';
toggleButtonClass = 'addon-settings-enable';
}
const updateButtonClass = this.updateUrl ? '' : 'hidden';
const configButtonClass = this.schema ? '' : 'hidden';
return `
<li id="addon-item-${Utils.escapeHtml(this.name)}" class="addon-item">
<div class="addon-settings-header">
<span class="addon-settings-name">
${Utils.escapeHtml(this.name)}
</span>
<span class="addon-settings-version">
${Utils.escapeHtml(this.version)}
</span>
<span class="addon-settings-description">
${Utils.escapeHtml(this.description)}
</span>
<span class="addon-settings-author">
by <a href="${this.homepage}" target="_blank" rel="noopener">
${Utils.escapeHtml(this.author)}
</a>
</span>
</div>
<div class="addon-settings-controls">
<button id="addon-config-${Utils.escapeHtml(this.name)}"
class="text-button addon-settings-config ${configButtonClass}">
Configure
</button>
<button id="addon-update-${Utils.escapeHtml(this.name)}"
class="text-button addon-settings-update ${updateButtonClass}">
Update
</button>
<span class="addon-settings-spacer"></span>
<button id="addon-remove-${Utils.escapeHtml(this.name)}"
class="text-button addon-settings-remove">
Remove
</button>
<button id="addon-toggle-${Utils.escapeHtml(this.name)}"
class="text-button ${toggleButtonClass}">
${toggleButtonText}
</button>
</div>
</li>`;
};
/**
* Render InstalledAddon view and add to DOM.
*/
InstalledAddon.prototype.render = function() {
this.container.insertAdjacentHTML('beforeend', this.view());
const configButton = document.getElementById(
`addon-config-${Utils.escapeHtml(this.name)}`);
configButton.addEventListener('click', this.handleConfig.bind(this));
const updateButton = document.getElementById(
`addon-update-${Utils.escapeHtml(this.name)}`);
updateButton.addEventListener('click', this.handleUpdate.bind(this));
const removeButton = document.getElementById(
`addon-remove-${Utils.escapeHtml(this.name)}`);
removeButton.addEventListener('click', this.handleRemove.bind(this));
const toggleButton = document.getElementById(
`addon-toggle-${Utils.escapeHtml(this.name)}`);
toggleButton.addEventListener('click', this.handleToggle.bind(this));
};
/**
* Handle a click on the config button.
*/
InstalledAddon.prototype.handleConfig = function() {
page(`/settings/addons/config/${this.name}`);
};
/**
* Handle a click on the update button.
*/
InstalledAddon.prototype.handleUpdate = function(e) {
const controlDiv = e.target.parentNode;
const versionDiv = document.querySelector(
`#addon-item-${Utils.escapeHtml(this.name)} .addon-settings-version`);
const updating = document.createElement('span');
updating.classList.add('addon-updating');
updating.innerText = 'Updating...';
controlDiv.replaceChild(updating, e.target);
API.updateAddon(this.name, this.updateUrl, this.updateChecksum)
.then(() => {
versionDiv.innerText = this.updateVersion;
updating.innerText = 'Updated';
})
.catch((err) => {
console.error(`Failed to update add-on: ${this.name}\n${err}`);
updating.innerText = 'Failed';
});
};
/**
* Handle a click on the remove button.
*/
InstalledAddon.prototype.handleRemove = function() {
API.uninstallAddon(this.name)
.then(() => {
const el = document.getElementById(
`addon-item-${Utils.escapeHtml(this.name)}`);
el.parentNode.removeChild(el);
this.installedAddonsMap.delete(this.name);
const addon = this.availableAddonsMap.get(this.name);
if (addon) {
addon.installed = false;
}
})
.catch((e) => {
console.error(`Failed to uninstall add-on: ${this.name}\n${e}`);
});
};
/**
* Handle a click on the enable/disable button.
*/
InstalledAddon.prototype.handleToggle = function(e) {
const button = e.target;
this.enabled = !this.enabled;
API.setAddonSetting(this.name, this.enabled)
.then(() => {
if (this.enabled) {
button.innerText = 'Disable';
button.classList.remove('addon-settings-enable');
button.classList.add('addon-settings-disable');
} else {
button.innerText = 'Enable';
button.classList.remove('addon-settings-disable');
button.classList.add('addon-settings-enable');
}
})
.catch((err) => {
console.error(`Failed to toggle add-on: ${this.name}\n${err}`);
});
};
module.exports = InstalledAddon;
| JavaScript | 0 | @@ -6072,29 +6072,30 @@
e.target;%0A
-this.
+const
enabled = !t
@@ -6140,21 +6140,16 @@
s.name,
-this.
enabled)
@@ -6163,24 +6163,152 @@
hen(() =%3E %7B%0A
+ this.enabled = enabled;%0A const addon = this.installedAddonsMap.get(this.name);%0A addon.moziot.enabled = enabled;%0A
if (th
|
af46b356bc9ffa45deed6fe709b7e8fab198653d | Update playground.js | static/scripts/playground.js | static/scripts/playground.js | (function() {
String.prototype.escape = function() {
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
return this.replace(/[&<>]/g, function(tag) {
return tagsToReplace[tag] || tag;
});
};
var NatashaEndpoint = 'https://natasha-playground.herokuapp.com/api/extract';
var GrammarsClasses = {
Person: 'person',
Organisation: 'org',
Geo: 'geo',
Date: 'date',
Money: 'money',
Event: 'event',
Brand: 'brand',
};
var form = document.forms[0].addEventListener('submit', function(e) {
e.preventDefault();
var request = new XMLHttpRequest(),
text = this.text.value.escape(),
button = this.start;
button.className = button.className.replace('pure-button-primary', 'pure-button-disabled');
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var matches = JSON.parse(request.responseText),
originals = [];
matches = matches.sort(function(a, b) {
return b.match.length - a.match.length;
});
for (var i = matches.length - 1; i >= 0; i--) {
var grammar = matches[i].grammar,
tokens = matches[i].match;
var position = [tokens[0][2][0], tokens[tokens.length - 1][2][1]];
var original = text.substring(position[0], position[1]);
originals.push([grammar, original, position]);
};
for (var i = originals.length - 1; i >= 0; i--) {
var grammar = originals[i][0],
original = originals[i][1],
position = originals[i][2];
text = text.split(original).join('<span class="' + GrammarsClasses[grammar] + '">' + original + '</span>');
};
text = text.split('\n').join('<br>');
document.getElementById("result").innerHTML = text;
button.className = button.className.replace('pure-button-disabled', 'pure-button-primary');
};
};
request.open("POST", NatashaEndpoint, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("text=" + text);
});
})();
| JavaScript | 0.000001 | @@ -1200,21 +1200,22 @@
eturn b.
-match
+tokens
.length
@@ -1218,21 +1218,22 @@
gth - a.
-match
+tokens
.length;
@@ -1415,21 +1415,22 @@
ches%5Bi%5D.
-match
+tokens
;%0A
@@ -1469,17 +1469,17 @@
kens%5B0%5D%5B
-2
+1
%5D%5B0%5D, to
@@ -1502,17 +1502,17 @@
th - 1%5D%5B
-2
+1
%5D%5B1%5D%5D;%0A
|
9d99c3d7a6330d999bc953a14a5f4e88e686f12c | Fix module loading in timetable | app/scripts/timetable_builder/collections/TimetableModuleCollection.js | app/scripts/timetable_builder/collections/TimetableModuleCollection.js | define([
'underscore',
'backbone',
'common/collections/ModuleCollection',
'../models/LessonModel',
'../collections/LessonCollection'
],
function(_, Backbone, ModuleCollection, LessonModel, LessonCollection) {
'use strict';
return ModuleCollection.extend({
initialize: function (models, options) {
this.colors = [];
this.exams = options.exams;
this.timetable = options.timetable;
this.on('add', this.onAdd, this);
this.on('remove', this.onRemove, this);
},
onAdd: function(module) {
var code = module.id;
if (!this.colors.length) {
this.colors = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
}
var color = this.colors.splice(Math.floor(Math.random() * this.colors.length), 1)[0];
var title = timetableData.mods[code].title;
this.exams.add({
color: color,
id: code,
time: module.get('examStr'),
title: title,
unixTime: module.get('exam')
});
var lessonKeys = ['type', 'group', 'week', 'day', 'start', 'end', 'room'];
var lessons = _.map(timetableData.mods[code].lessons, function(lesson) {
return _.object(lessonKeys, lesson);
});
_.each(_.groupBy(lessons, 'type'), function(groups, type) {
var firstGroup = true;
var isDraggable = _.size(groups) > 1;
var sameType = new LessonCollection();
_.each(_.groupBy(groups, 'group'), function(lessonsData, group) {
var sameGroup = new LessonCollection();
_.each(lessonsData, function(lessonData) {
var lesson = new LessonModel({
week: lessonData.week,
day: lessonData.day,
start: lessonData.start,
end: lessonData.end,
room: lessonData.room,
code: code,
color: color,
group: group,
isDraggable: isDraggable,
sameGroup: sameGroup,
sameType: sameType,
title: title,
type: type
});
sameGroup.add(lesson);
sameType.add(lesson);
if (firstGroup) {
this.timetable.add(lesson);
}
}, this);
firstGroup = false;
}, this);
}, this);
},
onRemove: function(module) {
this.timetable.remove(this.timetable.where({code: module.id}));
this.exams.remove(this.exams.get(module.id));
}
});
});
| JavaScript | 0 | @@ -582,18 +582,25 @@
module.
-id
+get('id')
;%0A%0A
|
e462c1bc333d8a83d3322be07b19716338c1578e | Allow multiple connection with strapi-bookshelf connector | packages/strapi-bookshelf/lib/index.js | packages/strapi-bookshelf/lib/index.js | 'use strict';
/**
* Module dependencies
*/
// Public node modules.
const _ = require('lodash');
const bookshelf = require('bookshelf');
const pluralize = require('pluralize');
// Local helpers.
const utils = require('./utils/');
// Strapi helpers for models.
const utilsModels = require('strapi-utils').models;
/**
* Bookshelf hook
*/
module.exports = function (strapi) {
const hook = {
/**
* Default options
*/
defaults: {
defaultConnection: 'default',
host: 'localhost'
},
/**
* Initialize the hook
*/
initialize: cb => {
let globalName;
// Make sure the Knex hook is present since Knex needs it.
if (!strapi.hooks.knex) {
strapi.log.error('Impossible to load the ORM without the query builder!');
strapi.log.error('You need to install the Strapi query builder with `$ npm install strapi-knex --save`.');
strapi.stop(1);
}
// Only run this logic after the Knex has finished to load.
strapi.after('hook:knex:loaded', () => {
// Initialize collections
_.set(strapi, 'bookshelf.collections', {});
// Return callback if there is no model
if (_.isEmpty(strapi.models)) {
return cb();
}
_.forEach(_.pickBy(strapi.config.connections, {connector: 'strapi-bookshelf'}), (connection, connectionName) => {
// Apply defaults
_.defaults(connection.settings, strapi.hooks.bookshelf.defaults);
// Select models concerned by this connection
const models = _.pickBy(strapi.models, {connection: connectionName});
// Return callback if there is no model
if (_.isEmpty(models)) {
return cb();
}
const loadedHook = _.after(_.size(models), () => {
cb();
});
// Parse every registered model.
_.forEach(models, (definition, model) => {
globalName = _.upperFirst(_.camelCase(definition.globalId));
// Make sure the model has a table name.
// If not, use the model name.
if (_.isEmpty(definition.tableName)) {
definition.tableName = model;
}
// Add some informations about ORM & client connection
definition.orm = 'bookshelf';
definition.client = _.get(connection.settings, 'client');
// Register the final model for Bookshelf.
const loadedModel = {
tableName: definition.tableName,
hasTimestamps: _.get(definition, 'options.timestamps') === true
};
// Initialize the global variable with the
// capitalized model name.
global[globalName] = {};
// Call this callback function after we are done parsing
// all attributes for relationships-- see below.
const done = _.after(_.size(definition.attributes), () => {
try {
// Initialize lifecycle callbacks.
loadedModel.initialize = () => {
const self = this;
const lifecycle = {
creating: 'beforeCreate',
created: 'afterCreate',
destroying: 'beforeDestroy',
destroyed: 'afterDestroy',
updating: 'beforeUpdate',
updated: 'afterUpdate',
fetching: 'beforeFetch',
fetched: 'afterFetch',
saving: 'beforeSave',
saved: 'afterSave'
};
_.forEach(lifecycle, (fn, key) => {
if (_.isFunction(strapi.models[model.toLowerCase()][fn])) {
self.on(key, strapi.models[model.toLowerCase()][fn]);
}
});
};
loadedModel.hidden = _.keys(_.keyBy(_.filter(definition.attributes, (value, key) => {
if (value.hasOwnProperty('columnName') && !_.isEmpty(value.columnName) && value.columnName !== key) {
return true;
}
}), 'columnName'));
const ORM = new bookshelf(strapi.connections[connectionName]);
// Load plugins
ORM.plugin('visibility');
global[globalName] = ORM.Model.extend(loadedModel);
global[pluralize(globalName)] = ORM.Collection.extend({
model: global[globalName]
});
// Push model to strapi global variables.
strapi.bookshelf.collections[globalName.toLowerCase()] = global[globalName];
// Push attributes to be aware of model schema.
strapi.bookshelf.collections[globalName.toLowerCase()]._attributes = definition.attributes;
loadedHook();
} catch (err) {
strapi.log.error('Impossible to register the `' + model + '` model.');
strapi.log.error(err);
strapi.stop();
}
});
if (_.isEmpty(definition.attributes)) {
done();
}
// Add every relationships to the loaded model for Bookshelf.
// Basic attributes don't need this-- only relations.
_.forEach(definition.attributes, (details, name) => {
const verbose = _.get(utilsModels.getNature(details, name), 'verbose') || '';
// Build associations key
if (!_.isEmpty(verbose)) {
utilsModels.defineAssociations(globalName, definition, details, name);
}
switch (verbose) {
case 'hasOne': {
const FK = _.findKey(strapi.models[details.model].attributes, details => {
if (details.hasOwnProperty('model') && details.model === model && details.hasOwnProperty('via') && details.via === name) {
return details;
}
});
const globalId = _.get(strapi.models, `${details.model.toLowerCase()}.globalId`);
loadedModel[name] = function () {
return this.hasOne(global[globalId], _.get(strapi.models[details.model].attributes, `${FK}.columnName`) || FK);
};
break;
}
case 'hasMany': {
const globalId = _.get(strapi.models, `${details.collection.toLowerCase()}.globalId`);
const FKTarget = _.get(strapi.models[globalId.toLowerCase()].attributes, `${details.via}.columnName`) || details.via;
loadedModel[name] = function () {
return this.hasMany(global[globalId], FKTarget);
};
break;
}
case 'belongsTo': {
const globalId = _.get(strapi.models, `${details.model.toLowerCase()}.globalId`);
loadedModel[name] = function () {
return this.belongsTo(global[globalId], _.get(details, 'columnName') || name);
};
break;
}
case 'belongsToMany': {
const tableName = _.get(details, 'tableName') || _.map(_.sortBy([strapi.models[details.collection].attributes[details.via], details], 'collection'), table => {
return _.snakeCase(pluralize.plural(table.collection) + ' ' + pluralize.plural(table.via));
}).join('__');
const relationship = _.clone(strapi.models[details.collection].attributes[details.via]);
// Force singular foreign key
relationship.attribute = pluralize.singular(relationship.collection);
details.attribute = pluralize.singular(details.collection);
// Define PK column
details.column = utils.getPK(model, strapi.models);
relationship.column = utils.getPK(details.collection, strapi.models);
// Sometimes the many-to-many relationships
// is on the same keys on the same models (ex: `friends` key in model `User`)
if (details.attribute + '_' + details.column === relationship.attribute + '_' + relationship.column) {
relationship.attribute = pluralize.singular(details.via);
}
loadedModel[name] = function () {
return this.belongsToMany(global[_.upperFirst(details.collection)], tableName, relationship.attribute + '_' + relationship.column, details.attribute + '_' + details.column);
};
break;
}
default: {
break;
}
}
done();
});
});
});
});
}
};
return hook;
};
| JavaScript | 0 | @@ -1266,26 +1266,36 @@
-_.forEach(
+const connections =
_.pickBy
@@ -1354,16 +1354,135 @@
shelf'%7D)
+;%0A%0A const done = _.after(_.size(connections), () =%3E %7B%0A cb();%0A %7D);%0A%0A _.forEach(connections
, (conne
@@ -1939,34 +1939,36 @@
%3E %7B%0A
-cb
+done
();%0A %7D)
|
2533a7ababce0f2b0e6a7a8a771088c1654d592c | Fix the suspicious knob | www/assets/admin.js | www/assets/admin.js | $(document).ready(function() {
// Wire up is_suspicious toggle.
// =============================
$('.is-suspicious-label input').change(function() {
var username = $(this).attr('data-username');
jQuery.ajax({
url: '/' + username + '/toggle-is-suspicious.json',
type: 'POST',
dataType: 'json',
success: function (data) {
$('.avatar').toggleClass('is-suspicious', data.is_suspicious);
$('.is-suspicious-label input').prop('checked', data.is_suspicious);
},
error: Gratipay.error,
});
});
});
| JavaScript | 0 | @@ -250,16 +250,17 @@
url: '/
+~
' + user
|
63e606aa152ce3baaea7f5638ee331c27f971039 | Fix javascript errors resulting from SAK-29356 | assignment/assignment-tool/tool/src/webapp/js/studentViewSubmission.js | assignment/assignment-tool/tool/src/webapp/js/studentViewSubmission.js | var ASN_SVS = {};
/* For the cancel button - if the user made progress, we need them to confirm that they want to discard their progress */
ASN_SVS.confirmDiscardOrSubmit = function(attachmentsModified)
{
var inlineProgress = false;
var ckEditor = CKEDITOR.instances["$name_submission_text"];
if (ckEditor)
{
inlineProgress = CKEDITOR.instances["$name_submission_text"].checkDirty();
}
var showDiscardDialog = inlineProgress || attachmentsModified;
var submitPanel = document.getElementById("submitPanel");
var confirmationDialogue = document.getElementById("confirmationDialogue");
if (showDiscardDialog)
{
submitPanel.setAttribute('style', 'display:none;');
confirmationDialogue.removeAttribute('style');
}
else
{
cancelProceed();
}
}
ASN_SVS.cancelProceed = function()
{
document.addSubmissionForm.onsubmit();
document.addSubmissionForm.option.value='cancel';
document.addSubmissionForm.submit();
}
ASN_SVS.undoCancel = function()
{
var submitPanel = document.getElementById("submitPanel");
var confirmationDialogue = document.getElementById("confirmationDialogue");
submitPanel.removeAttribute('style');
confirmationDialogue.setAttribute('style', 'display:none;');
}
| JavaScript | 0 | @@ -730,16 +730,25 @@
lse%0A%09%7B%0A%09
+%09ASN_SVS.
cancelPr
|
4947ec2f63b2edc29fdee3cd6c0e45f3122c939d | Change API to prod | www/js/constants.js | www/js/constants.js | (function() {
// var API_BASE_URL = "http://www.probebe.org.br/api";
var API_BASE_URL = "http://192.168.0.103:3000/api";
angular.module("proBebe.constants", []).constant("Constants", Object.freeze({
API_BASE_URL: API_BASE_URL,
CHILDREN_URL: API_BASE_URL + "/children",
CREDENTIALS_URL: API_BASE_URL + "/credentials",
CREDENCIALS_SOCIAL_NETWORK_ID: API_BASE_URL + "/credentials/update_social_network_id",
DONATED_MESSAGES_URL: API_BASE_URL + "/donated_messages",
DEVICE_REGISTRATION_URL: API_BASE_URL + "/device_registrations/:platform_code",
MESSAGE_URL: API_BASE_URL + "/messages/",
ONLY_NEW_MESSAGE_URL: API_BASE_URL + "/only_new_messages",
PUSH_NOTIFICATION: {
GCM: {
SENDER_ID: "315459751586"
}
},
PROFILE_MAX_RECIPIENT_CHILDREN: API_BASE_URL + '/profiles/max_recipient_children',
SIGN_UP_URL: API_BASE_URL + "/users",
PROFILE_URL: API_BASE_URL + "/profiles",
PROFILE_TYPE_DONOR: 'donor',
PROFILE_TYPE_POSSIBLE_DONOR: 'possible_donor',
CLIENT_ID_FACEBOOK: '123448778003166',
USER_DATA_FACEBOOK: 'https://graph.facebook.com/v2.2/me',
CLIENT_ID_GOOGLEPLUS: '315459751586-34134ej3bd5gq9u3f9loubd1r8kkc3rk.apps.googleusercontent.com',
USER_DATA_GOOFLEPLUES: 'https://www.googleapis.com/plus/v1/people/me',
RESET_PASSWORD: API_BASE_URL + "/users/reset_password",
BIRTHDAY_CARD: API_BASE_URL + "/birthday_cards/show",
CATEGORIES: API_BASE_URL + "/categories"
}));
}());
| JavaScript | 0 | @@ -12,11 +12,8 @@
%7B%0A
- //
var
@@ -62,16 +62,19 @@
/api%22;%0A
+ //
var API
|
0fd7673abbc4dc525a8d70fb9ebb2b2ef966f409 | Read the file as text on the directive | www/js/directive.js | www/js/directive.js | //global directives go here
angular.module('omniwallet').directive('d3PieChart', function() {
return {
template: '<svg></svg>',
controller: function($scope, $element, $attrs) {
$scope.chart = {
width: 300,
height: 300
}
$scope.radius = Math.min($scope.chart.width, $scope.chart.height) / 2
$element.find('svg').attr('height', $scope.chart.height).attr('width', $scope.chart.width);
var color = d3.scale.category20()
var arc = d3.svg.arc()
.outerRadius($scope.radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.value;
});
var svg = d3.select("svg")
$scope.totalsPromise.then(function(successData) {
var data = [],
keys = Object.keys($scope.totals);
keys.forEach(function(e, i) {
data.push({
value: $scope.totals[e],
name: keys[i],
color: Math.floor(Math.random() * 10)
});
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) {
return color(d.data.color);
})
.attr('transform', 'translate(150,150)');
g.append("text")
.attr("transform", function(d) {
var c = arc.centroid(d);
return "translate(" + (150 + c[0]) + "," + (150 + c[1]) + ")";
})
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) {
return d.data.name;
});
});
}
}
}).directive('omTooltip', function() {
return {
template: '<small><strong>(?)<strong></small>',
link: function(scope, iElement, iAttrs, controller) {
if (iAttrs.text)
iElement.tooltip({
title: iAttrs.text,
placement: 'down',
container: 'body'
});
}
}
}).directive('match', [function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
scope.$watch('[' + attrs.ngModel + ', ' + attrs.match + ']', function(value) {
ctrl.$setValidity('match', value[0] === value[1]);
}, true);
}
}
}]).directive('autoFocus', function($timeout) {
return {
restrict: 'AC',
scope: {
'autoFocus': '=autoFocus'
},
link: function(scope, element) {
scope.$watch('autoFocus', function() {
if(scope.autoFocus) {
$timeout(function(){
$(element[0]).focus();
}, 100);
}
});
}
};
}).directive('combobox', function(){
return {
restrict:'E',
templateUrl:'/template/combobox/combobox.html',
scope:{
optionList: '=',
modelValue:'=',
label:'@',
placeholder:'@',
valueSelected:'&'
},
controller:function($scope){
$scope.filteredList = $scope.optionList;
$scope.selectedOption=false;
$scope.filter=function(){
var results = $scope.optionList.filter(function(option){
var matcher = new RegExp("^"+$scope.modelValue);
return matcher.test(option);
}) ;
$scope.filteredList = results.length > 0 ? results: ["No results"];
$scope.valueSelected({category:$scope.modelValue});
};
$scope.$watch(function(){ return $scope.optionList; },function(options){
$scope.filteredList = options.length > 0 ? options : ["No results"];
});
},
link: function(scope, element, attr){
scope.open = function(){
$('ul',element).css({
"max-height": 150,
"overflow-y": "auto",
"overflow-x": "hidden",
"width":$('input',element).outerWidth(),
"left":$('.input-group-addon',element).outerWidth()
});
$('.dropdown',element).addClass('open');
};
scope.close = function(){
if(!scope.selectedOption)
$('.dropdown',element).removeClass('open');
};
scope.optionSelected = function(option){
scope.modelValue = option;
$('.dropdown',element).removeClass('open');
scope.valueSelected({category:option});
scope.selectedOption=false;
};
element.on('mousedown','a',function(){
scope.selectedOption = true;
});
}
};
}).directive('ensureInteger', function() {
return {
restrict: 'A',
require: 'ngModel',
scope:{
ensureIf:'&',
ensureOver:'='
},
link: function(scope, ele, attrs, ngModel) {
scope.$watch("ensureOver", function(value) {
if(scope.ensureIf())
if (!(typeof value==='number' && (value%1)===0))
scope.ensureOver = Math.ceil(value);
});
scope.$watch("ensureIf", function(value) {
if(scope.ensureIf())
if (!(typeof value==='number' && (value%1)===0))
scope.ensureOver = Math.ceil(value);
});
}
};
}).directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
};
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
};
}]);
| JavaScript | 0.000011 | @@ -5731,15 +5731,12 @@
adAs
-DataURL
+Text
(cha
|
f14ee8b8dcc2e1e13a4a8dcb7f7bbb30b8757133 | Fix bad default filename | www/Hazelnut.js | www/Hazelnut.js | var process = function (filename, url, successCallback, errorCallback) {
if(!filename) {
filename = url.split('.').pop();
}
return cordova.exec(successCallback, errorCallback, 'Hazelnut', 'Open', [{
url: url,
filename: filename
}]);
};
window.hazelnut = {
open: process
};
if(module && module.exports) {
module.exports = process;
} | JavaScript | 0.000332 | @@ -29,17 +29,17 @@
name, ur
-l
+i
, succes
@@ -105,17 +105,17 @@
= ur
-l
+i
.split('
.').
@@ -110,17 +110,17 @@
.split('
-.
+/
').pop()
@@ -215,14 +215,14 @@
ur
-l
+i
: ur
-l
+i
,%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.