text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Support undo functions that return a promise | PromiseAllSync = {
extend: function(PromiseClass) {
var emptyPromise = PromiseClass.resolve || PromiseClass.when;
PromiseClass.allSync = function(collection, fn, unfn) {
var stack = [];
return collection.reduce(function(promise, item) {
return promise.then(function() {
var nextPromise = fn ? fn(item) : item;
return nextPromise.then(function() {
if(unfn) stack.push(item);
});
});
}, emptyPromise.apply(PromiseClass))
.catch(function(e) {
if(unfn) {
stack.reduceRight(function(promise, item) {
return promise.then(function() {
return unfn(item);
});
}, emptyPromise.apply(PromiseClass));
}
return PromiseClass.reject(e);
});
}
}
}; | PromiseAllSync = {
extend: function(PromiseClass) {
var emptyPromise = PromiseClass.resolve || PromiseClass.when;
PromiseClass.allSync = function(collection, fn, unfn) {
var stack = [];
return collection.reduce(function(promise, item) {
return promise.then(function() {
var nextPromise = fn ? fn(item) : item;
return nextPromise.then(function() {
if(unfn) stack.push(item);
});
});
}, emptyPromise.apply(PromiseClass))
.catch(function(e) {
if(unfn) while(stack.length) unfn(stack.pop());
return PromiseClass.reject(e);
});
}
}
}; |
Use update_title in DocumentTitle component | import {connect} from 'react-redux';
import {Component} from 'react';
import PropTypes from 'prop-types';
class DocumentTitle extends Component {
constructor(props) {
super(props);
const {update_title} = props.config;
this.state = {
initialTitle: document.title,
update_title: update_title,
};
}
UNSAFE_componentWillReceiveProps(props) {
if (props.pendingCallbacks.length) {
document.title = this.state.update_title;
} else {
document.title = this.state.initialTitle;
}
}
shouldComponentUpdate() {
return false;
}
render() {
return null;
}
}
DocumentTitle.propTypes = {
pendingCallbacks: PropTypes.array.isRequired,
update_title: PropTypes.string,
};
export default connect(state => ({
config: state.config,
pendingCallbacks: state.pendingCallbacks,
}))(DocumentTitle);
| import {connect} from 'react-redux';
import {Component} from 'react';
import PropTypes from 'prop-types';
class DocumentTitle extends Component {
constructor(props) {
super(props);
this.state = {
initialTitle: document.title,
};
}
UNSAFE_componentWillReceiveProps(props) {
if (props.pendingCallbacks.length) {
document.title = 'Updating...';
} else {
document.title = this.state.initialTitle;
}
}
shouldComponentUpdate() {
return false;
}
render() {
return null;
}
}
DocumentTitle.propTypes = {
pendingCallbacks: PropTypes.array.isRequired,
};
export default connect(state => ({
pendingCallbacks: state.pendingCallbacks,
}))(DocumentTitle);
|
Change name of trackercli suite to acceptance suite | package main_test
import (
"fmt"
"io/ioutil"
"os/exec"
"testing"
"github.com/onsi/gomega/gexec"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestTrackercli(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Acceptance Suite")
}
var pathToTrackerCLI string
var _ = BeforeSuite(func() {
var err error
pathToTrackerCLI, err = gexec.Build("github.com/kkallday/tracker-cli")
Expect(err).NotTo(HaveOccurred())
})
var _ = AfterSuite(func() {
gexec.CleanupBuildArtifacts()
})
func executeTrackerCLI(args []string) *gexec.Session {
command := exec.Command(pathToTrackerCLI, args...)
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(0))
return session
}
func loadFixture(pathToFixture string) string {
fixtureFileContents, err := ioutil.ReadFile(fmt.Sprintf("fixtures/%s", pathToFixture))
Expect(err).NotTo(HaveOccurred())
return string(fixtureFileContents)
}
| package main_test
import (
"fmt"
"io/ioutil"
"os/exec"
"testing"
"github.com/onsi/gomega/gexec"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
func TestTrackercli(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "TrackerCLI Suite")
}
var pathToTrackerCLI string
var _ = BeforeSuite(func() {
var err error
pathToTrackerCLI, err = gexec.Build("github.com/kkallday/tracker-cli")
Expect(err).NotTo(HaveOccurred())
})
var _ = AfterSuite(func() {
gexec.CleanupBuildArtifacts()
})
func executeTrackerCLI(args []string) *gexec.Session {
command := exec.Command(pathToTrackerCLI, args...)
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).NotTo(HaveOccurred())
Eventually(session).Should(gexec.Exit(0))
return session
}
func loadFixture(pathToFixture string) string {
fixtureFileContents, err := ioutil.ReadFile(fmt.Sprintf("fixtures/%s", pathToFixture))
Expect(err).NotTo(HaveOccurred())
return string(fixtureFileContents)
}
|
Fix a bug (?) in detmine_package
Canditates have their first character removed if it is ".". | """
Utility that detects the package of a given object.
"""
from __future__ import division, print_function, with_statement
import inspect
import os
def determine_package(some_object):
"""
Resolves a call by object to a call by package.
- Determine absolute package name of the given object.
- When the task gets executed, the worker process will import it.
"""
# expand the module's path to an absolute import
filename = inspect.getsourcefile(some_object)
module_path, module_filename = os.path.split(filename)
module_name, _ = os.path.splitext(module_filename)
prefix = []
for directory in module_path.split(os.sep)[::-1]:
prefix.append(directory)
candidate = ".".join(prefix[::-1] + [module_name])
if candidate.startswith("."):
candidate = candidate[1:]
try:
__import__(name=candidate, globals=globals(), locals=locals(),
fromlist=[], level=0)
some_object = candidate
return some_object
except ImportError:
pass
raise ImportError("Could not determine the package of the given " +
"object. This should not happen.")
| """
Utility that detects the package of a given object.
"""
from __future__ import division, print_function, with_statement
import inspect
import os
def determine_package(some_object):
"""
Resolves a call by object to a call by package.
- Determine absolute package name of the given object.
- When the task gets executed, the worker process will import it.
"""
# expand the module's path to an absolute import
filename = inspect.getsourcefile(some_object)
module_path, module_filename = os.path.split(filename)
module_name, _ = os.path.splitext(module_filename)
prefix = []
for directory in module_path.split(os.sep)[::-1]:
prefix.append(directory)
candidate = ".".join(prefix[::-1] + [module_name])
try:
__import__(name=candidate, globals=globals(), locals=locals(),
fromlist=[], level=0)
some_object = candidate
return some_object
except ImportError:
pass
raise ImportError("Could not determine the package of the given " +
"object. This should not happen.")
|
Fix for bad file separators for screenshots | package se.claremont.autotest.common;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* The LogFolder class maintains the test run log folder for logging purposes of test based logs,
* html based logs, summary log, screen shots and other assets that has to do with test resources
* being saved along a test execution.
*
* Created by jordam on 2016-09-05.
*/
public class LogFolder {
public static String testRunLogFolder = null; //Used for test case logging
@SuppressWarnings("FieldCanBeLocal")
private static String baseLogFolder = null; //Read from Settings
/**
* Sets the values to run time values.
*
* @param testSetName The name of the testSet. Normally used to get test case logs in correct folder
*/
public static void setLogFolder(String testSetName){
if(testRunLogFolder == null){
baseLogFolder = TestRun.settings.getValue(Settings.SettingParameters.BASE_LOG_FOLDER);
if(!baseLogFolder.endsWith("\\") || !baseLogFolder.endsWith("/")){ baseLogFolder = baseLogFolder + "\\"; }
testRunLogFolder = baseLogFolder.replace("\\", File.separator).replace("/", File.separator) + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + "_" + testSetName + File.separator;
}
}
}
| package se.claremont.autotest.common;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* The LogFolder class maintains the test run log folder for logging purposes of test based logs,
* html based logs, summary log, screen shots and other assets that has to do with test resources
* being saved along a test execution.
*
* Created by jordam on 2016-09-05.
*/
public class LogFolder {
public static String testRunLogFolder = null; //Used for test case logging
@SuppressWarnings("FieldCanBeLocal")
private static String baseLogFolder = null; //Read from Settings
/**
* Sets the values to run time values.
*
* @param testSetName The name of the testSet. Normally used to get test case logs in correct folder
*/
public static void setLogFolder(String testSetName){
if(testRunLogFolder == null){
baseLogFolder = TestRun.settings.getValue(Settings.SettingParameters.BASE_LOG_FOLDER);
if(!baseLogFolder.endsWith("\\")){ baseLogFolder = baseLogFolder + "\\"; }
testRunLogFolder = baseLogFolder + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + "_" + testSetName + "\\";
}
}
}
|
Use `html_entity_decode()` for decoding entities in upgrader strings. | <?php
namespace WP_CLI;
/**
* A Upgrader Skin for WordPress that only generates plain-text
*
* @package wp-cli
*/
class UpgraderSkin extends \WP_Upgrader_Skin {
public $api;
function header() {}
function footer() {}
function bulk_header() {}
function bulk_footer() {}
function error( $error ) {
if ( !$error )
return;
if ( is_string( $error ) && isset( $this->upgrader->strings[ $error ] ) )
$error = $this->upgrader->strings[ $error ];
// TODO: show all errors, not just the first one
\WP_CLI::warning( $error );
}
function feedback( $string ) {
if ( isset( $this->upgrader->strings[$string] ) )
$string = $this->upgrader->strings[$string];
if ( strpos($string, '%') !== false ) {
$args = func_get_args();
$args = array_splice($args, 1);
if ( !empty($args) )
$string = vsprintf($string, $args);
}
if ( empty($string) )
return;
$string = str_replace( '…', '...', strip_tags( $string ) );
$string = html_entity_decode( $string, ENT_QUOTES, get_bloginfo( 'charset' ) );
\WP_CLI::log( $string );
}
}
| <?php
namespace WP_CLI;
/**
* A Upgrader Skin for WordPress that only generates plain-text
*
* @package wp-cli
*/
class UpgraderSkin extends \WP_Upgrader_Skin {
public $api;
function header() {}
function footer() {}
function bulk_header() {}
function bulk_footer() {}
function error( $error ) {
if ( !$error )
return;
if ( is_string( $error ) && isset( $this->upgrader->strings[ $error ] ) )
$error = $this->upgrader->strings[ $error ];
// TODO: show all errors, not just the first one
\WP_CLI::warning( $error );
}
function feedback( $string ) {
if ( isset( $this->upgrader->strings[$string] ) )
$string = $this->upgrader->strings[$string];
if ( strpos($string, '%') !== false ) {
$args = func_get_args();
$args = array_splice($args, 1);
if ( !empty($args) )
$string = vsprintf($string, $args);
}
if ( empty($string) )
return;
$string = str_replace( '…', '...', strip_tags( $string ) );
\WP_CLI::log( $string );
}
}
|
Raise the timeout limit for slow banking modules; | import americano from 'americano';
import path from 'path-extra';
import { makeLogger } from './helpers';
let log = makeLogger('index');
let application = (options = {}, callback) => {
options.name = 'Kresus';
options.root = options.root || path.join(__dirname, '..');
options.port = process.env.PORT || 9876;
options.host = process.env.HOST || '127.0.0.1';
// If we try to import 'init', this has to be done at the global scope
// level. In this case, we will import init and its transitive closure of
// imports before americano is initialized. As a matter of fact, default
// parameters of americano will be taken into account (no routes, no
// models, no standalone cozydb). So the 'init' import has to be
// synchronous, at the last minute.
americano.start(options, (err, app, server) => {
if (err) {
return log.error(`Error when starting americano: ${ err }`);
}
// Raise the timeout limit, since some banking modules can be quite
// long at fetching new operations. Time is in milliseconds.
server.timeout = 5 * 60 * 1000;
require('./init')(app, server, callback);
});
};
if (typeof module.parent === 'undefined' || !module.parent)
application();
module.exports = application;
| import americano from 'americano';
import path from 'path-extra';
import { makeLogger } from './helpers';
let log = makeLogger('index');
let application = (options = {}, callback) => {
options.name = 'Kresus';
options.root = options.root || path.join(__dirname, '..');
options.port = process.env.PORT || 9876;
options.host = process.env.HOST || '127.0.0.1';
// If we try to import 'init', this has to be done at the global scope
// level. In this case, we will import init and its transitive closure of
// imports before americano is initialized. As a matter of fact, default
// parameters of americano will be taken into account (no routes, no
// models, no standalone cozydb). So the 'init' import has to be
// synchronous, at the last minute.
americano.start(options, (err, app, server) => {
if (err) {
return log.error(`Error when starting americano: ${ err }`);
}
require('./init')(app, server, callback);
});
};
if (typeof module.parent === 'undefined' || !module.parent)
application();
module.exports = application;
|
Set product_configurator_mrp to uninstallable until fixing / refactoring | {
'name': 'Product Configurator Manufacturing',
'version': '11.0.1.0.0',
'category': 'Manufacturing',
'summary': 'BOM Support for configurable products',
'author': 'Pledra',
'license': 'AGPL-3',
'website': 'http://www.pledra.com/',
'depends': ['mrp', 'product_configurator'],
"data": [
'security/configurator_security.xml',
'security/ir.model.access.csv',
'views/product_view.xml',
'views/product_config_view.xml',
'views/mrp_view.xml',
],
'demo': [],
'test': [],
'installable': False,
'auto_install': False,
}
| {
'name': 'Product Configurator Manufacturing',
'version': '11.0.1.0.0',
'category': 'Manufacturing',
'summary': 'BOM Support for configurable products',
'author': 'Pledra',
'license': 'AGPL-3',
'website': 'http://www.pledra.com/',
'depends': ['mrp', 'product_configurator'],
"data": [
'security/configurator_security.xml',
'security/ir.model.access.csv',
'views/product_view.xml',
'views/product_config_view.xml',
'views/mrp_view.xml',
],
'demo': [],
'test': [],
'installable': True,
'auto_install': False,
}
|
Remove React error from modal to pick a widget (wysiwyg) | import React from 'react';
import PropTypes from 'prop-types';
export default function WidgetBlockCreation({ block, onSubmit }) {
const { widgets } = block.admin;
return (
<div className="fa-add-widget">
<h3>Select a widget</h3>
<ul>
{widgets.map((w) => {
return (
<li key={w.widget.id}>
<h4>{w.widget.name}</h4>
<button onClick={() => onSubmit({
widgetId: w.widget.id,
datasetId: w.widget.dataset,
categories: []
})}
>Add widget
</button>
</li>);
})}
</ul>
</div>
);
}
WidgetBlockCreation.propTypes = {
};
| import React from 'react';
import PropTypes from 'prop-types';
export default function WidgetBlockCreation({ block, onSubmit }) {
const { widgets } = block.admin;
return (
<div className="fa-add-widget">
<h3>Select a widget</h3>
<ul>
{widgets.map((w) => {
return (
<li key={w.widget.name}>
<h4>{w.widget.name}</h4>
<button onClick={() => onSubmit({
widgetId: w.widget.id,
datasetId: w.widget.dataset,
categories: []
})}
>Add widget
</button>
</li>);
})}
</ul>
</div>
);
}
WidgetBlockCreation.propTypes = {
};
|
Document kicad python unicode bug | import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'):
pretties.append(os.path.realpath(dirname))
break
src_plugin = pcbnew.IO_MGR.PluginFind(1)
for libpath in pretties:
try:
list_of_footprints = src_plugin.FootprintEnumerate(libpath)
except UnicodeDecodeError:
# pcbnew python modules (at least git-7d6230a and v4.x) have an issue
# with loading unicode paths
# https://bugs.launchpad.net/kicad/+bug/1740881
pass
except Exception as e:
print(libpath)
raise e
| import pcbnew
import sys
import os
pretties = []
for dirname, dirnames, filenames in os.walk(sys.argv[1]):
# don't go into any .git directories.
if '.git' in dirnames:
dirnames.remove('.git')
for filename in filenames:
if (not os.path.isdir(filename)) and (os.path.splitext(filename)[-1] == '.kicad_mod'):
pretties.append(os.path.realpath(dirname))
break
src_plugin = pcbnew.IO_MGR.PluginFind(1)
for libpath in pretties:
try:
list_of_footprints = src_plugin.FootprintEnumerate(libpath)
except UnicodeDecodeError:
pass
except Exception as e:
print(libpath)
raise e
|
Remove unused noble emitter code | var EventEmitter = require('events').EventEmitter;
var hardware = module.exports = new EventEmitter();
var e = (process.env.DEVICE) ?
require('./serial')(process.env.DEVICE) :
require('./stdin-mock');
var commands = {
0: function () {
emitScore('a'); // single click
},
1: function () {
emitScore('b'); // single click
},
2: function () {
emitUndo('a'); // double click
},
3: function () {
emitUndo('b'); // double click
},
4: function () {
hardware.emit('restart'); // long press
},
5: function () {
hardware.emit('restart'); // long press
}
};
e.on('connected', function () {
console.log('ble connected');
hardware.emit('connected');
});
e.on('data', function (data) {
console.log('data: ', data);
if(commands[data])
commands[data]();
else
console.log('unknown command "' + data + '"');
});
e.on('disconnected', function () {
console.log('ble disconnected');
hardware.emit('disconnected');
});
function emitScore (side) {
hardware.emit('score', { side: side });
}
function emitUndo (side) {
hardware.emit('undo', { side: side });
}
| var EventEmitter = require('events').EventEmitter;
var hardware = module.exports = new EventEmitter();
//var e = nobleEmitter.connect(peripheralUuid, serviceUuid, characteristicUuid);
var e = (process.env.DEVICE) ?
require('./serial')(process.env.DEVICE) :
require('./stdin-mock');
var commands = {
0: function () {
emitScore('a'); // single click
},
1: function () {
emitScore('b'); // single click
},
2: function () {
emitUndo('a'); // double click
},
3: function () {
emitUndo('b'); // double click
},
4: function () {
hardware.emit('restart'); // long press
},
5: function () {
hardware.emit('restart'); // long press
}
};
e.on('connected', function () {
console.log('ble connected');
hardware.emit('connected');
});
e.on('data', function (data) {
console.log('data: ', data);
if(commands[data])
commands[data]();
else
console.log('unknown command "' + data + '"');
});
e.on('disconnected', function () {
console.log('ble disconnected');
hardware.emit('disconnected');
});
function emitScore (side) {
hardware.emit('score', { side: side });
}
function emitUndo (side) {
hardware.emit('undo', { side: side });
}
|
Create soundAndCounter method to call updateCounterView | function Metronome(tempo, beatsPerMeasure){
this.tempo = Number(tempo);
this.beatsPerMeasure = Number(beatsPerMeasure);
this.interval = null;
}
Metronome.prototype.start = function(){
var millisecondsToWait = this.tempoToMilliseconds(this.tempo);
this.interval = window.setInterval(soundAndCounter, millisecondsToWait, this);
}
Metronome.prototype.tempoToMilliseconds = function(tempo){
return (1000 * 60)/tempo;
}
soundAndCounter = function(metronome){
updateCounterView(metronome);
}
updateCounterView = function(metronome){
var counter = document.getElementById("metronome-counter");
var pastBeat = Number(counter.innerHTML);
if (pastBeat < metronome.beatsPerMeasure){
counter.innerHTML = pastBeat + 1;
} else {
counter.innerHTML = 1;
}
}
Metronome.prototype.stop = function(){
window.clearInterval(this.interval);
counter.innerHTML = "";
} | function Metronome(tempo, beatsPerMeasure){
this.tempo = Number(tempo);
this.beatsPerMeasure = Number(beatsPerMeasure);
this.interval = null;
}
Metronome.prototype.start = function(){
var millisecondsToWait = this.tempoToMilliseconds(this.tempo);
this.interval = window.setInterval(updateCounterView, millisecondsToWait, this);
}
Metronome.prototype.tempoToMilliseconds = function(tempo){
return (1000 * 60)/tempo;
}
updateCounterView = function(metronome){
var counter = document.getElementById("metronome-counter");
var pastBeat = Number(counter.innerHTML);
if (pastBeat < metronome.beatsPerMeasure){
counter.innerHTML = pastBeat + 1;
} else {
counter.innerHTML = 1;
}
}
Metronome.prototype.stop = function(){
window.clearInterval(this.interval);
counter.innerHTML = "";
} |
Send results to the server | import os
import glob
import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
req = requests.post(url, files=file)
req.raise_for_status()
def sync():
# send all results
for path in glob.glob(os.path.join(config.results_dir,'[!_]*.json')):
try:
submit_result(path)
except Exception, e:
logging.error("Unable to send result file %s" % (path))
| import requests
import config
def request(slug):
url = "%s%s" % (config.server_url, slug)
req = requests.get(url)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
return req.json()
def get_recommended_versions():
return request("/versions")
def get_experiments():
return request("/experiments")
def get_results():
return request("/results")
def get_clients():
return request("/clients")
def submit_result(file_name):
with open(file_name) as result_file:
file = {'result' : result_file}
url = "%s%s" % (config.server_url, "/results")
requests.post(url, files=file)
if req.status_code != requests.codes.ok:
raise req.raise_for_status()
|
Add additional timeout for travis | // This is a karma config file. For more details see
// http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
// https://github.com/webpack/karma-webpack
let webpackConfig = require('../../build/webpack.test.conf');
module.exports = function(config) {
config.set({
// to run in additional browsers:
// 1. install corresponding karma launcher
// http://karma-runner.github.io/0.13/config/browsers.html
// 2. add it to the `browsers` array below.
browsers: ['PhantomJS'],
browserNoActivityTimeout: 24000,
frameworks: ['mocha', 'sinon-chai'],
reporters: ['spec', 'coverage'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true,
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' },
]
},
});
};
| // This is a karma config file. For more details see
// http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
// https://github.com/webpack/karma-webpack
var webpackConfig = require('../../build/webpack.test.conf');
module.exports = function (config) {
config.set({
// to run in additional browsers:
// 1. install corresponding karma launcher
// http://karma-runner.github.io/0.13/config/browsers.html
// 2. add it to the `browsers` array below.
browsers: ['PhantomJS'],
frameworks: ['mocha', 'sinon-chai'],
reporters: ['spec', 'coverage'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true,
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' },
]
},
});
};
|
Use string_from_file() to interpret file-based DSNs | """
Functions for connecting to the pScheduler database
"""
import psycopg2
from filestring import string_from_file
def pg_connection(dsn='', autocommit=True):
"""
Connect to the database, and return a handle to it
Arguments:
dsn - A data source name to use in connecting to the database. If
the string begins with an '@', the remainder will be treated as
the path to a file where the value can be retrieved.
autocommit - Whether or not commits are done automatically when
quesies are issued.
"""
dsn = string_from_file(dsn)
pg = psycopg2.connect(dsn)
if autocommit:
pg.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
return pg
def pg_cursor(dsn='', autocommit=True):
"""
Connect to the database, and return a cursor.
Arguments:
dsn - A data source name to use in connecting to the database. If
the string begins with an '@', the remainder will be treated as
the path to a file where the value can be retrieved.
autocommit - Whether or not commits are done automatically when
quesies are issued.
"""
pg = pg_connection(dsn, autocommit)
return pg.cursor()
# TODO: Need a routine that does the select wait currently
# rubberstamped into the services to do timed waits for notifications.
| """
Functions for connecting to the pScheduler database
"""
import psycopg2
def pg_connection(dsn='', autocommit=True):
"""
Connect to the database, and return a handle to it
Arguments:
dsn - A data source name to use in connecting to the database. If
the string begins with an '@', the remainder will be treated as
the path to a file where the value can be retrieved.
autocommit - Whether or not commits are done automatically when
quesies are issued.
"""
# Read the DSN from a file if requested
if dsn.startswith('@'):
with open(dsn[1:], 'r') as dsnfile:
dsn = dsnfile.read().replace('\n', '')
pg = psycopg2.connect(dsn)
if autocommit:
pg.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
return pg
def pg_cursor(dsn='', autocommit=True):
"""
Connect to the database, and return a cursor.
Arguments:
dsn - A data source name to use in connecting to the database. If
the string begins with an '@', the remainder will be treated as
the path to a file where the value can be retrieved.
autocommit - Whether or not commits are done automatically when
quesies are issued.
"""
pg = pg_connection(dsn, autocommit)
return pg.cursor()
# TODO: Need a routine that does the select wait currently
# rubberstamped into the services to do timed waits for notifications.
|
Fix oops in previous commit(folder shadow). | <?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
AppAsset::register($this);?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<link rel="stylesheet" type="text/css" href="../css/main_site.css" />
<link rel="shortcut icon" href="../images/favicon.ico" />
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<div class="wrapper">
<div width="500px"><img src="../images/logo.png" alt="Coursey" title="Coursey"/></div><br>
<div style="position:absolute; margin: -51px 0 0 15px;"><img src="../images/fold.png"/></div>
<?= $content ?>
</div>
<div><p class="credit" align="center">Copyright by Khnure Students. 2014<br></p></div>
</div>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?> | <?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
AppAsset::register($this);?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<link rel="stylesheet" type="text/css" href="../css/main_site.css" />
<link rel="shortcut icon" href="../images/favicon.ico" />
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<div class="wrapper">
<div width="500px"><img src="../images/logo.png" alt="Coursey" title="Coursey"/></div><br>
<?= $content ?>
</div>
<div><p class="credit" align="center">Copyright by Khnure Students. 2014<br></p></div>
</div>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?> |
Fix error checking for sentiment analysis | "use strict";
const express = require('express');
const twilio = require('twilio');
const bodyParser = require('body-parser');
const app = express();
// Run server to listen on port 8000.
const server = app.listen(8000, () => {
console.log('listening on *:8000');
});
const io = require('socket.io')(server);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('static'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
});
app.post('/sms', (req, res) => {
let twiml = twilio.TwimlResponse();
let addOns = JSON.parse(req.body.AddOns);
let sentimentStatus = addOns.results.ibm_watson_sentiment.status;
if (sentimentStatus === 'successful') {
let sentiment = addOns.results.ibm_watson_sentiment.result.docSentiment.type;
io.emit('sms', sentiment);
console.log(sentiment);
} else {
console.log('Sentiment failed');
}
twiml.message('Thanks for joining my demo :)');
res.send(twiml.toString());
});
| "use strict";
const express = require('express');
const twilio = require('twilio');
const bodyParser = require('body-parser');
const app = express();
// Run server to listen on port 5000.
const server = app.listen(5000, () => {
console.log('listening on *:5000');
});
const io = require('socket.io')(server);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('static'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
});
app.post('/sms', (req, res) => {
let twiml = twilio.TwimlResponse();
let sentiment = 'positive'; // For now
io.emit('sms', sentiment);
twiml.message('Thanks for joining my demo :)');
res.send(twiml.toString());
});
|
Add license to controller file. | /*
* Copyright 2016 Function1. All Rights Reserved.
*
* 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 com.fatwire.gst.foundation.controller;
import javax.servlet.ServletContext;
import com.fatwire.assetapi.data.BaseController;
import com.fatwire.gst.foundation.controller.action.Injector;
import com.fatwire.gst.foundation.controller.support.WebContextUtil;
import COM.FutureTense.Interfaces.DependenciesAwareModelAndView;
public class InjectingController extends BaseController {
public DependenciesAwareModelAndView handleRequest() {
ServletContext srvCtx = ics.getIServlet().getServlet().getServletContext();
AppContext ctx = WebContextUtil.getWebAppContext(srvCtx);
Injector injector = ctx.getBean("Injector",Injector.class);
injector.inject(ics, this);
return super.handleRequest();
}
}
| package com.fatwire.gst.foundation.controller;
import javax.servlet.ServletContext;
import com.fatwire.assetapi.data.BaseController;
import com.fatwire.gst.foundation.controller.action.Injector;
import com.fatwire.gst.foundation.controller.support.WebContextUtil;
import COM.FutureTense.Interfaces.DependenciesAwareModelAndView;
import COM.FutureTense.Interfaces.ICS;
public class InjectingController extends BaseController {
public InjectingController(ICS ics)
{
super();
this.setICS(ics);
}
public DependenciesAwareModelAndView handleRequest()
{
ServletContext srvCtx = ics.getIServlet().getServlet().getServletContext();
AppContext ctx = WebContextUtil.getWebAppContext(srvCtx);
Injector injector = ctx.getBean("Injector",Injector.class);
injector.inject(ics, this);
return super.handleRequest();
}
}
|
test: Fix event handler test with callback | /* eslint-env mocha */
'use strict'
const chai = require('chai')
chai.should()
let result = ''
module.exports = function () {
this.registerHandler('BeforeFeatures', function (features, cb) {
result += features.length
cb()
})
this.registerHandler('BeforeFeature', function (feature, cb) {
result += feature.getName()
cb()
})
this.registerHandler('BeforeScenario', function (scenario, cb) {
result += scenario.getName()
cb()
})
this.registerHandler('BeforeStep', function (step, cb) {
result += step.getName()
cb()
})
this.registerHandler('AfterStep', function (step, cb) {
result += step.getName()
cb()
})
this.registerHandler('AfterScenario', function (scenario, cb) {
result += scenario.getName()
cb()
})
this.registerHandler('AfterFeature', function (feature, cb) {
result += feature.getName()
cb()
})
this.registerHandler('AfterFeatures', function (features, cb) {
result += features.length
if (process.send) process.send(result)
cb()
})
}
| /* eslint-env mocha */
'use strict'
const chai = require('chai')
chai.should()
let result = ''
module.exports = function () {
this.registerHandler('BeforeFeatures', function (features, cb) {
result += features.length
cb()
})
this.registerHandler('BeforeFeature', function (feature, cb) {
result += feature.getName()
cb()
})
this.registerHandler('BeforeScenario', function (scenario, cb) {
result += scenario.getName()
cb()
})
this.registerHandler('BeforeStep', function (step, cb) {
this.click('#before-step')
result += step.getName()
cb()
})
this.registerHandler('AfterStep', function (step, cb) {
result += step.getName()
cb()
})
this.registerHandler('AfterScenario', function (scenario, cb) {
result += scenario.getName()
cb()
})
this.registerHandler('AfterFeature', function (feature, cb) {
result += feature.getName()
cb()
})
this.registerHandler('AfterFeatures', function (features, cb) {
result += features.length
if (process.send) process.send(result)
cb()
})
}
|
Add some more info in vendor download page | <?php
use app\commands\FilesController;
use yii\bootstrap\Html;
?>
<p>
Vendor files may be required by
<?php
echo Html::a('D-BF', [
'/download/index',
'type' => FilesController::TYPE_CLIENT
], [
'title' => 'List client downloads'
]);
?>
client.
They are compressed as 7zip archive. After download they should be extracted into vendor directory of D-BF client (dbf-data/vendor/).
<br> These files are mostly crackers for CPU or GPU processors. <br>
CPU cracking is enabled by default in the D-BF client. If you need to
enable GPU cracking, you should activate the proper platform in the
D-BF config file (dbf-data/config/dbf.json). After activating a
platform, the client will look for corresponding vendor file on each
start and will download it form server if it doesn't exist. But it is
strongly recommended that you download large vendor files yourself and
extract it into vendor directory of D-BF client (dbf-data/vendor/). <br>The
client also performs benchmark of active platforms on each start and
stores the results in the config file. If the benchmark result is
greater than 0, it means the activated platform works correctly on your
system. <br> The current supporting GPUs are AMD and Nvidia for both
Linux and Windows operating system. <br>
As noted in
<?php
echo Html::a('http://hashcat.net/oclhashcat', 'http://hashcat.net/oclhashcat');
?>
GPU driver requirement is:
<br> Nvidia users require ForceWare 346.59 or later <br> AMD users
require Catalyst 15.7 or later
</p> | <?php
use app\commands\FilesController;
use yii\bootstrap\Html;
?>
<p>
Vendor files may be required by
<?php
echo Html::a('D-BF', [
'/download/index',
'type' => FilesController::TYPE_CLIENT
], [
'title' => 'List client downloads'
]);
?>
client.
They are compressed as 7zip archive. After download they should be extracted into vendor directory of D-BF client (dbf-data/vendor/).
<br> These files are mostly crackers for CPU or GPU processors. <br>
CPU cracking is enabled by default in the D-BF client. If you need to
enable GPU cracking, you should activate the proper platform in the
D-BF config file (dbf-data/config/dbf.json). The current supporting
GPUs are AMD and Nvidia for both Linux and Windows operating system. <br>
As noted in
<?php
echo Html::a('http://hashcat.net/oclhashcat', 'http://hashcat.net/oclhashcat');
?>
GPU driver requirement is:
<br> Nvidia users require ForceWare 346.59 or later <br> AMD users
require Catalyst 15.7 or later
</p> |
Allow mailing lists to be permanently deleted
Summary: Allow `PhabricatorMetaMTAMailingList` to be permanently deleted with `./bin/remove destroy`.
Test Plan:
```
./bin/remove destroy PHID-MLST-nseux3r55escj573shsf
IMPORTANT: OBJECTS WILL BE PERMANENTLY DESTROYED!
There is no way to undo this operation or ever retrieve this data.
These 1 object(s) will be completely destroyed forever:
- PHID-MLST-nseux3r55escj573shsf (PhabricatorMetaMTAMailingList)
Are you absolutely certain you want to destroy these 1 object(s)? [y/N] y
Destroying objects...
Destroying PhabricatorMetaMTAMailingList PHID-MLST-nseux3r55escj573shsf...
Permanently destroyed 1 object(s).
```
Reviewers: #blessed_reviewers, epriestley
Reviewed By: #blessed_reviewers, epriestley
Subscribers: epriestley, Korvin
Differential Revision: https://secure.phabricator.com/D9979 | <?php
final class PhabricatorMetaMTAMailingList extends PhabricatorMetaMTADAO
implements
PhabricatorPolicyInterface,
PhabricatorDestructableInterface {
protected $name;
protected $email;
protected $uri;
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorMailingListPHIDTypeList::TYPECONST);
}
public function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
) + parent::getConfiguration();
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
return PhabricatorPolicies::POLICY_USER;
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
public function describeAutomaticCapability($capability) {
return null;
}
/* -( PhabricatorDestructableInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$this->openTransaction();
$this->delete();
$this->saveTransaction();
}
}
| <?php
final class PhabricatorMetaMTAMailingList extends PhabricatorMetaMTADAO
implements PhabricatorPolicyInterface {
protected $name;
protected $email;
protected $uri;
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorMailingListPHIDTypeList::TYPECONST);
}
public function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
) + parent::getConfiguration();
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
return PhabricatorPolicies::POLICY_USER;
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
public function describeAutomaticCapability($capability) {
return null;
}
}
|
Add 'use-strict' just to trigger the build | #!/usr/bin/env node
module.exports = (function() {
'use strict';
var turboLogo = require('turbo-logo'),
colors = require('colors/safe');
return {
print: finalPrint
};
/////////
function getText() {
return 'Burger JS';
}
function getBurgerAscii() {
return ' _..----.._ \r\n .\' o \'. \r\n \/ o o \\\r\n |o o o|\r\n \/\'-.._o __.-\'\\\r\n \\ ````` \/\r\n |``--........--\'`|\r\n \\ \/\r\n `\'----------\'`';
}
function finalPrint(options) {
var burger = getBurgerAscii(),
text = getText(),
color = options && options.color || 'rainbow';
console.log(colors[color](burger));
turboLogo(text, color);
}
})();
| #!/usr/bin/env node
module.exports = (function() {
var turboLogo = require('turbo-logo'),
colors = require('colors/safe');
return {
print: finalPrint
};
/////////
function getText() {
return 'Burger JS';
}
function getBurgerAscii() {
return ' _..----.._ \r\n .\' o \'. \r\n \/ o o \\\r\n |o o o|\r\n \/\'-.._o __.-\'\\\r\n \\ ````` \/\r\n |``--........--\'`|\r\n \\ \/\r\n `\'----------\'`';
}
function finalPrint(options) {
var burger = getBurgerAscii(),
text = getText(),
color = options && options.color || 'rainbow';
console.log(colors[color](burger));
turboLogo(text, color);
}
})();
|
Add static url to urlconf | """imagersite 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.conf.urls.static import static
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT
)
| """imagersite 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
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
|
Remove original_gear brand data from merchandises.json
This is a bit redundant and doesn't really add anything we don't already have. | const Updater = require('./Updater');
const SplatNet = require('../splatnet');
const { getOriginalGear } = require('../../js/splatoon');
class MerchandisesUpdater extends Updater {
constructor() {
super({
name: 'Merchandises',
filename: 'merchandises.json',
request: (splatnet) => splatnet.getMerchandises(),
rootKeys: ['merchandises'],
imagePaths: [
'$..gear.image',
'$..gear.brand.image',
'$..gear.brand.frequent_skill.image',
'$..skill.image',
],
});
}
processData(data) {
for (let merchandise of data.merchandises) {
let originalGear = getOriginalGear(merchandise.gear);
// We don't need the brand data since it should match the SplatNet gear's brand
if (originalGear)
delete originalGear.brand
merchandise.original_gear = originalGear;
}
return data;
}
}
module.exports = MerchandisesUpdater;
| const Updater = require('./Updater');
const SplatNet = require('../splatnet');
const { getOriginalGear } = require('../../js/splatoon');
class MerchandisesUpdater extends Updater {
constructor() {
super({
name: 'Merchandises',
filename: 'merchandises.json',
request: (splatnet) => splatnet.getMerchandises(),
rootKeys: ['merchandises'],
imagePaths: [
'$..gear.image',
'$..gear.brand.image',
'$..gear.brand.frequent_skill.image',
'$..skill.image',
],
});
}
processData(data) {
for (let merchandise of data.merchandises)
merchandise.original_gear = getOriginalGear(merchandise.gear);
return data;
}
}
module.exports = MerchandisesUpdater;
|
Use custom error message if email is not unique | const Sequelize = require('sequelize')
const bcrypt = require('bcrypt')
module.exports = {
model: {
name: Sequelize.STRING,
email: {
type: Sequelize.STRING,
allowNull: false,
unique: {
msg: 'username taken'
},
validate: {
isEmail: true
}
},
password: Sequelize.STRING,
photo: Sequelize.STRING,
verifiedEmail: Sequelize.BOOLEAN,
emailToken: Sequelize.STRING,
emailTokenExpires: Sequelize.DATE,
permission: {
type: Sequelize.STRING,
defaultValue: 'admin'
}
},
options: {
freezeTableName: true,
setterMethods: {
password: function(value) {
const salt = bcrypt.genSaltSync()
const hash = bcrypt.hashSync(value, salt)
this.setDataValue('password', hash)
}
},
instanceMethods: {
validPassword: function(password) {
return bcrypt.compareSync(password, this.password)
}
}
},
relations: [
['belongsToMany', 'hub', {
through: 'userHub'
}]
]
}
| const Sequelize = require('sequelize')
const bcrypt = require('bcrypt')
module.exports = {
model: {
name: Sequelize.STRING,
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: Sequelize.STRING,
photo: Sequelize.STRING,
verifiedEmail: Sequelize.BOOLEAN,
emailToken: Sequelize.STRING,
emailTokenExpires: Sequelize.DATE,
permission: {
type: Sequelize.STRING,
defaultValue: 'admin'
}
},
options: {
freezeTableName: true,
setterMethods: {
password: function(value) {
const salt = bcrypt.genSaltSync()
const hash = bcrypt.hashSync(value, salt)
this.setDataValue('password', hash)
}
},
instanceMethods: {
validPassword: function(password) {
return bcrypt.compareSync(password, this.password)
}
}
},
relations: [
['belongsToMany', 'hub', {
through: 'userHub'
}]
]
}
|
Change binary benchmark to loop forever too | import socket
import time
import random
import struct
NUM = 1024 * 1024
KEYS = ["test", "foobar", "zipzap"]
VALS = [32, 100, 82, 101, 5, 6, 42, 73]
BINARY_HEADER = struct.Struct("<BBHd")
BIN_TYPES = {"kv": 1, "c": 2, "ms": 3}
def format(key, type, val):
"Formats a binary message for statsite"
key = str(key)
key_len = len(key) + 1
type_num = BIN_TYPES[type]
header = BINARY_HEADER.pack(170, type_num, key_len, float(val))
mesg = header + key + "\0"
return mesg
METS = []
for x in xrange(NUM):
key = random.choice(KEYS)
val = random.choice(VALS)
METS.append(format(key, "c", val))
s = socket.socket()
s.connect(("localhost", 8125))
start = time.time()
total = 0
while True:
current = 0
while current < len(METS):
msg = "".join(METS[current:current + 1024])
current += 1024
total += 1024
s.sendall(msg)
diff = time.time() - start
ops_s = total / diff
print "%0.2f sec\t - %.0f ops/sec" % (diff, ops_s)
| import socket
import time
import random
import struct
NUM = 1024 * 1024 * 4
KEYS = ["test", "foobar", "zipzap"]
VALS = [32, 100, 82, 101, 5, 6, 42, 73]
BINARY_HEADER = struct.Struct("<BBHd")
BIN_TYPES = {"kv": 1, "c": 2, "ms": 3}
def format(key, type, val):
"Formats a binary message for statsite"
key = str(key)
key_len = len(key) + 1
type_num = BIN_TYPES[type]
header = BINARY_HEADER.pack(170, type_num, key_len, float(val))
mesg = header + key + "\0"
return mesg
METS = []
for x in xrange(NUM):
key = random.choice(KEYS)
val = random.choice(VALS)
METS.append(format(key, "c", val))
s = socket.socket()
s.connect(("localhost", 8125))
start = time.time()
current = 0
while current < len(METS):
msg = "".join(METS[current:current + 1024])
current += 1024
s.sendall(msg)
s.close()
end = time.time()
print NUM / (end - start), "ops/sec", (end - start), "sec"
|
Implement eslint suggestion around equals comparison | /*!
* Copyright 2015 Geoscience Australia (http://www.ga.gov.au/copyright.html)
*/
(function(angular) {
'use strict';
angular.module("icsm.toolbar", [])
.directive("icsmToolbar", [function() {
return {
controller: 'toolbarLinksCtrl'
};
}])
/**
* Override the default mars tool bar row so that a different implementation of the toolbar can be used.
*/
.directive('icsmToolbarRow', [function() {
return {
scope:{
map:"="
},
restrict:'AE',
templateUrl:'icsm/toolbar/toolbar.html'
};
}])
.directive('icsmToolbarInfo', [function() {
return {
templateUrl: 'radwaste/toolbar/toolbarInfo.html'
};
}])
.controller("toolbarLinksCtrl", ["$scope", "configService", function($scope, configService) {
var self = this;
configService.getConfig().then(function(config) {
self.links = config.toolbarLinks;
});
$scope.item = "";
$scope.toggleItem = function(item) {
$scope.item = ($scope.item === item) ? "" : item;
};
}]);
})(angular); | /*!
* Copyright 2015 Geoscience Australia (http://www.ga.gov.au/copyright.html)
*/
(function(angular) {
'use strict';
angular.module("icsm.toolbar", [])
.directive("icsmToolbar", [function() {
return {
controller: 'toolbarLinksCtrl'
};
}])
/**
* Override the default mars tool bar row so that a different implementation of the toolbar can be used.
*/
.directive('icsmToolbarRow', [function() {
return {
scope:{
map:"="
},
restrict:'AE',
templateUrl:'icsm/toolbar/toolbar.html'
};
}])
.directive('icsmToolbarInfo', [function() {
return {
templateUrl: 'radwaste/toolbar/toolbarInfo.html'
};
}])
.controller("toolbarLinksCtrl", ["$scope", "configService", function($scope, configService) {
var self = this;
configService.getConfig().then(function(config) {
self.links = config.toolbarLinks;
});
$scope.item = "";
$scope.toggleItem = function(item) {
$scope.item = ($scope.item == item) ? "" : item;
};
}]);
})(angular); |
Use start/stop in the applet. | package com.nullprogram.maze;
import java.awt.Dimension;
import javax.swing.JApplet;
public class MazeApplet extends JApplet {
private static final long serialVersionUID = 7742407602430714892L;
private int cellSize = 15;
private int speed = 10;
private Maze maze;
private MazeDisplay display;
private MazeSolve solution;
public void init() {
Dimension size = getSize();
maze = new Maze((int) (size.getWidth() / cellSize),
(int) (size.getHeight() / cellSize));
display = new MazeDisplay(maze, cellSize);
add(display);
solution = new MazeSolve(maze, display, speed);
}
public void start() {
solution.start();
}
public void stop() {
solution.stop();
}
public void destroy() {
stop();
}
}
| package com.nullprogram.maze;
import java.awt.Dimension;
import javax.swing.JApplet;
public class MazeApplet extends JApplet {
private static final long serialVersionUID = 7742407602430714892L;
private int cellSize = 15;
private int speed = 10;
private Maze maze;
private MazeDisplay display;
private MazeSolve solution;
public void init() {
Dimension size = getSize();
maze = new Maze((int) (size.getWidth() / cellSize),
(int) (size.getHeight() / cellSize));
display = new MazeDisplay(maze, cellSize);
add(display);
solution = new MazeSolve(maze, display, speed);
}
}
|
Add code to write collected JSON. This code does not affect current test result but tester get chance to see output | 'use strict';
var jf = require('../../'),
expect = require('chai').expect,
fs = require('fs'),
path = require('path');
const obj1 = { msg: 'This is 1' };
const obj2 = { msg: 'This is 2' };
const objToIgnore = { msg: 'ignored' };
describe('Event executer ', function () {
it('works without error', function (done) {
jf
.event(
function( receiveListner, stopListener ){
setTimeout(() => {
receiveListner( obj1 );
setTimeout(() => {
receiveListner( obj2 );
stopListener();
receiveListner( objToIgnore );
}, 200 );
}, 200 );
},
function( obj ) { return './' + Math.random() + '.json'; } ,
function( err ){ console.log(err); }
)
.collect(
function(obj){
expect( obj[0] ).to.be.eql( obj1 );
expect( obj[1] ).to.be.eql( obj2 );
expect( obj.length ).to.be.equal( 2 );
done();
return obj;
},
'./' + Math.random() + '.json',
function(err){ console.log(err); }
)
.exec();
});
});
| 'use strict';
var jf = require('../../'),
expect = require('chai').expect,
fs = require('fs'),
path = require('path');
const obj1 = { msg: 'This is 1' };
const obj2 = { msg: 'This is 2' };
const objToIgnore = { msg: 'ignored' };
describe('Event executer ', function () {
it('works without error', function (done) {
jf
.event(
function( receiveListner, stopListener ){
setTimeout(() => {
receiveListner( obj1 );
setTimeout(() => {
receiveListner( obj2 );
stopListener();
receiveListner( objToIgnore );
}, 200 );
}, 200 );
},
function( obj ) { return './' + Math.random() + '.json'; } ,
function( err ){ console.log(err); }
)
.collect(
function(obj){
expect( obj[0] ).to.be.eql( obj1 );
expect( obj[1] ).to.be.eql( obj2 );
expect( obj.length ).to.be.equal( 2 );
done();
},
'./' + Math.random() + '.json',
function(err){ console.log(err); }
)
.exec();
});
});
|
Clone sidebar to bottom for phone display
Signed-off-by: Herman Banken <a70bbf187a5275b5d5ff0f9d438a50197e0c274d@gmail.com> | <?php get_template_part('templates/part/head'); ?>
<body <?php body_class(); ?>>
<!--[if lt IE 7]><div class="alert">Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</div><![endif]-->
<div class="wrap">
<div id="columnleft">
<div id="menu">
<?php get_template_part('templates/part/menu'); ?>
</div>
<div class="hidden-phone">
<?php
ob_start();
dynamic_sidebar('sidebar-menu');
$_sb = ob_get_flush();
?></div>
</div>
<div id="content" style="min-height: 300px;">
<!--<section class="quick-bar">
<?php //get_template_part('templates/quickbar'); ?>
</section>-->
<section class="articles">
<?php include roots_template_path(); ?>
<?php //include roots_sidebar_path(); ?>
</section>
</div>
<div class="visible-phone sidebar-menu-bottom"><?php echo $_sb; ?></div>
<?php get_template_part('templates/part/footer'); ?>
</div><!-- End of .wrap -->
</body>
</html>
| <?php get_template_part('templates/part/head'); ?>
<body <?php body_class(); ?>>
<!--[if lt IE 7]><div class="alert">Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</div><![endif]-->
<div class="wrap">
<div id="columnleft">
<div id="menu">
<?php get_template_part('templates/part/menu'); ?>
</div>
<?php dynamic_sidebar('sidebar-menu'); ?>
</div>
<div id="content" style="min-height: 300px;">
<!--<section class="quick-bar">
<?php //get_template_part('templates/quickbar'); ?>
</section>-->
<section class="articles">
<?php include roots_template_path(); ?>
<?php //include roots_sidebar_path(); ?>
</section>
</div>
<?php get_template_part('templates/part/footer'); ?>
</div><!-- End of .wrap -->
</body>
</html>
|
Add Emoji list of `Binary_Property`s | const {
assemble,
writeFile,
unicodeVersion
} = require('./utils.js');
// This includes only the binary properties required by UTS18 RL1.2 for level 1 Unicode regex
// support, minus `Assigned` which has special handling since it is the inverse of Unicode category
// `Unassigned`. To include all binary properties, change this to:
// `const properties = require(`${unicodeVersion}`).Binary_Property;`
const properties = [
'ASCII',
'Alphabetic',
'Any',
'Default_Ignorable_Code_Point',
'Emoji',
'Lowercase',
'Noncharacter_Code_Point',
'Uppercase',
'White_Space'
];
const result = [];
for (const property of properties) {
const codePoints = require(`${unicodeVersion}/Binary_Property/${property}/code-points.js`);
result.push(assemble({
name: property,
codePoints
}));
}
writeFile('properties.js', result);
| const {
assemble,
writeFile,
unicodeVersion
} = require('./utils.js');
// This includes only the binary properties required by UTS18 RL1.2 for level 1 Unicode regex
// support, minus `Assigned` which has special handling since it is the inverse of Unicode category
// `Unassigned`. To include all binary properties, change this to:
// `const properties = require(`${unicodeVersion}`).Binary_Property;`
const properties = [
'ASCII',
'Alphabetic',
'Any',
'Default_Ignorable_Code_Point',
'Lowercase',
'Noncharacter_Code_Point',
'Uppercase',
'White_Space'
];
const result = [];
for (const property of properties) {
const codePoints = require(`${unicodeVersion}/Binary_Property/${property}/code-points.js`);
result.push(assemble({
name: property,
codePoints
}));
}
writeFile('properties.js', result);
|
Add "where" to top level dask.array module | from __future__ import absolute_import, division, print_function
from ..utils import ignoring
from .core import (Array, stack, concatenate, tensordot, transpose, from_array,
choose, where, coarsen, constant, fromfunction, compute, unique, store)
from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2,
ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod,
frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians,
sin, sinh, sqrt, tan, tanh, trunc, isnull, notnull)
from .reductions import (sum, prod, mean, std, var, any, all, min, max, vnorm,
argmin, argmax,
nansum, nanmean, nanstd, nanvar, nanmin,
nanmax, nanargmin, nanargmax)
from .percentile import percentile
with ignoring(ImportError):
from .reductions import nanprod
from . import random, linalg, ghost
from .wrap import ones, zeros, empty
from ..context import set_options
| from __future__ import absolute_import, division, print_function
from ..utils import ignoring
from .core import (Array, stack, concatenate, tensordot, transpose, from_array,
choose, coarsen, constant, fromfunction, compute, unique, store)
from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2,
ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod,
frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians,
sin, sinh, sqrt, tan, tanh, trunc, isnull, notnull)
from .reductions import (sum, prod, mean, std, var, any, all, min, max, vnorm,
argmin, argmax,
nansum, nanmean, nanstd, nanvar, nanmin,
nanmax, nanargmin, nanargmax)
from .percentile import percentile
with ignoring(ImportError):
from .reductions import nanprod
from . import random, linalg, ghost
from .wrap import ones, zeros, empty
from ..context import set_options
|
Add example of using route parameters to fetch data. | import page from 'page'
import { connect } from 'react-redux'
import React, { PropTypes } from 'react'
import {
fetchExample,
deleteExample,
} from 'client/views/example-details/actions'
const connector = connect(
state => ({
route: state.route,
example: state.example,
}),
dispatch => ({
onFetchExample: id => dispatch(fetchExample(id)),
onDeleteExample: id => dispatch(deleteExample(id)),
}))
export default connector(React.createClass({
propTypes: {
example: PropTypes.object.isRequired,
onFetchExample: PropTypes.func.isRequired,
onDeleteExample: PropTypes.func.isRequired,
},
componentDidMount() {
this.props.onFetchExample(this.props.route.params.example)
},
deleteExample() {
this.props.onDeleteExample(this.props.example)
.then(() => page('/'))
},
render() {
return (
<section className="view-example-details">
<div className="app-state">
<pre>{JSON.stringify(this.props, null, 2)}</pre>
</div>
<div className="app-state-operations">
<button onClick={this.deleteExample}>Delete Example</button>
</div>
</section>
)
},
}))
| import page from 'page'
import { connect } from 'react-redux'
import React, { PropTypes } from 'react'
import {
fetchExample,
deleteExample,
} from 'client/views/example-details/actions'
const connector = connect(
state => ({
example: state.example,
}),
dispatch => ({
onFetchExample: id => dispatch(fetchExample(id)),
onDeleteExample: id => dispatch(deleteExample(id)),
}))
export default connector(React.createClass({
propTypes: {
example: PropTypes.object.isRequired,
onFetchExample: PropTypes.func.isRequired,
onDeleteExample: PropTypes.func.isRequired,
},
componentDidMount() {
this.props.onFetchExample(this.props.example)
},
deleteExample() {
this.props.onDeleteExample(this.props.example)
.then(() => page('/'))
},
render() {
return (
<section className="view-example-details">
<div className="app-state">
<pre>{JSON.stringify(this.props, null, 2)}</pre>
</div>
<div className="app-state-operations">
<button onClick={this.deleteExample}>Delete Example</button>
</div>
</section>
)
},
}))
|
BB-5745: Fix fields ACL JS component to support access_level_route parameter
- fix CS | define(function(require) {
'use strict';
var WorkflowActionPermissionsRowView;
var mediator = require('oroui/js/mediator');
var ActionPermissionsRowView = require('orouser/js/datagrid/action-permissions-row-view');
var FieldView = require('./workflow-action-permissions-field-view');
WorkflowActionPermissionsRowView = ActionPermissionsRowView.extend({
fieldItemView: FieldView,
onAccessLevelChange: function(model) {
// override to prevent marking 'Entity' permissions grid tabs as changed
mediator.trigger('securityAccessLevelsComponent:link:click', {
accessLevel: model.get('access_level'),
identityId: model.get('identity'),
permissionName: model.get('name')
});
}
});
return WorkflowActionPermissionsRowView;
});
| define(function(require) {
'use strict';
var WorkflowActionPermissionsRowView;
var _ = require('underscore');
var mediator = require('oroui/js/mediator');
var ActionPermissionsRowView = require('orouser/js/datagrid/action-permissions-row-view');
var FieldView = require('./workflow-action-permissions-field-view');
WorkflowActionPermissionsRowView = ActionPermissionsRowView.extend({
fieldItemView: FieldView,
onAccessLevelChange: function(model) {
// override to prevent marking 'Entity' permissions grid tabs as changed
mediator.trigger('securityAccessLevelsComponent:link:click', {
accessLevel: model.get('access_level'),
identityId: model.get('identity'),
permissionName: model.get('name')
});
}
});
return WorkflowActionPermissionsRowView;
});
|
Remove settle_time kwarg from c700
This kwarg has been removed from ophyd, but will be coming back (and be
functional) soon. Revert these changes when that happens: ophyd 0.2.1) | from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO
from ophyd import Component as C
from ophyd.device import DeviceStatus
class CS700TemperatureController(PVPositioner):
setpoint = C(EpicsSignal, 'T-SP')
readback = C(EpicsSignalRO, 'T-I')
done = C(EpicsSignalRO, 'Cmd-Busy')
stop_signal = C(EpicsSignal, 'Cmd-Cmd')
def trigger(self):
# There is nothing to do. Just report that we are done.
# Note: This really should not necessary to do --
# future changes to PVPositioner may obviate this code.
status = DeviceStatus()
status._finished()
return status
cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700')
# this functionality never worked, has now been removed, but will shortly be
# coming back
# settle_time=10)
cs700.done_value = 0
cs700.read_attrs = ['setpoint', 'readback']
cs700.readback.name = 'temperautre'
cs700.setpoint.name = 'temperautre_setpoint'
| from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO
from ophyd import Component as C
from ophyd.device import DeviceStatus
class CS700TemperatureController(PVPositioner):
setpoint = C(EpicsSignal, 'T-SP')
readback = C(EpicsSignalRO, 'T-I')
done = C(EpicsSignalRO, 'Cmd-Busy')
stop_signal = C(EpicsSignal, 'Cmd-Cmd')
def trigger(self):
# There is nothing to do. Just report that we are done.
# Note: This really should not necessary to do --
# future changes to PVPositioner may obviate this code.
status = DeviceStatus()
status._finished()
return status
cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700',
settle_time=10)
cs700.done_value = 0
cs700.read_attrs = ['setpoint', 'readback']
cs700.readback.name = 'temperautre'
cs700.setpoint.name = 'temperautre_setpoint'
|
Improve comannd line help for config option | // Load optional local-config file
"use strict"
/* eslint-env node */
/* jslint node: true */
const log = require("./log")
const configDefault = require("./configDefault")
const yargs = require("yargs")
let localConfig = {}
const argv = yargs.option({
config: {
describe: "use different config file then config-local.js"
}
}).help().argv
console.log("yargs.argv", argv)
try {
log("info", "Loading config file")
if (!argv.config) {
localConfig = require("../../local-config")
} else {
localConfig = require("../../" + argv.config)
}
} catch (e) {
if (e.code === "MODULE_NOT_FOUND") {
log("info", "No config file found, so using defaults")
} else {
log("error", "Problem when loading config file:", e)
throw e
}
}
const config = Object.assign({}, configDefault, localConfig)
module.exports = {
config
}
| // Load optional local-config file
"use strict"
/* eslint-env node */
/* jslint node: true */
const log = require("./log")
const configDefault = require("./configDefault")
const argv = require("yargs").argv
console.log("argv", argv)
let localConfig = {}
try {
log("info", "Loading config file")
if (!argv.config) {
localConfig = require("../../local-config")
} else {
localConfig = require("../../" + argv.config)
}
} catch (e) {
if (e.code === "MODULE_NOT_FOUND") {
log("info", "No config file found -- using defaults")
} else {
log("error", "Problem when loading config file:", e)
throw e
}
}
const config = Object.assign({}, configDefault, localConfig)
module.exports = {
config
}
|
ACCESS TOKEN FIX FINALLY :sweat_drops: | (function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
alert("Sign in Successful");
$.ajax({
url: "https://www.googleapis.com/plus/v1/people/me?access_token="+authResult["access_token"],
type: 'GET',
dataType: 'json',
success: function(data) {
//do something with the data
},
});
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
alert("Sign in failed");
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
} | (function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
alert("Sign in Successful");
$.ajax({
url: "https://www.googleapis.com/plus/v1/people/me",
type: 'GET',
dataType: 'json',
success: function(data) {
alert(data);
},
});
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
alert("Sign in failed");
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
} |
Remove unnecessary @return doc for constructor | <?php
namespace Wheniwork\OAuth2\Client\Grant;
use League\OAuth2\Client\Grant\GrantInterface;
use League\OAuth2\Client\Token\AccessToken as AccessToken;
class RenewToken implements GrantInterface
{
/**
* @var string
*/
protected $accessToken;
/**
* @param AccessToken $token
*/
public function __construct(AccessToken $token = null)
{
if ($token) {
$this->accessToken = $token->accessToken;
}
}
public function __toString()
{
return 'renew_token';
}
public function prepRequestParams($defaultParams, $params)
{
if (empty($params['access_token'])) {
if (!$this->accessToken) {
throw new \BadMethodCallException('Missing access_token');
}
$params['access_token'] = $this->accessToken;
}
return array_merge($defaultParams, $params);
}
public function handleResponse($response = [])
{
return new AccessToken($response);
}
}
| <?php
namespace Wheniwork\OAuth2\Client\Grant;
use League\OAuth2\Client\Grant\GrantInterface;
use League\OAuth2\Client\Token\AccessToken as AccessToken;
class RenewToken implements GrantInterface
{
/**
* @var string
*/
protected $accessToken;
/**
* @param AccessToken $token
* @return void
*/
public function __construct(AccessToken $token = null)
{
if ($token) {
$this->accessToken = $token->accessToken;
}
}
public function __toString()
{
return 'renew_token';
}
public function prepRequestParams($defaultParams, $params)
{
if (empty($params['access_token'])) {
if (!$this->accessToken) {
throw new \BadMethodCallException('Missing access_token');
}
$params['access_token'] = $this->accessToken;
}
return array_merge($defaultParams, $params);
}
public function handleResponse($response = [])
{
return new AccessToken($response);
}
}
|
Remove template strings for node compatibility | var CLIEngine = require('eslint').CLIEngine;
var chalk = require('chalk');
var cli = new CLIEngine({});
var format = '';
module.exports = function (paths, options) {
if (options && options.formatter) {
format = options.formatter;
}
describe('eslint', function () {
paths.forEach(function (p) {
it('should have no errors in ' + p, function () {
try {
var report = cli.executeOnFiles([p]);
var formatter = cli.getFormatter(format);
} catch (err) {
throw new Error(err);
}
if (
report &&
report.errorCount > 0
) {
throw new Error(
`${chalk.red('Code did not pass lint rules')}
${formatter(report.results)}`
);
}
});
});
});
};
| var CLIEngine = require('eslint').CLIEngine;
var chalk = require('chalk');
var cli = new CLIEngine({});
var format = '';
module.exports = function (paths, options) {
if (options && options.formatter) {
format = options.formatter;
}
describe('eslint', function () {
paths.forEach(function (p) {
it(`should have no errors in ${p}`, function () {
try {
var report = cli.executeOnFiles([p]);
var formatter = cli.getFormatter(format);
} catch (err) {
throw new Error(err);
}
if (
report &&
report.errorCount > 0
) {
throw new Error(
`${chalk.red('Code did not pass lint rules')}
${formatter(report.results)}`
);
}
});
});
});
};
|
Fix wrong public URL for static in webpack
After a recent change, `STATIC_URL` is now `assets` in the webapp.
The webpack config has not been updated though, and the frontend was trying an old URL. | /* eslint-disable */
const path = require('path');
const webpack = require('webpack');
const makeConfig = require('./config.base');
// The app/ dir
const app_root = path.resolve(__dirname, '..');
const filenameTemplate = 'webapp/[name]';
const config = makeConfig({
filenameTemplate: filenameTemplate,
mode: 'development',
devtool: 'eval-source-map',
namedModules: true,
minimize: false,
// Needed for inline CSS (via JS) - see set-public-path.js for more info
prependSources: [path.resolve(app_root, 'webpack', 'set-public-path.js')],
// This must be same as Django's STATIC_URL setting
publicPath: '/assets/',
plugins: [],
performance: {
hints: 'warning',
},
});
console.log("Using DEV config");
module.exports = config;
| /* eslint-disable */
const path = require('path');
const webpack = require('webpack');
const makeConfig = require('./config.base');
// The app/ dir
const app_root = path.resolve(__dirname, '..');
const filenameTemplate = 'webapp/[name]';
const config = makeConfig({
filenameTemplate: filenameTemplate,
mode: 'development',
devtool: 'eval-source-map',
namedModules: true,
minimize: false,
// Needed for inline CSS (via JS) - see set-public-path.js for more info
prependSources: [path.resolve(app_root, 'webpack', 'set-public-path.js')],
// This must be same as Django's STATIC_URL setting
publicPath: '/static/',
plugins: [],
performance: {
hints: 'warning',
},
});
console.log("Using DEV config");
module.exports = config;
|
Refactor command to find cases by default | from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
self._setup()
two_years = self.now - relativedelta(years=2)
return Case.objects.filter(created__lte=two_years).exclude(log__created__gte=two_years)
class Command(BaseCommand):
help = (
"Find or delete cases that are 2 years old or over that were not deleted prior to the task command being fixed"
)
def handle(self, *args, **kwargs):
instance = FindAndDeleteCasesUsingCreationTime()
if len(args) == 0:
cases = instance.get_eligible_cases()
print(cases.count())
elif args[0] == "delete":
instance.run()
| from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
super(FindAndDeleteCasesUsingCreationTime, self)._setup()
two_years = self.now - relativedelta(years=2)
return Case.objects.filter(created__lte=two_years).exclude(log__created__gte=two_years)
class Command(BaseCommand):
help = (
"Find or delete cases that are 2 years old or over that were not deleted prior to the task command being fixed"
)
def handle(self, *args, **kwargs):
if args[0] == "find":
cases = FindAndDeleteCasesUsingCreationTime().get_eligible_cases()
print(cases)
print(cases.count())
if args[0] == "delete":
FindAndDeleteCasesUsingCreationTime().run()
|
Fix drop_connection for the default connection
While `get_connection()` used `get_default_connection()` if there is no specific connection,
(aka `$name = null`) , `drop_connection()` didn't and therefore did not drop a connection
if no specific name was given.
In `Table::reestablish_connection()` the connection (name) is retrieved like this:
$connection = $this->class->getStaticPropertyValue('connection',null);
This meant that if no static property 'connection' is set, the `$connection` will be `null`.
This should mean that the default connection is use, but currently nothing will be
dropped, which is a bug.
This fix changes that, so that if the default connection is used, the default connection is dropped.
An alternative might have been to change this in the call
(`Table::reestablish_connection()` for instance), but it seems to me that keeping
`drop_connection`'s behaviour the same as `get_connection()` is the best way. | <?php
/**
* @package ActiveRecord
*/
namespace ActiveRecord;
/**
* Singleton to manage any and all database connections.
*
* @package ActiveRecord
*/
class ConnectionManager extends Singleton
{
/**
* Array of {@link Connection} objects.
* @var array
*/
static private $connections = array();
/**
* If $name is null then the default connection will be returned.
*
* @see Config
* @param string $name Optional name of a connection
* @return Connection
*/
public static function get_connection($name=null)
{
$config = Config::instance();
$name = $name ? $name : $config->get_default_connection();
if (!isset(self::$connections[$name]) || !self::$connections[$name]->connection)
self::$connections[$name] = Connection::instance($config->get_connection($name));
return self::$connections[$name];
}
/**
* Drops the connection from the connection manager. Does not actually close it since there
* is no close method in PDO.
*
* If $name is null then the default connection will be returned.
*
* @param string $name Name of the connection to forget about
*/
public static function drop_connection($name=null)
{
$config = Config::instance();
$name = $name ? $name : $config->get_default_connection();
if (isset(self::$connections[$name]))
unset(self::$connections[$name]);
}
} | <?php
/**
* @package ActiveRecord
*/
namespace ActiveRecord;
/**
* Singleton to manage any and all database connections.
*
* @package ActiveRecord
*/
class ConnectionManager extends Singleton
{
/**
* Array of {@link Connection} objects.
* @var array
*/
static private $connections = array();
/**
* If $name is null then the default connection will be returned.
*
* @see Config
* @param string $name Optional name of a connection
* @return Connection
*/
public static function get_connection($name=null)
{
$config = Config::instance();
$name = $name ? $name : $config->get_default_connection();
if (!isset(self::$connections[$name]) || !self::$connections[$name]->connection)
self::$connections[$name] = Connection::instance($config->get_connection($name));
return self::$connections[$name];
}
/**
* Drops the connection from the connection manager. Does not actually close it since there
* is no close method in PDO.
*
* @param string $name Name of the connection to forget about
*/
public static function drop_connection($name=null)
{
if (isset(self::$connections[$name]))
unset(self::$connections[$name]);
}
} |
Support for Python 2.7 and PyPy in the classifiers!
✨ | import sys
from setuptools import setup, find_packages
# defines __version__
exec(open("h11/_version.py").read())
setup(
name="h11",
version=__version__,
description=
"A pure-Python, bring-your-own-I/O implementation of HTTP/1.1",
long_description=open("README.rst").read(),
author="Nathaniel J. Smith",
author_email="njs@pobox.com",
license="MIT",
packages=find_packages(),
url="https://github.com/njsmith/h11",
# This means, just install *everything* you see under zs/, even if it
# doesn't look like a source file, so long as it appears in MANIFEST.in:
include_package_data=True,
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"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",
"Topic :: Internet :: WWW/HTTP",
"Topic :: System :: Networking",
],
)
| import sys
from setuptools import setup, find_packages
# defines __version__
exec(open("h11/_version.py").read())
setup(
name="h11",
version=__version__,
description=
"A pure-Python, bring-your-own-I/O implementation of HTTP/1.1",
long_description=open("README.rst").read(),
author="Nathaniel J. Smith",
author_email="njs@pobox.com",
license="MIT",
packages=find_packages(),
url="https://github.com/njsmith/h11",
# This means, just install *everything* you see under zs/, even if it
# doesn't look like a source file, so long as it appears in MANIFEST.in:
include_package_data=True,
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Internet :: WWW/HTTP",
"Topic :: System :: Networking",
],
)
|
Allow Expression to be called as a Shuntless alternative to ScanExpression | package compiler
type Expression struct {
Name Translatable
OnScan func(*Compiler) Type
Detect func(*Compiler) *Type
}
func (c *Compiler) Expression() Type {
var token = c.Scan()
for _, expression := range c.Expressions {
if expression.Name[c.Language] == token {
return expression.OnScan(c)
}
}
for _, expression := range c.Expressions {
if expression.Detect != nil {
if t := expression.Detect(c); t != nil {
return *t
}
}
}
return Type{Name: NoTranslation(c.Token()), Fake: true}
}
func (c *Compiler) ScanExpression() Type {
var result = c.Shunt(c.Expression(), 0)
if result.Fake {
c.RaiseError(Translatable{
English: "Unknown Expression: "+result.Name[c.Language],
})
}
return result
}
| package compiler
type Expression struct {
Name Translatable
OnScan func(*Compiler) Type
Detect func(*Compiler) *Type
}
func (c *Compiler) scanExpression() Type {
var token = c.Scan()
for _, expression := range c.Expressions {
if expression.Name[c.Language] == token {
return expression.OnScan(c)
}
}
for _, expression := range c.Expressions {
if expression.Detect != nil {
if t := expression.Detect(c); t != nil {
return *t
}
}
}
return Type{Name: NoTranslation(c.Token()), Fake: true}
}
func (c *Compiler) ScanExpression() Type {
var result = c.Shunt(c.scanExpression(), 0)
if result.Fake {
c.RaiseError(Translatable{
English: "Unknown Expression: "+result.Name[c.Language],
})
}
return result
}
|
Fix to ensure that tokens is not undefined on the next iteration when the previous file was empty | 'use strict';
var glob = require('glob'),
_ = require('lodash'),
async = require('async'),
fs = require('fs'),
lex = require('./lex');
function isFile(path) {
var stat = fs.statSync(path);
return stat.isFile();
}
function getStrings(path, done) {
glob(path, function(er, files) {
var tokens = [];
files = files.filter(isFile);
async.reduce(files, tokens, function(tokens, file, next) {
fs.readFile(file, function(err, src) {
if (err) return next();
if (src.length === 0) return next(null, tokens);
tokens.push(lex(src.toString()));
return next(null, tokens);
});
}, done);
});
}
function scan(path, done) {
getStrings(path, function(err, results) {
var strings = [];
if (err) return done(err, strings);
strings = results.reduce(function(strings, result) {
return strings.concat(result);
}, []);
return done(null, _.uniq(strings).sort());
});
}
module.exports = scan;
| 'use strict';
var glob = require('glob'),
_ = require('lodash'),
async = require('async'),
fs = require('fs'),
lex = require('./lex');
function isFile(path) {
var stat = fs.statSync(path);
return stat.isFile();
}
function getStrings(path, done) {
glob(path, function(er, files) {
var tokens = [];
files = files.filter(isFile);
async.reduce(files, tokens, function(tokens, file, next) {
fs.readFile(file, function(err, src) {
if (err) return next();
if (src.length === 0) return next();
tokens.push(lex(src.toString()));
return next(null, tokens);
});
}, done);
});
}
function scan(path, done) {
getStrings(path, function(err, results) {
var strings = [];
if (err) return done(err, strings);
strings = results.reduce(function(strings, result) {
return strings.concat(result);
}, []);
return done(null, _.uniq(strings).sort());
});
}
module.exports = scan;
|
Change start-weblogic-server using jdk as default.
Code reviewed by Edwin Tang | ############################################################################
# Generic script applicable on any Operating Environments (Unix, Windows)
# ScriptName : wls_start.py
# Properties : weblogic.properties
# Author : Kevin Yuan
############################################################################
#===========================================================================
# Start server using wlst command
#===========================================================================
#startServer('%%TARGET_SERVER%%', 'eclipselink', url='t3://%%WL_HOST%%:%%WL_PORT%%', username='%%WL_USR%%', password='%%WL_PWD%%', domainDir='%%WL_DOMAIN%%', jvmArgs='-Xms256m -Xmx960m -Dweblogic.Stdout=stdout.log -Dweblogic.Stderr=stderr.log')
#===========================================================================
# Using the following instead of above "jvmarg" setting when using SUN jdk
# because jrockit doesn't support PermSize when the server run on SUN jdk
#===========================================================================
startServer('%%TARGET_SERVER%%', 'eclipselink', url='t3://%%WL_HOST%%:%%WL_PORT%%', username='%%WL_USR%%', password='%%WL_PWD%%', domainDir='%%WL_DOMAIN%%', jvmArgs='-XX:PermSize=128m -XX:MaxPermSize=256m -Dweblogic.Stdout=stdout.log -Dweblogic.Stderr=stderr.log')
#===========================================================================
# Add the following jvmarg(s) into wlst command when you try to debug
#===========================================================================
#-Xdebug
#-Xnoagent
#-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=4000
| ############################################################################
# Generic script applicable on any Operating Environments (Unix, Windows)
# ScriptName : wls_start.py
# Properties : weblogic.properties
# Author : Kevin Yuan
############################################################################
#===========================================================================
# Start server using wlst command
#===========================================================================
startServer('%%TARGET_SERVER%%', 'eclipselink', url='t3://%%WL_HOST%%:%%WL_PORT%%', username='%%WL_USR%%', password='%%WL_PWD%%', domainDir='%%WL_DOMAIN%%', jvmArgs='-Xms256m -Xmx960m -Dweblogic.Stdout=stdout.log -Dweblogic.Stderr=stderr.log')
#===========================================================================
# Using the following instead of above "jvmarg" setting when using SUN jdk
# because jrockit doesn't support PermSize when the server run on SUN jdk
#===========================================================================
#startServer('%%TARGET_SERVER%%', 'eclipselink', url='t3://%%WL_HOST%%:%%WL_PORT%%', username='%%WL_USR%%', password='%%WL_PWD%%', domainDir='%%WL_DOMAIN%%', jvmArgs='-XX:PermSize=128m -XX:MaxPermSize=256m -Dweblogic.Stdout=stdout.log -Dweblogic.Stderr=stderr.log')
#===========================================================================
# Add the following jvmarg(s) into wlst command when you try to debug
#===========================================================================
#-Xdebug
#-Xnoagent
#-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=4000
|
Remove Linux/android@5.1 from automated tests | var args = require('yargs').argv;
module.exports = {
extraScripts: args.dom === 'shadow' ? ['test/enable-shadow-dom.js'] : [],
registerHooks: function(context) {
// The Good
var crossPlatforms = [
'Windows 10/chrome@55',
'Windows 10/firefox@50'
];
// The Bad
var otherPlatforms = [
'OS X 10.11/iphone@9.3',
'OS X 10.11/ipad@9.3',
'Windows 10/microsoftedge@13',
'Windows 10/internet explorer@11',
'OS X 10.11/safari@10.0'
];
// run SauceLabs tests for pushes, except cases when branch contains 'quick/'
if (process.env.TRAVIS_EVENT_TYPE === 'push' && process.env.TRAVIS_BRANCH.indexOf('quick/') === -1) {
// crossPlatforms are not tested here, but in Selenium WebDriver (see .travis.yml)
context.options.plugins.sauce.browsers = otherPlatforms;
// Run SauceLabs for daily builds, triggered by cron
} else if (process.env.TRAVIS_EVENT_TYPE === 'cron') {
context.options.plugins.sauce.browsers = crossPlatforms.concat(otherPlatforms);
}
}
};
| var args = require('yargs').argv;
module.exports = {
extraScripts: args.dom === 'shadow' ? ['test/enable-shadow-dom.js'] : [],
registerHooks: function(context) {
// The Good
var crossPlatforms = [
'Windows 10/chrome@55',
'Windows 10/firefox@50'
];
// The Bad
var otherPlatforms = [
'OS X 10.11/iphone@9.3',
'OS X 10.11/ipad@9.3',
'Linux/android@5.1',
'Windows 10/microsoftedge@13',
'Windows 10/internet explorer@11',
'OS X 10.11/safari@10.0'
];
// run SauceLabs tests for pushes, except cases when branch contains 'quick/'
if (process.env.TRAVIS_EVENT_TYPE === 'push' && process.env.TRAVIS_BRANCH.indexOf('quick/') === -1) {
// crossPlatforms are not tested here, but in Selenium WebDriver (see .travis.yml)
context.options.plugins.sauce.browsers = otherPlatforms;
// Run SauceLabs for daily builds, triggered by cron
} else if (process.env.TRAVIS_EVENT_TYPE === 'cron') {
context.options.plugins.sauce.browsers = crossPlatforms.concat(otherPlatforms);
}
}
};
|
Tweak alert message on no resources. | function info_set_location(slice_id, url)
{
$.getJSON("aggregates.php", { slice_id: slice_id },
function (responseTxt, statusTxt, xhr) {
var json_agg = responseTxt;
var agg_ids = Object.keys(json_agg);
var agg_count = agg_ids.length;
if (agg_count > 0) {
for (var i = 0; i < agg_count; i++) {
url += "&am_id[]=" + agg_ids[i];
}
window.location = url;
} else {
alert("This slice has no known resources.");
}
})
.fail(function() {
alert("Unable to location sliver information for this slice.");
});
}
| function info_set_location(slice_id, url)
{
$.getJSON("aggregates.php", { slice_id: slice_id },
function (responseTxt, statusTxt, xhr) {
var json_agg = responseTxt;
var agg_ids = Object.keys(json_agg);
var agg_count = agg_ids.length;
if (agg_count > 0) {
for (var i = 0; i < agg_count; i++) {
url += "&am_id[]=" + agg_ids[i];
}
window.location = url;
} else {
alert("Slice has no sliver information");
}
})
.fail(function() {
alert("Unable to location sliver information for this slice.");
});
}
|
Fix small property rename issue after rebase. | import React from 'react';
function applyProperties(text, properties) {
// TODO: support more than 1 property
const property = properties[0];
return React.createElement('p', null, [
React.createElement('span', null, text.substring(0, property.offsets.start)),
React.createElement(property.type, null, text.substring(property.offsets.start, property.offsets.end)),
React.createElement('span', null, text.substring(property.offsets.end)),
]);
}
export default function paragraphObjetToReact(paragraph, level) {
if (!paragraph.inlineProperties || paragraph.inlineProperties.length === 0) {
return React.createElement(
'p',
{
className: 'c_print-view__paragraph',
'data-level': level,
},
paragraph.text,
);
}
return applyProperties(paragraph.text, paragraph.inlineProperties);
}
| import React from 'react';
function applyProperties(text, properties) {
// TODO: support more than 1 property
const property = properties[0];
return React.createElement('p', null, [
React.createElement('span', null, text.substring(0, property.offSets.start)),
React.createElement(property.type, null, text.substring(property.offSets.start, property.offSets.end)),
React.createElement('span', null, text.substring(property.offSets.end)),
]);
}
export default function paragraphObjetToReact(paragraph, level) {
if (!paragraph.inlineProperties || paragraph.inlineProperties.length === 0) {
return React.createElement(
'p',
{
className: 'c_print-view__paragraph',
'data-level': level,
},
paragraph.text,
);
}
return applyProperties(paragraph.text, paragraph.inlineProperties);
}
|
Test now extends new base unit-test-case | <?php
use Faker\Factory as FakerFactory;
/**
* Class Collection Test Case
*
* Base test case class for most collection tests
*
* @author Alin Eugen Deac <aedart@gmail.com>
* @package unit\collection
*/
abstract class CollectionTestCase extends UnitTestCase
{
/*********************************************************************************
* Helpers
********************************************************************************/
/**
* Returns a list of key => value pairs, where the keys are
* unique
*
* @return array
*/
protected function getListOfKeyValuePairs(){
return [
$this->faker->unique()->word => $this->faker->boolean(),
$this->faker->unique()->word => $this->faker->sentence(),
$this->faker->unique()->word => $this->faker->randomNumber(),
];
}
/*********************************************************************************
* Actual tests
********************************************************************************/
} | <?php
use Faker\Factory as FakerFactory;
/**
* Class Collection Test Case
*
* Base test case class for most collection tests
*
* @author Alin Eugen Deac <aedart@gmail.com>
* @package unit\collection
*/
abstract class CollectionTestCase extends \Codeception\TestCase\Test
{
/**
* @var \UnitTester
*/
protected $tester;
/**
* Instance of faker
*
* @var \Faker\Generator
*/
protected $faker = null;
protected function _before()
{
$this->faker = FakerFactory::create();
}
protected function _after()
{
}
/*********************************************************************************
* Helpers
********************************************************************************/
/**
* Returns a list of key => value pairs, where the keys are
* unique
*
* @return array
*/
protected function getListOfKeyValuePairs(){
return [
$this->faker->unique()->word => $this->faker->boolean(),
$this->faker->unique()->word => $this->faker->sentence(),
$this->faker->unique()->word => $this->faker->randomNumber(),
];
}
/*********************************************************************************
* Actual tests
********************************************************************************/
} |
Change minimisation example mif name | def main():
from sim import Sim
from mesh import Mesh
from energies.exchange import Exchange
from energies.demag import Demag
from energies.zeeman import Zeeman
from drivers import evolver
# Mesh specification.
lx = ly = lz = 50e-9 # x, y, and z dimensions (m)
dx = dy = dz = 5e-9 # x, y, and z cell dimensions (m)
Ms = 8e5 # saturation magnetisation (A/m)
A = 1e-11 # exchange energy constant (J/m)
H = (1e3, 0, 0) # external magnetic field (A/m)
m_init = (0, 0, 1) # initial magnetisation
# Create a mesh.
mesh = Mesh((lx, ly, lz), (dx, dy, dz))
# Create a simulation object.
sim = Sim(mesh, Ms, name='minimisation_example', debug=True)
# Add energies.
sim.add_energy(Exchange(A))
sim.add_energy(Demag())
sim.add_energy(Zeeman(H))
sim.add_evolver(evolver.Minimiser(m_init, Ms, 'test'))
# Set initial magnetisation.
# Run simulation.
sim.minimise()
print("Done")
if __name__ == "__main__":
main()
| def main():
from sim import Sim
from mesh import Mesh
from energies.exchange import Exchange
from energies.demag import Demag
from energies.zeeman import Zeeman
from drivers import evolver
# Mesh specification.
lx = ly = lz = 50e-9 # x, y, and z dimensions (m)
dx = dy = dz = 5e-9 # x, y, and z cell dimensions (m)
Ms = 8e5 # saturation magnetisation (A/m)
A = 1e-11 # exchange energy constant (J/m)
H = (1e3, 0, 0) # external magnetic field (A/m)
m_init = (0, 0, 1) # initial magnetisation
# Create a mesh.
mesh = Mesh((lx, ly, lz), (dx, dy, dz))
# Create a simulation object.
sim = Sim(mesh, Ms, name='small_example_min', debug=True)
# Add energies.
sim.add_energy(Exchange(A))
sim.add_energy(Demag())
sim.add_energy(Zeeman(H))
sim.add_evolver(evolver.Minimiser(m_init, Ms, 'test'))
# Set initial magnetisation.
# Run simulation.
sim.minimise()
print("Done")
if __name__ == "__main__":
main()
|
Add active flag to entities | from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.graphics import Ellipse
from engine.entity import Entity
class BaseEntity(Widget, Entity):
def __init__(self, imageStr, **kwargs):
self.active = False
Widget.__init__(self, **kwargs)
Entity.__init__(self)
with self.canvas:
self.size = (Window.width*.002*25, Window.width*.002*25)
self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size)
self.bind(pos=self.update_graphics_pos)
self.x = self.center_x
self.y = self.center_y
self.pos = (self.x, self.y)
self.rect_bg.pos = self.pos
def update(self):
self.move()
def update_graphics_pos(self, instance, value):
self.rect_bg.pos = value
def setSize(self, width, height):
self.size = (width, height)
def setPos(xpos, ypos):
self.x = xpos
self.y = ypos | from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.graphics import Ellipse
from engine.entity import Entity
class BaseEntity(Widget, Entity):
def __init__(self, imageStr, **kwargs):
Widget.__init__(self, **kwargs)
Entity.__init__(self)
with self.canvas:
self.size = (Window.width*.002*25, Window.width*.002*25)
self.rect_bg = Ellipse(source=imageStr, pos=self.pos, size=self.size)
self.bind(pos=self.update_graphics_pos)
self.x = self.center_x
self.y = self.center_y
self.pos = (self.x, self.y)
self.rect_bg.pos = self.pos
def update(self):
self.move()
def update_graphics_pos(self, instance, value):
self.rect_bg.pos = value
def setSize(self, width, height):
self.size = (width, height)
def setPos(xpos, ypos):
self.x = xpos
self.y = ypos |
Test cases for slave version check | package org.jenkins.ci.plugins.jenkinslint.check;
import hudson.model.Node;
import hudson.model.Slave;
import hudson.slaves.DumbSlave;
import hudson.slaves.JNLPLauncher;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.util.Collections;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* SlaveVersionChecker Test Case.
*
* @author Victor Martinez
*/
public class SlaveVersionCheckerTestCase {
private SlaveVersionChecker checker = new SlaveVersionChecker();
@Rule public JenkinsRule j = new JenkinsRule();
@Test public void testDefaultSlave() throws Exception {
Slave slave = createSlave("default", "", "");
assertFalse(checker.executeCheck(slave));
}
@Test public void testControlComment() throws Exception {
Slave slave = createSlave("default", "", "");
assertFalse(checker.isIgnored(slave.getNodeDescription()));
slave = createSlave("default", "#lint:ignore:" + checker.getClass().getSimpleName(), "");
assertTrue(checker.isIgnored(slave.getNodeDescription()));
}
private Slave createSlave(String name, String description, String label) throws Exception {
return new DumbSlave(name, description, "/wherever", "1", Node.Mode.NORMAL, label, new JNLPLauncher(), RetentionStrategy.NOOP, Collections.<NodeProperty<?>>emptyList());
}
}
| package org.jenkins.ci.plugins.jenkinslint.check;
import hudson.slaves.DumbSlave;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import static org.junit.Assert.assertTrue;
/**
* SlaveDescriptionChecker Test Case.
*
* @author Victor Martinez
*/
public class SlaveVersionCheckerTestCase {
private SlaveDescriptionChecker checker = new SlaveDescriptionChecker();
@Rule public JenkinsRule j = new JenkinsRule();
@Test public void testDefaultSlave() throws Exception {
DumbSlave slave = j.createSlave();
assertTrue(checker.executeCheck(slave));
}
@Test public void testEmptySlaveName() throws Exception {
DumbSlave slave = j.createSlave();
slave.setNodeName("");
assertTrue(checker.executeCheck(slave));
}
@Test public void testSlaveDescription() throws Exception {
DumbSlave slave = j.createSlave();
slave.setNodeName("blablabla");
assertTrue(checker.executeCheck(slave));
}
/**
@Test public void testControlComment() throws Exception {
DumbSlave slave = j.createSlave();
assertFalse(checker.isIgnored(project.getDescription()));
project.setDescription("#lint:ignore:" + checker.getClass().getSimpleName());
assertTrue(checker.isIgnored(project.getDescription()));
}*/
}
|
Edit path to config.json in require statement | 'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
| 'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/..\config\config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
|
Add some priorities on listeners | <?php
namespace Behapi\Extension\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Behat\Behat\EventDispatcher\Event\OutlineTested;
use Behat\Behat\EventDispatcher\Event\ScenarioTested;
use Behapi\Extension\Tools\LastHistory;
/**
* Listener that cleans everything once a Scenario was finished
*
* @author Baptiste Clavié <clavie.b@gmail.com>
*/
class Cleaner implements EventSubscriberInterface
{
/** @var LastHistory */
private $history;
public function __construct(LastHistory $history)
{
$this->history = $history;
}
/** {@inheritDoc} */
public static function getSubscribedEvents()
{
return [
OutlineTested::AFTER => ['clear', -99],
ScenarioTested::AFTER => ['clear', -99]
];
}
/** Resets the current history of the current client */
public function clear(): void
{
$this->history->reset();
}
}
| <?php
namespace Behapi\Extension\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Behat\Behat\EventDispatcher\Event\OutlineTested;
use Behat\Behat\EventDispatcher\Event\ScenarioTested;
use Behapi\Extension\Tools\LastHistory;
/**
* Listener that cleans everything once a Scenario was finished
*
* @author Baptiste Clavié <clavie.b@gmail.com>
*/
class Cleaner implements EventSubscriberInterface
{
/** @var LastHistory */
private $history;
public function __construct(LastHistory $history)
{
$this->history = $history;
}
/** {@inheritDoc} */
public static function getSubscribedEvents()
{
return [
OutlineTested::AFTER => 'clear',
ScenarioTested::AFTER => 'clear'
];
}
/** Resets the current history of the current client */
public function clear(): void
{
$this->history->reset();
}
}
|
Fix definition files not generating | const gulp = require('gulp');
const gulp_ts = require('gulp-typescript');
const gulp_tslint = require('gulp-tslint');
const gulp_sourcemaps = require('gulp-sourcemaps');
const tslint = require('tslint');
const del = require('del');
const path = require('path');
const project = gulp_ts.createProject('tsconfig.json');
const linter = tslint.Linter.createProgram('tsconfig.json');
gulp.task('default', ['lint', 'build']);
gulp.task('lint', () => {
gulp.src('./src/**/*.ts')
.pipe(gulp_tslint({
configuration: 'tslint.json',
formatter: 'prose',
program: linter
}))
.pipe(gulp_tslint.report());
})
gulp.task('build', () => {
del.sync(['./bin/**/*.*']);
const tsCompile = gulp.src('./src/**/*.ts')
.pipe(gulp_sourcemaps.init())
.pipe(project());
tsCompile.pipe(gulp.dest('bin/'));
gulp.src('./src/**/*.js')
.pipe(gulp.dest('bin/'));
gulp.src('./src/**/*.json')
.pipe(gulp.dest('bin/'));
return tsCompile.js
.pipe(gulp_sourcemaps.write({
sourceRoot: file => path.relative(path.join(file.cwd, file.path), file.base)
}))
.pipe(gulp.dest('bin/'));
});
| const gulp = require('gulp');
const gulp_ts = require('gulp-typescript');
const gulp_tslint = require('gulp-tslint');
const gulp_sourcemaps = require('gulp-sourcemaps');
const tslint = require('tslint');
const del = require('del');
const path = require('path');
const project = gulp_ts.createProject('tsconfig.json');
const linter = tslint.Linter.createProgram('tsconfig.json');
gulp.task('default', ['lint', 'build']);
gulp.task('lint', () => {
gulp.src('./src/**/*.ts')
.pipe(gulp_tslint({
configuration: 'tslint.json',
formatter: 'prose',
program: linter
}))
.pipe(gulp_tslint.report());
})
gulp.task('build', () => {
del.sync(['./bin/**/*.*']);
const tsCompile = gulp.src('./src/**/*.ts')
.pipe(gulp_sourcemaps.init())
.pipe(project());
gulp.src('./src/**/*.js')
.pipe(gulp.dest('bin/'));
gulp.src('./src/**/*.json')
.pipe(gulp.dest('bin/'));
return tsCompile.js
.pipe(gulp_sourcemaps.write({
sourceRoot: file => path.relative(path.join(file.cwd, file.path), file.base)
}))
.pipe(gulp.dest('bin/'));
});
|
Use HTTPS for default resource icon | <?php
require_once(__DIR__ . "/inc/header.php");
$db = get_database();
$sql = "SELECT
`name`, `url`, `image_url`
FROM
`Resource`";
$resource_result = $db->query($sql);
?>
<div class="col-xs-12 col-md-offset-2 col-md-10">
<?php while ($resource_row = $resource_result->fetch_assoc()): ?>
<div class="resource-container">
<?php
$image_url = "https://assets.iu.edu/brand/2.x/trident-large.png";
if (isset($resource_row["image_url"])) {
$image_url = $resource_row["image_url"];
}
?>
<img class="resource-image" width="64" src="<?=$image_url?>" />
<span class="resource-name"><?=$resource_row["name"]?></span>
<a>
<span class="resource-url"><?=$resource_row["url"]?></span>
</a>
</div>
<?php endwhile; ?>
</div>
<?php
require_once(__DIR__ . "/inc/footer.php");
?>
| <?php
require_once(__DIR__ . "/inc/header.php");
$db = get_database();
$sql = "SELECT
`name`, `url`, `image_url`
FROM
`Resource`";
$resource_result = $db->query($sql);
?>
<div class="col-xs-12 col-md-offset-2 col-md-10">
<?php while ($resource_row = $resource_result->fetch_assoc()): ?>
<div class="resource-container">
<?php
$image_url = "http://assets.iu.edu/brand/2.x/trident-large.png";
if (isset($resource_row["image_url"])) {
$image_url = $resource_row["image_url"];
}
?>
<img class="resource-image" width="64" src="<?=$image_url?>" />
<span class="resource-name"><?=$resource_row["name"]?></span>
<a>
<span class="resource-url"><?=$resource_row["url"]?></span>
</a>
</div>
<?php endwhile; ?>
</div>
<?php
require_once(__DIR__ . "/inc/footer.php");
?>
|
Update test scan to work for new model | # coding=utf-8
try:
import unittest.mock as mock
except ImportError:
import mock
import unittest
import nessusapi.scan
class TestScan(unittest.TestCase):
def test_init(self):
fake_nessus = mock.Mock(request_single=
mock.Mock(return_value='e3b4f63f-de03-ec8b'))
scan = nessusapi.scan.Scan(fake_nessus,'192.0.2.9', 'TestScan', 5)
self.assertEqual(scan.uuid, 'e3b4f63f-de03-ec8b')
fake_nessus.request_single.assert_called_with('scan/new',
'scan', 'uuid',
target='192.0.2.9',
scan_name='TestScan',
policy_id=5)
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
# coding=utf-8
try:
import unittest.mock as mock
except ImportError:
import mock
import unittest
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from nessusapi.scan import Scan
from nessusapi.session import Session
class SessionTestCase(unittest.TestCase):
def test_init(self):
fake_session = mock.MagicMock(Session)
fake_session.request.return_value = {'uuid': 'e3b4f63f-de03-ec8b'}
scan = Scan('192.0.2.9', 'TestScan', '5', fake_session)
self.assertEqual(scan.uuid, 'e3b4f63f-de03-ec8b')
fake_session.request.assert_called_with('scan/new',
target='192.0.2.9',
scan_name='TestScan',
policy_id='5')
if __name__ == '__main__':
unittest.main()
|
Add very basic user authentication support | module.exports = {
getConnection: getConnection
};
function getDbOpts(opts) {
opts = opts || {
host: 'localhost',
db: 'my-app',
port: 27017
};
opts.port = opts.port || 27017;
return opts;
}
function getConnection(opts, cb) {
opts = getDbOpts(opts);
var mongodb = require('mongodb'),
server = new mongodb.Server(opts.host, opts.port, {});
new mongodb.Db(opts.db, server, {safe: true}).open(function (err, db) {
if (err) {
return cb(err);
}
var complete = function(authErr, res) {
if(authErr) {
return cb(authErr);
}
var collection = new mongodb.Collection(db, 'migrations');
cb(null, {
connection: db,
migrationCollection: collection
});
};
if(opts.username) {
db.authenticate(opts.username,opts.password, {}, complete);
} else {
complete(null, null);
}
});
}
| module.exports = {
getConnection: getConnection
};
function getDbOpts(opts) {
opts = opts || {
host: 'localhost',
db: 'my-app',
port: 27017
};
opts.port = opts.port || 27017;
return opts;
}
function getConnection(opts, cb) {
opts = getDbOpts(opts);
var mongodb = require('mongodb'),
server = new mongodb.Server(opts.host, opts.port, {});
new mongodb.Db(opts.db, server, {safe: true}).open(function (err, db) {
if (err) {
return cb(err);
}
var collection = new mongodb.Collection(db, 'migrations');
cb(null, {
connection: db,
migrationCollection: collection
});
});
} |
Convert Pantheon plugin from spaces to tabs for indentation | <?php
// Only in Test and Live Environments...
if ( in_array( $_ENV['PANTHEON_ENVIRONMENT'], Array('test', 'live') ) ) {
//
// Disable Core Updates EVERYWHERE (use git upstream)
//
function _pantheon_disable_wp_updates() {
include ABSPATH . WPINC . '/version.php';
return (object) array(
'updates' => array(),
'version_checked' => $wp_version,
'last_checked' => time(),
);
}
add_filter( 'pre_site_transient_update_core', '_pantheon_disable_wp_updates' );
//
// Disable Plugin Updates
//
add_action('admin_menu','hide_admin_notices');
function hide_admin_notices() {
remove_action( 'admin_notices', 'update_nag', 3 );
}
remove_action( 'load-update-core.php', 'wp_update_plugins' );
add_filter( 'pre_site_transient_update_plugins', '_pantheon_disable_wp_updates' );
//
// Disable Theme Updates
//
remove_action( 'load-update-core.php', 'wp_update_themes' );
add_filter( 'pre_site_transient_update_themes', '_pantheon_disable_wp_updates' );
}
| <?php
// Only in Test and Live Environments...
if ( in_array( $_ENV['PANTHEON_ENVIRONMENT'], Array('test', 'live') ) ) {
//
// Disable Core Updates EVERYWHERE (use git upstream)
//
function _pantheon_disable_wp_updates() {
include ABSPATH . WPINC . '/version.php';
return (object) array(
'updates' => array(),
'version_checked' => $wp_version,
'last_checked' => time(),
);
}
add_filter( 'pre_site_transient_update_core', '_pantheon_disable_wp_updates' );
//
// Disable Plugin Updates
//
add_action('admin_menu','hide_admin_notices');
function hide_admin_notices() {
remove_action( 'admin_notices', 'update_nag', 3 );
}
remove_action( 'load-update-core.php', 'wp_update_plugins' );
add_filter( 'pre_site_transient_update_plugins', '_pantheon_disable_wp_updates' );
//
// Disable Theme Updates
//
remove_action( 'load-update-core.php', 'wp_update_themes' );
add_filter( 'pre_site_transient_update_themes', '_pantheon_disable_wp_updates' );
}
|
Use the standard Javadoc description for framework parameters | package org.tinylog.core.backend;
import org.tinylog.core.Framework;
/**
* Builder for creating {@link LoggingBackend LoggingBackends}.
*
* <p>
* This interface must be implemented by all logging backends and provided as
* {@link java.util.ServiceLoader service} in {@code META-INF/services}.
* </p>
*/
public interface LoggingBackendBuilder {
/**
* Gets the name of the logging backend, which can be used to address the logging backend in a configuration.
*
* <p>
* The name must start with a lower case ASCII letter [a-z] and end with a lower case ASCII letter [a-z] or
* digit [0-9]. Within the name, lower case letters [a-z], numbers [0-9], spaces [ ], and hyphens [-] are
* allowed.
* </p>
*
* @return The name of the logging backend
*/
String getName();
/**
* Creates a new instance of the logging backend.
*
* @param framework The actual logging framework instance
* @return New instance of the logging backend
*/
LoggingBackend create(Framework framework);
}
| package org.tinylog.core.backend;
import org.tinylog.core.Framework;
/**
* Builder for creating {@link LoggingBackend LoggingBackends}.
*
* <p>
* This interface must be implemented by all logging backends and provided as
* {@link java.util.ServiceLoader service} in {@code META-INF/services}.
* </p>
*/
public interface LoggingBackendBuilder {
/**
* Gets the name of the logging backend, which can be used to address the logging backend in a configuration.
*
* <p>
* The name must start with a lower case ASCII letter [a-z] and end with a lower case ASCII letter [a-z] or
* digit [0-9]. Within the name, lower case letters [a-z], numbers [0-9], spaces [ ], and hyphens [-] are
* allowed.
* </p>
*
* @return The name of the logging backend
*/
String getName();
/**
* Creates a new instance of the logging backend.
*
* @param framework Configuration and hooks
* @return New instance of the logging backend
*/
LoggingBackend create(Framework framework);
}
|
Remove comment from package change | package com.ejpm.euler.math.prime;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
*
* @author edgar.mateus
*/
@RunWith(Parameterized.class)
public class PrimeNumberTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{1, false}, {2, true}, {3, true}, {4, false}, {5, true}, {6, false},
{37, true}, {49, false}, {199, true}, {7919, true}, {15487039, true}, {15486725, false}
});
}
private final int number;
private final boolean isPrime;
public PrimeNumberTest(final int number, final boolean isPrime) {
this.number = number;
this.isPrime = isPrime;
}
@Test
public void checkIfPrime() {
assertThat(PrimeNumber.isPrime(number), is(equalTo(isPrime)));
}
}
| package com.ejpm.euler.math.prime;
import com.ejpm.euler.math.prime.PrimeNumber;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
*
* @author edgar.mateus
*/
@RunWith(Parameterized.class)
public class PrimeNumberTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{1, false}, {2, true}, {3, true}, {4, false}, {5, true}, {6, false},
{37, true}, {49, false}, {199, true}, {7919, true}, {15487039, true}, {15486725, false}
});
}
private final int number;
private final boolean isPrime;
public PrimeNumberTest(final int number, final boolean isPrime) {
this.number = number;
this.isPrime = isPrime;
}
@Test
public void checkIfPrime() {
assertThat(PrimeNumber.isPrime(number), is(equalTo(isPrime)));
}
}
|
Configure the extension to use django_comments | """Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_comments',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
| """Settings for Zinnia documentation"""
from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS
DATABASES = {'default': {'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'}}
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY = 'secret-key'
AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY'
TYPEPAD_SECRET_API_KEY = 'TYPEPAD_API_KEY'
BITLY_LOGIN = 'BITLY_LOGIN'
BITLY_API_KEY = 'BITLY_API_KEY'
MOLLOM_PUBLIC_KEY = 'MOLLOM_PUBLIC_KEY'
MOLLOM_PRIVATE_KEY = 'MOLLOM_PRIVATE_KEY'
INSTALLED_APPS = [
'django.contrib.sites',
'django.contrib.contenttypes',
'django.contrib.comments',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.auth',
'django_xmlrpc',
'mptt', 'tagging', 'zinnia']
|
Fix exit_on_error in case of return value | from functools import wraps
import gevent
from greenlet import GreenletExit
def exit_on_error(func):
@wraps(func)
def wrapper(*args, **kw):
try:
return func(*args, **kw)
except gevent.get_hub().SYSTEM_ERROR:
raise
except GreenletExit:
raise
except BaseException as err:
raise UnhandledError(err) from err
return wrapper
def wait_for_one_task_to_complete(pool):
if not pool:
raise ValueError("pool is empty")
with gevent.iwait(pool) as completed:
next(completed)
class UnhandledError(SystemExit):
pass
| from functools import wraps
import gevent
from greenlet import GreenletExit
def exit_on_error(func):
@wraps(func)
def wrapper(*args, **kw):
try:
func(*args, **kw)
except gevent.get_hub().SYSTEM_ERROR:
raise
except GreenletExit:
raise
except BaseException as err:
raise UnhandledError(err) from err
return wrapper
def wait_for_one_task_to_complete(pool):
if not pool:
raise ValueError("pool is empty")
with gevent.iwait(pool) as completed:
next(completed)
class UnhandledError(SystemExit):
pass
|
Fix test for returning correct value. String trimmed and parsed. | var expect = require('chai').expect;
var thirteen = require('../index.js');
describe('thirteen', function () {
it('should be a function', function () {
expect(thirteen).to.be.a("function");
});
it('should return its argument multiplied by thirteen', function () {
// Cast to number from string for test comparison. Test will pass even if value is returned with more force (i.e. "130!!!!!!!!").
var returnedAsNumber = parseFloat(thirteen(10).replace(/\!/g, ""));
expect(returnedAsNumber).to.eql(130);
});
it('should NOT return its argument multiplied by twelve', function () {
var returnedAsNumber = parseFloat(thirteen(10).replace(/\!/g, ""));
expect(returnedAsNumber).to.not.eql(120);
});
it('should return its arguments number-like value multiplied by thirteen', function () {
var wannabeString = {};
var wannabeValue = {};
wannabeString.toString = function () { return '13'; };
wannabeValue.valueOf = function () { return '13'; };
expect(thirteen(wannabeString)).to.eql(169);
expect(thirteen(wannabeValue)).to.eql(169);
});
});
| var expect = require('chai').expect;
var thirteen = require('../index.js');
describe('thirteen', function () {
it('should be a function', function () {
expect(thirteen).to.be.a("function");
});
it('should return its argument multiplied by thirteen', function () {
expect(thirteen(10)).to.eql(130);
});
it('should NOT return its argument multiplied by twelve', function () {
expect(thirteen(10)).to.not.eql(120);
});
it('should return its arguments number-like value multiplied by thirteen', function () {
var wannabeString = {};
var wannabeValue = {};
wannabeString.toString = function () { return '13'; };
wannabeValue.valueOf = function () { return '13'; };
expect(thirteen(wannabeString)).to.eql(169);
expect(thirteen(wannabeValue)).to.eql(169);
});
});
|
Fix the Configuration.Env to follow the breaking-change of the mergo library | package main
import (
"encoding/json"
"fmt"
"github.com/imdario/mergo"
"io/ioutil"
)
// Configuration is the configuration type
type Configuration struct {
Environment
Environments map[string]Environment `json:"environments"`
}
// Load open, read and parse the given configuration file
func Load(filename string) (Configuration, error) {
var c Configuration
raw, err := ioutil.ReadFile(filename)
if err != nil {
return c, err
}
err = json.Unmarshal(raw, &c)
if err != nil {
return c, err
}
return c, nil
}
// Env return the requested environment from the configuration
func (c Configuration) Env(name string) (Environment, error) {
if name == "default" {
return c.Environment, nil
}
overrides, found := c.Environments[name]
if !found {
return Environment{}, fmt.Errorf("unknown environment %s", name)
}
_ = mergo.Merge(&overrides, c.Environment) // No error can possibly occur here
return overrides, nil
}
| package main
import (
"encoding/json"
"fmt"
"github.com/imdario/mergo"
"io/ioutil"
)
// Configuration is the configuration type
type Configuration struct {
Environment
Environments map[string]Environment `json:"environments"`
}
// Load open, read and parse the given configuration file
func Load(filename string) (Configuration, error) {
var c Configuration
raw, err := ioutil.ReadFile(filename)
if err != nil {
return c, err
}
err = json.Unmarshal(raw, &c)
if err != nil {
return c, err
}
return c, nil
}
// Env return the requested environment from the configuration
func (c Configuration) Env(name string) (Environment, error) {
environment := c.Environment
if name == "default" {
return environment, nil
}
overrides, found := c.Environments[name]
if !found {
return Environment{}, fmt.Errorf("unknown environment %s", name)
}
_ = mergo.Merge(&environment, overrides) // No error can possibly occur here
return environment, nil
}
|
Change e2e challenge-solved checks to isPresent()
(as previously checked "hidden" attribute is not used any more) | protractor.expect = {
challengeSolved: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/score-board')
})
it("challenge '" + context.challenge + "' should be solved on score board", () => {
expect(element(by.id(context.challenge + '.solved')).isPresent()).toBeFalsy()
expect(element(by.id(context.challenge + '.notSolved')).isPresent()).toBeTruthy()
})
})
}
}
protractor.beforeEach = {
login: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/login')
element(by.id('email')).sendKeys(context.email)
element(by.id('password')).sendKeys(context.password)
element(by.id('loginButton')).click()
})
it('should have logged in user "' + context.email + '" with password "' + context.password + '"', () => {
expect(browser.getCurrentUrl()).toMatch(/\/search/) // TODO Instead check for uib-tooltip of <i> with fa-user-circle
})
})
}
}
| protractor.expect = {
challengeSolved: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/score-board')
})
it("challenge '" + context.challenge + "' should be solved on score board", () => {
expect(element(by.id(context.challenge + '.solved')).getAttribute('hidden')).toBeFalsy()
expect(element(by.id(context.challenge + '.notSolved')).getAttribute('hidden')).toBeTruthy()
})
})
}
}
protractor.beforeEach = {
login: function (context) {
describe('(shared)', () => {
beforeEach(() => {
browser.get('/#/login')
element(by.id('email')).sendKeys(context.email)
element(by.id('password')).sendKeys(context.password)
element(by.id('loginButton')).click()
})
it('should have logged in user "' + context.email + '" with password "' + context.password + '"', () => {
expect(browser.getCurrentUrl()).toMatch(/\/search/) // TODO Instead check for uib-tooltip of <i> with fa-user-circle
})
})
}
}
|
Check if the index is available before calling the query. | from util import hook
import elasticutils
from elasticutils import S
@hook.command
@hook.command('sf')
def symfony(inp):
if not elasticutils.get_es().indices.exists('doc-index'):
return "Index currently unavailable. Try again in a bit."
search = S().indexes('doc-index').doctypes('doc-section-type')
# cant fit more than 3 links into 1 irs message
results = search.query(tags__match=inp, title__match=inp, content__match=inp, should=True)[:3].execute()
if not len(results):
return "Sorry, seems like I can't help you with that."
topScore = results.results[0]['_score']
matches = []
print topScore
for result in results:
if result._score + 1 >= topScore:
matches.append(result.id)
if len(matches) > 1:
responseText = "These are the docs I found most relevant for you: %s"
else:
responseText = "This is what I found most relevant for you: %s"
return responseText % ', '.join(matches) | from util import hook
from elasticutils import S
@hook.command
@hook.command('sf')
def symfony(inp):
search = S().indexes('doc-index').doctypes('doc-section-type')
# cant fit more than 3 links into 1 irs message
results = search.query(tags__match=inp, title__match=inp, content__match=inp, should=True)[:3].execute()
if not len(results):
return "Sorry, seems like I can't help you with that."
topScore = results.results[0]['_score']
matches = []
print topScore
for result in results:
if result._score + 1 >= topScore:
matches.append(result.id)
if len(matches) > 1:
responseText = "These are the docs I found most relevant for you: %s"
else:
responseText = "This is what I found most relevant for you: %s"
return responseText % ', '.join(matches) |
Rename delay to lowDelay as original name conflicts with Prototype | /*
==================================================================================================
Lowland - JavaScript low level functions
Copyright (C) 2012 Sebatian Fastner
==================================================================================================
*/
/**
* #require(ext.sugar.Object)
*/
(function(window) {
var hasPostMessage = !!window.postMessage;
var slice = Array.prototype.slice;
var timeouts = [];
var messageName = "$$lowland-zero-timeout-message";
var handleMessage = function(event) {
if (event.source == window && event.data == messageName) {
lowland.bom.Events.stopPropagation(event);
if (timeouts.length > 0) {
var timeout = timeouts.shift();
timeout[0].apply(timeout[1], timeout[2]);
}
}
};
lowland.bom.Events.set(window, "message", handleMessage, true);
core.Main.addMembers("Function", {
lowDelay : function(time, context) {
var func = this;
return setTimeout(function(context, args) {
func.apply(context||this, args||[]);
}, time, context, slice.call(arguments, 2));
},
/**
* Based upon work of http://dbaron.org/log/20100309-faster-timeouts
*/
lazy : function(context) {
context = context || this;
//timeouts.push([func, slice.call(arguments,1)]);
timeouts.push([this, context, slice.call(arguments,1)]);
postMessage(messageName, "*");
}
});
})(window); | /*
==================================================================================================
Lowland - JavaScript low level functions
Copyright (C) 2012 Sebatian Fastner
==================================================================================================
*/
/**
* #require(ext.sugar.Object)
*/
(function(window) {
var hasPostMessage = !!window.postMessage;
var slice = Array.prototype.slice;
var timeouts = [];
var messageName = "$$lowland-zero-timeout-message";
var handleMessage = function(event) {
if (event.source == window && event.data == messageName) {
lowland.bom.Events.stopPropagation(event);
if (timeouts.length > 0) {
var timeout = timeouts.shift();
timeout[0].apply(timeout[1], timeout[2]);
}
}
};
lowland.bom.Events.set(window, "message", handleMessage, true);
core.Main.addMembers("Function", {
delay : function(time, context) {
var func = this;
return setTimeout(function(context, args) {
func.apply(context, args);
}, time, context, slice.call(arguments, 2));
},
/**
* Based upon work of http://dbaron.org/log/20100309-faster-timeouts
*/
lazy : function(context) {
context = context || this;
//timeouts.push([func, slice.call(arguments,1)]);
timeouts.push([this, context, slice.call(arguments,1)]);
postMessage(messageName, "*");
}
});
})(window); |
Update the js model to match the backend model | define(['backbone'], function(Backbone) {
return Backbone.Model.extend({
urlRoot: '/paste',
defaults: {
'hostname': location.hostname,
'id': null,
'owner': null,
'created_at': parseInt(new Date().getTime()/1000),
'updated_at': null,
'revision': 0,
'ttl': 432000,
'password': null,
'views': 0,
'syntax': 'none',
'line_numbers': true,
'code_folding': true,
'content': ''
},
/**
* Return a Moment object that specifies when the paste will expire
*
* @returns object
*/
expirationMoment: function() {
var startTime = this.get('last_updated_at') !== null ? this.get('last_updated_at') : this.get('created_at');
return moment.unix(startTime + parseInt(this.get('ttl')));
},
/**
* Return the URL for the paste based upon the current location
*
* @returns {string}
*/
fullURL: function() {
return document.location.protocol + '//' + document.location.hostname + '/' + this.get('id');
}
});
});
| define(['backbone'], function(Backbone) {
return Backbone.Model.extend({
urlRoot: '/paste',
defaults: {
"id": null,
"syntax": 'none',
"ttl": 432000,
"password": null,
"line_numbers": true,
"code_folding": true,
"views": 0,
"revision": 0,
"created_at": parseInt(new Date().getTime()/1000),
"last_updated_at": null,
"content": ''
},
/**
* Return a Moment object that specifies when the paste will expire
*
* @returns object
*/
expirationMoment: function() {
var startTime = this.get('last_updated_at') !== null ? this.get('last_updated_at') : this.get('created_at');
return moment.unix(startTime + parseInt(this.get('ttl')));
},
/**
* Return the URL for the paste based upon the current location
*
* @returns {string}
*/
fullURL: function() {
return document.location.protocol + '//' + document.location.hostname + '/' + this.get('id');
}
});
});
|
Fix Notification import error after reabse. | /**
* UserInputSuccessNotification component.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import Notification from '../legacy-notifications/notification';
import UserInputSuccessImage from '../../../svg/congrats.svg';
export default function UserInputSuccessNotification() {
return (
<Notification
id="user-input-success"
title={ __( 'Congrats! You set your site goals.', 'google-site-kit' ) }
description={ __( 'Now Site Kit will begin showing you suggestions how to add more metrics to your dashboard that are relevant specifically to you, based on the goals you shared.', 'google-site-kit' ) }
SmallImageSVG={ UserInputSuccessImage }
dismiss={ __( 'OK, got it!', 'google-site-kit' ) }
format="small"
/>
);
}
| /**
* UserInputSuccessNotification component.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import Notification from '../notifications/notification';
import UserInputSuccessImage from '../../../svg/congrats.svg';
export default function UserInputSuccessNotification() {
return (
<Notification
id="user-input-success"
title={ __( 'Congrats! You set your site goals.', 'google-site-kit' ) }
description={ __( 'Now Site Kit will begin showing you suggestions how to add more metrics to your dashboard that are relevant specifically to you, based on the goals you shared.', 'google-site-kit' ) }
SmallImageSVG={ UserInputSuccessImage }
dismiss={ __( 'OK, got it!', 'google-site-kit' ) }
format="small"
/>
);
}
|
Add support for the OPTIONS method | /*
* Copyright (C) 2013 Matija Mazi
*
* 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 si.mazi.rescu;
/**
* @author Matija Mazi <br>
*/
public enum HttpMethod {
GET, POST, PUT, DELETE, HEAD, OPTIONS
}
| /*
* Copyright (C) 2013 Matija Mazi
*
* 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 si.mazi.rescu;
/**
* @author Matija Mazi <br>
*/
public enum HttpMethod {
GET, POST, PUT, DELETE, HEAD
}
|
Add trailing semicolon to js file | /* global $, document */
$(function() {
$(document).on('click', '#add_membership', function(e) {
e.preventDefault();
$.ajax({
url: this,
success: function(data) {
var el_to_add;
el_to_add = $(data).html();
$('#memberships').append(el_to_add);
}
});
});
});
$(function() {
$(document).on('click', 'a.remove-new-membership', function(e) {
e.preventDefault();
$(this).parents('.membership').remove();
});
});
$(function() {
$(document).on('click', 'a.show-role-editable', function(e) {
e.preventDefault();
$(this).closest('.role-summary').hide();
$(this).closest('.membership').children('.editable-fields').show();
});
});
| /* global $, document */
$(function() {
$(document).on('click', '#add_membership', function(e) {
e.preventDefault();
$.ajax({
url: this,
success: function(data) {
var el_to_add;
el_to_add = $(data).html();
$('#memberships').append(el_to_add);
}
});
});
});
$(function() {
$(document).on('click', 'a.remove-new-membership', function(e) {
e.preventDefault();
$(this).parents('.membership').remove();
});
});
$(function() {
$(document).on('click', 'a.show-role-editable', function(e) {
e.preventDefault();
$(this).closest('.role-summary').hide();
$(this).closest('.membership').children('.editable-fields').show();
});
})
|
tests: Add test for the region reported for a failed match
If the match fails at the first level of the pyramid algorithm (when
we're searching in a down-scaled version of the frame) then we have to
up-scale the region we report for the best (but not good enough) match.
This passes currently, but there was no test for it and I want to make
sure I don't break it when I implement `stbt.match_all`. | import cv2
import numpy
from nose.tools import raises
import stbt
from _stbt.core import _load_template
def black(width=1280, height=720):
return numpy.zeros((height, width, 3), dtype=numpy.uint8)
def test_that_matchresult_image_matches_template_passed_to_match():
assert stbt.match("black.png", frame=black()).image == "black.png"
def test_that_matchresult_str_image_matches_template_passed_to_match():
assert "image=\'black.png\'" in str(stbt.match("black.png", frame=black()))
def test_that_matchresult_str_image_matches_template_passed_to_match_custom():
assert "image=<Custom Image>" in str(
stbt.match(black(30, 30), frame=black()))
def test_matchresult_region_when_first_pyramid_level_fails_to_match():
f = _imread("videotestsrc-full-frame.png")
assert stbt.Region(184, 0, width=92, height=160) == stbt.match(
"videotestsrc-redblue-flipped.png", frame=f).region
@raises(ValueError)
def test_that_match_rejects_greyscale_template():
grey = cv2.cvtColor(_load_template("black.png").image, cv2.cv.CV_BGR2GRAY)
stbt.match(grey, frame=black())
| import cv2
import numpy
from nose.tools import raises
import stbt
from _stbt.core import _load_template
def black(width=1280, height=720):
return numpy.zeros((height, width, 3), dtype=numpy.uint8)
def test_that_matchresult_image_matches_template_passed_to_match():
assert stbt.match("black.png", frame=black()).image == "black.png"
def test_that_matchresult_str_image_matches_template_passed_to_match():
assert "image=\'black.png\'" in str(stbt.match("black.png", frame=black()))
def test_that_matchresult_str_image_matches_template_passed_to_match_custom():
assert "image=<Custom Image>" in str(
stbt.match(black(30, 30), frame=black()))
@raises(ValueError)
def test_that_match_rejects_greyscale_template():
grey = cv2.cvtColor(_load_template("black.png").image, cv2.cv.CV_BGR2GRAY)
stbt.match(grey, frame=black())
|
Set minimum version requirement for tensorflow-datasets
PiperOrigin-RevId: 414736430 | # coding=utf-8
# Copyright 2021 The Balloon Learning Environment Authors.
#
# 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.
"""Setup file for installing the BLE."""
import setuptools
setuptools.setup(
name='balloon_learning_environment',
version='0.0.3',
packages=setuptools.find_packages(),
install_requires=[
'absl-py',
'dopamine-rl >= 4.0.0',
'flax',
'gcsfs',
'gin-config',
'gym',
'opensimplex',
's2sphere',
'scikit-learn',
'tensorflow',
'tensorflow-datasets >= 4.4.0',
'tensorflow-probability',
'transitions',
'zarr',
],
package_data={
'': ['*.msgpack', '*.pb'],
},
python_requires='>=3.7',
)
| # coding=utf-8
# Copyright 2021 The Balloon Learning Environment Authors.
#
# 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.
"""Setup file for installing the BLE."""
import setuptools
setuptools.setup(
name='balloon_learning_environment',
version='0.0.2',
packages=setuptools.find_packages(),
install_requires=[
'absl-py',
'dopamine-rl >= 4.0.0',
'flax',
'gcsfs',
'gin-config',
'gym',
'opensimplex',
's2sphere',
'scikit-learn',
'tensorflow',
'tensorflow-datasets',
'tensorflow-probability',
'transitions',
'zarr',
],
package_data={
'': ['*.msgpack', '*.pb'],
},
python_requires='>=3.7',
)
|
Remove Connect 3 deprecation warning | 'use strict';
var _ = require('underscore');
var config = require('./config');
var express = require('express');
var knox = require('knox');
var app = express();
// Configure knox.
app.s3 = knox.createClient({
key: config.accessKeyId,
secret: config.secretAccessKey,
bucket: config.bucket
});
// Don't waste bytes on an extra header.
app.disable('x-powered-by');
// Helpful vendor middleware.
app.use(express.compress());
app.use(express.urlencoded());
app.use(express.json());
app.use(express.methodOverride());
// Enable CORS on demand.
if (config.cors) app.use(require('./lib/cors'));
// Set req.authorized based on servo key.
app.use(require('./lib/authorize'));
// Upload files to the S3 bucket.
app.put('*', require('./lib/update-files'));
// Delete a file from the S3 bucket.
app.del('*', require('./lib/delete-file'));
// Requests should be in the form /path/to/image(-job-name)(.extension)
app.get(
/^(\/.*?)(?:-(.*?))?(?:\.(.*))?$/,
require('./lib/check-user-agent'),
require('./lib/read-file')
);
// Ensure bad responses aren't cached.
app.use(require('./lib/handle-error'));
// Start listening for requests.
var server = app.listen(config.port);
process.on('SIGTERM', _.bind(server.close, server));
| 'use strict';
var _ = require('underscore');
var config = require('./config');
var express = require('express');
var knox = require('knox');
var app = express();
// Configure knox.
app.s3 = knox.createClient({
key: config.accessKeyId,
secret: config.secretAccessKey,
bucket: config.bucket
});
// Don't waste bytes on an extra header.
app.disable('x-powered-by');
// Helpful vendor middleware.
app.use(express.compress());
app.use(express.bodyParser());
app.use(express.methodOverride());
// Enable CORS on demand.
if (config.cors) app.use(require('./lib/cors'));
// Set req.authorized based on servo key.
app.use(require('./lib/authorize'));
// Upload files to the S3 bucket.
app.put('*', require('./lib/update-files'));
// Delete a file from the S3 bucket.
app.del('*', require('./lib/delete-file'));
// Requests should be in the form /path/to/image(-job-name)(.extension)
app.get(
/^(\/.*?)(?:-(.*?))?(?:\.(.*))?$/,
require('./lib/check-user-agent'),
require('./lib/read-file')
);
// Ensure bad responses aren't cached.
app.use(require('./lib/handle-error'));
// Start listening for requests.
var server = app.listen(config.port);
process.on('SIGTERM', _.bind(server.close, server));
|
Introduce `generate` and `regenerate` methods | // Not to mix with `DataSnapshots` class which is about different thing
// (serialized list views updated reactively)
//
// This one is about snaphots of data made in specific moments of time.
// Snaphots are not reactive in any way. They're updated only if given specific moment repeats
// for entity it refers to.
// e.g. We want to store a state of submitted dataForms at business process at its submission
// After it's stored it's not updated (and safe against any external changes like model changes)
// Just in case of re-submissions (e.g. return of file from sent back case) the snapshot is
// overwritten with regenerated value
'use strict';
var memoize = require('memoizee/plain')
, ensureDb = require('dbjs/valid-dbjs')
, extendBase = require('../../base');
module.exports = memoize(function (db) {
extendBase(ensureDb(db));
return db.Object.extend('DataSnapshot', {
jsonString: { type: db.String },
// Generates snapshot (if it was not generated already)
generate: { type: db.Function, value: function (ignore) {
if (!this.jsonString) this.regenerate();
} },
// Generates snapshot (overwrites old snapshot if it exist)
regenerate: { type: db.Function, value: function (ignore) {
this.jsonString = JSON.stringify(this.owner.toJSON());
} }
});
}, { normalizer: require('memoizee/normalizers/get-1')() });
| // Not to mix with `DataSnapshots` class which is about different thing
// (serialized list views updated reactively)
//
// This one is about snaphots of data made in specific moments of time.
// Snaphots are not reactive in any way. They're updated only if given specific moment repeats
// for entity it refers to.
// e.g. We want to store a state of submitted dataForms at business process at its submission
// After it's stored it's not updated (and safe against any external changes like model changes)
// Just in case of re-submissions (e.g. return of file from sent back case) the snapshot is
// overwritten with regenerated value
'use strict';
var memoize = require('memoizee/plain')
, ensureDb = require('dbjs/valid-dbjs')
, extendBase = require('../../base');
module.exports = memoize(function (db) {
extendBase(ensureDb(db));
return db.Object.extend('DataSnapshot', {
jsonString: { type: db.String }
// 'resolved' property evaluation is configured in ./resolve.js
});
}, { normalizer: require('memoizee/normalizers/get-1')() });
|
Fix 3rd body tests for Moon, simplify interpolant code | import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from astropy.coordinates import get_body_barycentric, ICRS, GCRS, CartesianRepresentation
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
r = get_body_barycentric(body.name, epoch)
r = (ICRS(x=r.x, y=r.y, z=r.z, representation_type=CartesianRepresentation)
.transform_to(GCRS(obstime=epoch))
.represent_as(CartesianRepresentation)
)
r_values[i] = r.xyz.to(u.km)
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
| import numpy as np
from scipy.interpolate import interp1d
from astropy import units as u
from astropy.time import Time
from poliastro.bodies import Moon
from poliastro.twobody.orbit import Orbit
from poliastro.coordinates import transform
from astropy.coordinates import ICRS, GCRS
def build_ephem_interpolant(body, period, t_span, rtol=1e-5):
h = (period * rtol).to(u.day).value
t_span = ((t_span[0].to(u.day).value, t_span[1].to(u.day).value + 0.01))
t_values = np.linspace(*t_span, int((t_span[1] - t_span[0]) / h))
r_values = np.zeros((t_values.shape[0], 3))
for i, t in enumerate(t_values):
epoch = Time(t, format='jd', scale='tdb')
body_t = Orbit.from_body_ephem(body, epoch)
if body != Moon:
body_t = transform(body_t, ICRS, GCRS)
r_values[i] = body_t.r
t_values = ((t_values - t_span[0]) * u.day).to(u.s).value
return interp1d(t_values, r_values, kind='cubic', axis=0, assume_sorted=True)
|
Fix intermittent travis build error. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import pytest
from wamopacker.process import run_command, ProcessException
import os
import uuid
def test_run_command():
cwd = os.getcwd()
output_cmd = run_command('ls -1A', working_dir = cwd)
output_py = os.listdir(cwd)
assert sorted(output_cmd) == sorted(output_py)
def test_run_command_error():
data = uuid.uuid4().hex
with pytest.raises(ProcessException) as e:
run_command('cat {}'.format(data))
assert e.value.log_stdout == ''
assert e.value.log_stderr.startswith('cat: {}'.format(data))
assert e.value.exit_code != 0
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import pytest
from wamopacker.process import run_command, ProcessException
import os
import uuid
def test_run_command():
cwd = os.getcwd()
output_cmd = run_command('ls -1A', working_dir = cwd)
output_py = os.listdir(cwd)
assert sorted(output_cmd) == sorted(output_py)
def test_run_command_error():
data = uuid.uuid4().hex
with pytest.raises(ProcessException) as e:
run_command('cat {}'.format(data))
assert e.value.log_stdout == ''
assert e.value.log_stderr == 'cat: {}: No such file or directory\n'.format(data)
assert e.value.exit_code != 0
|
Fix for bugs that stop parsing if underscores are found in declaration values and slashes inside comments | /*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('underscore');
function CssStylesheet(raw) {
this.raw = raw;
}
CssStylesheet.prototype.getRules = function () {
if (this.raw.length) {
var pattern = /[\w\s>\.:\-_#\*\(\),\[\]\"\=]*\{[\w\s\:\n;\-#\.\(\)%,\/!\*_]*}/g;
return stripFormatting(stripComments(this.raw)).match(pattern);
}
else return {};
};
var stripComments = function (string) {
return string.replace(/\/\*[^\*]*\*\//g, '');
};
var stripFormatting = function (string) {
return stripNewlines(trimWhitespace(string));
};
var trimWhitespace = function (string) {
return string.replace(/[ ]+/g, ' ');
};
var stripNewlines = function (string) {
return string.replace(/\n/g, '');
};
module.exports = CssStylesheet; | /*! Parker v0.0.0 - MIT license */
'use strict';
var _ = require('underscore');
function CssStylesheet(raw) {
this.raw = raw;
}
CssStylesheet.prototype.getRules = function () {
if (this.raw.length) {
var pattern = /[\w\s>\.:\-_#\*\(\),\[\]\"\=]*\{[\w\s\:\n;\-#\.\(\)%,\/!\*]*}/g;
return stripFormatting(stripComments(this.raw)).match(pattern);
}
else return {};
};
var stripComments = function (string) {
return string.replace(/\/\*[^\/\*]*\*\//g, '');
};
var stripFormatting = function (string) {
return stripNewlines(trimWhitespace(string));
};
var trimWhitespace = function (string) {
return string.replace(/[ ]+/g, ' ');
};
var stripNewlines = function (string) {
return string.replace(/\n/g, '');
};
module.exports = CssStylesheet; |
Fix for integer division error:
$ python3 create_images_and_readme.py
Processing <function test_circles at 0x10cda6400>
written: graph-0-0.png
written: graph-0-1.png
Processing <function test_piechart_1 at 0x10d1d4a60>
written: graph-1-0.png
written: graph-1-1.png
Processing <function test_piechart_2 at 0x10d1ed1e0>
written: graph-2-0.png
written: graph-2-1.png
Processing <function test_barchart_1 at 0x10d1edb70>
written: graph-3-0.png
written: graph-3-1.png
Processing <function test_barchart_2 at 0x10d1edbf8>
written: graph-4-0.png
written: graph-4-1.png
Processing <function test_barchart_horizontal at 0x10d1edc80>
written: graph-5-0.png
written: graph-5-1.png
Processing <function test_barchart_with_generator at 0x10d1edd08>
written: graph-6-0.png
written: graph-6-1.png
Traceback (most recent call last):
File "create_images_and_readme.py", line 698, in <module>
images = function()
File "create_images_and_readme.py", line 216, in test_function
return coordinate_system.draw(300, 200), coordinate_system.draw(300, 200, antialiasing=True)
File "/Users/loos/Documents/schule/src/PycharmProjects/cartesius/cartesius/main.py", line 246, in draw
self.__draw_elements(image=image, draw=draw, draw_handler=draw_handler, hide_x_axis=hide_x_axis, hide_y_axis=hide_y_axis)
File "/Users/loos/Documents/schule/src/PycharmProjects/cartesius/cartesius/main.py", line 211, in __draw_elements
element.draw(image=image, draw=draw, draw_handler=draw_handler)
File "/Users/loos/Documents/schule/src/PycharmProjects/cartesius/cartesius/main.py", line 304, in draw
self.process_image(draw_handler)
File "/Users/loos/Documents/schule/src/PycharmProjects/cartesius/cartesius/charts.py", line 373, in process_image
draw_handler.draw_line(x1, y1, x2, y2, self.get_color_with_transparency(self.color))
File "/Users/loos/Documents/schule/src/PycharmProjects/cartesius/cartesius/main.py", line 397, in draw_line
self.pil_draw.line((image_x1, image_y1, image_x2, image_y2), color)
File "/usr/local/lib/python3.5/site-packages/PIL/ImageDraw.py", line 177, in line
ink, fill = self._getink(fill)
File "/usr/local/lib/python3.5/site-packages/PIL/ImageDraw.py", line 125, in _getink
ink = self.draw.draw_ink(ink, self.mode)
TypeError: integer argument expected, got float | # -*- coding: utf-8 -*-
""" Utility functions folr colors """
def get_color(color):
""" Can convert from integer to (r, g, b) """
if not color:
return None
if isinstance(color, int):
temp = color
blue = temp % 256
temp = int(temp / 256)
green = temp % 256
temp = int(temp / 256)
red = temp % 256
return (red, green, blue)
if not len(color) == 3:
raise Exception('Invalid color {0}'.format(color))
return color
def brighten(color, n):
return (int((color[0] + n) % 256), int((color[1] + n) % 256), int((color[2] + n) % 256))
def darken(color, n):
return brighten(color, -n)
def get_color_between(color1, color2, i):
""" i is a number between 0 and 1, if 0 then color1, if 1 color2, ... """
if i <= 0:
return color1
if i >= 1:
return color2
return (int(color1[0] + (color2[0] - color1[0]) * i),
int(color1[1] + (color2[1] - color1[1]) * i),
int(color1[2] + (color2[2] - color1[2]) * i))
| # -*- coding: utf-8 -*-
""" Utility functions folr colors """
def get_color(color):
""" Can convert from integer to (r, g, b) """
if not color:
return None
if isinstance(color, int):
temp = color
blue = temp % 256
temp = temp / 256
green = temp % 256
temp = temp / 256
red = temp % 256
return (red, green, blue)
if not len(color) == 3:
raise Exception('Invalid color {0}'.format(color))
return color
def brighten(color, n):
return (int((color[0] + n) % 256), int((color[1] + n) % 256), int((color[2] + n) % 256))
def darken(color, n):
return brighten(color, -n)
def get_color_between(color1, color2, i):
""" i is a number between 0 and 1, if 0 then color1, if 1 color2, ... """
if i <= 0:
return color1
if i >= 1:
return color2
return (int(color1[0] + (color2[0] - color1[0]) * i),
int(color1[1] + (color2[1] - color1[1]) * i),
int(color1[2] + (color2[2] - color1[2]) * i))
|
Move deferred command additions to be processed after `'after_wp_load'` hook.
For the command additions within (mu-)plugins to work, they need to be processed after all plugins have actually been loaded.
Fixes #4122 | <?php
namespace WP_CLI\Bootstrap;
/**
* Class RegisterDeferredCommands.
*
* Registers the deferred commands that for which no parent was registered yet.
* This is necessary, because we can have sub-commands that have no direct
* parent, like `wp network meta`.
*
* @package WP_CLI\Bootstrap
*/
final class RegisterDeferredCommands implements BootstrapStep {
/**
* Process this single bootstrapping step.
*
* @param BootstrapState $state Contextual state to pass into the step.
*
* @return BootstrapState Modified state to pass to the next step.
*/
public function process( BootstrapState $state ) {
\WP_CLI::add_hook(
'after_wp_load',
array( $this, 'add_deferred_commands' )
);
return $state;
}
/**
* Add deferred commands that are still waiting to be processed.
*/
public function add_deferred_commands() {
$deferred_additions = \WP_CLI::get_deferred_additions();
foreach ( $deferred_additions as $name => $addition ) {
\WP_CLI::add_command(
$name,
$addition['callable'],
$addition['args']
);
}
}
}
| <?php
namespace WP_CLI\Bootstrap;
/**
* Class RegisterDeferredCommands.
*
* Registers the deferred commands that for which no parent was registered yet.
* This is necessary, because we can have sub-commands that have no direct
* parent, like `wp network meta`.
*
* @package WP_CLI\Bootstrap
*/
final class RegisterDeferredCommands implements BootstrapStep {
/**
* Process this single bootstrapping step.
*
* @param BootstrapState $state Contextual state to pass into the step.
*
* @return BootstrapState Modified state to pass to the next step.
*/
public function process( BootstrapState $state ) {
$deferred_additions = \WP_CLI::get_deferred_additions();
foreach ( $deferred_additions as $name => $addition ) {
\WP_CLI::add_command(
$name,
$addition['callable'],
$addition['args']
);
}
return $state;
}
}
|
Update version number and supported Python versions | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.4',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
| import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
readme = readme.read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as requirements_file:
requirements = [line.rstrip() for line in requirements_file if line != '\n']
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-webmention',
version='0.0.3',
packages=find_packages(),
description='A pluggable implementation of webmention for Django projects.',
keywords='webmention pingback linkback blogging',
author='Dane Hillard',
author_email='github@danehillard.com',
long_description=readme,
install_requires=requirements,
url='https://github.com/daneah/django-webmention',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Topic :: Internet :: WWW/HTTP :: Indexing/Search',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
)
|
[MonorepoBuilder] Improve exception about same priority workers | <?php declare(strict_types=1);
namespace Symplify\MonorepoBuilder\Release\Exception;
use Exception;
use Symplify\MonorepoBuilder\Release\Contract\ReleaseWorker\ReleaseWorkerInterface;
use function Safe\sprintf;
final class ConflictingPriorityException extends Exception
{
public function __construct(ReleaseWorkerInterface $firstReleaseWorker, ReleaseWorkerInterface $secondReleaseWorker)
{
$message = sprintf(
'There 2 workers with %d priority:%s-%s%s-%s.%sChange value in "getPriority()" method in one of them',
$firstReleaseWorker->getPriority(),
PHP_EOL,
get_class($firstReleaseWorker),
PHP_EOL,
get_class($secondReleaseWorker),
PHP_EOL
);
parent::__construct($message);
}
}
| <?php declare(strict_types=1);
namespace Symplify\MonorepoBuilder\Release\Exception;
use Exception;
use Symplify\MonorepoBuilder\Release\Contract\ReleaseWorker\ReleaseWorkerInterface;
use function Safe\sprintf;
final class ConflictingPriorityException extends Exception
{
public function __construct(ReleaseWorkerInterface $firstReleaseWorker, ReleaseWorkerInterface $secondReleaseWorker)
{
$message = sprintf(
'There 2 workers with %d priority: %s and %s. Change value in getPriority() in one of them',
$firstReleaseWorker->getPriority(),
get_class($firstReleaseWorker),
get_class($secondReleaseWorker)
);
parent::__construct($message);
}
}
|
Use different variable names for localized errors | // Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package api // import "miniflux.app/api"
import (
"net/http"
"miniflux.app/http/response/json"
"miniflux.app/reader/subscription"
)
// GetSubscriptions is the API handler to find subscriptions.
func (c *Controller) GetSubscriptions(w http.ResponseWriter, r *http.Request) {
subscriptionInfo, bodyErr := decodeURLPayload(r.Body)
if bodyErr != nil {
json.BadRequest(w, r, bodyErr)
return
}
subscriptions, finderErr := subscription.FindSubscriptions(
subscriptionInfo.URL,
subscriptionInfo.UserAgent,
subscriptionInfo.Username,
subscriptionInfo.Password,
)
if finderErr != nil {
json.ServerError(w, r, finderErr)
return
}
if subscriptions == nil {
json.NotFound(w, r)
return
}
json.OK(w, r, subscriptions)
}
| // Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package api // import "miniflux.app/api"
import (
"net/http"
"miniflux.app/http/response/json"
"miniflux.app/reader/subscription"
)
// GetSubscriptions is the API handler to find subscriptions.
func (c *Controller) GetSubscriptions(w http.ResponseWriter, r *http.Request) {
subscriptionInfo, err := decodeURLPayload(r.Body)
if err != nil {
json.BadRequest(w, r, err)
return
}
subscriptions, err := subscription.FindSubscriptions(
subscriptionInfo.URL,
subscriptionInfo.UserAgent,
subscriptionInfo.Username,
subscriptionInfo.Password,
)
if err != nil {
json.ServerError(w, r, err)
return
}
if subscriptions == nil {
json.NotFound(w, r)
return
}
json.OK(w, r, subscriptions)
}
|
Disable ReactDev tools warning that appears in React 16
- this was crufting up the output of our end-to-end tests locally, as these are compiled using development configs | const path = require("path")
const webpack = require("webpack")
const HardSourceWebpackPlugin = require("hard-source-webpack-plugin")
process.noDeprecation = true
module.exports = {
cache: true,
entry: {
vendor: ["./web/static/js/vendor"],
},
stats: "errors-only",
output: {
path: path.resolve(__dirname, "priv/static/js/dll"),
filename: "dll.[name].js",
library: "[name]",
},
plugins: [
new HardSourceWebpackPlugin(),
new webpack.DllPlugin({
path: path.resolve(__dirname, "web/static/js/dll", "[name]-manifest.json"),
name: "[name]",
context: path.resolve(__dirname, "web/static/js"),
}),
new webpack.DefinePlugin({
__REACT_DEVTOOLS_GLOBAL_HOOK__: "({ isDisabled: true })",
}),
],
resolve: {
modules: ["node_modules"],
},
}
| const path = require("path")
const webpack = require("webpack")
const HardSourceWebpackPlugin = require("hard-source-webpack-plugin")
process.noDeprecation = true
module.exports = {
cache: true,
entry: {
vendor: ["./web/static/js/vendor"],
},
stats: "errors-only",
output: {
path: path.resolve(__dirname, "priv/static/js/dll"),
filename: "dll.[name].js",
library: "[name]",
},
plugins: [
new HardSourceWebpackPlugin(),
new webpack.DllPlugin({
path: path.resolve(__dirname, "web/static/js/dll", "[name]-manifest.json"),
name: "[name]",
context: path.resolve(__dirname, "web/static/js"),
}),
],
resolve: {
modules: ["node_modules"],
},
}
|
OAK-2954: Add MBean to enforce session refresh on all open sessions
Update package export version as required
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1683423 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@Version("1.1.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.management;
import aQute.bnd.annotation.Version;
import aQute.bnd.annotation.Export; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@Version("1.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.management;
import aQute.bnd.annotation.Version;
import aQute.bnd.annotation.Export; |
Change include to exclude to maintain compat | /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-place-autocomplete',
contentFor: function(type, config) {
var content = '';
if (type === 'body-footer') {
var src = "//maps.googleapis.com/maps/api/js",
placeAutocompleteConfig = config['place-autocomplete'] || {},
params = [],
exclude = placesAutocompleteConfig.exclude,
key = placeAutocompleteConfig.key;
if (!exclude) {
if (key)
params.push('key=' + encodeURIComponent(key));
src += '?' + params.join('&') + "&libraries=places";
content = '<script type="text/javascript" src="' + src + '"></script>';
}
}
return content;
}
};
| /* jshint node: true */
'use strict';
module.exports = {
name: 'ember-place-autocomplete',
contentFor: function(type, config) {
var content = '';
if (type === 'body-footer') {
var src = "//maps.googleapis.com/maps/api/js",
placeAutocompleteConfig = config['place-autocomplete'] || {},
params = [],
include = placesAutocompleteConfig.include,
key = placeAutocompleteConfig.key;
if (include) {
if (key)
params.push('key=' + encodeURIComponent(key));
src += '?' + params.join('&') + "&libraries=places";
content = '<script type="text/javascript" src="' + src + '"></script>';
}
}
return content;
}
};
|
Replace use of Laravel Facades with dependency injection
I'm not a huge fan of the Laravel Facades concept. But I get why it's
there. So this moves me away from that, making the code both clearer, as
well as easier for the IDE (PhpStorm of course) to figure out what's going on. | <?php
namespace App\Http\Controllers;
use App\Url;
use Illuminate\Http\Request;
use Illuminate\Session\Store;
use Illuminate\Validation\Factory as Validator;
use Zenapply\Shortener\Facades\Shortener;
class UrlController extends Controller
{
public function manageUrl(Request $request, Store $session, Validator $validator)
{
if ($request->isMethod('post')) {
if ($request->has('url')) {
$url = new Url();
$url->original_url = $request->input('url');
$url->shortened_url = Shortener::shorten($request->input('url'));
$url->save();
\Session::flash('message', 'Record saved');
}
return redirect('/view-urls');
}
return view('url.manage', []);
}
public function viewUrls()
{
$urls = Url::all();
return view('url.view', [
'urls' => $urls,
'message' => \Session::get('message')
]);
}
}
| <?php
namespace App\Http\Controllers;
use App\Url;
use Illuminate\Http\Request;
use Zenapply\Shortener\Facades\Shortener;
class UrlController extends Controller
{
public function manageUrl(Request $request)
{
if ($request->isMethod('post')) {
if ($request->has('url')) {
$url = new Url();
$url->original_url = $request->input('url');
$url->shortened_url = Shortener::shorten($request->input('url'));
$url->save();
\Session::flash('message', 'Record saved');
}
return redirect('/view-urls');
}
return view('url.manage', []);
}
public function viewUrls()
{
$urls = Url::all();
return view('url.view', [
'urls' => $urls,
'message' => \Session::get('message')
]);
}
}
|
Add API access to a Spell's hidden flag | package com.elmakers.mine.bukkit.api.spell;
import java.util.Collection;
import org.bukkit.Color;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import com.elmakers.mine.bukkit.api.block.MaterialAndData;
import com.elmakers.mine.bukkit.api.effect.EffectPlayer;
/**
* A Spell template, as defined in the spells configuration files.
*/
public interface SpellTemplate extends Comparable<SpellTemplate>, CostReducer {
public String getName();
public String getAlias();
public String getDescription();
public String getExtendedDescription();
public String getKey();
public Color getColor();
public long getWorth();
public SpellCategory getCategory();
public long getCastCount();
public String getUsage();
public MaterialAndData getIcon();
public boolean hasIcon();
public boolean hasCastPermission(CommandSender sender);
public Collection<CastingCost> getCosts();
public Collection<CastingCost> getActiveCosts();
public Collection<EffectPlayer> getEffects(SpellResult result);
public Collection<EffectPlayer> getEffects(String effectsKey);
public void getParameters(Collection<String> parameters);
public void getParameterOptions(Collection<String> examples, String parameterKey);
public long getDuration();
public long getCooldown();
public Spell createSpell();
public void loadTemplate(String key, ConfigurationSection node);
public String getPermissionNode();
public boolean isHidden();
}
| package com.elmakers.mine.bukkit.api.spell;
import java.util.Collection;
import org.bukkit.Color;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import com.elmakers.mine.bukkit.api.block.MaterialAndData;
import com.elmakers.mine.bukkit.api.effect.EffectPlayer;
/**
* A Spell template, as defined in the spells configuration files.
*/
public interface SpellTemplate extends Comparable<SpellTemplate>, CostReducer {
public String getName();
public String getAlias();
public String getDescription();
public String getExtendedDescription();
public String getKey();
public Color getColor();
public long getWorth();
public SpellCategory getCategory();
public long getCastCount();
public String getUsage();
public MaterialAndData getIcon();
public boolean hasIcon();
public boolean hasCastPermission(CommandSender sender);
public Collection<CastingCost> getCosts();
public Collection<CastingCost> getActiveCosts();
public Collection<EffectPlayer> getEffects(SpellResult result);
public Collection<EffectPlayer> getEffects(String effectsKey);
public void getParameters(Collection<String> parameters);
public void getParameterOptions(Collection<String> examples, String parameterKey);
public long getDuration();
public long getCooldown();
public Spell createSpell();
public void loadTemplate(String key, ConfigurationSection node);
public String getPermissionNode();
}
|
Add toString method for formulas | package beaform.entities;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import beaform.Type;
public class Formula {
private final Type type;
private final Label label;
private final String name;
private final String description;
public Formula(String name, String description) {
this.type = Type.FORMULA;
this.label = this.type.getLabel();
this.name = name;
this.description = description;
}
public Label getLabel() {
return this.label;
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
/**
* Store the Formula in the graph database.
*
* @param graphDb a handle to the graph database.
* @return the newly created node
*/
public Node persist(GraphDatabaseService graphDb) {
Node thisNode;
try ( Transaction tx = graphDb.beginTx()) {
thisNode = graphDb.createNode(this.label);
thisNode.setProperty( "name", this.name );
thisNode.setProperty( "description", this.description );
tx.success();
}
return thisNode;
}
@Override
public String toString() {
return this.type + " name: " + this.name + " desc: " + this.description;
}
}
| package beaform.entities;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import beaform.Type;
public class Formula {
private final Type type;
private final Label label;
private final String name;
private final String description;
public Formula(String name, String description) {
this.type = Type.FORMULA;
this.label = this.type.getLabel();
this.name = name;
this.description = description;
}
public Label getLabel() {
return this.label;
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
/**
* Store the Formula in the graph database.
*
* @param graphDb a handle to the graph database.
* @return the newly created node
*/
public Node persist(GraphDatabaseService graphDb) {
Node thisNode;
try ( Transaction tx = graphDb.beginTx()) {
thisNode = graphDb.createNode(this.label);
thisNode.setProperty( "name", this.name );
thisNode.setProperty( "description", this.description );
tx.success();
}
return thisNode;
}
}
|
Use nodeType from params instead of static prop. | import Command from '../../ui/Command'
import insertInlineNode from '../../model/transform/insertInlineNode'
class InsertInlineNodeCommand extends Command {
constructor(...args) {
super(...args)
if (!this.params.nodeType) {
throw new Error('Every AnnotationCommand must have a nodeType')
}
}
getCommandState(props, context) {
let sel = context.documentSession.getSelection()
let newState = {
disabled: !sel.isPropertySelection(),
active: false
}
return newState
}
execute(props, context) {
let state = this.getCommandState(props, context)
if (state.disabled) return
let surface = context.surface || context.surfaceManager.getFocusedSurface()
if (surface) {
surface.transaction(function(tx, args) {
return this.insertInlineNode(tx, args)
}.bind(this))
}
return true
}
insertInlineNode(tx, args) {
args.node = this.createNodeData(tx, args)
return insertInlineNode(tx, args)
}
createNodeData(tx, args) { // eslint-disable-line
return {
type: this.params.nodeType
}
}
_getAnnotationsForSelection(props) {
return props.selectionState.getAnnotationsForType(this.params.nodeType)
}
}
export default InsertInlineNodeCommand
| import Command from '../../ui/Command'
import insertInlineNode from '../../model/transform/insertInlineNode'
class InsertInlineNodeCommand extends Command {
constructor(...args) {
super(...args)
if (!this.params.nodeType) {
throw new Error('Every AnnotationCommand must have a nodeType')
}
}
getCommandState(props, context) {
let sel = context.documentSession.getSelection()
let newState = {
disabled: !sel.isPropertySelection(),
active: false
}
return newState
}
execute(props, context) {
let state = this.getCommandState(props, context)
if (state.disabled) return
let surface = context.surface || context.surfaceManager.getFocusedSurface()
if (surface) {
surface.transaction(function(tx, args) {
return this.insertInlineNode(tx, args)
}.bind(this))
}
return true
}
insertInlineNode(tx, args) {
args.node = this.createNodeData(tx, args)
return insertInlineNode(tx, args)
}
createNodeData(tx, args) { // eslint-disable-line
return {
type: this.constructor.type
}
}
_getAnnotationsForSelection(props) {
return props.selectionState.getAnnotationsForType(this.params.nodeType)
}
}
export default InsertInlineNodeCommand
|
Add getVariantUrl to content node. | 'use strict';
const ContentNode = function (context) {
const self = this;
const api = require('../api');
const config = require('../config');
this.uuid = context.content.uuid;
this.document = context.content;
this.children = [];
if (this.document.children && this.document.children.length === this.document.itemCount) {
this.document.children.forEach(child => {
self.children.push(new ContentNode({ content: child }));
});
}
this.getChildren = () => {
if (this.document.itemCount != this.children.length) {
return api.getContentNode(this.uuid)
.then(that => {
self.document = that.document;
self.children = that.children;
return self.children;
});
} else {
return Promise.resolve(this.children);
}
};
this.getUrl = () => {
return config.host + '/api/delivery' + escape(this.document.path);
};
this.getVariantUrl = name => {
const query = '?variant=' + encodeURIComponent(name);
return config.host + '/api/delivery' + escape(this.document.path) + query;
};
};
module.exports = ContentNode;
| 'use strict';
const ContentNode = function (context) {
const self = this;
const api = require('../api');
const config = require('../config');
this.uuid = context.content.uuid;
this.document = context.content;
this.children = [];
if (this.document.children && this.document.children.length === this.document.itemCount) {
this.document.children.forEach(child => {
self.children.push(new ContentNode({ content: child }));
});
}
this.getChildren = () => {
if (this.document.itemCount != this.children.length) {
return api.getContentNode(this.uuid)
.then(that => {
self.document = that.document;
self.children = that.children;
return self.children;
});
} else {
return Promise.resolve(this.children);
}
};
this.getUrl = () => {
return config.host + '/api/delivery' + escape(this.document.path);
};
};
module.exports = ContentNode;
|
Split up vars for consistency with official Sanity terms | import array from 'role:@sanity/form-builder/input/array?'
import boolean from 'role:@sanity/form-builder/input/boolean?'
import date from 'role:@sanity/form-builder/input/date?'
import email from 'role:@sanity/form-builder/input/email?'
import geopoint from 'role:@sanity/form-builder/input/geopoint?'
import number from 'role:@sanity/form-builder/input/number?'
import object from 'role:@sanity/form-builder/input/object?'
import reference from 'role:@sanity/form-builder/input/reference?'
import string from 'role:@sanity/form-builder/input/string?'
import text from 'role:@sanity/form-builder/input/text?'
import url from 'role:@sanity/form-builder/input/url?'
import DefaultReference from '../inputs/Reference'
const primitiveTypes = {
array,
boolean,
date,
number,
object,
reference: reference || DefaultReference,
string
}
const bundledTypes = {
email,
geopoint,
text,
url
}
const coreTypes = Object.assign({}, primitiveTypes, bundledTypes)
const inputResolver = (field, fieldType) => {
const inputRole = coreTypes[field.type] || coreTypes[fieldType.name]
return field.input || inputRole
}
export default inputResolver
| import array from 'role:@sanity/form-builder/input/array?'
import boolean from 'role:@sanity/form-builder/input/boolean?'
import date from 'role:@sanity/form-builder/input/date?'
import email from 'role:@sanity/form-builder/input/email?'
import geopoint from 'role:@sanity/form-builder/input/geopoint?'
import number from 'role:@sanity/form-builder/input/number?'
import object from 'role:@sanity/form-builder/input/object?'
import reference from 'role:@sanity/form-builder/input/reference?'
import string from 'role:@sanity/form-builder/input/string?'
import text from 'role:@sanity/form-builder/input/text?'
import url from 'role:@sanity/form-builder/input/url?'
import DefaultReference from '../inputs/Reference'
const coreTypes = {
array,
boolean,
date,
email,
geopoint,
number,
object,
reference: reference || DefaultReference,
string,
text,
url
}
const inputResolver = (field, fieldType) => {
const inputRole = coreTypes[field.type] || coreTypes[fieldType.name]
return field.input || inputRole
}
export default inputResolver
|
Fix setting `auth.defaults.provider` config option | <?php
declare(strict_types=1);
namespace Cortex\Foundation\Http\Middleware;
use Closure;
use Illuminate\Support\Str;
class SetAuthDefaults
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($guard = $request->guard()) {
// It's better to set auth defaults config globally,
// instead of using `auth()->shouldUse($guard);`
config()->set('auth.defaults.guard', $guard);
config()->set('auth.defaults.provider', Str::afterLast(Str::plural($guard), ':'));
config()->set('auth.defaults.passwords', $guard);
config()->set('auth.defaults.emails', $guard);
}
return $next($request);
}
}
| <?php
declare(strict_types=1);
namespace Cortex\Foundation\Http\Middleware;
use Closure;
use Illuminate\Support\Str;
class SetAuthDefaults
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($guard = $request->guard()) {
// It's better to set auth defaults config globally,
// instead of using `auth()->shouldUse($guard);`
config()->set('auth.defaults.guard', $guard);
config()->set('auth.defaults.provider', Str::plural($guard));
config()->set('auth.defaults.passwords', $guard);
config()->set('auth.defaults.emails', $guard);
}
return $next($request);
}
}
|
Add coversion of id column | var nconf = require('nconf');
var conf_file = './config/config.json';
var dbtype = nconf.get('database:type')
exports.up = function(db, Promise) {
if (dbtype == 'mysql'){
return Promise.all([
// This is here to fix original broken mysql installs - probably not required going forward.
db.schema.table('messages', function (table) {
table.integer('alias_id').unsigned().references('id').inTable('capcodes').onUpdate('CASCADE').onDelete('CASCADE');
}),
db.schema.alterTable('capccodes', function (table) {
table.increments('id').primary().unique().notNullable().alter();
})
//end broken MySQL Fix
])
} else {
return Promise.resolve('Not Required')
}
};
exports.down = function(db, Promise) {
};
| var nconf = require('nconf');
var conf_file = './config/config.json';
var dbtype = nconf.get('database:type')
exports.up = function(db, Promise) {
if (dbtype == 'mysql'){
return Promise.all([
// This is here to fix original broken mysql installs - probably not required going forward.
db.schema.table('messages', function (table) {
table.integer('alias_id').unsigned().references('id').inTable('capcodes').onUpdate('CASCADE').onDelete('CASCADE');
})
//end broken MySQL Fix
])
} else {
return Promise.resolve('Not Required')
}
};
exports.down = function(db, Promise) {
};
|
Fix up consume either/both check | <?php
namespace SwaggerGen\Swagger\Type;
/**
* Basic file type definition.
*
* @package SwaggerGen
* @author Martijn van der Lee <martijn@vanderlee.com>
* @copyright 2014-2015 Martijn van der Lee
* @license https://opensource.org/licenses/MIT MIT
*/
class FileType extends AbstractType
{
protected function parseDefinition($definition)
{
$type = strtolower($definition);
$parent = $this->getParent();
if (!($parent instanceof \SwaggerGen\Swagger\Parameter) || !$parent->isForm()) {
throw new \SwaggerGen\Exception("File type '{$definition}' only allowed on form parameter");
}
$consumes = $this->getParentClass('\SwaggerGen\Swagger\Operation')->getConsumes();
if (empty($consumes)) {
$consumes = $this->getRoot()->getConsumes();
}
$valid_consumes = ((int) in_array('multipart/form-data', $consumes)) + ((int) in_array('application/x-www-form-urlencoded', $consumes));
if (empty($consumes) || $valid_consumes !== count($consumes)) {
throw new \SwaggerGen\Exception("File type '{$definition}' without valid consume");
}
}
public function toArray()
{
return self::array_filter_null([
'type' => 'file',
]);
}
public function __toString()
{
return __CLASS__;
}
}
| <?php
namespace SwaggerGen\Swagger\Type;
/**
* Basic file type definition.
*
* @package SwaggerGen
* @author Martijn van der Lee <martijn@vanderlee.com>
* @copyright 2014-2015 Martijn van der Lee
* @license https://opensource.org/licenses/MIT MIT
*/
class FileType extends AbstractType
{
protected function parseDefinition($definition)
{
$type = strtolower($definition);
$parent = $this->getParent();
if (!($parent instanceof \SwaggerGen\Swagger\Parameter) || !$parent->isForm()) {
throw new \SwaggerGen\Exception("File type only allowed on form parameter: '{$definition}'");
}
$consumes = $this->getParentClass('\SwaggerGen\Swagger\Operation')->getConsumes();
if (empty($consumes)) {
$consumes = $this->getRoot()->getConsumes();
}
if ($consumes !== array('multipart/form-data') && $consumes !== array('application/x-www-form-urlencoded')) {
throw new \SwaggerGen\Exception("File type without valid consume: '{$definition}'");
}
}
public function toArray()
{
return self::array_filter_null([
'type' => 'file',
]);
}
public function __toString()
{
return __CLASS__;
}
}
|
Fix Okapi-301. null ptr when enabling module without permissionSets
When we have a tenantPermissions interface in some other module | package org.folio.okapi.bean;
/**
* List of Permissions (and permission sets) belonging to a module. Used as a
* parameter in the system request to initialize the permission module when a
* module is being enabled for a tenant.
*
* @author heikki
*/
public class PermissionList {
String moduleId; // The module that owns these permissions.
Permission[] perms;
public PermissionList() {
}
public PermissionList(String moduleId, Permission[] perms) {
this.moduleId = moduleId;
this.perms = perms;
}
public PermissionList(PermissionList other) {
this.moduleId = other.moduleId;
this.perms = other.perms;
}
public String getModuleId() {
return moduleId;
}
public void setModuleId(String moduleId) {
this.moduleId = moduleId;
}
public Permission[] getPerms() {
return perms;
}
public void setPerms(Permission[] perms) {
this.perms = perms;
}
}
| package org.folio.okapi.bean;
/**
* List of Permissions (and permission sets) belonging to a module. Used as a
* parameter in the system request to initialize the permission module when a
* module is being enabled for a tenant.
*
* @author heikki
*/
public class PermissionList {
String moduleId; // The module that owns these permissions.
Permission[] perms;
public PermissionList() {
}
public PermissionList(String moduleId, Permission[] perms) {
this.moduleId = moduleId;
this.perms = perms.clone();
}
public PermissionList(PermissionList other) {
this.moduleId = other.moduleId;
this.perms = other.perms.clone();
}
public String getModuleId() {
return moduleId;
}
public void setModuleId(String moduleId) {
this.moduleId = moduleId;
}
public Permission[] getPerms() {
return perms;
}
public void setPerms(Permission[] perms) {
this.perms = perms;
}
}
|
Update import path of gform and w32. | package main
import (
"syscall"
"github.com/AllenDang/gform"
"github.com/AllenDang/w32"
)
const IDR_PNG1 = 100
func onpaint(arg *gform.EventArg) {
if data, ok := arg.Data().(*gform.PaintEventData); ok {
if bmp, err := gform.NewBitmapFromResource(
gform.GetAppInstance(),
w32.MakeIntResource(IDR_PNG1),
syscall.StringToUTF16Ptr("PNG"),
gform.RGB(255, 0, 0)); err == nil {
data.Canvas.DrawBitmap(bmp, 10, 10)
bmp.Dispose()
} else {
println(err.Error())
}
}
}
func main() {
gform.Init()
mf := gform.NewForm(nil)
mf.SetSize(300, 200)
mf.Center()
mf.OnPaint().Bind(onpaint)
mf.Show()
gform.RunMainLoop()
}
| package main
import (
"gform"
"syscall"
"w32"
)
const IDR_PNG1 = 100
func onpaint(arg *gform.EventArg) {
if data, ok := arg.Data().(*gform.PaintEventData); ok {
if bmp, err := gform.NewBitmapFromResource(
gform.GetAppInstance(),
w32.MakeIntResource(IDR_PNG1),
syscall.StringToUTF16Ptr("PNG"),
gform.RGB(255, 0, 0)); err == nil {
data.Canvas.DrawBitmap(bmp, 10, 10)
bmp.Dispose()
} else {
println(err.Error())
}
}
}
func main() {
gform.Init()
mf := gform.NewForm(nil)
mf.SetSize(300, 200)
mf.Center()
mf.OnPaint().Bind(onpaint)
mf.Show()
gform.RunMainLoop()
}
|
Fix constructor for SpaceAlignedTableWriter class | import copy
import dataproperty
from ._csv import CsvTableWriter
class SpaceAlignedTableWriter(CsvTableWriter):
"""
A table writer class for space aligned format.
:Example:
:ref:`example-space-aligned-table-writer`
.. py:method:: write_table
|write_table| with space aligned format.
:Example:
:ref:`example-space-aligned-table-writer`
"""
FORMAT_NAME = "space_aligned"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
def __init__(self) -> None:
super().__init__()
self.column_delimiter = " "
self.char_cross_point = " "
self.is_padding = True
self.is_formatting_float = True
self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
| import copy
import dataproperty
from ._csv import CsvTableWriter
class SpaceAlignedTableWriter(CsvTableWriter):
"""
A table writer class for space aligned format.
:Example:
:ref:`example-space-aligned-table-writer`
.. py:method:: write_table
|write_table| with space aligned format.
:Example:
:ref:`example-space-aligned-table-writer`
"""
FORMAT_NAME = "space_aligned"
@property
def format_name(self) -> str:
return self.FORMAT_NAME
def __init__(self) -> None:
super().__init__()
self.column_delimiter = " "
self.is_padding = True
self.is_formatting_float = True
self._quoting_flags = copy.deepcopy(dataproperty.NOT_QUOTING_FLAGS)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.