text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Simplify GraphQL error logging function
|
// @flow
import { red } from 'chalk';
import R from 'ramda';
type Clog = typeof console.log;
type GraphQLError = { message: string };
// FIXME: Improve naming
export function exitError(clog: Clog, ...errors: Array<string | Error | GraphQLError>): number {
R.compose(
R.apply(clog),
R.tail,
R.chain(err => ['\n', err]),
R.map(err => (err.stack ? red(err.stack) : red(err))),
)(errors);
return 1;
}
export function exitNoConfig(clog: Clog): number {
return exitError(clog, '.amazeeio.yml config file not found.');
}
export function exitGraphQLError(clog: Clog, errors: Array<GraphQLError>): number {
return exitError(clog, 'Oops! The server returned errors:', ...errors);
}
|
// @flow
import { red } from 'chalk';
import R from 'ramda';
type Clog = typeof console.log;
type GraphQLError = { message: string };
// FIXME: Improve naming
export function exitError(clog: Clog, ...errors: Array<string>): number {
R.compose(
R.apply(clog),
R.tail,
R.chain(err => ['\n', err]),
R.map(err => (err.stack ? red(err.stack) : red(err))),
)(errors);
return 1;
}
export function exitNoConfig(clog: Clog): number {
return exitError(clog, '.amazeeio.yml config file not found.');
}
export function exitGraphQLError(clog: Clog, errors: Array<GraphQLError>): number {
R.compose(
R.apply(clog),
R.tail,
R.chain(err => ['\n', red(err)]),
R.prepend(red('Oops! The server returned errors:')),
)(errors);
return 1;
}
|
Fix typo in logical operators test
|
if (typeof define !== 'function') { var define = require('amdefine')(module); }
if (typeof expect !== 'function') { var expect = require('expect.js'); }
define([
'app/logicalOperators'
], function(answers) {
describe("logical operators", function(){
it("you should be able to work with logical or", function() {
expect(answers.and(false, false)).not.to.be.ok();
expect(answers.and(true, false)).not.to.be.ok();
expect(answers.and(true, true)).to.be.ok();
});
it("you should be able to work with logical and", function() {
expect(answers.or(true, false)).to.be.ok();
expect(answers.or(true, true)).to.be.ok();
expect(answers.or(false, false)).not.to.be.ok();
});
});
});
|
if (typeof define !== 'function') { var define = require('amdefine')(module); }
if (typeof expect !== 'function') { var expect = require('expect.js'); }
define([
'app/logicalOperators'
], function(answers) {
describe("logial operators", function(){
it("you should be able to work with logical or", function() {
expect(answers.and(false, false)).not.to.be.ok();
expect(answers.and(true, false)).not.to.be.ok();
expect(answers.and(true, true)).to.be.ok();
});
it("you should be able to work with logical and", function() {
expect(answers.or(true, false)).to.be.ok();
expect(answers.or(true, true)).to.be.ok();
expect(answers.or(false, false)).not.to.be.ok();
});
});
});
|
Comment and toast delete tested
|
(function () {
'use strict';
angular
.module('drinks', ['ngAnimate', 'toastr'])
.controller('DrinksListController', DrinksListController);
DrinksListController.$inject = ['DrinksService', '$state' , '$scope', 'toastr'];
function DrinksListController(DrinksService, $state, $scope, toastr) {
var vm = this;
vm.AddToMenu = AddToMenu;
vm.mvOnMenu = mvOnMenu;
vm.mvOffMenu = mvOffMenu;
vm.drinks = DrinksService.query();
function AddToMenu(drink) {
drink.$update(successCallback, errorCallback);
function successCallback(res) {
$state.go('drinks.list', {
drinkId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
//Menu drink toggle notification via toastr
function mvOnMenu(drink) {
toastr.success(
drink.drinkName + ' was added to tap!',
{
closeHtml: '<button></button>'
}
);
}
function mvOffMenu(drink) {
toastr.success(
drink.drinkName + ' was removed from tap!'
);
}
}
})();
|
(function () {
'use strict';
angular
.module('drinks', ['ngAnimate', 'toastr'])
.controller('DrinksListController', DrinksListController);
DrinksListController.$inject = ['DrinksService', '$state' , '$scope', 'toastr'];
function DrinksListController(DrinksService, $state, $scope, toastr) {
var vm = this;
vm.AddToMenu = AddToMenu;
vm.mvOnMenu = mvOnMenu;
vm.mvOffMenu = mvOffMenu;
vm.drinks = DrinksService.query();
function AddToMenu(drink) {
drink.$update(successCallback, errorCallback);
function successCallback(res) {
$state.go('drinks.list', {
drinkId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
function mvOnMenu(drink) {
toastr.success(drink.drinkName + ' was added to tap!');
}
function mvOffMenu(drink) {
toastr.success(drink.drinkName + ' was removed from tap!');
}
}
})();
|
Adjust and output bundle to dev dir
|
import babel from 'rollup-plugin-babel';
/**
* glsl transform from three.js rollup.config.js
*
* @see https://github.com/mrdoob/three.js/blob/r82/rollup.config.js
*/
function glsl () {
return {
transform ( code, id ) {
if ( !/\.glsl$/.test( id ) ) return;
var transformedCode = 'export default ' + JSON.stringify(
code
.replace( /[ \t]*\/\/.*\n/g, '' )
.replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' )
.replace( /\n{2,}/g, '\n' )
) + ';';
return {
code: transformedCode,
map: { mappings: '' }
};
}
};
}
export default {
entry: 'src/Game.js',
plugins: [
glsl(),
babel({
exclude: [
'node_modules/**',
'src/lib/**'
]
})
],
targets: [
{
format: 'iife',
dest: 'dev/invaders.js',
moduleName: 'Invaders'
}
]
};
|
import babel from 'rollup-plugin-babel';
/**
* glsl transform from three.js rollup.config.js
*
* @see https://github.com/mrdoob/three.js/blob/r82/rollup.config.js
*/
function glsl () {
return {
transform ( code, id ) {
if ( !/\.glsl$/.test( id ) ) return;
var transformedCode = 'export default ' + JSON.stringify(
code
.replace( /[ \t]*\/\/.*\n/g, '' )
.replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' )
.replace( /\n{2,}/g, '\n' )
) + ';';
return {
code: transformedCode,
map: { mappings: '' }
};
}
};
}
export default {
entry: 'src/Game.js',
plugins: [
glsl(),
babel({
exclude: [
'node_modules/**',
'src/lib/**'
]
})
],
targets: [
{
format: 'iife',
dest: 'dist/dev/invaders.js',
moduleName: 'Invaders'
}
]
};
|
Reformat tests to remove tabs
|
/*
* Copyright 2017 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.rendering;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class FontUnderlineTest {
private static final char START_UNDERLINE = 0xF001;
private static final char END_UNDERLINE = 0xF002;
@Test
public void testStartUnderline() {
assertTrue(FontUnderline.isValid(START_UNDERLINE));
}
@Test
public void testEndUnderline() {
assertTrue(FontUnderline.isValid(END_UNDERLINE));
}
@Test
public void testInvalidUnderline() {
char invalidUnderline = 0xF003;
assertFalse(FontUnderline.isValid(invalidUnderline));
}
@Test
public void testMarkUnderlined() {
String testString = "string";
assertTrue(FontUnderline.markUnderlined(testString).equals(START_UNDERLINE + testString + END_UNDERLINE));
}
}
|
/*
* Copyright 2017 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.rendering;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class FontUnderlineTest {
private static final char START_UNDERLINE = 0xF001;
private static final char END_UNDERLINE = 0xF002;
@Test
public void testStartUnderline() {
assertTrue(FontUnderline.isValid(START_UNDERLINE));
}
@Test
public void testEndUnderline() {
assertTrue(FontUnderline.isValid(END_UNDERLINE));
}
@Test
public void testInvalidUnderline() {
char invalidUnderline = 0xF003;
assertFalse(FontUnderline.isValid(invalidUnderline));
}
@Test
public void testMarkUnderlined() {
String testString = "string";
assertTrue(FontUnderline.markUnderlined(testString).equals(START_UNDERLINE + testString + END_UNDERLINE));
}
}
|
Revert back to original settings for Celery Broker
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'db.sqlite3'),
}
}
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'http'
TEMPLATE_CONTEXT_PROCESSORS += (
"django.core.context_processors.debug",
)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
INSTALLED_APPS += ('django_extensions',)
# settings for celery
BROKER_URL = os.environ.get("BROKER_URL", "redis://redis:6379/0")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", 'redis://redis:6379/0')
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'db.sqlite3'),
}
}
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'http'
TEMPLATE_CONTEXT_PROCESSORS += (
"django.core.context_processors.debug",
)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
INSTALLED_APPS += ('django_extensions',)
# settings for celery
BROKER_URL = os.environ.get("BROKER_URL", "redis://127.0.0.1:6379/0")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", 'redis://127.0.0.1:6379/0')
|
Modify app to expect IP/Port from .config, or use Cloud9 Port/IP if none found.
|
module.exports = function(app) {
var mongoose = require('mongoose'); // require mongoose (for mongodb integration
var fs = require('fs'); // necessary to read from files
var db = require('./app_api/models/db'); // handles database connection open/close
var routesApi = require('./app_api/routes/index');
app.use('/api', routesApi); // provide routes in API route index
fs.readFile('.config', 'utf8', function(err,data){
if (err) {
console.log(err);
} else {
var config = JSON.parse(data); // if read successful, parse JSON into object
db(config.url, config.user, config.password); // connect to database
app.get('/api/hello', function(request, response) { // provide RESTful GET API at /hello
response.send('Hello, World!'); // respond with string
});
app.listen(config.port || process.env.PORT, config.ip || process.env.IP); // try to open port/ip and try to use Cloud9 Port/IP if none specified
console.log('API running!');
}
});
}
|
module.exports = function(app) {
var mongoose = require('mongoose'); // require mongoose (for mongodb integration
var fs = require('fs'); // necessary to read from files
var db = require('./app_api/models/db'); // handles database connection open/close
var routesApi = require('./app_api/routes/index');
app.use('/api', routesApi); // provide routes in API route index
fs.readFile('.dbconfig', 'utf8', function(err,data){
if (err) {
console.log(err);
} else {
var dbAccess = JSON.parse(data); // if read successful, parse JSON into object
db(dbAccess.url, dbAccess.user, dbAccess.password); // connect to database
}
});
app.get('/api/hello', function(request, response) { // provide RESTful GET API at /hello
response.send('Hello, World!'); // respond with string
});
app.listen(process.env.PORT, process.env.IP); // begin app listening on Cloud9 port/IP
console.log('API running!');
}
|
Use an array, not a NodeList, to allow for-of iteration of l10n nodes
|
import AmpersandView from 'ampersand-view';
import mustache from 'mustache';
// BaseView just abstracts out stuff we seem to use in all the views
export default AmpersandView.extend({
// override _template with a mustache template
_template: '',
template(ctx) {
return mustache.render(this._template, ctx);
},
render() {
this.beforeRender();
AmpersandView.prototype.render.apply(this, arguments);
this.afterRender();
this.localizeRendered();
if (this.model) {
this.model.on('change', () => this.localizeRendered);
}
},
getL10nArgs() {
// Most common case for l10n args comes from the current model - e.g. on
// experiment detail page.
return this.model ? this.model.toJSON() : {};
},
localizeRendered() {
const args = this.getL10nArgs();
const argsJSON = JSON.stringify(args);
// HACK: Slap the same data-l10n-args data on every localized node, because
// the most common case is they all need the same model data.
const nodes = this.queryAll('[data-l10n-id]');
for (const node of nodes) {
node.setAttribute('data-l10n-args', argsJSON);
}
},
// implement in subclasses
beforeRender() {},
afterRender() {}
});
|
import AmpersandView from 'ampersand-view';
import mustache from 'mustache';
// BaseView just abstracts out stuff we seem to use in all the views
export default AmpersandView.extend({
// override _template with a mustache template
_template: '',
template(ctx) {
return mustache.render(this._template, ctx);
},
render() {
this.beforeRender();
AmpersandView.prototype.render.apply(this, arguments);
this.afterRender();
this.localizeRendered();
if (this.model) {
this.model.on('change', () => this.localizeRendered);
}
},
getL10nArgs() {
// Most common case for l10n args comes from the current model - e.g. on
// experiment detail page.
return this.model ? this.model.toJSON() : {};
},
localizeRendered() {
const args = this.getL10nArgs();
const argsJSON = JSON.stringify(args);
// HACK: Slap the same data-l10n-args data on every localized node, because
// the most common case is they all need the same model data.
const nodes = this.el.querySelectorAll('[data-l10n-id]');
for (const node of nodes) {
node.setAttribute('data-l10n-args', argsJSON);
}
},
// implement in subclasses
beforeRender() {},
afterRender() {}
});
|
Fix Unicode field in Python 3.2
|
"""Domain models fields."""
import six
class Field(property):
"""Base field."""
def __init__(self):
"""Initializer."""
self.name = None
self.value = None
self.model = None
super(Field, self).__init__(self._get, self._set)
def _get(self, _):
"""Return field's value."""
return self.value
def _set(self, _, value):
"""Set field's value."""
self.value = value
class Int(Field):
"""Int field."""
def _set(self, _, value):
"""Set field's value."""
self.value = int(value)
class String(Field):
"""String field."""
def _set(self, _, value):
"""Set field's value."""
self.value = str(value)
class Unicode(Field):
"""Unicode string field."""
def _set(self, _, value):
"""Set field's value."""
self.value = six.u(value)
|
"""Domain models fields."""
class Field(property):
"""Base field."""
def __init__(self):
"""Initializer."""
self.name = None
self.value = None
self.model = None
super(Field, self).__init__(self._get, self._set)
def _get(self, _):
"""Return field's value."""
return self.value
def _set(self, _, value):
"""Set field's value."""
self.value = value
class Int(Field):
"""Int field."""
def _set(self, _, value):
"""Set field's value."""
self.value = int(value)
class String(Field):
"""String field."""
def _set(self, _, value):
"""Set field's value."""
self.value = str(value)
class Unicode(Field):
"""Unicode string field."""
def _set(self, _, value):
"""Set field's value."""
self.value = unicode(value)
|
Clear electron-link's snapshot cache in script/clean
|
'use strict'
const fs = require('fs-extra')
const os = require('os')
const path = require('path')
const CONFIG = require('../config')
module.exports = function () {
const cachePaths = [
path.join(CONFIG.repositoryRootPath, 'electron'),
path.join(CONFIG.atomHomeDirPath, '.node-gyp'),
path.join(CONFIG.atomHomeDirPath, 'storage'),
path.join(CONFIG.atomHomeDirPath, '.apm'),
path.join(CONFIG.atomHomeDirPath, '.npm'),
path.join(CONFIG.atomHomeDirPath, 'compile-cache'),
path.join(CONFIG.atomHomeDirPath, 'snapshot-cache'),
path.join(CONFIG.atomHomeDirPath, 'atom-shell'),
path.join(CONFIG.atomHomeDirPath, 'electron'),
path.join(os.tmpdir(), 'atom-build'),
path.join(os.tmpdir(), 'atom-cached-atom-shells')
]
for (let path of cachePaths) {
console.log(`Cleaning ${path}`)
fs.removeSync(path)
}
}
|
'use strict'
const fs = require('fs-extra')
const os = require('os')
const path = require('path')
const CONFIG = require('../config')
module.exports = function () {
const cachePaths = [
path.join(CONFIG.repositoryRootPath, 'electron'),
path.join(CONFIG.atomHomeDirPath, '.node-gyp'),
path.join(CONFIG.atomHomeDirPath, 'storage'),
path.join(CONFIG.atomHomeDirPath, '.apm'),
path.join(CONFIG.atomHomeDirPath, '.npm'),
path.join(CONFIG.atomHomeDirPath, 'compile-cache'),
path.join(CONFIG.atomHomeDirPath, 'atom-shell'),
path.join(CONFIG.atomHomeDirPath, 'electron'),
path.join(os.tmpdir(), 'atom-build'),
path.join(os.tmpdir(), 'atom-cached-atom-shells')
]
for (let path of cachePaths) {
console.log(`Cleaning ${path}`)
fs.removeSync(path)
}
}
|
Change all 1d to 24h
|
export const defaultRuleConfigs = {
deadman: {
period: '10m',
},
relative: {
change: 'change',
period: '1m',
shift: '1m',
operator: 'greater than',
value: '90',
},
threshold: {
operator: 'greater than',
value: '90',
relation: 'once',
percentile: '90',
period: '1m',
},
};
export const OPERATORS = ['greater than', 'equal to or greater', 'equal to or less than', 'less than', 'equal to', 'not equal to'];
// export const RELATIONS = ['once', 'more than ', 'less than'];
export const PERIODS = ['1m', '5m', '10m', '30m', '1h', '2h', '24h'];
export const CHANGES = ['change', '% change'];
export const SHIFTS = ['1m', '5m', '10m', '30m', '1h', '2h', '24h'];
export const ALERTS = ['hipchat', 'opsgenie', 'pagerduty', 'sensu', 'slack', 'smtp', 'talk', 'telegram', 'victorops'];
export const DEFAULT_RULE_ID = 'DEFAULT_RULE_ID';
|
export const defaultRuleConfigs = {
deadman: {
period: '10m',
},
relative: {
change: 'change',
period: '1m',
shift: '1m',
operator: 'greater than',
value: '90',
},
threshold: {
operator: 'greater than',
value: '90',
relation: 'once',
percentile: '90',
period: '1m',
},
};
export const OPERATORS = ['greater than', 'equal to or greater', 'equal to or less than', 'less than', 'equal to', 'not equal to'];
// export const RELATIONS = ['once', 'more than ', 'less than'];
export const PERIODS = ['1m', '5m', '10m', '30m', '1h', '2h', '1d'];
export const CHANGES = ['change', '% change'];
export const SHIFTS = ['1m', '5m', '10m', '30m', '1h', '2h', '1d'];
export const ALERTS = ['hipchat', 'opsgenie', 'pagerduty', 'sensu', 'slack', 'smtp', 'talk', 'telegram', 'victorops'];
export const DEFAULT_RULE_ID = 'DEFAULT_RULE_ID';
|
Remove impossible check & check primitive
|
package org.jenkins.tools.test.model.hook;
import org.apache.commons.lang.ClassUtils;
import java.util.Map;
/**
* An abstract class that marks a hook that runs before the checkout stage of the
* Plugins Compat Tester.
*
* This exists simply for the ability to check when a subclass should be implemented.
*/
public abstract class PluginCompatTesterHookBeforeCheckout implements PluginCompatTesterHook {
/**
* Check the:
* + executionResult - if set, the required result of this execution (CANNOT CHECK IN THIS CLASS)
* + runCheckout - if the plugin should be checked out again
* + pluginDir - if set, the location of the plugin directory
*/
public void validate(Map<String, Object> toCheck) throws Exception {
if((toCheck.get("runCheckout") != null &&
(toCheck.get("runCheckout").getClass().isPrimitive() || ClassUtils.wrapperToPrimitive(toCheck.get("runCheckout").getClass()) != null)) &&
(toCheck.get("pluginDir") != null &&
toCheck.get("pluginDir") instanceof String) ) {
throw new IllegalArgumentException("A hook modified a required parameter for plugin checkout.");
}
}
}
|
package org.jenkins.tools.test.model.hook;
import hudson.model.UpdateSite.Plugin;
//import org.jenkins.tools.test.model.TestExecutionResult;
import java.util.Map;
/**
* An abstract class that marks a hook that runs before the checkout stage of the
* Plugins Compat Tester.
*
* This exists simply for the ability to check when a subclass should be implemented.
*/
public abstract class PluginCompatTesterHookBeforeCheckout implements PluginCompatTesterHook {
/**
* Check the:
* + executionResult - if set, the required result of this execution
* + runCheckout - if the plugin should be checked out again
* + pluginDir - if set, the location of the plugin directory
*/
public void validate(Map<String, Object> toCheck) throws Exception {
/*if((toCheck.get("executionResult") != null &&
toCheck.get("executionResult") instanceof TestExecutionResult) &&
(toCheck.get("runCheckout") != null &&
toCheck.get("runCheckout")) &&
(toCheck.get("pluginDir") != null &&
toCheck.get("pluginDir") instanceof String) ) {
throw new IllegalArgumentException("A hook modified a required parameter for plugin checkout.");
}*/
}
}
|
Fix typo in GPU worker config setup
|
"""
Grab worker configuration from GCloud instance attributes.
"""
import json
import requests
MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url"
SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder"
GPU_CAPABILITY_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-gpu"
MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text
SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text
HAS_GPU = requests.get(GPU_CAPABILITY_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text == "true"
with open("config.json", "w") as configfile:
json.dump({
"MANAGER_URL": MANAGER_URL,
"SECRET_FOLDER": SECRET_FOLDER,
"CAPABILITIES": ["gpu"] if HAS_GPU else [],
}, configfile)
|
"""
Grab worker configuration from GCloud instance attributes.
"""
import json
import requests
MANAGER_URL_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-manager-url"
SECRET_FOLDER_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-secret-folder"
GPU_CAPABILITY_METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/instance/attributes/halite-gpu"
MANAGER_URL = requests.get(MANAGER_URL_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text
SECRET_FOLDER = requests.get(SECRET_FOLDER_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text
HAS_GPU = requests.get(SECRET_FOLDER_METADATA_URL, headers={
"Metadata-Flavor": "Google"
}).text == "true"
with open("config.json", "w") as configfile:
json.dump({
"MANAGER_URL": MANAGER_URL,
"SECRET_FOLDER": SECRET_FOLDER,
"CAPABILITIES": ["gpu"] if HAS_GPU else [],
}, configfile)
|
Add warning about custom presets
|
import path from 'path';
import { logger } from '@storybook/node-logger';
import loadPresets from './presets';
import serverRequire from './serverRequire';
function customPreset({ configDir }) {
const presets = serverRequire(path.resolve(configDir, 'presets'));
if (presets) {
logger.warn(
'"Custom presets" is an experimental and undocumented feature that will be changed or deprecated soon. Use it on your own risk.'
);
return presets;
}
return [];
}
function getWebpackConfig(options, presets) {
const babelOptions = presets.extendBabel({}, options);
const entries = {
iframe: presets.extendPreview([], options),
manager: presets.extendManager([], options),
};
return presets.extendWebpack({}, { ...options, babelOptions, entries });
}
export default options => {
const { corePresets = [], frameworkPresets = [], ...restOptions } = options;
const presetsConfig = [
...corePresets,
require.resolve('./core-preset-babel-cache.js'),
...frameworkPresets,
...customPreset(options),
require.resolve('./core-preset-webpack-custom.js'),
];
const presets = loadPresets(presetsConfig);
return getWebpackConfig(restOptions, presets);
};
|
import path from 'path';
import loadPresets from './presets';
import serverRequire from './serverRequire';
function customPreset({ configDir }) {
return serverRequire(path.resolve(configDir, 'presets')) || [];
}
function getWebpackConfig(options, presets) {
const babelOptions = presets.extendBabel({}, options);
const entries = {
iframe: presets.extendPreview([], options),
manager: presets.extendManager([], options),
};
return presets.extendWebpack({}, { ...options, babelOptions, entries });
}
export default options => {
const { corePresets = [], frameworkPresets = [], ...restOptions } = options;
const presetsConfig = [
...corePresets,
require.resolve('./core-preset-babel-cache.js'),
...frameworkPresets,
...customPreset(options),
require.resolve('./core-preset-webpack-custom.js'),
];
const presets = loadPresets(presetsConfig);
return getWebpackConfig(restOptions, presets);
};
|
Implement workaround to fix JS not loading issue
|
/* global require, module, __dirname */
const path = require( 'path' );
module.exports = {
entry: {
'./assets/js/amp-blocks-compiled': './blocks/index.js',
'./assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle.js',
'./assets/js/amp-validation-error-detail-toggle-compiled': './assets/src/amp-validation-error-detail-toggle.js'
},
output: {
path: path.resolve( __dirname ),
filename: '[name].js'
},
externals: {
'amp-validation-i18n': 'ampValidationI18n'
},
devtool: 'cheap-eval-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
}
]
}
};
|
/* global require, module, __dirname */
const path = require( 'path' );
module.exports = {
entry: {
'./assets/js/amp-blocks-compiled': './blocks/index.js',
'./assets/js/amp-block-editor-toggle-compiled': './assets/src/amp-block-editor-toggle.js',
'./assets/js/amp-validation-error-detail-toggle-compiled': './assets/src/amp-validation-error-detail-toggle.js'
},
output: {
path: path.resolve( __dirname ),
filename: '[name].js'
},
externals: {
'@wordpress/dom-ready': 'wp.domReady',
'amp-validation-i18n': 'ampValidationI18n'
},
devtool: 'cheap-eval-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
}
]
}
};
|
Remove nonexistent and unused variable
|
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Http\Controllers;
use App\Models\Chat\Channel;
use App\Models\Chat\UserChannel;
use App\Models\User;
use Auth;
use Request;
class ChatController extends Controller
{
public function __construct()
{
$this->middleware('auth');
return parent::__construct();
}
public function index()
{
$json = [];
$targetUser = User::lookup(Request::input('sendto'), 'id');
if ($targetUser) {
$json['target'] = json_item($targetUser, 'UserCompact');
$json['can_message'] = priv_check('ChatStart', $targetUser)->can();
$channel = Channel::where('name', Channel::getPMChannelName($targetUser, Auth::user()))->first();
if ($channel !== null && !$channel->hasUser(Auth::user())) {
$channel->addUser(Auth::user());
}
}
$presence = UserChannel::presenceForUser(Auth::user());
return ext_view('chat.index', compact('presence', 'json'));
}
}
|
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Http\Controllers;
use App\Models\Chat\Channel;
use App\Models\Chat\UserChannel;
use App\Models\User;
use Auth;
use Request;
class ChatController extends Controller
{
public function __construct()
{
$this->middleware('auth');
return parent::__construct();
}
public function index()
{
$json = [];
$targetUser = User::lookup(Request::input('sendto'), 'id');
if ($targetUser) {
$json['target'] = json_item($targetUser, 'UserCompact');
$json['can_message'] = priv_check('ChatStart', $targetUser)->can();
$channel = Channel::where('name', Channel::getPMChannelName($targetUser, Auth::user()))->first();
if ($channel !== null && !$channel->hasUser(Auth::user())) {
$channel->addUser(Auth::user());
}
}
$presence = UserChannel::presenceForUser(Auth::user());
return ext_view('chat.index', compact('presence', 'messages', 'json'));
}
}
|
Update energy chunk exchange for energy users
|
// Copyright 2016, University of Colorado Boulder
/**
* Base class for energy users, i.e. model elements that take energy from
* an energy converter and do something with it, such as producing light or
* heat.
*
* @author John Blanco
* @author Andrew Adare
*/
define( function( require ) {
'use strict';
// Modules
var EnergySystemElement = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/model/EnergySystemElement' );
var inherit = require( 'PHET_CORE/inherit' );
function EnergyUser( iconImage ) {
EnergySystemElement.call( this, iconImage );
this.incomingEnergyChunks = [];
}
return inherit( EnergySystemElement, EnergyUser, {
/**
* Inject a list of energy chunks into this energy system element. Once
* injected, it is the system's responsibility to move, convert, and
* otherwise manage them.
*
* @param {Array{EnergyChunk}} energyChunks List of energy chunks to inject.
*/
injectEnergyChunks: function( energyChunks ) {
this.incomingEnergyChunks = _.union( this.incomingEnergyChunks, energyChunks );
},
/**
* @public
* @override
*/
clearEnergyChunks: function() {
EnergySystemElement.prototype.clearEnergyChunks.call( this );
this.incomingEnergyChunks.length = 0;
}
} );
} );
|
// Copyright 2016, University of Colorado Boulder
/**
* Base class for energy users, i.e. model elements that take energy from
* an energy converter and do something with it, such as producing light or
* heat.
*
* @author John Blanco
* @author Andrew Adare
*/
define( function( require ) {
'use strict';
// Modules
var EnergySystemElement = require( 'ENERGY_FORMS_AND_CHANGES/energy-systems/model/EnergySystemElement' );
var inherit = require( 'PHET_CORE/inherit' );
function EnergyUser( iconImage ) {
EnergySystemElement.call( this, iconImage );
this.incomingEnergyChunks = [];
}
return inherit( EnergySystemElement, EnergyUser, {
/**
* Inject a list of energy chunks into this energy system element. Once
* injected, it is the system's responsibility to move, convert, and
* otherwise manage them.
*
* @param {Array{EnergyChunkk}} energyChunks List of energy chunks to inject.
*/
injectEnergyChunks: function( energyChunks ) {
// incomingEnergyChunks.addAll( energyChunks );
},
/**
* [clearEnergyChunks description]
* @public
* @override
*/
clearEnergyChunks: function() {
this.clearEnergyChunks();
this.incomingEnergyChunks.clear();
}
} );
} );
|
Revert "Increased maxBuffer size, for some reason it was reaching the limit on a big repository."
This reverts commit 111c0bcad3555505b7e5f3901ff60f05cdccd0bf.
|
'use strict';
var grunt = require('grunt');
var chalk = require('chalk');
var util = require('util');
var exec = require('child_process').exec;
var conf = require('./conf.js');
module.exports = function(command, args, done, suppress){
args.unshift(command);
var cmd = util.format.apply(util, args);
grunt.log.writeln(chalk.magenta(cmd));
var proc = exec(cmd, { env: conf() }, callback);
if (suppress !== true) {
proc.stdout.on('data', function (data) {
grunt.log.writeln(data);
});
}
proc.stderr.on('data', function (data) {
grunt.log.writeln(chalk.yellow(data));
});
function callback (err, stdout) {
if (err) { grunt.fatal(err); }
if (suppress !== true) {
done();
} else {
done(stdout);
}
}
return proc;
};
|
'use strict';
var grunt = require('grunt');
var chalk = require('chalk');
var util = require('util');
var exec = require('child_process').exec;
var conf = require('./conf.js');
module.exports = function(command, args, done, suppress){
args.unshift(command);
var cmd = util.format.apply(util, args);
grunt.log.writeln(chalk.magenta(cmd));
var proc = exec(cmd, { maxBuffer: 10000 * 1024, env: conf() }, callback);
if (suppress !== true) {
proc.stdout.on('data', function (data) {
grunt.log.writeln(data);
});
}
proc.stderr.on('data', function (data) {
grunt.log.writeln(chalk.yellow(data));
});
function callback (err, stdout) {
if (err) { grunt.fatal(err); }
if (suppress !== true) {
done();
} else {
done(stdout);
}
}
return proc;
};
|
Change the category from skin to other
|
<?php
if(!defined('MEDIAWIKI')) die;
$dir = __DIR__;
$ext = 'HideUnwanted';
$wgExtensionCredits['other'][] = array(
'path' => __FILE__,
'name' => $ext,
'version' => '0.1',
'author' => 'uta',
'url' => 'https://github.com/uta/HideUnwanted',
'descriptionmsg' => 'hide-unwanted-desc',
'license-name' => 'MIT-License',
);
$wgAutoloadClasses["${ext}Hooks"] = "$dir/classes/${ext}Hooks.php";
$wgExtensionMessagesFiles[$ext] = "$dir/i18n/_backward_compatibility.php";
$wgHooks['SkinTemplateOutputPageBeforeExec'][] = "${ext}Hooks::hide";
$wgMessagesDirs[$ext] = "$dir/i18n";
$wgHideUnwantedFooters = array();
$wgHideUnwantedHeaders = array();
$wgHideUnwantedTabs = array();
|
<?php
if(!defined('MEDIAWIKI')) die;
$dir = __DIR__;
$ext = 'HideUnwanted';
$wgExtensionCredits['skin'][] = array(
'path' => __FILE__,
'name' => $ext,
'version' => '0.1',
'author' => 'uta',
'url' => 'https://github.com/uta/HideUnwanted',
'descriptionmsg' => 'hide-unwanted-desc',
'license-name' => 'MIT-License',
);
$wgAutoloadClasses["${ext}Hooks"] = "$dir/classes/${ext}Hooks.php";
$wgExtensionMessagesFiles[$ext] = "$dir/i18n/_backward_compatibility.php";
$wgHooks['SkinTemplateOutputPageBeforeExec'][] = "${ext}Hooks::hide";
$wgMessagesDirs[$ext] = "$dir/i18n";
$wgHideUnwantedFooters = array();
$wgHideUnwantedHeaders = array();
$wgHideUnwantedTabs = array();
|
Increase size of large source tree 10x
- up to 1000 source files
- use parallel make
- preserve source tree
|
import unittest
from yeast_harness import *
class TestLargeSourceTree(unittest.TestCase):
def test_large_source_tree(self):
make_filename = lambda ext='': ''.join(
random.choice(string.ascii_lowercase) for _ in range(8)) + ext
make_sources = lambda path: [
CSourceFile(path + '/' + make_filename('.c')) for _ in range(100)]
make_spore = lambda: SporeFile(
sources=make_sources(make_filename()),
products='static_lib',
name=make_filename('.spore'))
mk = Makefile(
spores=[make_spore() for _ in range(10)], name='Makefile')
with SourceTree('tree', preserve=True) as src:
src.create(mk)
build = Build(src, mk)
self.assertEqual(0, build.make('-j4'))
|
import unittest
from yeast_harness import *
class TestLargeSourceTree(unittest.TestCase):
def test_large_source_tree(self):
make_filename = lambda ext='': ''.join(
random.choice(string.ascii_lowercase) for _ in range(8)) + ext
make_sources = lambda path: [
CSourceFile(path + '/' + make_filename('.c')) for _ in range(10)]
make_spore = lambda: SporeFile(
sources=make_sources(make_filename()),
products='static_lib',
name=make_filename('.spore'))
mk = Makefile(
spores=[make_spore() for _ in range(10)], name='Makefile')
with SourceTree('tree') as src:
src.create(mk)
build = Build(src, mk)
self.assertEqual(0, build.make())
|
Use compilation warnings instead of console.log
|
var path = require('path');
var findRoot = require('find-root');
var chalk = require('chalk');
var _ = require('lodash');
function DuplicatePackageCheckerPlugin() {}
DuplicatePackageCheckerPlugin.prototype.apply = function(compiler) {
compiler.plugin('emit', function(compilation, callback) {
var modules = {};
compilation.modules.forEach(module => {
if (!module.resource) {
return;
}
var root = findRoot(module.resource);
var pkg = require(path.join(root, 'package.json'));
modules[pkg.name] = (modules[pkg.name] || []);
if (!_.includes(modules[pkg.name], pkg.version)) {
modules[pkg.name].push(pkg.version);
}
});
var duplicates = _.omitBy(modules, versions => versions.length <= 1);
if (Object.keys(duplicates).length) {
_.each(duplicates, (versions, name) => {
compilation.warnings.push(new Error('duplicate-package-checker: <' + chalk.green.bold(name) + '> - ' + chalk.yellow.bold(versions.join(', '))));
});
}
callback();
});
};
module.exports = DuplicatePackageCheckerPlugin;
|
var path = require('path');
var findRoot = require('find-root');
var chalk = require('chalk');
var _ = require('lodash');
function DuplicatePackageCheckerPlugin() {}
DuplicatePackageCheckerPlugin.prototype.apply = function(compiler) {
compiler.plugin('emit', function(compilation, callback) {
var modules = {};
compilation.modules.forEach(module => {
if (!module.resource) {
return;
}
var root = findRoot(module.resource);
var pkg = require(path.join(root, 'package.json'));
modules[pkg.name] = (modules[pkg.name] || []);
if (!_.includes(modules[pkg.name], pkg.version)) {
modules[pkg.name].push(pkg.version);
}
});
var duplicates = _.omitBy(modules, versions => versions.length <= 1);
console.log('');
if (Object.keys(duplicates).length) {
console.log(chalk.yellow('WARNING! Duplicate packages found.'));
_.each(duplicates, (versions, name) => {
console.log('<' + chalk.green.bold(name) + '> - ' + chalk.yellow.bold(versions.join(', ')));
});
} else {
console.log(chalk.green('No duplicate packages found!'));
}
console.log('');
callback();
});
};
module.exports = DuplicatePackageCheckerPlugin;
|
Add PyPI long project description
|
""" Setup script for PyPI """
import os
from setuptools import setup
try:
from ConfigParser import SafeConfigParser
except ImportError:
from configparser import SafeConfigParser
settings = SafeConfigParser()
settings.read(os.path.realpath('aws_ec2_assign_elastic_ip/settings.conf'))
with open('README.md', 'r') as fh:
long_description = fh.read()
setup(
name='aws-ec2-assign-elastic-ip',
version=settings.get('general', 'version'),
license='Apache License, Version 2.0',
description='Automatically assign Elastic IPs to AWS EC2 instances',
long_description=long_description,
long_description_content_type='text/markdown',
author='Sebastian Dahlgren, Skymill Solutions',
author_email='sebastian.dahlgren@skymill.se',
url='https://github.com/skymill/aws-ec2-assign-elastic-ip',
keywords="aws amazon web services ec2 as elasticip eip",
platforms=['Any'],
packages=['aws_ec2_assign_elastic_ip'],
scripts=['aws-ec2-assign-elastic-ip'],
include_package_data=True,
zip_safe=False,
install_requires=['boto >= 2.36.0', 'netaddr >= 0.7.12'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python'
]
)
|
""" Setup script for PyPI """
import os
from setuptools import setup
try:
from ConfigParser import SafeConfigParser
except ImportError:
from configparser import SafeConfigParser
settings = SafeConfigParser()
settings.read(os.path.realpath('aws_ec2_assign_elastic_ip/settings.conf'))
setup(
name='aws-ec2-assign-elastic-ip',
version=settings.get('general', 'version'),
license='Apache License, Version 2.0',
description='Automatically assign Elastic IPs to AWS EC2 instances',
author='Sebastian Dahlgren, Skymill Solutions',
author_email='sebastian.dahlgren@skymill.se',
url='https://github.com/skymill/aws-ec2-assign-elastic-ip',
keywords="aws amazon web services ec2 as elasticip eip",
platforms=['Any'],
packages=['aws_ec2_assign_elastic_ip'],
scripts=['aws-ec2-assign-elastic-ip'],
include_package_data=True,
zip_safe=False,
install_requires=['boto >= 2.36.0', 'netaddr >= 0.7.12'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python'
]
)
|
Add recaptcha to signup page
Signup page is currently not used, but
doing it now in case it is forgotten later.
|
"""Forms for user application."""
from django.forms import ModelForm
from django.contrib.auth import get_user_model, forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3
User = get_user_model()
class SignupForm(ModelForm):
"""Sign up for user registration."""
captcha = ReCaptchaField(widget=ReCaptchaV3, label='')
class Meta:
"""Metadata for SignupForm class."""
model = get_user_model()
fields = ['first_name', 'last_name']
def signup(self, request, user):
"""Extra logic when a user signs up.
Required by django-allauth.
"""
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
class UserChangeForm(forms.UserChangeForm):
"""Form class for changing user."""
class Meta(forms.UserChangeForm.Meta):
"""Metadata for UserChangeForm class."""
model = User
fields = ('email', 'last_name')
class UserCreationForm(forms.UserCreationForm):
"""Form class for creating user."""
class Meta(forms.UserCreationForm.Meta):
"""Metadata for UserCreationForm class."""
model = User
fields = ('email', 'first_name', 'last_name')
|
"""Forms for user application."""
from django.forms import ModelForm
from django.contrib.auth import get_user_model, forms
User = get_user_model()
class SignupForm(ModelForm):
"""Sign up for user registration."""
class Meta:
"""Metadata for SignupForm class."""
model = get_user_model()
fields = ['first_name', 'last_name']
def signup(self, request, user):
"""Extra logic when a user signs up.
Required by django-allauth.
"""
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
class UserChangeForm(forms.UserChangeForm):
"""Form class for changing user."""
class Meta(forms.UserChangeForm.Meta):
"""Metadata for UserChangeForm class."""
model = User
fields = ('email', 'last_name')
class UserCreationForm(forms.UserCreationForm):
"""Form class for creating user."""
class Meta(forms.UserCreationForm.Meta):
"""Metadata for UserCreationForm class."""
model = User
fields = ('email', 'first_name', 'last_name')
|
Add 'physicalproperty' to pkg list for install
|
# -*- coding: utf-8 -*-
from distutils.core import setup
import ibei
setup(name = "ibei",
version = ibei.__version__,
author = "Joshua Ryan Smith",
author_email = "joshua.r.smith@gmail.com",
packages = ["ibei", "physicalproperty"],
url = "https://github.com/jrsmith3/ibei",
description = "Calculator for incomplete Bose-Einstein integral",
classifiers = ["Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 3 - Alpha",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Physics",
"Natural Language :: English",],
install_requires = ["numpy",
"sympy",
"astropy"],)
|
# -*- coding: utf-8 -*-
from distutils.core import setup
import ibei
setup(name = "ibei",
version = ibei.__version__,
author = "Joshua Ryan Smith",
author_email = "joshua.r.smith@gmail.com",
packages = ["ibei"],
url = "https://github.com/jrsmith3/ibei",
description = "Calculator for incomplete Bose-Einstein integral",
classifiers = ["Programming Language :: Python",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 3 - Alpha",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Physics",
"Natural Language :: English",],
install_requires = ["numpy",
"sympy",
"astropy"],)
|
Add comments to JS functions
|
/** Updates trend in carousel. */
function switchTrend(val) {
var trends = document.getElementsByClassName('trends');
var i = 0;
var updatedCurrentSlide = false;
while(i < trends.length && !updatedCurrentSlide) {
if(trends[i].style.display === 'block') {
var nextTrend = getNextTrend(trends[i],val);
trends[i].style.display = 'none';
nextTrend.style.display = 'block';
updatedCurrentSlide = true;
}
i+=1;
}
}
/** Returns next trend in carousel. */
function getNextTrend(trend, val) {
var nextSlide = -1;
var currentTrendVal = parseInt(trend.getAttribute('value'));
// Clicking left on the first slide returns to last slide
if (currentTrendVal + val === 0) {
nextSlide = 4;
// Clicking right on the last slide returns to first slide
} else if (currentTrendVal + val === 5) {
nextSlide = 1;
} else {
nextSlide = currentTrendVal + val;
}
return document.getElementById('trend-' + nextSlide);
}
|
function switchTrend(val) {
var trends = document.getElementsByClassName('trends');
var i = 0;
var updatedCurrentSlide = false;
while(i < trends.length && !updatedCurrentSlide) {
if(trends[i].style.display === 'block') {
var nextTrend = getNextTrend(trends[i],val);
trends[i].style.display = 'none';
nextTrend.style.display = 'block';
updatedCurrentSlide = true;
}
i+=1;
}
}
function getNextTrend(trend, val) {
var nextSlide = -1;
var currentTrendVal = parseInt(trend.getAttribute('value'));
// Clicking left on the first slide returns to last slide
if (currentTrendVal + val === 0) {
nextSlide = 4;
// Clicking right on the last slide returns to first slide
} else if (currentTrendVal + val === 5) {
nextSlide = 1;
} else {
nextSlide = currentTrendVal + val;
}
return document.getElementById('trend-' + nextSlide);
}
|
Split long import line up into two.
|
import unittest
from datetime import date as vanilla_date
from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian
from calexicon.internal.julian import is_julian_leap_year
class TestJulian(unittest.TestCase):
def test_is_gregorian_leap_year(self):
self.assertTrue(is_julian_leap_year(2000))
self.assertTrue(is_julian_leap_year(1984))
self.assertTrue(is_julian_leap_year(1900))
self.assertFalse(is_julian_leap_year(1901))
def test_distant_julian_to_gregorian(self):
self.assertEqual(distant_julian_to_gregorian(9999, 12, 1), (10000, 2, 12))
def test_julian_to_gregorian(self):
self.assertEqual(julian_to_gregorian(1984, 2, 29), vanilla_date(1984, 3, 13))
|
import unittest
from datetime import date as vanilla_date
from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian, is_julian_leap_year
class TestJulian(unittest.TestCase):
def test_is_gregorian_leap_year(self):
self.assertTrue(is_julian_leap_year(2000))
self.assertTrue(is_julian_leap_year(1984))
self.assertTrue(is_julian_leap_year(1900))
self.assertFalse(is_julian_leap_year(1901))
def test_distant_julian_to_gregorian(self):
self.assertEqual(distant_julian_to_gregorian(9999, 12, 1), (10000, 2, 12))
def test_julian_to_gregorian(self):
self.assertEqual(julian_to_gregorian(1984, 2, 29), vanilla_date(1984, 3, 13))
|
Add comment on PHPUnit installation via Composer
|
<?php
/**
* Runs PHPUnit command in browser for ZnZend module tests
*
* Useful if there is no access to commandline, eg. restricted permissions
* Assuming the contents of ZnZend module are in <webroot>/zf2app/vendor/ZnZend,
* and this file resides in ZnZend/test, just type the following line in the browser:
* http://localhost/zf2app/vendor/ZnZend/test/phpunit_cmd_browser.php
*
* @author Zion Ng <zion@intzone.com>
* @link [Source] http://github.com/zionsg/ZnZend
* @since 2012-12-04T13:00+08:00
*/
// Assumes PHPUnit has been installed via Composer and is in include path
require_once 'PHPUnit/vendor/autoload.php';
$command = new PHPUnit_TextUI_Command;
?>
<pre>
<?php $command->run(array(), true); // output result in <pre> tags ?>
</pre>
|
<?php
/**
* Runs PHPUnit command in browser for ZnZend module tests
*
* Useful if there is no access to commandline, eg. restricted permissions
* Assuming the contents of ZnZend module are in <webroot>/zf2app/vendor/ZnZend,
* and this file resides in ZnZend/test, just type the following line in the browser:
* http://localhost/zf2app/vendor/ZnZend/test/phpunit_cmd_browser.php
*
* @author Zion Ng <zion@intzone.com>
* @link [Source] http://github.com/zionsg/ZnZend
* @since 2012-12-04T13:00+08:00
*/
require_once 'PHPUnit/vendor/autoload.php'; // assumes PHPUnit library is in include path
$command = new PHPUnit_TextUI_Command;
?>
<pre>
<?php $command->run(array(), true); // output result in <pre> tags ?>
</pre>
|
Remove fast path in resize handler
It can't reliably determine whether the scrollbar still needs to
be clipped
Closes #5445
|
import { onBlur } from "../display/focus.js"
import { on } from "../util/event.js"
// These must be handled carefully, because naively registering a
// handler for each editor will cause the editors to never be
// garbage collected.
function forEachCodeMirror(f) {
if (!document.getElementsByClassName) return
let byClass = document.getElementsByClassName("CodeMirror")
for (let i = 0; i < byClass.length; i++) {
let cm = byClass[i].CodeMirror
if (cm) f(cm)
}
}
let globalsRegistered = false
export function ensureGlobalHandlers() {
if (globalsRegistered) return
registerGlobalHandlers()
globalsRegistered = true
}
function registerGlobalHandlers() {
// When the window resizes, we need to refresh active editors.
let resizeTimer
on(window, "resize", () => {
if (resizeTimer == null) resizeTimer = setTimeout(() => {
resizeTimer = null
forEachCodeMirror(onResize)
}, 100)
})
// When the window loses focus, we want to show the editor as blurred
on(window, "blur", () => forEachCodeMirror(onBlur))
}
// Called when the window resizes
function onResize(cm) {
let d = cm.display
// Might be a text scaling operation, clear size caches.
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
d.scrollbarsClipped = false
cm.setSize()
}
|
import { onBlur } from "../display/focus.js"
import { on } from "../util/event.js"
// These must be handled carefully, because naively registering a
// handler for each editor will cause the editors to never be
// garbage collected.
function forEachCodeMirror(f) {
if (!document.getElementsByClassName) return
let byClass = document.getElementsByClassName("CodeMirror")
for (let i = 0; i < byClass.length; i++) {
let cm = byClass[i].CodeMirror
if (cm) f(cm)
}
}
let globalsRegistered = false
export function ensureGlobalHandlers() {
if (globalsRegistered) return
registerGlobalHandlers()
globalsRegistered = true
}
function registerGlobalHandlers() {
// When the window resizes, we need to refresh active editors.
let resizeTimer
on(window, "resize", () => {
if (resizeTimer == null) resizeTimer = setTimeout(() => {
resizeTimer = null
forEachCodeMirror(onResize)
}, 100)
})
// When the window loses focus, we want to show the editor as blurred
on(window, "blur", () => forEachCodeMirror(onBlur))
}
// Called when the window resizes
function onResize(cm) {
let d = cm.display
if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
return
// Might be a text scaling operation, clear size caches.
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
d.scrollbarsClipped = false
cm.setSize()
}
|
Update GitHub repos from blancltd to developersociety
|
#!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='django-glitter-news',
version='0.3.3',
description='Django Glitter News for Django',
long_description=readme,
url='https://github.com/developersociety/django-glitter-news',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
install_requires=[
'django-glitter',
'django-taggit>=0.21.3',
'django-admin-sortable>=2.0.0',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
license='BSD',
)
|
#!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='django-glitter-news',
version='0.3.3',
description='Django Glitter News for Django',
long_description=readme,
url='https://github.com/blancltd/django-glitter-news',
maintainer='Blanc Ltd',
maintainer_email='studio@blanc.ltd.uk',
platforms=['any'],
packages=find_packages(),
include_package_data=True,
install_requires=[
'django-glitter',
'django-taggit>=0.21.3',
'django-admin-sortable>=2.0.0',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
license='BSD',
)
|
Move point light into position behind camera
|
var skyBox = require('./sky_box'),
TWEEN = require('tween.js'),
global = require('../lib/util').global(),
raf = require('raf-component'),
THREE = require('three');
module.exports = function scene (config) {
var distance = 1000,
camera,
world,
renderer;
camera = new THREE.PerspectiveCamera(30, global.innerWidth / global.innerHeight, 0.1, 100000000);
camera.up = new THREE.Vector3(0, 0, 1);
camera.useQuaternion = true;
camera.position.y = distance * 5;
camera.position.z = distance * 2;
world = new THREE.Scene();
renderer = new THREE.WebGLRenderer({ antialias: true });
config.maxAnisotropy = renderer.getMaxAnisotropy();
skyBox(world, config.sky_box);
var point = new THREE.PointLight(0xffffff, 1, 0);
point.position.y = 4000;
point.position.z = 1000;
world.add(point);
world.add(new THREE.AmbientLight(0x333333));
skyBox(world, config.sky_box);
return {
setSize: setSize,
render: render,
domCanvas: renderer.domElement,
scene: world,
camera: camera
};
function setSize (width, height) {
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
function render () {
raf(render);
TWEEN.update();
renderer.render(world, camera);
}
};
|
var skyBox = require('./sky_box'),
TWEEN = require('tween.js'),
global = require('../lib/util').global(),
raf = require('raf-component'),
THREE = require('three');
module.exports = function scene (config) {
var distance = 1000,
camera,
scene,
renderer;
camera = new THREE.PerspectiveCamera(30, global.innerWidth / global.innerHeight, 0.1, 100000000);
camera.up = new THREE.Vector3(0, 0, 1);
camera.useQuaternion = true;
camera.position.y = distance * 10;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({ antialias: true });
config.maxAnisotropy = renderer.getMaxAnisotropy();
skyBox(scene, config.sky_box);
scene.add(new THREE.PointLight(0xffffff, 1, 0));
scene.add(new THREE.AmbientLight(0x333333));
skyBox(scene, config.sky_box);
return {
setSize: setSize,
render: render,
domCanvas: renderer.domElement,
scene: scene,
camera: camera
};
function setSize (width, height) {
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
function render () {
raf(render);
TWEEN.update();
renderer.render(scene, camera);
}
};
|
Make path to sample project shorter
|
"""Provide APP constant for the purposes of manually running the flask app
For example, build the front end, then run the app with environment variables::
cd smif/app/
npm run build
cd ../http_api/
FLASK_APP=smif.http_api.app FLASK_DEBUG=1 flask run
"""
import os
from smif.data_layer import DatafileInterface
from smif.http_api import create_app
def get_data_interface():
"""Return a data_layer.DataInterface
"""
return DatafileInterface(
os.path.join(os.path.dirname(__file__), '..', 'sample_project')
)
APP = create_app(
static_folder=os.path.join(os.path.dirname(__file__), '..', 'app', 'dist'),
template_folder=os.path.join(os.path.dirname(__file__), '..', 'app', 'dist'),
get_data_interface=get_data_interface
)
|
"""Provide APP constant for the purposes of manually running the flask app
For example, build the front end, then run the app with environment variables::
cd smif/app/
npm run build
cd ../http_api/
FLASK_APP=smif.http_api.app FLASK_DEBUG=1 flask run
"""
import os
from smif.data_layer import DatafileInterface
from smif.http_api import create_app
def get_data_interface():
"""Return a data_layer.DataInterface
"""
return DatafileInterface(
os.path.join(os.path.dirname(__file__), '..', '..', 'smif', 'sample_project')
)
APP = create_app(
static_folder=os.path.join(os.path.dirname(__file__), '..', 'app', 'dist'),
template_folder=os.path.join(os.path.dirname(__file__), '..', 'app', 'dist'),
get_data_interface=get_data_interface
)
|
Fix players unable to claim chunks
|
package com.cjburkey.claimchunk.service.prereq.claim;
import com.cjburkey.claimchunk.Config;
import com.cjburkey.claimchunk.Utils;
import com.cjburkey.claimchunk.worldguard.WorldGuardHandler;
import java.util.Optional;
public class WorldGuardPrereq implements IClaimPrereq {
@Override
public int getWeight() {
return 100;
}
@Override
public boolean getPassed(PrereqClaimData data) {
boolean allowedToClaimWG = WorldGuardHandler.isAllowedClaim(data.chunk);
boolean worldAllowsClaims = !Config.getList("chunks", "disabledWorlds").contains(data.chunk.getWorld().getName());
boolean adminOverride = Config.getBool("worldguard", "allowAdminOverride");
@SuppressWarnings("OptionalGetWithoutIsPresent")
boolean hasAdmin = Utils.hasAdmin(data.player.get());
// This can be simplified but it works and I'm feeling lazy
// I promise I'll get around to it
return !(!(worldAllowsClaims || (hasAdmin && adminOverride)) || !(allowedToClaimWG || (hasAdmin && adminOverride)));
}
@Override
public Optional<String> getErrorMessage(PrereqClaimData data) {
return Optional.of(data.claimChunk.getMessages().claimLocationBlock);
}
}
|
package com.cjburkey.claimchunk.service.prereq.claim;
import com.cjburkey.claimchunk.Config;
import com.cjburkey.claimchunk.Utils;
import com.cjburkey.claimchunk.worldguard.WorldGuardHandler;
import java.util.Optional;
public class WorldGuardPrereq implements IClaimPrereq {
@Override
public int getWeight() {
return 100;
}
@Override
public boolean getPassed(PrereqClaimData data) {
boolean allowedToClaimWG = WorldGuardHandler.isAllowedClaim(data.chunk);
boolean worldAllowsClaims = !Config.getList("chunks", "disabledWorlds").contains(data.chunk.getWorld().getName());
boolean adminOverride = Config.getBool("worldguard", "allowAdminOverride");
@SuppressWarnings("OptionalGetWithoutIsPresent")
boolean hasAdmin = Utils.hasAdmin(data.player.get());
return (worldAllowsClaims || allowedToClaimWG) && (hasAdmin && adminOverride);
}
@Override
public Optional<String> getErrorMessage(PrereqClaimData data) {
return Optional.of(data.claimChunk.getMessages().claimLocationBlock);
}
}
|
Add .matches() as default choice for browserUtils.matchSelector
Formerly known as matchesSelector(), with many vendor prefixes as seen in this function.
I'm using ADT in a jsdom environment, which doesn't support any vendor-prefixed variations
of this function.
http://caniuse.com/#feat=matchesselector
|
// Copyright 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.provide('axs.browserUtils');
/**
* Use Webkit matcher when matches() is not supported.
* Use Firefox matcher when Webkit is not supported.
* Use IE matcher when neither webkit nor Firefox supported.
* @param {Element} element
* @param {string} selector
* @return {boolean} true if the element matches the selector
*/
axs.browserUtils.matchSelector = function(element, selector) {
if (element.matches)
return element.matches(selector);
if (element.webkitMatchesSelector)
return element.webkitMatchesSelector(selector);
if (element.mozMatchesSelector)
return element.mozMatchesSelector(selector);
if (element.msMatchesSelector)
return element.msMatchesSelector(selector);
return false;
};
|
// Copyright 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.provide('axs.browserUtils');
/**
* Use Firefox matcher when Webkit is not supported.
* Use IE matcher when neither webkit nor Firefox supported.
* @param {Element} element
* @param {string} selector
* @return {boolean} true if the element matches the selector
*/
axs.browserUtils.matchSelector = function(element, selector) {
if (element.webkitMatchesSelector)
return element.webkitMatchesSelector(selector);
if (element.mozMatchesSelector)
return element.mozMatchesSelector(selector);
if (element.msMatchesSelector)
return element.msMatchesSelector(selector);
return false;
};
|
Return outer html tag too
|
// This script needs to be run using phantomjs
//
// Example usage:
// ~/.phantomjs/2.1.1/darwin/bin/phantomjs phantomjs/get.js
var page = require('webpage').create();
var system = require('system');
function doRender(page) {
var html = page.evaluate(function() {
// Magically this bit will get evaluated in the context of the page
// TODO Also return doctype. This currently doesn't
return document.documentElement.outerHTML;
});
console.log(html);
phantom.exit();
}
if (system.args.length === 1) {
console.log('Usage: get.js <some URL>');
phantom.exit();
}
var url = system.args[1];
// This displays console messages from inside the page.evaluate block
page.onConsoleMessage = function(msg) {
// For the time being disable console output here.
// TODO Return console output by making this script return json
// which contains the html and the console output separately
//console.log('console:', msg);
};
page.open(url, function (status) {
// As a first (very rough) pass wait for a
// half second before rendering the page
setTimeout(function() {
doRender(page);
}, 500);
});
|
// This script needs to be run using phantomjs
//
// Example usage:
// ~/.phantomjs/2.1.1/darwin/bin/phantomjs phantomjs/get.js
var page = require('webpage').create();
var system = require('system');
function doRender(page) {
var html = page.evaluate(function() {
// Magically this bit will get evaluated in the context of the page
return document.documentElement.innerHTML;
});
console.log(html);
phantom.exit();
}
if (system.args.length === 1) {
console.log('Usage: get.js <some URL>');
phantom.exit();
}
var url = system.args[1];
// This displays console messages from inside the page.evaluate block
page.onConsoleMessage = function(msg) {
// For the time being disable console output here.
// TODO Return console output by making this script return json
// which contains the html and the console output separately
//console.log('console:', msg);
};
page.open(url, function (status) {
// As a first (very rough) pass wait for a
// half second before rendering the page
setTimeout(function() {
doRender(page);
}, 500);
});
|
Fix angle of clocks hour indicator
|
/**
* @module timed
* @submodule timed-components
* @public
*/
import Component from '@ember/component'
import moment from 'moment'
import Ember from 'ember'
import { task, timeout } from 'ember-concurrency'
const { testing } = Ember
export default Component.extend({
classNames: ['timed-clock'],
hour: 0,
minute: 0,
second: 0,
_update() {
let now = moment()
let second = now.seconds() * 6
let minute = now.minutes() * 6 + second / 60
let hour = (now.hours() % 12) / 12 * 360 + minute / 12
this.setProperties({ second, minute, hour })
},
timer: task(function*() {
for (;;) {
this._update()
/* istanbul ignore else */
if (testing) {
return
}
/* istanbul ignore next */
yield timeout(1000)
}
}).on('didInsertElement')
})
|
/**
* @module timed
* @submodule timed-components
* @public
*/
import Component from '@ember/component'
import moment from 'moment'
import Ember from 'ember'
import { task, timeout } from 'ember-concurrency'
const { testing } = Ember
export default Component.extend({
classNames: ['timed-clock'],
hour: 0,
minute: 0,
second: 0,
_update() {
let now = moment()
let second = now.seconds() * 6
let minute = now.minutes() * 6 + second / 60
let hour = (now.hours() % 12) / 12 * 360 + 90 + minute / 12
this.setProperties({ second, minute, hour })
},
timer: task(function*() {
for (;;) {
this._update()
/* istanbul ignore else */
if (testing) {
return
}
/* istanbul ignore next */
yield timeout(1000)
}
}).on('didInsertElement')
})
|
Call to contructor method should begin with capital letter
|
var Client = require('./carbon'),
metric = require('./metric');
function GraphiteClient (properties) {
this._carbon = properties.carbon;
}
GraphiteClient.createClient = function (config) {
return new this({
carbon: new Client(config)
});
};
/**
* Writes metric with timestamp to Graphite
*
* @param metrics an object with values, e.g. {home:{indoor:{temp:21.2}}}
* @param timestamp defaults to Date.now()
* @returns {Promise} a promise
*/
GraphiteClient.prototype.write = function (metrics, timestamp) {
timestamp = timestamp || Date.now();
timestamp = Math.floor(timestamp / 1000);
return this._carbon.write(metric.flatten(metrics), timestamp);
};
/**
* Ends the connection
*/
GraphiteClient.prototype.end = function () {
return this._carbon.end();
};
module.exports = GraphiteClient;
|
var client = require('./carbon'),
metric = require('./metric');
function GraphiteClient (properties) {
this._carbon = properties.carbon;
}
GraphiteClient.createClient = function (config) {
return new this({
carbon: new client(config)
});
};
/**
* Writes metric with timestamp to Graphite
*
* @param metrics an object with values, e.g. {home:{indoor:{temp:21.2}}}
* @param timestamp defaults to Date.now()
* @returns {RSVP.Promise} a promise
*/
GraphiteClient.prototype.write = function (metrics, timestamp) {
timestamp = timestamp || Date.now();
timestamp = Math.floor(timestamp / 1000);
return this._carbon.write(metric.flatten(metrics), timestamp);
};
/**
* Ends the connection
*/
GraphiteClient.prototype.end = function () {
return this._carbon.end();
};
module.exports = GraphiteClient;
|
Move the service initialisation creation to onCreate
|
package com.example.crystalgame.communication;
import com.example.crystalgame.library.communication.Communication;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* The service responsible for the management of communication
* @author Balazs Pete, Shen Chen
*
*/
public class CommunicationService extends Service {
private Communication communication;
public void onCreate() {
super.onCreate();
ClientCommunicationManager manager = new ClientCommunicationManager("192.168.1.8", 3000);
communication = new Communication(manager);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startService(intent);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
|
package com.example.crystalgame.communication;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* The service responsible for the management of communication
* @author Balazs Pete, Shen Chen
*
*/
public class CommunicationService extends Service {
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
startService(intent);
// TODO: remove
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
|
Return None for unsupported platforms
|
import os
import os.path
import sys
def enumerate():
ports = []
if sys.platform == 'win32':
# Iterate through registry because WMI does not show virtual serial ports
import _winreg
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'HARDWARE\DEVICEMAP\SERIALCOMM')
i = 0
while True:
try:
ports.append(_winreg.EnumValue(key, i)[1])
i = i + 1
except WindowsError:
break
elif sys.platform == 'linux2':
if os.path.exists('/dev/serial/by-id'):
entries = os.listdir('/dev/serial/by-id')
dirs = [os.readlink(os.path.join('/dev/serial/by-id', x))
for x in entries]
ports.extend([os.path.normpath(os.path.join('/dev/serial/by-id', x))
for x in dirs])
else:
return None
return ports
|
import os
import os.path
import sys
def enumerate():
ports = []
if sys.platform == 'win32':
# Iterate through registry because WMI does not show virtual serial ports
import _winreg
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'HARDWARE\DEVICEMAP\SERIALCOMM')
i = 0
while True:
try:
ports.append(_winreg.EnumValue(key, i)[1])
i = i + 1
except WindowsError:
break
elif sys.platform == 'linux2':
if os.path.exists('/dev/serial/by-id'):
entries = os.listdir('/dev/serial/by-id')
dirs = [os.readlink(os.path.join('/dev/serial/by-id', x))
for x in entries]
ports.extend([os.path.normpath(os.path.join('/dev/serial/by-id', x))
for x in dirs])
return ports
|
Exit program on uncaught/unhandled errors
|
'use strict';
const log = require('silk-alog');
const Vibrator = require('silk-vibrator').default;
const wifi = require('silk-wifi').default;
const Input = require('silk-input').default;
const util = require('silk-sysutils');
function bail(err) {
log.error(err.stack || err);
process.abort();
}
process.on('unhandledRejection', bail);
process.on('uncaughtException', bail);
module.exports = {
init: () => {
/**
* Initializing the Wi-Fi module.
*/
wifi.init()
.then(() => {
return wifi.online();
})
.then(() => {
log.info('Wifi initialized successfully');
})
.catch((err) => {
log.error('Failed to initialize wifi', err);
});
// Power key handling
let input = new Input();
let vib = new Vibrator();
input.on('down', e => {
vib.pattern(50);
switch (e.keyId) {
case 'power':
log.warn('Powering down');
util.setprop('sys.powerctl', 'shutdown');
break;
default:
log.verbose(`Unhandled key: ${JSON.stringify(e)}`);
break;
}
});
}
};
|
'use strict';
const log = require('silk-alog');
const Vibrator = require('silk-vibrator').default;
const wifi = require('silk-wifi').default;
const Input = require('silk-input').default;
const util = require('silk-sysutils');
module.exports = {
init: () => {
/**
* Initializing the Wi-Fi module.
*/
wifi.init()
.then(() => {
return wifi.online();
})
.then(() => {
log.info('Wifi initialized successfully');
})
.catch((err) => {
log.error('Failed to initialize wifi', err);
});
// Power key handling
let input = new Input();
let vib = new Vibrator();
input.on('down', e => {
vib.pattern(50);
switch (e.keyId) {
case 'power':
log.warn('Powering down');
util.setprop('sys.powerctl', 'shutdown');
break;
default:
log.verbose(`Unhandled key: ${JSON.stringify(e)}`);
break;
}
});
}
};
|
Make OriginKind an int "enum".
|
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package resource
import (
"github.com/juju/errors"
)
// These are the valid kinds of resource origin.
const (
originKindUnknown OriginKind = iota
OriginKindUpload
OriginKindStore
)
var knownOriginKinds = map[OriginKind]string{
OriginKindUpload: "upload",
OriginKindStore: "store",
}
// OriginKind identifies the kind of a resource origin.
type OriginKind int
// ParseOriginKind converts the provided string into an OriginKind.
// If it is not a known origin kind then an error is returned.
func ParseOriginKind(value string) (OriginKind, error) {
for kind, str := range knownOriginKinds {
if value == str {
return kind, nil
}
}
return originKindUnknown, errors.Errorf("unknown origin %q", value)
}
// String returns the printable representation of the origin kind.
func (o OriginKind) String() string {
return knownOriginKinds[o]
}
// Validate ensures that the origin is correct.
func (o OriginKind) Validate() error {
// Ideally, only the (unavoidable) zero value would be invalid.
// However, typedef'ing int means that the use of int literals
// could result in invalid Type values other than the zero value.
if _, ok := knownOriginKinds[o]; !ok {
return errors.NewNotValid(nil, "unknown origin")
}
return nil
}
|
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package resource
import (
"github.com/juju/errors"
)
// These are the valid kinds of resource origin.
var (
OriginKindUpload = OriginKind{"upload"}
OriginKindStore = OriginKind{"store"}
)
var knownOriginKinds = map[OriginKind]bool{
OriginKindUpload: true,
OriginKindStore: true,
}
// OriginKind identifies the kind of a resource origin.
type OriginKind struct {
str string
}
// ParseOriginKind converts the provided string into an OriginKind.
// If it is not a known origin kind then an error is returned.
func ParseOriginKind(value string) (OriginKind, error) {
for kind := range knownOriginKinds {
if value == kind.str {
return kind, nil
}
}
return OriginKind{}, errors.Errorf("unknown origin %q", value)
}
// String returns the printable representation of the origin kind.
func (o OriginKind) String() string {
return o.str
}
// Validate ensures that the origin is correct.
func (o OriginKind) Validate() error {
// Only the zero value is invalid.
var zero OriginKind
if o == zero {
return errors.NewNotValid(nil, "unknown origin")
}
return nil
}
|
Set default table prefix as ` localhost.`
|
package com.coding4people.mosquitoreport.api.factories;
import java.util.Optional;
import javax.inject.Inject;
import org.glassfish.hk2.api.Factory;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride;
import com.coding4people.mosquitoreport.api.Env;
public class DynamoDBMapperFactory implements Factory<DynamoDBMapper> {
DynamoDBMapper mapper;
@Inject
public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) {
mapper = new DynamoDBMapper(client,
new DynamoDBMapperConfig.Builder()
.withTableNameOverride(TableNameOverride.withTableNamePrefix(Optional
.ofNullable(env.get("MOSQUITO_REPORT_DYNAMODB_TABLE_PREFIX")).orElse("localhost.")))
.build());
}
@Override
public void dispose(DynamoDBMapper mapper) {
}
@Override
public DynamoDBMapper provide() {
return mapper;
}
}
|
package com.coding4people.mosquitoreport.api.factories;
import java.util.Optional;
import javax.inject.Inject;
import org.glassfish.hk2.api.Factory;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride;
import com.coding4people.mosquitoreport.api.Env;
public class DynamoDBMapperFactory implements Factory<DynamoDBMapper> {
DynamoDBMapper mapper;
@Inject
public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) {
mapper = new DynamoDBMapper(client,
new DynamoDBMapperConfig.Builder()
.withTableNameOverride(TableNameOverride.withTableNamePrefix(Optional
.ofNullable(env.get("MOSQUITO_REPORT_DYNAMODB_TABLE_PREFIX")).orElse("localhost")))
.build());
}
@Override
public void dispose(DynamoDBMapper mapper) {
}
@Override
public DynamoDBMapper provide() {
return mapper;
}
}
|
Return null as early as possible if the prefix is invalid
|
'use babel';
import completions from '../data/completions';
class CurryProvider {
constructor() {
this.scopeSelector = '.source.curry';
this.disableForScopeSelector = '.source.curry .comment';
this.suggestionPriority = 2;
this.filterSuggestions = true;
this.acpTypes = new Map([['types', 'type'], ['constructors', 'tag'], ['functions', 'function']]);
}
getSuggestions({prefix}) {
if (!prefix) {
return null;
}
const suggestions = [];
for (const module of completions) {
for (const [key, type] of this.acpTypes) {
const createSugg = this.createSuggestion.bind(null, module.name, type);
const matches = module[key].map(createSugg);
suggestions.push(...matches);
}
}
return suggestions;
}
createSuggestion(module, type, suggestion) {
return {
text: suggestion.name,
description: suggestion.description,
type: type,
leftLabel: module,
rightLabel: suggestion.typeSig
};
}
}
export default new CurryProvider();
|
'use babel';
import completions from '../data/completions';
class CurryProvider {
constructor() {
this.scopeSelector = '.source.curry';
this.disableForScopeSelector = '.source.curry .comment';
this.suggestionPriority = 2;
this.filterSuggestions = true;
this.acpTypes = new Map([['types', 'type'], ['constructors', 'tag'], ['functions', 'function']]);
}
getSuggestions({prefix}) {
if (prefix) {
const suggestions = [];
for (const module of completions) {
for (const [key, type] of this.acpTypes) {
const createSugg = this.createSuggestion.bind(null, module.name, type);
const matches = module[key].map(createSugg);
suggestions.push(...matches);
}
}
return suggestions;
}
return null;
}
createSuggestion(module, type, suggestion) {
return {
text: suggestion.name,
description: suggestion.description,
type: type,
leftLabel: module,
rightLabel: suggestion.typeSig
};
}
}
export default new CurryProvider();
|
Add redis as a session store.
Don't forget turning on a redis-server.
|
"use strict";
var debug = require('debug')('server');
var express = require('express');
var io = require('socket.io')();
var path = require('path');
var redis = require('redis');
var session = require('express-session');
var sessionStore = require('connect-redis')(session);
var routes = require('./routes/index');
var app = express();
var redisClient = redis.createClient();
app.use(session({
secret: 'kashikoi kawaii erichika',
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
store: new sessionStore({ host: 'localhost', port: 6379, client: redisClient })
}));
app.use('/', routes);
app.set('view engine', 'jade');
app.set('views', path.join(__dirname, 'views'));
var server = app.listen(process.env.PORT || 3000, function () {
var host = server.address().address;
var port = server.address().port;
debug('listening at http://%s:%s', host, port);
});
io.attach(server);
// TODO: move these lines to separated file.
io.on('connection', function (socket) {
debug('+1 socket connection');
io.emit('test', { message: 'Hey, everyone! +1 connection' });
socket.on('test', function (data) {
debug('received: %s', data);
});
socket.on('disconnect', function () {
debug('-1 socket connection');
});
});
|
"use strict";
var debug = require('debug')('server');
var express = require('express');
var io = require('socket.io')();
var path = require('path');
var routes = require('./routes/index');
var app = express();
app.use('/', routes);
app.set('view engine', 'jade');
app.set('views', path.join(__dirname, 'views'));
var server = app.listen(process.env.PORT || 3000, function () {
var host = server.address().address;
var port = server.address().port;
debug('listening at http://%s:%s', host, port);
});
io.attach(server);
// TODO: move these lines to separated file.
io.on('connection', function (socket) {
debug('+1 socket connection');
io.emit('test', { message: 'Hey, everyone! +1 connection' });
socket.on('test', function (data) {
debug('received: %s', data);
});
socket.on('disconnect', function () {
debug('-1 socket connection');
});
});
|
Change default value in example
|
//- JavaScript source code
//- roll-up.js ~~
//
// NOTE: This file isn't just an example -- it is also used as part of the
// QM project's build process :-)
//
// ~~ (c) SRW, 17 Dec 2012
// ~~ last updated 20 Nov 2014
(function () {
'use strict';
// Pragmas
/*jshint maxparams: 1, quotmark: single, strict: true */
/*jslint indent: 4, maxlen: 80, node: true */
/*properties argv, length, roll_up */
// Declarations
var directory, json_file;
// Definitions
directory = (process.argv.length > 2) ? process.argv[2] : 'public';
json_file = (process.argv.length > 3) ? process.argv[3] : 'katamari.json';
// Demonstration
require('../').roll_up(directory, json_file);
// That's all, folks!
return;
}());
//- vim:set syntax=javascript:
|
//- JavaScript source code
//- roll-up.js ~~
//
// NOTE: This file isn't just an example -- it is also used as part of the
// QM project's build process :-)
//
// ~~ (c) SRW, 17 Dec 2012
// ~~ last updated 12 Aug 2014
(function () {
'use strict';
// Pragmas
/*jshint maxparams: 1, quotmark: single, strict: true */
/*jslint indent: 4, maxlen: 80, node: true */
/*properties argv, length, roll_up */
// Declarations
var directory, json_file;
// Definitions
directory = (process.argv.length > 2) ? process.argv[2] : 'public_html';
json_file = (process.argv.length > 3) ? process.argv[3] : 'katamari.json';
// Demonstration
require('../').roll_up(directory, json_file);
// That's all, folks!
return;
}());
//- vim:set syntax=javascript:
|
Fix local development when redux tools unavailable
|
import hashHistory from 'react-router/lib/hashHistory';
import { routerMiddleware } from 'react-router-redux';
import Raven from 'raven-js';
import createRavenMiddleware from 'raven-for-redux';
import thunkMiddleware from 'redux-thunk';
import promiseMiddleware from 'redux-simple-promise';
import { createStore, applyMiddleware, compose } from 'redux';
import { errorReportingMiddleware } from './lib/reduxHelpers';
import getRootReducer from './reducers/root';
import { isDevMode } from './config';
const reduxRouterMiddleware = routerMiddleware(hashHistory);
const middlewares = [
promiseMiddleware(),
reduxRouterMiddleware,
thunkMiddleware,
errorReportingMiddleware,
];
function configDevelopmentStore(appName) {
/* eslint-disable no-underscore-dangle */
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
/* eslint-enable */
return createStore(getRootReducer(appName), {}, composeEnhancers(
applyMiddleware(...middlewares)
));
}
function configProductionStore(appName) {
return createStore(getRootReducer(appName), {}, compose(
applyMiddleware(...middlewares,
createRavenMiddleware(Raven, {
breadcrumbDataFromAction: action => (
{ STRING: action.str }
),
})),
));
}
let store; // singleton store
// acts as a singleton factory method
function getStore(appName) {
if (store === undefined) {
store = (isDevMode()) ? configDevelopmentStore(appName) : configProductionStore(appName);
}
return store;
}
export default getStore;
|
import hashHistory from 'react-router/lib/hashHistory';
import { routerMiddleware } from 'react-router-redux';
import Raven from 'raven-js';
import createRavenMiddleware from 'raven-for-redux';
import thunkMiddleware from 'redux-thunk';
import promiseMiddleware from 'redux-simple-promise';
import { createStore, applyMiddleware, compose } from 'redux';
import { errorReportingMiddleware } from './lib/reduxHelpers';
import getRootReducer from './reducers/root';
import { isDevMode } from './config';
const reduxRouterMiddleware = routerMiddleware(hashHistory);
const middlewares = [
promiseMiddleware(),
reduxRouterMiddleware,
thunkMiddleware,
errorReportingMiddleware,
];
function configDevelopmentStore(appName) {
/* eslint-disable no-underscore-dangle */
return createStore(getRootReducer(appName), {}, compose(
applyMiddleware(...middlewares),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
));
/* eslint-enable */
}
function configProductionStore(appName) {
return createStore(getRootReducer(appName), {}, compose(
applyMiddleware(...middlewares,
createRavenMiddleware(Raven, {
breadcrumbDataFromAction: action => (
{ STRING: action.str }
),
})),
));
}
let store; // singleton store
// acts as a singleton factory method
function getStore(appName) {
if (store === undefined) {
store = (isDevMode()) ? configDevelopmentStore(appName) : configProductionStore(appName);
}
return store;
}
export default getStore;
|
Change the facet to sort by name instead of project count
|
from registry.models import *
from operator import attrgetter
related_by_projects_Models = [
BigAim,
ClinicalArea,
ClinicalSetting,
Descriptor,
]
class FacetForm:
def __init__(self):
self.facet_categories = [model.__name__ for model in related_by_projects_Models]
for model in related_by_projects_Models:
models = list(model.objects.all())
models.sort(key=lambda m : m.__str__(), reverse=False)
setattr(self, model.__name__, models)
def get_display(self, facet_category):
displays = {
'BigAim': 'Big Aim',
'ClinicalArea': 'Clinical Area',
'ClinicalSetting': 'Clinical Setting',
'Descriptor': 'MeSH Keyword',
}
return displays[facet_category]
|
from registry.models import *
from operator import attrgetter
related_by_projects_Models = [
BigAim,
ClinicalArea,
ClinicalSetting,
Descriptor,
]
class FacetForm:
def __init__(self):
self.facet_categories = [model.__name__ for model in related_by_projects_Models]
for model in related_by_projects_Models:
models = list(model.objects.all())
models.sort(key=lambda m : m.projects.count(), reverse=True)
setattr(self, model.__name__, models)
def get_display(self, facet_category):
displays = {
'BigAim': 'Big Aim',
'ClinicalArea': 'Clinical Area',
'ClinicalSetting': 'Clinical Setting',
'Descriptor': 'MeSH Keyword',
}
return displays[facet_category]
|
Use IRC server on localhost by default
|
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
import importlib
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'localhost',
server_port = 6667,
use_ssl = False,
password = None,
silent_bot = False,
log_channels = [],
other_channels = [],
places = ['London', 'Tokyo', 'New York'],
feed_interval = 15, # minutes
feeds = [dict(
name = 'pmxbot bitbucket',
channel = '#inane',
linkurl = 'http://bitbucket.org/yougov/pmxbot',
url = 'http://bitbucket.org/yougov/pmxbot',
),
],
librarypaste = 'http://paste.jaraco.com',
)
"The config object"
if __name__ == '__main__':
importlib.import_module('pmxbot.core').run()
|
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
import importlib
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'irc.freenode.net',
server_port = 6667,
use_ssl = False,
password = None,
silent_bot = False,
log_channels = [],
other_channels = [],
places = ['London', 'Tokyo', 'New York'],
feed_interval = 15, # minutes
feeds = [dict(
name = 'pmxbot bitbucket',
channel = '#inane',
linkurl = 'http://bitbucket.org/yougov/pmxbot',
url = 'http://bitbucket.org/yougov/pmxbot',
),
],
librarypaste = 'http://paste.jaraco.com',
)
"The config object"
if __name__ == '__main__':
importlib.import_module('pmxbot.core').run()
|
Check if action returns disposable
|
from rx.core import Disposable
from rx.disposables import SingleAssignmentDisposable
def default_sub_comparer(x, y):
return 0 if x == y else 1 if x > y else -1
class ScheduledItem(object):
def __init__(self, scheduler, state, action, duetime, comparer=None):
self.scheduler = scheduler
self.state = state
self.action = action
self.duetime = duetime
self.comparer = comparer or default_sub_comparer
self.disposable = SingleAssignmentDisposable()
def invoke(self):
ret = self.action(self.scheduler, self.state)
if isinstance(ret, Disposable):
self.disposable.disposable = ret
def compare_to(self, other):
return self.comparer(self.duetime, other.duetime)
def cancel(self):
"""Cancels the work item by disposing the resource returned by
invoke_core as soon as possible."""
self.disposable.dispose()
def is_cancelled(self):
return self.disposable.is_disposed
def __lt__(self, other):
return self.compare_to(other) < 0
def __gt__(self, other):
return self.compare_to(other) > 0
def __eq__(self, other):
return self.compare_to(other) == 0
|
from rx.disposables import SingleAssignmentDisposable
def default_sub_comparer(x, y):
return 0 if x == y else 1 if x > y else -1
class ScheduledItem(object):
def __init__(self, scheduler, state, action, duetime, comparer=None):
self.scheduler = scheduler
self.state = state
self.action = action
self.duetime = duetime
self.comparer = comparer or default_sub_comparer
self.disposable = SingleAssignmentDisposable()
def invoke(self):
self.disposable.disposable = self.invoke_core()
def compare_to(self, other):
return self.comparer(self.duetime, other.duetime)
def cancel(self):
"""Cancels the work item by disposing the resource returned by
invoke_core as soon as possible."""
self.disposable.dispose()
def is_cancelled(self):
return self.disposable.is_disposed
def invoke_core(self):
return self.action(self.scheduler, self.state)
def __lt__(self, other):
return self.compare_to(other) < 0
def __gt__(self, other):
return self.compare_to(other) > 0
def __eq__(self, other):
return self.compare_to(other) == 0
|
Allow request vars to work even with disabled session middleware.
|
from django.template.loader import render_to_string
from debug_toolbar.panels import DebugPanel
class RequestVarsDebugPanel(DebugPanel):
"""
A panel to display request variables (POST/GET, session, cookies).
"""
name = 'RequestVars'
has_content = True
def nav_title(self):
return 'Request Vars'
def title(self):
return 'Request Vars'
def url(self):
return ''
def process_request(self, request):
self.request = request
def content(self):
context = {
'get': [(k, self.request.GET.getlist(k)) for k in self.request.GET.iterkeys()],
'post': [(k, self.request.POST.getlist(k)) for k in self.request.POST.iterkeys()],
'cookies': [(k, self.request.COOKIES.get(k)) for k in self.request.COOKIES.iterkeys()],
}
if hasattr(self.request, 'session'):
context['session'] = [(k, self.request.session.get(k)) for k in self.request.session.iterkeys()],
return render_to_string('debug_toolbar/panels/request_vars.html', context)
|
from django.template.loader import render_to_string
from debug_toolbar.panels import DebugPanel
class RequestVarsDebugPanel(DebugPanel):
"""
A panel to display request variables (POST/GET, session, cookies).
"""
name = 'RequestVars'
has_content = True
def nav_title(self):
return 'Request Vars'
def title(self):
return 'Request Vars'
def url(self):
return ''
def process_request(self, request):
self.request = request
def content(self):
context = {
'get': [(k, self.request.GET.getlist(k)) for k in self.request.GET.iterkeys()],
'post': [(k, self.request.POST.getlist(k)) for k in self.request.POST.iterkeys()],
'session': [(k, self.request.session.get(k)) for k in self.request.session.iterkeys()],
'cookies': [(k, self.request.COOKIES.get(k)) for k in self.request.COOKIES.iterkeys()],
}
return render_to_string('debug_toolbar/panels/request_vars.html', context)
|
Change Twitter Search to include "ember-data" and "emberjs"
|
require('dashboard/core');
Dashboard.DataSource = Ember.Object.extend({
getLatestTweets: function(callback) {
Ember.$.getJSON('http://search.twitter.com/search.json?callback=?&q=ember.js%20OR%20emberjs%20OR%20ember-data%20OR%20emberjs', callback);
},
getLatestStackOverflowQuestions: function(callback) {
Ember.$.getJSON('https://api.stackexchange.com/2.0/search?pagesize=20&order=desc&sort=activity&tagged=emberjs&site=stackoverflow&callback=?', callback);
},
getLatestRedditEntries: function(callback) {
Ember.$.getJSON('http://www.reddit.com/r/emberjs/new.json?sort=new&jsonp=?', callback);
},
getLatestGitHubEvents: function(callback) {
Ember.$.getJSON('https://api.github.com/repos/emberjs/ember.js/events?page=1&per_page=100&callback=?', callback);
}
});
|
require('dashboard/core');
Dashboard.DataSource = Ember.Object.extend({
getLatestTweets: function(callback) {
Ember.$.getJSON('http://search.twitter.com/search.json?callback=?&q=ember.js%20OR%20emberjs', callback);
},
getLatestStackOverflowQuestions: function(callback) {
Ember.$.getJSON('https://api.stackexchange.com/2.0/search?pagesize=20&order=desc&sort=activity&tagged=emberjs&site=stackoverflow&callback=?', callback);
},
getLatestRedditEntries: function(callback) {
Ember.$.getJSON('http://www.reddit.com/r/emberjs/new.json?sort=new&jsonp=?', callback);
},
getLatestGitHubEvents: function(callback) {
Ember.$.getJSON('https://api.github.com/repos/emberjs/ember.js/events?page=1&per_page=100&callback=?', callback);
}
});
|
Fix the settings dot tests
|
package cmd
import (
"github.com/gsamokovarov/jump/cli"
)
func Example_helpCmd() {
_ = helpCmd(cli.Args{}, nil)
// Output:
// Usage: jump [COMMAND ...]
//
// Jump to a fuzzy-matched directory passed as an argument.
//
// Commands:
// cd Fuzzy match a directory to jump to.
// chdir Update the score of directory during chdir.
// clean Cleans the database of inexisting entries.
// forget Removes the current directory from the database.
// hint Hints relevant paths for jumping.
// import Import autojump or z scores.
// pin Pin a directory to a search term.
// pins Lists all the pinned search terms.
// settings Configure jump settings.
// shell Display a shell integration script.
// top Lists the directories as they are scored.
// unpin Unpin a search term.
//
// Options:
// --help Show this screen.
// --version Show version.
}
|
package cmd
import (
"github.com/gsamokovarov/jump/cli"
)
func Example_helpCmd() {
_ = helpCmd(cli.Args{}, nil)
// Output:
// Usage: jump [COMMAND ...]
//
// Jump to a fuzzy-matched directory passed as an argument.
//
// Commands:
// cd Fuzzy match a directory to jump to.
// chdir Update the score of directory during chdir.
// clean Cleans the database of inexisting entries.
// forget Removes the current directory from the database.
// hint Hints relevant paths for jumping.
// import Import autojump or z scores.
// pin Pin a directory to a search term.
// pins Lists all the pinned search terms.
// settings Configure jump settings
// shell Display a shell integration script.
// top Lists the directories as they are scored.
// unpin Unpin a search term.
//
// Options:
// --help Show this screen.
// --version Show version.
}
|
Use default number of workers from config
config does a better job at figuring out the optimal number of workers,
so it will be used instead.
|
import Queue
from parallel import config
from parallel import worker
class Runner(object):
def __init__(self, num_workers=config.NUM_WORKERS):
self.in_queue = Queue.Queue()
self.out_queue = Queue.Queue()
self.num_workers = num_workers
self.workers = None
self._start_workers()
def _start_workers(self):
self.workers = [worker.Worker(self.in_queue, self.out_queue)
for i in range(self.num_workers)]
def add_task(self, task, *args, **kwargs):
self.in_queue.put((task, args, kwargs))
def results(self):
self.in_queue.join()
return self.out_queue.queue
|
import Queue
from parallel import worker
class Runner(object):
def __init__(self, num_workers=4):
self.in_queue = Queue.Queue()
self.out_queue = Queue.Queue()
self.num_workers = num_workers
self.workers = None
self._start_workers()
def _start_workers(self):
self.workers = [worker.Worker(self.in_queue, self.out_queue)
for i in range(self.num_workers)]
def add_task(self, task, *args, **kwargs):
self.in_queue.put((task, args, kwargs))
def results(self):
self.in_queue.join()
return self.out_queue.queue
|
Fix login issue in case the user is already signed in
In case you're already signed in and visit the login page,
you have to sign in again, but actually u're still authenticated.
I have added a check that will lead to a redirection to the admin
dashboard in case you're still signed in otherwise you keep on the
login page.
|
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
/**
* BlogSystem - Login as the default controller.
*
* @version 0.1.1 27-Mar-16
* @copyright Copyright (c) 2016 by Andy Liebke. All rights reserved. (http://andysmiles4games.com)
*/
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$auth = $this->get('security.authentication_utils');
$security = $this->get('security.authorization_checker');
if ($security->isGranted('IS_AUTHENTICATED_FULLY')){
return $this->redirectToRoute('admin_dashboard');
} else {
return $this->render('page/login.html.twig', []);
}
}
}
|
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
/**
* BlogSystem - Login as the default controller.
*
* @version 0.1.1 27-Mar-16
* @copyright Copyright (c) 2016 by Andy Liebke. All rights reserved. (http://andysmiles4games.com)
*/
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$auth = $this->get('security.authentication_utils');
$listErrors = $auth->getLastAuthenticationError();
/*var_dump($listErrors);*/
return $this->render('page/login.html.twig', []);
}
}
|
Make hash method return whole numbers
The generated hash number is used to create
an array index which should be a whole number.
Fixes #8
|
/*
* Conversion from virtual time streams out to diagram data, and
* vice-versa, and related functions.
*/
function calculateNotificationContentHash(content) {
var SOME_PRIME_NUMBER = 877;
if (typeof content === "string") {
return content.split("")
.map(function(x) { return x.charCodeAt(0); })
.reduce(function(x, y) { return x + y; });
} else if (typeof content === "number") {
return parseInt(content) * SOME_PRIME_NUMBER;
} else if (typeof content === 'boolean') {
return content ? SOME_PRIME_NUMBER : SOME_PRIME_NUMBER*3;
}
};
function calculateNotificationHash(marbleData) {
var SMALL_PRIME = 7;
var LARGE_PRIME = 1046527;
var MAX = 100000;
var contentHash = calculateNotificationContentHash(marbleData.content);
return ((marbleData.time + contentHash + SMALL_PRIME) * LARGE_PRIME) % MAX;
};
module.exports = {
calculateNotificationHash: calculateNotificationHash,
calculateNotificationContentHash: calculateNotificationContentHash
};
|
/*
* Conversion from virtual time streams out to diagram data, and
* vice-versa, and related functions.
*/
function calculateNotificationContentHash(content) {
var SOME_PRIME_NUMBER = 877;
if (typeof content === "string") {
return content.split("")
.map(function(x) { return x.charCodeAt(0); })
.reduce(function(x, y) { return x + y; });
} else if (typeof content === "number") {
return content * SOME_PRIME_NUMBER;
} else if (typeof content === 'boolean') {
return content ? SOME_PRIME_NUMBER : SOME_PRIME_NUMBER*3;
}
};
function calculateNotificationHash(marbleData) {
var SMALL_PRIME = 7;
var LARGE_PRIME = 1046527;
var MAX = 100000;
var contentHash = calculateNotificationContentHash(marbleData.content);
return ((marbleData.time + contentHash + SMALL_PRIME) * LARGE_PRIME) % MAX;
};
module.exports = {
calculateNotificationHash: calculateNotificationHash,
calculateNotificationContentHash: calculateNotificationContentHash
};
|
Add annotations to prevent ibatis binding exception
|
package fi.nls.oskari.map.layer;
import fi.nls.oskari.domain.map.DataProvider;
import org.apache.ibatis.annotations.*;
import org.json.JSONObject;
import java.util.List;
public interface DataProviderMapper {
@Select("select id, locale from oskari_dataprovider where id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "locale", column = "locale")
})
@Options(useCache = true)
DataProvider find(int id);
@Select("select id, locale from oskari_dataprovider order by id")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "locale", column = "locale")
})
List<DataProvider> findAll();
@Update("update oskari_dataprovider set locale = #{locale} where id = #{id}")
void update(@Param("locale") JSONObject locale, @Param("id") int id);
@Delete("delete from oskari_dataprovider where id = #{id}")
void delete(int id);
@Insert("insert into oskari_dataprovider (locale) values (#{locale})")
@Options(useGeneratedKeys=true, keyColumn = "id", keyProperty = "id")
void insert(final DataProvider dataProvider);
}
|
package fi.nls.oskari.map.layer;
import fi.nls.oskari.domain.map.DataProvider;
import org.apache.ibatis.annotations.*;
import org.json.JSONObject;
import java.util.List;
public interface DataProviderMapper {
@Select("select id, locale from oskari_dataprovider where id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "locale", column = "locale")
})
@Options(useCache = true)
DataProvider find(int id);
@Select("select id, locale from oskari_dataprovider order by id")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "locale", column = "locale")
})
List<DataProvider> findAll();
@Update("update oskari_dataprovider set locale = #{locale} where id = #{id}")
void update(JSONObject locale, int id);
@Delete("delete from oskari_dataprovider where id = #{id}")
void delete(int id);
@Insert("insert into oskari_dataprovider (locale) values (#{locale})")
@Options(useGeneratedKeys=true, keyColumn = "id", keyProperty = "id")
void insert(final DataProvider dataProvider);
}
|
fix: Correct type of last_commit id
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
module.exports = {
name: 'MergeRequest',
schema: new Schema({
merge_request: {
id: Number,
url: String,
target_branch: String,
source_branch: String,
created_at: String,
updated_at: String,
title: String,
description: String,
status: String,
work_in_progress: Boolean
},
last_commit: {
id: String,
message: String,
timestamp: String,
url: String,
author: {
name: String,
email: String
}
},
project: {
name: String,
namespace: String
},
author: {
name: String,
username: String
},
assignee: {
claimed_on_slack: Boolean,
name: String,
username: String
}
})
}
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
module.exports = {
name: 'MergeRequest',
schema: new Schema({
merge_request: {
id: Number,
url: String,
target_branch: String,
source_branch: String,
created_at: String,
updated_at: String,
title: String,
description: String,
status: String,
work_in_progress: Boolean
},
last_commit: {
id: Number,
message: String,
timestamp: String,
url: String,
author: {
name: String,
email: String
}
},
project: {
name: String,
namespace: String
},
author: {
name: String,
username: String
},
assignee: {
claimed_on_slack: Boolean,
name: String,
username: String
}
})
}
|
Use loader options if available
|
var ejs = require('ejs'),
UglifyJS = require('uglify-js'),
utils = require('loader-utils'),
path = require('path'),
htmlmin = require('html-minifier'),
merge = require('merge');
module.exports = function (source) {
this.cacheable && this.cacheable();
var query = typeof this.query === 'object' ? this.query : utils.parseQuery(this.query);
var opts = merge(this.options['ejs-compiled-loader'] || {}, query);
opts.client = true;
// Skip compile debug for production when running with
// webpack --optimize-minimize
if (this.minimize && opts.compileDebug === undefined) {
opts.compileDebug = false;
}
// Use filenames relative to working dir, which should be project root
opts.filename = path.relative(process.cwd(), this.resourcePath);
if (opts.htmlmin) {
source = htmlmin.minify(source, opts['htmlminOptions'] || {});
}
var template = ejs.compile(source, opts);
// Beautify javascript code
if (!this.minimize && opts.beautify !== false) {
var ast = UglifyJS.parse(template.toString());
ast.figure_out_scope();
template = ast.print_to_string({beautify: true});
}
return 'module.exports = ' + template;
};
|
var ejs = require('ejs'),
UglifyJS = require('uglify-js'),
utils = require('loader-utils'),
path = require('path'),
htmlmin = require('html-minifier'),
merge = require('merge');
module.exports = function (source) {
this.cacheable && this.cacheable();
var opts = merge(this.options['ejs-compiled-loader'] || {}, utils.parseQuery(this.query));
opts.client = true;
// Skip compile debug for production when running with
// webpack --optimize-minimize
if (this.minimize && opts.compileDebug === undefined) {
opts.compileDebug = false;
}
// Use filenames relative to working dir, which should be project root
opts.filename = path.relative(process.cwd(), this.resourcePath);
if (opts.htmlmin) {
source = htmlmin.minify(source, opts['htmlminOptions'] || {});
}
var template = ejs.compile(source, opts);
// Beautify javascript code
if (!this.minimize && opts.beautify !== false) {
var ast = UglifyJS.parse(template.toString());
ast.figure_out_scope();
template = ast.print_to_string({beautify: true});
}
return 'module.exports = ' + template;
};
|
Remove absolute paths which were unnecessary and broke dist builds
|
var path = require('path');
var webpack = require('webpack');
var webpackSettings = require('./webpack-helper');
module.exports = webpackSettings({
entry: {
'backbone': './adaptors/backbone',
'ampersand': './adaptors/ampersand',
'core': './tungsten',
'template': ['./precompile/tungsten_template/template_helper.js']
},
output: {
filename: './dist/tungsten.[name].js',
libraryTarget: 'umd',
library: ['tungsten', '[name]']
},
resolve: {
alias: {
jquery: 'backbone.native'
}
},
externals: [
{underscore: 'var window._'},
{lodash: 'var window._'}
],
resolveLoader: {
modulesDirectories: ['node_modules']
},
module: {
loaders: []
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('./dist/tungsten.core.js')
]
});
|
var path = require('path');
var webpack = require('webpack');
var webpackSettings = require('./webpack-helper');
module.exports = webpackSettings({
entry: {
'backbone': path.join(__dirname, './adaptors/backbone'),
'ampersand': path.join(__dirname, './adaptors/ampersand'),
'core': path.join(__dirname, './tungsten'),
'template': [path.join(__dirname, './src/template/template.js')]
},
output: {
filename: path.join(__dirname, './dist/tungsten.[name].js'),
libraryTarget: 'var',
library: ['tungsten', '[name]']
},
resolve: {
alias: {
jquery: 'backbone.native'
}
},
externals: [
{underscore: 'var window._'},
{lodash: 'var window._'}
],
resolveLoader: {
modulesDirectories: [path.join(__dirname, 'node_modules')]
},
devtool: '#eval-source-map',
module: {
loaders: []
},
plugins: [
new webpack.optimize.CommonsChunkPlugin(path.join(__dirname, './dist/tungsten.core.js'))
]
});
|
Move from `expandFiles` to grunt 0.4's `expand`
This largely fixes 0.4 compatibility for me
|
module.exports = function(grunt) {"use strict";
var Builder = require('../').Builder;
grunt.registerMultiTask("spritesheet", "Compile images to sprite sheet", function() {
var helpers = require('grunt-lib-contrib').init(grunt);
var options = helpers.options(this);
var done = this.async()
grunt.verbose.writeflags(options, "Options");
// TODO: ditch this when grunt v0.4 is released
this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);
var srcFiles;
var images;
grunt.util.async.forEachSeries(this.files, function(file, callback) {
var builder;
var dir = '';
//grunt.task.expand( './..' );
srcFiles = grunt.file.expand(file.src);
for(var i = 0; i < srcFiles.length; i++) {
srcFiles[i] = dir + srcFiles[i];
}
options.images = srcFiles;
options.outputDirectory = dir + file.dest;
builder = Builder.fromGruntTask(options);
builder.build(callback);
}, done);
});
};
|
module.exports = function(grunt) {"use strict";
var Builder = require('../').Builder;
grunt.registerMultiTask("spritesheet", "Compile images to sprite sheet", function() {
var helpers = require('grunt-lib-contrib').init(grunt);
var options = helpers.options(this);
var done = this.async()
grunt.verbose.writeflags(options, "Options");
// TODO: ditch this when grunt v0.4 is released
this.files = this.files || helpers.normalizeMultiTaskFiles(this.data, this.target);
var srcFiles;
var images;
grunt.util.async.forEachSeries(this.files, function(file, callback) {
var builder;
var dir = '';
//grunt.task.expand( './..' );
srcFiles = grunt.file.expandFiles(file.src);
for(var i = 0; i < srcFiles.length; i++) {
srcFiles[i] = dir + srcFiles[i];
}
options.images = srcFiles;
options.outputDirectory = dir + file.dest;
builder = Builder.fromGruntTask(options);
builder.build(callback);
}, done);
});
};
|
Fix bug that prevents default admin user from seeing companies list
|
/**
* BusinessUnit publications
*/
Core.publish("BusinessUnits", function () {
let user = this.userId;
let found = Meteor.users.findOne({_id: user});
if(found.businessIds && found.businessIds.length > 0){
console.log(`usesr businessIds is NOT null`)
return BusinessUnits.find({_id: {$in: found.businessIds}});
} else {
console.log(`usesr businessIds is null`)
if (Core.hasPayrollAccess(user) || Core.hasEmployeeAccess(user)) {
return BusinessUnits.find();
} else {
return this.ready();
}
}
});
/**
* Business units
*/
Core.publish("BusinessUnit", function (id) {
//if (Core.hasPayrollAccess(this.userId) || Core.hasEmployeeAccess(this.userId)) {
return BusinessUnits.find({_id: id})//return BusinessUnits.find();
//} else {
// // user not authorized. do not publish business units
// return this.ready();
//}
});
Core.publish("BusinessUnitLogoImage", function (id) {
return BusinessUnitLogoImages.find({_id: id})
});
|
/**
* BusinessUnit publications
*/
Core.publish("BusinessUnits", function () {
let user = this.userId;
// if (Core.hasPayrollAccess(user) || Core.hasEmployeeAccess(user)) {
// return BusinessUnits.find();
// } else {
let found = Meteor.users.findOne({_id: user});
// user not authorized. do not publish business units
if(found.businessIds){
return BusinessUnits.find({_id: {$in: found.businessIds}});
} else{
return this.ready();
}
// }
});
/**
* Business units
*/
Core.publish("BusinessUnit", function (id) {
//if (Core.hasPayrollAccess(this.userId) || Core.hasEmployeeAccess(this.userId)) {
return BusinessUnits.find({_id: id})//return BusinessUnits.find();
//} else {
// // user not authorized. do not publish business units
// return this.ready();
//}
});
Core.publish("BusinessUnitLogoImage", function (id) {
return BusinessUnitLogoImages.find({_id: id})
});
|
Make sure to change the toaster when new error appears
|
import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux'
import { Intent, Position, Toaster } from "@blueprintjs/core";
class App extends Component {
componentWillMount() {
this.toaster = Toaster.create({
className: "my-toaster",
position: Position.TOP_CENTER
});
}
componentWillReceiveProps(nextProps) {
if (nextProps.error.get('message')) {
this.toaster.clear();
this.toaster.show({
message: nextProps.error.get('message'),
intent: Intent.DANGER
});
}
}
render() {
return (
<div className="App">
{this.props.children}
</div>
);
}
}
const mapStateToProps = state => ({
error: state.get('error')
});
export default connect(mapStateToProps)(App);
|
import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux'
import { Intent, Position, Toaster } from "@blueprintjs/core";
class App extends Component {
componentWillMount() {
this.toaster = Toaster.create({
className: "my-toaster",
position: Position.TOP_CENTER
});
}
componentWillReceiveProps(nextProps) {
if (this.props.error.get('message') !== nextProps.error.get('message')) {
this.toaster.show({
message: nextProps.error.get('message'),
intent: Intent.DANGER
});
}
}
render() {
return (
<div className="App">
{this.props.children}
</div>
);
}
}
const mapStateToProps = state => ({
error: state.get('error')
});
export default connect(mapStateToProps)(App);
|
Fix catalog app icon issue
https://github.com/rancher/rancher/issues/23291
|
import Mixin from '@ember/object/mixin';
import { set, get } from '@ember/object';
import $ from 'jquery';
export default Mixin.create({
srcSet: false,
genericIconPath: null,
init() {
this._super(...arguments);
set(this, 'genericIconPath', `${ get(this, 'app.baseAssets') }assets/images/generic-catalog.svg`);
},
initAppIcon() {
if (!get(this, 'srcSet')) {
set(this, 'srcSet', true);
const $icon = $(this.element).find('.catalog-icon > img');
const $srcPath = $icon.attr('src');
if ($srcPath === this.genericIconPath) {
$icon.attr('src', $icon.data('src'));
const img = $(this.element).find('img');
img.on('error', () => {
if ( this.isDestroyed || this.isDestroying ) {
if ( img ) {
img.off('error');
}
return;
}
$icon.attr('src', this.genericIconPath);
});
}
}
},
});
|
import Mixin from '@ember/object/mixin';
import { set, get } from '@ember/object';
import $ from 'jquery';
export default Mixin.create({
srcSet: false,
genericIconPath: null,
init() {
this._super(...arguments);
set(this, 'genericIconPath', `${ get(this, 'app.baseAssets') }assets/images/generic-catalog.svg`);
},
initAppIcon() {
if (!get(this, 'srcSet')) {
set(this, 'srcSet', true);
var $icon = $('.catalog-icon > img');
const $srcPath = $icon.attr('src');
if ($srcPath === this.genericIconPath) {
$icon.attr('src', $icon.data('src'));
$('img').on('error', () => {
if ( this.isDestroyed || this.isDestroying ) {
if ($('img')) {
$('img').off('error');
}
return;
}
$icon.attr('src', this.genericIconPath);
});
}
}
},
});
|
Remove showing cursor at end of prompt. cli-cursor handles it
|
'use strict';
var _ = require('lodash');
var readlineFacade = require('readline2');
/**
* Base interface class other can inherits from
*/
var UI = module.exports = function (opt) {
// Instantiate the Readline interface
// @Note: Don't reassign if already present (allow test to override the Stream)
if (!this.rl) {
this.rl = readlineFacade.createInterface(opt);
}
this.rl.resume();
this.onForceClose = this.onForceClose.bind(this);
// Make sure new prompt start on a newline when closing
this.rl.on('SIGINT', this.onForceClose);
process.on('exit', this.onForceClose);
};
/**
* Handle the ^C exit
* @return {null}
*/
UI.prototype.onForceClose = function () {
this.close();
console.log('\n'); // Line return
};
/**
* Close the interface and cleanup listeners
*/
UI.prototype.close = function () {
// Remove events listeners
this.rl.removeListener('SIGINT', this.onForceClose);
process.removeListener('exit', this.onForceClose);
// Restore prompt functionnalities
this.rl.output.unmute();
// Close the readline
this.rl.output.end();
this.rl.pause();
this.rl.close();
this.rl = null;
};
|
'use strict';
var _ = require('lodash');
var readlineFacade = require('readline2');
/**
* Base interface class other can inherits from
*/
var UI = module.exports = function (opt) {
// Instantiate the Readline interface
// @Note: Don't reassign if already present (allow test to override the Stream)
if (!this.rl) {
this.rl = readlineFacade.createInterface(opt);
}
this.rl.resume();
this.onForceClose = this.onForceClose.bind(this);
// Make sure new prompt start on a newline when closing
this.rl.on('SIGINT', this.onForceClose);
process.on('exit', this.onForceClose);
};
/**
* Handle the ^C exit
* @return {null}
*/
UI.prototype.onForceClose = function () {
this.close();
console.log('\n'); // Line return
};
/**
* Close the interface and cleanup listeners
*/
UI.prototype.close = function () {
// Remove events listeners
this.rl.removeListener('SIGINT', this.onForceClose);
process.removeListener('exit', this.onForceClose);
// Restore prompt functionnalities
this.rl.output.unmute();
this.rl.output.write('\x1B[?25h'); // show cursor
// Close the readline
this.rl.output.end();
this.rl.pause();
this.rl.close();
this.rl = null;
};
|
Remove unused lines of code.
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import Navbar from './components/Navbar.js';
import Header from './components/Header.js';
import Home from './components/Home.js';
import Instruction from './components/Instruction.js';
import AboutUs from './components/AboutUs.js';
import ContactForm from './components/ContactForm.js';
import ColorBlindnessView from './components/ColorBlindnessView.js';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
const root = document.getElementById('root');
ReactDOM.render(
<Router>
<div>
<Navbar></Navbar>
<hr/>
<Header></Header>
<Route exact path="/" component={Home}/>
{/*<Route exact path="/" component={OtherComponent}/>*/}
<Route path="/instructions" component={Instruction}/>
<Route path="/quiz" component={App}/>
<Route path="/about-us" component={AboutUs}/>
<Route path="/contact-us" component={ContactForm}/>
<Route path="/color-view" component={ColorBlindnessView}/>
</div>
</Router>,
root);
registerServiceWorker();
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import Navbar from './components/Navbar.js';
import Header from './components/Header.js';
import Home from './components/Home.js';
import Instruction from './components/Instruction.js';
import AboutUs from './components/AboutUs.js';
import ContactForm from './components/ContactForm.js';
import ColorBlindnessView from './components/ColorBlindnessView.js';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
const OtherComponent = () => (
<div>Other component is rendered as well</div>
)
const root = document.getElementById('root');
ReactDOM.render(
<Router>
<div>
<Navbar></Navbar>
<hr/>
<Header></Header>
<Route exact path="/" component={Home}/>
{/*<Route exact path="/" component={OtherComponent}/>*/}
<Route path="/instructions" component={Instruction}/>
<Route path="/quiz" component={App}/>
<Route path="/about-us" component={AboutUs}/>
<Route path="/contact-us" component={ContactForm}/>
<Route path="/color-view" component={ColorBlindnessView}/>
</div>
</Router>,
root);
registerServiceWorker();
|
Throw a more specific exception if an attempt is made to create a recurrence type that is not in the factory.
|
<?php
namespace Plummer\Calendarful\Recurrence;
class RecurrenceFactory implements RecurrenceFactoryInterface
{
protected $recurrenceTypes = [];
public function addRecurrenceType($type, $recurrenceType)
{
if(is_string($recurrenceType) and !class_exists($recurrenceType)) {
throw new \InvalidArgumentException("Class {$recurrenceType} des not exist.");
}
else if(!in_array('Plummer\Calendarful\Recurrence\RecurrenceInterface', class_implements($recurrenceType))) {
throw new \InvalidArgumentException('File or File path required.');
}
$this->recurrenceTypes[$type] = is_string($recurrenceType) ?
$recurrenceType :
get_class($recurrenceType);
}
public function getRecurrenceTypes()
{
return $this->recurrenceTypes;
}
public function createRecurrenceType($type)
{
if(!isset($this->recurrenceTypes[$type])) {
throw new \OutOfBoundsException("A recurrence type called {$type} does not exist within the factory.");
}
return $this->recurrenceTypes[$type];
}
}
|
<?php
namespace Plummer\Calendarful\Recurrence;
class RecurrenceFactory implements RecurrenceFactoryInterface
{
protected $recurrenceTypes = [];
public function addRecurrenceType($type, $recurrenceType)
{
if(is_string($recurrenceType) and !class_exists($recurrenceType)) {
throw new \InvalidArgumentException("Class {$recurrenceType} des not exist.");
}
else if(!in_array('Plummer\Calendarful\Recurrence\RecurrenceInterface', class_implements($recurrenceType))) {
throw new \InvalidArgumentException('File or File path required.');
}
$this->recurrenceTypes[$type] = is_string($recurrenceType) ?
$recurrenceType :
get_class($recurrenceType);
}
public function getRecurrenceTypes()
{
return $this->recurrenceTypes;
}
public function createRecurrenceType($type)
{
if(!isset($this->recurrenceTypes[$type])) {
throw new \Exception('The type passed does not exist.');
}
return $this->recurrenceTypes[$type];
}
}
|
Update ConfigurableItems demo to not refresh page onSave
|
import ConfigurableItemsPattern from './';
import ConfigurableItemsActions from './actions';
import Definition from './../../../demo/utils/definition';
let definition = new Definition('configurable-items-pattern', ConfigurableItemsPattern, {
dataVariable: 'configurableItemsData',
description: `A dialog that allows a list of items to be checked/unchecked and re-ordered.`,
designerNotes: `
* Combines the ConfigurableItems and ConfigurableItemRow components.
`,
hiddenProps: ['itemsData'],
propValues: {
itemsData: `configurableItemsData`,
onSave: `configurableItemsOnSave`,
title: 'Configure Items'
},
propTypes: {
className: 'String',
itemsData: 'Object',
onCancel: 'Function',
onSave: 'Function',
title: 'String'
},
propDescriptions: {
itemsData: 'Data to define the items that can be configured',
className : 'Classes to apply to the component.',
onCancel: 'Callback triggered when the form is cancelled.',
onSave: 'Callback triggered when the form is saved.',
title: 'Title to display as heading'
},
relatedComponentsNotes: `
* [ConfigurableItems component](/components/configurable-items).
* [ConfigurableItemRow component](/components/configurable-items/configurable-item-row).
`,
requiredProps: ['onSave', 'title'],
});
definition.openPreview = true;
definition.onOpenPreview = function onOpenPreview() {
ConfigurableItemsActions.toggleDialogOpen()
};
global.configurableItemsOnSave = (event) => {
event.preventDefault();
ConfigurableItemsActions.toggleDialogOpen()
}
export default definition;
|
import ConfigurableItemsPattern from './';
import ConfigurableItemsActions from './actions';
import Definition from './../../../demo/utils/definition';
let definition = new Definition('configurable-items-pattern', ConfigurableItemsPattern, {
dataVariable: 'configurableItemsData',
description: `A dialog that allows a list of items to be checked/unchecked and re-ordered.`,
designerNotes: `
* Combines the ConfigurableItems and ConfigurableItemRow components.
`,
hiddenProps: ['itemsData'],
propValues: {
itemsData: `configurableItemsData`,
onSave: `() => {}`,
title: 'Configure Items'
},
propTypes: {
className: 'String',
itemsData: 'Object',
onCancel: 'Function',
onSave: 'Function',
title: 'String'
},
propDescriptions: {
itemsData: 'Data to define the items that can be configured',
className : 'Classes to apply to the component.',
onCancel: 'Callback triggered when the form is cancelled.',
onSave: 'Callback triggered when the form is saved.',
title: 'Title to display as heading'
},
relatedComponentsNotes: `
* [ConfigurableItems component](/components/configurable-items).
* [ConfigurableItemRow component](/components/configurable-items/configurable-item-row).
`,
requiredProps: ['onSave', 'title'],
});
definition.openPreview = true;
definition.onOpenPreview = function onOpenPreview() {
ConfigurableItemsActions.toggleDialogOpen()
};
export default definition;
|
Use same variable names as testing environment
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from keys import url, key
import argparse
import tools
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create a given number of event containing a given number of attributes eachh.')
parser.add_argument("-l", "--limit", type=int, help="Number of events to create (default 1)")
parser.add_argument("-a", "--attribute", type=int, help="Number of attributes per event (default 3000)")
args = parser.parse_args()
misp = PyMISP(url, key, True, 'json')
if args.limit is None:
args.limit = 1
if args.attribute is None:
args.attribute = 3000
for i in range(args.limit):
tools.create_massive_dummy_events(misp, args.attribute)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from keys import misp_url, misp_key, misp_verifycert
import argparse
import tools
def init(url, key):
return PyMISP(url, key, misp_verifycert, 'json')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create a given number of event containing a given number of attributes eachh.')
parser.add_argument("-l", "--limit", type=int, help="Number of events to create (default 1)")
parser.add_argument("-a", "--attribute", type=int, help="Number of attributes per event (default 3000)")
args = parser.parse_args()
misp = init(misp_url, misp_key)
if args.limit is None:
args.limit = 1
if args.attribute is None:
args.attribute = 3000
for i in range(args.limit):
tools.create_massive_dummy_events(misp, args.attribute)
|
Make sure that we normalize paths.
|
const path = require('path');
const mime = require('mime');
function serveBuild(registry) {
return async function(req, res, next) {
const username = req.user && req.user.username;
const branchId = await registry.models.user.getBranch(username);
const {bucketId, overlays} = await registry.models.branch.getLatestBuild(branchId);
const filePath = req.path.replace(/^\//, '');
const filePathSegments = filePath.split('/').reduce((valid, seg) => {
return seg.length > 0 ? valid.concat(seg) : valid;
}, []);
let relevantBucketId = bucketId;
let relevantFilePath = filePathSegments.join('/');
if (filePathSegments.length && overlays[filePathSegments[0]]) {
relevantBucketId = overlays[filePathSegments[0]];
relevantFilePath = filePathSegments.slice(1).join('/');
}
const file = await registry.models.bucket.get(relevantBucketId, relevantFilePath);
if (file === null) {
next();
return;
}
res.set('ETag', file.digest);
res.set('Content-Type', mime.lookup(filePath));
res.send(file.buffer);
}
}
module.exports = serveBuild;
|
const path = require('path');
const mime = require('mime');
function serveBuild(registry) {
return async function(req, res, next) {
const username = req.user && req.user.username;
const branchId = await registry.models.user.getBranch(username);
const {bucketId, overlays} = await registry.models.branch.getLatestBuild(branchId);
const filePath = req.path.replace(/^\//, '');
const filePathSegments = filePath.split('/');
let relevantBucketId = bucketId;
let relevantFilePath = filePath;
if (filePathSegments.length && overlays[filePathSegments[0]]) {
relevantBucketId = overlays[filePathSegments[0]];
relevantFilePath = filePathSegments.slice(1).join('/');
}
const file = await registry.models.bucket.get(relevantBucketId, relevantFilePath);
if (file === null) {
next();
return;
}
res.set('ETag', file.digest);
res.set('Content-Type', mime.lookup(filePath));
res.send(file.buffer);
}
}
module.exports = serveBuild;
|
Add some (inefective) score maximizing attempts
|
import time
from stock_awesome.obj import market
def main():
"""
Algorithm: Wait for an ask, then send a fill or kill for the quantity of the ask at the ask
price.
"""
m = market.StockAPI('RAJ40214463', 'SSMCEX', 'IPSO')
#collection of orders placed
orders = {}
filled = 0
upper_limit = 2450
#try to buy 100000
to_buy = 100000
while to_buy > 0:
quote = m.quote()
ask = quote.get('ask', 0)
bid = quote.get('bid')
if ask < upper_limit:
r = m.buy(quote['askSize'], ask, order_type='fill-or-kill')
to_buy -= r['totalFilled']
print("Bought {}, {} remaining".format(r['totalFilled'], to_buy))
else:
time.sleep(1)
print('done')
def update_orders(m, orders):
"""
update order status
"""
return {o: m.order_status(o) for o in orders}
def update_filled(orders):
"""
Remove filled orders and update our count.
"""
closed = [o for o in orders if not orders[o]['open']]
#remove and sum filled orders
filled = sum(orders.pop(o)['totalFilled'] for o in closed)
return filled
if __name__ == '__main__':
main()
|
import time
from stock_awesome.obj import market
def main():
"""
Algorithm: Wait for an ask, then send a fill or kill for the quantity of the ask at the ask
price.
"""
m = market.StockAPI('WEB29978261', 'NOWUEX', 'BBCM')
#collection of orders placed
orders = {}
filled = 0
upper_limit = 3300
#try to buy 100000
to_send = 1000
while to_send > 0:
quote = m.quote()
ask = quote.get('ask')
if ask and ask < upper_limit:
r = m.buy(quote['askSize'], quote['ask'], order_type='fill-or-kill')
to_send -= 1
orders[r['id']] = r
orders = update_orders(m, orders)
filled += update_filled(orders)
else:
time.sleep(1)
def update_orders(m, orders):
"""
update order status
"""
return {o: m.order_status(o) for o in orders}
def update_filled(orders):
"""
Remove filled orders and update our count.
"""
closed = [o for o in orders if not orders[o]['open']]
#remove and sum filled orders
filled = sum(orders.pop(o)['totalFilled'] for o in closed)
return filled
if __name__ == '__main__':
main()
|
Make trailing slash optional for API URLs.
Admin website URLs will still redirect to canonical version with trailing slash.
|
"""hub URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from .sensorhub import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/temperatures/?$', views.api.TemperatureApiView.as_view()),
url(r'^api/status/?$', views.api.StatusApiView.as_view()),
]
|
"""hub URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from .sensorhub import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/temperatures/$', views.api.TemperatureApiView.as_view()),
url(r'^api/status/$', views.api.StatusApiView.as_view()),
]
|
Fix unicode import in test
|
'''Test sentence boundaries are deserialized correctly,
even for non-projective sentences.'''
from __future__ import unicode_literals
import pytest
import numpy
from ... tokens import Doc
from ... vocab import Vocab
from ... attrs import HEAD, DEP
def test_issue1799():
problem_sentence = 'Just what I was looking for.'
heads_deps = numpy.asarray([[1, 397], [4, 436], [2, 426], [1, 402],
[0, 8206900633647566924], [18446744073709551615, 440],
[18446744073709551614, 442]], dtype='uint64')
doc = Doc(Vocab(), words='Just what I was looking for .'.split())
doc.vocab.strings.add('ROOT')
doc = doc.from_array([HEAD, DEP], heads_deps)
assert len(list(doc.sents)) == 1
|
'''Test sentence boundaries are deserialized correctly,
even for non-projective sentences.'''
import pytest
import numpy
from ... tokens import Doc
from ... vocab import Vocab
from ... attrs import HEAD, DEP
def test_issue1799():
problem_sentence = 'Just what I was looking for.'
heads_deps = numpy.asarray([[1, 397], [4, 436], [2, 426], [1, 402],
[0, 8206900633647566924], [18446744073709551615, 440],
[18446744073709551614, 442]], dtype='uint64')
doc = Doc(Vocab(), words='Just what I was looking for .'.split())
doc.vocab.strings.add('ROOT')
doc = doc.from_array([HEAD, DEP], heads_deps)
assert len(list(doc.sents)) == 1
|
Move version numbers back to the package init file
|
__author__ = 'matt'
__version__ = '1.24.02'
target_schema_version = '1.24.00'
from flask import Flask
app = Flask(__name__)
def startup():
import blockbuster.bb_dbconnector_factory
import blockbuster.bb_logging as log
import blockbuster.bb_auditlogger as audit
try:
if blockbuster.bb_dbconnector_factory.DBConnectorInterfaceFactory().create().db_version_check():
import blockbuster.bb_routes
print("Running...")
else:
raise RuntimeError("Incorrect database schema version.")
except RuntimeError, e:
log.logger.exception("Incorrect database schema version.")
audit.BBAuditLoggerFactory().create().logException('app', 'STARTUP', 'Incorrect database schema version.')
startup()
|
__author__ = 'matt'
from flask import Flask
app = Flask(__name__)
def startup():
import blockbuster.bb_dbconnector_factory
import blockbuster.bb_logging as log
import blockbuster.bb_auditlogger as audit
try:
if blockbuster.bb_dbconnector_factory.DBConnectorInterfaceFactory().create().db_version_check():
import blockbuster.bb_routes
print("Running...")
else:
raise RuntimeError("Incorrect database schema version.")
except RuntimeError, e:
log.logger.exception("Incorrect database schema version.")
audit.BBAuditLoggerFactory().create().logException('app', 'STARTUP', 'Incorrect database schema version.')
startup()
|
build: Add missing flow definitions for mocha
|
// flow-typed signature: 6b82cf8c1da27b4f0fa7a58e5ed5babf
// flow-typed version: edf70dde46/mocha_v3.1.x/flow_>=v0.22.x
type TestFunction = ((done: () => void) => void | Promise<mixed>);
declare var describe : {
(name:string, spec:() => void): void;
only(description:string, spec:() => void): void;
skip(description:string, spec:() => void): void;
timeout(ms:number): void;
};
declare var context : typeof describe;
declare var it : {
(name:string, spec?:TestFunction): void;
only(description:string, spec:TestFunction): void;
skip(description:string, spec:TestFunction): void;
timeout(ms:number): void;
};
declare function before(method : TestFunction):void;
declare function beforeEach(method : TestFunction):void;
declare function after(method : TestFunction):void;
declare function afterEach(method : TestFunction):void;
/****************************************************************************/
/* TODO: Contribute missing definitions upstream */
/****************************************************************************/
declare function before(desc: string, method: TestFunction):void;
declare function beforeEach(desc: string, method: TestFunction):void;
declare function after(desc: string, method: TestFunction):void;
declare function afterEach(desc: string, method: TestFunction):void;
declare var xdescribe : typeof describe;
declare var xcontext : typeof context;
declare var xit : typeof it;
|
// flow-typed signature: 6b82cf8c1da27b4f0fa7a58e5ed5babf
// flow-typed version: edf70dde46/mocha_v3.1.x/flow_>=v0.22.x
type TestFunction = ((done: () => void) => void | Promise<mixed>);
declare var describe : {
(name:string, spec:() => void): void;
only(description:string, spec:() => void): void;
skip(description:string, spec:() => void): void;
timeout(ms:number): void;
};
declare var context : typeof describe;
declare var it : {
(name:string, spec?:TestFunction): void;
only(description:string, spec:TestFunction): void;
skip(description:string, spec:TestFunction): void;
timeout(ms:number): void;
};
declare function before(method : TestFunction):void;
declare function beforeEach(method : TestFunction):void;
declare function after(method : TestFunction):void;
declare function afterEach(method : TestFunction):void;
|
Add endpoint for updating own presence
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vincent Zhang/PhoenixLAB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.phoenixlab.discord.api.endpoints;
import co.phoenixlab.discord.api.entities.Presence;
import co.phoenixlab.discord.api.entities.SelfUser;
import co.phoenixlab.discord.api.request.EditProfileRequest;
import java.awt.image.BufferedImage;
public interface UsersEndpoint {
BufferedImage getAvatar(long userId, String avatar)
throws ApiException;
SelfUser editProfile(EditProfileRequest request)
throws ApiException;
void updatePresence(Presence request)
throws ApiException;
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Vincent Zhang/PhoenixLAB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.phoenixlab.discord.api.endpoints;
import co.phoenixlab.discord.api.entities.SelfUser;
import co.phoenixlab.discord.api.request.EditProfileRequest;
import java.awt.image.BufferedImage;
public interface UsersEndpoint {
BufferedImage getAvatar(long userId, String avatar)
throws ApiException;
SelfUser editProfile(EditProfileRequest request)
throws ApiException;
}
|
Refactor stub into real query
|
var db = require( '../config/db' );
var helpers = require( '../config/helpers' );
var Sequelize = require( 'sequelize' );
var User = require( '../users/users' );
var Session = require( '../sessions/sessions' );
var Session_User = db.define( 'sessions_users', {
user_id: {
type: Sequelize.INTEGER,
unique: 'session_user_idx'
},
session_id: {
type: Sequelize.INTEGER,
unique: 'session_user_idx'
}
} );
Session_User.sync().then( function(){
console.log("sessions_users table created");
} )
.catch( function( err ){
console.error(err);
} );
Session_User.belongsTo( User, {foreignKey: 'user_id'} );
Session_User.belongsTo( Session, {foreignKey: 'session_id'} );
Session_User.getSessionUserBySessionIdAndUserId = function( sessionID, userID ) {
return Session_User.findOne({where: {session_id: sessionID, user_id: userID} })
.catch( function( err ) {
helpers.errorLogger( err );
});
};
Session_User.countUsersInOneSession = function( sessionID ) {
return Session_User.count( { where: { id: sessionId } } )
.catch( function( err ) {
helpers.errorLogger( err );
});
};
module.exports = Session_User;
|
var db = require( '../config/db' );
var helpers = require( '../config/helpers' );
var Sequelize = require( 'sequelize' );
var User = require( '../users/users' );
var Session = require( '../sessions/sessions' );
var Session_User = db.define( 'sessions_users', {
user_id: {
type: Sequelize.INTEGER,
unique: 'session_user_idx'
},
session_id: {
type: Sequelize.INTEGER,
unique: 'session_user_idx'
}
} );
Session_User.sync().then( function(){
console.log("sessions_users table created");
} )
.catch( function( err ){
console.error(err);
} );
Session_User.belongsTo( User, {foreignKey: 'user_id'} );
Session_User.belongsTo( Session, {foreignKey: 'session_id'} );
Session_User.getSessionUserBySessionIdAndUserId = function( sessionID, userID ) {
return Session_User.findOne({where: {session_id: sessionID, user_id: userID} })
.catch( function( err ) {
helpers.errorLogger( err );
});
};
Session_User.countUsersInOneSession = function( sessionID ) {
/* STUB FOR TESTING, REMOVE WHEN THIS FUNCTION IS IMPLEMENTED */
return {
then: function( resolve ) {
if( sessionID == 1 ) {
resolve( 2 );
} else {
resolve( 0 );
}
}
}
/* END STUB */
};
module.exports = Session_User;
|
Enable debug level for log file
|
#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
#
# Configure logging
#
import logging
logging.basicConfig(filename="log.txt", level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
# Define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter('>>> %(message)s', '%H:%M:%S'))
logging.getLogger('').addHandler(console)
#
# Import core classes
#
from jasy.Session import *
from jasy.Project import *
from jasy.Resolver import *
from jasy.Sorter import *
from jasy.Combiner import *
from jasy.Assets import *
from jasy.Optimization import *
from jasy.Format import *
from jasy.File import *
from jasy.Task import *
|
#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
#
# Configure logging
#
import logging
logging.basicConfig(filename="log.txt", level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
# Define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter('>>> %(message)s', '%H:%M:%S'))
logging.getLogger('').addHandler(console)
#
# Import core classes
#
from jasy.Session import *
from jasy.Project import *
from jasy.Resolver import *
from jasy.Sorter import *
from jasy.Combiner import *
from jasy.Assets import *
from jasy.Optimization import *
from jasy.Format import *
from jasy.File import *
from jasy.Task import *
|
Fix mobile footer toolbar import rename
|
// @flow
import React from 'react'
import 'normalize.css/normalize.css'
import Footer from 'components/Footer/Footer'
import Nav from '../Nav/Nav'
import MobileFooterToolbar from '../Nav/MobileFooterNav/MobileFooterNav'
import styles from './App.scss'
import '../../styles/global.scss'
import Content from 'react-mdc-web/lib/Content/Content'
const title = 'Reango'
type AppPropsType = {
viewer: Object,
children: Object
}
let App = (props: AppPropsType) =>
<div className={styles.root} >
<Nav
title={title}
viewer={props.viewer}
/>
<Content className={`${styles.wrap}`} >
<div className={styles.content} >
{props.children}
</div>
</Content>
{props.viewer.isAuthenticated ?
<div className={styles.mobile_footer_wrap} >
<MobileFooterToolbar />
</div> : null}
<div className={`${styles.footer_wrap} ${!props.viewer.isAuthenticated ? styles.hidden_mobile_footer_wrap: null}`} >
<div className={styles.footer} >
<Footer
title={title}
/>
</div>
</div>
</div>
export default App
|
// @flow
import React from 'react'
import 'normalize.css/normalize.css'
import Footer from 'components/Footer/Footer'
import Nav from '../Nav/Nav'
import MobileFooterToolbar from '../Nav/MobileFooterToolbar/MobileFooterToolbar'
import styles from './App.scss'
import '../../styles/global.scss'
import Content from 'react-mdc-web/lib/Content/Content'
const title = 'Reango'
type AppPropsType = {
viewer: Object,
children: Object
}
let App = (props: AppPropsType) =>
<div className={styles.root} >
<Nav
title={title}
viewer={props.viewer}
/>
<Content className={`${styles.wrap}`} >
<div className={styles.content} >
{props.children}
</div>
</Content>
{props.viewer.isAuthenticated ?
<div className={styles.mobile_footer_wrap} >
<MobileFooterToolbar />
</div> : null}
<div className={`${styles.footer_wrap} ${!props.viewer.isAuthenticated ? styles.hidden_mobile_footer_wrap: null}`} >
<div className={styles.footer} >
<Footer
title={title}
/>
</div>
</div>
</div>
export default App
|
Simplify text input to functional component and to use connect
|
import React from 'react';
import PropTypes from 'prop-types';
import {updateValue} from '../actions/controls';
import {connect} from '../store';
const TextInput = ({placeholder, id, type='text', name, className, style, value='', updateValue}) =>
<input
placeholder={placeholder}
id={id}
className={className}
style={style}
type={type}
name={name}
value={value}
onChange={(e) => updateValue(name, e.target.value)}
/>;
TextInput.propTypes = {
className: PropTypes.string,
id: PropTypes.string,
name: PropTypes.string.isRequired,
placeholder: PropTypes.string,
style: PropTypes.string,
type: PropTypes.oneOf(['text', 'email']),
value: PropTypes.string,
updateValue: PropTypes.func.isRequired,
};
const mapStateToProps = ({controls}, props) => ({
value: controls.get(props.name),
});
const mapDispatchToProps = {
updateValue,
};
export default connect(mapStateToProps, mapDispatchToProps)(TextInput);
|
import React from 'react';
import PropTypes from 'prop-types';
import Control from './Control';
class TextInput extends Control {
static propTypes = {
className: PropTypes.string,
id: PropTypes.string,
name: PropTypes.string.isRequired,
placeholder: PropTypes.string,
style: PropTypes.string,
type: PropTypes.oneOf(['text', 'email']),
};
static defaultProps = {
type: 'text',
};
render() {
const {placeholder, id, type, name, className, style} = this.props;
return (
<input
placeholder={placeholder}
id={id}
className={className}
style={style}
type={type}
name={name}
value={this._getValue()}
onChange={(e) => this._onChange(e.target.value)}
/>
);
}
}
export default TextInput;
|
Restructure templates to avoid name conflict
We were about to get into a lot of confusion with registering for
comments and registering for the con... this should help confusion
somewhat.
|
# Copyright (c) 2014-2015, Doug Kelly
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Create your views here.
from django.shortcuts import render
from django.views.generic import View
class Register(View):
def get(self, request):
return render(request, 'register/register.html')
|
# Copyright (c) 2014-2015, Doug Kelly
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Create your views here.
from django.shortcuts import render
from django.views.generic import View
class Register(View):
def get(self, request):
return render(request, 'register.html')
|
Update functional test to error correctly if a needed file is missing
|
package hoverfly_test
import (
"bytes"
"encoding/json"
"io/ioutil"
"github.com/SpectoLabs/hoverfly/functional-tests"
"github.com/dghubble/sling"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("/api/v2/simulation/schema", func() {
var (
hoverfly *functional_tests.Hoverfly
)
BeforeEach(func() {
hoverfly = functional_tests.NewHoverfly()
hoverfly.Start()
})
AfterEach(func() {
hoverfly.Stop()
})
Context("GET", func() {
It("Should get the JSON schema", func() {
req := sling.New().Get("http://localhost:" + hoverfly.GetAdminPort() + "/api/v2/simulation/schema")
res := functional_tests.DoRequest(req)
Expect(res.StatusCode).To(Equal(200))
fileBytes, err := ioutil.ReadFile("../../schema.json")
Expect(err).To(BeNil(), "schema.json not found")
fileBuffer := new(bytes.Buffer)
json.Compact(fileBuffer, fileBytes)
responseJson, err := ioutil.ReadAll(res.Body)
Expect(err).To(BeNil())
Expect(responseJson).To(Equal(fileBuffer.Bytes()))
})
})
})
|
package hoverfly_test
import (
"bytes"
"encoding/json"
"io/ioutil"
"github.com/SpectoLabs/hoverfly/functional-tests"
"github.com/dghubble/sling"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("/api/v2/simulation/schema", func() {
var (
hoverfly *functional_tests.Hoverfly
)
BeforeEach(func() {
hoverfly = functional_tests.NewHoverfly()
hoverfly.Start()
})
AfterEach(func() {
hoverfly.Stop()
})
Context("GET", func() {
It("Should get the JSON schema", func() {
req := sling.New().Get("http://localhost:" + hoverfly.GetAdminPort() + "/api/v2/simulation/schema")
res := functional_tests.DoRequest(req)
Expect(res.StatusCode).To(Equal(200))
fileBytes, _ := ioutil.ReadFile("../../schema.json")
fileBuffer := new(bytes.Buffer)
json.Compact(fileBuffer, fileBytes)
responseJson, err := ioutil.ReadAll(res.Body)
Expect(err).To(BeNil())
Expect(responseJson).To(Equal(fileBuffer.Bytes()))
})
})
})
|
Use PHP5.3 compat array syntax
|
<?php
/**
* Created by JetBrains PhpStorm.
* User: Doug
* Date: 28/07/13
* Time: 12:58
* To change this template use File | Settings | File Templates.
*/
namespace DVDoug\BoxPacker;
class BoxListTest extends \PHPUnit_Framework_TestCase {
function testCompare() {
$box1 = new TestBox('Small', 21, 21, 3, 1, 20, 20, 2, 100);
$box2 = new TestBox('Large', 201, 201, 21, 1, 200, 200, 20, 1000);
$box3 = new TestBox('Medium', 101, 101, 11, 5, 100, 100, 10, 500);
$list = new BoxList;
$list->insert($box1);
$list->insert($box2);
$list->insert($box3);
$sorted = array();
while (!$list->isEmpty()) {
$sorted[] = $list->extract();
}
self::assertEquals(array($box1,$box3,$box2), $sorted);
}
}
|
<?php
/**
* Created by JetBrains PhpStorm.
* User: Doug
* Date: 28/07/13
* Time: 12:58
* To change this template use File | Settings | File Templates.
*/
namespace DVDoug\BoxPacker;
class BoxListTest extends \PHPUnit_Framework_TestCase {
function testCompare() {
$box1 = new TestBox('Small', 21, 21, 3, 1, 20, 20, 2, 100);
$box2 = new TestBox('Large', 201, 201, 21, 1, 200, 200, 20, 1000);
$box3 = new TestBox('Medium', 101, 101, 11, 5, 100, 100, 10, 500);
$list = new BoxList;
$list->insert($box1);
$list->insert($box2);
$list->insert($box3);
$sorted = [];
while (!$list->isEmpty()) {
$sorted[] = $list->extract();
}
self::assertEquals(array($box1,$box3,$box2), $sorted);
}
}
|
Increase thumbnail quality to 80 from 60
Some of them were looking pretty compressed.
|
from imagekit import ImageSpec, register
from imagekit.processors import ResizeToFit
from spectator.core import app_settings
class Thumbnail(ImageSpec):
"Base class"
format = "JPEG"
options = {"quality": 80}
class ListThumbnail(Thumbnail):
"For displaying in lists of Publications, Events, etc."
processors = [ResizeToFit(*app_settings.THUMBNAIL_LIST_SIZE)]
class ListThumbnail2x(ListThumbnail):
"""Retina version of ListThumbnail
Generated twice the size of our set dimensions.
"""
dimensions = [d * 2 for d in app_settings.THUMBNAIL_LIST_SIZE]
processors = [ResizeToFit(*dimensions)]
class DetailThumbnail(Thumbnail):
"For displaying on the detail pages of Publication, Event, etc"
processors = [ResizeToFit(*app_settings.THUMBNAIL_DETAIL_SIZE)]
class DetailThumbnail2x(DetailThumbnail):
"""Retina version of DetailThumbnail
Generated twice the size of our set dimensions.
"""
dimensions = [d * 2 for d in app_settings.THUMBNAIL_DETAIL_SIZE]
processors = [ResizeToFit(*dimensions)]
register.generator("spectator:list_thumbnail", ListThumbnail)
register.generator("spectator:list_thumbnail2x", ListThumbnail2x)
register.generator("spectator:detail_thumbnail", DetailThumbnail)
register.generator("spectator:detail_thumbnail2x", DetailThumbnail2x)
|
from imagekit import ImageSpec, register
from imagekit.processors import ResizeToFit
from spectator.core import app_settings
class Thumbnail(ImageSpec):
"Base class"
format = "JPEG"
options = {"quality": 60}
class ListThumbnail(Thumbnail):
"For displaying in lists of Publications, Events, etc."
processors = [ResizeToFit(*app_settings.THUMBNAIL_LIST_SIZE)]
class ListThumbnail2x(ListThumbnail):
"""Retina version of ListThumbnail
Generated twice the size of our set dimensions.
"""
dimensions = [d * 2 for d in app_settings.THUMBNAIL_LIST_SIZE]
processors = [ResizeToFit(*dimensions)]
class DetailThumbnail(Thumbnail):
"For displaying on the detail pages of Publication, Event, etc"
processors = [ResizeToFit(*app_settings.THUMBNAIL_DETAIL_SIZE)]
class DetailThumbnail2x(DetailThumbnail):
"""Retina version of DetailThumbnail
Generated twice the size of our set dimensions.
"""
dimensions = [d * 2 for d in app_settings.THUMBNAIL_DETAIL_SIZE]
processors = [ResizeToFit(*dimensions)]
register.generator("spectator:list_thumbnail", ListThumbnail)
register.generator("spectator:list_thumbnail2x", ListThumbnail2x)
register.generator("spectator:detail_thumbnail", DetailThumbnail)
register.generator("spectator:detail_thumbnail2x", DetailThumbnail2x)
|
Use `const` for the options variable
The options variable does not change, so use `const` for it.
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
|
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { push } from 'connected-react-router';
import { selectors } from '@openchemistry/redux'
import { molecules } from '@openchemistry/redux'
import { isNil } from 'lodash-es';
import Molecules from '../components/molecules';
class MoleculesContainer extends Component {
componentDidMount() {
const options = { limit: 25, offset: 0, sort: '_id', sortdir: -1 }
this.props.dispatch(molecules.loadMolecules(options));
}
onOpen = (inchikey) => {
this.props.dispatch(push(`/molecules/inchikey/${inchikey}`));
}
render() {
const { molecules } = this.props;
if (isNil(molecules)) {
return null;
}
return (
<Molecules molecules={molecules} onOpen={this.onOpen} />
);
}
}
MoleculesContainer.propTypes = {
}
MoleculesContainer.defaultProps = {
}
function mapStateToProps(state, ownProps) {
let molecules = selectors.molecules.getMolecules(state);
return { molecules };
}
export default connect(mapStateToProps)(MoleculesContainer)
|
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { push } from 'connected-react-router';
import { selectors } from '@openchemistry/redux'
import { molecules } from '@openchemistry/redux'
import { isNil } from 'lodash-es';
import Molecules from '../components/molecules';
class MoleculesContainer extends Component {
componentDidMount() {
var options = { limit: 25, offset: 0, sort: '_id', sortdir: -1 }
this.props.dispatch(molecules.loadMolecules(options));
}
onOpen = (inchikey) => {
this.props.dispatch(push(`/molecules/inchikey/${inchikey}`));
}
render() {
const { molecules } = this.props;
if (isNil(molecules)) {
return null;
}
return (
<Molecules molecules={molecules} onOpen={this.onOpen} />
);
}
}
MoleculesContainer.propTypes = {
}
MoleculesContainer.defaultProps = {
}
function mapStateToProps(state, ownProps) {
let molecules = selectors.molecules.getMolecules(state);
return { molecules };
}
export default connect(mapStateToProps)(MoleculesContainer)
|
Switch to Zepto for examples
|
require.config({
baseUrl: '../',
paths: {
'text': 'bower_components/requirejs-text/text',
'$': 'lib/zeptojs/dist/zepto',
'bouncefix': 'bower_components/bouncefix.js/dist/bouncefix.min',
'velocity': 'bower_components/mobify-velocity/velocity',
'modal-center': 'dist/effect/modal-center',
'sheet-bottom': 'dist/effect/sheet-bottom',
'sheet-left': 'dist/effect/sheet-left',
'sheet-right': 'dist/effect/sheet-right',
'sheet-top': 'dist/effect/sheet-top',
'plugin': 'bower_components/plugin/dist/plugin.min',
'shade': 'bower_components/shade/dist/shade.min',
'pinny': 'dist/pinny'
},
'shim': {
'$': {
exports: '$'
}
}
});
|
require.config({
baseUrl: '../',
paths: {
'text': 'bower_components/requirejs-text/text',
'$': 'bower_components/jquery/dist/jquery',
'bouncefix': 'bower_components/bouncefix.js/dist/bouncefix.min',
'velocity': 'bower_components/mobify-velocity/velocity',
'modal-center': 'dist/effect/modal-center',
'sheet-bottom': 'dist/effect/sheet-bottom',
'sheet-left': 'dist/effect/sheet-left',
'sheet-right': 'dist/effect/sheet-right',
'sheet-top': 'dist/effect/sheet-top',
'plugin': 'bower_components/plugin/dist/plugin.min',
'shade': 'bower_components/shade/dist/shade.min',
'pinny': 'dist/pinny'
},
'shim': {
'$': {
exports: '$'
}
}
});
|
Update snapshot inspect formatter test
|
package inspect
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestFormat(t *testing.T) {
m := []typeStats{{
Name: "msg",
Sum: 1,
Count: 2,
}}
mkv := []typeStats{{
Name: "msgKV",
Sum: 1,
Count: 2,
}}
info := OutputFormat{
Meta: &MetadataInfo{
ID: "one",
Size: 2,
Index: 3,
Term: 4,
Version: 1,
},
Stats: m,
StatsKV: mkv,
TotalSize: 1,
TotalSizeKV: 1,
}
detailed := false
formatters := map[string]Formatter{
"pretty": newPrettyFormatter(),
// the JSON formatter ignores the showMeta
"json": newJSONFormatter(),
}
for fmtName, formatter := range formatters {
t.Run(fmtName, func(t *testing.T) {
actual, err := formatter.Format(&info, detailed)
require.NoError(t, err)
gName := fmt.Sprintf("%s", fmtName)
expected := golden(t, gName, actual)
require.Equal(t, expected, actual)
})
}
}
|
package inspect
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestFormat(t *testing.T) {
m := []typeStats{{
Name: "msg",
Sum: 1,
Count: 2,
}}
info := OutputFormat{
Meta: &MetadataInfo{
ID: "one",
Size: 2,
Index: 3,
Term: 4,
Version: 1,
},
Stats: m,
TotalSize: 1,
}
formatters := map[string]Formatter{
"pretty": newPrettyFormatter(),
// the JSON formatter ignores the showMeta
"json": newJSONFormatter(),
}
for fmtName, formatter := range formatters {
t.Run(fmtName, func(t *testing.T) {
actual, err := formatter.Format(&info)
require.NoError(t, err)
gName := fmt.Sprintf("%s", fmtName)
expected := golden(t, gName, actual)
require.Equal(t, expected, actual)
})
}
}
|
Add another test demonstrating that multiple assignment doesn't affect __requires__ parsing.
|
from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
def test_reads_files_with_multiple_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x, a = [a, x]
''')
assert scripts.DepsReader(script).read() == ['foo']
|
from __future__ import unicode_literals
import textwrap
import sys
import subprocess
from rwt import scripts
def test_pkg_imported(tmpdir):
"""
Create a script that loads cython and ensure it runs.
"""
body = textwrap.dedent("""
import cython
print("Successfully imported cython")
""").lstrip()
script_file = tmpdir / 'script'
script_file.write_text(body, 'utf-8')
pip_args = ['cython']
cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)]
out = subprocess.check_output(cmd, universal_newlines=True)
assert 'Successfully imported cython' in out
class TestDepsReader:
def test_reads_files_with_attribute_assignment(self):
script = textwrap.dedent('''
__requires__=['foo']
x.a = 'bar'
''')
assert scripts.DepsReader(script).read() == ['foo']
|
Remove bson of the required packages
|
#!/usr/bin/env python3
from setuptools import setup
packages = [
'ardupi_weather',
'ardupi_weather.arduino',
'ardupi_weather.database',
'ardupi_weather.flaskfiles.app'
]
extras = {
'rpi':['RPI.GPIO>=0.6.1']
}
setup(
name='ardupi_weather',
url='https://github.com/jordivilaseca/Weather-station',
license='Apache License, Version 2.0',
author='Jordi Vilaseca',
author_email='jordivilaseca@outlook.com',
description='Weather station with Raspberry Pi and Arduino',
long_description=open('../README.md').read(),
packages=[str(l) for l in packages],
zip_safe=False,
include_package_data=True,
extras_require=extras,
install_requires=[
'Flask>=0.10.1',
'pymongo>=3.2.2',
'PyYAML>=3.11',
'pyserial>=3.0.1'
],
entry_points={
'console_scripts': [
'weather-station = ardupi_weather.station:main',
'weather-server = ardupi_weather.flaskapp:main'
],
},
)
|
#!/usr/bin/env python3
from setuptools import setup
packages = [
'ardupi_weather',
'ardupi_weather.arduino',
'ardupi_weather.database',
'ardupi_weather.flaskfiles.app'
]
extras = {
'rpi':['RPI.GPIO>=0.6.1']
}
setup(
name='ardupi_weather',
url='https://github.com/jordivilaseca/Weather-station',
license='Apache License, Version 2.0',
author='Jordi Vilaseca',
author_email='jordivilaseca@outlook.com',
description='Weather station with Raspberry Pi and Arduino',
long_description=open('../README.md').read(),
packages=[str(l) for l in packages],
zip_safe=False,
include_package_data=True,
extras_require=extras,
install_requires=[
'Flask>=0.10.1',
'pymongo>=3.2.2',
'PyYAML>=3.11',
'bson>=0.4.2',
'pyserial>=3.0.1'
],
entry_points={
'console_scripts': [
'weather-station = ardupi_weather.station:main',
'weather-server = ardupi_weather.flaskapp:main'
],
},
)
|
Add infor to base service class
|
package com.boundary.camel.component.common;
/**
*
* @author davidg
*
*/
public class ServiceInfo {
private ServiceStatus status = ServiceStatus.SUCCESS;
private String message = "OK";
private String host = "localhost";
private int port = 7;
private int timeOut = 5000;
public ServiceInfo() {
}
public void setStatus(ServiceStatus status) {
this.status = status;
}
public ServiceStatus getStatus() {
return this.status;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
public void setHost(String host) {
this.host = host;
}
public String getHost() {
return this.host;
}
public void setPort(int port) {
this.port = port;
}
public int getPort() {
return this.port;
}
public void setTimeout(int timeOut) {
this.timeOut = timeOut;
}
public int getTimeout() {
return this.timeOut;
}
}
|
package com.boundary.camel.component.common;
/**
*
* @author davidg
*
*/
public class ServiceInfo {
private ServiceStatus status;
private String message;
private String host;
private int port;
public ServiceInfo() {
status = ServiceStatus.SUCCESS;
}
public void setStatus(ServiceStatus status) {
this.status = status;
}
public ServiceStatus getStatus() {
return this.status;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
public void setHost(String host) {
this.host = host;
}
public String getHost() {
return this.host;
}
public void setPort(int port) {
this.port = port;
}
public int getPort() {
return this.port;
}
}
|
Fix rating types updated message
Now we save all the rating types (before we were saving one type at once).
Former-commit-id: 5531021b980db9846344d2f6ad53e0b301fe056d
|
<?php
namespace Concrete\Controller\SinglePage\Dashboard\System\Conversations;
use \Concrete\Core\Page\Controller\DashboardPageController;
use Loader;
use \Concrete\Core\Conversation\Rating\Type as ConversationRatingType;
class Points extends DashboardPageController
{
public function view()
{
$ratingTypes = array_reverse(ConversationRatingType::getList());
$this->set('ratingTypes', $ratingTypes);
}
public function success() {
$this->view();
$this->set('message', t('Rating types updated.'));
}
public function save() {
$db = Loader::db();
foreach (ConversationRatingType::getList() as $crt) {
$rtID = $crt->getConversationRatingTypeID();
$rtPoints = $this->post('rtPoints_' . $rtID);
if (is_string($rtPoints) && is_numeric($rtPoints)) {
$db->Execute('UPDATE ConversationRatingTypes SET cnvRatingTypeCommunityPoints = ? WHERE cnvRatingTypeID = ? LIMIT 1', array($rtPoints, $rtID));
}
}
$this->redirect('/dashboard/system/conversations/points', 'success');
}
}
|
<?php
namespace Concrete\Controller\SinglePage\Dashboard\System\Conversations;
use \Concrete\Core\Page\Controller\DashboardPageController;
use Loader;
use \Concrete\Core\Conversation\Rating\Type as ConversationRatingType;
class Points extends DashboardPageController
{
public function view()
{
$ratingTypes = array_reverse(ConversationRatingType::getList());
$this->set('ratingTypes', $ratingTypes);
}
public function success() {
$this->view();
$this->set('message', t('Rating type updated.'));
}
public function save() {
$db = Loader::db();
foreach (ConversationRatingType::getList() as $crt) {
$rtID = $crt->getConversationRatingTypeID();
$rtPoints = $this->post('rtPoints_' . $rtID);
if (is_string($rtPoints) && is_numeric($rtPoints)) {
$db->Execute('UPDATE ConversationRatingTypes SET cnvRatingTypeCommunityPoints = ? WHERE cnvRatingTypeID = ? LIMIT 1', array($rtPoints, $rtID));
}
}
$this->redirect('/dashboard/system/conversations/points', 'success');
}
}
|
Add short shortcut for experimental flag.
|
import locale
import os
import signal
import sys
from argparse import ArgumentParser
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('GtkSource', '3.0')
from gi.repository import Gio, GLib, Gtk
from rsr import __version__
from rsr import paths
from rsr.app import Application
parser = ArgumentParser(prog='runsqlrun', description='Run SQL statements')
parser.add_argument(
'--version', action='version', version='%(prog)s ' + __version__)
parser.add_argument(
'--experimental', '-e', action='store_true',
help='Enable experimental features.')
# See issue3. Unfortunately this needs to be done before opening
# any Oracle connection.
os.environ.setdefault('NLS_LANG', '.AL32UTF8')
locale.setlocale(locale.LC_ALL, '.'.join(locale.getlocale()))
def main():
args = parser.parse_args()
signal.signal(signal.SIGINT, signal.SIG_DFL)
GLib.set_application_name('RunSQLRun')
GLib.set_prgname('runsqlrun')
resource = Gio.resource_load(
os.path.join(paths.data_dir, 'runsqlrun.gresource'))
Gio.Resource._register(resource)
#if args.dark_theme:
# Gtk.Settings.get_default().set_property(
# 'gtk-application-prefer-dark-theme', True)
app = Application(args)
sys.exit(app.run([]))
|
import locale
import os
import signal
import sys
from argparse import ArgumentParser
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('GtkSource', '3.0')
from gi.repository import Gio, GLib, Gtk
from rsr import __version__
from rsr import paths
from rsr.app import Application
parser = ArgumentParser(prog='runsqlrun', description='Run SQL statements')
parser.add_argument(
'--version', action='version', version='%(prog)s ' + __version__)
parser.add_argument(
'--experimental', action='store_true',
help='Enable experimental features.')
# See issue3. Unfortunately this needs to be done before opening
# any Oracle connection.
os.environ.setdefault('NLS_LANG', '.AL32UTF8')
locale.setlocale(locale.LC_ALL, '.'.join(locale.getlocale()))
def main():
args = parser.parse_args()
signal.signal(signal.SIGINT, signal.SIG_DFL)
GLib.set_application_name('RunSQLRun')
GLib.set_prgname('runsqlrun')
resource = Gio.resource_load(
os.path.join(paths.data_dir, 'runsqlrun.gresource'))
Gio.Resource._register(resource)
#if args.dark_theme:
# Gtk.Settings.get_default().set_property(
# 'gtk-application-prefer-dark-theme', True)
app = Application(args)
sys.exit(app.run([]))
|
Include 'models' subdirectory in package
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
from distutils.core import setup
setup(
name='django-banking',
version='0.1-dev',
description='Banking (SWIFT) classes for Python/Django',
long_description=open('README').read(),
author='Benjamin P. Jung',
author_email='headcr4sh@gmail.com',
url='https://github.com/headcr4sh/dango-banking',
download_url='https://github.com/headcr4sh/django-banking/downloads/',
packages = ['django_banking', 'django_banking.models'],
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
from distutils.core import setup
setup(
name='django-banking',
version='0.1-dev',
description='Banking (SWIFT) classes for Python/Django',
long_description=open('README').read(),
author='Benjamin P. Jung',
author_email='headcr4sh@gmail.com',
url='https://github.com/headcr4sh/dango-banking',
download_url='https://github.com/headcr4sh/django-banking/downloads/',
packages = ['django_banking',],
license='BSD',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Fix error where componentdidmount didn't load fast enough and caused a crash at render
|
"use strict";
import React, { Component } from 'react';
// Bootstrap
export default class BenefitsList extends Component {
constructor(props) {
super(props);
this.state = {
programs: []
};
}
componentDidMount(){
$.get('/api/v1/programs', function(result){
this.setState({
programs: result
});
}.bind(this));
}
render(){
return(
<div className='BenefitsList'>
<ul>
{this.state.programs.map(function(program, i){
return(
<div key={i}>{program.program_name}</div>
);
}, this)}
</ul>
</div>
);
}
}
|
"use strict";
import React, { Component } from 'react';
// Bootstrap
export default class BenefitsList extends Component {
componentDidMount(){
$.get('/api/v1/programs', function(result){
this.setState({
programs: result
});
console.log(result);
}.bind(this));
}
constructor(props) {
super(props);
}
render(){
return(
<div className='BenefitsList'>
<ul>
{this.state.programs.map(function(program){
return(
<div>{program.program_name}</div>
);
}, this)}
</ul>
</div>
);
}
}
|
Reset global var correctly in test teardown
|
import Ember from 'ember';
import config from '../../../config/environment';
import { initialize } from '../../../initializers/export-application-global';
var container, application, originalModulePrefix, originalExportApplicationGlobal;
module('ExportApplicationGlobalInitializer', {
setup: function() {
originalModulePrefix = config.modulePrefix;
originalExportApplicationGlobal = config.exportApplicationGlobal;
Ember.run(function() {
application = Ember.Application.create();
application.deferReadiness();
});
},
teardown: function() {
var classifiedName = Ember.String.classify(config.modulePrefix);
delete window[classifiedName];
config.modulePrefix = originalModulePrefix;
config.exportApplicationGlobal = originalExportApplicationGlobal;
}
});
test('it sets the application on window with the classified modulePrefix', function() {
config.modulePrefix = 'foo';
initialize(null, 'blazorz');
equal(window.Foo, 'blazorz');
});
test('it does not set the global unless exportApplicationGlobal is true', function() {
config.modulePrefix = 'foo';
config.exportApplicationGlobal = false;
initialize(null, 'blazorz');
ok(window.Foo !== 'blazorz');
});
|
import Ember from 'ember';
import config from '../../../config/environment';
import { initialize } from '../../../initializers/export-application-global';
var container, application, originalModulePrefix, originalExportApplicationGlobal;
module('ExportApplicationGlobalInitializer', {
setup: function() {
originalModulePrefix = config.modulePrefix;
originalExportApplicationGlobal = config.exportApplicationGlobal;
Ember.run(function() {
application = Ember.Application.create();
application.deferReadiness();
});
},
teardown: function() {
delete window[config.modulePrefix];
config.modulePrefix = originalModulePrefix;
config.exportApplicationGlobal = originalExportApplicationGlobal;
}
});
test('it sets the application on window with the classified modulePrefix', function() {
config.modulePrefix = 'foo';
initialize(null, 'blazorz');
equal(window.Foo, 'blazorz');
});
test('it does not set the global unless exportApplicationGlobal is true', function() {
config.modulePrefix = 'foo';
config.exportApplicationGlobal = false;
initialize(null, 'blazorz');
ok(window.Foo !== 'blazorz');
});
|
Select popular pbs first instead of only closest
|
from django.contrib.gis.measure import D
from django.contrib.gis.db.models.functions import Distance
from froide.publicbody.models import PublicBody
from .amenity import AmenityProvider
class AmenityLocalProvider(AmenityProvider):
'''
Like Amenity provider but tries to find the public body
for the amenity at its location
'''
NEARBY_RADIUS = 200
def _get_publicbody(self, amenity):
nearby_popular_pbs = PublicBody.objects.filter(
geo__isnull=False
).filter(
geo__dwithin=(amenity.geo, self.NEARBY_RADIUS)
).filter(
geo__distance_lte=(amenity.geo, D(m=self.NEARBY_RADIUS))
).annotate(
distance=Distance("geo", amenity.geo)
).order_by("-number_of_requests", "distance")[:1]
if nearby_popular_pbs:
return nearby_popular_pbs[0]
return super()._get_publicbody(amenity)
|
from django.contrib.gis.measure import D
from django.contrib.gis.db.models.functions import Distance
from froide.publicbody.models import PublicBody
from .amenity import AmenityProvider
class AmenityLocalProvider(AmenityProvider):
'''
Like Amenity provider but tries to find the public body
for the amenity at its location
'''
NEARBY_RADIUS = 200
def _get_publicbody(self, amenity):
nearby_pbs = PublicBody.objects.filter(
geo__isnull=False
).filter(
geo__dwithin=(amenity.geo, self.NEARBY_RADIUS)
).filter(
geo__distance_lte=(amenity.geo, D(m=self.NEARBY_RADIUS))
).annotate(
distance=Distance("geo", amenity.geo)
).order_by("distance")[:1]
if nearby_pbs:
return nearby_pbs[0]
return super()._get_publicbody(amenity)
|
Fix another warning assertion in credentials test
This commit fixes a warning assertion in a credentials test now that we
are stricter about warning message assertions.
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cloud.aws;
import com.amazonaws.auth.AWSCredentialsProvider;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;
public class SyspropCredentialsTests extends ESTestCase {
public void test() {
AWSCredentialsProvider provider =
InternalAwsS3Service.buildCredentials(logger, deprecationLogger, Settings.EMPTY, Settings.EMPTY, "default");
// NOTE: sys props are setup by the test runner in gradle
assertEquals("sysprop_access", provider.getCredentials().getAWSAccessKeyId());
assertEquals("sysprop_secret", provider.getCredentials().getAWSSecretKey());
assertWarnings("Supplying S3 credentials through system properties is deprecated. " +
"See the breaking changes lists in the documentation for details.");
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cloud.aws;
import com.amazonaws.auth.AWSCredentialsProvider;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESTestCase;
public class SyspropCredentialsTests extends ESTestCase {
public void test() {
AWSCredentialsProvider provider =
InternalAwsS3Service.buildCredentials(logger, deprecationLogger, Settings.EMPTY, Settings.EMPTY, "default");
// NOTE: sys props are setup by the test runner in gradle
assertEquals("sysprop_access", provider.getCredentials().getAWSAccessKeyId());
assertEquals("sysprop_secret", provider.getCredentials().getAWSSecretKey());
assertWarnings("Supplying S3 credentials through system properties is deprecated");
}
}
|
:sparkes: Use fake mailer on tests
|
'use strict';
class StubMailer {
static send(options, context, cb) {
cb(null, null);
}
}
module.exports = function(User) {
User.afterRemote('create', async (context, user) => {
let options = null;
if (process.env.NODE_ENV === 'testing') {
options = {
type: 'email',
from: 'test',
mailer: StubMailer,
};
} else {
options = {
type: 'email',
protocol: process.env.PROTOCOL || 'http',
port: process.env.DISPLAY_PORT || 3000,
host: process.env.HOSTNAME || 'localhost',
to: user.email,
from: 'noreply@redborder.com',
user: user,
};
}
user.verify(options, (err, response) => {
if (err) {
User.deleteById(user.id);
throw err;
}
});
});
};
|
'use strict';
module.exports = function(User) {
if (process.env.NODE_ENV !== 'testing') {
User.afterRemote('create', async (context, user) => {
const options = {
type: 'email',
protocol: process.env.PROTOCOL || 'http',
port: process.env.DISPLAY_PORT || 3000,
host: process.env.HOSTNAME || 'localhost',
to: user.email,
from: 'noreply@redborder.com',
user: user,
};
user.verify(options, (err, response) => {
if (err) {
User.deleteById(user.id);
throw err;
}
});
});
}
};
|
Add minimum size to the Application window
|
package nl.tudelft.dnainator.ui;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
/**
* DNAinator's main window, from which all interaction will occur.
* <p>
* The {@link #start(Stage) start} method will automatically load
* the required fxml files, which in turn instantiates all controllers.
* </p>
*/
public class DNAinator extends Application {
private static final String DNAINATOR = "DNAinator";
private static final String FXML = "/ui/fxml/dnainator.fxml";
private static final String ICON = "/ui/icons/dnainator.png";
private static final int MIN_WIDTH = 300;
private static final int MIN_HEIGHT = 150;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setMinHeight(MIN_HEIGHT);
primaryStage.setMinWidth(MIN_WIDTH);
primaryStage.setTitle(DNAINATOR);
primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON)));
primaryStage.setMaximized(true);
try {
BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML));
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
} catch (IOException e) {
e.printStackTrace();
}
primaryStage.show();
}
}
|
package nl.tudelft.dnainator.ui;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
/**
* DNAinator's main window, from which all interaction will occur.
* <p>
* The {@link #start(Stage) start} method will automatically load
* the required fxml files, which in turn instantiates all controllers.
* </p>
*/
public class DNAinator extends Application {
private static final String DNAINATOR = "DNAinator";
private static final String FXML = "/ui/fxml/dnainator.fxml";
private static final String ICON = "/ui/icons/dnainator.png";
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle(DNAINATOR);
primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(ICON)));
primaryStage.setMaximized(true);
try {
BorderPane rootLayout = FXMLLoader.load(getClass().getResource(FXML));
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
} catch (IOException e) {
e.printStackTrace();
}
primaryStage.show();
}
}
|
Revert "Use __CLASS__ for option name"
This reverts commit 803a3909605915d4ca20ba9a82e100267024bcca.
|
<?php
abstract class CM_Provision_Script_OptionBased extends CM_Provision_Script_Abstract implements CM_Typed {
use CM_Provision_Script_IsLoadedTrait;
/**
* @param bool $loaded
*/
protected function _setLoaded($loaded) {
CM_Option::getInstance()->set($this->_getOptionName(), (bool) $loaded);
}
/**
* @param CM_Service_Manager $manager
* @return bool
*/
protected function _isLoaded(CM_Service_Manager $manager) {
try {
return CM_Option::getInstance()->get($this->_getOptionName());
} catch (CM_Db_Exception $e) {
return false;
}
}
/**
* @return string
*/
private function _getOptionName() {
return 'SetupScript.' . $this->getType();
}
}
|
<?php
abstract class CM_Provision_Script_OptionBased extends CM_Provision_Script_Abstract implements CM_Typed {
use CM_Provision_Script_IsLoadedTrait;
/**
* @param bool $loaded
*/
protected function _setLoaded($loaded) {
CM_Option::getInstance()->set($this->_getOptionName(), (bool) $loaded);
}
/**
* @param CM_Service_Manager $manager
* @return bool
*/
protected function _isLoaded(CM_Service_Manager $manager) {
try {
return CM_Option::getInstance()->get($this->_getOptionName());
} catch (CM_Db_Exception $e) {
return false;
}
}
/**
* @return string
*/
private function _getOptionName() {
return __CLASS__ . ':' . $this->getType();
}
}
|
Increase reserved memory size for registerShutdownFunction handler
|
<?php
class sfRavenPluginConfiguration extends sfPluginConfiguration
{
const CONFIG_PATH = 'config/raven.yml';
/**
* Initializes the plugin.
*
* This method is called after the plugin's classes have been added to sfAutoload.
*/
public function initialize()
{
if ($this->configuration instanceof sfApplicationConfiguration)
{
$configCache = $this->configuration->getConfigCache();
$configCache->registerConfigHandler(self::CONFIG_PATH, 'sfDefineEnvironmentConfigHandler', array(
'prefix' => 'raven_',
));
require $configCache->checkConfig(self::CONFIG_PATH);
if (!sfConfig::get('raven_dsn'))
{
return;
}
$client = new sfRavenClient(sfConfig::get('raven_dsn'));
$errorHandler = new Raven_ErrorHandler($client);
$errorHandler->registerExceptionHandler();
$errorHandler->registerErrorHandler(true, E_ERROR | E_PARSE | E_NOTICE | E_STRICT);
$errorHandler->registerShutdownFunction(500);
}
}
}
|
<?php
class sfRavenPluginConfiguration extends sfPluginConfiguration
{
const CONFIG_PATH = 'config/raven.yml';
/**
* Initializes the plugin.
*
* This method is called after the plugin's classes have been added to sfAutoload.
*/
public function initialize()
{
if ($this->configuration instanceof sfApplicationConfiguration)
{
$configCache = $this->configuration->getConfigCache();
$configCache->registerConfigHandler(self::CONFIG_PATH, 'sfDefineEnvironmentConfigHandler', array(
'prefix' => 'raven_',
));
require $configCache->checkConfig(self::CONFIG_PATH);
if (!sfConfig::get('raven_dsn'))
{
return;
}
$client = new sfRavenClient(sfConfig::get('raven_dsn'));
$errorHandler = new Raven_ErrorHandler($client);
$errorHandler->registerExceptionHandler();
$errorHandler->registerErrorHandler(true, E_ERROR | E_PARSE | E_NOTICE | E_STRICT);
$errorHandler->registerShutdownFunction();
}
}
}
|
Add full syntax for SHOW TABLES to help
|
package com.facebook.presto.cli;
public final class Help
{
private Help() {}
public static String getHelpText()
{
return "" +
"Supported commands:\n" +
"QUIT\n" +
"DESCRIBE <table>\n" +
"SHOW COLUMNS FROM <table>\n" +
"SHOW FUNCTIONS\n" +
"SHOW PARTITIONS FROM <table>\n" +
"SHOW TABLES [LIKE <pattern>]\n" +
"";
}
}
|
package com.facebook.presto.cli;
public final class Help
{
private Help() {}
public static String getHelpText()
{
return "" +
"Supported commands:\n" +
"QUIT\n" +
"DESCRIBE <table>\n" +
"SHOW COLUMNS FROM <table>\n" +
"SHOW FUNCTIONS\n" +
"SHOW PARTITIONS FROM <table>\n" +
"SHOW TABLES\n" +
"";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.