text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Update the PyPI version to 7.0.1.
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0.1',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
# -*- coding: utf-8 -*-
import os
from setuptools import setup
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except:
return ''
setup(
name='todoist-python',
version='7.0',
packages=['todoist', 'todoist.managers'],
author='Doist Team',
author_email='info@todoist.com',
license='BSD',
description='todoist-python - The official Todoist Python API library',
long_description = read('README.md'),
install_requires=[
'requests',
],
# see here for complete list of classifiers
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=(
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
),
)
|
Store game state in global var
|
var express = require('express');
var http = require('http');
var socketIO = require('socket.io');
var path = require('path');
var game = require('./game.js');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'jade');
app.use(express.static('public'));
var gameState = game.getInitialState();
app.get('/', function(req, res) {
res.render('index', gameState);
});
io.on('connection', function(socket){
console.log('CONNECT', socket.id);
socket.on('log on', function(name){
console.log('LOG ON', name);
socket.broadcast.emit('log on', name);
})
socket.on('log off', function(name) {
console.log('LOG OFF', name);
socket.broadcast.emit('log off', name);
})
socket.on('disconnect', function(){
console.log('DISCONNECT', socket.id);
});
socket.on('card click', function(click){
console.log('CARD CLICK', click.user, click.card);
io.emit('card click', click);
});
});
server.listen(3000, function() {
console.log("listening on port 3000");
});
|
var express = require('express');
var http = require('http');
var socketIO = require('socket.io');
var path = require('path');
var game = require('./game.js');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.set('views', path.join(__dirname, 'templates'));
app.set('view engine', 'jade');
app.use(express.static('public'));
app.get('/', function(req, res) {
var state0 = game.getInitialState()
res.render('index', state0);
})
io.on('connection', function(socket){
console.log('CONNECT', socket.id);
socket.on('log on', function(name){
console.log('LOG ON', name);
socket.broadcast.emit('log on', name);
})
socket.on('log off', function(name) {
console.log('LOG OFF', name);
socket.broadcast.emit('log off', name);
})
socket.on('disconnect', function(){
console.log('DISCONNECT', socket.id);
});
socket.on('card click', function(click){
console.log('CARD CLICK', click.user, click.card);
io.emit('card click', click);
});
});
server.listen(3000, function() {
console.log("listening on port 3000");
});
|
Add instruction about interpreter selection
|
<?php
/**
* Simple Breakpoints
*
* Tell the interpreter to pause execution and inspect variables.
*
* Ctrl+F8 (Windows/Linux)
* Command+F8 (Mac OS X)
*/
namespace Debugging1\JetBrains;
$name = 'Maarten';
// 0. PhpStorm has already preconfigured "PHP 7.1 with XDebug" interpreter with enabled XDebug. Please make sure it's
// selected in Settings|PHP|CLI Interpreter.
// 1. Place a breakpoint on the following line of code.
$name = 'Mikhail';
for ($i = 0; $i < 5; $i++) {
// 2. Place a breakpoint on the following line of code.
$name = 'Person ' . $i;
}
// 4. Use the context menu to debug the current PHP script. This should launch the debugger and break on our first breakpoint.
// We can see the current statement (that is about to be executed) marked.
// From the tool window below, the $name variable holds 'Maarten'.
// 5. Resume program by pressing the green icon from the tool window or using F9 (Command+Alt+R on Mac OS X).
// 6. From the tool window below, the $name variable holds 'Mikhail'.
// Also a new variable $i is now available, set to zero.
// 7. Resume debugging.
// 8. Every time we go through the loop, the variables that have been modified can be inspected.
|
<?php
/**
* Simple Breakpoints
*
* Tell the interpreter to pause execution and inspect variables.
*
* Ctrl+F8 (Windows/Linux)
* Command+F8 (Mac OS X)
*/
namespace Debugging1\JetBrains;
$name = 'Maarten';
// 1. Place a breakpoint on the following line of code.
$name = 'Mikhail';
for ($i = 0; $i < 5; $i++) {
// 2. Place a breakpoint on the following line of code.
$name = 'Person ' . $i;
}
// 4. Use the context menu to debug the current PHP script. This should launch the debugger and break on our first breakpoint.
// We can see the current statement (that is about to be executed) marked.
// From the tool window below, the $name variable holds 'Maarten'.
// 5. Resume program by pressing the green icon from the tool window or using F9 (Command+Alt+R on Mac OS X).
// 6. From the tool window below, the $name variable holds 'Mikhail'.
// Also a new variable $i is now available, set to zero.
// 7. Resume debugging.
// 8. Every time we go through the loop, the variables that have been modified can be inspected.
|
Allow component styles to be editable in React Dev Tools
|
import flattenStyle from './flattenStyle';
import StyleRegistry from './registry';
// allow component styles to be editable in React Dev Tools
if (process.env.NODE_ENV !== 'production') {
const { canUseDOM } = require('fbjs/lib/ExecutionEnvironment');
if (canUseDOM && window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__.resolveRNStyle = flattenStyle;
}
}
const absoluteFillObject = {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0
};
const absoluteFill = StyleRegistry.register(absoluteFillObject);
const StyleSheet = {
absoluteFill,
absoluteFillObject,
create(styles) {
const result = {};
Object.keys(styles).forEach(key => {
if (process.env.NODE_ENV !== 'production') {
const StyleSheetValidation = require('./StyleSheetValidation').default;
StyleSheetValidation.validateStyle(key, styles);
}
result[key] = StyleRegistry.register(styles[key]);
});
return result;
},
flatten: flattenStyle,
getStyleSheets() {
return StyleRegistry.getStyleSheets();
},
hairlineWidth: 1
};
export default StyleSheet;
|
import flattenStyle from './flattenStyle';
import StyleRegistry from './registry';
const absoluteFillObject = {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0
};
const absoluteFill = StyleRegistry.register(absoluteFillObject);
const StyleSheet = {
absoluteFill,
absoluteFillObject,
create(styles) {
const result = {};
Object.keys(styles).forEach(key => {
if (process.env.NODE_ENV !== 'production') {
const StyleSheetValidation = require('./StyleSheetValidation').default;
StyleSheetValidation.validateStyle(key, styles);
}
result[key] = StyleRegistry.register(styles[key]);
});
return result;
},
flatten: flattenStyle,
getStyleSheets() {
return StyleRegistry.getStyleSheets();
},
hairlineWidth: 1
};
export default StyleSheet;
|
Refactor magic strings into a constant.
git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1594249 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.core.config.plugins;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.apache.logging.log4j.util.Strings;
/**
* Annotation that identifies a Class as a Plugin.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Plugin {
/**
* Value of the elementType when none is specified.
*/
String EMPTY = Strings.EMPTY;
String name();
String category();
String elementType() default EMPTY;
boolean printObject() default false;
boolean deferChildren() default false;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.core.config.plugins;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation that identifies a Class as a Plugin.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Plugin {
/**
* Value of the elementType when none is specified.
*/
String EMPTY = "";
String name();
String category();
String elementType() default EMPTY;
boolean printObject() default false;
boolean deferChildren() default false;
}
|
Add vars & disable auto pausing
|
/*
* boot.js
* Sets up game and loads preloader assets
*/
/* Sets a global object to hold all the states of the game */
YINS = {
/* declare global variables, these will persist across different states */
score: 0,
/* Declare global colors used throughout the game
Usage example: YINS.color.purple */
color: {
purple: '#673ab7',
purple_light: '#b39ddb'
},
/* Text styles are available by calling: YINS.text.STYLE
for example: YINS.text.header */
text: {
title: {
font: '12vh Courier New',
fill: '#404040',
align: 'center'
},
header: {
font: '8vh Arial',
fill: '#f0f0f0',
align: 'center'
}
}
}
/* Constructor creates the game object */
YINS.Boot = function(game) {
console.log('%cStarting YINS..', 'color: white; background: #673ab7');
};
YINS.Boot.prototype = {
preload: function() {
// Load assets for the preloader state
},
create: function() {
// Phaser will automatically pause if the browser tab the game is in loses focus.
// This disables that
YINS.game.stage.disableVisibilityChange = true;
YINS.game.state.start('preloader');
}
};
|
/*
* boot.js
* Sets up game and loads preloader assets
*/
/* Sets a global object to hold all the states of the game */
YINS = {
/* declare global variables, these will persist across different states */
score: 0,
/* Declare global colors used throughout the game
Usage example: YINS.color.purple */
color: {
purple: '#673ab7'
},
/* Text styles are available by calling: YINS.text.STYLE
for example: YINS.text.header */
text: {
header: {
font: '8vh Arial',
fill: '#f0f0f0',
align: 'center'
}
}
}
/* Constructor creates the game object */
YINS.Boot = function(game) {
console.log('%cStarting YINS..', 'color: white; background: #673ab7');
};
YINS.Boot.prototype = {
preload: function() {
// Load assets for the preloader state
},
create: function() {
YINS.game.state.start('preloader');
}
};
|
Add method to get admin users.
|
module.exports = function(r) {
'use strict';
return {
allByProject: allByProject,
adminUsers: adminUsers,
};
function allByProject() {
return r.table('access').run().then(function(allAccess) {
let byProject = {};
allAccess.forEach(function(a) {
if (!(a.project_id in byProject)) {
byProject[a.project_id] = [];
}
byProject[a.project_id].push(a);
});
return byProject;
});
}
function adminUsers() {
return r.table('users').filter({admin: true}).run();
}
};
|
module.exports = function(r) {
'use strict';
return {
allByProject: allByProject
};
function allByProject() {
return r.table('access').run().then(function(allAccess) {
let byProject = {};
allAccess.forEach(function(a) {
if (!(a.project_id in byProject)) {
byProject[a.project_id] = [];
}
byProject[a.project_id].push(a);
});
return byProject;
});
}
};
|
Add error handling to station endpoint
|
"""
Michael duPont - michael@mdupont.com
avwx_api.views - Routes and views for the Quart application
"""
# pylint: disable=W0702
# stdlib
from dataclasses import asdict
# library
import avwx
from quart import Response, jsonify
from quart_openapi.cors import crossdomain
# module
from avwx_api import app
# Static Web Pages
@app.route('/')
@app.route('/home')
async def home() -> Response:
"""
Returns static home page
"""
return await app.send_static_file('html/home.html')
# API Routing Errors
@app.route('/api')
async def no_report() -> Response:
"""
Returns no report msg
"""
return jsonify({'error': 'No report type given'}), 400
@app.route('/api/metar')
@app.route('/api/taf')
async def no_station() -> Response:
"""
Returns no station msg
"""
return jsonify({'error': 'No station given'}), 400
@app.route('/api/station/<string:station>')
@crossdomain(origin='*')
async def station_endpoint(station: str) -> Response:
"""
Returns raw station info if available
"""
station = station.upper()
try:
return jsonify(asdict(avwx.Station.from_icao(station)))
except avwx.exceptions.BadStation:
return jsonify({
'error': f'Station ident "{station}" not found. Email me if data is missing :)'
})
|
"""
Michael duPont - michael@mdupont.com
avwx_api.views - Routes and views for the Quart application
"""
# pylint: disable=W0702
# stdlib
from dataclasses import asdict
# library
import avwx
from quart import Response, jsonify
from quart_openapi.cors import crossdomain
# module
from avwx_api import app
# Static Web Pages
@app.route('/')
@app.route('/home')
async def home() -> Response:
"""
Returns static home page
"""
return await app.send_static_file('html/home.html')
# API Routing Errors
@app.route('/api')
async def no_report() -> Response:
"""
Returns no report msg
"""
return jsonify({'error': 'No report type given'}), 400
@app.route('/api/metar')
@app.route('/api/taf')
async def no_station() -> Response:
"""
Returns no station msg
"""
return jsonify({'error': 'No station given'}), 400
@app.route('/api/station/<string:station>')
@crossdomain(origin='*')
async def station_endpoint(station: str) -> Response:
"""
Returns raw station info if available
"""
station = station.upper()
data = avwx.Station.from_icao(station)
if data:
return jsonify(asdict(data))
return jsonify({'error': f'Station ident "{station}" not found'})
|
Update device revoke icon margin
|
// @flow
import React from 'react'
import type {Props} from './index.render'
import {Confirm, Box, Text, Icon} from '../../common-adapters'
import {globalStyles, globalColors} from '../../styles/style-guide'
import type {Props as IconProps} from '../../common-adapters/icon'
const Render = ({name, type, deviceID, currentDevice, onSubmit, onCancel}: Props) => {
const icon: IconProps.type = {
'mobile': 'phone-color-revoke-m',
'desktop': 'computer-bw-revoke-m',
'backup': 'paper-key-remove-m'
}[type]
return (
<Confirm theme='public' danger submitLabel='Yes, delete it' onSubmit={() => onSubmit({deviceID, name, currentDevice})} onCancel={onCancel}>
<Box style={{...globalStyles.flexBoxColumn, minHeight: 80, marginBottom: 16, alignItems: 'center'}}>
<Icon type={icon} />
<Text type='Body' style={stylesName}>{name}</Text>
</Box>
<Text type='Header'>Are you sure you want to revoke {currentDevice ? 'your current device' : name}?</Text>
</Confirm>
)
}
const stylesName = {
textDecoration: 'line-through',
color: globalColors.red,
fontStyle: 'italic',
marginTop: 4,
flow: 1
}
export default Render
|
// @flow
import React from 'react'
import type {Props} from './index.render'
import {Confirm, Box, Text, Icon} from '../../common-adapters'
import {globalStyles, globalColors} from '../../styles/style-guide'
import type {Props as IconProps} from '../../common-adapters/icon'
const Render = ({name, type, deviceID, currentDevice, onSubmit, onCancel}: Props) => {
const icon: IconProps.type = {
'mobile': 'phone-color-revoke-m',
'desktop': 'computer-bw-revoke-m',
'backup': 'paper-key-remove-m'
}[type]
return (
<Confirm theme='public' danger submitLabel='Yes, delete it' onSubmit={() => onSubmit({deviceID, name, currentDevice})} onCancel={onCancel}>
<Box style={{...globalStyles.flexBoxColumn, minHeight: 80, marginBottom: 16, alignItems: 'center'}}>
<Icon type={icon} />
<Text type='Body' style={stylesName}>{name}</Text>
</Box>
<Text type='Header'>Are you sure you want to revoke {currentDevice ? 'your current device' : name}?</Text>
</Confirm>
)
}
const stylesName = {
textDecoration: 'line-through',
color: globalColors.red,
fontStyle: 'italic',
marginTop: 2,
flow: 1
}
export default Render
|
Fix support for SSL for proxied sites, or otherwise uncertain situations
My particular situation is deployed through ElasticBeanstalk, proxying
HTTPS to HTTP on the actual endpoints. This makes flask think that it is
only running with http, not https
|
from jinja2 import Markup
from flask import current_app, request
class _pagedown(object):
def include_pagedown(self):
return Markup('''
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/pagedown/1.0/Markdown.Converter.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/pagedown/1.0/Markdown.Sanitizer.min.js"></script>
''')
def html_head(self):
return self.include_pagedown()
class PageDown(object):
def __init__(self, app = None):
if app is not None:
self.init_app(app)
def init_app(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['pagedown'] = _pagedown()
app.context_processor(self.context_processor)
@staticmethod
def context_processor():
return {
'pagedown': current_app.extensions['pagedown']
}
|
from jinja2 import Markup
from flask import current_app, request
class _pagedown(object):
def include_pagedown(self):
if request.is_secure:
protocol = 'https'
else:
protocol = 'http'
return Markup('''
<script type="text/javascript" src="{0}://cdnjs.cloudflare.com/ajax/libs/pagedown/1.0/Markdown.Converter.min.js"></script>
<script type="text/javascript" src="{0}://cdnjs.cloudflare.com/ajax/libs/pagedown/1.0/Markdown.Sanitizer.min.js"></script>
'''.format(protocol))
def html_head(self):
return self.include_pagedown()
class PageDown(object):
def __init__(self, app = None):
if app is not None:
self.init_app(app)
def init_app(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['pagedown'] = _pagedown()
app.context_processor(self.context_processor)
@staticmethod
def context_processor():
return {
'pagedown': current_app.extensions['pagedown']
}
|
Fix typo in user script gen, s/versiom/version/
|
#!/usr/bin/env node
// Note: This is written in a semi-generic way, but only supports 1 script.
const manifestPath = __dirname + '/manifest.json';
const outPath = __dirname + '/dont-track-me-google.user.js';
const fs = require('fs');
const manifest = JSON.parse(fs.readFileSync(manifestPath));
const content_script0 = manifest.content_scripts[0];
let metadata = [
['name', manifest.name],
['namespace', 'Rob W'],
['description', manifest.description],
['version', manifest.version],
['icon', 'https://raw.githubusercontent.com/Rob--W/dont-track-me-google/master/icon48.png'],
['run-at', content_script0.run_at.replace('_', '-')],
...content_script0.matches.map(pattern => ['match', pattern]),
].map(([key, value]) => {
return `// @${key} ${value}`;
}).join('\n');
let outStream = fs.createWriteStream(outPath);
outStream.write(`// ==UserScript==
${metadata}
// ==/UserScript==
`);
// Pipes and closes.
fs.createReadStream(content_script0.js[0]).pipe(outStream);
|
#!/usr/bin/env node
// Note: This is written in a semi-generic way, but only supports 1 script.
const manifestPath = __dirname + '/manifest.json';
const outPath = __dirname + '/dont-track-me-google.user.js';
const fs = require('fs');
const manifest = JSON.parse(fs.readFileSync(manifestPath));
const content_script0 = manifest.content_scripts[0];
let metadata = [
['name', manifest.name],
['namespace', 'Rob W'],
['description', manifest.description],
['versiom', manifest.version],
['icon', 'https://raw.githubusercontent.com/Rob--W/dont-track-me-google/master/icon48.png'],
['run-at', content_script0.run_at.replace('_', '-')],
...content_script0.matches.map(pattern => ['match', pattern]),
].map(([key, value]) => {
return `// @${key} ${value}`;
}).join('\n');
let outStream = fs.createWriteStream(outPath);
outStream.write(`// ==UserScript==
${metadata}
// ==/UserScript==
`);
// Pipes and closes.
fs.createReadStream(content_script0.js[0]).pipe(outStream);
|
Fix of license header.
P.S. Last two commits (fa1eb4, de784f) were reviewed by M. Grebac, M. Vojtek
Signed-off-by: Marcel Valovy <ef00af7100c873d895802f1bb3b3980ada420991@oracle.com>
|
/**
* ****************************************************************************
* Copyright (c) 2014, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
* <p/>
* Contributors:
* Marcel Valovy - initial API and implementation
* ****************************************************************************
*/
package org.eclipse.persistence.testing.jaxb.beanvalidation.special;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @author Marcel Valovy
*/
public class CustomAnnotationValidator implements ConstraintValidator<CustomAnnotation, Integer> {
@Override
public void initialize(CustomAnnotation constraintAnnotation) {
}
@Override
public boolean isValid(Integer object, ConstraintValidatorContext constraintContext) {
return false;
}
}
|
package org.eclipse.persistence.testing.jaxb.beanvalidation.special;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* ****************************************************************************
* Copyright (c) 2014, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
* <p/>
* Contributors:
* Marcel Valovy - initial API and implementation
* ****************************************************************************
*/
public class CustomAnnotationValidator implements ConstraintValidator<CustomAnnotation, Integer> {
@Override
public void initialize(CustomAnnotation constraintAnnotation) {
}
@Override
public boolean isValid(Integer object, ConstraintValidatorContext constraintContext) {
return false;
}
}
|
Add recent changes to compressed version
|
(function(e){e.Model.extend=e.Collection.extend=e.Router.extend=e.View.extend=function(e,t){var r=n(this,e,t);r.extend=this.extend;return r};var t=function(){},n=function(e,n,r){var i,s=e.prototype,o=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;if(n&&n.hasOwnProperty("constructor")){i=n.constructor}else{i=function(){e.apply(this,arguments)}}_.extend(i,e);t.prototype=e.prototype;i.prototype=new t;if(n){_.extend(i.prototype,n);for(var u in n){if(typeof n[u]=="function"&&typeof s[u]=="function"&&o.test(n[u])){i.prototype[u]=function(e,t){var n=function(){var n=this._super;this._super=s[e];var r=t.apply(this,arguments);this._super=n;return r};for(var r in t){n[r]=t[r];delete t[r]}return n}(u,n[u])}}}if(r)_.extend(i,r);i.prototype.constructor=i;i.__super__=e.prototype;return i}})(Backbone)
|
(function(a){a.Model.extend=a.Collection.extend=a.Router.extend=a.View.extend=function(a,b){var d=c(this,a,b);d.extend=this.extend;return d};var b=function(){},c=function(a,c,d){var e,f=a.prototype,g=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;if(c&&c.hasOwnProperty("constructor")){e=c.constructor}else{e=function(){a.apply(this,arguments)}}_.extend(e,a);b.prototype=a.prototype;e.prototype=new b;if(c){_.extend(e.prototype,c);for(var h in c){if(typeof c[h]=="function"&&typeof f[h]=="function"&&g.test(c[h])){e.prototype[h]=function(a,b){return function(){var c=this._super;this._super=f[a];var d=b.apply(this,arguments);this._super=c;return d}}(h,c[h])}}}if(d)_.extend(e,d);e.prototype.constructor=e;e.__super__=a.prototype;return e}})(Backbone)
|
Test list command after the installation
|
<?php
use PhpBrew\Testing\CommandTestCase;
class InstallCommandTest extends CommandTestCase
{
/**
* @outputBuffering enabled
*/
public function testInstallCommandLatestMinorVersion() {
$this->assertTrue($this->runCommand("phpbrew --quiet install 5.4")); // we will likely get 5.4.34 - 2014-11-02
}
/**
* @outputBuffering enabled
*/
public function testInstallCommand()
{
$this->assertTrue($this->runCommand("phpbrew --quiet install 5.4.29 +sqlite +intl +icu"));
}
/**
* @outputBuffering enabled
* @depends testInstallCommand
*/
public function testListCommand()
{
$this->assertTrue($this->runCommand("phpbrew list -v -d"));
$this->assertTrue($this->runCommand("phpbrew list --dir --variants"));
}
/**
* @outputBuffering enabled
* @depends testInstallCommand
*/
public function testCleanCommand()
{
$this->assertTrue($this->runCommand("phpbrew --quiet clean 5.4.29"));
}
/**
* @outputBuffering enabled
* @depends testInstallCommand
*/
public function testInstallLikeCommand() {
$this->assertTrue($this->runCommand("phpbrew --quiet install -d --like 5.4.29 5.5.18 +soap"));
}
}
|
<?php
use PhpBrew\Testing\CommandTestCase;
class InstallCommandTest extends CommandTestCase
{
/**
* @outputBuffering enabled
*/
public function testInstallCommandLatestMinorVersion() {
$this->assertTrue($this->runCommand("phpbrew --quiet install 5.4")); // we will likely get 5.4.34 - 2014-11-02
}
/**
* @outputBuffering enabled
*/
public function testInstallCommand()
{
$this->assertTrue($this->runCommand("phpbrew --quiet install 5.4.29 +sqlite +intl +icu"));
}
/**
* @outputBuffering enabled
* @depends testInstallCommand
*/
public function testCleanCommand()
{
$this->assertTrue($this->runCommand("phpbrew --quiet clean 5.4.29"));
}
/**
* @outputBuffering enabled
* @depends testInstallCommand
*/
public function testInstallLikeCommand() {
$this->assertTrue($this->runCommand("phpbrew --quiet install -d --like 5.4.29 5.5.18 +soap"));
}
}
|
Sort extracted messages by key
|
import fs from 'fs'
import { sync as globSync } from 'glob'
import { sync as mkdirpSync } from 'mkdirp'
const MESSAGES_PATTERN = './_translations/**/*.json'
const LANG_DIR = './_translations/lang/'
// Aggregates the default messages that were extracted from the example app's
// React components via the React Intl Babel plugin. An error will be thrown if
// there are messages in different components that use the same `id`. The result
// is a flat collection of `id: message` pairs for the app's default locale.
let defaultMessages = globSync(MESSAGES_PATTERN)
.map(filename => fs.readFileSync(filename, 'utf8'))
.map(file => JSON.parse(file))
.reduce((collection, descriptors) => {
descriptors.forEach(({ id, defaultMessage }) => {
if (collection.hasOwnProperty(id))
throw new Error(`Duplicate message id: ${id}`)
collection[id] = defaultMessage
})
return collection
}, {})
// Sort keys by name
const messageKeys = Object.keys(defaultMessages)
messageKeys.sort()
defaultMessages = messageKeys.reduce((acc, key) => {
acc[key] = defaultMessages[key]
return acc
}, {})
mkdirpSync(LANG_DIR)
fs.writeFileSync(LANG_DIR + 'en.json',
JSON.stringify(defaultMessages, null, 2))
|
import fs from 'fs'
import { sync as globSync } from 'glob'
import { sync as mkdirpSync } from 'mkdirp'
const MESSAGES_PATTERN = './_translations/**/*.json'
const LANG_DIR = './_translations/lang/'
// Aggregates the default messages that were extracted from the example app's
// React components via the React Intl Babel plugin. An error will be thrown if
// there are messages in different components that use the same `id`. The result
// is a flat collection of `id: message` pairs for the app's default locale.
let defaultMessages = globSync(MESSAGES_PATTERN)
.map(filename => fs.readFileSync(filename, 'utf8'))
.map(file => JSON.parse(file))
.reduce((collection, descriptors) => {
descriptors.forEach(({ id, defaultMessage }) => {
if (collection.hasOwnProperty(id))
throw new Error(`Duplicate message id: ${id}`)
collection[id] = defaultMessage
})
return collection
}, {})
mkdirpSync(LANG_DIR)
fs.writeFileSync(LANG_DIR + 'en.json',
JSON.stringify(defaultMessages, null, 2))
|
Add pandas as requirement for the project
|
from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'numpy>=1.11',
'pandas>=0.18',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
|
from setuptools import setup
REPO_URL = 'http://github.com/datasciencebr/serenata-toolbox'
setup(
author='Serenata de Amor',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities',
],
description='Toolbox for Serenata de Amor project',
install_requires=[
'requests',
],
keywords='serenata de amor, data science, brazil, corruption',
license='MIT',
long_description='Check `Serenata Toolbox at GitHub <{}>`_.'.format(REPO_URL),
name='serenata-toolbox',
packages=['serenata_toolbox'],
url=REPO_URL,
version='0.0.1'
)
|
Update up to changes to QueryHandler
|
// Handle search query states
// Listens for changes in query string, then ensures that provided values are coherent,
// and if all is fine emits valid query objects
// (which are usually consumed by list managers to update state of tables)
'use strict';
var ensureObject = require('es5-ext/object/valid-object')
, ensureString = require('es5-ext/object/validate-stringifiable-value')
, once = require('timers-ext/once')
, fixLocationQuery = require('./fix-location-query')
, QueryHandler = require('./query-handler');
module.exports = function (handlersList, appLocation, pathname) {
var queryHandler, update;
appLocation = ensureObject(appLocation);
pathname = ensureString(pathname);
queryHandler = new QueryHandler(handlersList);
queryHandler.update = update = once(function () {
if (pathname !== appLocation.pathname) return;
queryHandler.resolve(appLocation.query).catch(function (e) {
if (!e.queryHandler) throw e;
console.error("Invalid query value: " + e.message);
fixLocationQuery(e.queryHandler.name, e.fixedQueryValue);
return;
});
});
queryHandler._handlers.forEach(function (handler) {
appLocation.query.get(handler.name).on('change', update);
});
appLocation.on('change', update);
update();
return queryHandler;
};
|
// Handle search query states
// Listens for changes in query string, then ensures that provided values are coherent,
// and if all is fine emits valid query objects
// (which are usually consumed by list managers to update state of tables)
'use strict';
var ensureObject = require('es5-ext/object/valid-object')
, ensureString = require('es5-ext/object/validate-stringifiable-value')
, once = require('timers-ext/once')
, fixLocationQuery = require('./fix-location-query')
, QueryHandler = require('./query-handler');
module.exports = function (handlersList, appLocation, pathname) {
var queryHandler, update;
appLocation = ensureObject(appLocation);
pathname = ensureString(pathname);
queryHandler = new QueryHandler(handlersList);
queryHandler.update = update = once(function () {
if (pathname !== appLocation.pathname) return;
try {
queryHandler.resolve(appLocation.query);
} catch (e) {
if (!e.queryHandler) throw e;
console.error("Invalid query value: " + e.message);
fixLocationQuery(e.queryHandler.name, e.fixedQueryValue);
return;
}
});
queryHandler._handlers.forEach(function (handler) {
appLocation.query.get(handler.name).on('change', update);
});
appLocation.on('change', update);
update();
return queryHandler;
};
|
Remove hardcoded AddThis ID, made migrations and form changes to store it in database.
|
<?php namespace app\Helpers\Validators;
use Illuminate\Validation\Validator;
/**
* Class MainMetaValidator
*
* A class to handle validation of main meta
* updates and creation.
*
* @author Rob Attfield <emailme@robertattfield.com> <http://www.robertattfield.com>
* @package app\Helpers\Validators
*/
class MainMetaValidator extends Validator
{
public static function validationRules()
{
return [
'title' => 'min:10|max:70',
'description' => 'min:20|max:160',
'keywords' => 'min:3|max:255',
'google_analytics_code' => 'max:20',
'yandex_verification' => 'max:70',
'bing_verification' => 'max:70',
'addthisid' => 'max:35',
'page_main_title' => 'required|min:15|max:100',
];
}
}
|
<?php namespace app\Helpers\Validators;
use Illuminate\Validation\Validator;
/**
* Class MainMetaValidator
*
* A class to handle validation of main meta
* updates and creation.
*
* @author Rob Attfield <emailme@robertattfield.com> <http://www.robertattfield.com>
* @package app\Helpers\Validators
*/
class MainMetaValidator extends Validator
{
public static function validationRules()
{
return [
'title' => 'min:10|max:70',
'description' => 'min:20|max:160',
'keywords' => 'min:3|max:255',
'google_analytics_code' => 'max:20',
'yandex_verification' => 'max:70',
'bing_verification' => 'max:70',
'addthisid' => 'max:35',
'page_main_title' => 'required|min:15|max:100',
//'page_main_content' => '',
];
}
}
|
Change server default option values
|
package main
import (
"flag"
"net"
"github.com/hnakamur/rdirsync"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
)
func main() {
var enableTLS bool
flag.BoolVar(&enableTLS, "enable-tls", false, "enable TLS")
var certFile string
flag.StringVar(&certFile, "cert-file", "server.crt", "TLS cert file")
var keyFile string
flag.StringVar(&keyFile, "key-file", "server.key", "TLS key file")
var addr string
flag.StringVar(&addr, "addr", ":10000", "server listen address")
flag.Parse()
lis, err := net.Listen("tcp", addr)
if err != nil {
grpclog.Fatal(err)
}
var opts []grpc.ServerOption
if enableTLS {
creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)
if err != nil {
grpclog.Fatalf("Failed to generate credentials %v", err)
}
opts = []grpc.ServerOption{grpc.Creds(creds)}
}
grpcServer := grpc.NewServer(opts...)
rdirsync.RegisterNewRDirSyncServer(grpcServer)
grpcServer.Serve(lis)
}
|
package main
import (
"flag"
"net"
"github.com/hnakamur/rdirsync"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
)
func main() {
var enableTLS bool
flag.BoolVar(&enableTLS, "enable-tls", false, "enable TLS")
var certFile string
flag.StringVar(&certFile, "cert-file", "../../ssl/server/server.crt", "TLS cert file")
var keyFile string
flag.StringVar(&keyFile, "key-file", "../../ssl/server/server.key", "TLS key file")
var addr string
flag.StringVar(&addr, "addr", ":10000", "server listen address")
flag.Parse()
lis, err := net.Listen("tcp", addr)
if err != nil {
grpclog.Fatal(err)
}
var opts []grpc.ServerOption
if enableTLS {
creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)
if err != nil {
grpclog.Fatalf("Failed to generate credentials %v", err)
}
opts = []grpc.ServerOption{grpc.Creds(creds)}
}
grpcServer := grpc.NewServer(opts...)
rdirsync.RegisterNewRDirSyncServer(grpcServer)
grpcServer.Serve(lis)
}
|
Define our plan of action for the code
|
<?php
function insert($xml)
{
//Standard SQL connection stuff
$linkID = mysql_connect("localhost", "root", "") or die ("Could not connect to database!");
mysql_select_db("agora", $linkID) or die ("Could not find database");
//Dig the Map ID out of the XML
//Check to see if the map already exists
//$mapClause = mysql_real_escape_string("$mapID");
//If not, create it!
//Validate nodes
//Validate textboxes
//Validate nodetext
//Validate arguments
//Validate connections
//Insert/update everything
//Set up the basics of the output XML.
header("Content-type: text/xml");
$xmlstr = "<?xml version='1.0' ?>\n<map></map>";
$output = new SimpleXMLElement($xmlstr);
return $output;
}
$xml = $_REQUEST['xml']; //TODO: Change this back to a GET when all testing is done.
$output = insert($xml);
print($output->asXML());
?>
|
<?php
function insert($map_id)
{
//Standard SQL connection stuff
$linkID = mysql_connect("localhost", "root", "") or die ("Could not connect to database!");
mysql_select_db("agora", $linkID) or die ("Could not find database");
$whereclause = mysql_real_escape_string("$mapID");
//Set up the basics of the XML.
header("Content-type: text/xml");
$xmlstr = "<?xml version='1.0' ?>\n<map></map>";
$xml = new SimpleXMLElement($xmlstr);
}
$map_id = $_REQUEST['map_id']; //TODO: Change this back to a GET when all testing is done.
$xml = $_REQUEST['xml']; //TODO: Change this back to a GET when all testing is done.
$output = insert($map_id);
print($output->asXML());
?>
|
Add example for query datetime range
|
#!/usr/bin/env python
from config import MongoSource
from manager import PluginManager
from log import LogDocGenerator
import datetime
def main():
# 1. load all plugins
plugin_manager = PluginManager()
# 2. get one or more mongodb collection
ms = MongoSource()
collection = ms.get_collection("net-test", "ename_access")
# 3. make a log_generator
log_generator = LogDocGenerator(collection)
# 4. use condition to get filtered logs
#condition = {"host":"192.168.1.57"}
now = datetime.datetime.now()
start = now - datetime.timedelta(hours=8, minutes=10)
end = now - datetime.timedelta(hours=8)
condition = {"time":{"$gte":start, "$lt":end}}
# 5. use keywords plugins to parse logs
keywords = ['ip']
for log_doc in log_generator.get_log_docs(condition):
plugin_manager.call_method('process', args=log_doc, keywords=keywords)
# 6. give a report
plugin_manager.call_method('report', args={}, keywords=keywords)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
from config import MongoSource
from manager import PluginManager
from log import LogDocGenerator
def main():
# 1. load all plugins
plugin_manager = PluginManager()
# 2. get one or more mongodb collection
ms = MongoSource()
collection = ms.get_collection("net-test", "ename_access")
# 3. make a log_generator
log_generator = LogDocGenerator(collection)
# 4. use condition to get filtered logs
#condition = {"host":"192.168.1.57"}
condition = {}
# 5. use keywords plugins to parse logs
keywords = ['ip']
for log_doc in log_generator.get_log_docs(condition):
plugin_manager.call_method('process', args=log_doc, keywords=keywords)
# 6. give a report
plugin_manager.call_method('report', args={}, keywords=keywords)
if __name__ == '__main__':
main()
|
Update migration script for users whose usernames aren't in emails field
OSF-5462
Previously the script only migrated users who had an empty emails
field. This updates the script to also handle users whose username
isn't in the emails field, even when the emails field isn't empty
|
"""Ensure that confirmed users' usernames are included in their emails field.
"""
import logging
import sys
from modularodm import Q
from website import models
from website.app import init_app
from scripts import utils as scripts_utils
logger = logging.getLogger(__name__)
def main():
# Set up storage backends
init_app(routes=False)
dry_run = 'dry' in sys.argv
count = 0
if not dry_run:
scripts_utils.add_file_logger(logger, __file__)
logger.info("Finding users with username not in confirmed emails")
for user in get_users_with_username_not_in_emails():
user.emails.append(user.username)
logger.info(repr(user))
if not dry_run:
user.save()
count += 1
logger.info('Migrated {} users'.format(count))
def get_users_with_username_not_in_emails():
return (
user for user in
models.User.find(Q('date_confirmed', 'ne', None))
if user.is_active and
user.username.lower() not in [email.lower() for email in user.emails] and
user.username is not None
)
if __name__ == '__main__':
main()
|
"""Ensure that users with User.emails == [] have User.username inserted.
"""
import logging
import sys
from modularodm import Q
from nose.tools import *
from website import models
from website.app import init_app
from scripts import utils as scripts_utils
logger = logging.getLogger(__name__)
def main():
# Set up storage backends
init_app(routes=False)
dry_run = 'dry' in sys.argv
if not dry_run:
scripts_utils.add_file_logger(logger, __file__)
logger.info("Iterating users with username not in confirmed emails")
for user in get_users_with_username_not_in_emails():
add_username_to_emails(user)
logger.info(repr(user))
if not dry_run:
user.save()
def get_users_with_username_not_in_emails():
return models.User.find(
Q('date_confirmed', 'ne', None)
& Q('emails', 'eq', [])
)
def add_username_to_emails(user):
user.emails.append(user.username)
if __name__ == '__main__':
main()
|
Fix spec failing over year with default options
|
var banner = require('./');
var chai = require('chai');
var expect = chai.expect;
describe('banner', function() {
var FILEPATH = 'test-target.js';
context('without options (using defaults)', function() {
var year = new Date().getFullYear();
var expectation = '/*!\n * add-banner <https://github.com/jonschlinkert/add-banner>\n *\n * Copyright (c) ' + year + ' Jon Schlinkert, contributors.\n * Licensed under the MIT license.\n */\n\n';
it('expected to populate banner', function() {
expect(banner(FILEPATH)).to.eql(expectation);
});
});
context('with specific options', function() {
var options = {
name: 'addbanner',
author: 'J. Schlinkert (https://github.com/jonschlinkert)',
homepage: 'https://github.com/jonschlinkert/addbanner',
banner: 'banner.tmpl',
year: '2017',
license: 'GPL-3'
};
var expectation = '/*!\n * addbanner <https://github.com/jonschlinkert/addbanner>\n *\n * Copyright (c) 2017 J. Schlinkert, contributors.\n * Licensed under the GPL-3 license.\n */\n\n';
it('expected to populate banner', function() {
expect(banner(FILEPATH, options)).to.eql(expectation);
});
});
});
|
var banner = require('./');
var chai = require('chai');
var expect = chai.expect;
describe('banner', function() {
var FILEPATH = 'test-target.js';
context('without options (using defaults)', function() {
var expectation = '/*!\n * add-banner <https://github.com/jonschlinkert/add-banner>\n *\n * Copyright (c) 2018 Jon Schlinkert, contributors.\n * Licensed under the MIT license.\n */\n\n';
it('expected to populate banner', function() {
expect(banner(FILEPATH)).to.eql(expectation);
});
});
context('with specific options', function() {
var options = {
name: 'addbanner',
author: 'J. Schlinkert (https://github.com/jonschlinkert)',
homepage: 'https://github.com/jonschlinkert/addbanner',
banner: 'banner.tmpl',
year: '2017',
license: 'GPL-3'
};
var expectation = '/*!\n * addbanner <https://github.com/jonschlinkert/addbanner>\n *\n * Copyright (c) 2017 J. Schlinkert, contributors.\n * Licensed under the GPL-3 license.\n */\n\n';
it('expected to populate banner', function() {
expect(banner(FILEPATH, options)).to.eql(expectation);
});
});
});
|
Add sample points API call
|
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var wims = new XMLHttpRequest();
wims.open("GET", "http://environment.data.gov.uk/water-quality/id/sampling-point?_limit=60000", false);
wims.send();
// status 200 = OK
console.log(wims.status);
console.log(wims.statusText);
//console.log(wims.responseText);
var json = JSON.parse(wims.responseText);
var count = Object.keys(json.items).length;
console.log(count);
//Get the file contents
// TODO: fix ReferenceError: File is not defined
/*
var txtFile = new File('sampling-points.txt');
txtFile.writeln(JSON.stringify(json.items));
txtFile.close();
*/
//console.log(JSON.parse(wims.responseText).length);
/*
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('test.db');
db.serialize(function() {
db.run('CREATE TABLE lorem (info TEXT)');
var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
for (var i = 0; i < 10; i++) {
stmt.run('Ipsum ' + i);
}
stmt.finalize();
db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
console.log(row.id + ': ' + row.info);
});
});
db.close();
*/
module.exports = router;
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var wims = new XMLHttpRequest();
wims.open("GET", "http://environment.data.gov.uk/water-quality/id/sampling-point/AN-WOODTON", false);
wims.send();
console.log(wims.status);
console.log(wims.statusText);
console.log(wims.responseText);
/*
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('test.db');
db.serialize(function() {
db.run('CREATE TABLE lorem (info TEXT)');
var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
for (var i = 0; i < 10; i++) {
stmt.run('Ipsum ' + i);
}
stmt.finalize();
db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
console.log(row.id + ': ' + row.info);
});
});
db.close();
*/
module.exports = router;
|
Fix NavListItem title property type declaration
|
/**
*
* NavItem
*
*/
import React from 'react';
import { Link } from 'react-router';
import { ListItem } from 'material-ui/List';
import * as Colors from 'material-ui/styles/colors';
function NavListItem(props) {
const borderRadiusSize = 2;
const linkStyle = {
textDecoration: 'none',
borderRadius: borderRadiusSize,
};
const activeLinkStyle = {
display: 'block',
backgroundColor: Colors.grey200,
};
return (
<Link to={props.to} style={linkStyle} activeStyle={activeLinkStyle}>
<ListItem insetChildren primaryText={props.title} leftIcon={props.icon} style={{ borderRadius: borderRadiusSize }} />
</Link>
);
}
NavListItem.propTypes = {
to: React.PropTypes.string.isRequired,
title: React.PropTypes.object.isRequired,
icon: React.PropTypes.object,
};
export default NavListItem;
|
/**
*
* NavItem
*
*/
import React from 'react';
import { Link } from 'react-router';
import { ListItem } from 'material-ui/List';
import * as Colors from 'material-ui/styles/colors';
function NavListItem(props) {
const borderRadiusSize = 2;
const linkStyle = {
textDecoration: 'none',
borderRadius: borderRadiusSize,
};
const activeLinkStyle = {
display: 'block',
backgroundColor: Colors.grey200,
};
return (
<Link to={props.to} style={linkStyle} activeStyle={activeLinkStyle}>
<ListItem insetChildren primaryText={props.title} leftIcon={props.icon} style={{ borderRadius: borderRadiusSize }} />
</Link>
);
}
NavListItem.propTypes = {
to: React.PropTypes.string.isRequired,
title: React.PropTypes.string.isRequired,
icon: React.PropTypes.object,
};
export default NavListItem;
|
Remove PDF_AD from stats list
|
# Licensed under an MIT open source license - see LICENSE
'''
Returns a list of all available distance metrics
'''
statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer",
"Skewness", "Kurtosis", "VCS_Density", "VCS_Velocity",
"PDF_Hellinger", "PDF_KS", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
twoD_statistics_list = \
["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "Tsallis", "Skewness", "Kurtosis",
"PDF_Hellinger", "PDF_KS", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
|
# Licensed under an MIT open source license - see LICENSE
'''
Returns a list of all available distance metrics
'''
statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer",
"Skewness", "Kurtosis", "VCS_Density", "VCS_Velocity",
"PDF_Hellinger", "PDF_KS", "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
twoD_statistics_list = \
["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "Tsallis", "Skewness", "Kurtosis",
"PDF_Hellinger", "PDF_KS", "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
|
Return lines from plot command
|
"""Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking.
*kwargs* are passed to matplotlib's ``imshow`` function. This command
always creates a new figure. Returns matplotlib's ``AxesImage``.
"""
plt.figure()
mpl_image = plt.imshow(image, **kwargs)
plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
plt.show(blocking)
return mpl_image
def plot(*args, **kwargs):
"""Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
*kwargs* are infected with *blocking* and if False or not specified,
the call is nonblocking. This command always creates a new figure. Returns
a list of ``Line2D`` instances.
"""
blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
plt.figure()
lines = plt.plot(*args, **kwargs)
plt.show(blocking)
return lines
|
"""Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking.
*kwargs* are passed to matplotlib's ``imshow`` function. This command
always creates a new figure. Returns matplotlib's ``AxesImage``.
"""
plt.figure()
mpl_image = plt.imshow(image, **kwargs)
plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
plt.show(blocking)
return mpl_image
def plot(*args, **kwargs):
"""Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
*kwargs* are infected with *blocking* and if False or not specified,
the call is nonblocking. This command always creates a new figure.
"""
blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
plt.figure()
plt.plot(*args, **kwargs)
plt.show(blocking)
|
Add "pyyaml" because it is used by ScrambleSuit.
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
import versioneer
versioneer.versionfile_source = 'obfsproxy/_version.py'
versioneer.versionfile_build = 'obfsproxy/_version.py'
versioneer.tag_prefix = 'obfsproxy-' # tags are like 1.2.0
versioneer.parentdir_prefix = 'obfsproxy-' # dirname like 'myproject-1.2.0'
setup(
name = "obfsproxy",
author = "asn",
author_email = "asn@torproject.org",
description = ("A pluggable transport proxy written in Python"),
license = "BSD",
keywords = ['tor', 'obfuscation', 'twisted'],
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
packages = find_packages(),
entry_points = {
'console_scripts': [
'obfsproxy = obfsproxy.pyobfsproxy:run'
]
},
install_requires = [
'setuptools',
'PyCrypto',
'Twisted',
'argparse',
'pyptlib >= 0.0.5',
'gmpy',
'pyyaml'
],
)
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
import versioneer
versioneer.versionfile_source = 'obfsproxy/_version.py'
versioneer.versionfile_build = 'obfsproxy/_version.py'
versioneer.tag_prefix = 'obfsproxy-' # tags are like 1.2.0
versioneer.parentdir_prefix = 'obfsproxy-' # dirname like 'myproject-1.2.0'
setup(
name = "obfsproxy",
author = "asn",
author_email = "asn@torproject.org",
description = ("A pluggable transport proxy written in Python"),
license = "BSD",
keywords = ['tor', 'obfuscation', 'twisted'],
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
packages = find_packages(),
entry_points = {
'console_scripts': [
'obfsproxy = obfsproxy.pyobfsproxy:run'
]
},
install_requires = [
'setuptools',
'PyCrypto',
'Twisted',
'argparse',
'pyptlib >= 0.0.5',
'gmpy'
],
)
|
Use correct path to config
|
<?php
namespace CedricZiel\L5Shariff;
use Illuminate\Support\ServiceProvider;
/**
* Class ShariffServiceProvider
* Registers the Heise Shariff components to your application.
*
* @package CedricZiel\L5Shariff
*/
class ShariffServiceProvider extends ServiceProvider
{
/**
* Registers routes and templates
*/
public function boot()
{
if (!$this->app->routesAreCached()) {
require __DIR__ . '/../routes.php';
}
$this->loadViewsFrom(__DIR__ . '/../resources/views', 'shariff');
$this->publishes([
__DIR__ . '/../resources/views' => resource_path('views/vendor/shariff'),
], 'views');
$this->publishes([
__DIR__ . '/../config/shariff.php' => config_path('shariff.php'),
], 'config');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__ . '/../config/shariff.php', 'shariff'
);
}
}
|
<?php
namespace CedricZiel\L5Shariff;
use Illuminate\Support\ServiceProvider;
/**
* Class ShariffServiceProvider
* Registers the Heise Shariff components to your application.
*
* @package CedricZiel\L5Shariff
*/
class ShariffServiceProvider extends ServiceProvider
{
/**
* Registers routes and templates
*/
public function boot()
{
if (!$this->app->routesAreCached()) {
require __DIR__ . '/../routes.php';
}
$this->loadViewsFrom(__DIR__ . '/../resources/views', 'shariff');
$this->publishes([
__DIR__ . '/../resources/views' => resource_path('views/vendor/shariff'),
], 'views');
$this->publishes([
__DIR__ . '/../config/shariff.php' => config_path('shariff.php'),
], 'config');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__ . '/path/to/config/courier.php', 'courier'
);
}
}
|
Use __dict__ instead of to_dict()
|
from pywatson.answer.answer import Answer
from pywatson.question.question import Question
import requests
class Watson(object):
"""The Watson API adapter class"""
def __init__(self, url, username, password):
self.url = url
self.username = username
self.password = password
def ask_question(self, question_text, question=None):
"""Ask Watson a question via the Question and Answer API
:param question_text: question to ask Watson
:type question_text: str
:param question: if question_text is not provided, a Question object
representing the question to ask Watson
:type question: Question
:return: Answer
"""
if question is not None:
q = question.__dict__
else:
q = Question(question_text).__dict__
r = requests.post(self.url + '/question', json=q)
return Answer(r.json())
|
from pywatson.answer.answer import Answer
from pywatson.question.question import Question
import requests
class Watson:
"""The Watson API adapter class"""
def __init__(self, url, username, password):
self.url = url
self.username = username
self.password = password
def ask_question(self, question_text, question=None):
"""Ask Watson a question via the Question and Answer API
:param question_text: question to ask Watson
:type question_text: str
:param question: if question_text is not provided, a Question object
representing the question to ask Watson
:type question: Question
:return: Answer
"""
if question is not None:
q = question.to_dict()
else:
q = Question(question_text).to_dict()
r = requests.post(self.url + '/question', json=q)
return Answer(r.json())
|
Add live-reload to watch task
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify: {
debug: {
files: {
'public/assets/js/app.debug.js': ['app/ui/static/js/app.js']
},
options: {
bundleOptions: {
debug: true
}
}
},
app: {
files: {
'public/assets/js/app.js': ['app/ui/static/js/app.js']
}
}
},
uglify : {
js: {
files: {
'public/assets/js/app.min.js' : [ 'public/assets/js/app.js' ]
}
}
},
watch: {
files: [ "**/static/**/*.js*"],
tasks: [ 'default' ],
options: {
livereload: true,
}
}
});
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', [ 'browserify', 'uglify:js' ]);
}
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify: {
debug: {
files: {
'public/assets/js/app.debug.js': ['app/ui/static/js/app.js']
},
options: {
bundleOptions: {
debug: true
}
}
},
app: {
files: {
'public/assets/js/app.js': ['app/ui/static/js/app.js']
}
}
},
uglify : {
js: {
files: {
'public/assets/js/app.min.js' : [ 'public/assets/js/app.js' ]
}
}
},
watch: {
files: [ "**/static/**/*.js*"],
tasks: [ 'default' ]
}
});
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', [ 'browserify', 'uglify:js' ]);
}
|
Fix memoized docker image pull
|
import execa from 'execa'
import promiseMemoize from 'p-memoize'
import debugLog from '../../../debugLog.js'
export default class DockerImage {
constructor(imageNameTag) {
this._imageNameTag = imageNameTag
}
static async _pullImage(imageNameTag) {
debugLog(`Downloading base Docker image... (${imageNameTag})`)
try {
await execa('docker', [
'pull',
'--disable-content-trust=false',
imageNameTag,
])
} catch (err) {
console.error(err.stderr)
throw err
}
}
async pull() {
return DockerImage._memoizedPull(this._imageNameTag)
}
}
DockerImage._memoizedPull = promiseMemoize(DockerImage._pullImage)
|
import execa from 'execa'
import promiseMemoize from 'p-memoize'
import debugLog from '../../../debugLog.js'
export default class DockerImage {
constructor(imageNameTag) {
this._imageNameTag = imageNameTag
}
static async _pullImage(imageNameTag) {
debugLog(`Downloading base Docker image... (${imageNameTag})`)
try {
await execa('docker', [
'pull',
'--disable-content-trust=false',
imageNameTag,
])
} catch (err) {
console.error(err.stderr)
throw err
}
}
async pull() {
const memoizedPull = promiseMemoize(DockerImage._pullImage)
return memoizedPull(this._imageNameTag)
}
}
|
Fix Device model, not needed to set last_seen on creation
|
import json
from django.db import models
import requests
from Suchary.settings import GCM_API_KEY
class Device(models.Model):
registration_id = models.TextField()
android_id = models.TextField(unique=True)
alias = models.TextField(blank=True)
version = models.CharField(max_length=20)
model = models.CharField(max_length=60)
os_version = models.CharField(max_length=20)
type = models.CharField(max_length=20)
active = models.BooleanField(default=True)
last_used = models.DateTimeField(auto_now=True)
last_seen = models.DateTimeField(auto_now_add=True)
created = models.DateTimeField(auto_now_add=True)
def send_data(self, data):
url = 'https://android.googleapis.com/gcm/send'
header = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
payload = {'registration_ids': [self.registration_id], 'data': data}
r = requests.post(url, data=json.dumps(payload), headers=header)
return r
def __str__(self):
if self.alias:
return str(self.alias)
return str(self.registration_id)
|
import json
from django.db import models
import requests
from Suchary.settings import GCM_API_KEY
class Device(models.Model):
registration_id = models.TextField()
android_id = models.TextField(unique=True)
alias = models.TextField(blank=True)
version = models.CharField(max_length=20)
model = models.CharField(max_length=60)
os_version = models.CharField(max_length=20)
type = models.CharField(max_length=20)
active = models.BooleanField(default=True)
last_used = models.DateTimeField(auto_now=True)
last_seen = models.DateTimeField()
created = models.DateTimeField(auto_now_add=True)
def send_data(self, data):
url = 'https://android.googleapis.com/gcm/send'
header = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'}
payload = {'registration_ids': [self.registration_id], 'data': data}
r = requests.post(url, data=json.dumps(payload), headers=header)
return r
def __str__(self):
if self.alias:
return str(self.alias)
return str(self.registration_id)
|
Add SES_REGION to local environment file
The region used by SES was hardcoded into the config file, when all other values were set as environment variables. Tweaked to keep the region consistent with other config options
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, SparkPost and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => env('SES_REGION','us-east-1'),
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
];
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Stripe, Mailgun, SparkPost and others. This file provides a sane
| default location for this type of information, allowing packages
| to have a conventional place to find your various credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('SES_KEY'),
'secret' => env('SES_SECRET'),
'region' => 'us-east-1',
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
];
|
Install initscript link into /etc/init.d. Allows for system integration while the original file can still be modified
|
import os
from fabric.api import put, task, sudo
from fablib import authbind, requires_root
from fablib.twisted import service
@task
@requires_root
def install():
# TODO:
# - Setup zone files (incl. PYTHONPATH in script if needed)
# - Rename dns to t-names or whatever (locations, scripts,...)
# Bootstrap a new service environment
service.bootstrap('dns')
# Setup authbind
authbind.install()
authbind.allow('dns', 53)
initscript = os.path.join(os.path.dirname(__file__), 'initscript.sh')
put(initscript, '/srv/dns/etc/init.d/dns', use_sudo=True, mode=0755)
sudo('ln -fs /srv/dns/etc/init.d/dns /etc/init.d/dns')
sudo('update-rc.d dns defaults')
@task
def update():
# TODO
pass
@task
def start():
service.start('dns')
@task
def stop():
service.stop('dns')
@task
def restart():
service.restart('dns')
|
import os
from fabric.api import put, task
from fablib import authbind, requires_root
from fablib.twisted import service
@task
@requires_root
def install():
# TODO:
# - Setup zone files (incl. PYTHONPATH in script if needed)
# - Rename dns to t-names or whatever (locations, scripts,...)
# Bootstrap a new service environment
service.bootstrap('dns')
# Setup authbind
authbind.install()
authbind.allow('dns', 53)
initscript = os.path.join(os.path.dirname(__file__), 'initscript.sh')
put(initscript, '/srv/dns/etc/init.d/dns', use_sudo=True, mode=0755)
@task
def update():
# TODO
pass
@task
def start():
service.start('dns')
@task
def stop():
service.stop('dns')
@task
def restart():
service.restart('dns')
|
Fix migration for running PostgreSQL.
|
'use strict';
const Schema = use('Schema');
class BlogPostSchema extends Schema {
up () {
this.create('blog_posts', (table) => {
table.increments();
table.integer('category_id').references('id').inTable('blog_categories');
table.integer('user_id').references('id').inTable('users');
table.string('slug', 80).notNullable().unique();
table.string('title', 150).notNullable();
table.string('summary', 250).notNullable();
table.string('markdown').notNullable();
table.string('html').notNullable();
table.integer('likes').defaultTo(0);
table.integer('comments').defaultTo(0);
table.timestamps();
});
}
down () {
this.dropIfExists('blog_posts');
}
}
module.exports = BlogPostSchema;
|
'use strict';
const Schema = use('Schema');
class BlogPostSchema extends Schema {
up () {
this.create('blog_posts', (table) => {
table.increments();
table.integer('category_id').unsigned().references('id').inTable('blog_categories');
table.integer('user_id').unsigned().references('id').inTable('users');
table.string('slug', 80).notNullable().unique();
table.string('title', 150).notNullable();
table.string('summary', 250).notNullable();
table.string('markdown').notNullable();
table.string('html').notNullable();
table.integer('likes').defaultTo(0);
table.integer('comments').defaultTo(0);
table.timestamps();
});
}
down () {
this.dropIfExists('blog_posts');
}
}
module.exports = BlogPostSchema;
|
Edit inline nodes which goes one after another.
|
import Command from './Command'
class EditInlineNodeCommand extends Command {
constructor(...args) {
super(...args)
if (!this.config.nodeType) {
throw new Error('Every AnnotationCommand must have a nodeType')
}
}
getCommandState(params) {
let sel = params.selection
let newState = {
disabled: true,
active: false
}
let annos = this._getAnnotationsForSelection(params)
if (annos.length > 0 && annos[0].getSelection().equals(sel)) {
newState.disabled = false
newState.nodeId = annos[0].id
}
return newState
}
execute(params) { // eslint-disable-line
}
_getAnnotationsForSelection(params) {
return params.selectionState.getAnnotationsForType(this.config.nodeType)
}
}
export default EditInlineNodeCommand
|
import Command from './Command'
class EditInlineNodeCommand extends Command {
constructor(...args) {
super(...args)
if (!this.config.nodeType) {
throw new Error('Every AnnotationCommand must have a nodeType')
}
}
getCommandState(params) {
let sel = params.selection
let newState = {
disabled: true,
active: false
}
let annos = this._getAnnotationsForSelection(params)
if (annos.length === 1 && annos[0].getSelection().equals(sel)) {
newState.disabled = false
newState.nodeId = annos[0].id
}
return newState
}
execute(params) { // eslint-disable-line
}
_getAnnotationsForSelection(params) {
return params.selectionState.getAnnotationsForType(this.config.nodeType)
}
}
export default EditInlineNodeCommand
|
Exclude more characters at the end of a link.
|
import re
urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.)]")
def URLToTag(message):
"""
searches for an URL in message and sets an <a>-tag arround
it, then returns the new string
"""
lastEnd = 0
while True:
match = urlExp.search(message, lastEnd)
if not match:
break
mStart = match.start()
mEnd = match.end()
lastEnd = mStart
url = message[mStart:mEnd]
tagStart="<a href='%s'>" % url
tagEnd = "</a>"
msgStart = message[0:mStart]
msgEnd = message[mEnd:]
newUrl = tagStart + url + tagEnd
message = msgStart + newUrl + msgEnd
lastEnd += len(tagStart)+len(tagEnd)+len(url)
return message
|
import re
urlExp = re.compile("(\w+)://[^ \t\"'<>]+[^ \t\"'<>,.]")
def URLToTag(message):
"""
searches for an URL in message and sets an <a>-tag arround
it, then returns the new string
"""
lastEnd = 0
while True:
match = urlExp.search(message, lastEnd)
if not match:
break
mStart = match.start()
mEnd = match.end()
lastEnd = mStart
url = message[mStart:mEnd]
tagStart="<a href='%s'>" % url
tagEnd = "</a>"
msgStart = message[0:mStart]
msgEnd = message[mEnd:]
newUrl = tagStart + url + tagEnd
message = msgStart + newUrl + msgEnd
lastEnd += len(tagStart)+len(tagEnd)+len(url)
return message
|
Disable debug and trace log when run tests.
|
<?php
require_once __DIR__ . "/config.php";
require_once __DIR__ . "/toolkit/RandStr.php";
require_once __DIR__ . "/toolkit/TcpStat.php";
require_once __DIR__ . "/toolkit/functions.php";
ini_set("assert.active", 1);
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 1);
assert_options(ASSERT_BAIL, 0);
assert_options(ASSERT_QUIET_EVAL, 0);
ini_set("memory_limit", "1024M");
ini_set("swoole.aio_mode", SWOOLE_AIO_BASE); // SWOOLE_AIO_BASE, SWOOLE_AIO_LINUX
swoole_async_set([
"socket_dontwait" => 1,
"aio_mode" => SWOOLE_AIO_BASE,
"thread_num" => 1,
'disable_dns_cache' => true,
'dns_lookup_random' => true,
]);
if (method_exists('co','set'))
{
Co::set([
'log_level' => SWOOLE_LOG_INFO,
'trace_flags' => 0
]);
}
|
<?php
require_once __DIR__ . "/config.php";
require_once __DIR__ . "/toolkit/RandStr.php";
require_once __DIR__ . "/toolkit/TcpStat.php";
require_once __DIR__ . "/toolkit/functions.php";
ini_set("assert.active", 1);
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 1);
assert_options(ASSERT_BAIL, 0);
assert_options(ASSERT_QUIET_EVAL, 0);
ini_set("memory_limit", "1024M");
ini_set("swoole.aio_mode", SWOOLE_AIO_BASE); // SWOOLE_AIO_BASE, SWOOLE_AIO_LINUX
swoole_async_set([
"socket_dontwait" => 1,
"aio_mode" => SWOOLE_AIO_BASE,
"thread_num" => 1,
'disable_dns_cache' => true,
'dns_lookup_random' => true,
]);
|
Add timestamp to wikipedia queries
|
/**
* Created by codaphillips on 4/18/15.
*/
(function() {
angular.module('wikiMiner.services.query_api', ['ngResource'])
.factory('query_api', ['$resource', function($resource){
return $resource('http://104.236.226.8/w/api.php', {
action:'query',
prop:'revisions',
format:'json',
rvprop:'user|ids|comment|timestamp',
rvlimit:'100',
titles:'@titles'
},{
get:{method:'GET'}
});
}]);
})();
|
/**
* Created by codaphillips on 4/18/15.
*/
(function() {
angular.module('wikiMiner.services.query_api', ['ngResource'])
.factory('query_api', ['$resource', function($resource){
return $resource('http://104.236.226.8/w/api.php', {
action:'query',
prop:'revisions',
format:'json',
rvprop:'user|ids|comment',
rvlimit:'100',
titles:'@titles'
},{
get:{method:'GET'}
});
}]);
})();
|
Add documentation and tidy up a bit
git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/branches/rel-2-1@349151 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: 27e9d82281f1ffccef29acba25b279d8ebca551c
|
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.util;
/**
* @version $Revision$
*/
public final class StringUtilities {
/**
* Private constructor to prevent instantiation.
*/
private StringUtilities() {
}
/**
* Replace all patterns in a String
*
* @see String.replaceAll(regex,replacement) - JDK1.4 only
*
* @param input - string to be transformed
* @param pattern - pattern to replace
* @param sub - replacement
* @return the updated string
*/
public static String substitute(final String input, final String pattern, final String sub) {
StringBuffer ret = new StringBuffer(input.length());
int start = 0;
int index = -1;
final int length = pattern.length();
while ((index = input.indexOf(pattern, start)) >= start) {
ret.append(input.substring(start, index));
ret.append(sub);
start = index + length;
}
ret.append(input.substring(start));
return ret.toString();
}
}
|
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.util;
/**
* @version $Revision$
*/
public final class StringUtilities {
public static String substitute(String input, String pattern, String sub) {
StringBuffer ret = new StringBuffer();
int start = 0;
int index = -1;
while ((index = input.indexOf(pattern, start)) >= start) {
ret.append(input.substring(start, index));
ret.append(sub);
start = index + pattern.length();
}
ret.append(input.substring(start));
return ret.toString();
}
/**
* Private constructor to prevent instantiation.
*/
private StringUtilities() {
}
}
|
Update ``maps`` to use the ``json_response`` function.
|
from django.template.response import TemplateResponse
from us_ignite.common.response import json_response
from us_ignite.maps.models import Location
def location_list(request):
"""Shows a list of locations in a map."""
object_list = Location.published.select_related('category').all()
context = {
'object_list': object_list,
}
return TemplateResponse(request, 'maps/object_list.html', context)
def _get_content(name, website):
if not website:
return name
return u'<div><h2><a href="%s">%s</a></h2></div>' % (website, name)
def _get_location_data(location):
return {
'latitude': location.position.latitude,
'longitude': location.position.longitude,
'name': location.name,
'website': location.website,
'category': location.category.name,
'image': location.get_image_url(),
'content': _get_content(location.name, location.website),
}
def location_list_json(request):
"""Returns the locations in JSON format"""
object_list = Location.published.select_related('category').all()
dict_list = [_get_location_data(l) for l in object_list]
return json_response(dict_list, callback='map.render')
|
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.template.response import TemplateResponse
from us_ignite.maps.models import Location
def location_list(request):
"""Shows a list of locations in a map."""
object_list = Location.published.select_related('category').all()
context = {
'object_list': object_list,
}
return TemplateResponse(request, 'maps/object_list.html', context)
def _get_content(name, website):
if not website:
return name
return u'<div><h2><a href="%s">%s</a></h2></div>' % (website, name)
def _get_location_data(location):
return {
'latitude': location.position.latitude,
'longitude': location.position.longitude,
'name': location.name,
'website': location.website,
'category': location.category.name,
'image': location.get_image_url(),
'content': _get_content(location.name, location.website),
}
def location_list_json(request):
"""Returns the locations in JSON format"""
object_list = Location.published.select_related('category').all()
dict_list = [_get_location_data(l) for l in object_list]
response = 'map.render(%s)' % json.dumps(dict_list, cls=DjangoJSONEncoder)
return HttpResponse(response, content_type='application/javascript')
|
Remove assumption that spaces are always valid separators
|
var _ = require('lodash');
var tokenSeparator = '■';
exports.tokenSeparator = tokenSeparator;
exports.removeStopwords = function(text, options) {
var defaults = {
'stopwords': require('./stopwords_en.js').words,
'inputSeparator': /[\\., ]+/,
'outputSeparator': ' '
}
options = _.defaults(options || {}, defaults);
var tokens = text.split(options.inputSeparator);
tokens = _.compact(tokens.map(function(value) {
if (options.stopwords.indexOf(value.toLowerCase()) != -1) return '';
return value.toLowerCase();
}));
return tokens.join(tokenSeparator);
}
exports.getStopwords = function(lang) {
var defaultLang = 'en';
lang = lang || defaultLang;
try {
return require('./stopwords_' + lang + '.js').words;
}
catch(e) {
throw new Error('no list for ' + lang +
' getStopwords has lists for en, es, fa, fr, it, ja, nl, no, pl, pt, ru, zh');
}
}
|
var _ = require('lodash');
exports.removeStopwords = function(text, options) {
var defaults = {
'stopwords': require('./stopwords_en.js').words,
'inputSeparator': /[\\., ]+/,
'outputSeparator': ' '
}
options = _.defaults(options || {}, defaults);
var tokens = text.split(options.inputSeparator);
tokens = _.compact(tokens.map(function(value) {
if (options.stopwords.indexOf(value.toLowerCase()) != -1) return '';
return value.toLowerCase();
}));
return tokens.join(options.outputSeparator);
}
exports.getStopwords = function(lang) {
var defaultLang = 'en';
lang = lang || defaultLang;
try {
return require('./stopwords_' + lang + '.js').words;
}
catch(e) {
throw new Error('no list for ' + lang +
' getStopwords has lists for en, es, fa, fr, it, ja, nl, no, pl, pt, ru, zh');
}
}
|
Fix build event listener method name
|
<?php
/**
*
* @author h.woltersdorf
*/
namespace Fortuneglobe\IceHawk;
use Fortuneglobe\IceHawk\Exceptions\EventListenerMethodNotCallable;
use Fortuneglobe\IceHawk\Interfaces\ListensToIceHawkEvents;
use Fortuneglobe\IceHawk\Interfaces\ServesIceHawkEventData;
/**
* Class IceHawkEventListener
*
* @package Fortuneglobe\IceHawk
*/
abstract class IceHawkEventListener implements ListensToIceHawkEvents
{
/**
* @param ServesIceHawkEventData $event
*
* @return bool
*/
public function acceptsEvent( ServesIceHawkEventData $event )
{
return in_array( get_class( $event ), $this->getAcceptedEvents() );
}
/**
* @param ServesIceHawkEventData $event
*
* @throws EventListenerMethodNotCallable
*/
public function notify( ServesIceHawkEventData $event )
{
$namespaceComponents = explode( "\\", get_class( $event ) );
$methodName = sprintf( 'when%s', preg_replace( "#Event$#", '', end( $namespaceComponents ) ) );
if ( is_callable( [ $this, $methodName ] ) )
{
$this->{$methodName}( $event );
}
else
{
throw new EventListenerMethodNotCallable( $methodName );
}
}
}
|
<?php
/**
*
* @author h.woltersdorf
*/
namespace Fortuneglobe\IceHawk;
use Fortuneglobe\IceHawk\Exceptions\EventListenerMethodNotCallable;
use Fortuneglobe\IceHawk\Interfaces\ListensToIceHawkEvents;
use Fortuneglobe\IceHawk\Interfaces\ServesIceHawkEventData;
/**
* Class IceHawkEventListener
*
* @package Fortuneglobe\IceHawk
*/
abstract class IceHawkEventListener implements ListensToIceHawkEvents
{
/**
* @param ServesIceHawkEventData $event
*
* @return bool
*/
public function acceptsEvent( ServesIceHawkEventData $event )
{
return in_array( get_class( $event ), $this->getAcceptedEvents() );
}
/**
* @param ServesIceHawkEventData $event
*
* @throws EventListenerMethodNotCallable
*/
public function notify( ServesIceHawkEventData $event )
{
$methodName = sprintf( 'when', preg_replace( '#Event$#', '', get_class( $event ) ) );
if ( is_callable( [ $this, $methodName ] ) )
{
$this->{$methodName}( $event );
}
else
{
throw new EventListenerMethodNotCallable( $methodName );
}
}
}
|
Update test suite generator to import tests in source_test.
|
#! /usr/bin/env python
#
# test_suite.py
#
# Copyright (c) 2015-2016 Junpei Kawamoto
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
""" Test suite.
"""
from __future__ import absolute_import
import sys
import unittest
from . import downloader_test
from . import source_test
def suite():
""" Return a test suite.
"""
loader = unittest.TestLoader()
res = unittest.TestSuite()
res.addTest(loader.loadTestsFromModule(downloader_test))
res.addTest(loader.loadTestsFromModule(source_test))
return res
def main():
""" The main function.
Returns:
exit code.
"""
try:
res = unittest.TextTestRunner(verbosity=2).run(suite())
except KeyboardInterrupt:
return -1
else:
return 0 if res.wasSuccessful() else 1
if __name__ == "__main__":
sys.exit(main())
|
#! /usr/bin/env python
#
# test_suite.py
#
# Copyright (c) 2015-2016 Junpei Kawamoto
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
""" Test suite.
"""
from __future__ import absolute_import
import sys
import unittest
from . import downloader_test
def suite():
""" Return a test suite.
"""
loader = unittest.TestLoader()
res = unittest.TestSuite()
res.addTest(loader.loadTestsFromModule(downloader_test))
return res
def main():
""" The main function.
Returns:
exit code.
"""
try:
res = unittest.TextTestRunner(verbosity=2).run(suite())
except KeyboardInterrupt:
return -1
else:
return 0 if res.wasSuccessful() else 1
if __name__ == "__main__":
sys.exit(main())
|
Fix NPE when using keyboard
|
package openperipheral.addons.glasses;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import openperipheral.addons.OpenPeripheralAddons;
import openperipheral.addons.api.ITerminalItem;
import cpw.mods.fml.common.FMLCommonHandler;
public class ItemKeyboard extends Item {
public ItemKeyboard() {
setCreativeTab(OpenPeripheralAddons.tabOpenPeripheralAddons);
setMaxStackSize(1);
}
@Override
public void registerIcons(IIconRegister register) {
itemIcon = register.registerIcon("openperipheraladdons:keyboard");
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (world.isRemote) {
ItemStack helmet = TerminalUtils.getHeadSlot(player);
if (helmet != null) {
Item item = helmet.getItem();
if (item instanceof ITerminalItem) {
Long guid = ((ITerminalItem)item).getTerminalGuid(helmet);
if (guid != null) FMLCommonHandler.instance().showGuiScreen(new GuiCapture(guid));
}
}
}
return stack;
}
}
|
package openperipheral.addons.glasses;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import openperipheral.addons.OpenPeripheralAddons;
import openperipheral.addons.api.ITerminalItem;
import cpw.mods.fml.common.FMLCommonHandler;
public class ItemKeyboard extends Item {
public ItemKeyboard() {
setCreativeTab(OpenPeripheralAddons.tabOpenPeripheralAddons);
setMaxStackSize(1);
}
@Override
public void registerIcons(IIconRegister register) {
itemIcon = register.registerIcon("openperipheraladdons:keyboard");
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (world.isRemote) {
ItemStack helmet = TerminalUtils.getHeadSlot(player);
if (helmet != null) {
Item item = helmet.getItem();
if (item instanceof ITerminalItem) {
long guid = ((ITerminalItem)item).getTerminalGuid(helmet);
FMLCommonHandler.instance().showGuiScreen(new GuiCapture(guid));
}
}
}
return stack;
}
}
|
Add extra field to detail output
|
from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinManager
MANAGER = PinManager()
class Pin(BasicResource):
def __init__(self):
super(Pin, self).__init__()
self.fields = {
"num": fields.Integer,
"mode": fields.String,
"initial": fields.String,
"resistor": fields.String
}
class PinList(Pin):
def get(self):
return self.response(MANAGER.pins, 200)
class PinDetail(Pin):
def __init__(self):
super(PinDetail, self).__init__()
self.fields['value'] = fields.Integer
def get(self, pin_num):
output = MANAGER.read(pin_num)
if not output:
return {'message': 'Pin not found'}, 404
return self.response(output, 200)
def put(self, pin_num):
return {'pin': pin_num}
def patch(self, pin_num):
pass
|
from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinManager
MANAGER = PinManager()
class Pin(BasicResource):
def __init__(self):
super(Pin, self).__init__()
self.fields = {
"num": fields.Integer,
"mode": fields.String,
"initial": fields.String,
"resistor": fields.String
}
class PinList(Pin):
def get(self):
return self.response(MANAGER.pins, 200)
class PinDetail(Pin):
def get(self, pin_num):
output = MANAGER.read(pin_num)
if not output:
return {'message': 'Pin not found'}, 404
return self.response(output, 200)
def put(self, pin_num):
return {'pin': pin_num}
def patch(self, pin_num):
pass
|
Use the deferred register now for potions
|
package info.u_team.u_team_test.init;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.potion.RadiationPotion;
import net.minecraft.potion.Potion;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.*;
@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestPotions {
public static final DeferredRegister<Potion> POTIONS = DeferredRegister.create(ForgeRegistries.POTION_TYPES, TestMod.MODID);
public static final RegistryObject<Potion> RADIATION = POTIONS.register("radiation", () -> new RadiationPotion(1200, 0));
public static final RegistryObject<Potion> RADIATION_LONG = POTIONS.register("radiation", () -> new RadiationPotion(2400, 1));
public static final RegistryObject<Potion> RADIATION_EXTREME = POTIONS.register("radiation", () -> new RadiationPotion(1200, 2));
public static void register(IEventBus bus) {
POTIONS.register(bus);
}
}
|
package info.u_team.u_team_test.init;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.potion.RadiationPotion;
import net.minecraft.potion.Potion;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.*;
@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestPotions {
public static final DeferredRegister<Potion> POTIONS = DeferredRegister.create(ForgeRegistries.POTION_TYPES, TestMod.MODID);
public static final Potion RADIATION = new RadiationPotion("radiation", 1200, 0);
public static final Potion RADIATION_LONG = new RadiationPotion("radiation_long", 2400, 1);
public static final Potion RADIATION_EXTREME = new RadiationPotion("radiation_extreme", 1200, 2);
public static void register(IEventBus bus) {
POTIONS.register(bus);
}
}
|
Fix bug when deciding if file is supported.
|
package net.sourceforge.javydreamercsw.validation.manager.web.file;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
/**
*
* @author Javier A. Ortiz Bultron <javier.ortiz.78@gmail.com>
*/
public abstract class AbstractFileDisplay implements IFileDisplay {
@Override
public boolean supportFile(File f) {
return supportFile(f.getName());
}
@Override
public File loadFile(String name, byte[] bytes) throws IOException {
File result = new File(System.getProperty("java.io.tmpdir")
+ System.getProperty("file.separator") + name);
FileUtils.writeByteArrayToFile(result, bytes);
return result;
}
}
|
package net.sourceforge.javydreamercsw.validation.manager.web.file;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
/**
*
* @author Javier A. Ortiz Bultron <javier.ortiz.78@gmail.com>
*/
public abstract class AbstractFileDisplay implements IFileDisplay {
@Override
public boolean supportFile(File f) {
return f.isFile() && supportFile(f.getName());
}
@Override
public File loadFile(String name, byte[] bytes) throws IOException {
File result = new File(System.getProperty("java.io.tmpdir")
+ System.getProperty("file.separator") + name);
FileUtils.writeByteArrayToFile(result, bytes);
return result;
}
}
|
Add getSlotCapacity method in fluid slot
|
package info.u_team.u_team_core.container;
import info.u_team.u_team_core.api.fluid.IFluidHandlerModifiable;
import net.minecraftforge.fluids.FluidStack;
public class FluidSlot {
private final IFluidHandlerModifiable fluidHandler;
private final int index;
private final int x;
private final int y;
public FluidSlot(IFluidHandlerModifiable fluidHandler, int index, int x, int y) {
this.fluidHandler = fluidHandler;
this.index = index;
this.x = x;
this.y = y;
}
public boolean isFluidValid(FluidStack stack) {
if (stack.isEmpty()) {
return false;
}
return fluidHandler.isFluidValid(index, stack);
}
public FluidStack getStack() {
return fluidHandler.getFluidInTank(index);
}
public void putStack(FluidStack stack) {
fluidHandler.setFluidInTank(index, stack);
}
public int getSlotCapacity() {
return fluidHandler.getTankCapacity(index);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isEnabled() {
return true;
}
}
|
package info.u_team.u_team_core.container;
import info.u_team.u_team_core.api.fluid.IFluidHandlerModifiable;
import net.minecraftforge.fluids.FluidStack;
public class FluidSlot {
private final IFluidHandlerModifiable fluidHandler;
private final int index;
private final int x;
private final int y;
public FluidSlot(IFluidHandlerModifiable fluidHandler, int index, int x, int y) {
this.fluidHandler = fluidHandler;
this.index = index;
this.x = x;
this.y = y;
}
public boolean isFluidValid(FluidStack stack) {
if (stack.isEmpty()) {
return false;
}
return fluidHandler.isFluidValid(index, stack);
}
public FluidStack getStack() {
return fluidHandler.getFluidInTank(index);
}
public void putStack(FluidStack stack) {
fluidHandler.setFluidInTank(index, stack);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isEnabled() {
return true;
}
}
|
Fix initialization errors if MapbenderDataSourceBundle is not registered in kernel
|
<?php
namespace Mapbender\DigitizerBundle;
use Mapbender\CoreBundle\Component\MapbenderBundle;
use Mapbender\DataSourceBundle\MapbenderDataSourceBundle;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
/**
* Digitizer Bundle.
*
* @author Andriy Oblivantsev
* @author Stefan Winkelmann
*/
class MapbenderDigitizerBundle extends MapbenderBundle
{
/**
* @inheritdoc
*/
public function getElements()
{
return array(
'Mapbender\DigitizerBundle\Element\Digitizer'
);
}
public function build(ContainerBuilder $container)
{
// Ensure DataSourceBundle services exist (independent of kernel registration)
$dsBundle = new MapbenderDataSourceBundle();
$dsBundle->build($container);
$configLocator = new FileLocator(__DIR__ . '/Resources/config');
$loader = new XmlFileLoader($container, $configLocator);
$loader->load('services.xml');
}
}
|
<?php
namespace Mapbender\DigitizerBundle;
use Mapbender\CoreBundle\Component\MapbenderBundle;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
/**
* Digitizer Bundle.
*
* @author Andriy Oblivantsev
* @author Stefan Winkelmann
*/
class MapbenderDigitizerBundle extends MapbenderBundle
{
/**
* @inheritdoc
*/
public function getElements()
{
return array(
'Mapbender\DigitizerBundle\Element\Digitizer'
);
}
public function build(ContainerBuilder $container)
{
parent::build($container);
$configLocator = new FileLocator(__DIR__ . '/Resources/config');
$loader = new XmlFileLoader($container, $configLocator);
$loader->load('services.xml');
}
}
|
Use decimal value instead of octal one
|
package com.nilhcem.droidcontn.data.app.model;
import android.os.Build;
import android.os.Parcel;
import com.nilhcem.droidcontn.BuildConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import org.threeten.bp.LocalDate;
import java.util.Arrays;
import java.util.List;
import static com.google.common.truth.Truth.assertThat;
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
public class ScheduleDayTest {
@Test
public void should_restore_from_parcelable() {
// Given
LocalDate day = LocalDate.of(1985, 5, 15);
List<ScheduleSlot> slots = Arrays.asList(new ScheduleSlot(null, null));
ScheduleDay scheduleDay = new ScheduleDay(day, slots);
// When
Parcel parcel = Parcel.obtain();
scheduleDay.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
ScheduleDay fromParcel = ScheduleDay.CREATOR.createFromParcel(parcel);
// Then
assertThat(fromParcel.getDay()).isEqualTo(day);
assertThat(fromParcel.getSlots()).hasSize(1);
}
}
|
package com.nilhcem.droidcontn.data.app.model;
import android.os.Build;
import android.os.Parcel;
import com.nilhcem.droidcontn.BuildConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import org.threeten.bp.LocalDate;
import java.util.Arrays;
import java.util.List;
import static com.google.common.truth.Truth.assertThat;
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
public class ScheduleDayTest {
@Test
public void should_restore_from_parcelable() {
// Given
LocalDate day = LocalDate.of(1985, 05, 15);
List<ScheduleSlot> slots = Arrays.asList(new ScheduleSlot(null, null));
ScheduleDay scheduleDay = new ScheduleDay(day, slots);
// When
Parcel parcel = Parcel.obtain();
scheduleDay.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
ScheduleDay fromParcel = ScheduleDay.CREATOR.createFromParcel(parcel);
// Then
assertThat(fromParcel.getDay()).isEqualTo(day);
assertThat(fromParcel.getSlots()).hasSize(1);
}
}
|
Mark internal/technical tasks with an _
|
/* === PLUGINS === */
const gulp = require('gulp'),
rimraf = require('gulp-rimraf'),
webpack = require('webpack-stream'),
path = require('path'),
sequence = require('run-sequence');
/* === CONFIG === */
const src = 'src/**/*',
cfg = require('./webpack.config.js');
/* === TASKS === */
gulp.task('clean', function () {
return gulp.src(cfg.output.path, {read: false}).pipe(rimraf());
});
gulp.task('_webpack:offline', function(callback) {
cfg.entry['beverages-mock'] = path.join(__dirname, 'src/js/mock/fake-app-server');
callback();
});
gulp.task('_webpack:build', function () {
return gulp.src(src)
.pipe(webpack(cfg))
.pipe(gulp.dest(cfg.output.path));
});
gulp.task('_webpack:watch', ['_webpack:build'], function () {
return gulp.watch(src, ['_webpack:build']);
});
// Shortcut tasks
gulp.task('build', function (callback) {
sequence('clean', '_webpack:build', callback);
});
gulp.task('watch', ['_webpack:watch']);
gulp.task('watch-offline', ['_webpack:offline', '_webpack:watch']);
gulp.task('default', ['build']);
|
/* === PLUGINS === */
const gulp = require('gulp'),
rimraf = require('gulp-rimraf'),
webpack = require('webpack-stream'),
path = require('path'),
sequence = require('run-sequence');
/* === CONFIG === */
const src = 'src/**/*',
cfg = require('./webpack.config.js');
/* === TASKS === */
gulp.task('clean', function () {
return gulp.src(cfg.output.path, {read: false}).pipe(rimraf());
});
gulp.task('offline', function(callback) {
cfg.entry['beverages-mock'] = path.join(__dirname, 'src/js/mock/fake-app-server');
callback();
});
gulp.task('webpack:build', function () {
return gulp.src(src)
.pipe(webpack(cfg))
.pipe(gulp.dest(cfg.output.path));
});
gulp.task('webpack:watch', ['webpack:build'], function () {
return gulp.watch(src, ['webpack:build']);
});
// Shortcut tasks
gulp.task('build', function (callback) {
sequence('clean', 'webpack:build', callback);
});
gulp.task('watch', ['webpack:watch']);
gulp.task('watch-offline', ['offline', 'watch']);
gulp.task('default', ['build']);
|
MP3: Move files/tracklist count check to function
|
#!/usr/bin/python3
import ID3
import os
import sys
def read_tracklist():
tracklist = []
for line in sys.stdin:
tracklist.append(line)
return tracklist
def match_length(files, tracklist):
if len(files) != len(tracklist):
raise RuntimeError(
str(len(tracklist)) +
" file names were given but " +
str(len(files)) +
" files were found.")
tracklist = read_tracklist()
mp3_extension = ".mp3"
files_all = os.listdir('.')
files = []
for f in files_all:
# Prune directories
if not os.path.isfile(f):
continue
# Prune non-MP3 files
filename, extension = os.path.splitext(f)
if extension != mp3_extension:
continue
# Prune this file
f_temp = os.path.abspath(f)
if f_temp == os.path.abspath(__file__):
continue
files.append(f)
match_length(files, tracklist)
files.sort()
i = 0
for f in files:
os.rename(f, tracklist[i] + mp3_extension)
i += 1
|
#!/usr/bin/python3
import ID3
import os
import sys
def read_tracklist():
tracklist = []
for line in sys.stdin:
tracklist.append(line)
return tracklist
tracklist = read_tracklist()
mp3_extension = ".mp3"
files_all = os.listdir('.')
files = []
for f in files_all:
# Prune directories
if not os.path.isfile(f):
continue
# Prune non-MP3 files
filename, extension = os.path.splitext(f)
if extension != mp3_extension:
continue
# Prune this file
f_temp = os.path.abspath(f)
if f_temp == os.path.abspath(__file__):
continue
files.append(f)
if len(files) != len(tracklist):
raise RuntimeError(
str(len(tracklist)) +
" file names were given but " +
str(len(files)) +
" files were found.")
sys.exit()
files.sort()
i = 0
for f in files:
os.rename(f, tracklist[i] + mp3_extension)
i += 1
|
Switch to using export statements
|
export configureUrlQuery from './configureUrlQuery';
export * as Serialize, { encode, decode } from './serialize';
export {
replaceInUrlQuery,
replaceUrlQuery,
pushInUrlQuery,
pushUrlQuery,
} from './updateUrlQuery';
export UrlQueryParamTypes from './UrlQueryParamTypes';
export UrlUpdateTypes from './UrlUpdateTypes';
/** React */
export addUrlProps from './react/addUrlProps';
export RouterToUrlQuery from './react/RouterToUrlQuery';
/** Redux */
export {
replaceInUrlQueryFromAction,
replaceUrlQueryFromAction,
pushInUrlQueryFromAction,
pushUrlQueryFromAction,
} from './redux/updateUrlQueryFromAction';
export urlAction, {
urlReplaceAction,
urlPushAction,
urlReplaceInAction,
urlPushInAction,
} from './redux/urlAction';
export urlQueryMiddleware from './redux/urlQueryMiddleware';
export urlQueryReducer from './redux/urlQueryReducer';
/** Utils */
export subquery from './utils/subquery';
export subqueryOmit from './utils/subqueryOmit';
|
import configureUrlQuery from './configureUrlQuery';
import * as Serialize from './serialize';
import {
replaceInUrlQuery,
replaceUrlQuery,
pushInUrlQuery,
pushUrlQuery,
} from './updateUrlQuery';
import UrlQueryParamTypes from './UrlQueryParamTypes';
import UrlUpdateTypes from './UrlUpdateTypes';
/** React */
import addUrlProps from './react/addUrlProps';
import RouterToUrlQuery from './react/RouterToUrlQuery';
/** Redux */
import {
replaceInUrlQueryFromAction,
replaceUrlQueryFromAction,
pushInUrlQueryFromAction,
pushUrlQueryFromAction,
} from './redux/updateUrlQueryFromAction';
import urlAction, {
urlReplaceAction,
urlPushAction,
urlReplaceInAction,
urlPushInAction,
} from './redux/urlAction';
import urlQueryMiddleware from './redux/urlQueryMiddleware';
import urlQueryReducer from './redux/urlQueryReducer';
/** Utils */
import subquery from './utils/subquery';
import subqueryOmit from './utils/subqueryOmit';
// for convenience export these two directly
const decode = Serialize.decode;
const encode = Serialize.encode;
export {
configureUrlQuery,
Serialize,
decode,
encode,
pushInUrlQuery,
pushUrlQuery,
replaceInUrlQuery,
replaceUrlQuery,
UrlQueryParamTypes,
UrlUpdateTypes,
addUrlProps,
RouterToUrlQuery,
urlAction,
urlReplaceInAction,
urlReplaceAction,
urlPushInAction,
urlPushAction,
pushInUrlQueryFromAction,
pushUrlQueryFromAction,
replaceInUrlQueryFromAction,
replaceUrlQueryFromAction,
urlQueryMiddleware,
urlQueryReducer,
subquery,
subqueryOmit,
};
|
Use logging variable instead of hard coded string to set logging level.
|
#
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated 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 Pixelated. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
from twisted.python import log
def init(debug=False):
debug_enabled = debug or os.environ.get('DEBUG', False)
logging_level = logging.DEBUG if debug_enabled else logging.WARN
log_format = "%(asctime)s [%(name)s] %(levelname)s %(message)s"
date_format = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(level=logging_level,
format=log_format,
datefmt=date_format,
filemode='a')
observer = log.PythonLoggingObserver()
logging.getLogger('gnupg').setLevel(logging.WARN)
observer.start()
|
#
# Copyright (c) 2014 ThoughtWorks, Inc.
#
# Pixelated is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pixelated 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 Pixelated. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
from twisted.python import log
def init(debug=False):
debug_enabled = debug or os.environ.get('DEBUG', False)
logging_level = logging.DEBUG if debug_enabled else logging.WARN
log_format = "%(asctime)s [%(name)s] %(levelname)s %(message)s"
date_format = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(level=logging_level,
format=log_format,
datefmt=date_format,
filemode='a')
observer = log.PythonLoggingObserver()
logging.getLogger('gnupg').setLevel('WARN')
observer.start()
|
Test to see if commit works.
|
from django.conf.urls import url, patterns
from newswall.feeds import StoryFeed
from newswall import views
urlpatterns = patterns(
'',
url(r'^feed/$', StoryFeed()),
url(r'^$',
views.ArchiveIndexView.as_view(),
name='newswall_entry_archive'),
url(r'^(?P<year>\d{4})/$',
views.YearArchiveView.as_view(),
name='newswall_entry_archive_year'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/$',
views.MonthArchiveView.as_view(),
name='newswall_entry_archive_month'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$',
views.DayArchiveView.as_view(),
name='newswall_entry_archive_day'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',
views.DateDetailView.as_view(),
name='newswall_entry_detail'),
url(r'^source/(?P<slug>[-\w]+)/$',
views.SourceArchiveIndexView.as_view(),
name='newswall_source_detail'),
)
|
from django.conf.urls import url, patterns
from newswall.feeds import StoryFeed
from newswall import views
urlpatterns = patterns(
'',
url(r'^feed/$', StoryFeed()),
url(r'^$',
views.ArchiveIndexView.as_view(),
name='newswall_entry_archive'),
url(r'^(?P<year>\d{4})/$',
views.YearArchiveView.as_view(),
name='newswall_entry_archive_year'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/$',
views.MonthArchiveView.as_view(),
name='newswall_entry_archive_month'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$',
views.DayArchiveView.as_view(),
name='newswall_entry_archive_day'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',
views.DateDetailView.as_view(),
name='newswall_entry_detail'),
url(r'^source/(?P<slug>[-\w]+)/$',
views.SourceArchiveIndexView.as_view(),
name='newswall_source_detail'),
)
|
Make epochDays more legible by visualizing what it's divided by
|
import Day from './day';
const Calendar = ({ events }) => {
let id = 0;
let lastEpochDays = 0;
let daysEvents = [];
let allDays = [];
const MS_IN_DAY = 1000*60*60*24;
for (let event of events) {
event.start_time = new Date(event.start_time);
let epochDays = Math.floor(event.start_time.getTime() / MS_IN_DAY);
if (lastEpochDays == 0) {
daysEvents.push(event);
lastEpochDays = epochDays;
}
else if (epochDays > lastEpochDays) {
allDays.push(<Day events={daysEvents} key={id}/>);
daysEvents = [ event ];
lastEpochDays = epochDays;
}
else if (epochDays == lastEpochDays) {
daysEvents.push(event);
}
id++;
}
allDays.push(<Day events={daysEvents} key={id}/>);
return (
<div>
<h1>Calendar</h1>
{allDays}
</div>
);
};
export default Calendar;
|
import Day from './day';
const Calendar = ({ events }) => {
let id = 0;
let lastEpochDays = 0;
let daysEvents = [];
let allDays = [];
for (let event of events) {
event.start_time = new Date(event.start_time);
let epochDays = Math.floor(event.start_time.getTime() / 8.64e7);
if (lastEpochDays == 0) {
daysEvents.push(event);
lastEpochDays = epochDays;
}
else if (epochDays > lastEpochDays) {
allDays.push(<Day events={daysEvents} key={id}/>);
daysEvents = [ event ];
lastEpochDays = epochDays;
}
else if (epochDays == lastEpochDays) {
daysEvents.push(event);
}
id++;
}
allDays.push(<Day events={daysEvents} key={id}/>);
return (
<div>
<h1>Calendar</h1>
{allDays}
</div>
);
};
export default Calendar;
|
Use quotes for scope properties
|
goog.provide('app_scaleline_directive');
goog.require('app');
goog.require('ngeo_control_directive');
goog.require('ol.control.ScaleLine');
(function() {
var module = angular.module('app');
module.directive('appScaleline', [
/**
* @return {angular.Directive} The Directive Object Definition.
*/
function() {
return {
restrict: 'E',
scope: {
'map': '=appScalelineMap'
},
controller: function() {
this['createControl'] = function(target) {
return new ol.control.ScaleLine({
target: target
});
};
},
controllerAs: 'ctrl',
bindToController: true,
template: '<div ngeo-control="ctrl.createControl"' +
'ngeo-control-map="ctrl.map">'
};
}
]);
})();
|
goog.provide('app_scaleline_directive');
goog.require('app');
goog.require('ngeo_control_directive');
goog.require('ol.control.ScaleLine');
(function() {
var module = angular.module('app');
module.directive('appScaleline', [
/**
* @return {angular.Directive} The Directive Object Definition.
*/
function() {
return {
restrict: 'E',
scope: {
map: '=appScalelineMap'
},
controller: function() {
this['createControl'] = function(target) {
return new ol.control.ScaleLine({
target: target
});
};
},
controllerAs: 'ctrl',
bindToController: true,
template: '<div ngeo-control="ctrl.createControl"' +
'ngeo-control-map="ctrl.map">'
};
}
]);
})();
|
Fix issue with spaces in paths
|
<?php
define('CLEANHOME', '/opt/clean');
if (!isset($_REQUEST['lib'])) :
echo '<p>Add ?lib and ?mod.</p>';
elseif (!isset($_REQUEST['mod'])) :
echo '<p>Select a module on the left.</p>';
else :
$lib = preg_replace('/[^\\w\\/\\-]/', '', $_REQUEST['lib']);
$mod = preg_replace('/[^\\w\\/\\. ]/', '', $_REQUEST['mod']);
$mod = str_replace('.', '/', $mod);
$iclordcl = isset($_REQUEST['icl']) ? 'icl' : 'dcl';
$hl_lines = isset($_REQUEST['line']) ? escapeshellarg($_REQUEST['line']) : '';
$fname = CLEANHOME . '/lib/' . $lib . '/' . $mod . '.' . $iclordcl;
$efname = escapeshellarg($fname);
system("python3 cloogle_pygments.py $efname $hl_lines");
endif;
|
<?php
define('CLEANHOME', '/opt/clean');
if (!isset($_REQUEST['lib'])) :
echo '<p>Add ?lib and ?mod.</p>';
elseif (!isset($_REQUEST['mod'])) :
echo '<p>Select a module on the left.</p>';
else :
$lib = preg_replace('/[^\\w\\/\\-]/', '', $_REQUEST['lib']);
$mod = preg_replace('/[^\\w\\/\\.]/', '', $_REQUEST['mod']);
$mod = str_replace('.', '/', $mod);
$iclordcl = isset($_REQUEST['icl']) ? 'icl' : 'dcl';
$hl_lines = isset($_REQUEST['line']) ? escapeshellarg($_REQUEST['line']) : '';
$fname = CLEANHOME . '/lib/' . $lib . '/' . $mod . '.' . $iclordcl;
$efname = escapeshellarg($fname);
system("python3 cloogle_pygments.py $efname $hl_lines");
endif;
|
Refactor League scheduler to use LeagueService
|
package com.elorating.scheduler;
import com.elorating.model.League;
import com.elorating.repository.LeagueRepository;
import com.elorating.repository.MatchRepository;
import com.elorating.repository.PlayerRepository;
import com.elorating.service.GenericService;
import com.elorating.service.LeagueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class LeagueScheduler {
@Autowired
private MatchRepository matchRepository;
@Autowired
private PlayerRepository playerRepository;
@Autowired
private GenericService<League> leagueService;
@Scheduled(cron = "0 5 23 * * *")
public void removeUnassignedLeagues() {
List<League> leaguesToRemove = ((LeagueService) leagueService).findUnassignedLeagues();
for (League league : leaguesToRemove) {
String leagueId = league.getId();
matchRepository.deleteByLeagueId(leagueId);
playerRepository.deleteByLeagueId(leagueId);
leagueService.deleteById(leagueId);
}
}
}
|
package com.elorating.scheduler;
import com.elorating.model.League;
import com.elorating.repository.LeagueRepository;
import com.elorating.repository.MatchRepository;
import com.elorating.repository.PlayerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class LeagueScheduler {
@Autowired
private MatchRepository matchRepository;
@Autowired
private PlayerRepository playerRepository;
@Autowired
private LeagueRepository leagueRepository;
@Scheduled(cron = "0 5 23 * * *")
public void removeUnassignedLeagues() {
List<League> leaguesToRemove = leagueRepository.findByUsersNull();
for (League league : leaguesToRemove) {
String leagueId = league.getId();
matchRepository.deleteByLeagueId(leagueId);
playerRepository.deleteByLeagueId(leagueId);
leagueRepository.delete(leagueId);
}
}
}
|
Fix path to meteor app for PHM deploy
|
var secret = require('./mup-secrets.json');
module.exports = {
servers: {
one: {
host: '167.71.2.39',
username: 'deploy',
password: secret.password,
}
},
app: {
name: 'publichappinessmovement',
path: '../../.',
docker: {
image: 'abernix/meteord:node-8.4.0-base'
},
servers: {
one: {}
},
buildOptions: {
serverOnly: true
},
env: {
ROOT_URL: 'https://fl-maps.publichappinessmovement.com',
MONGO_URL: secret.mongo_url,
PORT: 8095,
}
},
};
|
var secret = require('./mup-secrets.json');
module.exports = {
servers: {
one: {
host: '167.71.2.39',
username: 'deploy',
password: secret.password,
}
},
app: {
name: 'publichappinessmovement',
path: './',
docker: {
image: 'abernix/meteord:node-8.4.0-base'
},
servers: {
one: {}
},
buildOptions: {
serverOnly: true
},
env: {
ROOT_URL: 'https://fl-maps.publichappinessmovement.com',
MONGO_URL: secret.mongo_url,
PORT: 8095,
}
},
};
|
Move short line names to object
|
const {getNativeInteger} = require("./helpers");
const ABBREVIATED_ROUTE_NAMES = {
Brn: "Brown",
G: "Green",
Org: "Orange",
P: "Purple",
Y: "Yellow",
};
class Route {
constructor(attributes) {
this.attributes = attributes;
}
route() {
return ABBREVIATED_ROUTE_NAMES[this.attributes.rt] || this.attributes.rt;
}
directionId() {
return getNativeInteger(this.attributes.trDr);
}
runNumber() {
return getNativeInteger(this.attributes.rn);
}
routeClass() {
return this.route().toLowerCase();
}
routeId() {
return this.attributes.rt;
}
toJSON() {
return {
class: this.routeClass(),
directionId: this.directionId(),
id: this.routeId(),
name: this.route(),
run: this.runNumber(),
};
}
}
module.exports = Route;
|
const {getNativeInteger} = require("./helpers");
class Route {
constructor(attributes) {
this.attributes = attributes;
}
route() {
var route;
switch ((route = this.routeId())) {
case "Brn":
return "Brown";
case "G":
return "Green";
case "Org":
return "Orange";
case "P":
return "Purple";
case "Y":
return "Yellow";
default:
return route;
}
}
directionId() {
return getNativeInteger(this.attributes.trDr);
}
runNumber() {
return getNativeInteger(this.attributes.rn);
}
routeClass() {
return this.route().toLowerCase();
}
routeId() {
return this.attributes.rt;
}
toJSON() {
return {
class: this.routeClass(),
directionId: this.directionId(),
id: this.routeId(),
name: this.route(),
run: this.runNumber(),
};
}
}
module.exports = Route;
|
Test the short version of "integer": "int"
|
<?php
/*
* Copyright 2016 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace JMS\Serializer\Tests\Fixtures;
use JMS\Serializer\Annotation\XmlAttribute;
use JMS\Serializer\Annotation\XmlValue;
use JMS\Serializer\Annotation\XmlRoot;
use JMS\Serializer\Annotation\XmlElement;
use JMS\Serializer\Annotation\Type;
/**
* @XmlRoot("child")
*/
class Person
{
/**
* @Type("string")
* @XmlValue(cdata=false)
*/
public $name;
/**
* @Type("int")
* @XmlAttribute
*/
public $age;
}
|
<?php
/*
* Copyright 2016 Johannes M. Schmitt <schmittjoh@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace JMS\Serializer\Tests\Fixtures;
use JMS\Serializer\Annotation\XmlAttribute;
use JMS\Serializer\Annotation\XmlValue;
use JMS\Serializer\Annotation\XmlRoot;
use JMS\Serializer\Annotation\XmlElement;
use JMS\Serializer\Annotation\Type;
/**
* @XmlRoot("child")
*/
class Person
{
/**
* @Type("string")
* @XmlValue(cdata=false)
*/
public $name;
/**
* @Type("integer")
* @XmlAttribute
*/
public $age;
}
|
Add missing events and locations to error handling
|
module.exports = function(app) {
app.use(function(err, _req, res, _next) { // eslint-disable-line no-unused-vars
/**
* Error messages may be split into a head and a body. The head part
* contains the descriptor for the error. The body part contains extra
* information for the API user.
*/
const errorMessageHead = err.message.split(':', 1)[0];
const statusCode = (function(errorMessage) {
switch (errorMessage) {
case 'Authentication failed':
return 401;
case 'Calendar item not found':
case 'Event not found':
case 'Location not found':
case 'User not found':
return 404;
case 'Bad path':
case 'Bad resource ID':
case 'Missing fields':
case 'Possibly too vague':
return 422;
case 'Database error':
return 500;
case 'Unsupported operation':
return 501;
default:
console.log(`undefined error: ${err}`);
return 500;
}
})(errorMessageHead);
res.status(statusCode);
res.json({error: err.message});
});
};
|
module.exports = function(app) {
app.use(function(err, _req, res, _next) { // eslint-disable-line no-unused-vars
/**
* Error messages may be split into a head and a body. The head part
* contains the descriptor for the error. The body part contains extra
* information for the API user.
*/
const errorMessageHead = err.message.split(':', 1)[0];
const statusCode = (function(errorMessage) {
switch (errorMessage) {
case 'Authentication failed':
return 401;
case 'Calendar item not found':
case 'User not found':
return 404;
case 'Bad path':
case 'Bad resource ID':
case 'Missing fields':
case 'Possibly too vague':
return 422;
case 'Database error':
return 500;
case 'Unsupported operation':
return 501;
default:
console.log(`undefined error: ${err}`);
return 500;
}
})(errorMessageHead);
res.status(statusCode);
res.json({error: err.message});
});
};
|
test: Use plan instead of manual count
|
var fs = require('../');
var rimraf = require('rimraf');
var mkdirp = require('mkdirp');
var test = require('tap').test;
var p = require('path').resolve(__dirname, 'files');
process.chdir(__dirname)
// Make sure to reserve the stderr fd
process.stderr.write('');
var num = 4097;
var paths = new Array(num);
test('make files', function (t) {
rimraf.sync(p);
mkdirp.sync(p);
for (var i = 0; i < num; ++i) {
paths[i] = 'files/file-' + i;
fs.writeFileSync(paths[i], 'content');
}
t.end();
})
test('read files', function (t) {
// now read them
t.plan(num)
for (var i = 0; i < num; ++i) {
fs.readFile(paths[i], 'ascii', function(err, data) {
if (err)
throw err;
t.equal(data, 'content')
});
}
});
test('cleanup', function (t) {
rimraf.sync(p);
t.end();
});
|
var fs = require('../');
var rimraf = require('rimraf');
var mkdirp = require('mkdirp');
var test = require('tap').test;
var p = require('path').resolve(__dirname, 'files');
process.chdir(__dirname)
// Make sure to reserve the stderr fd
process.stderr.write('');
var num = 4097;
var paths = new Array(num);
test('make files', function (t) {
rimraf.sync(p);
mkdirp.sync(p);
for (var i = 0; i < num; ++i) {
paths[i] = 'files/file-' + i;
fs.writeFileSync(paths[i], 'content');
}
t.end();
})
test('read files', function (t) {
// now read them
var done = 0;
for (var i = 0; i < num; ++i) {
fs.readFile(paths[i], function(err, data) {
if (err)
throw err;
++done;
if (done === num) {
t.pass('success');
t.end()
}
});
}
});
test('cleanup', function (t) {
rimraf.sync(p);
t.end();
});
|
Fix finalize for safari, firefox.
|
function makePostRequest(url, data) {
var jForm = $('<form></form>');
jForm.attr('action', url);
jForm.attr('method', 'post');
for (name in data) {
var jInput = $("<input/>");
jInput.attr({'name' : name, 'value': data[name], 'type': 'hidden'});
jForm.append(jInput);
}
var button = $("<input type='submit' style='display: none'/>");
jForm.append(button);
$("body").append(jForm);
button.trigger('click');
}
$(function(){
$("a[post=true]").each(function () {
$(this).on('click', function (e) {
e.preventDefault();
makePostRequest(
$(this).attr('phref'),
JSON.parse($(this).attr('pdata'))
);
});
});
});
|
function makePostRequest(url, data) {
console.log(url);
console.log(data);
var jForm = $('<form></form>');
jForm.attr('action', url);
jForm.attr('method', 'post');
for (name in data) {
var jInput = $("<input>");
jInput.attr('name', name);
jInput.attr('value', data[name]);
jForm.append(jInput);
}
//console.log(jForm);
jForm.submit();
}
$(function(){
$("a[post=true]").each(function () {
console.log('here');
$(this).on('click', function () {
makePostRequest(
$(this).attr('phref'),
JSON.parse($(this).attr('pdata'))
);
});
});
});
|
Increase to public visibility (better for use)
|
package net.aeten.core.spi.factory;
import java.util.concurrent.atomic.AtomicInteger;
import net.aeten.core.spi.SpiFactory;
public class ThreadFactory implements
SpiFactory <java.util.concurrent.ThreadFactory, String> {
private static final AtomicInteger threadCount = new AtomicInteger (0);
@Override
public java.util.concurrent.ThreadFactory create (String prefix) {
final String name = prefix + "-" + threadCount.incrementAndGet ();
return new java.util.concurrent.ThreadFactory () {
@Override
public Thread newThread (Runnable runnable) {
return new Thread (runnable, name);
}
};
}
@Override
public Class <?>[] getTypes () {
return new Class[] {
java.util.concurrent.ThreadFactory.class
};
}
@Override
public Class <String> getParameterType () {
return String.class;
}
}
|
package net.aeten.core.spi.factory;
import java.util.concurrent.atomic.AtomicInteger;
import net.aeten.core.spi.SpiFactory;
class ThreadFactory implements
SpiFactory <java.util.concurrent.ThreadFactory, String> {
private static final AtomicInteger threadCount = new AtomicInteger (0);
@Override
public java.util.concurrent.ThreadFactory create (String prefix) {
final String name = prefix + "-" + threadCount.incrementAndGet ();
return new java.util.concurrent.ThreadFactory () {
@Override
public Thread newThread (Runnable runnable) {
return new Thread (runnable, name);
}
};
}
@Override
public Class <?>[] getTypes () {
return new Class[] {
java.util.concurrent.ThreadFactory.class
};
}
@Override
public Class <String> getParameterType () {
return String.class;
}
}
|
Fix a rather embarrassing bug where HubMagic's pinging functionality would shut down after five minutes.
|
/**
* Copyright © 2014 tuxed <write@imaginarycode.com>
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
package com.imaginarycode.minecraft.hubmagic.bungee;
import com.imaginarycode.minecraft.hubmagic.HubMagic;
import com.imaginarycode.minecraft.hubmagic.selectors.ServerSelector;
import lombok.AllArgsConstructor;
import net.md_5.bungee.api.AbstractReconnectHandler;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
@AllArgsConstructor
public class HubMagicReconnectHandler extends AbstractReconnectHandler {
private final ServerSelector selector;
@Override
protected ServerInfo getStoredServer(ProxiedPlayer player) {
return selector.selectServer(player);
}
@Override
public final void setServer(ProxiedPlayer player) {
}
@Override
public final void save() {
}
@Override
public final void close() {
HubMagic.getPlugin().getPingManager().shutdown();
}
}
|
/**
* Copyright © 2014 tuxed <write@imaginarycode.com>
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License, Version 2,
* as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
package com.imaginarycode.minecraft.hubmagic.bungee;
import com.imaginarycode.minecraft.hubmagic.HubMagic;
import com.imaginarycode.minecraft.hubmagic.selectors.ServerSelector;
import lombok.AllArgsConstructor;
import net.md_5.bungee.api.AbstractReconnectHandler;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
@AllArgsConstructor
public class HubMagicReconnectHandler extends AbstractReconnectHandler {
private final ServerSelector selector;
@Override
protected ServerInfo getStoredServer(ProxiedPlayer player) {
return selector.selectServer(player);
}
@Override
public final void setServer(ProxiedPlayer player) {
}
@Override
public final void save() {
HubMagic.getPlugin().getPingManager().shutdown();
}
@Override
public final void close() {
}
}
|
Add user-agent field to html_fetcher
|
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import requests
def fetch_html_document(url, user_agent='python_requests.cli-ws'):
"""Fetch html from url and return html
:param str url: an address to a resource on the Internet
:opt param str user_agent: user agent that the request will be made with
:return no except hit: status code and html of page (if exists)
:rtype: tuple
:return except hit: error
:rtype: str
"""
try:
response = requests.get(url, headers={'User-Agent': user_agent})
if response.status_code == requests.codes.ok:
return response.status_code, response.text # html
else:
return response.status_code, response.text
except Exception as err:
return err
|
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import requests
def fetch_html_document(url):
"""Fetch html from url and return html
:param str url: an address to a resource on the Internet
:return no except hit: status code and html of page (if exists)
:rtype: tuple
:return except hit: error
:rtype: str
"""
try:
response = requests.get(url)
if response.status_code == requests.codes.ok:
return response.status_code, response.text # html
else:
return response.status_code, response.text
except Exception as err:
return err
|
Remove timestamps from role_user table
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('role_user');
}
}
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRoleUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role_user', function(Blueprint $table)
{
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('role_user');
}
}
|
Fix matomo generation to only happen in production
|
/* global MATOMO_SITE_ID, MATOMO_TRACKER_URL, MATOMO_ENABLE_LINK_TRACKING */
export default ({ router }) => {
// Google analytics integration
if (process.env.NODE_ENV === 'production' && typeof window !== 'undefined' && MATOMO_SITE_ID && MATOMO_TRACKER_URL) {
var _paq = _paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(['trackPageView']);
if (MATOMO_ENABLE_LINK_TRACKING) {
_paq.push(['enableLinkTracking']);
}
(function() {
var u=MATOMO_TRACKER_URL;
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', MATOMO_SITE_ID]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
router.afterEach(function (to) {
_paq.push(['trackPageView', to.fullPath]);
});
}
}
|
/* global MATOMO_SITE_ID, MATOMO_TRACKER_URL, MATOMO_ENABLE_LINK_TRACKING */
export default ({ router }) => {
// Google analytics integration
if (MATOMO_SITE_ID && MATOMO_TRACKER_URL) {
var _paq = _paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(['trackPageView']);
if (MATOMO_ENABLE_LINK_TRACKING) {
_paq.push(['enableLinkTracking']);
}
(function() {
var u=MATOMO_TRACKER_URL;
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', MATOMO_SITE_ID]);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
router.afterEach(function (to) {
_paq.push(['trackPageView', to.fullPath]);
});
}
}
|
Use the correct match function
|
'use strict';
var httpclient = require('../../http-client');
function messageListener(db, from, channel, message) {
var match = /(https?:\/\/[^ ]+)/.exec(message)
if (match) {
var res = httpclient(db, match[1]);
var match = /<title>(.+)<\/title>/.exec(res);
if (match) {
var decoded = match[1].replace(/&#\d+;/gm,function(s) {
return String.fromCharCode(s.match(/\d+/gm)[0]);
});
decoded = decoded.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, "\"")
.replace(/'/g, "'");
return [ { to: channel, message: decoded } ] ;
}
}
}
module.exports = messageListener;
|
'use strict';
var httpclient = require('../../http-client');
function messageListener(db, from, channel, message) {
var match = /(https?:\/\/[^ ]+)/.match(message)
if (match) {
var res = httpclient(db, match[1]);
var match = /<title>(.+)<\/title>/.exec(res);
if (match) {
var decoded = match[1].replace(/&#\d+;/gm,function(s) {
return String.fromCharCode(s.match(/\d+/gm)[0]);
});
decoded = decoded.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, "\"")
.replace(/'/g, "'");
return [ { to: channel, message: decoded } ] ;
}
}
}
module.exports = messageListener;
|
784: Change the column name to follow the standard naming convention.
|
const config = require('../../../knexfile').web
const knex = require('knex')(config)
module.exports = function (id, type) {
var table = "team_caseload_overview"
var whereObject = {}
if (id !== undefined) {
whereObject.id = id
}
return knex(table)
.where(whereObject)
.select('name',
'grade_code as gradeCode',
'untiered',
'd2',
'd1',
'c2',
'c1',
'b2',
'b1',
'a',
'total_cases as totalCases')
.then(function (results) {
return results
})
}
|
const config = require('../../../knexfile').web
const knex = require('knex')(config)
module.exports = function (id, type) {
var table = "team_caseload_overview"
var whereObject = {}
if (id !== undefined) {
whereObject.id = id
}
return knex(table)
.where(whereObject)
.select('name',
'gradeCode',
'untiered',
'd2',
'd1',
'c2',
'c1',
'b2',
'b1',
'a',
'totalCases')
.then(function (results) {
return results
})
}
|
Make sure exists filter values are sent to backend
|
'use strict';
var SearchService = function($http, $q) {
this.search = function(query) {
var deferred = $q.defer();
var from = query.from ? '&from=' + query.from : "";
var size = query.size ? '&size=' + query.size : "";
var facetlist = "&facet=resource.provenance&facet=resource.types";
// facet values in der Backend-URI: mit "resource."
var fq = query.fq;
if (fq == null) {
fq = "";
} else if (typeof fq === 'string') {
fq = "&fq=resource."+fq;
} else {
fq = "&fq=resource." + fq.join("&fq=resource.");
}
var exists = query.exists;
if (exists == null) {
exists = "";
} else if (typeof exists === 'string') {
exists = "&exists=resource."+exists;
} else {
exists = "&exists=resource." + exists.join("&exists=resource.");
}
var uri = '/data/period/?q=' + query.q + from + size + facetlist + fq + exists;
$http.get(uri).then(
function success(result) {
deferred.resolve(result.data);
},
function error(err) {
console.warn(err);
deferred.reject();
}
);
return deferred.promise;
}
}
angular.module('chronontology.services').service('searchService',
["$http", "$q", SearchService]);
|
'use strict';
var SearchService = function($http, $q) {
this.search = function(query) {
var deferred = $q.defer();
var from = query.from ? '&from=' + query.from : "";
var size = query.size ? '&size=' + query.size : "";
var facetlist = "&facet=resource.provenance&facet=resource.types";
// facet values in der Backend-URI: mit "resource."
var fq = query.fq;
if (fq == null) {
fq = "";
} else if (typeof fq === 'string') {
fq = "&fq=resource."+fq;
} else {
fq = "&fq=resource." + fq.join("&fq=resource.");
}
var uri = '/data/period/?q=' + query.q + from + size + facetlist + fq;
$http.get(uri).then(
function success(result) {
deferred.resolve(result.data);
},
function error(err) {
console.warn(err);
deferred.reject();
}
);
return deferred.promise;
}
}
angular.module('chronontology.services').service('searchService',
["$http", "$q", SearchService]);
|
Extend simple field from `SubscribableField`
|
/*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.base;
public final class SimpleField extends SubscribableField {
public SimpleField() {
this("temporarily empty");
}
public SimpleField(FieldPath value) {
super(value);
}
public SimpleField(String value) {
super(FieldPath.newBuilder().addFieldName(value).build());
}
}
|
/*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.base;
import io.spine.value.ValueHolder;
public final class SimpleField extends ValueHolder<FieldPath> {
private static final long serialVersionUID = 0L;
public SimpleField() {
this("temporarily empty");
}
public SimpleField(FieldPath value) {
super(value);
}
public SimpleField(String value) {
super(FieldPath.newBuilder().addFieldName(value).build());
}
}
|
Add env line to script
|
#! /usr/bin/env node
var fs = require('fs');
var formidable = require('formidable');
var git = require('./lib/git')(__dirname);
var http = require('http');
var hyperglue = require('hyperglue');
var _ = require('lodash');
var html = fs.readFileSync(__dirname + '/index.html');
var port = process.env.PORT || 8080;
function handlePost (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields) {
console.dir(fields);
res.writeHead(200);
res.end('git branch -D ' + fields.branches.join(' '));
});
}
function handleGet (req, res) {
git.branches(function (err, branches) {
var data = _.map(branches, function (b) {
return {
'.branch-id': { value: b },
'.branch-name': b
}
});
res.writeHead(200);
res.end(hyperglue(html, {
'.branch-item': data
}).outerHTML);
});
}
var server = http.createServer(function (req, res) {
if (req.method === 'POST') return handlePost(req, res);
handleGet(req, res);
});
server.listen(port);
console.log('Listening on ' + port);
|
var fs = require('fs');
var formidable = require('formidable');
var git = require('./lib/git')(__dirname);
var http = require('http');
var hyperglue = require('hyperglue');
var _ = require('lodash');
var html = fs.readFileSync(__dirname + '/index.html');
var port = process.env.PORT || 8080;
function handlePost (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields) {
console.dir(fields);
res.writeHead(200);
res.end('git branch -D ' + fields.branches.join(' '));
});
}
function handleGet (req, res) {
git.branches(function (err, branches) {
var data = _.map(branches, function (b) {
return {
'.branch-id': { value: b },
'.branch-name': b
}
});
res.writeHead(200);
res.end(hyperglue(html, {
'.branch-item': data
}).outerHTML);
});
}
var server = http.createServer(function (req, res) {
if (req.method === 'POST') return handlePost(req, res);
handleGet(req, res);
});
server.listen(port);
console.log('Listening on ' + port);
|
Refactor entry point to do setup
|
'use strict';
// Helper to avoid a lot of directory traversing
global.__base = __dirname + '/';
require('./libs/setup').then(() => {
// Load settings
const settings = require('./libs/settings');
// Run CLI and get arguments
const cli = require('./libs/cli'),
options = cli.start().input();
// Load required files
const task = require('./libs/task'),
queue = require('./libs/queue'),
logger = require('./libs/log');
// Load tasks from file
task.load(settings.directory + '/tasks.json').then((tasks) => {
// Extract jobs from tasks
let jobs = [];
tasks.forEach((t) => { t.jobs.forEach((j, i) => { jobs.push(j); }); });
// Add jobs into queue and convert
return queue.add({jobs: jobs});
// Conversion queue complete
}).then((complete) => {
logger.info('End of queue.');
process.exit(0);
// Catch any errors that bubble up
}).catch((err) => {
console.log(err);
process.exit(1);
});
}).catch((err) => {
console.log(err);
process.exit(1);
});
|
'use strict';
// Load settings
const settings = require('./libs/settings');
// Run CLI and get arguments
const cli = require('./libs/cli'),
options = cli.input();
// Load required files
const task = require('./libs/task'),
queue = require('./libs/queue'),
logger = require('./libs/log');
// Load tasks from file
task.load('./config/tasks.json').then((tasks) => {
// Extract jobs from tasks
let jobs = [];
tasks.forEach((t) => { t.jobs.forEach((j, i) => { jobs.push(j); }); });
// Add jobs into queue and convert
return queue.add({jobs: jobs});
// Conversion queue complete
}).then((complete) => {
logger.info('End of queue.');
process.exit(0);
// Catch any errors that bubble up
}).catch((err) => {
console.log(err);
process.exit(1);
});
|
Apply consistent code style as used in other tests.
|
<?php
namespace Tests\Feature;
use App\Actions\ValetSecure;
use App\Shell\Shell;
use Exception;
use Illuminate\Support\Facades\Config;
use Tests\Feature\Fakes\FakeProcess;
use Tests\TestCase;
class ValetSecureTest extends TestCase
{
private $shell;
public function setUp(): void
{
parent::setUp(); // TODO: Change the autogenerated stub
$this->shell = $this->mock(Shell::class);
}
/** @test */
function it_runs_valet_link()
{
Config::set('lambo.store.valet_secure', true);
$this->shell->shouldReceive('execInProject')
->with('valet secure')
->once()
->andReturn(FakeProcess::success());
app(ValetSecure::class)();
}
/** @test */
function it_throws_an_exception_if_the_after_script_fails()
{
Config::set('lambo.store.valet_secure', true);
$this->shell->shouldReceive('execInProject')
->with('valet secure')
->once()
->andReturn(FakeProcess::fail('valet secure'));
$this->expectException(Exception::class);
app(ValetSecure::class)();
}
}
|
<?php
namespace Tests\Feature;
use App\Actions\ValetSecure;
use App\Shell\Shell;
use Exception;
use Illuminate\Support\Facades\Config;
use Tests\Feature\Fakes\FakeProcess;
use Tests\TestCase;
class ValetSecureTest extends TestCase
{
/** @test */
function it_runs_valet_link()
{
$shell = $this->mock(Shell::class);
Config::set('lambo.store.valet_secure', true);
$shell->shouldReceive('execInProject')
->with('valet secure')
->once()
->andReturn(FakeProcess::success());
app(ValetSecure::class)();
}
/** @test */
function it_throws_an_exception_if_the_after_script_fails()
{
$shell = $this->mock(Shell::class);
Config::set('lambo.store.valet_secure', true);
$command = 'valet secure';
$shell->shouldReceive('execInProject')
->with($command)
->once()
->andReturn(FakeProcess::fail($command));
$this->expectException(Exception::class);
app(ValetSecure::class)();
}
}
|
Use path for fix webpack build
|
const path = require('path')
const webpack = require('webpack')
module.exports = {
context: __dirname,
debug: true,
cache: false,
process: true,
stats: {
colors: true
},
entry: {
'scrollto-with-animation': path.join(__dirname, 'src')
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].min.js'
},
plugins: [
new webpack.SourceMapDevToolPlugin({
filename: '[name].js.map'
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compressor: {
screw_ie8: true,
warnings: false
},
output: {
comments: false
}
})
],
module: {
loaders: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
cacheDirectory: true,
presets: ['es2015', 'stage-2']
}
}]
}
}
|
const path = require('path')
const webpack = require('webpack')
module.exports = {
debug: true,
cache: false,
process: true,
stats: {
colors: true
},
entry: {
'scrollto-with-animation': 'src'
},
output: {
path: 'dist',
filename: '[name].min.js'
},
plugins: [
new webpack.SourceMapDevToolPlugin({
filename: '[name].js.map'
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compressor: {
screw_ie8: true,
warnings: false
},
output: {
comments: false
}
})
],
module: {
loaders: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
cacheDirectory: true,
presets: ['es2015', 'stage-2']
}
}]
}
}
|
Remove build option from generated docker file
|
#!/usr/bin/env node
var fs = require('fs');
var version = JSON.parse(fs.readFileSync("./package.json")).version;
var tag = "truecar/gluestick:" + version;
var dockerfile = [
"# DO NOT MODIFY",
"# This file is automatically generated. You can copy this file and add a",
"# Dockerfile to the root of the project if you would like to use a custom",
"# docker setup.",
"FROM " + tag,
"",
"ADD . /app",
"",
"RUN npm install",
""
];
fs.writeFile("./templates/new/src/config/.Dockerfile", dockerfile.join("\n"));
|
#!/usr/bin/env node
var fs = require('fs');
var version = JSON.parse(fs.readFileSync("./package.json")).version;
var tag = "truecar/gluestick:" + version;
var dockerfile = [
"# DO NOT MODIFY",
"# This file is automatically generated. You can copy this file and add a",
"# Dockerfile to the root of the project if you would like to use a custom",
"# docker setup.",
"FROM " + tag,
"",
"ADD . /app",
"",
"RUN npm install",
"RUN gluestick build",
""
];
fs.writeFile("./templates/new/src/config/.Dockerfile", dockerfile.join("\n"));
|
Fix variable for input string
|
from future.builtins import ( # noqa
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
pow, round, filter, map, zip)
import re
__author__ = 'sukrit'
"""
Package that includes custom filters required for totem config processing
"""
USE_FILTERS = ('replace_regex', )
def replace_regex(input_str, find, replace):
"""
Regex replace filter that replaces all occurrences of given regex match
in a given string
:param input_str: Input string on which replacement is to be performed
:type input_str: str
:param find: Regular expression string that needs to be used for
find/replacement
:type find: str
:param replace: Regex replacement string
:type replace: str
:return: Regex replaced string
:rtype: str
"""
return re.sub(find, replace, input_str)
def apply_filters(env):
"""
Applies filters on jinja env.
:param env: Jinja environment
:return:
"""
for name in USE_FILTERS:
env.filters[name] = globals()[name]
return env
|
from future.builtins import ( # noqa
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
pow, round, filter, map, zip)
import re
__author__ = 'sukrit'
"""
Package that includes custom filters required for totem config processing
"""
USE_FILTERS = ('replace_regex', )
def replace_regex(input_str, find, replace):
"""
Regex replace filter that replaces all occurrences of given regex match
in a given string
:param input_str: Input string on which replacement is to be performed
:type input_str: str
:param find: Regular expression string that needs to be used for
find/replacement
:type find: str
:param replace: Regex replacement string
:type replace: str
:return: Regex replaced string
:rtype: str
"""
return re.sub(find, replace, input)
def apply_filters(env):
"""
Applies filters on jinja env.
:param env: Jinja environment
:return:
"""
for name in USE_FILTERS:
env.filters[name] = globals()[name]
return env
|
Add _GNU_SOURCE definition to ext_module
|
'''
(c) 2014 Farsight Security Inc.
(c) 2010 Victor Ng
Released under the MIT license. See license.txt.
'''
from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from os.path import join
import os
ext_modules=[
Extension("mmaparray",
extra_compile_args=['-std=gnu99', '-O2', '-D_LARGEFILE64_SOURCE', '-D_GNU_SOURCE'],
sources = [
"src/mmaparray.pyx",
'src/mmap_writer.c',],
include_dirs = ['src'],
),
]
setup(
name = 'mmaparray',
author='Henry Stern',
author_email = 'stern@fsi.io',
description = 'MMap File-Backed Arrays for Python',
long_description = open('README.rst').read(),
version='0.4',
url='https://github.com/farsightsec/mmaparray',
license = 'MIT License',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
test_suite = 'tests',
requires = [ 'six', 'Cython (>=0.13)' ],
classifiers = [
'License :: OSI Approved :: MIT License',
'Programming Language :: Cython',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
],
)
|
'''
(c) 2014 Farsight Security Inc.
(c) 2010 Victor Ng
Released under the MIT license. See license.txt.
'''
from setuptools import setup
from setuptools.extension import Extension
from Cython.Distutils import build_ext
from os.path import join
import os
ext_modules=[
Extension("mmaparray",
extra_compile_args=['-std=gnu99', '-O2', '-D_LARGEFILE64_SOURCE'],
sources = [
"src/mmaparray.pyx",
'src/mmap_writer.c',],
include_dirs = ['src'],
),
]
setup(
name = 'mmaparray',
author='Henry Stern',
author_email = 'stern@fsi.io',
description = 'MMap File-Backed Arrays for Python',
long_description = open('README.rst').read(),
version='0.4',
url='https://github.com/farsightsec/mmaparray',
license = 'MIT License',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules,
test_suite = 'tests',
requires = [ 'six', 'Cython (>=0.13)' ],
classifiers = [
'License :: OSI Approved :: MIT License',
'Programming Language :: Cython',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
],
)
|
Add id to API reponse for Reaction.
|
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Reaction
from rest_framework.fields import HyperlinkedIdentityField
class ReactionAuthorSerializer(serializers.ModelSerializer):
picture = SorlImageField('userprofile.picture', '90x90', crop='center')
class Meta:
model = User
fields = ('first_name', 'last_name', 'picture')
class ReactionDetailSerializer(serializers.ModelSerializer):
# Read-only fields.
created = serializers.Field()
# Custom fields.
author = ReactionAuthorSerializer()
# TODO: This isn't work with the pattern: api/blogs/<slug>/reactions/<pk>
# Delete or fix this ... we don't really need it so removing it is ok but it's nice to have.
# url = HyperlinkedIdentityField(view_name='reactions:reaction-detail')
class Meta:
model = Reaction
fields = ('created', 'author', 'reaction', 'id')
class ReactionListSerializer(ReactionDetailSerializer):
class Meta:
model = Reaction
fields = ('created', 'author', 'reaction', 'id')
|
from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Reaction
from rest_framework.fields import HyperlinkedIdentityField
class ReactionAuthorSerializer(serializers.ModelSerializer):
picture = SorlImageField('userprofile.picture', '90x90', crop='center')
class Meta:
model = User
fields = ('first_name', 'last_name', 'picture')
class ReactionDetailSerializer(serializers.ModelSerializer):
# Read-only fields.
created = serializers.Field()
# Custom fields.
author = ReactionAuthorSerializer()
# TODO: This isn't work with the pattern: api/blogs/<slug>/reactions/<pk>
# Delete or fix this ... we don't really need it so removing it is ok but it's nice to have.
# url = HyperlinkedIdentityField(view_name='reactions:reaction-detail')
class Meta:
model = Reaction
fields = ('created', 'author', 'reaction')
class ReactionListSerializer(ReactionDetailSerializer):
class Meta:
model = Reaction
fields = ('created', 'author', 'reaction')
|
Add explanatory comment for odd use of `delay()`
|
# coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
# Push this onto the task queue with `delay()` instead of calling
# it directly because a direct call in the absence of any Celery
# workers hangs indefinitely
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
|
# coding: utf-8
import kombu.exceptions
from django.apps import AppConfig
from django.core.checks import register, Tags
from kpi.utils.two_database_configuration_checker import \
TwoDatabaseConfigurationChecker
class KpiConfig(AppConfig):
name = 'kpi'
def ready(self, *args, **kwargs):
# Once it's okay to read from the database, apply the user-desired
# autoscaling configuration for Celery workers
from kobo.celery import update_concurrency_from_constance
try:
update_concurrency_from_constance.delay()
except kombu.exceptions.OperationalError as e:
# It's normal for Django to start without access to a message
# broker, e.g. while running `./manage.py collectstatic`
# during a Docker image build
pass
return super().ready(*args, **kwargs)
register(TwoDatabaseConfigurationChecker().as_check(), Tags.database)
|
Simplify menu debugging logic a bit.
|
package com.squareup.picasso.sample;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import com.squareup.picasso.Picasso;
public class SampleActivity extends Activity {
private SampleAdapter adapter;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.setThreadPolicy(
new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
adapter = new SampleAdapter(this);
ListView lv = new ListView(this);
lv.setAdapter(adapter);
setContentView(lv);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Debugging")
.setCheckable(true)
.setChecked(Picasso.with(this).isDebugging())
.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override public boolean onMenuItemClick(MenuItem item) {
item.setChecked(!item.isChecked());
Picasso.with(SampleActivity.this).setDebugging(item.isChecked());
adapter.notifyDataSetChanged();
return true;
}
});
return true;
}
}
|
package com.squareup.picasso.sample;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import com.squareup.picasso.Picasso;
public class SampleActivity extends Activity {
private SampleAdapter adapter;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.setThreadPolicy(
new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
adapter = new SampleAdapter(this);
ListView lv = new ListView(this);
lv.setAdapter(adapter);
setContentView(lv);
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == 0) {
item.setChecked(!item.isChecked());
Picasso.with(this).setDebugging(item.isChecked());
adapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
MenuItem debugItem = menu.add(0, 0, 0, "Debugging");
debugItem.setCheckable(true);
debugItem.setChecked(Picasso.with(this).isDebugging());
return super.onCreateOptionsMenu(menu);
}
}
|
Fix reference to context in require.context
|
import history from '!json!../assets/data/history.json'
import metadata from '!json!../assets/data/metadata.json'
// Loading latest season in the main bundle itself
import latestSeasonData from '!json!../assets/data/season-latest.json'
const seasonDataCtx = require.context(
'file-loader!../assets/data/',
false,
/^\.\/.*\.json$/
)
const distDataCtx = require.context(
'file-loader!../assets/data/distributions/',
false,
/^\.\/.*\.json$/
)
const seasonDataUrls = seasonDataCtx.keys().reduce((acc, key) => {
if (key.startsWith('./season-')) {
// Identifier is like '2013-2014'
acc[key.slice(9, -5)] = seasonDataCtx(key)
}
return acc
}, {})
const distDataUrls = distDataCtx.keys().reduce((acc, key) => {
if (key.startsWith('./season-')) {
// Identifier is like '2013-2014-hhs10'
acc[key.slice(9, -5)] = distDataCtx(key)
}
return acc
}, {})
export { seasonDataUrls, distDataUrls, latestSeasonData, history, metadata }
|
import history from '!json!../assets/data/history.json'
import metadata from '!json!../assets/data/metadata.json'
// Loading latest season in the main bundle itself
import latestSeasonData from '!json!../assets/data/season-latest.json'
const seasonDataCtx = require.context(
'file-loader!../assets/data/',
false,
/^\.\/.*\.json$/
)
const distDataCtx = require.context(
'file-loader!../assets/data/distributions/',
false,
/^\.\/.*\.json$/
)
const seasonDataUrls = seasonDataCtx.keys().reduce((acc, key) => {
if (key.startsWith('./season-')) {
// Identifier is like '2013-2014'
acc[key.slice(9, -5)] = req(key)
}
return acc
}, {})
const distDataUrls = distDataCtx.keys().reduce((acc, key) => {
if (key.startsWith('./season-')) {
// Identifier is like '2013-2014-hhs10'
acc[key.slice(9, -5)] = req(key)
}
return acc
}, {})
export { seasonDataUrls, distDataUrls, latestSeasonData, history, metadata }
|
Abort locale switcher set up if the local switcher is not present
If attachments references are not allowed the select is not rendered and trying to add an event listener to it was causing an error. This was causing the GovSpeak preview to break as well.
|
window.GOVUK = window.GOVUK || {}
window.GOVUK.Modules = window.GOVUK.Modules || {};
(function (Modules) {
function LocaleSwitcher (module) {
this.module = module
this.rightToLeftLocales = module.dataset.rtlLocales.split(' ')
}
LocaleSwitcher.prototype.init = function () {
this.setupLocaleSwitching()
}
LocaleSwitcher.prototype.setupLocaleSwitching = function () {
var form = this.module
var rightToLeftLocales = this.rightToLeftLocales
var select = form.querySelector('#attachment_locale')
if (!select) {
return
}
var title = form.querySelector('.attachment-form__title')
var body = form.querySelector('.attachment-form__body')
select.addEventListener('change', function () {
if (rightToLeftLocales.indexOf(this.value) > -1) {
title.classList.add('right-to-left')
body.classList.add('right-to-left')
} else {
title.classList.remove('right-to-left')
body.classList.remove('right-to-left')
}
})
}
Modules.LocaleSwitcher = LocaleSwitcher
})(window.GOVUK.Modules)
|
window.GOVUK = window.GOVUK || {}
window.GOVUK.Modules = window.GOVUK.Modules || {};
(function (Modules) {
function LocaleSwitcher (module) {
this.module = module
this.rightToLeftLocales = module.dataset.rtlLocales.split(' ')
}
LocaleSwitcher.prototype.init = function () {
this.setupLocaleSwitching()
}
LocaleSwitcher.prototype.setupLocaleSwitching = function () {
var form = this.module
var rightToLeftLocales = this.rightToLeftLocales
var title = form.querySelector('.attachment-form__title')
var body = form.querySelector('.attachment-form__body')
form.querySelector('#attachment_locale').addEventListener('change', function () {
if (rightToLeftLocales.indexOf(this.value) > -1) {
title.classList.add('right-to-left')
body.classList.add('right-to-left')
} else {
title.classList.remove('right-to-left')
body.classList.remove('right-to-left')
}
})
}
Modules.LocaleSwitcher = LocaleSwitcher
})(window.GOVUK.Modules)
|
Revert "Changed Model Variable m to protected. Used corresponding getters. changes made because dataset needed for calculating amount of triples."
This reverts commit f474d987593f1088e3571b18339682a8ff8c7d79.
|
package de.unibonn.iai.eis.diachron.qualitymetrics.utilities;
import java.util.ArrayList;
import java.util.List;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.sparql.core.Quad;
public class TestLoader {
protected List<Quad> streamingQuads = new ArrayList<Quad>();
/**
* Loads a sample dataset which can be used to test metrics
*/
public void loadDataSet() {
String filename = this.getClass().getClassLoader().getResource("testdumps/160114.ttl").toExternalForm();
//String filename = this.getClass().getClassLoader().getResource("testdumps/chembl-rdf-void.ttl").toExternalForm();
Model m = ModelFactory.createDefaultModel();
m.read(filename, "TTL");
StmtIterator si = m.listStatements();
while(si.hasNext()){
this.streamingQuads.add(new Quad(null, si.next().asTriple()));
}
}
/**
* Returns a list of triples from the loaded dataset. This can be used
* to simulate the streaming of triples
* @return list of Triples
*/
public List<Quad> getStreamingQuads(){
return this.streamingQuads;
}
}
|
package de.unibonn.iai.eis.diachron.qualitymetrics.utilities;
import java.util.ArrayList;
import java.util.List;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.sparql.core.Quad;
public class TestLoader {
protected List<Quad> streamingQuads = new ArrayList<Quad>();
protected Model m;
/**
* Loads a sample dataset which can be used to test metrics
*/
public void loadDataSet() {
String filename = this.getClass().getClassLoader().getResource("testdumps/160114.ttl").toExternalForm();
//String filename = this.getClass().getClassLoader().getResource("testdumps/chembl-rdf-void.ttl").toExternalForm();
m = ModelFactory.createDefaultModel();
m.read(filename, "TTL");
StmtIterator si = m.listStatements();
while(si.hasNext()){
this.streamingQuads.add(new Quad(null, si.next().asTriple()));
}
}
public Model getM() {
return m;
}
/**
* Returns a list of triples from the loaded dataset. This can be used
* to simulate the streaming of triples
* @return list of Triples
*/
public List<Quad> getStreamingQuads(){
return this.streamingQuads;
}
}
|
Add return type : string
|
<?php
namespace Coosos\TagBundle\Twig;
use Symfony\Component\Form\FormView;
class TagExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return [
new \Twig_SimpleFunction("form_coosos_tag", [$this, 'tagRendering'], [
'is_safe' => ['html'],
'needs_environment' => true // Tell twig we need the environment
]),
];
}
/**
* @param \Twig_Environment $environment
* @param FormView $formTag
* @return string
*/
public function tagRendering(\Twig_Environment $environment, FormView $formTag): string
{
return $environment->render("CoososTagBundle::formCoososTag.html.twig", ["formTag" => $formTag]);
}
}
|
<?php
namespace Coosos\TagBundle\Twig;
use Symfony\Component\Form\FormView;
class TagExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return [
new \Twig_SimpleFunction("form_coosos_tag", [$this, 'tagRendering'], [
'is_safe' => ['html'],
'needs_environment' => true // Tell twig we need the environment
]),
];
}
/**
* @param \Twig_Environment $environment
* @param FormView $formTag
* @return string
*/
public function tagRendering(\Twig_Environment $environment, FormView $formTag)
{
return $environment->render("CoososTagBundle::formCoososTag.html.twig", ["formTag" => $formTag]);
}
}
|
Fix weird glitchy thing again.
|
$(document).ready(function(){
$('button#boot').click(function() {
var l = Ladda.create( document.querySelector( '#boot' ) );
l.start();
$.get('/performActions.php?theAction=boot', function(data) {
l.stop();
$("#actionResults").show(0).delay(8000).hide(0);
$("#bootResult").show(0).delay(7777).hide(0);
});
return false;
});
$('button#reboot').click(function() {
var l = Ladda.create( document.querySelector( '#reboot' ) );
l.start();
$.get('/performActions.php?theAction=reboot', function(data) {
l.stop();
$("#actionResults").show(0).delay(8000).hide(0);
$("#rebootResult").show(0).delay(7777).hide(0);
});
return false;
});
$('button#shutdown').click(function() {
var l = Ladda.create( document.querySelector( '#shutdown' ) );
l.start();
$.get('/performActions.php?theAction=shutdown', function(data) {
l.stop();
$("#actionResults").show(0).delay(8000).hide(0);
$("#shutdownResult").show(0).delay(7777).hide(0);
});
return false;
});
});
|
$(document).ready(function(){
$('button#boot').click(function() {
var l = Ladda.create( document.querySelector( '#boot' ) );
l.start();
$.get('/performActions.php?theAction=boot', function(data) {
l.stop();
$("#actionResults").show(0).delay(5000).hide(0);
$("#bootResult").show(0).delay(4777).hide(0);
});
return false;
});
$('button#reboot').click(function() {
var l = Ladda.create( document.querySelector( '#reboot' ) );
l.start();
$.get('/performActions.php?theAction=reboot', function(data) {
l.stop();
$("#actionResults").show(0).delay(5000).hide(0);
$("#rebootResult").show(0).delay(4777).hide(0);
});
return false;
});
$('button#shutdown').click(function() {
var l = Ladda.create( document.querySelector( '#shutdown' ) );
l.start();
$.get('/performActions.php?theAction=shutdown', function(data) {
l.stop();
$("#actionResults").show(0).delay(5000).hide(0);
$("#shutdownResult").show(0).delay(4777).hide(0);
});
return false;
});
});
|
Simplify adding the template markup to the document
|
Wee.fn.make('todo', {
init: function() {
$('ref:nav').after($.first('ref:template').text);
Wee.app.make('items', {
view: 'ref:todo',
model: {
todo: [
{
label: 'Download and run Wee',
done: true
},
{
label: 'Explore the welcome module'
},
{
label: 'Configure wee.json'
},
{
label: 'Run node wee reset'
}
]
}
});
$('ref:toggle').on('click', function() {
var id = $(this).data('id'),
done = Wee.items.$get('todo.' + id + '.done');
Wee.items.$set('todo.' + id + '.done', done ? false : true);
}, {
delegate: 'ref:todo'
});
}
});
Wee.routes.map({
'$root': 'todo'
}, true);
|
Wee.fn.make('todo', {
init: function() {
$($('ref:template').text()).insertAfter('ref:nav');
Wee.app.make('items', {
view: 'ref:todo',
model: {
todo: [
{
label: 'Download and run Wee',
done: true
},
{
label: 'Explore the welcome module'
},
{
label: 'Configure wee.json'
},
{
label: 'Run node wee reset'
}
]
}
});
$('ref:toggle').on('click', function() {
var id = $(this).data('id'),
done = Wee.items.$get('todo.' + id + '.done');
Wee.items.$set('todo.' + id + '.done', done ? false : true);
}, {
delegate: 'ref:todo'
});
}
});
Wee.routes.map({
'$root': 'todo'
}, true);
|
Return value for client.stream.* calls
These endpoints didn’t return anything, making them unusable with the
promises version of the API.
|
/**
* Created by austin on 9/24/14.
*/
var streams = function (client) {
this.client = client;
};
var _qsAllowedProps = [
'resolution'
, 'series_type'
];
//===== streams endpoint =====
streams.prototype.activity = function(args,done) {
var endpoint = 'activities';
return this._typeHelper(endpoint,args,done);
};
streams.prototype.effort = function(args,done) {
var endpoint = 'segment_efforts';
return this._typeHelper(endpoint,args,done);
};
streams.prototype.segment = function(args,done) {
var endpoint = 'segments';
return this._typeHelper(endpoint,args,done);
};
streams.prototype.route = function(args,done) {
var endpoint = 'routes';
return this._typeHelper(endpoint,args,done);
};
//===== streams endpoint =====
//===== helpers =====
streams.prototype._typeHelper = function(endpoint,args,done) {
var err = null
, qs = this.client.getQS(_qsAllowedProps,args);
//require id
if(typeof args.id === 'undefined') {
throw new Error('args must include an id');
}
//require types
if(typeof args.types === 'undefined') {
throw new Error('args must include types');
}
endpoint += '/' + args.id + '/streams/' + args.types + '?' + qs;
return this.client.getEndpoint(endpoint,args,done);
};
//===== helpers =====
module.exports = streams;
|
/**
* Created by austin on 9/24/14.
*/
var streams = function (client) {
this.client = client;
};
var _qsAllowedProps = [
'resolution'
, 'series_type'
];
//===== streams endpoint =====
streams.prototype.activity = function(args,done) {
var endpoint = 'activities';
this._typeHelper(endpoint,args,done);
};
streams.prototype.effort = function(args,done) {
var endpoint = 'segment_efforts';
this._typeHelper(endpoint,args,done);
};
streams.prototype.segment = function(args,done) {
var endpoint = 'segments';
this._typeHelper(endpoint,args,done);
};
streams.prototype.route = function(args,done) {
var endpoint = 'routes';
this._typeHelper(endpoint,args,done);
};
//===== streams endpoint =====
//===== helpers =====
streams.prototype._typeHelper = function(endpoint,args,done) {
var err = null
, qs = this.client.getQS(_qsAllowedProps,args);
//require id
if(typeof args.id === 'undefined') {
throw new Error('args must include an id');
}
//require types
if(typeof args.types === 'undefined') {
throw new Error('args must include types');
}
endpoint += '/' + args.id + '/streams/' + args.types + '?' + qs;
return this.client.getEndpoint(endpoint,args,done);
};
//===== helpers =====
module.exports = streams;
|
Fix indefinite event loop on connection error
|
var _IsLoggedIn = undefined;
function checkIfLoggedInAndTriggerEvent(notifyLoggedOutEveryTime){
request({module:"user", type: "IsLoggedIn"}, function(res){
if(_IsLoggedIn === undefined){
$(document).trigger("InitialUserStatus", res.loggedIn);
}
if(res.loggedIn != _IsLoggedIn){
_IsLoggedIn = res.loggedIn;
$(document).trigger(_IsLoggedIn ? "logged_out_timer" : "logged_in_timer");
if(!_IsLoggedIn && typeof(Notifier) === "function")
new Notifier().show("You are not logged in!");
} else if(notifyLoggedOutEveryTime && !_IsLoggedIn){
new Notifier().show("You are not logged in!");
}
});
}
var lastIsLoggedInErrorCheck = 0;
$(document).bind('request_error', function(){
if(new Date().getTime() > lastIsLoggedInErrorCheck + 1000) //Only notify about login errors every sec
checkIfLoggedInAndTriggerEvent(true);
lastIsLoggedInErrorCheck = new Date().getTime();
});
setInterval(checkIfLoggedInAndTriggerEvent, 10000);
checkIfLoggedInAndTriggerEvent();
$(document).bind('InitialUserStatus', function(e, arg){
_IsLoggedIn = arg;
});
$(document).bind('LoggedIn', function(){
_IsLoggedIn = true;
});
$(document).bind('LoggedOut', function(){
_IsLoggedIn = false;
});
function isLoggedIn(){
return _IsLoggedIn;
}
|
var _IsLoggedIn = undefined;
function checkIfLoggedInAndTriggerEvent(notifyLoggedOutEveryTime){
request({module:"user", type: "IsLoggedIn"}, function(res){
if(_IsLoggedIn === undefined){
$(document).trigger("InitialUserStatus", res.loggedIn);
}
if(res.loggedIn != _IsLoggedIn){
_IsLoggedIn = res.loggedIn;
$(document).trigger(_IsLoggedIn ? "logged_out_timer" : "logged_in_timer");
if(!_IsLoggedIn && typeof(Notifier) === "function")
new Notifier().show("You are not logged in!");
} else if(notifyLoggedOutEveryTime && !_IsLoggedIn){
new Notifier().show("You are not logged in!");
}
});
}
$(document).bind('request_error', function(){
checkIfLoggedInAndTriggerEvent(true);
});
setInterval(checkIfLoggedInAndTriggerEvent, 10000);
checkIfLoggedInAndTriggerEvent();
$(document).bind('InitialUserStatus', function(e, arg){
_IsLoggedIn = arg;
});
$(document).bind('LoggedIn', function(){
_IsLoggedIn = true;
});
$(document).bind('LoggedOut', function(){
_IsLoggedIn = false;
});
function isLoggedIn(){
return _IsLoggedIn;
}
|
Add separate steps for production and development
|
/*
* USAGE:
*
* Make sure you use the right way to invoke webpack, because the config
* file relies on it to determine if development or production settings
* must be used.
*
* Development: webpack -d
*
* Production: NODE_ENV=production webpack -p
*
*/
var path = require('path')
var webpack = require('webpack')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebPackPlugin = require('html-webpack-plugin')
const production = process.env.NODE_ENV === 'production'
module.exports = {
entry: ['./src/app.js'],
output: {
path: path.resolve(__dirname, production ? 'dist' : 'build'),
filename: 'app_bundle.js',
sourceMapFilename: 'app_bundle.js.map'
},
module: {
loaders: [{
loader: 'babel-loader',
exclude: /node_modules/,
test: /\.js$/,
query: {
presets: ['es2015', 'react', 'stage-0']
}
}]
},
plugins: [
new CopyWebpackPlugin([{
from: './src/static/'
}]),
new HtmlWebPackPlugin({
title: 'MOOCFetcher',
template: './src/templates/index.html',
inject: false,
production: production
})
]
}
|
var path = require('path')
var CopyWebpackPlugin = require('copy-webpack-plugin')
var HtmlWebPackPlugin = require('html-webpack-plugin')
const production = process.env.NODE_ENV === 'production'
module.exports = {
entry: ['./src/app.js'],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'app_bundle.js'
},
module: {
loaders: [{
loader: 'babel-loader',
exclude: /node_modules/,
test: /\.js$/,
query: {
presets: ['es2015', 'react', 'stage-0']
}
}]
},
plugins: [
new CopyWebpackPlugin([{
from: './src/static/'
}]),
new HtmlWebPackPlugin({
title: 'MOOCFetcher',
template: './src/templates/index.html',
inject: false,
production: production
})
]
}
|
Add Orwell as a lib
|
(function(){
'use strict';
angular.module('application', [
'ui.router',
'ngAnimate',
//foundation
'foundation',
'foundation.dynamicRouting',
'foundation.dynamicRouting.animations',
// Libraries
'ngOrwell',
// Fusion Seed App
'fusionSeedApp.components',
'fusionSeedApp.services',
//'ObservableService'
])
.config(config)
.run(run)
;
config.$inject = ['$urlRouterProvider', '$locationProvider'];
function config($urlProvider, $locationProvider) {
$urlProvider.otherwise('/');
$locationProvider.html5Mode({
enabled:false,
requireBase: false
});
$locationProvider.hashPrefix('!');
}
function run($log, ConfigApiService) {
FastClick.attach(document.body);
}
})();
|
(function(){
'use strict';
angular.module('application', [
'ui.router',
'ngAnimate',
//foundation
'foundation',
'foundation.dynamicRouting',
'foundation.dynamicRouting.animations',
// Fusion Seed App
'fusionSeedApp.components',
'fusionSeedApp.services',
//'ObservableService'
])
.config(config)
.run(run)
;
config.$inject = ['$urlRouterProvider', '$locationProvider'];
function config($urlProvider, $locationProvider) {
$urlProvider.otherwise('/');
$locationProvider.html5Mode({
enabled:false,
requireBase: false
});
$locationProvider.hashPrefix('!');
}
function run($log, ConfigApiService) {
FastClick.attach(document.body);
}
})();
|
Add check for nan values
|
#!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
try:
import numpy as np
except ImportError:
np = None
def sanitize_np_types(value):
if math.isnan(value):
return None
if isinstance(value, (int, float, complex, type(None))):
return value
if np and np.isnan(value):
return None
if np and isinstance(value, np.integer):
return int(value)
if np and isinstance(value, np.floating):
return float(value)
return value
def to_np(value):
if isinstance(value, np.ndarray):
return value
if np.isscalar(value):
return np.array([value])
def calculate_scale_factor(tensor):
converted = tensor.numpy() if not isinstance(tensor, np.ndarray) else tensor
return 1 if converted.dtype == np.uint8 else 255
|
#!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
import numpy as np
except ImportError:
np = None
def sanitize_np_types(value):
if isinstance(value, (int, float, complex, type(None))):
return value
if np.isnan(value):
return None
if np and isinstance(value, np.integer):
return int(value)
if np and isinstance(value, np.floating):
return float(value)
return value
def to_np(value):
if isinstance(value, np.ndarray):
return value
if np.isscalar(value):
return np.array([value])
def calculate_scale_factor(tensor):
converted = tensor.numpy() if not isinstance(tensor, np.ndarray) else tensor
return 1 if converted.dtype == np.uint8 else 255
|
Return a valid JSON object for a valid XML presskit
|
// Convert presskit() data.xml file into the new JSON format
'use strict'
var fs = require('fs')
var xml2js = require('xml2js')
// Configure parser
// -- Avoid arrays for single elements
var xmlParser = new xml2js.Parser({explicitArray: false})
// -------------------------------------------------------------
// Module.
// -------------------------------------------------------------
var Converter = function () {
}
// Convert data.xml content into a JSON string
Converter.prototype.convert = function (xml, callback) {
var presskit
if (!xml) callback(new Error('XML input was null or empty'), presskit)
xmlParser.parseString(xml, function (err, result) {
if (!err && result) {
// Values are nested in the "game" node
if (result.game) {
presskit = result.game
}
}
callback(err, presskit)
})
}
// Convert an XML data file to a formatted JSON file
Converter.prototype.convertFile = function (source, destination, format, callback) {
fs.readFile(source, function (err, data) {
Converter.convert(data, function (error, result) {
if (!error) {
var json = JSON.stringify(result.game, null, (format ? 2 : 0))
fs.writeFile(destination, json, function (err) {
callback(err)
})
} else {
callback(err)
}
})
})
}
// -------------------------------------------------------------
// Exports.
// -------------------------------------------------------------
module.exports = new Converter()
|
// Convert presskit() data.xml file into the new JSON format
'use strict'
var fs = require('fs')
var xmlParser = require('xml2js').parseString
// -------------------------------------------------------------
// Module.
// -------------------------------------------------------------
var Converter = function () {}
// Convert data.xml content into a JSON string
Converter.prototype.convert = function (xml, callback) {
var json
if (!xml) callback(new Error('XML input was null or empty'), json)
xmlParser(xml, function (err, result) {
if (!err && result) {
json = JSON.stringify(result, null, 2)
}
callback(err, json)
})
}
// Convert an XML data file to a formatted JSON file
Converter.prototype.convertFile = function (source, destination, callback) {
fs.readFile(source, function (err, data) {
Converter.convert(data, function (error, result) {
if (!error) {
fs.writeFile(destination, data, function (err) {
callback(err)
})
} else {
callback(err)
}
})
})
}
// -------------------------------------------------------------
// Exports.
// -------------------------------------------------------------
module.exports = new Converter()
|
Increment minor version once more
|
import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='parserutils',
description='A collection of performant parsing utilities',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml',
version='1.2.1',
packages=[
'parserutils', 'parserutils.tests'
],
install_requires=[
'defusedxml>=0.4.1', 'python-dateutil>=2.4.2', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/parserutils',
license='BSD',
cmdclass={'test': RunTests}
)
|
import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'parserutils.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='parserutils',
description='A collection of performant parsing utilities',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml',
version='1.2',
packages=[
'parserutils', 'parserutils.tests'
],
install_requires=[
'defusedxml>=0.4.1', 'python-dateutil>=2.4.2', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/parserutils',
license='BSD',
cmdclass={'test': RunTests}
)
|
Fix Icon props doc page.
|
import { storiesOf } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
import Icon from '@ichef/gypcrete/src/Icon';
import getPropTables from 'utils/getPropTables';
import BasicIconsSet from './BasicIcons';
import PaymentIconsSet from './PaymentIcons';
import CRMIconsSet from './CRMIcons';
import InventoryIconsSet from './InventoryIcons';
import MenuPageIconsSet from './MenuPageIcons';
import PaginationIconsSet from './PaginationIcons';
import InlineIconsSet from './InlineIcons';
import LargeIconExample from './LargeIcon';
import IconColorsExample from './IconColors';
storiesOf('@ichef/gypcrete|Icon', module)
.add('basic icons set', withInfo()(BasicIconsSet))
.add('payment icons set', withInfo()(PaymentIconsSet))
.add('CRM icons set', withInfo()(CRMIconsSet))
.add('Inventory icons set', withInfo()(InventoryIconsSet))
.add('Menu page icons set', withInfo()(MenuPageIconsSet))
.add('Pagination icons set', withInfo()(PaginationIconsSet))
.add('inline-sized icons set', withInfo()(InlineIconsSet))
.add('large size', withInfo()(LargeIconExample))
.add('color options', withInfo()(IconColorsExample))
// Props table
.add('props', getPropTables([Icon]), { info: { propTables: [Icon] } });
|
import { storiesOf } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
import Icon from '@ichef/gypcrete/src/Icon';
import getPropTables from 'utils/getPropTables';
import BasicIconsSet from './BasicIcons';
import PaymentIconsSet from './PaymentIcons';
import CRMIconsSet from './CRMIcons';
import InventoryIconsSet from './InventoryIcons';
import MenuPageIconsSet from './MenuPageIcons';
import PaginationIconsSet from './PaginationIcons';
import InlineIconsSet from './InlineIcons';
import LargeIconExample from './LargeIcon';
import IconColorsExample from './IconColors';
storiesOf('@ichef/gypcrete|Icon', module)
.add('basic icons set', withInfo()(BasicIconsSet))
.add('payment icons set', withInfo()(PaymentIconsSet))
.add('CRM icons set', withInfo()(CRMIconsSet))
.add('Inventory icons set', withInfo()(InventoryIconsSet))
.add('Menu page icons set', withInfo()(MenuPageIconsSet))
.add('Pagination icons set', withInfo()(PaginationIconsSet))
.add('inline-sized icons set', withInfo()(InlineIconsSet))
.add('large size', withInfo()(LargeIconExample))
.add('color options', withInfo()(IconColorsExample))
// Props table
.add('props', getPropTables([Icon]));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.