text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Change reset css option to subpalette | <?php
/*
* Copyright NEXPER <info@nexper.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
$GLOBALS['TL_DCA']['tl_layout']['palettes']['__selector__'][] = 'nx_columns_load_css';
$GLOBALS['TL_DCA']['tl_layout']['palettes']['default'] .= ';{nx_columns_legend},nx_columns_load_css';
$GLOBALS['TL_DCA']['tl_layout']['subpalettes']['nx_columns_load_css'] = 'nx_columns_load_reset_css';
$GLOBALS['TL_DCA']['tl_layout']['fields']['nx_columns_load_css'] = array(
'inputType' => 'checkbox',
'label' => &$GLOBALS['TL_LANG']['tl_layout']['nx_columns_load_css'],
'eval' => array('submitOnChange' => true, 'tl_class' =>'w50'),
'sql' => "char(1) NOT NULL default '1'",
);
$GLOBALS['TL_DCA']['tl_layout']['fields']['nx_columns_load_reset_css'] = array(
'inputType' => 'checkbox',
'label' => &$GLOBALS['TL_LANG']['tl_layout']['nx_columns_load_reset_css'],
'eval' => array('tl_class' => 'w50'),
'sql' => "char(1) NOT NULL default '0'",
); | <?php
/*
* Copyright NEXPER <info@nexper.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
$GLOBALS['TL_DCA']['tl_layout']['palettes']['default'] .= ';{nx_columns_legend},nx_columns_load_reset_css,nx_columns_load_css';
$GLOBALS['TL_DCA']['tl_layout']['fields']['nx_columns_load_reset_css'] = array(
'inputType' => 'checkbox',
'label' => &$GLOBALS['TL_LANG']['tl_layout']['nx_columns_load_reset_css'],
'eval' => array('tl_class' => 'w50'),
'sql' => "char(1) NOT NULL default '0'",
);
$GLOBALS['TL_DCA']['tl_layout']['fields']['nx_columns_load_css'] = array(
'inputType' => 'checkbox',
'label' => &$GLOBALS['TL_LANG']['tl_layout']['nx_columns_load_css'],
'eval' => array('tl_class' =>'w50'),
'sql' => "char(1) NOT NULL default '1'",
); |
:art: Use common js exports instead of es exports | 'use babel'
/* @flow */
module.exports = function promisify(callback: Function): Function {
return function promisified(){
const parameters = arguments
const parametersLength = arguments.length + 1
return new Promise((resolve, reject) => {
Array.prototype.push.call(parameters, function(error, data) {
if (error) {
reject(error)
} else resolve(data)
})
if (parametersLength === 1) {
callback.call(this, parameters[0])
} else if (parametersLength === 2) {
callback.call(this, parameters[0], parameters[1])
} else if (parametersLength === 3) {
callback.call(this, parameters[0], parameters[1], parameters[2])
} else if (parametersLength === 4) {
callback.call(this, parameters[0], parameters[1], parameters[2], parameters[3])
} else {
callback.apply(this, parameters)
}
})
}
}
| 'use babel'
/* @flow */
export default function promisify(callback: Function): Function {
return function promisified(){
const parameters = arguments
const parametersLength = arguments.length + 1
return new Promise((resolve, reject) => {
Array.prototype.push.call(parameters, function(error, data) {
if (error) {
reject(error)
} else resolve(data)
})
if (parametersLength === 1) {
callback.call(this, parameters[0])
} else if (parametersLength === 2) {
callback.call(this, parameters[0], parameters[1])
} else if (parametersLength === 3) {
callback.call(this, parameters[0], parameters[1], parameters[2])
} else if (parametersLength === 4) {
callback.call(this, parameters[0], parameters[1], parameters[2], parameters[3])
} else {
callback.apply(this, parameters)
}
})
}
}
|
Speed up getOsMetadata() on macOS
Shell out to `sw_vers` once instead of three times.
Signed-off-by: Thomas Hallgren <5f50a84c1fa3bcff146405017f36aec1a10a9e38@datawire.io> | package scout
import (
"bufio"
"bytes"
"context"
"strings"
"github.com/datawire/dlib/dexec"
"github.com/datawire/dlib/dlog"
)
func getOsMetadata(ctx context.Context) map[string]interface{} {
osMeta := map[string]interface{}{
"os_version": "unknown",
"os_build_version": "unknown",
"os_name": "unknown",
}
cmd := dexec.CommandContext(ctx, "sw_vers")
cmd.DisableLogging = true
if r, err := cmd.Output(); err != nil {
dlog.Warnf(ctx, "Could not get os metadata: %v", err)
} else {
sc := bufio.NewScanner(bytes.NewReader(r))
for sc.Scan() {
fs := strings.Fields(sc.Text())
if len(fs) == 2 {
switch fs[0] {
case "ProductName:":
osMeta["os_name"] = fs[1]
case "ProductVersion:":
osMeta["os_version"] = fs[1]
case "BuildVersion:":
osMeta["os_build_version"] = fs[1]
}
}
}
}
return osMeta
}
| package scout
import (
"context"
"strings"
"github.com/datawire/dlib/dexec"
"github.com/datawire/dlib/dlog"
)
func runSwVers(ctx context.Context, versionName string) string {
cmd := dexec.CommandContext(ctx, "sw_vers", "-"+versionName)
cmd.DisableLogging = true
r, err := cmd.Output()
if err != nil {
dlog.Warnf(ctx, "Could not get os metadata %s: %v", versionName, err)
return "unknown"
}
return strings.TrimSpace(string(r))
}
func getOsMetadata(ctx context.Context) map[string]interface{} {
osMeta := map[string]interface{}{
"os_version": runSwVers(ctx, "productVersion"),
"os_build_version": runSwVers(ctx, "buildVersion"),
"os_name": runSwVers(ctx, "productName"),
}
return osMeta
}
|
Add logging for server-side work completed event | const io = require('socket.io'),
winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = 3031;
winston.info('Rupture real-time service starting');
winston.info('Listening on port ' + PORT);
var socket = io.listen(PORT);
socket.on('connection', function(client) {
winston.info('New connection from client ' + client.id);
client.on('get-work', function() {
winston.info('get-work from client ' + client.id);
client.emit('do-work', {
url: 'https://facebook.com/?breach-test',
amount: 1000,
timeout: 0
});
});
client.on('work-completed', function({work, success, host}) {
winston.info('Client indicates work completed: ', work, success, host);
});
client.on('disconnect', function() {
winston.info('Client ' + client.id + ' disconnected');
});
});
| const io = require('socket.io'),
winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {'timestamp': true});
const PORT = 3031;
winston.info('Rupture real-time service starting');
winston.info('Listening on port ' + PORT);
var socket = io.listen(PORT);
socket.on('connection', function(client) {
winston.info('New connection from client ' + client.id);
client.on('get-work', function() {
winston.info('get-work from client ' + client.id);
client.emit('do-work', {
url: 'https://facebook.com/?breach-test',
amount: 1000,
timeout: 0
});
});
client.on('disconnect', function() {
winston.info('Client ' + client.id + ' disconnected');
});
});
|
Mark as python 3 compatable. | #!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
import os
from setuptools import setup, find_packages
here = os.path.dirname(__file__)
version_file = os.path.join(here, 'src/iptools/__init__.py')
d = {}
execfile(version_file, d)
version = d['__version__']
setup(
name = 'iptools',
version = version,
description = 'Python utilites for manipulating IP addresses',
long_description = "Utilities for manipulating IP addresses including a class that can be used to include CIDR network blocks in Django's INTERNAL_IPS setting.",
url = 'http://python-iptools.googlecode.com',
download_url = '',
author = 'Bryan Davis',
author_email = 'casadebender+iptools@gmail.com',
license = 'BSD',
platforms = ['any',],
package_dir = {'': 'src'},
packages = find_packages('src'),
include_package_data = True,
test_suite='iptools.test_iptools',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Utilities',
'Topic :: Internet',
],
zip_safe=False,
)
| #!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
import os
from setuptools import setup, find_packages
here = os.path.dirname(__file__)
version_file = os.path.join(here, 'src/iptools/__init__.py')
d = {}
execfile(version_file, d)
version = d['__version__']
setup(
name = 'iptools',
version = version,
description = 'Python utilites for manipulating IP addresses',
long_description = "Utilities for manipulating IP addresses including a class that can be used to include CIDR network blocks in Django's INTERNAL_IPS setting.",
url = 'http://python-iptools.googlecode.com',
download_url = '',
author = 'Bryan Davis',
author_email = 'casadebender+iptools@gmail.com',
license = 'BSD',
platforms = ['any',],
package_dir = {'': 'src'},
packages = find_packages('src'),
include_package_data = True,
test_suite='iptools.test_iptools',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities',
'Topic :: Internet',
],
zip_safe=False,
)
|
Fix tests: logs needed config before it was created in first launch | 'use strict'
const _ = require('lodash')
const generateEnv = require('./generateEnv.js')
const setup = (app) => {
generateEnv()
let routes = []
const features = {
config: require('./config'),
env: require('./env'),
history: require('./history'),
horrible: require('./horrible'),
local: require('./local'),
mal: require('./mal'),
news: require('./news'),
nyaa: require('./nyaa'),
openExternal: require('./openExternal'),
seasons: require('./seasons'),
search: require('./search'),
wl: require('./watchList')
}
_.each(features, (feature) => {
_.each(feature, (route) => routes.push(route))
})
// auto update
/* istanbul ignore next */
if (!['KawAnime-test', 'development'].includes(process.env.NODE_ENV)) {
routes = require('./updater')(app, routes)
}
_.each(routes, (route) => route(app))
}
module.exports = setup
| 'use strict'
const _ = require('lodash')
const generateEnv = require('./generateEnv.js')
const features = {
config: require('./config'),
env: require('./env'),
history: require('./history'),
horrible: require('./horrible'),
local: require('./local'),
mal: require('./mal'),
news: require('./news'),
nyaa: require('./nyaa'),
openExternal: require('./openExternal'),
seasons: require('./seasons'),
search: require('./search'),
wl: require('./watchList')
}
let routes = []
const setup = (app) => {
generateEnv()
_.each(features, (feature) => {
_.each(feature, (route) => routes.push(route))
})
// auto update
/* istanbul ignore next */
if (!['KawAnime-test', 'development'].includes(process.env.NODE_ENV)) {
routes = require('./updater')(app, routes)
}
_.each(routes, (route) => route(app))
}
module.exports = setup
|
Fix wide and high entities thresholds and offsets handling | /**
* Check whether an element is in the viewport by
* more than offset px.
*/
export function inViewport (element, options) {
const { top, right, bottom, left, width, height } = element.getBoundingClientRect();
const intersection = {
t: bottom,
r: window.innerWidth - left,
b: window.innerHeight - top,
l: right
};
const threshold = {
x: options.threshold * width,
y: options.threshold * height
};
const verticalCheck = (
intersection.t > (options.offset.top + threshold.y) &&
intersection.b > (options.offset.bottom + threshold.y)
) || (
intersection.t < -options.offset.top &&
intersection.b < -options.offset.bottom
);
const horizontalCheck = (
intersection.r > (options.offset.right + threshold.x) &&
intersection.l > (options.offset.left + threshold.x)
) || (
intersection.r < -options.offset.right &&
intersection.l < -options.offset.left
);
return verticalCheck && horizontalCheck;
}
| /**
* Check whether an element is in the viewport by
* more than offset px.
*/
export function inViewport (element, options) {
const { top, right, bottom, left, width, height } = element.getBoundingClientRect();
const intersection = {
t: bottom,
r: window.innerWidth - left,
b: window.innerHeight - top,
l: right
};
const threshold = {
x: options.threshold * width,
y: options.threshold * height
};
const verticalCheck = (
intersection.t > (options.offset.top + threshold.y) &&
intersection.b > (options.offset.bottom + threshold.y)
) || (
intersection.t < (options.offset.top + threshold.y) &&
intersection.b < (options.offset.bottom + threshold.y)
);
const horizontalCheck = (
intersection.r > (options.offset.right + threshold.x) &&
intersection.l > (options.offset.left + threshold.x)
) || (
intersection.r < (options.offset.right + threshold.x) &&
intersection.l < (options.offset.left + threshold.x)
);
return verticalCheck && horizontalCheck;
}
|
Store the fields in array | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model {
public function __construct() {
parent::__construct();
}
// Return user credentials
public function exist()
{
$config = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$fields = array(
'a.id',
'a.username',
'a.password',
'a.fullname',
'a.email',
'a.emp_id',
'a.emp_no',
'a.supervisor_email',
'b.role_id',
'c.user_type'
);
$query = $this->db->select($fields)
->from('users_tbl AS a')
->join('users_role_tbl AS b', 'a.id = b.user_id', 'INNER')
->join('role_tbl AS c', 'b.role_id = c.id', 'INNER')
->where($config)
->get();
if ($query->num_rows())
{
return $query->row_array();
}
return false;
}
} | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model {
public function __construct() {
parent::__construct();
}
// Return user credentials
public function exist()
{
$config = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$query = $this->db->select('a.id, a.username, a.password, a.fullname, a.email, b.role_id, c.user_type')
->from('users_tbl AS a')
->join('users_role_tbl AS b', 'a.id = b.user_id', 'INNER')
->join('role_tbl AS c', 'b.role_id = c.id', 'INNER')
->where($config)
->get();
if ($query->num_rows())
{
return $query->row_array();
}
return false;
}
} |
Save and load data about corporations using LocalStorageService | app.controller('myCtrl', ['$scope', 'corporations', 'localStorageService', function($scope, corporations, localStorageService) {
$scope.apps = corporations.information();
$scope.selectedFactions = function()
{
var data = localStorageService.get("corporations")
if (data == undefined ) {
var data = shuffle($scope.apps).slice(0,3)
localStorageService.set("corporations", data)
return data
}
else
{
return data
}
}();
$scope.growthFaction = prepareInitialStats($scope.selectedFactions[0], 1)
$scope.valueFaction = prepareInitialStats($scope.selectedFactions[1], 2)
$scope.stableFaction = prepareInitialStats($scope.selectedFactions[2], 3)
$scope.attackTarget = function(faction) {
console.log("You pressed a button!")
}
}]);
app.controller('CorporateController', ['$scope', '$routeParams', 'corporations', function($scope, $routeParams, corporations) {
$scope.faction = corporations.information()[$routeParams.id - 1];
}]);
app.controller('PlayerController', ['$scope', 'localStorageService', function($scope, localStorageService) {
$scope.name = localStorageService.get("name");
$scope.changeName = function(name) {
localStorageService.set("name", name);
$scope.name = name;
}
$scope.attackTarget = function(faction) {
console.log("You pressed a button!")
}
}]); | app.controller('myCtrl', function($scope, corporations) {
$scope.apps = corporations.information();
$scope.selectedFactions = shuffle($scope.apps).slice(0,3)
$scope.growthFaction = prepareInitialStats($scope.selectedFactions[0], 1)
$scope.valueFaction = prepareInitialStats($scope.selectedFactions[1], 2)
$scope.stableFaction = prepareInitialStats($scope.selectedFactions[2], 3)
});
app.controller('CorporateController', ['$scope', '$routeParams', 'corporations', function($scope, $routeParams, corporations) {
$scope.faction = corporations.information()[$routeParams.id - 1];
}]);
app.controller('PlayerController', ['$scope', 'localStorageService', function($scope, localStorageService) {
$scope.name = localStorageService.get("name");
$scope.changeName = function(name) {
localStorageService.set("name", name);
$scope.name = name;
}
}]); |
Include the meta-python versions in the classifiers | import wsgi_intercept
from setuptools import setup, find_packages
CLASSIFIERS = """
Environment :: Web Environment
Intended Audience :: Developers
License :: OSI Approved :: MIT License
Operating System :: OS Independent
Programming Language :: Python :: 2
Programming Language :: Python :: 2.6
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Topic :: Internet :: WWW/HTTP :: WSGI
Topic :: Software Development :: Testing
""".strip().splitlines()
META = {
'name': 'wsgi_intercept',
'version': wsgi_intercept.__version__,
'author': 'Titus Brown, Kumar McMillan, Chris Dent',
'author_email': 'cdent@peermore.com',
'description': 'wsgi_intercept installs a WSGI application in place of a real URI for testing.',
# What will the name be?
'url': 'http://pypi.python.org/pypi/wsgi_intercept',
'long_description': wsgi_intercept.__doc__,
'license': 'MIT License',
'classifiers': CLASSIFIERS,
'packages': find_packages(),
'extras_require': {
'testing': [
'pytest>=2.4',
'httplib2',
'requests>=2.0.1'
],
},
}
if __name__ == '__main__':
setup(**META)
|
import wsgi_intercept
from setuptools import setup, find_packages
CLASSIFIERS = """
Environment :: Web Environment
Intended Audience :: Developers
License :: OSI Approved :: MIT License
Operating System :: OS Independent
Programming Language :: Python :: 2.6
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3.3
Topic :: Internet :: WWW/HTTP :: WSGI
Topic :: Software Development :: Testing
""".strip().splitlines()
META = {
'name': 'wsgi_intercept',
'version': wsgi_intercept.__version__,
'author': 'Titus Brown, Kumar McMillan, Chris Dent',
'author_email': 'cdent@peermore.com',
'description': 'wsgi_intercept installs a WSGI application in place of a real URI for testing.',
# What will the name be?
'url': 'http://pypi.python.org/pypi/wsgi_intercept',
'long_description': wsgi_intercept.__doc__,
'license': 'MIT License',
'classifiers': CLASSIFIERS,
'packages': find_packages(),
'extras_require': {
'testing': [
'pytest>=2.4',
'httplib2',
'requests>=2.0.1'
],
},
}
if __name__ == '__main__':
setup(**META)
|
Fix siteId retrieving from window. | /* eslint-disable no-underscore-dangle, no-undef */
import { takeEvery } from 'redux-saga';
import { put, select, call, take } from 'redux-saga/effects';
import * as types from '../types';
import * as actions from '../actions';
import * as selectors from '../selectors';
export function* siteIdChangedSaga(action) {
const newSiteId = action.siteId || action.payload.location.query.siteId;
const currentSiteId = yield select(selectors.getSiteId);
if (newSiteId !== currentSiteId) yield put(actions.siteIdChanged({ siteId: newSiteId }));
}
export function* previewSaga() {
yield put(actions.isPreview());
}
export default function* routerSagas() {
if (window.__woronaSiteId__) {
yield take(types.ROUTER_DID_CHANGE);
yield call(siteIdChangedSaga, { siteId: window.__woronaSiteId__ });
}
yield [
takeEvery(({ type, payload }) =>
type === types.ROUTER_DID_CHANGE && payload.location.query.preview === 'true',
previewSaga),
takeEvery(({ type, payload }) =>
type === types.ROUTER_DID_CHANGE && payload.location.query.siteId, siteIdChangedSaga),
];
}
| /* eslint-disable no-underscore-dangle, no-undef */
import { takeEvery } from 'redux-saga';
import { put, select, call } from 'redux-saga/effects';
import * as types from '../types';
import * as actions from '../actions';
import * as selectors from '../selectors';
export function* siteIdChangedSaga(action) {
const newSiteId = action.siteId || action.payload.location.query.siteId;
const currentSiteId = yield select(selectors.getSiteId);
if (newSiteId !== currentSiteId) yield put(actions.siteIdChanged({ siteId: newSiteId }));
}
export function* previewSaga() {
yield put(actions.isPreview());
}
export default function* routerSagas() {
if (window.__woronaSiteId__) yield call(siteIdChangedSaga, { siteId: window.__woronaSiteId__ });
yield [
takeEvery(({ type, payload }) =>
type === types.ROUTER_DID_CHANGE && payload.location.query.preview === 'true',
previewSaga),
takeEvery(({ type, payload }) =>
type === types.ROUTER_DID_CHANGE && payload.location.query.siteId, siteIdChangedSaga),
];
}
|
Update tests to reflect better seeding.
We have to lower our expectations a bit. | package algoholic
import "testing"
const BENCHMARK_LENGTH = 10
func TestFisherYatesShufflesEvenly(t *testing.T) {
// Set an arbitrary maximum error from expectation - We expect each number to occur within
// 1% of the probability in a list of length 10 after 1e6 iterations.
// TODO: Determine maximum error mathematically.
checkShufflesEvenly(t, ShuffleFisherYates, 10, 1e6, 0.01)
}
func TestRandomOrderShuffleShufflesEvenly(t *testing.T) {
// Set an arbitrary maximum error from expectation - We expect each number to occur within
// 1.1% of the probability in a list of length 10 after 1e6 iterations.
// TODO: Determine maximum error mathematically.
checkShufflesEvenly(t, ShuffleRandomSort, 10, 1e6, 0.011)
}
func BenchmarkFisherYatesShuffle(b *testing.B) {
benchmarkShuffle(b, BENCHMARK_LENGTH, ShuffleFisherYates)
}
func BenchmarkRandomSortShuffle(b *testing.B) {
benchmarkShuffle(b, BENCHMARK_LENGTH, ShuffleRandomSort)
}
| package algoholic
import "testing"
const BENCHMARK_LENGTH = 10
func TestFisherYatesShufflesEvenly(t *testing.T) {
// Set an arbitrary maximum error from expectation - We expect each number to occur within
// 0.7% of the probability in a list of length 10 after 1e6 iterations.
// TODO: Determine maximum error mathematically.
checkShufflesEvenly(t, ShuffleFisherYates, 10, 1e6, 0.007)
}
func TestRandomOrderShuffleShufflesEvenly(t *testing.T) {
// Set an arbitrary maximum error from expectation - We expect each number to occur within
// 1% of the probability in a list of length 10 after 1e6 iterations.
// TODO: Determine maximum error mathematically.
checkShufflesEvenly(t, ShuffleRandomSort, 10, 1e6, 0.01)
}
func BenchmarkFisherYatesShuffle(b *testing.B) {
benchmarkShuffle(b, BENCHMARK_LENGTH, ShuffleFisherYates)
}
func BenchmarkRandomSortShuffle(b *testing.B) {
benchmarkShuffle(b, BENCHMARK_LENGTH, ShuffleRandomSort)
}
|
Fix regex to only allow uppercased letters for the the first 2 characters. | import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
public class RobotTest {
private static final String EXPECTED_ROBOT_NAME_PATTERN = "[A-Z]{2}\\d{3}";
private final Robot robot = new Robot();
@Test
public void hasName() {
assertIsValidName(robot.getName());
}
@Test
public void differentRobotsHaveDifferentNames() {
assertThat(robot.getName(), not(equalTo(new Robot().getName())));
}
@Test
public void resetName() {
final String name = robot.getName();
robot.reset();
final String name2 = robot.getName();
assertThat(name, not(equalTo(name2)));
assertIsValidName(name2);
}
private static void assertIsValidName(String name) {
assertThat(name.matches(EXPECTED_ROBOT_NAME_PATTERN), is(true));
}
}
| import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
public class RobotTest {
private static final String EXPECTED_ROBOT_NAME_PATTERN = "\\w{2}\\d{3}";
private final Robot robot = new Robot();
@Test
public void hasName() {
assertIsValidName(robot.getName());
}
@Test
public void differentRobotsHaveDifferentNames() {
assertThat(robot.getName(), not(equalTo(new Robot().getName())));
}
@Test
public void resetName() {
final String name = robot.getName();
robot.reset();
final String name2 = robot.getName();
assertThat(name, not(equalTo(name2)));
assertIsValidName(name2);
}
private static void assertIsValidName(String name) {
assertThat(name.matches(EXPECTED_ROBOT_NAME_PATTERN), is(true));
}
}
|
Disable sequelize logging by default | module.exports = {
connect: function(Sequelize) {
if (typeof Sequelize === 'undefined') {
throw new Error(
'You must pass sequelize as an argument to the sequelize-heroku connect method (see README).'
);
}
var url, options;
// Look for ClearDB MySQL Add-on
if (process.env.CLEARDB_DATABASE_URL) {
url = process.env.CLEARDB_DATABASE_URL;
options = {
dialect: 'mysql',
protocol: 'mysql',
};
}
// Else, look for Heroku Postgres
else if (process.env.DATABASE_URL) {
url = process.env.DATABASE_URL;
options = {
dialect: 'postgres',
protocol: 'postgres',
dialectOptions: {
ssl: true,
},
};
}
if (url) {
options.logging = false;
sequelize = new Sequelize(url, options);
return sequelize;
}
return false;
},
};
| module.exports = {
connect: function(Sequelize) {
if (typeof Sequelize === 'undefined') {
throw new Error(
'You must pass sequelize as an argument to the sequelize-heroku connect method (see README).'
);
}
var url, options;
// Look for ClearDB MySQL Add-on
if (process.env.CLEARDB_DATABASE_URL) {
url = process.env.CLEARDB_DATABASE_URL;
options = {
dialect: 'mysql',
protocol: 'mysql',
};
}
// Else, look for Heroku Postgres
else if (process.env.DATABASE_URL) {
url = process.env.DATABASE_URL;
options = {
dialect: 'postgres',
protocol: 'postgres',
dialectOptions: {
ssl: true,
},
};
}
if (url) {
sequelize = new Sequelize(url, options);
return sequelize;
}
return false;
},
};
|
Rename config to req to avoid confusion | 'use strict';
angular.module('offlineMode', [])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
})
.factory('httpInterceptor', function ($q) {
var OFFLINE = location.search.indexOf('offline=true') > -1,
_config = {
OFFLINE_DATA_PATH: '/offline_data',
API_PATH: '/api'
};
return {
request: function(req) {
if (OFFLINE && req) {
if (req.url.indexOf(_config.API_PATH) === 0) {
var path = req.url.substring(_config.API_PATH.length);
req.url = _config.OFFLINE_DATA_PATH + path + '.' + req.method.toLowerCase() + '.json';
}
}
return req || $q.when(req);
},
config: _config
};
}
);
| 'use strict';
angular.module('offlineMode', [])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
})
.factory('httpInterceptor', function ($q) {
var OFFLINE = location.search.indexOf('offline=true') > -1,
_config = {
OFFLINE_DATA_PATH: '/offline_data',
API_PATH: '/api'
};
return {
request: function(config) {
if (OFFLINE && config) {
if (config.url.indexOf(_config.API_PATH) === 0) {
var path = config.url.substring(_config.API_PATH.length);
config.url = _config.OFFLINE_DATA_PATH + path + '.' + config.method.toLowerCase() + '.json';
}
}
return config || $q.when(config);
},
config: _config
};
}
);
|
Reset to upstream master instead of rebasing during deployment | from fabric.api import * # noqa
env.hosts = [
'104.131.30.135',
]
env.user = "root"
env.directory = "/home/django/api.freemusic.ninja"
env.deploy_path = "/home/django/django_project"
def deploy():
with cd(env.directory):
run("git reset --hard origin/master")
sudo("pip3 install -r requirements.txt")
sudo("python3 manage.py collectstatic --noinput", user='django')
sudo("python3 manage.py migrate --noinput", user='django')
run("rm -f {deploy_path}".format(deploy_path=env.deploy_path))
run("ln -s {project_path} {deploy_path}".format(
project_path=env.directory, deploy_path=env.deploy_path))
run("service gunicorn restart")
def dbshell():
with cd(env.directory):
sudo("python3 manage.py dbshell", user='django')
def shell():
with cd(env.directory):
sudo("python3 manage.py shell", user='django')
def migrate():
with cd(env.directory):
sudo("python3 manage.py migrate", user='django')
def gunicorn_restart():
run("service gunicorn restart")
| from fabric.api import * # noqa
env.hosts = [
'104.131.30.135',
]
env.user = "root"
env.directory = "/home/django/api.freemusic.ninja"
env.deploy_path = "/home/django/django_project"
def deploy():
with cd(env.directory):
run("git pull --rebase")
sudo("pip3 install -r requirements.txt")
sudo("python3 manage.py collectstatic --noinput", user='django')
sudo("python3 manage.py migrate --noinput", user='django')
run("rm -f {deploy_path}".format(deploy_path=env.deploy_path))
run("ln -s {project_path} {deploy_path}".format(
project_path=env.directory, deploy_path=env.deploy_path))
run("service gunicorn restart")
def dbshell():
with cd(env.directory):
sudo("python3 manage.py dbshell", user='django')
def shell():
with cd(env.directory):
sudo("python3 manage.py shell", user='django')
def migrate():
with cd(env.directory):
sudo("python3 manage.py migrate", user='django')
def gunicorn_restart():
run("service gunicorn restart")
|
Remove reference to manager that no longer exists | from modularodm import Q
PREREG_CAMPAIGNS = {
'prereg': 'Prereg Challenge',
'erpc': 'Election Research Preacceptance Competition',
}
def drafts_for_user(user, campaign):
from osf import models # noqa
PREREG_CHALLENGE_METASCHEMA = get_prereg_schema(campaign)
return models.DraftRegistration.objects.filter(
registration_schema=PREREG_CHALLENGE_METASCHEMA,
approval=None,
registered_node=None,
branched_from__in=models.AbstractNode.objects.filter(
is_deleted=False,
contributor__admin=True,
contributor__user=user).values_list('id', flat=True))
def get_prereg_schema(campaign='prereg'):
from website.models import MetaSchema # noqa
if campaign not in PREREG_CAMPAIGNS:
raise ValueError('campaign must be one of: {}'.format(', '.join(PREREG_CAMPAIGNS.keys())))
schema_name = PREREG_CAMPAIGNS[campaign]
return MetaSchema.find_one(
Q('name', 'eq', schema_name) &
Q('schema_version', 'eq', 2)
)
| from modularodm import Q
PREREG_CAMPAIGNS = {
'prereg': 'Prereg Challenge',
'erpc': 'Election Research Preacceptance Competition',
}
def drafts_for_user(user, campaign):
from osf import models # noqa
PREREG_CHALLENGE_METASCHEMA = get_prereg_schema(campaign)
return models.DraftRegistration.objects.filter(
registration_schema=PREREG_CHALLENGE_METASCHEMA,
approval=None,
registered_node=None,
branched_from__in=models.AbstractNode.subselect.filter(
is_deleted=False,
contributor__admin=True,
contributor__user=user).values_list('id', flat=True))
def get_prereg_schema(campaign='prereg'):
from website.models import MetaSchema # noqa
if campaign not in PREREG_CAMPAIGNS:
raise ValueError('campaign must be one of: {}'.format(', '.join(PREREG_CAMPAIGNS.keys())))
schema_name = PREREG_CAMPAIGNS[campaign]
return MetaSchema.find_one(
Q('name', 'eq', schema_name) &
Q('schema_version', 'eq', 2)
)
|
Revert major version, bump minor version 1.1.0 | #!/usr/bin/env python
from distutils.core import setup
with open('README.rst') as f:
long_description = f.read()
setup(
name='pylint-venv',
version='1.1.0',
description='pylint-venv provides a Pylint init-hook to use the same '
'Pylint installation with different virtual environments.',
long_description=long_description,
author='Jan Gosmann, Federico Jaramillo',
author_email='jan@hyper-world.de, federicojaramillom@gmail.com',
url='https://github.com/jgosmann/pylint-venv/',
py_modules=['pylint_venv'],
provides=['pylint_venv'],
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Software Development',
]
)
| #!/usr/bin/env python
from distutils.core import setup
with open('README.rst') as f:
long_description = f.read()
setup(
name='pylint-venv',
version='2.0.0.dev0',
description='pylint-venv provides a Pylint init-hook to use the same '
'Pylint installation with different virtual environments.',
long_description=long_description,
author='Jan Gosmann, Federico Jaramillo',
author_email='jan@hyper-world.de, federicojaramillom@gmail.com',
url='https://github.com/jgosmann/pylint-venv/',
py_modules=['pylint_venv'],
provides=['pylint_venv'],
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Software Development',
]
)
|
Optimize compiled references to the container itself | <?php
declare(strict_types=1);
namespace WoohooLabs\Zen\Container\Definition;
use WoohooLabs\Zen\Container\DefinitionCompilation;
class SelfDefinition extends AbstractDefinition
{
public function __construct(string $className)
{
parent::__construct($className, "", false, false, false, 0);
}
public function increaseReferenceCount(string $parentId = ""): DefinitionInterface
{
return $this;
}
public function needsDependencyResolution(): bool
{
return false;
}
public function resolveDependencies(): DefinitionInterface
{
return $this;
}
public function getClassDependencies(): array
{
return [];
}
public function compile(DefinitionCompilation $compilation, int $indentationLevel, bool $inline = false): string
{
$indent = $this->indent($indentationLevel);
if ($inline) {
return "\$this";
}
return "${indent}return \$this;\n";
}
}
| <?php
declare(strict_types=1);
namespace WoohooLabs\Zen\Container\Definition;
use WoohooLabs\Zen\Container\DefinitionCompilation;
class SelfDefinition extends AbstractDefinition
{
public function __construct(string $className)
{
parent::__construct($className, "", true, false, false, 0);
}
public function needsDependencyResolution(): bool
{
return false;
}
public function resolveDependencies(): DefinitionInterface
{
return $this;
}
public function getClassDependencies(): array
{
return [];
}
public function compile(DefinitionCompilation $compilation, int $indentationLevel, bool $inline = false): string
{
$indent = $this->indent($indentationLevel);
if ($inline) {
return "\$this";
}
return "${indent}return \$this;\n";
}
}
|
Change local to heroku host | var wpi = require("wiring-pi"),
http = require("http"),
port = 5000,
host = "https://portal-ns.herokuapp.com",
method = "POST";
var IRin = 12;
var cut_video = true;
wpi.setup("phys");
wpi.pinMode(IRin, wpi.INPUT);
wpi.pullUpDnControl(IRin, wpi.PUD_DOWN);
wpi.wiringPiISR(IRin, wpi.INT_EDGE_BOTH, function(){
//This part stop all the LOCAL tracks (Audio and Video)
if(!cut_video){
http.request({
method:method,
host:host,
port: port,
path: "/on"
}).end();
}else{
http.request({
method:method,
host:host,
port: port,
path: "/off"
}).end();
}
cut_video = !cut_video;
});
| var wpi = require("wiring-pi"),
http = require("http"),
port = 5000,
host = "localhost",
method = "POST";
var IRin = 12;
var cut_video = true;
wpi.setup("phys");
wpi.pinMode(IRin, wpi.INPUT);
wpi.pullUpDnControl(IRin, wpi.PUD_DOWN);
wpi.wiringPiISR(IRin, wpi.INT_EDGE_BOTH, function(){
//This part stop all the LOCAL tracks (Audio and Video)
if(!cut_video){
http.request({
method:method,
host:host,
port: port,
path: "/on"
}).end();
}else{
http.request({
method:method,
host:host,
port: port,
path: "/off"
}).end();
}
cut_video = !cut_video;
});
|
Update Frig valueLink From Hue Slider | let React = require("react")
let Colr = require('colr')
let draggable = require('./higher_order_components/draggable')
let {div} = React.DOM
@draggable
export default class extends React.Component {
static defaultProps = Object.assign(require("../../default_props.js"))
_updatePosition(saturation, value){
let rect = React.findDOMNode(this).getBoundingClientRect()
let hue = this.getScaledValue((rect.bottom - value) / rect.height)
let color = Colr.fromHsv(hue, saturation, value)
this.props.valueLink.requestChange(color.toHex())
}
render() {
let [hsv] = this.getHSV()
return div({
className: "slider vertical",
onMouseDown: this.startUpdates.bind(this),
onTouchStart: this.startUpdates.bind(this),
},
div({
className: "track",
}),
div({
className: "pointer",
style: {
"bottom": this.getPercentageValue(hsv.h),
},
})
)
}
} | let React = require("react")
let draggable = require('./higher_order_components/draggable')
let {div} = React.DOM
@draggable
export default class extends React.Component {
static defaultProps = Object.assign(require("../../default_props.js"))
_updatePosition(clientX, clientY) {
let rect = React.findDOMNode(this).getBoundingClientRect()
let value = this.getScaledValue((rect.bottom - clientY) / rect.height)
this.props.valueLink.requestChange(value)
}
render() {
return div({
className: "slider vertical",
onMouseDown: this.startUpdates.bind(this),
onTouchStart: this.startUpdates.bind(this),
},
div({
className: "track",
}),
div({
className: "pointer",
style: {
"bottom": this.getPercentageValue(this.props.valueLink.value),
},
})
)
}
} |
Add second argument to addResource for container | // add-resource.js
/*
Copyright (c) 2011 Talis Inc, Some Rights Reserved
Licensed under the Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0
*/
(function($){
calli.addTemplate = calli.addResource = function(event, container) {
event = calli.fixEvent(event);
var node = container ? $(container) : $(event.target);
var rel = node.closest('[data-add]');
var add = rel.attr("data-add");
if (!add)
return true;
jQuery.get(add, function(data) {
var clone = $(data).clone();
var child = clone.children("[about],[typeof],[typeof=''],[resource],[property]");
if (node.attr("data-add")) {
node.append(child);
} else {
node.before(child);
}
child.find(':input').andSelf().filter(':input:first').focus();
}, 'text');
return false;
};
})(jQuery);
| // add-resource.js
/*
Copyright (c) 2011 Talis Inc, Some Rights Reserved
Licensed under the Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0
*/
(function($){
calli.addTemplate = calli.addResource = function(event) {
event = calli.fixEvent(event);
var node = event.target;
var rel = $(node).add($(node).parents()).filter('[data-add]');
var add = rel.attr("data-add");
if (!add)
return true;
jQuery.get(add, function(data) {
var clone = $(data).clone();
var child = clone.children("[about],[typeof],[typeof=''],[resource],[property]");
if ($(node).attr("data-add")) {
$(node).append(child);
} else {
$(node).before(child);
}
child.find(':input').andSelf().filter(':input:first').focus();
}, 'text');
return false;
};
})(jQuery);
|
Fix a multiple execution in event handlers
As a bonus, also bind to the context, even if not used, to allow
the handler to be unbound using the context too. | (function(Backbone) {
_.extend(Backbone.Events, {
// Bind an event only once. When executed for the first time, it would
// remove itself from the callbacks list.
once: function(events, callback, context) {
var boundOff = _.bind(this.off, this);
var oneOffCallback = _.once(function() {
boundOff(events, oneOffCallback);
callback.apply(context, arguments);
});
return this.on(events, oneOffCallback, context);
}
});
// Mix `Backbone.Events` again so our `once` method gets picked up. By the
// time the classes first mixed `Backbone.Events`, it was not defined.
_.each(['Model', 'Collection', 'Router', 'View', 'History'], function(kind) {
_.extend(Backbone[kind].prototype, Backbone.Events);
});
}).call(this, Backbone);
| (function(Backbone) {
_.extend(Backbone.Events, {
// Bind an event only once. When executed for the first time, it would
// remove itself from the callbacks list.
once: function(events, callback, context) {
var boundOff = _.bind(this.off, this);
var oneOffCallback = function() {
boundOff(events, oneOffCallback);
callback.apply(context, arguments);
};
return this.on(events, oneOffCallback);
}
});
// Mix `Backbone.Events` again so our `once` method gets picked up. By the
// time the classes first mixed `Backbone.Events`, it was not defined.
_.each(['Model', 'Collection', 'Router', 'View', 'History'], function(kind) {
_.extend(Backbone[kind].prototype, Backbone.Events);
});
}).call(this, Backbone); |
Add generic method to create a new user | package gapi
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"github.com/grafana/grafana/pkg/api/dtos"
)
func (c *Client) CreateUserForm(settings dtos.AdminCreateUserForm) error {
data, err := json.Marshal(settings)
req, err := c.newRequest("POST", "/api/admin/users", bytes.NewBuffer(data))
if err != nil {
return err
}
resp, err := c.Do(req)
if err != nil {
return err
}
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New(resp.Status)
}
return err
}
func (c *Client) CreateUser(email, login, name, password string) error {
return c.CreateUserForm(dtos.AdminCreateUserForm{email, login, name, password})
}
func (c *Client) DeleteUser(id int64) error {
req, err := c.newRequest("DELETE", fmt.Sprintf("/api/admin/users/%d", id), nil)
if err != nil {
return err
}
resp, err := c.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New(resp.Status)
}
return err
}
| package gapi
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"github.com/grafana/grafana/pkg/api/dtos"
)
func (c *Client) CreateUserForm(settings dtos.AdminCreateUserForm) error {
data, err := json.Marshal(settings)
req, err := c.newRequest("POST", "/api/admin/users", bytes.NewBuffer(data))
if err != nil {
return err
}
resp, err := c.Do(req)
if err != nil {
return err
}
data, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New(resp.Status)
}
return err
}
func (c *Client) DeleteUser(id int64) error {
req, err := c.newRequest("DELETE", fmt.Sprintf("/api/admin/users/%d", id), nil)
if err != nil {
return err
}
resp, err := c.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New(resp.Status)
}
return err
}
|
Refactor react gulp code into its own task | var gulp = require('gulp');
var react = require('gulp-react');
var git = require('gulp-git');
var fs = require('fs');
var shell = require('gulp-shell')
gulp.task('brew', function () {
if (fs.existsSync('homebrew')) {
git.pull('origin', 'master', { cwd: 'homebrew' }, function (err) {
if (err) throw err;
});
} else {
git.clone('https://github.com/Homebrew/homebrew', function (err) {
if (err) throw err;
});
}
});
gulp.task('collect', shell.task([
'./bin/collect homebrew'
]));
gulp.task('info', shell.task([
'./bin/info homebrew'
]));
gulp.task('rank', shell.task([
'./bin/rank'
]));
gulp.task('dump', shell.task([
'./bin/dump > dist/formulae.json'
]));
gulp.task('copy', function () {
return gulp.src('src/index.html')
.pipe(gulp.dest('dist'))
})
gulp.task('react', function () {
return gulp.src('src/index.js')
.pipe(react())
.pipe(gulp.dest('dist'));
})
gulp.task('default', [ 'brew', 'collect', 'info', 'rank', 'dump', 'copy', 'react' ], function () {
});
| var gulp = require('gulp');
var react = require('gulp-react');
var git = require('gulp-git');
var fs = require('fs');
var shell = require('gulp-shell')
gulp.task('brew', function () {
if (fs.existsSync('homebrew')) {
git.pull('origin', 'master', { cwd: 'homebrew' }, function (err) {
if (err) throw err;
});
} else {
git.clone('https://github.com/Homebrew/homebrew', function (err) {
if (err) throw err;
});
}
});
gulp.task('collect', shell.task([
'./bin/collect homebrew'
]));
gulp.task('info', shell.task([
'./bin/info homebrew'
]));
gulp.task('rank', shell.task([
'./bin/rank'
]));
gulp.task('dump', shell.task([
'./bin/dump > dist/formulae.json'
]));
gulp.task('copy', function () {
return gulp.src('src/index.html')
.pipe(gulp.dest('dist'))
})
gulp.task('default', [ 'brew', 'collect', 'info', 'rank', 'dump', 'copy' ], function () {
return gulp.src('src/index.js')
.pipe(react())
.pipe(gulp.dest('dist'));
});
|
Return next fiscal year in YYYY format | // moment-fquarter.js
// version : 0.3
// author : Rob Allen
// license : MIT
// github.com/robgallen/moment-fquarter
(function () {
function onload(moment) {
moment.fn.fquarter = function (startMonth) {
var adjustedDate, quarter, year, nextYear;
startMonth = startMonth || 4; // default is April
if (startMonth > 1) {
adjustedDate = this.subtract("months", startMonth - 1);
nextYear = "/" + adjustedDate.clone().add("years", 1).format("YYYY");
} else {
adjustedDate = this;
nextYear = "";
}
quarter = Math.ceil((adjustedDate.month() + 1.0) / 3.0);
year = adjustedDate.year();
return {quarter: quarter, year: year, nextYear: nextYear}
};
return moment;
}
if (typeof define === "function" && define.amd) {
define("moment-fquarter", ["moment"], onload);
} else if (typeof module !== "undefined") {
module.exports = onload(require("moment"));
} else if (typeof window !== "undefined" && window.moment) {
onload(window.moment);
}
}).apply(this);
| // moment-fquarter.js
// version : 0.3
// author : Rob Allen
// license : MIT
// github.com/robgallen/moment-fquarter
(function () {
function onload(moment) {
moment.fn.fquarter = function (startMonth) {
var adjustedDate, quarter, year, nextYear;
startMonth = startMonth || 4; // default is April
if (startMonth > 1) {
adjustedDate = this.subtract("months", startMonth - 1);
nextYear = "/" + adjustedDate.clone().add("years", 1).format("YY");
} else {
adjustedDate = this;
nextYear = "";
}
quarter = Math.ceil((adjustedDate.month() + 1.0) / 3.0);
year = adjustedDate.year();
return {quarter: quarter, year: year, nextYear: year}
};
return moment;
}
if (typeof define === "function" && define.amd) {
define("moment-fquarter", ["moment"], onload);
} else if (typeof module !== "undefined") {
module.exports = onload(require("moment"));
} else if (typeof window !== "undefined" && window.moment) {
onload(window.moment);
}
}).apply(this);
|
Update the home screen greeting sometimes | const Marionette = require('backbone.marionette');
const HomeCardsView = require('./HomeCardsView.js');
module.exports = class HomeCapabilityView extends Marionette.View {
template = Templates['capabilities/home/home'];
className() {
return 'home-capability';
}
regions() {
return {cards: '.cards-container'};
}
initialize() {
// Update the greeting...
this.refreshInterval = setInterval(this.render.bind(this), 1000 * 60 * 5);
}
serializeData() {
const hour = (new Date()).getHours();
return {
greeting: (hour < 4 || hour >= 19) ? 'Good evening' :
((hour < 12) ? 'Good morning' : 'Good afternoon')
};
}
onRender() {
this.showChildView('cards',
new HomeCardsView({collection: window.app.cards}));
}
onDestroy() {
clearInterval(this.refreshInterval);
}
}
| const Marionette = require('backbone.marionette');
const HomeCardsView = require('./HomeCardsView.js');
module.exports = class HomeCapabilityView extends Marionette.View {
template = Templates['capabilities/home/home'];
className() {
return 'home-capability';
}
regions() {
return {cards: '.cards-container'};
}
serializeData() {
const hour = (new Date()).getHours();
// XXX Force this to update occasionally
return {
greeting: (hour < 4 || hour >= 19) ? 'Good evening.' :
((hour < 12) ? 'Good morning.' : 'Good afternoon.')
};
}
onRender() {
this.showChildView('cards',
new HomeCardsView({collection: window.app.cards}));
}
}
|
Update RAML Cop version requirement to 1.0.0 | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 1.0.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
| #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ethan Zimmerman,,,
# Copyright (c) 2014 Ethan Zimmerman,,,
#
# License: MIT
#
"""This module exports the RamlCop plugin class."""
from SublimeLinter.lint import NodeLinter
class RamlCop(NodeLinter):
"""Provides an interface to raml-cop."""
syntax = 'raml'
cmd = 'raml-cop --no-color'
version_requirement = '>= 0.2.0'
regex = (
r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] '
r'(?:(?P<warning>WARNING)|(?P<error>ERROR)) '
r'(?P<message>.+)'
)
line_col_base = (0, 0)
|
BAP-12009: Create command oro:debug:condition
- CR fixes | <?php
namespace Oro\Bundle\ActionBundle\Tests\Unit\Command;
use Oro\Bundle\ActionBundle\Command\DebugConditionCommand;
class DebugConditionCommandTest extends AbstractDebugCommandTestCase
{
public function testConfigure()
{
$this->assertNotEmpty($this->command->getDescription());
$this->assertNotEmpty($this->command->getHelp());
$this->assertEquals(DebugConditionCommand::COMMAND_NAME, $this->command->getName());
}
/**
* {@inheritdoc}
*/
protected function getFactoryServiceId()
{
return DebugConditionCommand::FACTORY_SERVICE_ID;
}
/**
* {@inheritdoc}
*/
protected function getArgumentName()
{
return DebugConditionCommand::ARGUMENT_NAME;
}
/**
* {@inheritdoc}
*/
protected function getCommandInstance()
{
return new DebugConditionCommand();
}
}
| <?php
namespace Oro\Bundle\ActionBundle\Tests\Unit\Command;
use Oro\Bundle\ActionBundle\Command\DebugConditionCommand;
class DebugConditionCommandTest extends AbstractDebugCommandTestCase
{
public function testConfigure()
{
$this->assertNotEmpty($this->command->getDescription());
$this->assertNotEmpty($this->command->getHelp());
$this->assertEquals(DebugConditionCommand::COMMAND_NAME, $this->command->getName());
}
/**
* {@inheritdoc}
*/
public function getFactoryServiceId()
{
return DebugConditionCommand::FACTORY_SERVICE_ID;
}
/**
* {@inheritdoc}
*/
public function getArgumentName()
{
return DebugConditionCommand::ARGUMENT_NAME;
}
/**
* {@inheritdoc}
*/
public function getCommandInstance()
{
return new DebugConditionCommand();
}
}
|
Fix test: Array merge accepts only arrays. | <?php
namespace Mimic\Test;
use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;
/**
* Unit Test for partialRight Mimic library function.
*
* @since 0.1.0
*/
class PartialRightFuncTest extends PHPUnit_Framework_TestCase {
/**
* @covers ::Mimic\Functional\partialRight
*/
public function testInvokeIf_InvokeTrue() {
$callback = F\partialRight('\Mimic\Functional\invokeIf', new Fake\InvokeTrue);
$this->assertTrue($callback('exists'));
$this->assertEquals(array(1, 2, 3), $callback('with', array(1, 2, 3)));
}
/**
* @covers ::Mimic\Functional\partialRight
*/
public function testArrayMerge() {
$expected = array(1, 2, 3, 4, 5, 6);
$callback = F\partialRight('array_merge', array(1, 2, 3));
$this->assertEquals($expected, $callback(array(4, 5, 6)));
}
}
| <?php
namespace Mimic\Test;
use PHPUnit_Framework_TestCase;
use Mimic\Functional as F;
/**
* Unit Test for partialRight Mimic library function.
*
* @since 0.1.0
*/
class PartialRightFuncTest extends PHPUnit_Framework_TestCase {
/**
* @covers ::Mimic\Functional\partialRight
*/
public function testInvokeIf_InvokeTrue() {
$callback = F\partialRight('\Mimic\Functional\invokeIf', new Fake\InvokeTrue);
$this->assertTrue($callback('exists'));
$this->assertEquals(array(1, 2, 3), $callback('with', array(1, 2, 3)));
}
/**
* @covers ::Mimic\Functional\partialRight
*/
public function testArrayMerge() {
$expected = array(1, 2, 3, 4, 5, 6);
$callback = F\partialRight('array_merge', array(1, 2, 3));
$this->assertEquals($expected, $callback(4, 5, 6));
}
}
|
Make anonymous functions static where possible | <?php
declare(strict_types=1);
namespace Inphest\MetaTests;
use Exception;
use Inphest\Assert;
use function Inphest\test;
use TypeError;
$sameData = [
'1 === 1' => [1, 1],
'abc === abc' => ['abc', 'abc'],
'[] === []' => [[], []],
'true === true' => [true, true],
'false === false' => [false, false],
'$this === $this' => [$this, $this],
];
test('`same` works correctly', static function (Assert $assert, $expected, $actual): void {
$assert->same($expected, $actual);
})->with($sameData);
test('invoke works correctly', static function (Assert $assert, $expected, $actual): void {
$assert($expected === $actual);
})->with($sameData);
test('throws (with exception)', static function (Assert $assert): void {
$assert->throws(static function (): void {
throw new Exception('oh no');
}, new Exception('oh no'));
});
test('throws (with error)', static function (Assert $assert): void {
$assert->throws(static function (): void {
throw new TypeError('bad');
}, new TypeError('bad'));
});
| <?php
declare(strict_types=1);
namespace Inphest\MetaTests;
use Exception;
use Inphest\Assert;
use function Inphest\test;
use TypeError;
$sameData = [
'1 === 1' => [1, 1],
'abc === abc' => ['abc', 'abc'],
'[] === []' => [[], []],
'true === true' => [true, true],
'false === false' => [false, false],
'$this === $this' => [$this, $this],
];
test('`same` works correctly', static function (Assert $assert, $expected, $actual): void {
$assert->same($expected, $actual);
})->with($sameData);
test('invoke works correctly', function (Assert $assert, $expected, $actual): void {
$assert($expected === $actual);
})->with($sameData);
test('throws (with exception)', function (Assert $assert): void {
$assert->throws(function (): void {
throw new Exception('oh no');
}, new Exception('oh no'));
});
test('throws (with error)', function (Assert $assert): void {
$assert->throws(function (): void {
throw new TypeError('bad');
}, new TypeError('bad'));
});
|
Update default value of confirmation code | <?php
use Illuminate\Database\Migrations\Migration;
class ConfideSetupUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Creates the users table
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('username');
$table->string('email');
$table->string('password');
$table->string('confirmation_code')->default(0);
$table->boolean('confirmed')->default(false);
$table->timestamps();
});
// Creates password reminders table
Schema::create('password_reminders', function($t)
{
$t->string('email');
$t->string('token');
$t->timestamp('created_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('password_reminders');
Schema::drop('users');
}
} | <?php
use Illuminate\Database\Migrations\Migration;
class ConfideSetupUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Creates the users table
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('username');
$table->string('email');
$table->string('password');
$table->string('confirmation_code');
$table->boolean('confirmed')->default(false);
$table->timestamps();
});
// Creates password reminders table
Schema::create('password_reminders', function($t)
{
$t->string('email');
$t->string('token');
$t->timestamp('created_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('password_reminders');
Schema::drop('users');
}
} |
Update code to reflect usage of secure functions | <?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html lang="en">
<?php
$beginning = '<div class="container"><nav class="navbar navbar-default "><div class="navbar-header">
<a class="navbar-brand">Navigation Bar </a>
</div><ul class="nav navbar-nav justified">';
$frontLink = '<li class="nav-item"> <a class="" href="';
$endLink = '</a></li>';
if (isset($_SESSION['user-type'])) {
echo $beginning;
switch ($_SESSION['user-type']) {
case 'doctor':
$result = getDoctorDetails();
$speciality = $result[0]['speciality'];
echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
echo $frontLink.'patient_info.php?speciality='.$speciality.'"> Upcomming Appointments '.$endLink;
break;
case 'clerk':
echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
echo $frontLink.'patient_info.php"> All Appointments '.$endLink;
break;
default:
// code...
break;
}
echo '</ul> </nav></div>';
}
?>
| <?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html lang="en">
<?php
$beginning = '<div class="container"><nav class="navbar navbar-default "><div class="navbar-header">
<a class="navbar-brand">Navigation Bar </a>
</div><ul class="nav navbar-nav justified">';
$frontLink = '<li class="nav-item"> <a class="" href="';
$endLink = '</a></li>';
if (isset($_SESSION['user-type'])) {
echo $beginning;
switch ($_SESSION['user-type']) {
case 'doctor':
$result = getDoctorDetails();
$row = $result->fetch_array(MYSQLI_ASSOC);
$speciality = $row['speciality'];
echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
echo $frontLink.'patient_info.php?speciality='.$speciality.'"> Upcomming Appointments '.$endLink;
break;
case 'clerk':
echo $frontLink.'add_patient.php"> Add Patient '.$endLink;
echo $frontLink.'patient_info.php"> All Appointments '.$endLink;
break;
default:
// code...
break;
}
echo '</ul> </nav></div>';
}
?>
|
Implement scheduled task handling in Slack | import time
import importlib
from tempora import schedule
import pmxbot
class Bot(pmxbot.core.Bot):
def __init__(self, server, port, nickname, channels, password=None):
token = pmxbot.config['slack token']
sc = importlib.import_module('slackclient')
self.client = sc.SlackClient(token)
self.scheduler = schedule.CallbackScheduler(self.handle_scheduled)
def start(self):
res = self.client.rtm_connect()
assert res, "Error connecting"
self.init_schedule(self.scheduler)
while True:
for msg in self.client.rtm_read():
self.handle_message(msg)
self.scheduler.run_pending()
time.sleep(0.1)
def handle_message(self, msg):
if msg.get('type') != 'message':
return
channel = self.client.server.channels.find(msg['channel']).name
nick = self.client.server.users.find(msg['user']).name
self.handle_action(channel, nick, msg['text'])
def transmit(self, channel, message):
channel = self.client.server.channels.find(channel)
channel.send_message(message)
| import time
import importlib
import pmxbot
class Bot(pmxbot.core.Bot):
def __init__(self, server, port, nickname, channels, password=None):
token = pmxbot.config['slack token']
sc = importlib.import_module('slackclient')
self.client = sc.SlackClient(token)
def start(self):
res = self.client.rtm_connect()
assert res, "Error connecting"
while True:
for msg in self.client.rtm_read():
self.handle_message(msg)
self.handle_scheduled_tasks()
time.sleep(0.1)
def handle_message(self, msg):
if msg.get('type') != 'message':
return
channel = self.client.server.channels.find(msg['channel']).name
nick = self.client.server.users.find(msg['user']).name
self.handle_action(channel, nick, msg['text'])
def handle_scheduled_tasks(self):
"stubbed"
def transmit(self, channel, message):
channel = self.client.server.channels.find(channel)
channel.send_message(message)
|
Fix unnecessary recomputation of file targets | import os
from ..target import Target
class LocalFile(Target):
def __init__(self, path):
self._path = path
super(LocalFile, self).__init__()
if self.exists():
self._memory['timestamp'] = os.path.getmtime(self._path)
else:
self._memory['timestamp'] = 0
def identifier(self):
return self._path
def exists(self):
return os.path.exists(self._path)
def path(self):
return self._path
def store(self, batch=None):
if self.exists():
self._memory['timestamp'] = os.path.getmtime(self._path)
else:
self._memory['timestamp'] = 0
super(LocalFile, self).store(batch)
def open(self, *args, **kwargs):
return open(self._path, *args, **kwargs)
def is_damaged(self):
mem = self.stored()
if mem is None or not 'timestamp' in mem:
return True
return self._memory['timestamp'] > mem['timestamp']
| import os
from ..target import Target
class LocalFile(Target):
def __init__(self, path):
self._path = path
super(LocalFile, self).__init__()
self._timestamp = 0
def identifier(self):
return self._path
def exists(self):
return os.path.exists(self._path)
def path(self):
return self._path
def open(self, *args, **kwargs):
return open(self._path, *args, **kwargs)
def store(self, batch=None):
if self.exists():
self._memory['timestamp'] = os.path.getmtime(self._path)
else:
self._memory['timestamp'] = 0
super(LocalFile, self).store(batch)
def is_damaged(self):
stored = self.stored()
if stored is None:
return True
if self.exists():
return os.path.getmtime(self._path) > stored['timestamp']
else:
return True
|
Add custom error message to number validation | package br.com.bloder.blormlib.validation.validations;
import android.text.TextUtils;
import android.widget.EditText;
import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;
/**
* Created by bloder on 31/07/16.
*/
public class Number extends Validation {
EditText editText;
@Override
public Validate validate() {
return new Validate() {
@Override
public boolean validate() {
editText = (EditText) field;
if (editText.getText().toString().isEmpty()) return false;
return TextUtils.isDigitsOnly(editText.getText().toString());
}
@Override
public void onError() {
editText.setError(errorMessage != null || !errorMessage.isEmpty() ? errorMessage : "This field only accept numbers!");
}
@Override
public void onSuccess() {
}
};
}
}
| package br.com.bloder.blormlib.validation.validations;
import android.text.TextUtils;
import android.widget.EditText;
import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;
/**
* Created by bloder on 31/07/16.
*/
public class Number extends Validation {
EditText editText;
@Override
public Validate validate() {
return new Validate() {
@Override
public boolean validate() {
editText = (EditText) field;
if (editText.getText().toString().isEmpty()) return false;
return TextUtils.isDigitsOnly(editText.getText().toString());
}
@Override
public void onError() {
editText.setError("This field only accept numbers!");
}
@Override
public void onSuccess() {
}
};
}
}
|
Test for using final classes in the middle of the path | package com.moonillusions.propertynavigation;
import static com.moonillusions.propertynavigation.PropertyNavigation.of;
import static com.moonillusions.propertynavigation.PropertyNavigation.prop;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Ignore;
import org.junit.Test;
public class PropertyNavigationTest {
@Test
public void shallow_class() {
assertThat(prop(of(Book.class).getAuthor()), equalTo("author"));
}
@Test
public void deep_class() {
assertThat(prop(of(Book.class).getAuthor().getAddress()),
equalTo("author.address"));
}
@Test
public void shallow_final_class() {
assertThat(prop(of(Book.class).getPageCount()), equalTo("pageCount"));
}
@Test
public void deep_final_class() {
assertThat(prop(of(Book.class).getAuthor().getName()),
equalTo("author.name"));
}
@Test
public void shallow_primitive() {
assertThat(prop(of(Book.class).getId()), equalTo("id"));
}
@Test
public void deep_primitive() {
assertThat(prop(of(Book.class).getAuthor().getBookCount()),
equalTo("author.bookCount"));
}
@Test
@Ignore
public void getter_of_final_class() {
assertThat(prop(of(Book.class).getAuthor().getName().getBytes()),
equalTo("author.name.bytes"));
}
} | package com.moonillusions.propertynavigation;
import static com.moonillusions.propertynavigation.PropertyNavigation.of;
import static com.moonillusions.propertynavigation.PropertyNavigation.prop;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class PropertyNavigationTest {
@Test
public void shallow_class() {
assertThat(prop(of(Book.class).getAuthor()), equalTo("author"));
}
@Test
public void deep_class() {
assertThat(prop(of(Book.class).getAuthor().getAddress()),
equalTo("author.address"));
}
@Test
public void shallow_final_class() {
assertThat(prop(of(Book.class).getPageCount()), equalTo("pageCount"));
}
@Test
public void deep_final_class() {
assertThat(prop(of(Book.class).getAuthor().getName()),
equalTo("author.name"));
}
@Test
public void shallow_primitive() {
assertThat(prop(of(Book.class).getId()), equalTo("id"));
}
@Test
public void deep_primitive() {
assertThat(prop(of(Book.class).getAuthor().getBookCount()),
equalTo("author.bookCount"));
}
} |
CLI: Replace hardcoded package name with ".". | """Foliant: Markdown to PDF, Docx, and LaTeX generator powered by Pandoc.
Usage:
foliant (build | make) <target> [--path=<project-path>]
foliant (upload | up) <document> [--secret=<client_secret*.json>]
foliant (-h | --help)
foliant --version
Options:
-h --help Show this screen.
-v --version Show version.
-p --path=<project-path> Path to your project [default: .].
-s --secret=<client_secret*.json> Path to Google app's client secret file.
"""
from docopt import docopt
import colorama
from colorama import Fore
from . import builder, uploader
from . import __version__ as foliant_version
def main():
"""Handles command-line params and runs the respective core function."""
colorama.init(autoreset=True)
args = docopt(__doc__, version="Foliant %s (Python)" % foliant_version)
if args["build"] or args["make"]:
result = builder.build(args["<target>"], args["--path"])
elif args["upload"] or args["up"]:
result = uploader.upload(args["<document>"])
print("---")
print(Fore.GREEN + "Result: %s" % result)
colorama.deinit()
| """Foliant: Markdown to PDF, Docx, and LaTeX generator powered by Pandoc.
Usage:
foliant (build | make) <target> [--path=<project-path>]
foliant (upload | up) <document> [--secret=<client_secret*.json>]
foliant (-h | --help)
foliant --version
Options:
-h --help Show this screen.
-v --version Show version.
-p --path=<project-path> Path to your project [default: .].
-s --secret=<client_secret*.json> Path to Google app's client secret file.
"""
from docopt import docopt
import colorama
from colorama import Fore
from foliant import builder, uploader
from foliant import __version__ as foliant_version
def main():
"""Handles command-line params and runs the respective core function."""
colorama.init(autoreset=True)
args = docopt(__doc__, version="Foliant %s (Python)" % foliant_version)
if args["build"] or args["make"]:
result = builder.build(args["<target>"], args["--path"])
elif args["upload"] or args["up"]:
result = uploader.upload(args["<document>"])
print("---")
print(Fore.GREEN + "Result: %s" % result)
colorama.deinit()
|
Update prop message for v-text-field masks | export default {
app: 'Designates the component as part of the application layout. Used for dynamically adjusting content sizing',
auto: 'Centers list on selected element',
centered: 'Centers the tabs',
clearable: 'Add input clear functionality, default icon is Material Icons **clear**',
dontFillMaskBlanks: 'Disables the automatic character display when typing',
falseValue: 'Sets value for falsy state',
fullWidth: 'Forces 100% width',
fixedTabs: '`v-tabs-item` min-width 160px (72px mobile), max-width 264px',
height: 'Sets the component height',
id: 'Sets the DOM id on the component',
mask: 'Apply a custom character mask to the input. See mask table below for more information',
max: 'Sets maximum width',
maxHeight: 'Sets the maximum height for the content',
min: 'Sets minimum width',
mobileBreakPoint: 'Sets the designated mobile breakpoint',
overlap: 'Component will overlap the slotted content',
persistent: 'Clicking outside will not dismiss the dialog',
returnMaskedValue: 'Returns the unmodified masked string',
ripple: 'Applies the `v-ripple` directive',
shift: 'Hide text of button when not active',
singleLine: 'Label does not move on focus/dirty',
size: 'Sets the height and width of the element',
textColor: 'Applies a specified color to the control text',
tile: 'Removes border radius',
trueValue: 'Sets value for truthy state',
value: 'Controls visibility',
width: 'The width of the content'
}
| export default {
app: 'Designates the component as part of the application layout. Used for dynamically adjusting content sizing',
auto: 'Centers list on selected element',
centered: 'Centers the tabs',
clearable: 'Add input clear functionality, default icon is Material Icons **clear**',
dontFillMaskBlanks: 'Disables the automatic character display when typing',
falseValue: 'Sets value for falsy state',
fullWidth: 'Forces 100% width',
fixedTabs: '`v-tabs-item` min-width 160px (72px mobile), max-width 264px',
height: 'Sets the component height',
id: 'Sets the DOM id on the component',
mask: 'Apply a custom character mask to the input. See mask table above for more information',
max: 'Sets maximum width',
maxHeight: 'Sets the maximum height for the content',
min: 'Sets minimum width',
mobileBreakPoint: 'Sets the designated mobile breakpoint',
overlap: 'Component will overlap the slotted content',
persistent: 'Clicking outside will not dismiss the dialog',
returnMaskedValue: 'Returns the unmodified masked string',
ripple: 'Applies the `v-ripple` directive',
shift: 'Hide text of button when not active',
singleLine: 'Label does not move on focus/dirty',
size: 'Sets the height and width of the element',
textColor: 'Applies a specified color to the control text',
tile: 'Removes border radius',
trueValue: 'Sets value for truthy state',
value: 'Controls visibility',
width: 'The width of the content'
}
|
Add in django.contrib.auth to the default test runner | #!/usr/bin/env python
import os, sys
from django.conf import settings
def runtests(*test_args):
if not test_args:
test_args = ['lockdown']
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
settings.configure(
DATABASE_ENGINE='sqlite3',
INSTALLED_APPS = (
'django.contrib.sessions',
'django.contrib.contenttypes',
'django.contrib.auth',
'lockdown'
),
ROOT_URLCONF='lockdown.tests.urls',
)
from django.test.utils import get_runner
test_runner = get_runner(settings)
failures = test_runner(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
| #!/usr/bin/env python
import os, sys
from django.conf import settings
def runtests(*test_args):
if not test_args:
test_args = ['lockdown']
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
settings.configure(
DATABASE_ENGINE='sqlite3',
INSTALLED_APPS = ('django.contrib.sessions', 'lockdown'),
ROOT_URLCONF='lockdown.tests.urls',
)
from django.test.utils import get_runner
test_runner = get_runner(settings)
failures = test_runner(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])
|
Update the version to 1.4.0. | from setuptools import setup, find_packages
setup(name='lightweight-rest-tester',
version='1.4.0',
description='A lightweight REST API testing framework.',
url='https://github.com/ridibooks/lightweight-rest-tester',
author='Jeehoon Yoo',
author_email='jeehoon.yoo@ridi.com',
license='MIT',
packages=find_packages(),
zip_safe=False,
install_requires=[
'certifi==2017.4.17',
'chardet==3.0.4',
'idna==2.5',
'jsonschema==2.6.0',
'requests==2.18.1',
'urllib3==1.21.1',
'click==6.7',
],
entry_points={
'console_scripts': [
'lw_rest_tester = rest_tester.command_line:main'
],
})
| from setuptools import setup, find_packages
setup(name='lightweight-rest-tester',
version='1.2.0',
description='A lightweight REST API testing framework.',
url='https://github.com/ridibooks/lightweight-rest-tester',
author='Jeehoon Yoo',
author_email='jeehoon.yoo@ridi.com',
license='MIT',
packages=find_packages(),
zip_safe=False,
install_requires=[
'certifi==2017.4.17',
'chardet==3.0.4',
'idna==2.5',
'jsonschema==2.6.0',
'requests==2.18.1',
'urllib3==1.21.1',
'click==6.7',
],
entry_points={
'console_scripts': [
'lw_rest_tester = rest_tester.command_line:main'
],
})
|
Support for CORS pre-flight requests added | package com.giraone.samples.pmspoc1.boundary.core;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
/**
* TODO: Only for non-production!
*/
public class BaseEndpoint
{
protected final static String DEFAULT_PAGING_SIZE = "20";
// Matches root-resources also - handle CORS pre-flight request
@OPTIONS
public Response options()
{
return Response.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*") // "127.0.0.1" does not work
//.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
.header("Access-Control-Allow-Methods", "*")
.build();
}
// Match sub-resources - handle CORS pre-flight request
@OPTIONS
@Path("{path:.*}")
public Response optionsAll(@PathParam("path") String path)
{
return Response.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*") // "127.0.0.1" does not work
.header("Access-Control-Allow-Methods", "*")
.build();
}
// No more used - see CorsFeature class
public Response buildWithCorsHeader(ResponseBuilder builder)
{
builder.header("Access-Control-Allow-Origin", "*");
return builder.build();
}
} | package com.giraone.samples.pmspoc1.boundary.core;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
/**
* TODO: Only for non-production!
*/
public class BaseEndpoint
{
protected final static String DEFAULT_PAGING_SIZE = "20";
// Match root-resources
@OPTIONS
public Response options()
{
return Response.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*") // "127.0.0.1" does not work
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.build();
}
// Match sub-resources
@OPTIONS
@Path("{path:.*}")
public Response optionsAll(@PathParam("path") String path)
{
return Response.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*") // "127.0.0.1" does not work
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.build();
}
} |
Fix test when it runs as well | package com.example;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.cloud.contract.wiremock.WireMockRestServiceServer;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
@DirtiesContext
// tag::wiremock_test[]
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
public class WiremockForDocsMockServerApplicationTests {
@Autowired
private RestTemplate restTemplate;
@Autowired
private Service service;
@Test
public void contextLoads() throws Exception {
// will read stubs classpath
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
.baseUrl("http://example.org").stubs("classpath:/stubs/resource.json");
// We're asserting if WireMock responded properly
assertThat(this.service.go()).isEqualTo("Hello World");
server.verify();
}
}
// end::wiremock_test[]
| package com.example;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.cloud.contract.wiremock.WireMockRestServiceServer;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
@DirtiesContext
// tag::wiremock_test[]
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
public class WiremockForDocsMockServerApplicationTests {
@Autowired
private RestTemplate restTemplate;
@Autowired
private Service service;
@Test
public void contextLoads() throws Exception {
// will read stubs from default /resources/stubs location
MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate)
.baseUrl("http://example.org").stubs("resource");
// We're asserting if WireMock responded properly
assertThat(this.service.go()).isEqualTo("Hello World");
server.verify();
}
}
// end::wiremock_test[]
|
Change how the library is exported
This commit makes the library define the |PEG| global variable (for
browser export) and possibly assign it into |module.exports| (for
Node.js export) later. The |module.exports| assignment is done *outside*
the main library |function| statement.
The big idea behind this is to make copy & paste inclusion of the
library into another code easier -- one just needs to strip the last
three lines. | /*
* PEG.js @VERSION
*
* http://pegjs.majda.cz/
*
* Copyright (c) 2010-2012 David Majda
* Licensend under the MIT license.
*/
var PEG = (function(undefined) {
var PEG = {
/* PEG.js version. */
VERSION: "@VERSION",
/*
* Generates a parser from a specified grammar and returns it.
*
* The grammar must be a string in the format described by the metagramar in
* the parser.pegjs file.
*
* Throws |PEG.parser.SyntaxError| if the grammar contains a syntax error or
* |PEG.GrammarError| if it contains a semantic error. Note that not all
* errors are detected during the generation and some may protrude to the
* generated parser and cause its malfunction.
*/
buildParser: function(grammar, options) {
return PEG.compiler.compile(PEG.parser.parse(grammar), options);
}
};
/* Thrown when the grammar contains an error. */
PEG.GrammarError = function(message) {
this.name = "PEG.GrammarError";
this.message = message;
};
PEG.GrammarError.prototype = Error.prototype;
// @include "utils.js"
// @include "parser.js"
// @include "compiler.js"
return PEG;
})();
if (typeof module !== "undefined") {
module.exports = PEG;
}
| /*
* PEG.js @VERSION
*
* http://pegjs.majda.cz/
*
* Copyright (c) 2010-2012 David Majda
* Licensend under the MIT license.
*/
(function(undefined) {
var PEG = {
/* PEG.js version. */
VERSION: "@VERSION",
/*
* Generates a parser from a specified grammar and returns it.
*
* The grammar must be a string in the format described by the metagramar in
* the parser.pegjs file.
*
* Throws |PEG.parser.SyntaxError| if the grammar contains a syntax error or
* |PEG.GrammarError| if it contains a semantic error. Note that not all
* errors are detected during the generation and some may protrude to the
* generated parser and cause its malfunction.
*/
buildParser: function(grammar, options) {
return PEG.compiler.compile(PEG.parser.parse(grammar), options);
}
};
/* Thrown when the grammar contains an error. */
PEG.GrammarError = function(message) {
this.name = "PEG.GrammarError";
this.message = message;
};
PEG.GrammarError.prototype = Error.prototype;
// @include "utils.js"
// @include "parser.js"
// @include "compiler.js"
if (typeof module === "object") {
module.exports = PEG;
} else if (typeof window === "object") {
window.PEG = PEG;
} else {
throw new Error("Can't export PEG library (no \"module\" nor \"window\" object detected).");
}
})();
|
Fix formatting and define the version up front. | from setuptools import setup
version = '2.1.0'
setup(name='PyFVCOM',
packages=['PyFVCOM'],
version=version,
description=("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
author='Pierre Cazenave',
author_email='pica@pml.ac.uk',
url='https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM',
download_url='http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref={}'.format(version),
keywords=['fvcom', 'unstructured grid', 'mesh'],
license='MIT',
platforms='any',
install_requires=['jdcal', 'lxml', 'matplotlib', 'netCDF4', 'networkx', 'numpy>=1.13.0', 'pandas', 'pyproj', 'pytz', 'scipy', 'pyshp', 'UTide', 'shapely'],
classifiers=[])
| from setuptools import setup
setup(
name='PyFVCOM',
packages=['PyFVCOM'],
version='2.1.0',
description=("PyFVCOM is a collection of various tools and utilities which can be used to extract, analyse and plot input and output files from FVCOM."),
author='Pierre Cazenave',
author_email='pica@pml.ac.uk',
url='https://gitlab.ecosystem-modelling.pml.ac.uk/fvcom/PyFVCOM',
download_url='http://gitlab.em.pml.ac.uk/fvcom/PyFVCOM/repository/archive.tar.gz?ref=2.1.0',
keywords=['fvcom', 'unstructured grid', 'mesh'],
license='MIT',
platforms='any',
install_requires=['jdcal', 'lxml', 'matplotlib', 'netCDF4', 'networkx', 'numpy>=1.13.0', 'pandas', 'pyproj', 'pytz', 'scipy', 'pyshp', 'UTide', 'shapely'],
classifiers=[]
)
|
Reorder callback data object construction | 'use strict';
var got = require('got');
var cheerio = require('cheerio');
var md = require('html-md');
module.exports = function(id, callback) {
var url = 'http://www.stm.dk/_p_' + id + '.html';
got(url, function(err, data){
var $ = cheerio.load(data);
var meta = $('meta[name="created"]');
var speech = $('.maininner.maininner-page');
speech.find('h1').remove();
speech.find('.nedtonet').remove();
var image = speech.find('.a110051').find('img').attr('src');
if(image){
speech.find('.a110051').remove();
image = 'http://www.stm.dk/' + image;
}
var linkElement = speech.find('a[onclick]');
if(linkElement.length){
var link = linkElement.attr('onclick').split('\'')[1];
linkElement.attr('href', link);
speech.children().last().remove();
speech.children().last().remove();
speech.children().last().remove();
}
var data = {
source: url,
date: meta.attr('content'),
rawHtml: speech.html(),
markdown: md(speech.html(), {inline: true}).replace(/\\/gi, ''),
image: image,
video: link
};
callback(null, data)
});
};
| 'use strict';
var got = require('got');
var cheerio = require('cheerio');
var md = require('html-md');
module.exports = function(id, callback) {
var url = 'http://www.stm.dk/_p_' + id + '.html';
got(url, function(err, data){
var $ = cheerio.load(data);
var meta = $('meta[name="created"]');
var speech = $('.maininner.maininner-page');
speech.find('h1').remove();
speech.find('.nedtonet').remove();
var data = {
source: url,
date: meta.attr('content'),
html: speech.html(),
markdown: md(speech.html(), {inline: true}).replace(/\\/gi, '')
};
var image = speech.find('.a110051').find('img').attr('src');
if(image){
speech.find('.a110051').remove();
image = 'http://www.stm.dk/' + image;
}
var linkElement = speech.find('a[onclick]');
if(linkElement.length){
var link = linkElement.attr('onclick').split('\'')[1];
linkElement.attr('href', link);
data.video = link;
speech.children().last().remove();
speech.children().last().remove();
speech.children().last().remove();
}
callback(null, data)
});
};
|
Change method name to better reflect file organization. | package gotwilio
type SmsResponse struct {
Sid string
DateCreated string // TODO: Change this to date type if possible
DateUpdate string // TODO: Change this to date type if possible
DateSent string // TODO: Change this to date type if possible
AccountSid string
To string
From string
Body string
Status string
Direction string
ApiVersion string
Price string // TODO: need to find out what this returns. My example is null
Url string
}
// SendTextMessage uses Twilio to send a text message.
// See http://www.twilio.com/docs/api/rest/sending-sms for more information.
func (twilio *Twilio) SendSMS(from, to, body, statusCallback, applicationSid string) (string, error) {
twilioUrl := twilio.BaseUrl + "/Accounts/" + twilio.AccountSid + "/SMS/Messages.json" // needs a better variable name
formValues := url.Values{}
formValues.Set("From", from)
formValues.Set("To", to)
formValues.Set("Body", body)
if statusCallback != "" {
formValues.Set("StatusCallback", statusCallback)
}
if applicationSid != "" {
formValues.Set("ApplicationSid", applicationSid)
}
return twilio.post(formValues, twilioUrl)
} | package gotwilio
type SmsResponse struct {
Sid string
DateCreated string // TODO: Change this to date type if possible
DateUpdate string // TODO: Change this to date type if possible
DateSent string // TODO: Change this to date type if possible
AccountSid string
To string
From string
Body string
Status string
Direction string
ApiVersion string
Price string // TODO: need to find out what this returns. My example is null
Url string
}
// SendTextMessage uses Twilio to send a text message.
// See http://www.twilio.com/docs/api/rest/sending-sms for more information.
func (twilio *Twilio) SendTextMessage(from, to, body, statusCallback, applicationSid string) (string, error) {
twilioUrl := twilio.BaseUrl + "/Accounts/" + twilio.AccountSid + "/SMS/Messages.json" // needs a better variable name
formValues := url.Values{}
formValues.Set("From", from)
formValues.Set("To", to)
formValues.Set("Body", body)
if statusCallback != "" {
formValues.Set("StatusCallback", statusCallback)
}
if applicationSid != "" {
formValues.Set("ApplicationSid", applicationSid)
}
return twilio.post(formValues, twilioUrl)
} |
Add custom error messages to error handler | import chalk from 'chalk';
import { get, includes, defaults } from 'lodash';
import {DEBUG} from './flags';
const formatMessage = (err, options = {}) => {
const codes = defaults({
ENOENT: 'No such file or directory: ' + err.path
}, args.errorMessages);
return codes[err.code] || err.message;
}
const errorHandler = (args = {}) => {
const debug = includes(args.argv, `--${DEBUG}`);
return (err) => {
console.log(chalk.red('Error:'))
console.log(chalk.red(formatMessage(err)));
if (debug) {
console.log('');
console.log(err.stack);
console.log('');
}
process.exit(1);
}
}
export default errorHandler;
| import chalk from 'chalk';
import { get, includes } from 'lodash';
import {DEBUG} from './flags';
const formatMessage = (err) => {
switch (err.code) {
case 'ENOENT':
return 'No such file or directory: ' + err.path;
default:
return err.message;
}
}
const errorHandler = (args = {}) => {
const debug = includes(args.argv, `--${DEBUG}`);
return (err) => {
console.log(chalk.red('Error:'))
console.log(chalk.red(formatMessage(err)));
if (debug) {
console.log('');
console.log(err.stack);
console.log('');
}
process.exit(1);
}
}
export default errorHandler;
|
Add a couple missing commas | var crypto = require('crypto')
var fs = require('fs')
var path = require('path')
var fingerprintPath = path.resolve(__dirname, '..', '..', 'node_modules', '.atom-ci-fingerprint')
module.exports = {
fingerprint: function () {
var packageJson = fs.readFileSync(path.resolve(__dirname, '..', '..', 'package.json'))
var body = packageJson.toString() + process.platform
return crypto.createHash('sha1').update(body).digest('hex')
},
writeFingerprint: function () {
var fingerprint = this.fingerprint()
fs.writeFileSync(fingerprintPath, fingerprint)
console.log('Wrote ci fingerprint:', fingerprintPath, fingerprint)
},
readFingerprint: function() {
if (fs.existsSync(fingerprintPath)) {
return fs.readFileSync(fingerprintPath).toString()
} else {
return null
}
},
fingerprintMatches: function () {
return this.readFingerprint() && this.readFingerprint() === this.fingerprint()
}
}
| var crypto = require('crypto')
var fs = require('fs')
var path = require('path')
var fingerprintPath = path.resolve(__dirname, '..', '..', 'node_modules', '.atom-ci-fingerprint')
module.exports = {
fingerprint: function () {
var packageJson = fs.readFileSync(path.resolve(__dirname, '..', '..', 'package.json'))
var body = packageJson.toString() + process.platform
return crypto.createHash('sha1').update(body).digest('hex')
},
writeFingerprint: function () {
var fingerprint = this.fingerprint()
fs.writeFileSync(fingerprintPath, fingerprint)
console.log('Wrote ci fingerprint:', fingerprintPath, fingerprint)
}
readFingerprint: function() {
if (fs.existsSync(fingerprintPath)) {
return fs.readFileSync(fingerprintPath).toString()
} else {
return null
}
}
fingerprintMatches: function () {
return this.readFingerprint() && this.readFingerprint() === this.fingerprint()
}
}
|
Change var to const for webpack. | const webpack = require('webpack');
module.exports = {
entry: {
main: ['babel-polyfill', './lib/index.js'],
test: ['babel-polyfill', 'mocha!./test/index.js'],
},
output: {
path: __dirname,
filename: '[name].bundle.js',
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
},
},
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.scss$/, loader: 'style!css!sass' },
],
},
resolve: {
extensions: ['', '.js', '.jsx', '.json', '.scss', '.css'],
alias: {
'jquery-ui': 'jquery-ui-dist/jquery-ui.js',
},
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
}),
],
};
| var webpack = require('webpack');
module.exports = {
entry: {
main: ['babel-polyfill', './lib/index.js'],
test: ['babel-polyfill', 'mocha!./test/index.js']
},
output: {
path: __dirname,
filename: '[name].bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
},
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.scss$/, loader: 'style!css!sass' }
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.json', '.scss', '.css'],
alias: {
'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
}
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
};
|
Remove a print in a unit test. sorry.... | <?php
namespace PureMachine\Bundle\WebServiceBundle\Tests\Service;
use PureMachine\Bundle\WebServiceBundle\Service\WebServiceManager;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @code
* phpunit -v -c app vendor/puremachine/ws/src/PureMachine/Bundle/WebServiceBundle/Tests/Service/DocumentationManagerTest.php
* @endcode
*/
class DocumentationManagerTest extends WebTestCase
{
/**
* Checks if the addService method for a given service will not try to parse
* and add method without the main webservice annotation
*
* @code
* phpunit -v --filter testWSReference -c app vendor/puremachine/ws/src/PureMachine/Bundle/WebServiceBundle/Tests/Service/DocumentationManagerTest.php
* @endcode
*/
public function testWSReference()
{
$symfony = static::createClient();
$wsManager = $symfony->getContainer()->get('pureMachine.sdk.webServiceManager');
$answer = $wsManager->call('PureMachine/Doc/WSReference','PureBilling/Charge/Capture');
//FIXME: not finished
}
}
| <?php
namespace PureMachine\Bundle\WebServiceBundle\Tests\Service;
use PureMachine\Bundle\WebServiceBundle\Service\WebServiceManager;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @code
* phpunit -v -c app vendor/puremachine/ws/src/PureMachine/Bundle/WebServiceBundle/Tests/Service/DocumentationManagerTest.php
* @endcode
*/
class DocumentationManagerTest extends WebTestCase
{
/**
* Checks if the addService method for a given service will not try to parse
* and add method without the main webservice annotation
*
* @code
* phpunit -v --filter testWSReference -c app vendor/puremachine/ws/src/PureMachine/Bundle/WebServiceBundle/Tests/Service/DocumentationManagerTest.php
* @endcode
*/
public function testWSReference()
{
$symfony = static::createClient();
$wsManager = $symfony->getContainer()->get('pureMachine.sdk.webServiceManager');
$answer = $wsManager->call('PureMachine/Doc/WSReference','PureBilling/Charge/Capture');
print $answer->getAnswer();
}
}
|
Allow importing RAR files in the UI
Fixes 2366 |
/**
* Default upload config
*
*/
module.exports = {
uploadStates: [
'enqueued',
'pending',
'importing',
'uploading',
'guessing',
'unpacking',
'getting',
'creating',
'complete'
],
fileExtensions: [
'csv',
'xls',
'xlsx',
'zip',
'kml',
'geojson',
'json',
'ods',
'kmz',
'tsv',
'gpx',
'tar',
'gz',
'tgz',
'osm',
'bz2',
'tif',
'tiff',
'txt',
'sql',
'rar'
],
// How big should file be?
fileTimesBigger: 3
}
|
/**
* Default upload config
*
*/
module.exports = {
uploadStates: [
'enqueued',
'pending',
'importing',
'uploading',
'guessing',
'unpacking',
'getting',
'creating',
'complete'
],
fileExtensions: [
'csv',
'xls',
'xlsx',
'zip',
'kml',
'geojson',
'json',
'ods',
'kmz',
'tsv',
'gpx',
'tar',
'gz',
'tgz',
'osm',
'bz2',
'tif',
'tiff',
'txt',
'sql'
],
// How big should file be?
fileTimesBigger: 3
} |
Replace assertTrue(x == y) with assertEquals(x, y) | package rxbroadcast;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.Assert;
import org.junit.Test;
public final class SenderTest {
@Test
public final void equalsContract() {
EqualsVerifier.forClass(Sender.class).verify();
}
@Test
public final void testCompareToSimple1() {
final Sender s1 = new Sender(new byte[]{1});
final Sender s2 = new Sender(new byte[]{2});
Assert.assertTrue("s1 < s2", s1.compareTo(s2) < 0);
}
@Test
public final void testCompareToSimple2() {
final Sender s1 = new Sender(new byte[]{2});
final Sender s2 = new Sender(new byte[]{1});
Assert.assertTrue("s1 > s2", s1.compareTo(s2) > 0);
}
@Test
public final void testCompareToSimple3() {
final Sender s1 = new Sender(new byte[]{2});
final Sender s2 = new Sender(new byte[]{2});
Assert.assertEquals(0, s1.compareTo(s2));
}
}
| package rxbroadcast;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.Assert;
import org.junit.Test;
public final class SenderTest {
@Test
public final void equalsContract() {
EqualsVerifier.forClass(Sender.class).verify();
}
@Test
public final void testCompareToSimple1() {
final Sender s1 = new Sender(new byte[]{1});
final Sender s2 = new Sender(new byte[]{2});
Assert.assertTrue("s1 < s2", s1.compareTo(s2) < 0);
}
@Test
public final void testCompareToSimple2() {
final Sender s1 = new Sender(new byte[]{2});
final Sender s2 = new Sender(new byte[]{1});
Assert.assertTrue("s1 > s2", s1.compareTo(s2) > 0);
}
@Test
public final void testCompareToSimple3() {
final Sender s1 = new Sender(new byte[]{2});
final Sender s2 = new Sender(new byte[]{2});
Assert.assertTrue("s1 ≡ s2", s1.compareTo(s2) == 0);
}
}
|
Use slug as post url | import React from 'react';
import moment from 'moment';
import { Link } from 'react-router';
const DATE_FORMAT = 'YYYY-MM-DD HH:mm';
const formatDate = (date) => moment(date).format(DATE_FORMAT);
const NewsPost = ({ post }) => (
<article className="news-article">
<h2><Link to={`/news/${post.slug}`}>{post.title}</Link></h2>
<small>by {post.author && post.author.email} | {moment(post.updatedAt).fromNow()} | {post.categories.map(c => c.name).join(', ')}</small>
<p dangerouslySetInnerHTML={{__html: post.body}}></p>
{post.eventData && <EventsPartial {...post.eventData} />}
</article>
);
const EventsPartial = ({ from, to, rsvp, location }) => (
<div className="event-partial">
<span>{from && formatDate(from)} {to && formatDate(to)}</span>
{rsvp && (<a href={rsvp} className="button">RSVP!</a>)}
{location && (<GoogleMapsLink {...location} />)}
</div>
);
const GoogleMapsLink = ({ lat, lng, name }) => (
<a href={`https://www.google.com/maps/preview/@${lat},${lng},13z`} target="_blank">{name}</a>
);
export default NewsPost; | import React from 'react';
import moment from 'moment';
import { Link } from 'react-router';
const DATE_FORMAT = 'YYYY-MM-DD HH:mm';
const formatDate = (date) => moment(date).format(DATE_FORMAT);
const NewsPost = ({ post }) => (
<article>
<h2><Link to={`/news/${post._id}`}>{post.title}</Link></h2>
<small>by {post.author.email} | {moment(post.updatedAt).fromNow()} | {post.categories.map(c => c.name).join(', ')}</small>
<p>{post.body}</p>
{post.eventData && <EventsPartial {...post.eventData} />}
</article>
);
const EventsPartial = ({ from, to, rsvp, location }) => (
<div className="event-partial">
<span>{formatDate(from)} {formatDate(to)}</span>
{rsvp && (<a href={rsvp} className="button">RSVP!</a>)}
<GoogleMapsLink {...location} />
</div>
);
const GoogleMapsLink = ({ lat, lng, name }) => (
<a href={`https://www.google.com/maps/preview/@${lat},${lng},13z`} target="_blank">{name}</a>
);
export default NewsPost; |
Declare exceptions that are already thrown by implementations | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Encoder;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
/**
* PasswordEncoderInterface is the interface for all encoders.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface PasswordEncoderInterface
{
/**
* Encodes the raw password.
*
* @param string $raw The password to encode
* @param string $salt The salt
*
* @return string The encoded password
*
* @throws BadCredentialsException If the raw password is invalid, e.g. excessively long
* @throws \InvalidArgumentException If the salt is invalid
*/
public function encodePassword($raw, $salt);
/**
* Checks a raw password against an encoded password.
*
* @param string $encoded An encoded password
* @param string $raw A raw password
* @param string $salt The salt
*
* @return bool true if the password is valid, false otherwise
*
* @throws \InvalidArgumentException If the salt is invalid
*/
public function isPasswordValid($encoded, $raw, $salt);
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Encoder;
/**
* PasswordEncoderInterface is the interface for all encoders.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface PasswordEncoderInterface
{
/**
* Encodes the raw password.
*
* @param string $raw The password to encode
* @param string $salt The salt
*
* @return string The encoded password
*/
public function encodePassword($raw, $salt);
/**
* Checks a raw password against an encoded password.
*
* @param string $encoded An encoded password
* @param string $raw A raw password
* @param string $salt The salt
*
* @return bool true if the password is valid, false otherwise
*/
public function isPasswordValid($encoded, $raw, $salt);
}
|
Sort by longest path (assuming stdlib stuff will be in the longest). | import collections
import os
import site
import sys
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = {
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(collections.__file__),
}
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(sorted(SYS_PREFIX_PATHS, key=len, reverse=True))
| import collections
import os
import site
import sys
from distutils.sysconfig import get_python_lib
SITE_PACKAGES_PATHS = set()
if hasattr(site, 'getsitepackages'):
SITE_PACKAGES_PATHS.update(site.getsitepackages())
if hasattr(site, 'getusersitepackages'):
SITE_PACKAGES_PATHS.add(site.getusersitepackages())
SITE_PACKAGES_PATHS.add(get_python_lib())
SITE_PACKAGES_PATHS = tuple(SITE_PACKAGES_PATHS)
SYS_PREFIX_PATHS = set((
sys.prefix,
sys.exec_prefix,
os.path.dirname(os.__file__),
os.path.dirname(collections.__file__),
))
for prop in 'real_prefix', 'real_exec_prefix', 'base_prefix', 'base_exec_prefix':
if hasattr(sys, prop):
SYS_PREFIX_PATHS.add(getattr(sys, prop))
SYS_PREFIX_PATHS = tuple(SYS_PREFIX_PATHS)
|
Add support for Django debug sidebar. | """elmo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.views.generic import TemplateView
from django.contrib.auth.views import logout
urlpatterns = [
url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'),
url(r'^admin/', admin.site.urls),
url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'),
url(r'^auth/', include('social_django.urls', namespace='social')),
url(r'^', include('moon_tracker.urls')),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
| """elmo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
from django.contrib.auth.views import logout
urlpatterns = [
url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'),
url(r'^admin/', admin.site.urls),
url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'),
url(r'^auth/', include('social_django.urls', namespace='social')),
url(r'^', include('moon_tracker.urls')),
]
|
Allow the login detecting page to find the cookie.
dirname shortens the path the cookie applies to,
to the entire IDE folder, not just the control script. | <?php
require_once("tokenstrategy.php");
class CookieStrategy extends TokenStrategy
{
/**
* the name for the cookie
*/
const COOKIENAME = "token";
/**
* the path the cookie is valid for
*/
private $path;
public function __construct()
{
$this->path = dirname($_SERVER['SCRIPT_NAME']).'/';
}
public function getAuthToken()
{
return $_COOKIE[self::COOKIENAME];
}
public function setNextAuthToken($token)
{
$expiry = Configuration::getInstance()->getConfig("cookie_expiry_time");
if ($expiry == null)
{
throw new Exception("no cookie expiry time found in config file", E_NO_EXPIRY_TIME);
}
setcookie(
self::COOKIENAME,
$token,
time() + (int)$expiry,
$this->path
);
}
public function removeAuthToken()
{
setcookie(self::COOKIENAME, "", time() - 3600, $this->path);
}
}
| <?php
require_once("tokenstrategy.php");
class CookieStrategy extends TokenStrategy
{
/**
* the name for the cookie
*/
const COOKIENAME = "token";
/**
* the path the cookie is valid for
*/
private $path;
public function __construct()
{
$this->path = $_SERVER['SCRIPT_NAME'];
}
public function getAuthToken()
{
return $_COOKIE[self::COOKIENAME];
}
public function setNextAuthToken($token)
{
$expiry = Configuration::getInstance()->getConfig("cookie_expiry_time");
if ($expiry == null)
{
throw new Exception("no cookie expiry time found in config file", E_NO_EXPIRY_TIME);
}
setcookie(
self::COOKIENAME,
$token,
time() + (int)$expiry,
$this->path
);
}
public function removeAuthToken()
{
setcookie(self::COOKIENAME, "", time() - 3600, $this->path);
}
}
|
Allow entities with dots in their names in the player selector pattern | package net.earthcomputer.easyeditors.api;
import java.util.regex.Pattern;
/**
* A class containing a number of {@link Pattern}s useful to Easy Editors.
*
* <b>This class is a member of the Easy Editors API</b>
*
* @author Earthcomputer
*
*/
public class Patterns {
public static final Pattern partialPlayerName = Pattern.compile("\\w{0,32}");
public static final Pattern playerName = Pattern.compile("\\w{1,32}");
public static final Pattern UUID = Pattern.compile("[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}");
public static final Pattern partialUUID = Pattern
.compile("[0-9a-fA-F]{0,8}-(?:[0-9a-fA-F]{0,4}-){3}[0-9a-fA-F]{0,12}");
public static final Pattern playerSelector = Pattern.compile("@([pare])(?:\\[([\\w\\.=,!-]*)\\])?");
public static final Pattern partialInteger = Pattern.compile("[+-]?[0-9]*");
public static final Pattern integer = Pattern.compile("[+-]?[0-9]+");
}
| package net.earthcomputer.easyeditors.api;
import java.util.regex.Pattern;
/**
* A class containing a number of {@link Pattern}s useful to Easy Editors.
*
* <b>This class is a member of the Easy Editors API</b>
*
* @author Earthcomputer
*
*/
public class Patterns {
public static final Pattern partialPlayerName = Pattern.compile("\\w{0,32}");
public static final Pattern playerName = Pattern.compile("\\w{1,32}");
public static final Pattern UUID = Pattern.compile("[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}");
public static final Pattern partialUUID = Pattern
.compile("[0-9a-fA-F]{0,8}-(?:[0-9a-fA-F]{0,4}-){3}[0-9a-fA-F]{0,12}");
public static final Pattern playerSelector = Pattern.compile("@([pare])(?:\\[([\\w=,!-]*)\\])?");
public static final Pattern partialInteger = Pattern.compile("[+-]?[0-9]*");
public static final Pattern integer = Pattern.compile("[+-]?[0-9]+");
}
|
Add visual identify which tab is active | /* jshint devel: true */
!function() {
'use strict';
var navGame = document.getElementById("nav-game");
var navUpgrade = document.getElementById("nav-upgrade");
var navAbout = document.getElementById("nav-about");
var showElement = function(element) {
document.getElementById(element).className = document
.getElementById(element).className.replace(
/(?:^|\s)invisible(?!\S)/g, '');
};
var hideElement = function(element) {
document.getElementById(element).className += " invisible";
};
var setActive = function(element) {
element.className += " active";
};
var setUnactive = function(element) {
element.className = element.className.replace(/(?:^|\s)active(?!\S)/g,
'');
};
var showGame = function() {
showElement("game");
hideElement("upgrades");
hideElement("about");
setActive(navGame);
setUnactive(navUpgrade);
setUnactive(navAbout);
};
var showUpgrades = function() {
hideElement("game");
showElement("upgrades");
hideElement("about");
setUnactive(navGame);
setActive(navUpgrade);
setUnactive(navAbout);
};
var showAbout = function() {
hideElement("game");
hideElement("upgrades");
showElement("about");
setUnactive(navGame);
setUnactive(navUpgrade);
setActive(navAbout);
};
navGame.addEventListener("click", showGame);
navUpgrade.addEventListener("click", showUpgrades);
navAbout.addEventListener("click", showAbout);
}(); | /* jshint devel: true */
!function() {
'use strict';
var navGame = document.getElementById("nav-game");
var navUpgrade = document.getElementById("nav-upgrade");
var navAbout = document.getElementById("nav-about");
var showElement = function(element) {
document.getElementById(element).className = document
.getElementById(element).className.replace(
/(?:^|\s)invisible(?!\S)/g, '');
};
var hideElement = function(element) {
document.getElementById(element).className += " invisible";
};
var showGame = function() {
showElement("game");
hideElement("upgrades");
hideElement("about");
};
var showUpgrades = function() {
hideElement("game");
showElement("upgrades");
hideElement("about");
};
var showAbout = function() {
hideElement("game");
hideElement("upgrades");
showElement("about");
};
navGame.addEventListener("click", showGame);
navUpgrade.addEventListener("click", showUpgrades);
navAbout.addEventListener("click", showAbout);
}(); |
Add bowl pickem all the time | <?php
namespace SofaChamps\Bundle\CoreBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class HomepageController extends CoreController
{
/**
* @Route("/", name="core_home")
*/
public function homepageAction()
{
// This is temporary
return $this->redirect($this->generateUrl('bp_home', array(
'season' => $this->getCurrentBowlPickemSeason(),
)));
$user = $this->getUser();
$template = $this->get('security.context')->isGranted('ROLE_USER')
? 'SofaChampsCoreBundle::homepage.auth.html.twig'
: 'SofaChampsCoreBundle::homepage.unauth.html.twig';
return $this->render($template , array(
'user' => $user,
'year' => $this->get('config.curyear'),
));
}
private function getCurrentBowlPickemSeason()
{
return $this->get('sofachamps.bp.season_manager')->getCurrentSeason();
}
}
| <?php
namespace SofaChamps\Bundle\CoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class HomepageController extends Controller
{
/**
* @Route("/", name="core_home")
*/
public function homepageAction()
{
$user = $this->getUser();
$template = $this->get('security.context')->isGranted('ROLE_USER')
? 'SofaChampsCoreBundle::homepage.auth.html.twig'
: 'SofaChampsCoreBundle::homepage.unauth.html.twig';
return $this->render($template , array(
'user' => $user,
'year' => $this->get('config.curyear'),
));
}
}
|
Call req.send when using get convienience function. | define(['exports',
'./lib/request',
'url'],
function(exports, Request, uri) {
function request(url, method, cb) {
var headers;
if (typeof url == 'object') {
var opts = url;
cb = method;
method = opts.method || 'GET';
url = uri.format(opts);
headers = opts.headers;
} else if (typeof method == 'function') {
cb = method;
method = 'GET';
}
var req = new Request(url, method);
if (headers) {
for (var name in headers) {
req.setHeader(name, headers[name]);
}
}
if (cb) req.on('response', cb);
return req;
}
function get(url, cb) {
var req = request(url, cb);
req.send();
return req;
}
exports.request = request;
exports.get = get;
});
| define(['exports',
'./lib/request',
'url'],
function(exports, Request, uri) {
function request(url, method, cb) {
var headers;
if (typeof url == 'object') {
var opts = url;
cb = method;
method = opts.method || 'GET';
url = uri.format(opts);
headers = opts.headers;
} else if (typeof method == 'function') {
cb = method;
method = 'GET';
}
var req = new Request(url, method);
if (headers) {
for (var name in headers) {
req.setHeader(name, headers[name]);
}
}
if (cb) req.on('response', cb);
return req;
}
function get(url, cb) {
var req = request(url, cb);
req.end();
return req;
}
exports.request = request;
exports.get = get;
});
|
Include tenant admin into main apps | <?php
namespace Annex\TenantBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class TenantController extends Controller
{
/**
* @Route("/tenant/list", name="tenant_list")
*/
public function tenantListAction()
{
if ($this->get('session')->get('tenantId')) {
$this->addFlash('error', "Sorry, no can do.");
return $this->redirectToRoute('homepage');
}
$em = $this->getDoctrine()->getManager();
/** @var \Annex\TenantBundle\Repository\TenantRepository $repo */
$repo = $em->getRepository('AnnexTenantBundle:Tenant');
$tenants = $repo->findAll();
return $this->render('AnnexTenantBundle::tenant_admin/tenant_list.html.twig', [
'appName' => $this->get('session')->get('appName'),
'tenants' => $tenants
]);
}
}
| <?php
namespace Annex\TenantBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class TenantController extends Controller
{
/**
* @Route("/tenant/list", name="tenant_list")
*/
public function homeAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
/** @var \Annex\TenantBundle\Repository\TenantRepository $repo */
$repo = $em->getRepository('AnnexTenantBundle:Tenant');
$tenants = $repo->findAll();
return $this->render('AnnexTenantBundle::tenant_admin/tenant_list.html.twig', [
'appName' => $this->get('session')->get('appName'),
'tenants' => $tenants
]);
}
}
|
Use format string. Readability. ValueError. | import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
elif isinstance(obj, string_types + integer_types):
text.write(u'%s ' % obj)
else:
raise ValueError('Unrecognized type: %s' % obj.__class__)
def _get_file(f, **kwargs):
text, data = StringIO(), f.read()
obj = json.loads(data.decode('utf8'))
_to_text(text, obj)
return text.getvalue()
| import json
from six import StringIO
from six import string_types
from six import integer_types
def _to_text(text, obj):
if isinstance(obj, dict):
for key in sorted(obj.keys()):
_to_text(text, key)
_to_text(text, obj[key])
elif isinstance(obj, list):
for item in obj:
_to_text(text, item)
elif isinstance(obj, string_types):
text.write(obj)
text.write(u' ')
elif isinstance(obj, integer_types):
text.write(str(obj))
text.write(u' ')
def _get_file(f, **kwargs):
text, obj = StringIO(), json.loads(f.read().decode('utf8'))
_to_text(text, obj)
return text.getvalue()
|
Use site metadata to find registered plugins/schemas.
This simplifies loading schemas, and eliminates some dependencies.
We also stash site metadata in the schema object, since it's useful
for tests. | // This module loads and exposes an object of all available schemas, using
// the schema key as the object key. It adds the site metadata to the schema
// header for convenient access.
//
// The schemas and site metadata are loaded from the extension plugin directory.
// We therefore need to have a checkout of the extension alongside the web
// service in order to use this module.
'use strict';
let jsonfile = require('jsonfile');
let sitesDir = '../extension';
let pluginDir = '../extension/src/plugins';
let sites = jsonfile.readFileSync(`${sitesDir}/sites.json`);
let schemas = {};
for (let site of sites) {
try {
let schema = jsonfile.readFileSync(`${pluginDir}/${site.plugin}/schema.json`);
if (schema.hasOwnProperty('schema') && schema.schema.hasOwnProperty('key')) {
schemas[schema.schema.key] = schema;
schema.schema.site = site;
} else {
console.log(`schema.json for plugin "${site.plugin}" does not have a valid schema header. Skipping.`);
}
} catch (e) {
console.log(`Problem reading schema.json for plugin "${site.plugin}". Skipping. Error was: ${e}`);
}
}
module.exports = schemas;
| // This module loads and exposes an object of all available schemas, using
// the schema key as the object key.
//
// The schemas are loaded from the extension plugin directory. We therefore need
// to have a checkout of the extension alongside the web service in order to use
// this module.
'use strict';
let jsonfile = require('jsonfile');
let fs = require('fs');
let path = require('path');
let pluginDir = '../extension/src/plugins';
let dirs = getDirectories(pluginDir);
let schemas = {};
for (let dir of dirs) {
try {
let schema = jsonfile.readFileSync(`${pluginDir}/${dir}/schema.json`);
if (schema.hasOwnProperty('schema') && schema.schema.hasOwnProperty('key')) {
schemas[schema.schema.key] = schema;
} else {
console.log(`schema.json for plugin "${dir}" does not have a valid schema header. Skipping.`);
}
} catch (e) {
console.log(`Problem reading schema.json for plugin "${dir}". Skipping.`);
}
}
function getDirectories(srcpath) {
return fs.readdirSync(srcpath).filter(function(file) {
return fs.statSync(path.join(srcpath, file)).isDirectory();
});
}
module.exports = schemas;
|
Clarify parameter names in item on object event. | package org.apollo.game.event.impl;
import org.apollo.game.event.Event;
import org.apollo.game.model.Position;
/**
* An {@link Event} sent by the client when an item is used on an object.
*
* @author Major
*/
public final class ItemOnObjectEvent extends InventoryItemEvent {
/**
* The object id the item was used on.
*/
private final int objectId;
/**
* The position of the object.
*/
private final Position position;
/**
* Creates an item on object event.
*
* @param interfaceId The interface id.
* @param itemId The item id.
* @param itemSlot The slot the item is in.
* @param objectId The object id.
* @param x The x coordinate.
* @param y The y coordinate.
*/
public ItemOnObjectEvent(int interfaceId, int itemId, int itemSlot, int objectId, int x, int y) {
super(0, interfaceId, itemId, itemSlot);
this.objectId = objectId;
this.position = new Position(x, y);
}
/**
* Gets the object id.
*
* @return The object id.
*/
public int getObjectId() {
return objectId;
}
/**
* Gets the position of the object.
*
* @return The position.
*/
public Position getPosition() {
return position;
}
} | package org.apollo.game.event.impl;
import org.apollo.game.event.Event;
import org.apollo.game.model.Position;
/**
* An {@link Event} sent by the client when an item is used on an object.
*
* @author Major
*/
public final class ItemOnObjectEvent extends InventoryItemEvent {
/**
* The object id the item was used on.
*/
private final int objectId;
/**
* The position of the object.
*/
private final Position position;
/**
* Creates an item on object event.
*
* @param interfaceId The interface id.
* @param id The item id.
* @param slot The slot the item is in.
* @param objectId The object id.
* @param x The x coordinate.
* @param y The y coordinate.
*/
public ItemOnObjectEvent(int interfaceId, int id, int slot, int objectId, int x, int y) {
super(0, interfaceId, id, slot);
this.objectId = objectId;
this.position = new Position(x, y);
}
/**
* Gets the object id.
*
* @return The object id.
*/
public int getObjectId() {
return objectId;
}
/**
* Gets the position of the object.
*
* @return The position.
*/
public Position getPosition() {
return position;
}
} |
Improve handling of large objects in pre-jekyll processes (cont'd)
Reduce grants arrays across all profiles. Goal is to reduce memory spikes when Jekyll attempts to sort the grants array during build time. | /**
* Splits the aggregated JSON file into individual JSON files per EIN
* Files are then available to Jekyll in the _data folder
*
* TODO Lots of opportunities to simplify - good first pull request 😉
*/
const {chain} = require('stream-chain');
const {parser} = require('stream-json');
const {streamArray} = require('stream-json/streamers/StreamArray');
const fs = require('fs');
try {
const pipeline = chain([
fs.createReadStream('aggregated.json'),
parser(),
streamArray(),
data => {
const doc = data.value;
// Mutute the array and keep only the largest 50 grants
doc.grants.sort((a, b) => b.amount - a.amount);
doc.grants.splice(50);
return doc;
},
]);
let counter = 0;
pipeline.on('data', (data) => {
counter++;
fs.writeFileSync('ein/' + data.ein + '.json', JSON.stringify(data), 'utf-8');
});
pipeline.on('end', () => {
console.log(`Processed ${counter} documents.`);
});
} catch (error) {
console.log(error);
}
| /**
* Splits the aggregated JSON file into individual JSON files per EIN
* Files are then available to Jekyll in the _data folder
*
* TODO Lots of opportunities to simplify - good first pull request 😉
*/
const {chain} = require('stream-chain');
const {parser} = require('stream-json');
const {streamArray} = require('stream-json/streamers/StreamArray');
const fs = require('fs');
try {
const pipeline = chain([
fs.createReadStream('aggregated.json'),
parser(),
streamArray(),
data => {
const doc = data.value;
return doc;
},
]);
let counter = 0;
pipeline.on('data', (data) => {
counter++;
fs.writeFileSync('ein/' + data.ein + '.json', JSON.stringify(data), 'utf-8');
});
pipeline.on('end', () => {
console.log(`Processed ${counter} documents.`);
});
} catch (error) {
console.log(error);
}
|
Check if url does exists (try to resolve!) | <?php
// Test if domain is set
if(isset($_GET["domain"]))
{
// Remove illegal characters
$url = filter_var($_GET["domain"], FILTER_SANITIZE_URL);
// Is this a valid domain?
if(!filter_var(gethostbyname($url), FILTER_VALIDATE_IP))
{
die("Invalid domain!");
}
}
else
{
die("No domain provided");
}
ob_end_flush();
ini_set("output_buffering", "0");
ob_implicit_flush(true);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
function echoEvent($datatext) {
echo "data: ".implode("\ndata: ", explode("\n", $datatext))."\n\n";
}
// echoEvent("***START***");
$proc = popen("sudo pihole -q ".$url, 'r');
while (!feof($proc)) {
echoEvent(fread($proc, 4096));
}
// echoEvent("***END***");
?>
| <?php
// Test if domain is set
if(isset($_GET["domain"]))
{
// Remove illegal characters
$url = filter_var($_GET["domain"], FILTER_SANITIZE_URL);
if(!filter_var("http://".$url, FILTER_VALIDATE_URL ) === true)
{
die("Invalid domain!");
}
}
else
{
die("No domain provided");
}
ob_end_flush();
ini_set("output_buffering", "0");
ob_implicit_flush(true);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
function echoEvent($datatext) {
echo "data: ".implode("\ndata: ", explode("\n", $datatext))."\n\n";
}
// echoEvent("***START***");
$proc = popen("sudo pihole -q ".$url, 'r');
while (!feof($proc)) {
echoEvent(fread($proc, 4096));
}
// echoEvent("***END***");
?>
|
Change type to abstract class | package jp.glassmoon.app;
import java.io.File;
import jp.glassmoon.events.GerritEvent;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gerrit.server.events.ChangeEvent;
import com.google.gerrit.server.events.PatchSetCreatedEvent;
public class App
{
public static void main( String[] args ) throws Exception
{
File f = new File("event.txt");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
GerritEvent ev = mapper.readValue(f, GerritEvent.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(ev));
ChangeEvent event;
if (new PatchSetCreatedEvent().type.equals(ev.type)) {
event = mapper.readValue(f, PatchSetCreatedEvent.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(event));
}
}
}
| package jp.glassmoon.app;
import java.io.File;
import jp.glassmoon.events.GerritEvent;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gerrit.server.events.PatchSetCreatedEvent;
public class App
{
public static void main( String[] args ) throws Exception
{
File f = new File("event.txt");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
GerritEvent ev = mapper.readValue(f, GerritEvent.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(ev));
if (new PatchSetCreatedEvent().type.equals(ev.type)) {
PatchSetCreatedEvent event = mapper.readValue(f, PatchSetCreatedEvent.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(event));
}
}
}
|
Implement isFriendsOnly to check for friends-only listings. | <?php
App::uses('AppModel', 'Model');
/**
* Product Listing Model
*/
class ProductListing extends AppModel
{
public $hasAndBelongsToMany = array(
'Buyer' => array(
'className' => 'Person',
'joinTable' => 'product_listing_buyers',
'associationForeignKey' => 'person_id',
'unique' => true
)
);
public $hasMany = array(
'Comment' => array(
'className' => 'ProductListingComment',
'foreignKey' => 'product_listing_id',
'dependent' => true
)
);
/**
* Checks if the given listing is owned by the person specified.
*
* @param int $listingId
* @param string $personId
* @return boolean
*/
public function isOwnedBy($listingId, $personId)
{
$listing = $this->findById($listingId);
return (string)$listing['ProductListing']['creator_id'] === (string)$personId;
}
/**
* Checks if a listing is only visible by friends.
*
* @param int $listingId
* @return boolean
*/
public function isFriendsOnly($listingId)
{
$listing = $this->findById($listingId);
return intval($listing['ProductListing']['friends_only']) !== 0;
}
}
| <?php
App::uses('AppModel', 'Model');
/**
* Product Listing Model
*/
class ProductListing extends AppModel
{
public $hasAndBelongsToMany = array(
'Buyer' => array(
'className' => 'Person',
'joinTable' => 'product_listing_buyers',
'associationForeignKey' => 'person_id',
'unique' => true
)
);
public $hasMany = array(
'Comment' => array(
'className' => 'ProductListingComment',
'foreignKey' => 'product_listing_id',
'dependent' => true
)
);
public function isOwnedBy($listingId, $personId)
{
$listing = $this->findById($listingId);
return (string)$listing['ProductListing']['creator_id'] === (string)$personId;
}
}
|
Add missing constructor for the entity class | <?php
namespace ModuleGenerator\Domain\Entity;
use ModuleGenerator\CLI\Service\Generate\GeneratableClass;
use ModuleGenerator\PhpGenerator\ClassName\ClassName;
final class Entity extends GeneratableClass
{
/** @var ClassName */
private $className;
/** @var string */
private $tableName;
/**
* @param ClassName $className
* @param string $tableName
*/
public function __construct(ClassName $className, string $tableName)
{
$this->className = $className;
$this->tableName = $tableName;
}
public function getClassName(): ClassName
{
return $this->className;
}
public function getTableName(): string
{
return $this->tableName;
}
public static function fromDataTransferObject(EntityDataTransferObject $entityDataTransferObject): self
{
return new self(
ClassName::fromDataTransferObject($entityDataTransferObject->className),
$entityDataTransferObject->tableName
);
}
}
| <?php
namespace ModuleGenerator\Domain\Entity;
use ModuleGenerator\CLI\Service\Generate\GeneratableClass;
use ModuleGenerator\PhpGenerator\ClassName\ClassName;
final class Entity extends GeneratableClass
{
/** @var ClassName */
private $className;
/** @var string */
private $tableName;
public function getClassName(): ClassName
{
return $this->className;
}
public function getTableName(): string
{
return $this->tableName;
}
public static function fromDataTransferObject(EntityDataTransferObject $entityDataTransferObject): self
{
return new self(
ClassName::fromDataTransferObject($entityDataTransferObject->className),
$entityDataTransferObject->tableName
);
}
}
|
Add helpers that allow divisions and multiplication with doubles | package com.sb.util;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
/**
*
*/
public final class MathUtil
{
private static MathContext context = MathContext.DECIMAL32;
public static BigDecimal divide(BigDecimal numerator, BigDecimal denominator)
{
return numerator.divide(denominator, context);
}
public static BigDecimal divide(BigDecimal numerator, int denominator)
{
return divide(numerator, BigDecimal.valueOf(denominator));
}
public static BigDecimal divide(BigDecimal numerator, double denominator)
{
return divide(numerator, BigDecimal.valueOf(denominator));
}
public static BigDecimal divide(int numerator, int denominator)
{
return divide(BigDecimal.valueOf(numerator), denominator);
}
public static BigDecimal multiply(BigDecimal a, int multiplier)
{
return a.multiply(BigDecimal.valueOf(multiplier));
}
public static BigDecimal multiply(BigDecimal a, double multiplier)
{
return a.multiply(BigDecimal.valueOf(multiplier));
}
}
| package com.sb.util;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
/**
*
*/
public final class MathUtil
{
private static MathContext context = MathContext.DECIMAL32;
public static BigDecimal divide(BigDecimal numerator, BigDecimal denominator)
{
return numerator.divide(denominator, context);
}
public static BigDecimal divide(BigDecimal numerator, int denominator)
{
return divide(numerator, BigDecimal.valueOf(denominator));
}
public static BigDecimal divide(int numerator, int denominator)
{
return divide(BigDecimal.valueOf(numerator), denominator);
}
public static BigDecimal multiply(BigDecimal a, int multiplier)
{
return a.multiply(BigDecimal.valueOf(multiplier));
}
}
|
Use correct filename for createUiDefinition.json
Azure expects the filename to be camel case for
`createUiDefinition.json` and will fail to accept a zipfile containing
with any different filename. This fixes the Gruntfile to look for the
correct filename and generate everything correctly.
Signed-off-by: Ryan Hass <7a1efea0847aa10fda44596a4a622bd3187d968e@users.noreply.github.com> | "use strict";
var grunt = require('grunt');
require('load-grunt-tasks')(grunt);
var branch=process.env.sourcebranch;
var folder=grunt.option('folder')||branch||'.';
var solutionjsonfiles = [`${folder}/**/*.json`,`!${folder}/node_modules/**/*.json`];
var createUiDefinition=`${folder}/createUiDefinition.json`;
grunt.initConfig({
fileExists: {
scripts: [`${folder}/mainTemplate.json`]
},
uidef: grunt.file.readJSON(createUiDefinition),
jsonlint: {
all: {
src: solutionjsonfiles
}
},
tv4: {
options: {
root: 'https://schema.management.azure.com/schemas/<%=uidef.version %>/CreateUIDefinition.MultiVm.json',
multi: true,
banUnknownProperties: true
},
myTarget: {
src: [createUiDefinition]
}
}
});
grunt.task.registerTask("test", ["fileExists","jsonlint","tv4"]);
| "use strict";
var grunt = require('grunt');
require('load-grunt-tasks')(grunt);
var branch=process.env.sourcebranch;
var folder=grunt.option('folder')||branch||'.';
var solutionjsonfiles = [`${folder}/**/*.json`,`!${folder}/node_modules/**/*.json`];
var createUIDefinition=`${folder}/createUIDefinition.json`;
grunt.initConfig({
fileExists: {
scripts: [`${folder}/mainTemplate.json`]
},
uidef: grunt.file.readJSON(createUIDefinition),
jsonlint: {
all: {
src: solutionjsonfiles
}
},
tv4: {
options: {
root: 'https://schema.management.azure.com/schemas/<%=uidef.version %>/CreateUIDefinition.MultiVm.json',
multi: true,
banUnknownProperties: true
},
myTarget: {
src: [createUIDefinition]
}
}
});
grunt.task.registerTask("test", ["fileExists","jsonlint","tv4"]);
|
Fix problem lines in nmap parsing. | import pandas as pd
import logging, os
import IPy as IP
log = logging.getLogger(__name__)
df3 = pd.read_csv('data/nmap/nmap.tsv', delimiter='\t')
df3.columns = ['host_and_fingerprint', 'port']
df3['host_and_fingerprint'] = df3['host_and_fingerprint'].map(lambda x: x.lstrip('Host:').rstrip(''))
df3['port'] = df3['port'].map(lambda x: x.lstrip('Ports:').rstrip(''))
#df3_hostfp_check = df3.applymap(lambda x: IP(df3_hostfp).iptype())
df3['ip'] = df3['host_and_fingerprint'].apply(lambda x: x.split(' ')[1])
#df3['host_and_fingerprint'] = df3['host_and_fingerprint'].apply(lambda x: IP(df3_hostfp).iptype())
print (df3)
#def logwrite():
#df3 = df3.to_csv('nmap.csv', index=None, encoding='utf-8')
| import pandas as pd
import logging, os
import IPy as IP
log = logging.getLogger(__name__)
df3 = pd.read_csv('nmap.tsv', delimiter='\t')
df3.columns = ['host_and_fingerprint', 'port']
df3['host_and_fingerprint'] = df3['host_and_fingerprint'].map(lambda x: x.lstrip('Host:').rstrip(''))
df3['port'] = df3['port'].map(lambda x: x.lstrip('Ports:').rstrip(''))
df3_hostfp = df3[['host_and_fingerprint']]
#df3_hostfp_check = df3.applymap(lambda x: IP(df3_hostfp).iptype())
df3['ip'] = df3['host_and_fingerprint'].apply(lambda x: x.split(' ')[1])
#df3['host_and_fingerprint'] = df3['host_and_fingerprint'].apply(lambda x: IP(df3_hostfp).iptype())
print (df3_hostfp_check)
#def logwrite():
#df3 = df3.to_csv('nmap.csv', index=None, encoding='utf-8')
|
Trim the team name before adding new team.
Former-commit-id: 1231ec173ad3c1cca919e1ba1d197af1eb7a9c5b | function viewTeams() {
getTeams(
success = function (data) {
populateTeamsTable(data.teams);
},
error = function (jqxhr) {
handleApiError(jqxhr);
}
);
function populateTeamsTable(data) {
var teams = _.sortBy(data, function (d) {return d.name.toLowerCase()});
var teamsHtml = templates.teamList(teams);
$('.section').html(teamsHtml);
$('.collections-select-table tbody tr').click(function () {
$('.collections-select-table tbody tr').removeClass('selected');
$(this).addClass('selected');
var teamId = $(this).attr('data-id');
viewTeamDetails(teamId);
});
$('.form-create-team').submit(function (e) {
e.preventDefault();
var teamName = $('#create-team-name').val();
if (teamName.length < 1) {
sweetAlert("Please enter a user name.");
return;
}
teamName = teamName.trim();
postTeam(teamName);
});
}
}
| function viewTeams() {
getTeams(
success = function (data) {
populateTeamsTable(data.teams);
},
error = function (jqxhr) {
handleApiError(jqxhr);
}
);
function populateTeamsTable(data) {
var teams = _.sortBy(data, function (d) {return d.name.toLowerCase()});
var teamsHtml = templates.teamList(teams);
$('.section').html(teamsHtml);
$('.collections-select-table tbody tr').click(function () {
$('.collections-select-table tbody tr').removeClass('selected');
$(this).addClass('selected');
var teamId = $(this).attr('data-id');
viewTeamDetails(teamId);
});
$('.form-create-team').submit(function (e) {
e.preventDefault();
var teamName = $('#create-team-name').val();
if (teamName.length < 1) {
sweetAlert("Please enter a user name.");
return;
}
postTeam(teamName);
});
}
}
|
Fix panel for when there is no masterPasswordState | /*
* This Source Code is subject to the terms of the Mozilla Public License
* version 2.0 (the "License"). You can obtain a copy of the License at
* http://mozilla.org/MPL/2.0/.
*/
"use strict";
let {EventTarget, emit} = require("../../lib/eventTarget");
module.exports = exports = new EventTarget();
exports.site = null;
exports.origSite = null;
exports.pwdList = null;
exports.masterPasswordState = null;
let stateToPanel = {
"unset": ["change-master"],
"set": ["enter-master", "change-master"],
"known": ["password-list", "generate-password", "legacy-password", "confirm"]
};
function set(state)
{
for (let key of ["site", "origSite", "pwdList", "masterPasswordState"])
if (key in state)
exports[key] = state[key];
if ("masterPasswordState" in state)
{
let {getActivePanel, setActivePanel} = require("./utils");
let panels = stateToPanel[state.masterPasswordState];
if (panels.indexOf(getActivePanel()) < 0)
setActivePanel(panels[0]);
}
emit(exports, "update");
}
exports.set = set;
| /*
* This Source Code is subject to the terms of the Mozilla Public License
* version 2.0 (the "License"). You can obtain a copy of the License at
* http://mozilla.org/MPL/2.0/.
*/
"use strict";
let {EventTarget, emit} = require("../../lib/eventTarget");
module.exports = exports = new EventTarget();
exports.site = null;
exports.origSite = null;
exports.pwdList = null;
exports.masterPasswordState = null;
let stateToPanel = {
"unset": "change-master",
"set": ["enter-master", "change-master"],
"known": ["password-list", "generate-password", "legacy-password", "confirm"]
};
function set(state)
{
for (let key of ["site", "origSite", "pwdList", "masterPasswordState"])
if (key in state)
exports[key] = state[key];
if ("masterPasswordState" in state)
{
let {getActivePanel, setActivePanel} = require("./utils");
let panels = stateToPanel[state.masterPasswordState];
if (panels.indexOf(getActivePanel()) < 0)
setActivePanel(panels[0]);
}
emit(exports, "update");
}
exports.set = set;
|
Allow the module to be seeded with an array of patterns | 'use strict';
var murl = require('murl');
var Patterns = module.exports = function (patterns) {
if (!(this instanceof Patterns))
return new Patterns(patterns);
this._patterns = (patterns || []).map(function (ptn) {
return [compile(ptn), ptn, undefined];
});
};
var compile = function (ptn) {
if (typeof ptn === 'string') return murl(ptn);
return function (target) {
return target.match(ptn);
};
};
Patterns.prototype.add = function (ptn, val) {
this._patterns.push([compile(ptn), ptn, val]);
};
Patterns.prototype.match = function (target, index) {
var self = this;
var next = function () {
return self.match(target, index+1);
};
var ptn, match;
if (!index) index = 0;
for (var l = this._patterns.length; index < l; index++) {
ptn = this._patterns[index];
match = ptn[0](target);
if (match) return {
target: target,
pattern: ptn[1],
params: match,
value: ptn[2],
next: next
};
}
return null;
};
| 'use strict';
var murl = require('murl');
var Patterns = module.exports = function (patterns) {
if (!(this instanceof Patterns))
return new Patterns(patterns);
this._patterns = patterns || [];
};
var compile = function (ptn) {
if (typeof ptn === 'string') return murl(ptn);
return function (target) {
return target.match(ptn);
};
};
Patterns.prototype.add = function (ptn, val) {
this._patterns.push([compile(ptn), ptn, val]);
};
Patterns.prototype.match = function (target, index) {
var self = this;
var next = function () {
return self.match(target, index+1);
};
var ptn, match;
if (!index) index = 0;
for (var l = this._patterns.length; index < l; index++) {
ptn = this._patterns[index];
match = ptn[0](target);
if (match) return {
target: target,
pattern: ptn[1],
params: match,
value: ptn[2],
next: next
};
}
return null;
};
|
Rename User model to AppUser | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class AppUser(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('app_user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user_id', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
| from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
is_admin = db.Column(db.Boolean())
def __init__(self, email, password, is_admin=False):
self.email = email
self.active = True
self.is_admin = is_admin
self.set_password(password)
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(User)
db.UniqueConstraint('user', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
|
Remove mention of Traits (removed in e1ced0b3) | # encoding: utf-8
"""A fancy version of Python's builtin :func:`dir` function.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from .py3compat import string_types
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
def safe_hasattr(obj, attr):
"""In recent versions of Python, hasattr() only catches AttributeError.
This catches all errors.
"""
try:
getattr(obj, attr)
return True
except:
return False
def dir2(obj):
"""dir2(obj) -> list of strings
Extended version of the Python builtin dir(), which does a few extra
checks.
This version is guaranteed to return only a list of true strings, whereas
dir() returns anything that objects inject into themselves, even if they
are later not really valid for attribute access (many extension libraries
have such bugs).
"""
# Start building the attribute list via dir(), and then complete it
# with a few extra special-purpose calls.
try:
words = set(dir(obj))
except Exception:
# TypeError: dir(obj) does not return a list
words = set()
# filter out non-string attributes which may be stuffed by dir() calls
# and poor coding in third-party modules
words = [w for w in words if isinstance(w, string_types)]
return sorted(words)
| # encoding: utf-8
"""A fancy version of Python's builtin :func:`dir` function.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from .py3compat import string_types
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
def safe_hasattr(obj, attr):
"""In recent versions of Python, hasattr() only catches AttributeError.
This catches all errors.
"""
try:
getattr(obj, attr)
return True
except:
return False
def dir2(obj):
"""dir2(obj) -> list of strings
Extended version of the Python builtin dir(), which does a few extra
checks, and handles Traits objects, which can confuse dir().
This version is guaranteed to return only a list of true strings, whereas
dir() returns anything that objects inject into themselves, even if they
are later not really valid for attribute access (many extension libraries
have such bugs).
"""
# Start building the attribute list via dir(), and then complete it
# with a few extra special-purpose calls.
try:
words = set(dir(obj))
except Exception:
# TypeError: dir(obj) does not return a list
words = set()
# filter out non-string attributes which may be stuffed by dir() calls
# and poor coding in third-party modules
words = [w for w in words if isinstance(w, string_types)]
return sorted(words)
|
Fix for Custom Table Name | <?php
/**
* @link http://mikhailmikhalev.ru
* @author Mikhail Mikhalev
*/
namespace nhkey\arh\managers;
use Yii;
use yii\db\Connection;
use yii\di\Instance;
/**
* Class DBManager for save history in DB
* @package nhkey\arh
*/
class DBManager extends BaseManager
{
public static $defaultTableName = '{{%modelhistory}}'; // static default for migration
public $tableName;
/**
* @var string
*/
public static $db = 'db';
/**
* @param array $data
*/
public function saveField($data)
{
$table = isset($this->tableName) ? $this->tableName : $this::$defaultTableName;
self::getDB()->createCommand()
->insert($table, $data)->execute();
}
/**
* @return object Return database connection
* @throws \yii\base\InvalidConfigException
*/
private static function getDB()
{
return Instance::ensure(self::$db, Connection::className());
}
}
| <?php
/**
* @link http://mikhailmikhalev.ru
* @author Mikhail Mikhalev
*/
namespace nhkey\arh\managers;
use Yii;
use yii\db\Connection;
use yii\di\Instance;
/**
* Class DBManager for save history in DB
* @package nhkey\arh
*/
class DBManager extends BaseManager
{
public $tableName = '{{%modelhistory}}';
/**
* @var string
*/
public static $db = 'db';
/**
* @param array $data
*/
public function saveField($data)
{
self::getDB()->createCommand()
->insert($this->tableName, $data)->execute();
}
/**
* @return object Return database connection
* @throws \yii\base\InvalidConfigException
*/
private static function getDB()
{
return Instance::ensure(self::$db, Connection::className());
}
}
|
Update URLs in ExampleIter to match the changes in httpbin's API
/redirect was changed to /relative-redirect | package httpclient_test
import (
"fmt"
"net/http"
"gnd.la/net/httpclient"
)
func ExampleIter() {
// Passing nil only works on non-App Engine and while
// running tests. Usually you should pass a *app.Context
// to httpclient.New.
c := httpclient.New(nil)
req, err := http.NewRequest("GET", "http://httpbin.org/relative-redirect/3", nil)
if err != nil {
panic(err)
}
iter := c.Iter(req)
// Don't forget to close the Iter after you're done with it
defer iter.Close()
var urls []string
for iter.Next() {
urls = append(urls, iter.Response().URL().String())
}
// iter.Assert() could also be used here
if err := iter.Err(); err != nil {
panic(err)
}
fmt.Println("Last", iter.Response().URL())
fmt.Println("Intermediate", urls)
// Output:
// Last http://httpbin.org/get
// Intermediate [http://httpbin.org/relative-redirect/3 http://httpbin.org/relative-redirect/2 http://httpbin.org/relative-redirect/1]
}
| package httpclient_test
import (
"fmt"
"net/http"
"gnd.la/net/httpclient"
)
func ExampleIter() {
// Passing nil only works on non-App Engine and while
// running tests. Usually you should pass a *app.Context
// to httpclient.New.
c := httpclient.New(nil)
req, err := http.NewRequest("GET", "http://httpbin.org/redirect/3", nil)
if err != nil {
panic(err)
}
iter := c.Iter(req)
// Don't forget to close the Iter after you're done with it
defer iter.Close()
var urls []string
for iter.Next() {
urls = append(urls, iter.Response().URL().String())
}
// iter.Assert() could also be used here
if err := iter.Err(); err != nil {
panic(err)
}
fmt.Println("Last", iter.Response().URL())
fmt.Println("Intermediate", urls)
// Output:
// Last http://httpbin.org/get
// Intermediate [http://httpbin.org/redirect/3 http://httpbin.org/redirect/2 http://httpbin.org/redirect/1]
}
|
Fix wrong dev config logic | process.on('unhandledRejection', err => {
throw err;
});
const express = require('express');
const next = require('next');
const { createRouter } = require('soya-next/server/router');
const { soya } = require('soya-next/server/config');
// @remove-on-eject-begin
const conf = require('../next.config');
// @remove-on-eject-end
const host = soya.config.host || '0.0.0.0';
const port = soya.config.port || 3000;
const dev = typeof soya.config.dev !== 'undefined' ? soya.config.dev : process.env.NODE_ENV !== 'production';
const app = next({
dev,
// @remove-on-eject-begin
conf,
// @remove-on-eject-end
});
app.prepare()
.then(() => {
const server = express();
server.use(createRouter(app, soya.config));
server.listen(port, host, err => {
if (err) {
throw err;
}
// eslint-disable-next-line no-console
console.log(`> Ready on ${host}:${port}`);
});
})
.catch(ex => {
// eslint-disable-next-line no-console
console.error(ex.stack);
process.exit(1);
});
| process.on('unhandledRejection', err => {
throw err;
});
const express = require('express');
const next = require('next');
const { createRouter } = require('soya-next/server/router');
const { soya } = require('soya-next/server/config');
// @remove-on-eject-begin
const conf = require('../next.config');
// @remove-on-eject-end
const host = soya.config.host || '0.0.0.0';
const port = soya.config.port || 3000;
const dev = soya.config.dev ? soya.config.dev : process.env.NODE_ENV !== 'production';
const app = next({
dev,
// @remove-on-eject-begin
conf,
// @remove-on-eject-end
});
app.prepare()
.then(() => {
const server = express();
server.use(createRouter(app, soya.config));
server.listen(port, host, err => {
if (err) {
throw err;
}
// eslint-disable-next-line no-console
console.log(`> Ready on ${host}:${port}`);
});
})
.catch(ex => {
// eslint-disable-next-line no-console
console.error(ex.stack);
process.exit(1);
});
|
Make download work using url filename
Add user agent string | from setuptools import setup, find_packages
from hdx.utilities.path import script_dir_plus_file
def get_version():
version_file = open(script_dir_plus_file('version.txt', get_version))
return version_file.read().strip()
requirements = ['ckanapi',
'colorlog',
'ndg-httpsclient',
'pyasn1',
'pyOpenSSL',
'pyaml',
'requests',
'scraperwiki',
'typing'
]
setup(
name='hdx-python-api',
version=get_version(),
packages=find_packages(exclude=['ez_setup', 'tests', 'tests.*']),
url='http://data.humdata.org/',
license='PSF',
author='Michael Rans',
author_email='rans@email.com',
description='HDX Python Library',
install_requires=requirements,
package_data={
# If any package contains *.yml files, include them:
'': ['*.yml'],
},
)
| from setuptools import setup, find_packages
from hdx.utilities.path import script_dir_plus_file
requirements = ['ckanapi',
'colorlog',
'ndg-httpsclient',
'pyasn1',
'pyOpenSSL',
'pyaml',
'requests',
'scraperwiki',
'typing'
]
version_file = open(script_dir_plus_file('version.txt', requirements))
version = version_file.read().strip()
setup(
name='hdx-python-api',
version=version,
packages=find_packages(exclude=['ez_setup', 'tests', 'tests.*']),
url='http://data.humdata.org/',
license='PSF',
author='Michael Rans',
author_email='rans@email.com',
description='HDX Python Library',
install_requires=requirements,
package_data={
# If any package contains *.yml files, include them:
'': ['*.yml'],
},
)
|
Exclude iOS Chrome as mobile safari | (function(window, Models) {
function Browser() {
var self = this;
self._isMobileSafariStandalone = function() {
return self.isMobileSafari && window.navigator.standalone;
};
}
Browser.prototype.isMobileSafari = function() {
return (/Version\/\S+ Mobile\/\w+ Safari\//).test(window.navigator.userAgent);
};
Browser.prototype.canScanCode = function() {
return this.isMobileSafari() && !this._isMobileSafariStandalone();
};
Browser.prototype.hasCryptoGetRandomValues = function() {
var crypto = window.crypto || window.msCrypto;
if (crypto && crypto.getRandomValues) {
return true;
} else {
return false;
}
};
Models.browser = new Browser();
})(window, CoinPocketApp.Models);
| (function(window, Models) {
function Browser() {
var self = this;
self._isMobileSafariStandalone = function() {
return self.isMobileSafari && window.navigator.standalone;
};
}
Browser.prototype.isMobileSafari = function() {
return (/Mobile\/\w+ Safari\//).test(window.navigator.userAgent);
};
Browser.prototype.canScanCode = function() {
return this.isMobileSafari() && !this._isMobileSafariStandalone();
};
Browser.prototype.hasCryptoGetRandomValues = function() {
var crypto = window.crypto || window.msCrypto;
if (crypto && crypto.getRandomValues) {
return true;
} else {
return false;
}
};
Models.browser = new Browser();
})(window, CoinPocketApp.Models);
|
Add unused DATABASE_ENGINE, DATABASE_NAME to pacify celeryinit | # -*- coding: utf-8 -*-
CELERY_BACKEND = "mongodb"
# We shouldn't need to supply these because we're using Mongo,
# but Celery gives us errors if we don't.
DATABASE_ENGINE = "sqlite3"
DATABASE_NAME = "celery.db"
AMQP_SERVER = "localhost"
AMQP_PORT = 5672
AMQP_VHOST = "celeryvhost"
AMQP_USER = "celeryuser"
AMQP_PASSWORD = "celerypw"
CELERYD_LOG_FILE = "celeryd.log"
CELERYD_PID_FILE = "celeryd.pid"
CELERYD_DAEMON_LOG_LEVEL = "INFO"
CELERY_MONGODB_BACKEND_SETTINGS = {
"host":"localhost",
"port":27017,
"database":"celery"
}
CELERY_AMQP_EXCHANGE = "tasks"
CELERY_AMQP_PUBLISHER_ROUTING_KEY = "task.regular"
CELERY_AMQP_EXCHANGE_TYPE = "topic"
CELERY_AMQP_CONSUMER_QUEUE = "forge_tasks"
CELERY_AMQP_CONSUMER_ROUTING_KEY = "forge.#"
CELERY_IMPORTS = ("pyforge.tasks.MailTask")
| # -*- coding: utf-8 -*-
CELERY_BACKEND = "mongodb"
AMQP_SERVER = "localhost"
AMQP_PORT = 5672
AMQP_VHOST = "celeryvhost"
AMQP_USER = "celeryuser"
AMQP_PASSWORD = "celerypw"
CELERYD_LOG_FILE = "celeryd.log"
CELERYD_PID_FILE = "celeryd.pid"
CELERYD_DAEMON_LOG_LEVEL = "INFO"
CELERY_MONGODB_BACKEND_SETTINGS = {
"host":"localhost",
"port":27017,
"database":"celery"
}
CELERY_AMQP_EXCHANGE = "tasks"
CELERY_AMQP_PUBLISHER_ROUTING_KEY = "task.regular"
CELERY_AMQP_EXCHANGE_TYPE = "topic"
CELERY_AMQP_CONSUMER_QUEUE = "forge_tasks"
CELERY_AMQP_CONSUMER_ROUTING_KEY = "forge.#"
CELERY_IMPORTS = ("pyforge.tasks.MailTask")
|
Add error catch to download component | import Ember from 'ember';
export default Ember.Controller.extend({
queryParams: ['viewType', 'nodeId'],
query: Ember.inject.service(),
viewType: 'live',
notify: Ember.inject.service(),
modelArrived: Ember.observer('model', function() {
const nodeList = this.get('model.nodes');
const nodeTuples = nodeList.map(node => {
return [node.properties.id, node.properties];
});
const nodeMap = new Map(nodeTuples);
this.set('nodeMap', nodeMap);
if (!this.get('nodeId')) {
this.set('nodeId', nodeList[0].properties.id);
}
}),
selectedNodeMeta: Ember.computed('nodeId', function() {
const nodeMap = this.get('nodeMap');
return nodeMap.get(this.get('nodeId'));
}),
actions: {
onSelect(nodeId) {
this.set('nodeId', nodeId);
},
download(params) {
this.get('query').sensorDownload(params).then(resp => {
this.transitionToRoute('datadump.download', resp.ticket, {queryParams: {data_type: 'csv'}});
}).catch(() => {
this.get('notify').error('Could not process request. ' +
'Try double-checking your request, and email plenario@uchicago.edu if the problem persists.');
}
);
}
}
});
| import Ember from 'ember';
export default Ember.Controller.extend({
queryParams: ['viewType', 'nodeId'],
query: Ember.inject.service(),
viewType: 'live',
modelArrived: Ember.observer('model', function() {
const nodeList = this.get('model.nodes');
const nodeTuples = nodeList.map(node => {
return [node.properties.id, node.properties];
});
const nodeMap = new Map(nodeTuples);
this.set('nodeMap', nodeMap);
if (!this.get('nodeId')) {
this.set('nodeId', nodeList[0].properties.id);
}
}),
selectedNodeMeta: Ember.computed('nodeId', function() {
const nodeMap = this.get('nodeMap');
return nodeMap.get(this.get('nodeId'));
}),
actions: {
onSelect(nodeId) {
this.set('nodeId', nodeId);
},
download(params) {
this.get('query').sensorDownload(params).then(resp => {
this.transitionToRoute('datadump.download', resp.ticket, {queryParams: {data_type: 'csv'}});
});
}
}
});
|
Fix copy and paste error in javadoc. | package uk.ac.ebi.quickgo.annotation.validation;
import java.lang.annotation.*;
import javax.validation.Constraint;
import javax.validation.Payload;
/**
* Annotation that allows a list of strings, separated by commas to be validated as Reference Ids (full or partial).
* @author Tony Wardell
* Date: 14/06/2016
* Time: 12:03
* Created with IntelliJ IDEA.
*/
@Constraint(validatedBy = ReferenceValuesValidation.class)
@Documented
@Target({ElementType.METHOD,
ElementType.FIELD,
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReferenceValidator {
String message() default "The reference value is invalid";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| package uk.ac.ebi.quickgo.annotation.validation;
import java.lang.annotation.*;
import javax.validation.Constraint;
import javax.validation.Payload;
/**
* Annotation that allows a list of strings, separated by commas to be validated as Gene Product IDs
* @author Tony Wardell
* Date: 14/06/2016
* Time: 12:03
* Created with IntelliJ IDEA.
*/
@Constraint(validatedBy = ReferenceValuesValidation.class)
@Documented
@Target({ElementType.METHOD,
ElementType.FIELD,
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReferenceValidator {
String message() default "The reference value is invalid";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
|
Fix settings manager override with null key | "use strict";
var JSONSerializer = require('./JSONSerializer'),
_ = require('lodash');
var SettingsManager = function (data, serializer) {
this._data = data || {};
this._serializer = serializer || new JSONSerializer();
};
SettingsManager.prototype.getValue = function (key, defaultValue) {
if (typeof this._data[key] !== 'undefined')
return this._data[key];
else if (hasLocalStorageSupport())
return this._serializer.deserialize(window.localStorage.getItem(key));
else
return defaultValue;
};
SettingsManager.prototype.setValue = function (key, value) {
if (key) {
this._data[key] = value;
if (hasLocalStorageSupport())
window.localStorage.setItem(key, this._serializer.serialize(value));
} else {
this._data = _.merge(this._data, value);
}
};
function hasLocalStorageSupport() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
module.exports = SettingsManager; | "use strict";
var JSONSerializer = require('./JSONSerializer'),
_ = require('lodash');
var SettingsManager = function (data, serializer) {
this._data = data || {};
this._serializer = serializer || new JSONSerializer();
};
SettingsManager.prototype.getValue = function (key, defaultValue) {
if (typeof this._data[key] !== 'undefined')
return this._data[key];
else if (hasLocalStorageSupport())
return this._serializer.deserialize(window.localStorage.getItem(key));
else
return defaultValue;
};
SettingsManager.prototype.setValue = function (key, value) {
if (key) {
this._data[key] = value;
if (hasLocalStorageSupport())
window.localStorage.setItem(key, this._serializer.serialize(value));
} else {
this._data = _.assign(this._data, value);
}
};
function hasLocalStorageSupport() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
module.exports = SettingsManager; |
Reset the access control details showing when coming back | import AuthenticatedRouteMixin from 'ui/mixins/authenticated-route';
import Ember from 'ember';
import C from 'ui/utils/constants';
export default Ember.Route.extend(AuthenticatedRouteMixin,{
model: function() {
var headers = {};
headers[C.HEADER.PROJECT] = undefined;
return this.get('store').find('githubconfig', null, {headers: headers, forceReload: true}).then(function(collection) {
return collection.get('firstObject');
});
},
setupController: function(controller, model) {
controller.set('model', model.clone());
controller.set('originalModel', model);
controller.set('confirmDisable',false);
controller.set('saving',false);
controller.set('saved',true);
controller.set('testing',false);
controller.set('wasShowing',false);
controller.set('organizations', this.get('session.orgs')||[]);
controller.set('error',null);
}
});
| import AuthenticatedRouteMixin from 'ui/mixins/authenticated-route';
import Ember from 'ember';
import C from 'ui/utils/constants';
export default Ember.Route.extend(AuthenticatedRouteMixin,{
model: function() {
var headers = {};
headers[C.HEADER.PROJECT] = undefined;
return this.get('store').find('githubconfig', null, {headers: headers, forceReload: true}).then(function(collection) {
return collection.get('firstObject');
});
},
setupController: function(controller, model) {
controller.set('model', model.clone());
controller.set('originalModel', model);
controller.set('confirmDisable',false);
controller.set('saving',false);
controller.set('saved',true);
controller.set('testing',false);
controller.set('organizations', this.get('session.orgs')||[]);
controller.set('error',null);
}
});
|
Add more details to py35 EoL changes | import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# TODO remove when python 3.5 is EoL (i.e. 2020-09-13)
# https://devguide.python.org/#status-of-python-branches
# https://www.python.org/dev/peps/pep-0478/
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
| import os
import sys
from contextlib import contextmanager
def is_buffer(obj, mode):
return ("r" in mode and hasattr(obj, "read")) or (
"w" in mode and hasattr(obj, "write")
)
@contextmanager
def open_file(path_or_buf, mode="r"):
if is_buffer(path_or_buf, mode):
yield path_or_buf
elif sys.version_info < (3, 6) and isinstance(path_or_buf, os.PathLike):
# todo: remove when 3.5 is EoL
with open(str(path_or_buf), mode) as f:
yield f
else:
with open(path_or_buf, mode) as f:
yield f
|
Fix port number for eventing stats
Change-Id: Ifaa7e9957f919febb1a297683077cd1c71c6aa9d
Reviewed-on: http://review.couchbase.org/84633
Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com>
Reviewed-by: Mahesh Mandhare <f05f25073b6d9a2858c6a374b80c02d5a2bccf33@couchbase.com> | from cbagent.collectors import Collector
class EventingStats(Collector):
COLLECTOR = "eventing_stats"
def __init__(self, settings, test):
super().__init__(settings)
self.eventing_node = test.function_nodes[0]
self.functions = test.functions
def _get_processing_stats(self, function_name="perf-test1"):
port = '8096'
uri = "/getEventProcessingStats?name={}".format(function_name)
samples = self.get_http(path=uri, server=self.eventing_node, port=port)
return samples
def sample(self):
for name, function in self.functions.items():
stats = self._get_processing_stats(function_name=name)
if stats:
self.update_metric_metadata(stats.keys(), bucket=name)
self.store.append(stats, cluster=self.cluster,
bucket=name, collector=self.COLLECTOR)
def update_metadata(self):
self.mc.add_cluster()
for name, function in self.functions.items():
self.mc.add_bucket(name)
| from cbagent.collectors import Collector
class EventingStats(Collector):
COLLECTOR = "eventing_stats"
def __init__(self, settings, test):
super().__init__(settings)
self.eventing_node = test.function_nodes[0]
self.functions = test.functions
def _get_processing_stats(self, function_name="perf-test1"):
port = '25000'
uri = "/getEventProcessingStats?name={}".format(function_name)
samples = self.get_http(path=uri, server=self.eventing_node, port=port)
return samples
def sample(self):
for name, function in self.functions.items():
stats = self._get_processing_stats(function_name=name)
if stats:
self.update_metric_metadata(stats.keys(), bucket=name)
self.store.append(stats, cluster=self.cluster,
bucket=name, collector=self.COLLECTOR)
def update_metadata(self):
self.mc.add_cluster()
for name, function in self.functions.items():
self.mc.add_bucket(name)
|
Fix migrations mongo url variable | var stream = require('stream')
var mongoose = require('mongoose')
exports.mongoose = mongoose
exports.connectMongoose = function() {
mongoose.connect(process.env.MONGOHQ_URL || 'mongodb://localhost/meku')
return this
}
exports.progressMonitor = function(num) {
var ii = 0
var tick = num || 250
return function(char) {
if (ii++ % tick == 0) process.stdout.write(char || '.')
}
}
exports.consumer = function(onRow, callback) {
var s = new stream.Writable({ objectMode: true })
s._write = function(row, enc, cb) { onRow(row, cb) }
s.on('finish', callback)
return s
}
exports.done = function(err) {
if (err) throw err
mongoose.disconnect(function() {
console.log('DONE.')
})
}
| var stream = require('stream')
var mongoose = require('mongoose')
exports.mongoose = mongoose
exports.connectMongoose = function() {
mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost/meku')
return this
}
exports.progressMonitor = function(num) {
var ii = 0
var tick = num || 250
return function(char) {
if (ii++ % tick == 0) process.stdout.write(char || '.')
}
}
exports.consumer = function(onRow, callback) {
var s = new stream.Writable({ objectMode: true })
s._write = function(row, enc, cb) { onRow(row, cb) }
s.on('finish', callback)
return s
}
exports.done = function(err) {
if (err) throw err
mongoose.disconnect(function() {
console.log('DONE.')
})
} |
Improve tolerance when matching url-paths for router-navigation. | /* @flow */
import type { State } from '../../common/types';
import React from 'react';
import AddrListByRoom from './AddressListByRoom';
import AddrList from './AddressList';
import { connect } from 'react-redux';
import linksMessages from '../../common/app/linksMessages';
import { isEmpty, pathOr, reject, test } from 'ramda';
import { Block, Title, View } from '../components';
import { Box } from 'reflexbox';
type HomePageProps = {
smartHomeState: Object,
location: Object,
};
const HomePage = ({ smartHomeState, location }: HomePageProps) => {
const { livestate, prefs } = smartHomeState;
/* Built address-list, remove some address-types which should not be displayed */
const addresses = reject(addr => addr.type === 'fb', livestate);
if (isEmpty(addresses)) {
return (
<Block>
<p>Waiting for SmartHome-State...</p>
</Block>
);
}
const viewType = pathOr('changes', ['pathname'], location);
const addrList = test(/rooms$/, viewType)
? <AddrListByRoom addresses={addresses} prefs={prefs} />
: <AddrList addresses={addresses} />;
return (
<View>
<Title message={linksMessages.home} />
<Box py={2}>
{addrList}
</Box>
</View>
);
};
export default connect((state: State) => ({
smartHomeState: state.smartHome,
}))(HomePage);
| /* @flow */
import type { State } from '../../common/types';
import React from 'react';
import AddrListByRoom from './AddressListByRoom';
import AddrList from './AddressList';
import { connect } from 'react-redux';
import linksMessages from '../../common/app/linksMessages';
import { isEmpty, pathOr, reject } from 'ramda';
import {
Block,
Title,
View,
} from '../components';
import { Box } from 'reflexbox';
type HomePageProps = {
smartHomeState: Object,
location: Object,
};
const HomePage = ({ smartHomeState, location }: HomePageProps) => {
const { livestate, prefs } = smartHomeState;
/* Built address-list, remove some address-types which should not be displayed */
const addresses = reject(addr => addr.type === 'fb', livestate);
if (isEmpty(addresses)) {
return (
<Block>
<p>Waiting for SmartHome-State...</p>
</Block>
);
}
const viewType = pathOr('changes', ['pathname'], location);
const addrList = viewType === 'changes'
? <AddrList addresses={addresses} />
: <AddrListByRoom addresses={addresses} prefs={prefs} />;
return (
<View>
<Title message={linksMessages.home} />
<Box py={2}>
{addrList}
</Box>
</View>
);
};
export default connect(
(state: State) => ({
smartHomeState: state.smartHome,
}),
)(HomePage);
|
Use some collection magic in the tests. | <?php
namespace Williamson\TPLinkSmartplug\tests;
use Illuminate\Support\Collection;
use ReflectionClass;
use ReflectionMethod;
use Williamson\TPLinkSmartplug\TPLinkCommand;
class TPLinkCommandTest extends \PHPUnit_Framework_TestCase
{
/** @test checks all commands returned are an array */
public function it_checks_all_commands_returned_are_an_array()
{
$reflector = new ReflectionClass(TPLinkCommand::class);
$methods = collect($reflector->getMethods(ReflectionMethod::IS_PUBLIC));
$methods
->filter(function (ReflectionMethod $method) {
return $method->getNumberOfParameters() === 0;
})
->each(function (ReflectionMethod $method) {
$name = $method->getName();
$this->assertInternalType('array', TPLinkCommand::$name());
});
}
}
| <?php
namespace Williamson\TPLinkSmartplug\tests;
use ReflectionClass;
use ReflectionMethod;
use Williamson\TPLinkSmartplug\TPLinkCommand;
class TPLinkCommandTest extends \PHPUnit_Framework_TestCase
{
/** @test checks all commands returned are an array */
public function it_checks_all_commands_returned_are_an_array()
{
$reflector = new ReflectionClass(TPLinkCommand::class);
$methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
if ($method->getNumberOfParameters() == 0) {
$name = $method->getName();
$this->assertInternalType('array', TPLinkCommand::$name());
}
}
}
//TODO Methods that require a parameter
}
|
Add guard clause to beginning of update method | myApp.service('breadCrumbService', function($location) {
this.crumbs = [
];
this.current = {
path: './',
display:'Inventories'
};
this.update = function(crumb) {
console.log("Updating crumbs:", crumb);
if(this.current.path === crumb.path || crumb.path === '/')
return;
var index = this.crumbs.findIndex(function(c) {
return c.path === crumb.path;
});
if(index == -1) {
this.crumbs.push(this.current);
this.current = crumb;
}
else {
this.current = this.crumbs[index];
this.crumbs = this.crumbs.slice(0, index);
}
};
this.get = function(i) {
var index = i || 0;
return this.crumbs[index];
};
});
| myApp.service('breadCrumbService', function($location) {
this.crumbs = [
];
this.current = {
path: './',
display:'Inventories'
};
this.update = function(crumb) {
console.log("Updating crumbs:", crumb);
var index = this.crumbs.findIndex(function(c) {
return c.path === crumb.path;
});
if(index == -1) {
this.crumbs.push(this.current);
this.current = crumb;
}
else {
this.current = this.crumbs[index];
this.crumbs = this.crumbs.slice(0, index);
}
};
this.get = function(i) {
var index = i || 0;
return this.crumbs[index];
};
});
|
Remove extraneous require of util | // jshint esversion:6
/**
* @module extensive
* @desc extensive exports the {@link extensive~extend} function.
*/
const extensive = (function() {
"use strict";
const _ = require('lodash');
const extend = function(constructor, instanceMethods, classMethods) {
instanceMethods = instanceMethods || {};
let parent = this || function() {};
constructor.prototype = _.create(parent.prototype, instanceMethods, {
'constructor': constructor,
'__super__': parent
});
_.merge(constructor, _.omit(parent, ['constructor', '__super__']), classMethods);
if (!_.has(parent, "extend")) {
constructor.extend = extend;
}
return constructor;
};
return extend;
})();
module.exports = extensive;
| // jshint esversion:6
/**
* @module extensive
* @desc extensive exports the {@link extensive~extend} function.
*/
const extensive = (function() {
"use strict";
const _ = require('lodash');
const util = require('util');
const extend = function(constructor, instanceMethods, classMethods) {
instanceMethods = instanceMethods || {};
let parent = this || function() {};
constructor.prototype = _.create(parent.prototype, instanceMethods, {
'constructor': constructor,
'__super__': parent
});
_.merge(constructor, _.omit(parent, ['constructor', '__super__']), classMethods);
if (!_.has(parent, "extend")) {
constructor.extend = extend;
}
return constructor;
};
return extend;
})();
module.exports = extensive;
|
Change default version to "dev-build" | <?php
return [
/**
* Displaying project name.
*/
'name' => 'Deplink: Dependency Manager for C/C++',
/**
* CLI version using semantic versioning.
*
* @link http://semver.org/
*/
'version' => 'dev-build',
/**
* Available commands via cli.
*
* @link https://github.com/symfony/console
*/
'commands' => [
\Deplink\Console\Commands\InitCommand::class,
\Deplink\Console\Commands\InstallCommand::class,
//\Deplink\Console\Commands\ListCommand::class,
//\Deplink\Console\Commands\UninstallCommand::class,
\Deplink\Console\Commands\BuildCommand::class,
//\Deplink\Console\Commands\RebuildCommand::class,
//\Deplink\Console\Commands\CleanCommand::class,
\Deplink\Console\Commands\RunCommand::class,
//\Deplink\Console\Commands\ScriptCommand::class,
],
];
| <?php
return [
/**
* Displaying project name.
*/
'name' => 'Deplink: Dependency Manager for C/C++',
/**
* CLI version using semantic versioning.
*
* @link http://semver.org/
*/
'version' => '0.1.0',
/**
* Available commands via cli.
*
* @link https://github.com/symfony/console
*/
'commands' => [
\Deplink\Console\Commands\InitCommand::class,
\Deplink\Console\Commands\InstallCommand::class,
//\Deplink\Console\Commands\ListCommand::class,
//\Deplink\Console\Commands\UninstallCommand::class,
\Deplink\Console\Commands\BuildCommand::class,
//\Deplink\Console\Commands\RebuildCommand::class,
//\Deplink\Console\Commands\CleanCommand::class,
\Deplink\Console\Commands\RunCommand::class,
//\Deplink\Console\Commands\ScriptCommand::class,
],
];
|
Add code comments for clarity | var vm = new Vue({
el: '#homeselling',
data: {
heading: "What's My Profit?",
homeprice: "Home Price",
realtorfee: "Realtor fee (in percent)",
mortgage: "Mortgage amount",
},
methods: {
// Format the number for currency
currencyFormat: function(num) {
// As seen at https://blog.tompawlak.org/number-currency-formatting-javascript.
return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
},
// Calculate the profit from the sale
calculateProfit: function(num) {
var price = document.getElementById('price').value;
var fee = document.getElementById('fee').value / 100;
var mortgage = document.getElementById('mortgage').value;
var takehome = (price - (price * fee));
var profit = takehome - mortgage;
document.getElementById('takehome').innerHTML = '<p>Your takehome money after the Realtor fee will be <strong>' + vm.currencyFormat(takehome) + '</strong>.</p>';
document.getElementById('result').innerHTML = '<p>Your profit after paying off your mortgage will be <strong>' + vm.currencyFormat(profit) + '</strong>.</p>';
return false;
}
}
});
| var vm = new Vue({
el: '#homeselling',
data: {
heading: "What's My Profit?",
homeprice: "Home Price",
realtorfee: "Realtor fee (in percent)",
mortgage: "Mortgage amount",
},
methods: {
currencyFormat: function(num) {
// As seen at https://blog.tompawlak.org/number-currency-formatting-javascript.
return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
},
calculateProfit: function(num) {
var price = document.getElementById('price').value;
var fee = document.getElementById('fee').value / 100;
var mortgage = document.getElementById('mortgage').value;
var takehome = (price - (price * fee));
var profit = takehome - mortgage;
document.getElementById('takehome').innerHTML = '<p>Your takehome money after the Realtor fee will be <strong>' + vm.currencyFormat(takehome) + '</strong>.</p>';
document.getElementById('result').innerHTML = '<p>Your profit after paying off your mortgage will be <strong>' + vm.currencyFormat(profit) + '</strong>.</p>';
return false;
}
}
});
|
Use java.io.tmpdir instead of hardcoded /tmp | //
// 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 com.cloud.storage.template;
import static org.junit.Assert.fail;
import java.io.File;
import org.junit.Test;
public class LocalTemplateDownloaderTest {
@Test
public void localTemplateDownloaderTest() {
String url = "file://" + new File("pom.xml").getAbsolutePath();
TemplateDownloader td = new LocalTemplateDownloader(null, url, System.getProperty("java.io.tmpdir"), TemplateDownloader.DEFAULT_MAX_TEMPLATE_SIZE_IN_BYTES, null);
long bytes = td.download(true, null);
if (!(bytes > 0)) {
fail("Failed download");
}
}
}
| //
// 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 com.cloud.storage.template;
import static org.junit.Assert.fail;
import java.io.File;
import org.junit.Test;
public class LocalTemplateDownloaderTest {
@Test
public void localTemplateDownloaderTest() {
String url = "file://" + new File("pom.xml").getAbsolutePath();
TemplateDownloader td = new LocalTemplateDownloader(null, url, "/tmp", TemplateDownloader.DEFAULT_MAX_TEMPLATE_SIZE_IN_BYTES, null);
long bytes = td.download(true, null);
if (!(bytes > 0)) {
fail("Failed download");
}
}
}
|
Fix width issue. Remove JS that was for <v4 | document.addEventListener('DOMContentLoaded', function() {
// Inititate Select2 on any select element with the class .select2
$('select.select2').select2({
// change that
allowClear: false,
placeholder: {
id: '-1', // the value of the option
text: 'Select an option'
}
})
})
$.fn.addSelect2Options = function (data) {
var select = this
function appendOption(select, data) {
var option = new Option(data.name, data.id, true, true)
select.append(option).trigger('change')
}
if (Array.isArray(data)) {
data.map(function(row) {
appendOption(select, row)
})
} else {
appendOption(select, data)
}
select.trigger({
type: 'select2:select',
params: {
data: data
}
})
}
$.fn.select2.defaults.set("width", "style")
$.fn.select2.defaults.set("dropdownAutoWidth", false)
$.fn.select2.defaults.set('theme', 'bootstrap4')
| document.addEventListener('DOMContentLoaded', function() {
// Inititate Select2 on any select element with the class .select2
$('select.select2').select2({
// change that
allowClear: false,
placeholder: {
id: '-1', // the value of the option
text: 'Select an option'
}
})
// BELOW: z-index fix for Select2 v3.x to lower the z-index of an opened Select2.
// The javascript below is not needed if Spree is updated to use Select2 v4.x
window.addEventListener('click', function(e) {
var select2Drop = document.getElementById('select2-drop')
if (select2Drop) {
if (select2Drop.contains(e.target)) {
// Clicking inside the Select2 dropdown does nothing...
} else {
// Clicking outside the Select2 dropdown close all open Select2 dropdowns.
$('*').select2('close')
}
}
})
})
$.fn.addSelect2Options = function (data) {
var select = this
function appendOption(select, data) {
var option = new Option(data.name, data.id, true, true)
select.append(option).trigger('change')
}
if (Array.isArray(data)) {
data.map(function(row) {
appendOption(select, row)
})
} else {
appendOption(select, data)
}
select.trigger({
type: 'select2:select',
params: {
data: data
}
})
}
$.fn.select2.defaults.set('theme', 'bootstrap4')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.