text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Fix function declaration for fuzz task
|
import redis
from celery import Celery
from .Fuzzer import Fuzzer
import os
import time
import driller.config as config
import logging
l = logging.getLogger("fuzzer.tasks")
backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT)
app = Celery('fuzzer', broker=config.BROKER_URL, backend=backend_url)
@app.task
def fuzz(binary):
binary_path = os.path.join(config.BINARY_DIR, binary)
fuzzer = Fuzzer(binary_path, "tests", config.FUZZER_INSTANCES)
try:
fuzzer.start()
except Fuzzer.EarlyCrash:
l.info("binary crashed on dummy testcase, moving on...")
return 0
# start the fuzzer and poll for a crash or timeout
fuzzer.start()
while not fuzzer.found_crash() and not fuzzer.timed_out():
time.sleep(config.CRASH_CHECK_INTERVAL)
# make sure to kill the fuzzers when we're done
fuzzer.kill()
return fuzzer.found_crash()
|
import redis
from celery import Celery
from .Fuzzer import Fuzzer
import os
import time
import driller.config as config
import logging
l = logging.getLogger("fuzzer.tasks")
backend_url = "redis://%s:%d" % (config.REDIS_HOST, config.REDIS_PORT)
app = Celery('fuzzer', broker=config.BROKER_URL, backend=backend_url)
@app.task
def drill(binary, input, fuzz_bitmap, exit_on_eof=False):
binary_path = os.path.join(config.BINARY_DIR, binary)
fuzzer = Fuzzer(binary_path, "tests", config.FUZZER_INSTANCES)
try:
fuzzer.start()
except Fuzzer.EarlyCrash:
l.info("binary crashed on dummy testcase, moving on...")
return 0
# start the fuzzer and poll for a crash or timeout
fuzzer.start()
while not fuzzer.found_crash() and not fuzzer.timed_out():
time.sleep(config.CRASH_CHECK_INTERVAL)
# make sure to kill the fuzzers when we're done
fuzzer.kill()
return fuzzer.found_crash()
|
Fix hotel restart on OS X
|
const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const startup = require('user-startup')
const common = require('../common')
const conf = require('../conf')
const uninstall = require('../scripts/uninstall')
module.exports = {
start,
stop
}
// Start daemon in background
function start () {
const node = process.execPath
const daemonFile = path.join(__dirname, '../daemon')
const startupFile = startup.getFile('hotel')
startup.create('hotel', node, [daemonFile], common.logFile)
// Save startup file path in ~/.hotel
// Will be used later by uninstall script
mkdirp.sync(common.hotelDir)
fs.writeFileSync(common.startupFile, startupFile)
console.log(`Started http://localhost:${conf.port}`)
}
// Stop daemon
function stop () {
startup.remove('hotel')
// kills process and clean stuff in ~/.hotel
uninstall()
console.log('Stopped')
}
|
const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const startup = require('user-startup')
const common = require('../common')
const conf = require('../conf')
const uninstall = require('../scripts/uninstall')
module.exports = {
start,
stop
}
// Start daemon in background
function start () {
const node = process.execPath
const daemonFile = path.join(__dirname, '../daemon')
const startupFile = startup.getFile('hotel')
startup.create('hotel', node, [daemonFile], common.logFile)
// Save startup file path in ~/.hotel
// Will be used later by uninstall script
mkdirp.sync(common.hotelDir)
fs.writeFileSync(common.startupFile, startupFile)
console.log(`Started http://localhost:${conf.port}`)
}
// Stop daemon (same as uninstall)
function stop () {
uninstall()
console.log('Stopped')
}
|
Drop runtime flag from karma webpack options
|
/* eslint-env node */
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha'],
files: [
'test/**/*.js'
],
preprocessors: {
'test/**/*.js': ['webpack', 'sourcemap']
},
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader?loose=es6.modules'
}
]
}
},
webpackMiddleware: {
noInfo: true
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false,
browsers: ['PhantomJS']
});
};
|
/* eslint-env node */
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha'],
files: [
'test/**/*.js'
],
preprocessors: {
'test/**/*.js': ['webpack', 'sourcemap']
},
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader?optional=runtime&loose=es6.modules'
}
]
}
},
webpackMiddleware: {
noInfo: true
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false,
browsers: ['PhantomJS']
});
};
|
Disable icon temporarily and adjust the debug print statements
|
import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Local Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.register()
class GNTPNotice(gntp.GNTPNotice):
def send(self):
print 'Sending Local Notification'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = [self.headers['Notification-Name']]
)
noticeIcon = None
if self.headers.get('Notification-Icon',False):
resource = self.headers['Notification-Icon'].split('://')
#print resource
resource = self.resources.get(resource[1],False)
#print resource
if resource:
noticeIcon = resource['Data']
growl.notify(
noteType = self.headers['Notification-Name'],
title = self.headers['Notification-Title'],
description=self.headers['Notification-Text'],
)
|
import gntp
import Growl
class GNTPRegister(gntp.GNTPRegister):
def send(self):
print 'Sending Registration'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = self.notifications,
defaultNotifications = self.defaultNotifications,
)
growl.register()
class GNTPNotice(gntp.GNTPNotice):
def send(self):
print 'Sending Notification'
growl = Growl.GrowlNotifier(
applicationName = self.headers['Application-Name'],
notifications = [self.headers['Notification-Name']]
)
noticeIcon = None
if self.headers.get('Notification-Icon',False):
resource = self.headers['Notification-Icon'].split('://')
#print resource
resource = self.resources.get(resource[1],False)
#print resource
if resource:
noticeIcon = resource['Data']
growl.notify(
noteType = self.headers['Notification-Name'],
title = self.headers['Notification-Title'],
description=self.headers['Notification-Text'],
icon=noticeIcon
)
|
Change the name template component to view component
|
'use strict';
var createComponent = require('./src/component');
var createTemplateComponent = require('./src/template-component');
var createAdapter = require('./src/rx/adapter');
var React = require('react');
var RxAdapter = createAdapter();
var Cycle = {
/**
* The component's definition function.
*
* @callback DefinitionFn
* @param {Object} interactions - The collection of events.
* @param {Object} props - The observable for React props.
* @param {Object} [self] - "this" object for the React component.
* @returns {}
*/
/**
* The component's definition.
*
* @typedef {(Observable<ReactElement>|{
* view: Observable<ReactElement>,
* events: ?Object,
* dispose: ?Function
* })} ComponentDefinition
*/
/**
* Takes a `DefinitionFn` function which outputs an Observable of React
* elements, and returns a native React component which can be used normally
* by `React.createElement`.
*
* @function component
* @param {String} displayName - A name which identifies the React component.
* @param {DefinitionFn} definitionFn - The implementation for the React component.
* This function takes two arguments: `interactions`, and `properties`, and
* should output an Observable of React elements.
* @param {Object} [options] - The options for component.
* @returns {ReactComponent} The React component.
*/
component: createComponent(React, RxAdapter),
viewComponent: createTemplateComponent(React, RxAdapter)
};
module.exports = Cycle;
|
'use strict';
var createComponent = require('./src/component');
var createTemplateComponent = require('./src/template-component');
var createAdapter = require('./src/rx/adapter');
var React = require('react');
var RxAdapter = createAdapter();
var Cycle = {
/**
* The component's definition function.
*
* @callback DefinitionFn
* @param {Object} interactions - The collection of events.
* @param {Object} props - The observable for React props.
* @param {Object} [self] - "this" object for the React component.
* @returns {}
*/
/**
* The component's definition.
*
* @typedef {(Observable<ReactElement>|{
* view: Observable<ReactElement>,
* events: ?Object,
* dispose: ?Function
* })} ComponentDefinition
*/
/**
* Takes a `DefinitionFn` function which outputs an Observable of React
* elements, and returns a native React component which can be used normally
* by `React.createElement`.
*
* @function component
* @param {String} displayName - A name which identifies the React component.
* @param {DefinitionFn} definitionFn - The implementation for the React component.
* This function takes two arguments: `interactions`, and `properties`, and
* should output an Observable of React elements.
* @param {Object} [options] - The options for component.
* @returns {ReactComponent} The React component.
*/
component: createComponent(React, RxAdapter),
templateComponent: createTemplateComponent(React, RxAdapter)
};
module.exports = Cycle;
|
Refactor body DOM selector to the body prop
|
import ReactDOM from 'react-dom';
import React, { PropTypes } from 'react';
import { Provider } from 'react-redux';
import createStore from '../../app/store/configureStore';
import InjectCardDepView from '../../app/containers/InjectCardDepView';
import InjectCardDepViewToggler from '../../app/containers/InjectCardDepViewToggler';
import { CHROME_SYNC_ITEMS } from '../../app/constants';
export default class Root extends React.Component {
render() {
return (
<Provider store={this.props.store}>
<div>
<InjectCardDepViewToggler />
<InjectCardDepView />
</div>
</Provider>
);
}
}
Root.propTypes = {
store: PropTypes.object.isRequired
};
chrome.storage.sync.get(CHROME_SYNC_ITEMS, obj => {
// const initialState = JSON.parse(app || '{}');
const initialState = obj || {};
console.log('initialState =', initialState);
window.addEventListener('load', () => {
const injectDOM = document.createElement('div');
injectDOM.style.display = 'none';
document.body.appendChild(injectDOM);
ReactDOM.render(
<Root store={createStore(initialState)} />,
injectDOM
);
});
});
|
import ReactDOM from 'react-dom';
import React, { PropTypes } from 'react';
import { Provider } from 'react-redux';
import createStore from '../../app/store/configureStore';
import InjectCardDepView from '../../app/containers/InjectCardDepView';
import InjectCardDepViewToggler from '../../app/containers/InjectCardDepViewToggler';
import { CHROME_SYNC_ITEMS } from '../../app/constants';
export default class Root extends React.Component {
render() {
return (
<Provider store={this.props.store}>
<div>
<InjectCardDepViewToggler />
<InjectCardDepView />
</div>
</Provider>
);
}
}
Root.propTypes = {
store: PropTypes.object.isRequired
};
chrome.storage.sync.get(CHROME_SYNC_ITEMS, obj => {
// const initialState = JSON.parse(app || '{}');
const initialState = obj || {};
console.log('initialState =', initialState);
window.addEventListener('load', () => {
const injectDOM = document.createElement('div');
injectDOM.style.display = 'none';
document.getElementsByTagName('body')[0].appendChild(injectDOM);
ReactDOM.render(
<Root store={createStore(initialState)} />,
injectDOM
);
});
});
|
Add test for duplicate rooms
|
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def setUp(self):
self.dojo = Dojo()
self.test_office = self.dojo.create_room("office", "test")
self.test_living_space = self.dojo.create_room("living_space", "test living space")
def test_create_room_successfully(self):
initial_room_count = len(self.dojo.all_rooms)
blue_office = self.dojo.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(self.dojo.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
initial_room_count = len(self.dojo.all_rooms)
offices = self.dojo.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(self.dojo.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
def test_addition_of_duplicate_room_names(self):
pass
|
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def setUp(self):
self.dojo = Dojo()
self.test_office = self.dojo.create_room("office", "test")
self.test_living_space = self.dojo.create_room("living_space", "test living space")
def test_create_room_successfully(self):
initial_room_count = len(self.dojo.all_rooms)
blue_office = self.dojo.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(self.dojo.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
initial_room_count = len(self.dojo.all_rooms)
offices = self.dojo.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(self.dojo.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
|
Use find_packages instead of an explicit list of packages for easier maintenance.
|
from setuptools import find_packages, setup
setup(
name="balrog",
version="1.0",
description="Mozilla's Update Server",
author="Ben Hearsum",
author_email="ben@hearsum.ca",
packages=find_packages(exclude=["vendor"]),
include_package_data=True,
install_requires=[
"flask==0.10.1",
"Werkzeug==0.9.6",
"wtforms==2.0.1",
"flask-wtf==0.10.2",
"sqlalchemy-migrate==0.7.2",
"tempita==0.5.1",
"decorator==3.3.3",
"blinker==1.2",
"cef==0.5",
"flask-compress==1.0.2",
"itsdangerous==0.24",
"repoze.lru==0.6",
],
url="https://github.com/mozilla/balrog",
)
|
from setuptools import setup
setup(
name="balrog",
version="1.0",
description="Mozilla's Update Server",
author="Ben Hearsum",
author_email="ben@hearsum.ca",
packages=[
"auslib",
"auslib.admin",
"auslib.admin.views",
"auslib.blobs",
"auslib.migrate",
"auslib.migrate.versions",
"auslib.util",
"auslib.web",
"auslib.web.views",
],
include_package_data=True,
install_requires=[
"flask==0.10.1",
"Werkzeug==0.9.6",
"wtforms==2.0.1",
"flask-wtf==0.10.2",
"sqlalchemy-migrate==0.7.2",
"tempita==0.5.1",
"decorator==3.3.3",
"blinker==1.2",
"cef==0.5",
"flask-compress==1.0.2",
"itsdangerous==0.24",
"repoze.lru==0.6",
],
url="https://github.com/mozilla/balrog",
)
|
Make the dark theme for JavaScript look a bit like Monokai.
|
module.exports = {
name: 'dark-syntax-theme',
installInto: function (pen) {
pen.installTheme('html', {
jsComment: 'gray',
jsFunctionName: 'jsKeyword',
jsKeyword: '#F92672', // red
jsNumber: [],
jsPrimitive: 'white',
jsRegexp: '#E6DB74', // yellow
jsString: '#E6DB74', // yellow
jsKey: '#A6E22E', // green
diffAddedHighlight: ['bgGreen', 'black'],
diffRemovedHighlight: ['bgRed', 'black'],
prismComment: 'jsComment',
prismSymbol: [ '#800080', 'bold' ], // purple
prismString: 'jsString',
prismOperator: '#F92672',
prismKeyword: 'jsKeyword',
prismRegex: 'jsRegexp',
prismFunction: []
});
}
};
|
module.exports = {
name: 'dark-syntax-theme',
installInto: function (pen) {
pen.installTheme('html', {
jsComment: 'gray',
jsFunctionName: 'jsKeyword',
jsKeyword: '#FFAA27',
jsNumber: [],
jsPrimitive: 'white',
jsRegexp: '#C6FF3C',
jsString: '#3CDAFF',
jsKey: '#939393',
diffAddedHighlight: ['bgGreen', 'black'],
diffRemovedHighlight: ['bgRed', 'black'],
prismComment: 'jsComment',
prismSymbol: 'jsPrimitive',
prismString: 'jsString',
prismOperator: 'jsString',
prismKeyword: 'jsKeyword',
prismRegex: 'jsRegexp',
prismFunction: []
});
}
};
|
Add a TODO to make a client for my API
|
import { call, put, takeEvery } from 'redux-saga/effects';
import _ from 'lodash';
import { sumPlayerRanks } from './utils';
import {
PLAYERS_FETCH_REQUESTED,
PLAYERS_FETCH_SUCCEEDED,
PLAYERS_FETCH_FAILED,
PLAYER_COLUMNS
} from './constants';
import request from 'superagent';
//TODO: Make a client for my API
const playerUrl = 'http://127.0.0.1:8080/api/v1/player';
function* fetchPlayers() {
try {
const res = yield call(() => request(playerUrl));
/* Delete unneeded columns and calculate rank sum */
let players = res.body.data.map( x => {
return Object.assign(
_.pick(x, PLAYER_COLUMNS),
{ sum: sumPlayerRanks(x) }
)
});
yield put({type: PLAYERS_FETCH_SUCCEEDED, players: players});
} catch (e) {
yield put({type: PLAYERS_FETCH_FAILED, message: e.message});
/* try again */
put({type: PLAYERS_FETCH_REQUESTED});
}
}
function* takeEveryPlayersFetchRequest() {
yield takeEvery(PLAYERS_FETCH_REQUESTED, fetchPlayers)
}
export default takeEveryPlayersFetchRequest;
|
import { call, put, takeEvery } from 'redux-saga/effects';
import _ from 'lodash';
import { sumPlayerRanks } from './utils';
import {
PLAYERS_FETCH_REQUESTED,
PLAYERS_FETCH_SUCCEEDED,
PLAYERS_FETCH_FAILED,
PLAYER_COLUMNS
} from './constants';
import request from 'superagent';
const playerUrl = 'http://127.0.0.1:8080/api/v1/player';
function* fetchPlayers() {
try {
const res = yield call(() => request(playerUrl));
/* Delete unneeded columns and calculate rank sum */
let players = res.body.data.map( x => {
return Object.assign(
_.pick(x, PLAYER_COLUMNS),
{ sum: sumPlayerRanks(x) }
)
});
console.log(players);
yield put({type: PLAYERS_FETCH_SUCCEEDED, players: players});
} catch (e) {
yield put({type: PLAYERS_FETCH_FAILED, message: e.message});
/* try again */
put({type: PLAYERS_FETCH_REQUESTED});
}
}
function* takeEveryPlayersFetchRequest() {
yield takeEvery(PLAYERS_FETCH_REQUESTED, fetchPlayers)
}
export default takeEveryPlayersFetchRequest;
|
Add an event emitter to I/O.
|
var stream = require('stream'),
events = require('events'),
run = require('./run'),
exit = require('./exit'),
slice = [].slice
function createStream (s) {
return s || new stream.PassThrough
}
module.exports = function (module, source, program) {
if (typeof source == 'function') {
program = source
source = module.filename
}
var invoke = module.exports = function (env, argv, options, callback) {
var io = {
stdout: createStream(options.stdout),
stdin: createStream(options.stdin),
stderr: createStream(options.stderr),
events: new events.EventEmitter
}
run(source, env, argv, io, program, callback)
return io
}
if (module === require.main) {
invoke(process.env, process.argv.slice(2), {
stdout: process.stdout,
stdin: process.stdin,
stderr: process.stderr
}, exit(process))
}
}
|
var stream = require('stream'),
run = require('./run'),
exit = require('./exit'),
slice = [].slice
function createStream (s) {
return s || new stream.PassThrough
}
module.exports = function (module, source, program) {
if (typeof source == 'function') {
program = source
source = module.filename
}
var invoke = module.exports = function (env, argv, options, callback) {
var io = {
stdout: createStream(options.stdout),
stdin: createStream(options.stdin),
stderr: createStream(options.stderr)
}
run(source, env, argv, io, program, callback)
return io
}
if (module === require.main) {
invoke(process.env, process.argv.slice(2), {
stdout: process.stdout,
stdin: process.stdin,
stderr: process.stderr
}, exit(process))
}
}
|
Change modfied variable to true
|
# -*- coding: utf-8 -*-
"""
This class represents an interface of an image processing algorithm.
The class abstracts algorithm interface from user so he can fully focus on his
algorithm implementation.
"""
__author__ = "p.shkadzko@gmail.com"
class Algorithm:
def __init__(self):
"""
Algorithm class
Instance vars:
self.modified -- True if Algorithm settings were modified
self.belongs -- A step name to which current algorithm belongs
"""
self.modified = True
# for debugging only
print '> Algorithm: I am "%s" algorithm' % self.name
def belongs(self):
"""Return a step name to which current algorithm belongs."""
return self.parent
def process(self, image):
"""
A user must override this method in order to comply with the interface.
"""
raise NotImplementedError
def get_name(self):
return self.name
def set_modified(self):
"""Set True if method settings were modified."""
print '> Algorithm: "%s" was modified.' % (self.name)
self.modified = True
def get_modified(self):
return self.modified
def report_pip(self):
pass
if __name__ == '__main__':
pass
|
# -*- coding: utf-8 -*-
"""
This class represents an interface of an image processing algorithm.
The class abstracts algorithm interface from user so he can fully focus on his
algorithm implementation.
"""
__author__ = "p.shkadzko@gmail.com"
class Algorithm:
def __init__(self):
"""
Algorithm class
Instance vars:
self.modified -- True if Algorithm settings were modified
self.belongs -- A step name to which current algorithm belongs
"""
self.modified = False
# for debugging only
print '> Algorithm: I am "%s" algorithm' % self.name
def belongs(self):
"""Return a step name to which current algorithm belongs."""
return self.parent
def process(self, image):
"""
A user must override this method in order to comply with the interface.
"""
raise NotImplementedError
def get_name(self):
return self.name
def set_modified(self):
"""Set True if method settings were modified."""
print '> Algorithm: "%s" was modified.' % (self.name)
self.modified = True
def get_modified(self):
return self.modified
def report_pip(self):
pass
if __name__ == '__main__':
pass
|
Fix test break for windows: better error handling
|
// +build windows
package buf
import (
"syscall"
)
func checkReadVConstraint(conn syscall.RawConn) (bool, error) {
var isSocketReady = false
var reason error
/*
In Windows, WSARecv system call only support socket connection.
It it required to check if the given fd is of a socket type
Fix https://github.com/v2ray/v2ray-core/issues/1666
Additional Information:
https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-wsarecv
https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-getsockopt
https://docs.microsoft.com/en-us/windows/desktop/WinSock/sol-socket-socket-options
*/
err := conn.Control(func(fd uintptr) {
var val [4]byte
var le = int32(len(val))
err := syscall.Getsockopt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_RCVBUF, &val[0], &le)
if err != nil {
isSocketReady = false
} else {
isSocketReady = true
}
reason = err
})
if err != nil {
return false, err
}
return isSocketReady, reason
}
|
// +build windows
package buf
import (
"syscall"
)
func checkReadVConstraint(conn syscall.RawConn) (bool, error) {
var isSocketReady = false
var reason error
/*
In Windows, WSARecv system call only support socket connection.
It it required to check if the given fd is of a socket type
Fix https://github.com/v2ray/v2ray-core/issues/1666
Additional Information:
https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-wsarecv
https://docs.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-getsockopt
https://docs.microsoft.com/en-us/windows/desktop/WinSock/sol-socket-socket-options
*/
err := conn.Control(func(fd uintptr) {
var val [4]byte
var le = int32(len(val))
err := syscall.Getsockopt(syscall.Handle(fd), syscall.SOL_SOCKET, syscall.SO_RCVBUF, &val[0], &le)
if err != nil {
isSocketReady = false
} else {
isSocketReady = true
}
reason = err
})
return isSocketReady, err
}
|
Update download URL to match current version / tag.
|
from setuptools import setup
setup(name='pagerduty_events_api',
version='0.2.0',
description='Python wrapper for Pagerduty Events API',
url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api',
download_url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api/tarball/0.2.0',
author='Balazs Szerencsi',
author_email='balazs.szerencsi@icloud.com',
license='MIT',
packages=['pagerduty_events_api'],
zip_safe=False,
test_suite='nose.collector',
tests_require=['nose', 'ddt'],
install_requires=['requests'],
keywords=['pagerduty', 'event', 'api', 'incident', 'trigger', 'acknowledge', 'resolve'])
|
from setuptools import setup
setup(name='pagerduty_events_api',
version='0.2.0',
description='Python wrapper for Pagerduty Events API',
url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api',
download_url='https://github.com/BlasiusVonSzerencsi/pagerduty-events-api/tarball/0.1.1',
author='Balazs Szerencsi',
author_email='balazs.szerencsi@icloud.com',
license='MIT',
packages=['pagerduty_events_api'],
zip_safe=False,
test_suite='nose.collector',
tests_require=['nose', 'ddt'],
install_requires=['requests'],
keywords=['pagerduty', 'event', 'api', 'incident', 'trigger', 'acknowledge', 'resolve'])
|
Fix tabbar for requests and expertise
|
/**
* fills the righthandside flexTab-Bar with the relevant tools
* @see packages/rocketchat-livechat/client/ui.js
* @see packages/rocketchat-lib/client/defaultTabBars.js
*/
RocketChat.TabBar.addGroup('starred-messages', ['request', 'expertise']);
RocketChat.TabBar.addGroup('push-notifications', ['request', 'expertise']);
RocketChat.TabBar.addGroup('channel-settings', ['request', 'expertise']);
RocketChat.TabBar.addGroup('members-list', ['request', 'expertise']);
RocketChat.TabBar.addGroup('message-search',['request', 'expertise']);
RocketChat.TabBar.addGroup('uploaded-files-list',['request', 'expertise']);
RocketChat.TabBar.addButton({
groups: ['request', 'expertise', 'live'],
id: 'external-search',
i18nTitle: 'Knowledge_Base',
icon: 'icon-lightbulb',
template: 'dbsAI_externalSearch',
order: 0
});
|
/**
* fills the righthandside flexTab-Bar with the relevant tools
* @see packages/rocketchat-livechat/client/ui.js
* @see packages/rocketchat-lib/client/defaultTabBars.js
*/
RocketChat.TabBar.addGroup('starred-messages', ['request', 'expertise']);
RocketChat.TabBar.addGroup('push-notifications', ['request', 'expertise']);
RocketChat.TabBar.addButton({
groups: ['request', 'expertise', 'live'],
id: 'external-search',
i18nTitle: 'Knowledge_Base',
icon: 'icon-lightbulb',
template: 'dbsAI_externalSearch',
order: 0
});
RocketChat.TabBar.addButton({
groups: ['request', 'expertise'],
id: 'channel-settings',
i18nTitle: 'Room_Info',
icon: 'icon-info-circled',
template: 'channelSettings',
order: 1
});
RocketChat.TabBar.addButton({
groups: ['request', 'expertise'],
id: 'members-list',
i18nTitle: 'Members_List',
icon: 'icon-users',
template: 'membersList',
order: 3
});
RocketChat.TabBar.addButton({
groups: ['request', 'expertise'],
id: 'message-search',
i18nTitle: 'Search',
icon: 'icon-search',
template: 'messageSearch',
order: 10
});
RocketChat.TabBar.addButton({
groups: ['request', 'expertise'],
id: 'uploaded-files-list',
i18nTitle: 'Room_uploaded_file_list',
icon: 'icon-attach',
template: 'uploadedFilesList',
order: 30
});
|
casper: Fix waiting condition in message deletion tests.
We now specifically wait for the length to decrease by one. This seems
like a more deterministic condition to wait on.
Previously we were waiting till the id of the deleted message remained
visible; intuitively, this should have worked but it seems that there
is some race condition that was causing the test to fail sporadically.
|
var common = require('../casper_lib/common.js').common;
common.start_and_log_in();
var last_message_id;
var msgs_qty;
casper.then(function () {
casper.waitUntilVisible("#zhome");
});
casper.then(function () {
msgs_qty = this.evaluate(function () {
return $('#zhome .message_row').length;
});
last_message_id = this.evaluate(function () {
var msg = $('#zhome .message_row:last');
msg.find('.info').click();
$('.delete_message').click();
return msg.attr('id');
});
});
casper.then(function () {
casper.waitUntilVisible("#delete_message_modal", function () {
casper.click('#do_delete_message_button');
});
});
casper.then(function () {
casper.waitFor(function check_length() {
return casper.evaluate(function (expected_length) {
return $('#zhome .message_row').length === expected_length;
}, msgs_qty - 1);
});
});
casper.then(function () {
casper.test.assertDoesntExist(last_message_id);
});
casper.run(function () {
casper.test.done();
});
|
var common = require('../casper_lib/common.js').common;
common.start_and_log_in();
var last_message_id;
var msgs_qty;
casper.then(function () {
casper.waitUntilVisible("#zhome");
});
casper.then(function () {
msgs_qty = this.evaluate(function () {
return $('#zhome .message_row').length;
});
last_message_id = this.evaluate(function () {
var msg = $('#zhome .message_row:last');
msg.find('.info').click();
$('.delete_message').click();
return msg.attr('id');
});
});
casper.then(function () {
casper.waitUntilVisible("#delete_message_modal", function () {
casper.click('#do_delete_message_button');
});
});
casper.then(function () {
casper.waitWhileVisible(last_message_id, function () {
var msgs_after_deleting = casper.evaluate(function () {
return $('#zhome .message_row').length;
});
casper.test.assertEquals(msgs_qty - 1, msgs_after_deleting);
casper.test.assertDoesntExist(last_message_id);
});
});
casper.run(function () {
casper.test.done();
});
|
Make the detection of Node.js environments on Electron strict.
The main process and its child processes should be detected as Node.js environments.
|
/* Copyright 2018 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* globals process */
// NW.js / Electron is a browser context, but copies some Node.js objects; see
// http://docs.nwjs.io/en/latest/For%20Users/Advanced/JavaScript%20Contexts%20in%20NW.js/#access-nodejs-and-nwjs-api-in-browser-context
// https://www.electronjs.org/docs/api/process#processversionselectron-readonly
// https://www.electronjs.org/docs/api/process#processtype-readonly
const isNodeJS =
typeof process === "object" &&
process + "" === "[object process]" &&
!process.versions.nw &&
!(process.versions.electron && process.type && process.type !== "browser");
export { isNodeJS };
|
/* Copyright 2018 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* globals process */
// NW.js / Electron is a browser context, but copies some Node.js objects; see
// http://docs.nwjs.io/en/latest/For%20Users/Advanced/JavaScript%20Contexts%20in%20NW.js/#access-nodejs-and-nwjs-api-in-browser-context
// https://electronjs.org/docs/api/process#processversionselectron
const isNodeJS =
typeof process === "object" &&
process + "" === "[object process]" &&
!process.versions.nw &&
!process.versions.electron;
export { isNodeJS };
|
Rename the loadGroups method to loadCategories
|
package org.monospark.actioncontrol.category;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import org.monospark.actioncontrol.config.ConfigParseException;
import org.monospark.actioncontrol.config.ConfigParser;
import org.spongepowered.api.entity.living.player.Player;
public final class CategoryRegistry {
private static final String PERMISSION_BASE = "actioncontrol.category.";
private Set<Category> allCategories;
CategoryRegistry() {}
public void loadCategories(Path path) throws ConfigParseException {
Path groupsFile = path.resolve("categories.json");
File file = groupsFile.toFile();
try {
if(!file.exists()) {
path.toFile().mkdir();
file.createNewFile();
this.allCategories = Collections.emptySet();
} else {
this.allCategories = ConfigParser.parseConfig(groupsFile);
}
} catch (IOException e) {
throw new ConfigParseException(e);
}
}
public Set<Category> getCategories(Player p) {
return allCategories.stream()
.filter(c -> /* p.hasPermission(PERMISSION_BASE + c.getName()) */ true)
.collect(Collectors.toSet());
}
}
|
package org.monospark.actioncontrol.category;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import org.monospark.actioncontrol.config.ConfigParseException;
import org.monospark.actioncontrol.config.ConfigParser;
import org.spongepowered.api.entity.living.player.Player;
public final class CategoryRegistry {
private static final String PERMISSION_BASE = "actioncontrol.category.";
private Set<Category> allCategories;
CategoryRegistry() {}
public void loadGroups(Path path) throws ConfigParseException {
Path groupsFile = path.resolve("categories.json");
File file = groupsFile.toFile();
try {
if(!file.exists()) {
path.toFile().mkdir();
file.createNewFile();
this.allCategories = Collections.emptySet();
} else {
this.allCategories = ConfigParser.parseConfig(groupsFile);
}
} catch (IOException e) {
throw new ConfigParseException(e);
}
}
public Set<Category> getCategories(Player p) {
return allCategories.stream()
.filter(c -> /* p.hasPermission(PERMISSION_BASE + c.getName()) */ true)
.collect(Collectors.toSet());
}
}
|
Return password when it contains =
Fixes #3
|
// Code based largely on this module:
// https://www.npmjs.org/package/git-credential
function parseOutput(data, callback) {
var output = {};
if (data) {
output = data.toString('utf-8')
.split('\n')
.map(function (line) {
var index = line.indexOf('=');
if (index !== -1) {
return [line.substr(0, index), line.substr(index + 1)];
} else {
return line;
}
})
.filter(function (lineItems) {
// Filter out empty lines
return lineItems.length === 2;
})
.reduce(function (obj, val) {
obj[val[0].trim()] = val[1].trim();
return obj;
}, {});
}
callback(null, output);
}
module.exports = parseOutput;
|
// Code based largely on this module:
// https://www.npmjs.org/package/git-credential
function parseOutput(data, callback) {
var output = {};
if (data) {
output = data.toString('utf-8')
.split('\n')
.map(function (line) {
return line.split('=');
})
.filter(function (lineItems) {
// Filter out empty lines
return lineItems.length === 2;
})
.reduce(function (obj, val) {
obj[val[0].trim()] = val[1].trim();
return obj;
}, {});
}
callback(null, output);
}
module.exports = parseOutput;
|
Add CSV folder setting comment
|
import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
# If this is set to a valid path, all CSV files extracted from emails will be
# stored in sub-folders within it.
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
|
import os
import re
from imap import EmailCheckError, EmailServer
from postgresql import DatabaseServer
CSV_FOLDER = os.getcwd()
# Values come from `EMAIL_SUBJECT_RE`.
CSV_NAME_FORMAT = '{year}-{month}-{day}T{hour}{minute}.csv'
# Restrict emails by sender.
EMAIL_FROM = 'sender@example.com'
# Restrict emails by subject.
EMAIL_SUBJECT_RE = re.compile(''.join([
r'(?P<year>\d{4})',
r'(?P<month>\d{2})',
r'(?P<day>\d{2})',
r'(?P<hour>\d{2})',
r'(?P<minute>\d{2})',
r'\.csv',
]))
LOGGING_FORMAT = '''
- file: %(pathname)s
level: %(levelname)s
line: %(lineno)s
message: |
%(message)s
time: %(asctime)s
'''.strip()
# Values come from `EMAIL_SUBJECT_RE`.
TABLE_NAME_FORMAT = 'data_{year}{month}'
def get_database_client():
con = 'my_username/my_password@database.example.com:5432/my_database'
return DatabaseServer(con)
def get_email_client():
return EmailServer('mail.example.com', 'my_username', 'my_password')
|
Include classes and interfaces with generics
|
<?hh // strict
namespace HHVM\UserDocumentation;
use FredEmmott\DefinitionFinder\ScannedBase;
use FredEmmott\DefinitionFinder\ScannedFunctionAbstract;
use FredEmmott\DefinitionFinder\HasScannedGenerics;
abstract final class ScannedDefinitionFilters {
public static function IsHHSpecific(ScannedBase $def): bool {
$is_hh_specific =
strpos($def->getName(), 'HH\\') === 0
|| strpos($def->getName(), '__SystemLib\\') === 0
|| $def->getAttributes()->containsKey('__HipHopSpecific')
|| strpos($def->getName(), 'fb_') === 0
|| strpos($def->getName(), 'hphp_') === 0;
if ($is_hh_specific) {
return true;
}
if ($def instanceof HasScannedGenerics && $def->getGenericTypes()) {
return true;
}
if (!$def instanceof ScannedFunctionAbstract) {
return false;
}
if ($def->getReturnType()?->getTypeName() === 'Awaitable') {
return true;
}
return false;
}
public static function ShouldNotDocument(ScannedBase $def): bool {
return strpos($def->getName(), "__SystemLib\\") === 0;
}
}
|
<?hh // strict
namespace HHVM\UserDocumentation;
use FredEmmott\DefinitionFinder\ScannedBase;
use FredEmmott\DefinitionFinder\ScannedFunctionAbstract;
abstract final class ScannedDefinitionFilters {
public static function IsHHSpecific(ScannedBase $def): bool {
$is_hh_specific =
strpos($def->getName(), 'HH\\') === 0
|| strpos($def->getName(), '__SystemLib\\') === 0
|| $def->getAttributes()->containsKey('__HipHopSpecific')
|| strpos($def->getName(), 'fb_') === 0
|| strpos($def->getName(), 'hphp_') === 0;
if ($is_hh_specific) {
return true;
}
if (!$def instanceof ScannedFunctionAbstract) {
return false;
}
if ($def->getReturnType()?->getTypeName() === 'Awaitable') {
return true;
}
if (count($def->getGenericTypes()) > 0) {
return true;
}
return false;
}
public static function ShouldNotDocument(ScannedBase $def): bool {
return strpos($def->getName(), "__SystemLib\\") === 0;
}
}
|
Use some PHP 5.4 constants unconditionally
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Translation\Dumper;
use Symfony\Component\Translation\MessageCatalogue;
/**
* JsonFileDumper generates an json formatted string representation of a message catalogue.
*
* @author singles
*/
class JsonFileDumper extends FileDumper
{
/**
* {@inheritdoc}
*/
public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = [])
{
if (isset($options['json_encoding'])) {
$flags = $options['json_encoding'];
} else {
$flags = JSON_PRETTY_PRINT;
}
return json_encode($messages->all($domain), $flags);
}
/**
* {@inheritdoc}
*/
protected function getExtension()
{
return 'json';
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Translation\Dumper;
use Symfony\Component\Translation\MessageCatalogue;
/**
* JsonFileDumper generates an json formatted string representation of a message catalogue.
*
* @author singles
*/
class JsonFileDumper extends FileDumper
{
/**
* {@inheritdoc}
*/
public function formatCatalogue(MessageCatalogue $messages, $domain, array $options = [])
{
if (isset($options['json_encoding'])) {
$flags = $options['json_encoding'];
} else {
$flags = \defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0;
}
return json_encode($messages->all($domain), $flags);
}
/**
* {@inheritdoc}
*/
protected function getExtension()
{
return 'json';
}
}
|
Modify Zika fasta fields to match default VIPRBRC ordering.
|
import os, re, time, datetime, csv, sys
import rethinkdb as r
from Bio import SeqIO
from vdb_upload import vdb_upload
from vdb_upload import parser
class Zika_vdb_upload(vdb_upload):
def __init__(self, fasta_fields, fasta_fname, database, virus, source, locus=None, vsubtype=None, authors=None, path=None, auth_key=None):
'''
:param fasta_fields: Dictionary defining position in fasta field to be included in database
'''
vdb_upload.__init__(self, fasta_fields, fasta_fname, database, virus, source, locus, vsubtype, authors, path, auth_key)
if __name__=="__main__":
args = parser.parse_args()
fasta_fields = {0:'accession', 2:'strain', 4:'date', 6:'country'}
# 0 1 2 3 4 5 6
# >KU647676|Zika_virus|MRS_OPY_Martinique_PaRi_2015|NA|2015_12|Human|Martinique
run = Zika_vdb_upload(fasta_fields, fasta_fname=args.fname, database=args.database, virus=args.virus, source=args.source, locus=args.locus, vsubtype=args.subtype, authors=args.authors, path=args.path)
run.upload()
|
import os, re, time, datetime, csv, sys
import rethinkdb as r
from Bio import SeqIO
from vdb_upload import vdb_upload
from vdb_upload import parser
class Zika_vdb_upload(vdb_upload):
def __init__(self, fasta_fields, fasta_fname, database, virus, source, locus=None, vsubtype=None, authors=None, path=None, auth_key=None):
'''
:param fasta_fields: Dictionary defining position in fasta field to be included in database
'''
vdb_upload.__init__(self, fasta_fields, fasta_fname, database, virus, source, locus, vsubtype, authors, path, auth_key)
if __name__=="__main__":
args = parser.parse_args()
fasta_fields = {0:'accession', 1:'strain', 2:'date', 4:'country', 5:'division', 6:'location'}
run = Zika_vdb_upload(fasta_fields, fasta_fname=args.fname, database=args.database, virus=args.virus, source=args.source, locus=args.locus, vsubtype=args.subtype, authors=args.authors, path=args.path)
run.upload()
|
Fix EventEmitter on Node 0.10
|
'use strict';
var acquire = require('acquire'),
mapKeys = require('map-keys'),
camelCase = require('camel-case');
var fs = require('fs'),
path = require('path'),
EventEmitter = require('events').EventEmitter;
module.exports = function (repl, dir) {
var ee = new EventEmitter;
process.nextTick(function () {
var modules = acquire.resolve({ basedir: dir,
skipFailures: ee.emit.bind(ee, 'fail') });
modules = mapKeys(modules, camelCase);
Object.keys(modules).forEach(function (name) {
try {
repl.context[name] = require(modules[name]);
ee.emit('load', name, modules[name]);
}
catch (e) {
ee.emit('fail', name, modules[name]);
}
});
ee.emit('end');
});
return ee;
};
|
'use strict';
var acquire = require('acquire'),
mapKeys = require('map-keys'),
camelCase = require('camel-case');
var fs = require('fs'),
path = require('path'),
EventEmitter = require('events');
module.exports = function (repl, dir) {
var ee = new EventEmitter;
process.nextTick(function () {
var modules = acquire.resolve({ basedir: dir,
skipFailures: ee.emit.bind(ee, 'fail') });
modules = mapKeys(modules, camelCase);
Object.keys(modules).forEach(function (name) {
try {
repl.context[name] = require(modules[name]);
ee.emit('load', name, modules[name]);
}
catch (e) {
ee.emit('fail', name, modules[name]);
}
});
ee.emit('end');
});
return ee;
};
|
Make expand hints underline on mouseenter
|
function expandInfo(elem) {
$(elem).children('.section-expand-hint').slideUp();
$(elem).children('.section-hidden-text').slideDown();
}
function retractInfo(elem) {
$(elem).children('.section-expand-hint').slideDown();
$(elem).children('.section-hidden-text').slideUp();
}
$(document).ready( function() {
/* Create "Expand..." hint: */
expandHint = $("<em>Expand</em>").addClass('section-text section-expand-hint');
$(".expandable-section").append(expandHint);
$(".info-section").mouseenter(function(ev) {
$(this).children('.section-expand-hint').css('text-decoration', 'underline');
});
$(".info-section").mouseleave(function(ev) {
$(this).children('.section-expand-hint').css('text-decoration', 'none');
});
$(".info-section").click(function(ev) {
if($(this).data("toggle")) {
$(this).data("toggle", false);
retractInfo(this);
} else {
$(this).data("toggle", true);
expandInfo(this);
}
})
})
|
function expandInfo(elem) {
$(elem).children('.section-expand-hint').slideUp();
$(elem).children('.section-hidden-text').slideDown();
}
function retractInfo(elem) {
$(elem).children('.section-expand-hint').slideDown();
$(elem).children('.section-hidden-text').slideUp();
}
$(document).ready( function() {
/* Create "Expand..." hint: */
expandHint = $("<em>Expand</em>").addClass('section-text section-expand-hint');
$(".expandable-section").append(expandHint);
$(".info-section").click(function(ev) {
if($(this).data("toggle")) {
$(this).data("toggle", false);
retractInfo(this);
} else {
$(this).data("toggle", true);
expandInfo(this);
}
})
})
|
Fix extra spaces after callstack print
|
package aya;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Stack;
import aya.instruction.variable.GetVariableInstruction;
/**
* Utility class for tracing function calls during Aya execution
* @author npaul
*
*/
public class CallStack {
private Stack<GetVariableInstruction> _stack;
public CallStack() {
_stack = new Stack<GetVariableInstruction>();
}
public void push(GetVariableInstruction var) {
_stack.push(var);
}
public void pop() {
_stack.pop();
}
public void reset() {
_stack.clear();
}
public String toString() {
StringBuilder sb = new StringBuilder("Function call traceback:\n Error ");
ArrayList<GetVariableInstruction> stack_list = new ArrayList<GetVariableInstruction>(_stack.size());
for (GetVariableInstruction l : _stack) stack_list.add(l);
Collections.reverse(stack_list);
for (GetVariableInstruction l : stack_list)
{
sb.append("in: ");
sb.append(l.toString());
sb.append("\n ");
}
sb.append("\n");
return sb.toString();
}
public boolean isEmpty() {
return _stack.isEmpty();
}
}
|
package aya;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Stack;
import aya.instruction.variable.GetVariableInstruction;
/**
* Utility class for tracing function calls during Aya execution
* @author npaul
*
*/
public class CallStack {
private Stack<GetVariableInstruction> _stack;
public CallStack() {
_stack = new Stack<GetVariableInstruction>();
}
public void push(GetVariableInstruction var) {
_stack.push(var);
}
public void pop() {
_stack.pop();
}
public void reset() {
_stack.clear();
}
public String toString() {
StringBuilder sb = new StringBuilder("Function call traceback:\n Error ");
ArrayList<GetVariableInstruction> stack_list = new ArrayList<GetVariableInstruction>(_stack.size());
for (GetVariableInstruction l : _stack) stack_list.add(l);
Collections.reverse(stack_list);
for (GetVariableInstruction l : stack_list)
{
sb.append("in: ");
sb.append(l.toString());
sb.append("\n ");
}
return sb.toString();
}
public boolean isEmpty() {
return _stack.isEmpty();
}
}
|
Stop bot after 30 consecutive failed API calls
|
var _ = require('underscore');
var async = require('async');
var logger = require('./loggingservice.js');
var api = require('./api.js');
var downloader = function(refreshInterval){
this.refreshInterval = refreshInterval;
this.noTradesCount = 0;
_.bindAll(this, 'start', 'stop', 'processTrades');
};
//---EventEmitter Setup
var Util = require('util');
var EventEmitter = require('events').EventEmitter;
Util.inherits(downloader, EventEmitter);
//---EventEmitter Setup
downloader.prototype.processTrades = function(err, trades) {
if(!err) {
if(trades.length === 0) {
this.noTradesCount += 1;
} else {
this.noTradesCount = 0;
}
if(this.noTradesCount >= 30) {
logger.error('Haven\'t received data from the API for 30 consecutive attempts, stopping qpplication');
return process.exit();
}
this.emit('update', trades);
}
};
downloader.prototype.start = function() {
logger.log('Downloader started!');
api.getTrades(this.processTrades);
this.downloadInterval = setInterval(function(){
api.getTrades(this.processTrades);
}.bind(this),1000 * this.refreshInterval);
};
downloader.prototype.stop = function() {
clearInterval(this.downloadInterval);
logger.log('Downloader stopped!');
};
module.exports = downloader;
|
var _ = require('underscore');
var async = require('async');
var logger = require('./loggingservice.js');
var api = require('./api.js');
var downloader = function(refreshInterval){
this.refreshInterval = refreshInterval;
_.bindAll(this, 'start', 'stop', 'processTrades');
};
//---EventEmitter Setup
var Util = require('util');
var EventEmitter = require('events').EventEmitter;
Util.inherits(downloader, EventEmitter);
//---EventEmitter Setup
downloader.prototype.processTrades = function(err, trades) {
if(!err) {
this.emit('update', trades);
}
};
downloader.prototype.start = function() {
logger.log('Downloader started!');
api.getTrades(this.processTrades);
this.downloadInterval = setInterval(function(){
api.getTrades(this.processTrades);
}.bind(this),1000 * this.refreshInterval);
};
downloader.prototype.stop = function() {
clearInterval(this.downloadInterval);
logger.log('Downloader stopped!');
};
module.exports = downloader;
|
Change the default sort to be by name
|
Meteor.methods({
groupsList: function(nameFilter, limit, sort) {
if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'groupsList' });
}
let options = {
fields: { name: 1 },
sort: { name: 1 }
};
//Verify the limit param is a number
if (_.isNumber(limit)) {
options.limit = limit;
}
//Verify there is a sort option and it's a string
if (_.trim(sort)) {
switch (sort) {
case 'name':
options.sort = { name: 1 };
break;
case 'msgs':
options.sort = { msgs: -1 };
break;
}
}
//Determine if they are searching or not, base it upon the name field
if (nameFilter) {
return { groups: RocketChat.models.Rooms.findByTypeAndNameContainingUsername('p', new RegExp(s.trim(s.escapeRegExp(nameFilter)), 'i'), Meteor.user().username, options).fetch() };
} else {
let roomIds = _.pluck(RocketChat.models.Subscriptions.findByTypeAndUserId('p', Meteor.userId()).fetch(), 'rid');
return { groups: RocketChat.models.Rooms.findByIds(roomIds, options).fetch() };
}
}
});
|
Meteor.methods({
groupsList: function(nameFilter, limit, sort) {
if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'groupsList' });
}
let options = {
fields: { name: 1 },
sort: { msgs: -1 }
};
//Verify the limit param is a number
if (_.isNumber(limit)) {
options.limit = limit;
}
//Verify there is a sort option and it's a string
if (_.trim(sort)) {
switch (sort) {
case 'name':
options.sort = { name: 1 };
break;
case 'msgs':
options.sort = { msgs: -1 };
break;
}
}
//Determine if they are searching or not, base it upon the name field
if (nameFilter) {
return { groups: RocketChat.models.Rooms.findByTypeAndNameContainingUsername('p', new RegExp(s.trim(s.escapeRegExp(nameFilter)), 'i'), Meteor.user().username, options).fetch() };
} else {
let roomIds = _.pluck(RocketChat.models.Subscriptions.findByTypeAndUserId('p', Meteor.userId()).fetch(), 'rid');
return { groups: RocketChat.models.Rooms.findByIds(roomIds, options).fetch() };
}
}
});
|
Fix artisan error for empty module
|
<?php namespace Pingpong\Modules;
use Illuminate\Foundation\Application;
use Illuminate\Support\Str;
class ModuleFinder
{
/**
* @var \Illuminate\Foundation\Application
*/
protected $app;
/**
* Constructor.
*
* @param \Illuminate\Foundation\Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
$this->files = $app['files'];
}
/**
* Get all modules.
*
* @return array
*/
public function all()
{
$modules = array();
if($this->getDirectories())
{
foreach ($this->getDirectories() as $module) {
$name = basename($module);
if( ! Str::startsWith($name, '.'))
{
$modules[] = $name;
}
}
}
return $modules;
}
/**
* Get all directories from modules path.
*
* @return string
*/
protected function getDirectories()
{
if(is_dir($dir = $this->getModulesPath()))
{
return $this->files->directories($dir);
}
return null;
}
/**
* Get modules path.
*
* @return string
*/
protected function getModulesPath()
{
return $this->app['modules']->getPath();
}
}
|
<?php namespace Pingpong\Modules;
use Illuminate\Foundation\Application;
use Illuminate\Support\Str;
class ModuleFinder
{
/**
* @var \Illuminate\Foundation\Application
*/
protected $app;
/**
* Constructor.
*
* @param \Illuminate\Foundation\Application $app
*/
public function __construct(Application $app)
{
$this->app = $app;
$this->files = $app['files'];
}
/**
* Get all modules.
*
* @return array
*/
public function all()
{
$modules = array();
foreach ($this->getDirectories() as $module) {
$name = basename($module);
if( ! Str::startsWith($name, '.'))
{
$modules[] = $name;
}
}
return $modules;
}
/**
* Get all directories from modules path.
*
* @return string
*/
protected function getDirectories()
{
return $this->files->directories($this->getModulesPath());
}
/**
* Get modules path.
*
* @return string
*/
protected function getModulesPath()
{
return $this->app['modules']->getPath();
}
}
|
Test that there is only one entry in the DB.
|
package javaeems.chapter1.model;
import static org.junit.Assert.*;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ModelEJBTest {
private ModelEJB ejb;
private EntityManagerFactory emf;
@Before
public void setUp() {
ejb = new ModelEJB();
emf = Persistence.createEntityManagerFactory("ejb-tests-pu");
ejb.em = emf.createEntityManager();
}
@After
public void tearDown() {
if (ejb.em != null) {
ejb.em.close();
}
if (emf != null) {
emf.close();
}
}
@Test(expected=MessageException.class)
public void testNothingInDB() throws MessageException {
ejb.getStoredMessage();
}
@Test
public void testSetAndGet() throws MessageException {
EntityTransaction tx = ejb.em.getTransaction();
try {
tx.begin();
ejb.putUserMessage("hello");
ejb.putUserMessage("some statistically improbable phrase");
} finally {
tx.commit();
}
long numEntries = (long) ejb.em.createQuery("select count(m) from Message m").getSingleResult();
assertEquals(1, numEntries);
String message = ejb.getStoredMessage();
assertTrue(message.contains("some statistically improbable phrase"));
}
}
|
package javaeems.chapter1.model;
import static org.junit.Assert.*;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ModelEJBTest {
private ModelEJB ejb;
private EntityManagerFactory emf;
@Before
public void setUp() {
ejb = new ModelEJB();
emf = Persistence.createEntityManagerFactory("ejb-tests-pu");
ejb.em = emf.createEntityManager();
}
@After
public void tearDown() {
if (ejb.em != null) {
ejb.em.close();
}
if (emf != null) {
emf.close();
}
}
@Test(expected=MessageException.class)
public void testNothingInDB() throws MessageException {
ejb.getStoredMessage();
}
@Test
public void testSetAndGet() throws MessageException {
EntityTransaction tx = ejb.em.getTransaction();
try {
tx.begin();
ejb.putUserMessage("hello");
ejb.putUserMessage("some statistically improbable phrase");
} finally {
tx.commit();
}
String message = ejb.getStoredMessage();
assertTrue(message.contains("some statistically improbable phrase"));
}
}
|
Fix inverted array read check
|
package us.myles.ViaVersion.api.type.types;
import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
import us.myles.ViaVersion.api.type.Type;
public class ByteArrayType extends Type<byte[]> {
public ByteArrayType() {
super(byte[].class);
}
@Override
public void write(ByteBuf buffer, byte[] object) throws Exception {
Type.VAR_INT.write(buffer, object.length);
buffer.writeBytes(object);
}
@Override
public byte[] read(ByteBuf buffer) throws Exception {
int length = Type.VAR_INT.read(buffer);
Preconditions.checkArgument(buffer.isReadable(length), "Length is fewer than readable bytes");
byte[] array = new byte[length];
buffer.readBytes(array);
return array;
}
}
|
package us.myles.ViaVersion.api.type.types;
import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
import us.myles.ViaVersion.api.type.Type;
public class ByteArrayType extends Type<byte[]> {
public ByteArrayType() {
super(byte[].class);
}
@Override
public void write(ByteBuf buffer, byte[] object) throws Exception {
Type.VAR_INT.write(buffer, object.length);
buffer.writeBytes(object);
}
@Override
public byte[] read(ByteBuf buffer) throws Exception {
int length = Type.VAR_INT.read(buffer);
Preconditions.checkArgument(!buffer.isReadable(length), "Length is fewer than readable bytes");
byte[] array = new byte[length];
buffer.readBytes(array);
return array;
}
}
|
Use Math to transform duration to seconds
|
'use strict'
const sanitize = require('sanitize-html')
exports.html = html
exports.duration = duration
const allowedTags = [
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'li',
'b', 'i', 'strong', 'em', 'code', 'br', 'div', 'pre'
]
function html (str) {
if (typeof str !== 'string') return null
return sanitize(str, {
allowedTags: allowedTags
})
}
function duration (str) {
if (typeof str !== 'string' || str === '') return null
const tokens = str.split(':').slice(0, 3)
const m = Math.pow(60, tokens.length - 1)
const [s] = tokens.reduce((acc, token) => {
let [s, m] = acc
return [s + token * m, m / 60]
}, [0, m])
return isNaN(s) || s === 0 ? null : s
}
|
'use strict'
const sanitize = require('sanitize-html')
exports.html = html
exports.duration = duration
const allowedTags = [
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'li',
'b', 'i', 'strong', 'em', 'code', 'br', 'div', 'pre'
]
function html (str) {
if (typeof str !== 'string') return null
return sanitize(str, {
allowedTags: allowedTags
})
}
function duration (str) {
if (typeof str !== 'string' || str === '') return null
const tokens = str.split(':')
const l = tokens.length
let multipliers = (() => {
if (l === 1) return [1]
if (l === 2) return [60, 1]
if (l > 2) return [3600, 60, 1]
})()
let s = tokens.reduce((acc, token, i) => {
if (i > 2) return acc
let m = multipliers[i]
return acc + parseInt(token, 10) * m
}, 0)
return isNaN(s) || s === 0 ? null : s
}
|
Set a https url because firefox was being a little bitch.
|
var streamURL = "https://half-shot.uk/stream.json";
var player = document.querySelector("audio#stream_player");
var streamended = true;
var player_interval;
function getStream(){
var rstatus = new Request(streamURL);
fetch(rstatus).then(function(response) {
return response.json()
}).then(function(streamdata) {
var source = streamdata.icestats.source;
if(source["audio_bitrate"] != undefined){
document.querySelector("#stream_offline").hidden = "true";
document.querySelector("#stream_online").hidden = null;
document.querySelector("#stream_listeners").innerHTML = source.listeners;
if(player.paused && streamended){
clearInterval(player_interval);
player.src = source.listenurl + "?nocache=" + (Math.random()*100); //Dumb hack
player.play();
}
streamended = false;
}
else
{
document.querySelector("#stream_offline").hidden = null;
document.querySelector("#stream_online").hidden = "true";
streamended = true;
}
});
}
player.addEventListener("ended", function() { player_interval = setInterval(getStream,5000); }, true);
player_interval = setInterval(getStream,5000);
|
var streamURL = "http://half-shot.uk:8000/status-json.xsl";
var player = document.querySelector("audio#stream_player");
var streamended = true;
var player_interval;
function getStream(){
var rstatus = new Request(streamURL);
fetch(rstatus).then(function(response) {
return response.json()
}).then(function(streamdata) {
var source = streamdata.icestats.source;
if(source["audio_bitrate"] != undefined){
document.querySelector("#stream_offline").hidden = "true";
document.querySelector("#stream_online").hidden = null;
document.querySelector("#stream_listeners").innerHTML = source.listeners;
if(player.paused && streamended){
clearInterval(player_interval);
player.src = source.listenurl + "?nocache=" + (Math.random()*100); //Dumb hack
player.play();
}
streamended = false;
}
else
{
document.querySelector("#stream_offline").hidden = null;
document.querySelector("#stream_online").hidden = "true";
streamended = true;
}
});
}
player.addEventListener("ended", function() { player_interval = setInterval(getStream,5000); }, true);
player_interval = setInterval(getStream,5000);
|
Make sure that an empty time component does not trigger infinite onChange events.
|
import moment from 'moment';
import TextFieldComponent from '../textfield/TextField';
export default class TimeComponent extends TextFieldComponent {
static schema(...extend) {
return TextFieldComponent.schema({
type: 'time',
label: 'Time',
key: 'time',
inputType: 'time',
format: 'HH:mm'
}, ...extend);
}
static get builderInfo() {
return {
title: 'Time',
icon: 'clock-o',
group: 'basic',
documentation: 'http://help.form.io/userguide/#time',
weight: 60,
schema: TimeComponent.schema()
};
}
get defaultSchema() {
return TimeComponent.schema();
}
get inputInfo() {
const info = super.inputInfo;
info.attr.type = 'time';
return info;
}
getValueAt(index) {
if (!this.refs.input.length || !this.refs.input[index]) {
return this.emptyValue;
}
const val = this.refs.input[index].value;
if (!val) {
return this.emptyValue;
}
return moment(val, this.component.format).format('HH:mm:ss');
}
setValueAt(index, value) {
this.refs.input[index].value = moment(value, 'HH:mm:ss').format(this.component.format);
}
}
|
import moment from 'moment';
import TextFieldComponent from '../textfield/TextField';
export default class TimeComponent extends TextFieldComponent {
static schema(...extend) {
return TextFieldComponent.schema({
type: 'time',
label: 'Time',
key: 'time',
inputType: 'time',
format: 'HH:mm'
}, ...extend);
}
static get builderInfo() {
return {
title: 'Time',
icon: 'clock-o',
group: 'basic',
documentation: 'http://help.form.io/userguide/#time',
weight: 60,
schema: TimeComponent.schema()
};
}
get defaultSchema() {
return TimeComponent.schema();
}
get inputInfo() {
const info = super.inputInfo;
info.attr.type = 'time';
return info;
}
getValueAt(index) {
if (!this.refs.input.length || !this.refs.input[index]) {
return null;
}
const val = this.refs.input[index].value;
if (!val) {
return '';
}
return moment(val, this.component.format).format('HH:mm:ss');
}
setValueAt(index, value) {
this.refs.input[index].value = moment(value, 'HH:mm:ss').format(this.component.format);
}
}
|
Change standalone module tester to use arguments as input
|
package com.equalize.xpi.af.modules.tester;
import java.util.Hashtable;
import com.equalize.xpi.tester.util.ParameterHelper;
public class ModuleTesterMain {
public static void main(String[] args) {
try {
// Sample arguments:-
// arg0 - com.equalize.xpi.af.modules.FormatConversionBean
// arg1 - C:\Users\ksap086\Desktop\input.txt
// arg2 - C:\Users\ksap086\Desktop\param.txt
// arg3 - C:\Users\ksap086\Desktop\output.txt
if(args.length < 4)
throw new RuntimeException("Please enter arguments in Run Configuration");
// Module to be tested
String module = args[0];
// Files
String inputFile = args[1];
String paramFile = args[2];
String outFile = args[3];
// Get module parameters and initialize tester
Hashtable<String, String> contextData = ParameterHelper.newInstance(paramFile).getParams();
ModuleTester tester = ModuleTester.newInstance(module, inputFile, contextData);
// Add dynamic configuration
//tester.addDynCfg("http://sap.com/xi/XI/System/File", "FileName", "FileA.txt");
// Execute processing
tester.getDynCfg("before");
tester.execute(outFile);
tester.getDynCfg("after");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.equalize.xpi.af.modules.tester;
import java.util.Hashtable;
import com.equalize.xpi.tester.util.ParameterHelper;
public class ModuleTesterMain {
public static void main(String[] args) {
try {
// Default files
String inputFile = "C:\\Users\\ksap086\\Desktop\\Excel2XML_Scenario1.xlsx";
String paramFile = "C:\\Users\\ksap086\\Desktop\\Excel2XML_Scenario1_param.txt";
String outFile = "C:\\Users\\ksap086\\Desktop\\output.txt";
// Module to be tested
String module = "com.equalize.xpi.af.modules.FormatConversionBean";
// Get module parameters and initialize tester
Hashtable<String, String> contextData = ParameterHelper.newInstance(paramFile).getParams();
ModuleTester tester = ModuleTester.newInstance(module, inputFile, contextData);
// Add dynamic configuration
tester.addDynCfg("http://sap.com/xi/XI/System/File", "FileName", "FileA.txt");
// Execute processing
tester.getDynCfg("before");
tester.execute(outFile);
tester.getDynCfg("after");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Update chosen theme in ChangeThemeView on theme change
|
pageflow.ChangeThemeView = Backbone.Marionette.ItemView.extend({
template: 'templates/change_theme',
ui: {
changeThemeButton: '.change_theme',
labelText: 'label .name'
},
events: {
'click .change_theme': function() {
pageflow.ChangeThemeDialogView.open({
model: this.model,
themes: this.options.themes
});
}
},
initialize: function(options) {
this.listenTo(this.model, 'change:theme_name', this.render);
},
onRender: function() {
this.ui.labelText.text(this.labelText());
},
labelText: function() {
return this.options.label || this.labelPrefix() + ': ' + this.localizedThemeName();
},
labelPrefix: function() {
return I18n.t('pageflow.editor.templates.change_theme.current_prefix');
},
localizedThemeName: function() {
return I18n.t('pageflow.' + this.model.get('theme_name') + '_theme.name');
}
});
|
pageflow.ChangeThemeView = Backbone.Marionette.ItemView.extend({
template: 'templates/change_theme',
ui: {
changeThemeButton: '.change_theme',
labelText: 'label .name'
},
events: {
'click .change_theme': function() {
pageflow.ChangeThemeDialogView.open({
model: this.model,
themes: this.options.themes
});
}
},
onRender: function() {
this.ui.labelText.text(this.labelText());
},
labelText: function() {
return this.options.label || this.labelPrefix() + ': ' + this.localizedThemeName();
},
labelPrefix: function() {
return I18n.t('pageflow.editor.templates.change_theme.current_prefix');
},
localizedThemeName: function() {
return I18n.t('pageflow.' + this.model.get('theme_name') + '_theme.name');
}
});
|
Enable custom map loaders to setOwnedTextures when not residing in
the *.tiled namespace
|
package com.badlogic.gdx.maps.tiled;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.maps.Map;
import com.badlogic.gdx.utils.Array;
/**
* @brief Represents a tiled map, adds the concept of tiles and tilesets
*
* @see Map
*/
public class TiledMap extends Map {
private TiledMapTileSets tilesets;
private Array<Texture> ownedTextures;
/**
* @return collection of tilesets for this map
*/
public TiledMapTileSets getTileSets() {
return tilesets;
}
/**
* Creates empty TiledMap
*/
public TiledMap() {
tilesets = new TiledMapTileSets();
}
/**
* Used by TmxMapLoader to set textures when loading the map
* directly, without {@link AssetManager}. To be disposed in
* {@link #dispose()}.
* @param textures
*/
public void setOwnedTextures(Array<Texture> textures) {
this.ownedTextures = textures;
}
@Override
public void dispose() {
if(ownedTextures != null) {
for(Texture texture: ownedTextures) {
texture.dispose();
}
}
}
}
|
package com.badlogic.gdx.maps.tiled;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.maps.Map;
import com.badlogic.gdx.utils.Array;
/**
* @brief Represents a tiled map, adds the concept of tiles and tilesets
*
* @see Map
*/
public class TiledMap extends Map {
private TiledMapTileSets tilesets;
private Array<Texture> ownedTextures;
/**
* @return collection of tilesets for this map
*/
public TiledMapTileSets getTileSets() {
return tilesets;
}
/**
* Creates empty TiledMap
*/
public TiledMap() {
tilesets = new TiledMapTileSets();
}
/**
* Used by TmxMapLoader to set textures when loading the map
* directly, without {@link AssetManager}. To be disposed in
* {@link #dispose()}.
* @param textures
*/
void setOwnedTextures(Array<Texture> textures) {
this.ownedTextures = textures;
}
@Override
public void dispose() {
if(ownedTextures != null) {
for(Texture texture: ownedTextures) {
texture.dispose();
}
}
}
}
|
Use workspace.root() instead of workspace.path()
|
var Watcher = require('large-watcher');
module.exports = function(codebox) {
var events = codebox.events;
codebox.logger.log("Starting the file watcher");
var watcher = Watcher(codebox.workspace.root(), 2).start();
// Handle deleted files
watcher.on('deleted', function(files) {
codebox.events.emit('fs:deleted', files);
});
// Handle modified files
watcher.on('modified', function(files) {
codebox.events.emit('fs:modified', files);
});
// Handle created files
watcher.on('created', function(files) {
codebox.events.emit('fs:created', files);
});
// Handler errors
watcher.on('error', function(err) {
codebox.logger.error(err);
});
codebox.logger.log("File watcher started");
};
|
var Watcher = require('large-watcher');
module.exports = function(codebox) {
var events = codebox.events;
codebox.logger.log("Starting the file watcher");
codebox.workspace.path()
.then(function(path) {
var watcher = Watcher(path, 2).start();
// Handle deleted files
watcher.on('deleted', function(files) {
codebox.events.emit('fs:deleted', files);
});
// Handle modified files
watcher.on('modified', function(files) {
codebox.events.emit('fs:modified', files);
});
// Handle created files
watcher.on('created', function(files) {
codebox.events.emit('fs:created', files);
});
// Handler errors
watcher.on('error', function(err) {
codebox.logger.error(err);
});
codebox.logger.log("File watcher started");
});
};
|
Test if the DOI was actually created on DataCite
|
#!/usr/bin/env python
# encoding: utf-8
#
# This file is part of ckanext-doi
# Created by the Natural History Museum in London, UK
import time
import nose
from ckanext.doi.lib.api import DataciteClient
from ckantest.models import TestBase
from datacite.errors import DataCiteError
import constants
class TestAPI(TestBase):
plugins = [u'doi']
persist = {
u'ckanext.doi.debug': True
}
def test_generate_new_doi(self):
api = DataciteClient()
doi = api.generate_doi()
nose.tools.assert_is_instance(doi, (str, unicode))
def test_mint_new_doi(self):
api = DataciteClient()
doi = api.generate_doi()
pkg_id = u'abcd1234'
with nose.tools.assert_raises(DataCiteError):
api.mint_doi(doi, pkg_id)
api.set_metadata(doi, constants.XML_DICT)
api.mint_doi(doi, pkg_id)
time.sleep(10) # give datacite time to update
datacite_url = api.client.doi_get(doi)
nose.tools.assert_is_not_none(datacite_url)
def test_datacite_authentication(self):
api = DataciteClient()
nose.tools.assert_is_not_none(api.client)
|
#!/usr/bin/env python
# encoding: utf-8
#
# This file is part of ckanext-doi
# Created by the Natural History Museum in London, UK
import nose
from ckanext.doi.lib.api import DataciteClient
from ckantest.models import TestBase
from datacite.errors import DataCiteError
import constants
class TestAPI(TestBase):
plugins = [u'doi']
persist = {
u'ckanext.doi.debug': True
}
def test_generate_new_doi(self):
api = DataciteClient()
doi = api.generate_doi()
nose.tools.assert_is_instance(doi, (str, unicode))
def test_mint_new_doi(self):
api = DataciteClient()
doi = constants.XML_DICT[u'identifier'][u'identifier']
pkg_id = u'abcd1234'
with nose.tools.assert_raises(DataCiteError):
api.mint_doi(doi, pkg_id)
api.set_metadata(doi, constants.XML_DICT)
api.mint_doi(doi, pkg_id)
def test_datacite_authentication(self):
api = DataciteClient()
nose.tools.assert_is_not_none(api.client)
|
Fix case mismatch bug on AeriaMetabox
|
<?php
// Fix case mismatch bug on AeriaMetabox
class_alias('AeriaMetabox','AeriaMetaBox',false);
if(!function_exists('array_merge_replace')) {
function array_merge_replace () {
$arrays = func_get_args();
$base = array_shift($arrays);
if(!is_array($base)) $base = empty($base) ? array() : array($base);
foreach($arrays as $append) {
if(!is_array($append)) $append = array($append);
foreach($append as $key => $value) {
if(!array_key_exists($key, $base) and !is_numeric($key)) {
$base[$key] = $append[$key];
continue;
}
if(is_array($value) or is_array($base[$key])) {
$base[$key] = array_merge_replace($base[$key], $append[$key]);
} else if(is_numeric($key)) {
if(!in_array($value, $base)) $base[] = $value;
} else {
$base[$key] = $value;
}
}
}
return $base;
}
}
|
<?php
if(!function_exists('array_merge_replace')) {
function array_merge_replace () {
$arrays = func_get_args();
$base = array_shift($arrays);
if(!is_array($base)) $base = empty($base) ? array() : array($base);
foreach($arrays as $append) {
if(!is_array($append)) $append = array($append);
foreach($append as $key => $value) {
if(!array_key_exists($key, $base) and !is_numeric($key)) {
$base[$key] = $append[$key];
continue;
}
if(is_array($value) or is_array($base[$key])) {
$base[$key] = array_merge_replace($base[$key], $append[$key]);
} else if(is_numeric($key)) {
if(!in_array($value, $base)) $base[] = $value;
} else {
$base[$key] = $value;
}
}
}
return $base;
}
}
|
Remove experimental flag from the authenticator system 🚀
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Signature;
use Psr\Cache\CacheItemPoolInterface;
/**
* @author Ryan Weaver <ryan@symfonycasts.com>
*
* @final
*/
final class ExpiredSignatureStorage
{
private $cache;
private $lifetime;
public function __construct(CacheItemPoolInterface $cache, int $lifetime)
{
$this->cache = $cache;
$this->lifetime = $lifetime;
}
public function countUsages(string $hash): int
{
$key = rawurlencode($hash);
if (!$this->cache->hasItem($key)) {
return 0;
}
return $this->cache->getItem($key)->get();
}
public function incrementUsages(string $hash): void
{
$item = $this->cache->getItem(rawurlencode($hash));
if (!$item->isHit()) {
$item->expiresAfter($this->lifetime);
}
$item->set($this->countUsages($hash) + 1);
$this->cache->save($item);
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Signature;
use Psr\Cache\CacheItemPoolInterface;
/**
* @author Ryan Weaver <ryan@symfonycasts.com>
*
* @experimental in 5.2
*
* @final
*/
final class ExpiredSignatureStorage
{
private $cache;
private $lifetime;
public function __construct(CacheItemPoolInterface $cache, int $lifetime)
{
$this->cache = $cache;
$this->lifetime = $lifetime;
}
public function countUsages(string $hash): int
{
$key = rawurlencode($hash);
if (!$this->cache->hasItem($key)) {
return 0;
}
return $this->cache->getItem($key)->get();
}
public function incrementUsages(string $hash): void
{
$item = $this->cache->getItem(rawurlencode($hash));
if (!$item->isHit()) {
$item->expiresAfter($this->lifetime);
}
$item->set($this->countUsages($hash) + 1);
$this->cache->save($item);
}
}
|
Adjust POST_LOGIN_VIEW and POST_LOGOUT_VIEW test
|
# -*- coding: utf-8 -*-
"""
test_configuration
~~~~~~~~~~~~~~~~~~
Basic configuration tests
"""
import base64
import pytest
from utils import authenticate, logout
@pytest.mark.settings(
logout_url='/custom_logout',
login_url='/custom_login',
post_login_view='/post_login',
post_logout_view='/post_logout',
default_http_auth_realm='Custom Realm')
def test_view_configuration(client):
response = client.get('/custom_login')
assert b"<h1>Login</h1>" in response.data
response = authenticate(client, endpoint='/custom_login')
assert b'location' in response.headers
assert response.headers['Location'] == 'http://localhost/post_login'
response = logout(client, endpoint='/custom_logout')
assert b'location' in response.headers
assert response.headers['Location'] == 'http://localhost/post_logout'
response = client.get('/http', headers={
'Authorization': 'Basic %s' % base64.b64encode(b"joe@lp.com:bogus")
})
assert b'<h1>Unauthorized</h1>' in response.data
assert 'WWW-Authenticate' in response.headers
assert 'Basic realm="Custom Realm"' == response.headers['WWW-Authenticate']
@pytest.mark.settings(login_user_template='custom_security/login_user.html')
def test_template_configuration(client):
response = client.get('/login')
assert b'CUSTOM LOGIN USER' in response.data
|
# -*- coding: utf-8 -*-
"""
test_configuration
~~~~~~~~~~~~~~~~~~
Basic configuration tests
"""
import base64
import pytest
from utils import authenticate, logout
@pytest.mark.settings(
logout_url='/custom_logout',
login_url='/custom_login',
post_login_view='/post_login',
post_logout_view='/post_logout',
default_http_auth_realm='Custom Realm')
def test_view_configuration(client):
response = client.get('/custom_login')
assert b"<h1>Login</h1>" in response.data
response = authenticate(client, endpoint='/custom_login', follow_redirects=True)
assert b'Post Login' in response.data
response = logout(client, endpoint='/custom_logout', follow_redirects=True)
assert b'Post Logout' in response.data
response = client.get('/http', headers={
'Authorization': 'Basic %s' % base64.b64encode(b"joe@lp.com:bogus")
})
assert b'<h1>Unauthorized</h1>' in response.data
assert 'WWW-Authenticate' in response.headers
assert 'Basic realm="Custom Realm"' == response.headers['WWW-Authenticate']
@pytest.mark.settings(login_user_template='custom_security/login_user.html')
def test_template_configuration(client):
response = client.get('/login')
assert b'CUSTOM LOGIN USER' in response.data
|
Update package name and increment version
|
# inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy-nightly'
__version__ = '2.0.0a1'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__ = 'https://spacy.io'
__author__ = 'Explosion AI'
__email__ = 'contact@explosion.ai'
__license__ = 'MIT'
__docs_models__ = 'https://spacy.io/docs/usage/models'
__download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
__compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json'
__shortcuts__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts.json'
__model_files__ = 'https://raw.githubusercontent.com/explosion/spacy-dev-resources/develop/templates/model/'
|
# inspired from:
# https://python-packaging-user-guide.readthedocs.org/en/latest/single_source_version/
# https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
__title__ = 'spacy'
__version__ = '2.0.0a0'
__summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython'
__uri__ = 'https://spacy.io'
__author__ = 'Explosion AI'
__email__ = 'contact@explosion.ai'
__license__ = 'MIT'
__docs_models__ = 'https://spacy.io/docs/usage/models'
__download_url__ = 'https://github.com/explosion/spacy-models/releases/download'
__compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json'
__shortcuts__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/shortcuts.json'
__model_files__ = 'https://raw.githubusercontent.com/explosion/spacy-dev-resources/develop/templates/model/'
|
Revert "Import spareice per default."
This reverts commit d54042d41b981b3479adb140f2534f76c967fa1c.
|
# -*- coding: utf-8 -*-
from .version import __version__
try:
__TYPHON_SETUP__
except:
__TYPHON_SETUP__ = False
if not __TYPHON_SETUP__:
from . import arts
from . import atmosphere
from . import config
from . import constants
from . import files
from . import geodesy
from . import geographical
from . import latex
from . import math
from . import oem
from . import physics
from . import plots
from . import spectroscopy
from . import trees
from . import utils
from .environment import environ
def test():
"""Use pytest to collect and run all tests in typhon.tests."""
import pytest
return pytest.main(['--pyargs', 'typhon.tests'])
|
# -*- coding: utf-8 -*-
from .version import __version__
try:
__TYPHON_SETUP__
except:
__TYPHON_SETUP__ = False
if not __TYPHON_SETUP__:
from . import arts
from . import atmosphere
from . import config
from . import constants
from . import files
from . import geodesy
from . import geographical
from . import latex
from . import math
from . import oem
from . import physics
from . import plots
from . import spareice
from . import spectroscopy
from . import trees
from . import utils
from .environment import environ
def test():
"""Use pytest to collect and run all tests in typhon.tests."""
import pytest
return pytest.main(['--pyargs', 'typhon.tests'])
|
Insert unused import to test pyflakes in travis
|
import time
from django.conf.urls import patterns, url, include
urlpatterns = patterns('',
url(r'', include(patterns('',
url(r'^$', include('serrano.resources')),
url(r'^fields/', include('serrano.resources.field')),
url(r'^concepts/', include('serrano.resources.concept')),
url(r'^contexts/', include('serrano.resources.context', namespace='contexts')),
url(r'^queries/', include('serrano.resources.query', namespace='queries')),
url(r'^views/', include('serrano.resources.view', namespace='views')),
url(r'^data/', include(patterns('',
url(r'^export/', include('serrano.resources.exporter')),
url(r'^preview/', include('serrano.resources.preview')),
), namespace='data')),
), namespace='serrano')),
)
|
from django.conf.urls import patterns, url, include
urlpatterns = patterns('',
url(r'', include(patterns('',
url(r'^$', include('serrano.resources')),
url(r'^fields/', include('serrano.resources.field')),
url(r'^concepts/', include('serrano.resources.concept')),
url(r'^contexts/', include('serrano.resources.context', namespace='contexts')),
url(r'^queries/', include('serrano.resources.query', namespace='queries')),
url(r'^views/', include('serrano.resources.view', namespace='views')),
url(r'^data/', include(patterns('',
url(r'^export/', include('serrano.resources.exporter')),
url(r'^preview/', include('serrano.resources.preview')),
), namespace='data')),
), namespace='serrano')),
)
|
Make sure cookie-service gets enabled
|
/* load after build_application.js */
window.app.builders.CookieManager || ( window.app.builders.CookieManager = {} );
/**
* @param {Object} service the service description of the according service on the host side
*/
window.app.builders.CookieManager["1.0"] = function(service)
{
var namespace = cls.CookieManager && cls.CookieManager["1.0"];
var service_interface = window.services['cookie-manager'];
if (service_interface)
{
new cls.CookieManager["1.0"].CookieManagerView("cookie_manager", ui_strings.M_VIEW_LABEL_COOKIES, "scroll cookie_manager", cls.CookieManager["1.0"].CookieManagerData, service.version);
cls.CookieManager.create_ui_widgets();
return true;
}
}
window.app.builders.CookieManager["1.1"] = function(service)
{
var namespace = cls.CookieManager && cls.CookieManager["1.1"];
var service_interface = window.services['cookie-manager'];
if (service_interface)
{
new cls.CookieManager["1.1"].CookieManagerView("cookie_manager", ui_strings.M_VIEW_LABEL_COOKIES, "scroll cookie_manager", cls.CookieManager["1.1"].CookieManagerData, service.version);
cls.CookieManager.create_ui_widgets();
return true;
}
}
|
/* load after build_application.js */
window.app.builders.CookieManager || ( window.app.builders.CookieManager = {} );
/**
* @param {Object} service the service description of the according service on the host side
*/
window.app.builders.CookieManager["1.0"] = function(service)
{
var namespace = cls.CookieManager && cls.CookieManager["1.0"];
var service_interface = window.services['cookie-manager'];
if (service_interface)
{
new cls.CookieManager["1.0"].CookieManagerView("cookie_manager", ui_strings.M_VIEW_LABEL_COOKIES, "scroll cookie_manager", cls.CookieManager["1.0"].CookieManagerData, service.version);
cls.CookieManager.create_ui_widgets();
}
}
window.app.builders.CookieManager["1.1"] = function(service)
{
var namespace = cls.CookieManager && cls.CookieManager["1.1"];
var service_interface = window.services['cookie-manager'];
if (service_interface)
{
new cls.CookieManager["1.1"].CookieManagerView("cookie_manager", ui_strings.M_VIEW_LABEL_COOKIES, "scroll cookie_manager", cls.CookieManager["1.1"].CookieManagerData, service.version);
cls.CookieManager.create_ui_widgets();
return true;
}
}
|
Drop attributes on oc_share table
Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net>
|
<?php
declare(strict_types=1);
namespace OC\Core\Migrations;
use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
class Version21000Date20201120141228 extends SimpleMigrationStep {
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
if ($schema->hasTable('dav_job_status')) {
$schema->dropTable('dav_job_status');
}
if ($schema->hasTable('systemtag')) {
$table = $schema->getTable('systemtag');
if ($table->hasColumn('systemtag')) {
$table->dropColumn('assignable');
}
}
if ($schema->hasTable('share')) {
$table = $schema->getTable('share');
if ($table->hasColumn('attributes')) {
$table->dropColumn('attributes');
}
}
return $schema;
}
}
|
<?php
declare(strict_types=1);
namespace OC\Core\Migrations;
use Closure;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;
class Version21000Date20201120141228 extends SimpleMigrationStep {
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();
if ($schema->hasTable('dav_job_status')) {
$schema->dropTable('dav_job_status');
}
if ($schema->hasTable('systemtag')) {
$table = $schema->getTable('systemtag');
if ($table->hasColumn('systemtag')) {
$table->dropColumn('assignable');
}
}
return $schema;
}
}
|
Update HTML Webpack Plugin to use index.html as template
|
const path = require('path')
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const HtmlWebpackPlugin = require('html-webpack-plugin')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: resolve('src/index.js'),
output: {
path: resolve('dist'),
filename: '[name].js'
},
resolve: {
alias: {
'@': resolve('src')
}
},
module: {
rules: [
// general resolve
{
test: /\.js$/,
use: 'babel-loader',
include: resolve('src')
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
}),
include: resolve('src/assets')
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
}
})
]
}
|
const path = require('path')
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const HtmlWebpackPlugin = require('html-webpack-plugin')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: resolve('src/index.js'),
output: {
path: resolve('dist'),
filename: '[name].js'
},
resolve: {
alias: {
'@': resolve('src')
}
},
module: {
rules: [
// general resolve
{
test: /\.js$/,
use: 'babel-loader',
include: resolve('src')
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
}),
include: resolve('src/assets')
}
]
},
plugins: [
// generate index.html based on src/index.html
new HtmlWebpackPlugin({
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
}
})
]
}
|
Include static assets in pakage_data
|
from setuptools import setup, find_packages
setup(
name='django-treemenus',
version='0.8.8-pre',
description='Tree-structured menuing application for Django.',
author='Julien Phalip',
author_email='julien@julienphalip.com',
url='http://github.com/jphalip/django-treemenus/',
packages=find_packages(),
package_data={
'treemenus': [
'static/img/treemenus/*.gif',
'templates/admin/treemenus/menu/*.html',
'templates/admin/treemenus/menuitem/*.html',
]
},
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
from setuptools import setup, find_packages
setup(
name='django-treemenus',
version='0.8.8-pre',
description='Tree-structured menuing application for Django.',
author='Julien Phalip',
author_email='julien@julienphalip.com',
url='http://github.com/jphalip/django-treemenus/',
packages=find_packages(),
package_data={
'treemenus': [
'templates/admin/treemenus/menu/*.html',
'templates/admin/treemenus/menuitem/*.html'
]
},
zip_safe=False,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
Prepare for test PyPI upload
|
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
config = {
'description': 'A lattice-gas Monte-Carlo simulation tool',
'long_description': read('README.md'),
'author': 'Benjamin J. Morgan',
'author_email': 'b.j.morgan@bath.ac.uk',
'url': 'https://github.com/bjmorgan/lattice_mc',
'download_url': 'https://github.com/bjmorgan/lattice_mc/tarball/0.9.1',
'author_email': 'b.j.morgan@bath.ac.uk',
'version': '1.0.0',
'install_requires': ['numpy, matplotlib, pandas'],
'license': 'MIT',
'packages': ['lattice_mc'],
'scripts': [],
'name': 'lattice_mc'
}
setup(**config)
|
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
config = {
'description': 'A lattice-gas Monte-Carlo simulation tool',
'long_description': read('README.md'),
'author': 'Benjamin J. Morgan',
'author_email': 'b.j.morgan@bath.ac.uk',
'url': 'https://github.com/bjmorgan/lattice_mc',
'download_url': 'https://github.com/bjmorgan/lattice_mc/tarball/1.0.0',
'author_email': 'b.j.morgan@bath.ac.uk',
'version': '1.0.0',
'install_requires': ['numpy, matplotlib, pandas'],
'license': 'MIT',
'packages': ['lattice_mc'],
'scripts': [],
'name': 'lattice_mc'
}
setup(**config)
|
Add regression test against options evaluation during import in cli.
|
"""
Tests for `kolibri.utils.cli` module.
These tests deliberately omit `@pytest.mark.django_db` from the tests,
so that any attempt to access the Django database during the running
of these cli methods will result in an error and test failure.
"""
from __future__ import absolute_import
from __future__ import print_function
from mock import patch
@patch("sqlalchemy.create_engine")
def test_status_no_db_access(create_engine_mock):
"""
Tests that status does not try to access the database
"""
try:
from kolibri.utils import cli
cli.status.callback()
except SystemExit:
pass
create_engine_mock.assert_not_called()
@patch("sqlalchemy.create_engine")
def test_stop_no_db_access(create_engine_mock):
"""
Tests that status does not try to access the database
"""
try:
from kolibri.utils import cli
cli.stop.callback()
except SystemExit:
pass
create_engine_mock.assert_not_called()
@patch("kolibri.utils.options.read_options_file")
def test_import_no_options_evaluation(read_options_mock):
from kolibri.utils import cli # noqa F401
read_options_mock.assert_not_called()
|
"""
Tests for `kolibri.utils.cli` module.
These tests deliberately omit `@pytest.mark.django_db` from the tests,
so that any attempt to access the Django database during the running
of these cli methods will result in an error and test failure.
"""
from __future__ import absolute_import
from __future__ import print_function
from mock import patch
@patch("sqlalchemy.create_engine")
def test_status_no_db_access(create_engine_mock):
"""
Tests that status does not try to access the database
"""
try:
from kolibri.utils import cli
cli.status.callback()
except SystemExit:
pass
create_engine_mock.assert_not_called()
@patch("sqlalchemy.create_engine")
def test_stop_no_db_access(create_engine_mock):
"""
Tests that status does not try to access the database
"""
try:
from kolibri.utils import cli
cli.stop.callback()
except SystemExit:
pass
create_engine_mock.assert_not_called()
|
Revert "OLMIS-3533: Added javadoc for Reason type priority field"
This reverts commit e5ccc08d57d538b6d6a4c6a8fd099f50e3a769af.
|
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact info@OpenLMIS.org.
*/
package org.openlmis.stockmanagement.domain.reason;
import lombok.Getter;
public enum ReasonType {
CREDIT(2),
DEBIT(1),
BALANCE_ADJUSTMENT(0);
@Getter
private int priority;
ReasonType(int priority) {
this.priority = priority;
}
}
|
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact info@OpenLMIS.org.
*/
package org.openlmis.stockmanagement.domain.reason;
import lombok.Getter;
public enum ReasonType {
CREDIT(2),
DEBIT(1),
BALANCE_ADJUSTMENT(0);
/**
* Value of this field will be used to set correct order of stock card line items if both
* occurred and processed dates have the same date for the following line items. It is
* important that types that are used to increase (like {@link #CREDIT}) should have higher
* priority than types that are used to decrease (like {@link #DEBIT}).
*/
@Getter
private int priority;
ReasonType(int priority) {
this.priority = priority;
}
}
|
Update main Lcd import and init, and fix help msg
|
#!/usr/bin/env python
import sys
from getopt import getopt, GetoptError
from .api import Server
from .lcd import Lcd
USAGE = """\
Usage %s [-h|--help] [-f|--fake]
\t-h or --help\tThis help message
\t-f or --fake\tIf on RPi, use FakeHw
"""
def get_args(args):
arg0 = args[0]
try:
opts, args = getopt(args[1:], 'hf', ['help', 'fake'])
except GetoptError as e:
print('GetoptError %s' % e)
sys.exit(2)
ret_args = {}
ret_args['fake'] = False
for opt, arg in opts:
if opt in ['-h', '--help']:
print(USAGE % arg0)
sys.exit(0)
elif opt in ['-f', '--fake']:
ret_args['fake'] = True
else:
print(USAGE % arg0)
sys.exit(1)
return ret_args
def main_serv(clargs=sys.argv):
opts = get_args(clargs)
s = Server(lcd=Lcd(opts['fake']))
s.run()
return 0
if __name__ == "__main__":
sys.exit(main_serv())
|
#!/usr/bin/env python
import sys
from getopt import getopt, GetoptError
from .api import Server
from .fake import FakeLcdApi
USAGE = """\
Usage %s [-h|--help]
\t-h or --help\tThis help message
"""
def get_args(args):
try:
opts, args = getopt(args[1:], 'hf', ['help', 'fake'])
except GetoptError as e:
print('GetoptError %s' % e)
sys.exit(2)
ret_args = {}
ret_args['fake'] = False
for opt, arg in opts:
if opt in ['-h', '--help']:
print(USAGE % args[0])
sys.exit(0)
elif opt in ['-f', '--fake']:
ret_args['fake'] = True
else:
print(USAGE % args[0])
sys.exit(1)
return ret_args
def main_serv(clargs=sys.argv):
opts = get_args(clargs)
lcd = None
if opts['fake']:
lcd = FakeLcdApi()
s = Server(lcd=lcd)
s.run()
return 0
if __name__ == "__main__":
sys.exit(main_serv())
|
Use new headers method to avoid apache specific functions
|
<?php
namespace Bolt\Api\Request;
class Headers extends \Bolt\Base
{
private $headers;
public function __construct($auto = false)
{
if ($auto === true)
{
$this->parse();
}
}
public function __get($name)
{
return $this->$name;
}
public function __isset($name)
{
return isset($this->headers[$name]) ? true : false;
}
public function __call($name, $arguments)
{
if ($arguments == array())
{
return $this->headers[$name];
}
$this->headers[$name] = $arguments[0];
return true;
}
private function fetchHeaders()
{
$headers = array();
foreach ($_SERVER as $key => $value)
{
if (strpos($key, "HTTP_") === 0)
{
$bits = explode("_", $key);
array_shift($bits);
foreach ($bits as &$bit)
{
$bit = ucwords(strtolower($bit));
}
$headers[implode("-", $bits)] = $value;
}
}
return $headers;
}
public function parse()
{
$this->headers = array_change_key_case($this->fetchHeaders(), CASE_LOWER);
}
}
?>
|
<?php
namespace Bolt\Api\Request;
class Headers extends \Bolt\Base
{
private $headers;
public function __construct($auto = false)
{
if ($auto === true)
{
$this->parse();
}
}
public function __get($name)
{
return $this->$name;
}
public function __isset($name)
{
return isset($this->headers[$name]) ? true : false;
}
public function __call($name, $arguments)
{
if ($arguments == array())
{
return $this->headers[$name];
}
$this->headers[$name] = $arguments[0];
return true;
}
private function fetchHeaders()
{
$headers = array();
foreach ($_SERVER as $key => $value)
{
if (strpos($key, "HTTP_") === 0)
{
$bits = explode("_", $key);
array_shift($bits);
foreach ($bits as &$bit)
{
$bit = ucwords(strtolower($bit));
}
$headers[implode("-", $bits)] = $value;
}
}
return $headers;
}
public function parse()
{
$this->headers = array_change_key_case(apache_request_headers(), CASE_LOWER);
}
}
?>
|
Use logHelper instead of console.warn
|
/*
Copyright 2017 Google Inc. 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.
*/
import logHelper from './log-helper';
/**
* Warns users that an old property is deprecated in favor of a new property
* and aliases the old name to the new name.
* @param {Object} obj The object containing the methods.
* @param {string} oldName The method to deprecate.
* @param {string} newName The new method replacing the deprecated method.
* @param {string} ctx The context project/object to identify the method names.
*/
export default (obj, oldName, newName, ctx) => {
if (Object.prototype.hasOwnProperty.call(obj, oldName)) {
logHelper.warn(
`${oldName} is deprecated; use ${newName} instead`, {Context: ctx});
obj[newName] = obj[oldName];
}
};
|
/*
Copyright 2017 Google Inc. 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.
*/
/**
* Warns users that an old property is deprecated in favor of a new property
* and aliases the old name to the new name.
* @param {Object} obj The object containing the methods.
* @param {string} oldName The method to deprecate.
* @param {string} newName The new method replacing the deprecated method.
* @param {string} ctx The context project/object to identify the method names.
*/
export default (obj, oldName, newName, ctx) => {
if (Object.prototype.hasOwnProperty.call(obj, oldName)) {
/* eslint-disable no-console */
console.warn(`In ${ctx}: ` +
`${oldName} is deprecated, use ${newName} instead`);
/* eslint-enable no-console */
obj[newName] = obj[oldName];
}
};
|
Fix admin not being able to access reqs
|
var OwerRequestModel = require('../models/requests/owerRequest.js')
, error = require('../utils/error.js');
var allOwerRequests = function(req, res) {
var type = req.query.type;
var facebookId;
if (req.user && req.user.facebookId) {
facebookId = req.user.facebookId;
}
if (type && facebookId) {
if (type === 'received') {
conditions.to = facebookId;
} else if (type === 'sent') {
conditions.from = facebookId;
} else {
return error.badRequest(res, 'Invalid parameter: type must be either "received" or "sent"');
}
}
OwerRequestModel.findAsync(conditions)
.then(function(owerRequests) {
res.json(owerRequests);
})
.catch(error.serverHandler(res));
};
exports.owers = {
all: allOwerRequests
};
|
var OwerRequestModel = require('../models/requests/owerRequest.js')
, error = require('../utils/error.js');
var allOwerRequests = function(req, res) {
var facebookId = req.user.facebookId
, type = req.query.type;
if (type) {
if (type === 'received') {
conditions.to = facebookId;
} else if (type === 'sent') {
conditions.from = facebookId;
} else {
return error.badRequest(res, 'Invalid parameter: type must be either "received" or "sent"');
}
}
OwerRequestModel.findAsync(conditions)
.then(function(owerRequests) {
res.json(owerRequests);
})
.catch(error.serverHandler(res));
};
exports.owers = {
all: allOwerRequests
};
|
Change default time between images
|
import subprocess
from datetime import datetime, timedelta
frame_counter = 1
# Time in seconds
# 1 Hour = 3600
# 1 Day = 86400
# Time between each photo (seconds)
time_between_frames = 60
# Duration of Time Lapse (seconds)
duration = 86400
# Image Dimensions (pixels)
image_height = 972
image_width = 1296
total_frames = duration / time_between_frames
def capture_image():
t = datetime.now()
filename = "capture_%04d-%02d-%02d_%02d-%02d-%02d.jpg" % (t.year, t.month, t.day, t.hour, t.minute, t.second)
subprocess.call("raspistill -w %d -h %d -e jpg -q 15 -o %s" % (image_width, image_height, filename), shell = True)
print("Captured Image %d of %d, named: %s" % (frame_counter, total_frames, filename))
last_capture = datetime.now()
while frame_counter < total_frames:
if last_capture < (datetime.now() - timedelta(seconds = time_between_frames)):
last_capture = datetime.now()
capture_image()
frame_counter += 1
|
import subprocess
from datetime import datetime, timedelta
frame_counter = 1
# Time in seconds
# 1 Hour = 3600
# 1 Day = 86400
# Time between each photo (seconds)
time_between_frames = 3
# Duration of Time Lapse (seconds)
duration = 86400
# Image Dimensions (pixels)
image_height = 972
image_width = 1296
total_frames = duration / time_between_frames
def capture_image():
t = datetime.now()
filename = "capture_%04d-%02d-%02d_%02d-%02d-%02d.jpg" % (t.year, t.month, t.day, t.hour, t.minute, t.second)
subprocess.call("raspistill -w %d -h %d -e jpg -q 15 -o %s" % (image_width, image_height, filename), shell = True)
print("Captured Image %d of %d, named: %s" % (frame_counter, total_frames, filename))
last_capture = datetime.now()
while frame_counter < total_frames:
if last_capture < (datetime.now() - timedelta(seconds = time_between_frames)):
last_capture = datetime.now()
capture_image()
frame_counter += 1
|
Revert "Save .travis.yml into build properties"
The data is > 1024 so no dice.
This reverts commit 10960fd1465afb8de92e8fd35b1affca4f950e27.
|
from buildbot.process import buildstep
from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION
from buildbot.process.properties import Properties
from twisted.internet import defer
from ..travisyml import TravisYml
class ConfigurableStep(buildstep.LoggingBuildStep):
"""
Base class for a step which can be tuned by changing settings in .travis.yml
"""
@defer.inlineCallbacks
def getStepConfig(self):
log = self.addLog(".travis.yml")
cmd = self.cmd = buildstep.RemoteShellCommand(workdir="build", command=["cat", ".travis.yml"])
cmd.useLog(log, False, "stdio")
yield self.runCommand(cmd)
self.cmd = None
if cmd.rc != 0:
raise buildstep.BuildStepFailed()
config = TravisYml()
config.parse(log.getText())
defer.returnValue(config)
|
from buildbot.process import buildstep
from buildbot.process.buildstep import SUCCESS, FAILURE, EXCEPTION
from buildbot.process.properties import Properties
from twisted.internet import defer
from ..travisyml import TravisYml
class ConfigurableStep(buildstep.LoggingBuildStep):
"""
Base class for a step which can be tuned by changing settings in .travis.yml
"""
@defer.inlineCallbacks
def getStepConfig(self):
config = TravisYml()
struct = self.build.getProperty(".travis.yml", None)
if struct:
config.parse(struct)
defer.returnValue(config)
log = self.addLog(".travis.yml")
cmd = self.cmd = buildstep.RemoteShellCommand(workdir="build", command=["cat", ".travis.yml"])
cmd.useLog(log, False, "stdio")
yield self.runCommand(cmd)
self.cmd = None
if cmd.rc != 0:
raise buildstep.BuildStepFailed()
config = TravisYml()
config.parse(log.getText())
self.build.setProperty(".travis.yml", config.config, ".VCS")
defer.returnValue(config)
|
Hide sidenav when selecting team
|
const Backbone = require('backbone');
require('backbone.marionette');
const Repository = require('../../domain/repository');
const TeamItemViewTemplate = require('../template/team-item-view-template.hbs');
const Template = require('../template/sidenav-view-template.hbs');
const TeamItemView = Backbone.Marionette.View.extend({
template: TeamItemViewTemplate,
tagName: 'li'
});
const TeamListView = Backbone.Marionette.CollectionView.extend({
childView: TeamItemView
});
module.exports = Backbone.Marionette.View.extend({
template: Template,
ui: {
addTeamButton: '.btn.add-team'
},
events: {
'click @ui.addTeamButton': 'addTeam',
'click .teams': 'closeSidenav'
},
regions: {
teams: '.teams'
},
onRender: function() {
Repository.getTeams()
.then(teams => {
this.showChildView('teams', new TeamListView({collection: teams}));
});
},
onDomRefresh: function() {
this.$('.sidenav-button').sideNav();
},
addTeam: function() {
Repository.addTeam();
},
closeSidenav: function() {
this.$('.sidenav-button').sideNav('hide');
}
});
|
const Backbone = require('backbone');
require('backbone.marionette');
const Repository = require('../../domain/repository');
const TeamItemViewTemplate = require('../template/team-item-view-template.hbs');
const Template = require('../template/sidenav-view-template.hbs');
const TeamItemView = Backbone.Marionette.View.extend({
template: TeamItemViewTemplate,
tagName: 'li'
});
const TeamListView = Backbone.Marionette.CollectionView.extend({
childView: TeamItemView
});
module.exports = Backbone.Marionette.View.extend({
template: Template,
ui: {
addTeamButton: '.btn.add-team'
},
events: {
'click @ui.addTeamButton': 'addTeam'
},
regions: {
teams: '.teams'
},
onRender: function() {
Repository.getTeams()
.then(teams => {
this.showChildView('teams', new TeamListView({collection: teams}));
});
},
onDomRefresh: function() {
this.$('.sidenav-button').sideNav();
},
addTeam: function() {
Repository.addTeam();
}
});
|
Fix a bug in BufferUtils
|
'use strict';
const VAL32 = 0xFFFFFFFF;
class BufferUtils {
static readUInt64BE(buffer, offset) {
let hi = buffer.readUInt32BE(offset);
let value = buffer.readUInt32BE(offset + 4);
if (hi > 0) {
value += hi * (VAL32 + 1);
}
return value;
}
static writeUInt64BE(buffer, value, offset) {
let hi = 0;
let lo = value;
if (value > VAL32) {
hi = (value / (VAL32 + 1)) << 0;
lo = value % (VAL32 + 1);
}
buffer.writeUInt32BE(hi, offset);
buffer.writeUInt32BE(lo, offset + 4);
}
}
module.exports = BufferUtils;
|
'use strict';
const VAL32 = 0xFFFFFFFF;
class BufferUtils {
static readUInt64BE(buffer, offset) {
let hi = buffer.readUInt32BE(offset);
let value = buffer.readUInt32BE(offset + 4);
if (hi > 0) {
value += hi * VAL32;
}
return value;
}
static writeUInt64BE(buffer, value, offset) {
let hi = 0;
let lo = value;
if (value > VAL32) {
hi = (value / VAL32) << 0;
lo = value % VAL32;
}
buffer.writeUInt32BE(hi, offset);
buffer.writeUInt32BE(lo, offset + 4);
}
}
module.exports = BufferUtils;
|
Change primitive to object in task model
|
package com.github.solairerove.woodstock.domain;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by krivitski-no on 10/1/16.
*/
@Data
@Document
public class Task implements Serializable {
@Id
private String id;
private String question;
private Boolean enable;
private Boolean correct;
private Collection<? extends Ticket> tickets = new ArrayList<>();
public Task() {
}
public Task(String question, Collection<? extends Ticket> tickets) {
this.question = question;
this.enable = Boolean.TRUE;
this.correct = Boolean.FALSE;
this.tickets = tickets;
}
public Task(String question, Boolean enable, Boolean correct, Collection<? extends Ticket> tickets) {
this.question = question;
this.enable = enable;
this.correct = correct;
this.tickets = tickets;
}
}
|
package com.github.solairerove.woodstock.domain;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by krivitski-no on 10/1/16.
*/
@Data
@Document
public class Task implements Serializable {
@Id
private String id;
private String question;
private Boolean enable;
private Boolean correct;
private Collection<? extends Ticket> tickets = new ArrayList<>();
public Task() {
}
public Task(String question, Collection<? extends Ticket> tickets) {
this.question = question;
this.enable = true;
this.correct = false;
this.tickets = tickets;
}
public Task(String question, Boolean enable, Boolean correct, Collection<? extends Ticket> tickets) {
this.question = question;
this.enable = enable;
this.correct = correct;
this.tickets = tickets;
}
}
|
Add children handling to visibility queue
|
/* ***********************************************************************************************
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com
*********************************************************************************************** */
/**
* @break {unify.ui.layout.queue.Manager}
*/
(function() {
var widgetQueue = [];
core.Module("unify.ui.layout.queue.Visibility", {
name : "visibility",
add : function(widget) {
widgetQueue.push(widget);
unify.ui.layout.queue.Manager.run(unify.ui.layout.queue.Visibility.name);
},
flush : function() {
for (var i=0,ii=widgetQueue.length; i<ii; i++) {
var children = widgetQueue[i].getLayoutChildren();
widgetQueue = widgetQueue.concat(children);
}
for (i=0,ii=widgetQueue.length; i<ii; i++) {
widgetQueue[i].checkAppearanceNeeds();
}
}
});
})();
|
/* ***********************************************************************************************
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com
*********************************************************************************************** */
/**
* @break {unify.ui.layout.queue.Manager}
*/
(function() {
var widgetQueue = [];
core.Module("unify.ui.layout.queue.Visibility", {
name : "visibility",
add : function(widget) {
widgetQueue.push(widget);
unify.ui.layout.queue.Manager.run(unify.ui.layout.queue.Visibility.name);
},
flush : function() {
console.log("VISIBILITY: ", widgetQueue.length, widgetQueue);
for (var i=0,ii=widgetQueue.length; i<ii; i++) {
var widget = widgetQueue[i];
widget.checkAppearanceNeeds();
}
}
});
})();
|
Update label for US CT
|
const Command = require('../Command');
module.exports = Command.extend({
commandName: 'time',
commandAliases: ['now'],
moment: null,
Discord: null,
dependencies: {
'moment': 'moment',
'Discord': 'Discord',
},
processMessage: function (message, tokens) {
const now = this.moment().locale(this.i18n.getLocale());
const cdt = now.tz('America/Chicago');
const jst = now.clone().tz('Asia/Tokyo');
const gmt = now.clone().tz('Europe/London');
const embed = new this.Discord.RichEmbed();
embed.addField('Dallas (Shotbow Time)', cdt.format('lll'));
embed.addField('London', gmt.format('lll'));
embed.addField('東京', jst.format('lll'));
embed.setTimestamp(now);
message.channel.send(embed);
}
});
|
const Command = require('../Command');
module.exports = Command.extend({
commandName: 'time',
commandAliases: ['now'],
moment: null,
Discord: null,
dependencies: {
'moment': 'moment',
'Discord': 'Discord',
},
processMessage: function (message, tokens) {
const now = this.moment().locale(this.i18n.getLocale());
const cdt = now.tz('America/Chicago');
const jst = now.clone().tz('Asia/Tokyo');
const gmt = now.clone().tz('Europe/London');
const embed = new this.Discord.RichEmbed();
embed.addField('Chicago', cdt.format('lll'));
embed.addField('London', gmt.format('lll'));
embed.addField('東京', jst.format('lll'));
embed.setTimestamp(now);
message.channel.send(embed);
}
});
|
Revert "Add access log for logserver container "
|
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author gjoranv
*/
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> {
public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) {
super(parent, name, name, deployState);
addDefaultHandlersWithVip();
addLogHandler();
}
@Override
protected void doPrepare(DeployState deployState) { }
private void addLogHandler() {
Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings("*://*/logs");
addComponent(logHandler);
}
}
|
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author gjoranv
*/
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> {
public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) {
super(parent, name, name, deployState);
addDefaultHandlersWithVip();
addLogHandler();
addDefaultSearchAccessLog();
}
@Override
protected void doPrepare(DeployState deployState) { }
private void addLogHandler() {
Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings("*://*/logs");
addComponent(logHandler);
}
}
|
[CHORE] Remove ripple rest fom package.json.
|
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
function GatewayProcessManager() {
this.processNames = [
"deposits",
"outgoing",
"incoming",
"withdrawals",
"webapp"
];
this.processes = {};
}
GatewayProcessManager.prototype.start = function() {
var manager = this;
manager.processNames.forEach(function(name) {
var process = spawn('node', [__dirname+'/../processes/'+name]);
manager.processes[name] = process.pid;
process.stdout.on('data', function(data){
console.log(name.toUpperCase()+' :', data.toString());
});
process.stderr.on('data', function(data){
console.log(name.toUpperCase()+' :', data.toString());
});
});
console.log(manager.processes);
}
module.exports = GatewayProcessManager;
|
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
function GatewayProcessManager() {
this.processNames = [
"ripple_rest",
"deposits",
"outgoing",
"incoming",
"withdrawals",
"webapp"
];
this.processes = {};
}
GatewayProcessManager.prototype.start = function() {
var manager = this;
manager.processNames.forEach(function(name) {
var process = spawn('node', [__dirname+'/../processes/'+name]);
manager.processes[name] = process.pid;
process.stdout.on('data', function(data){
console.log(name.toUpperCase()+' :', data.toString());
});
process.stderr.on('data', function(data){
console.log(name.toUpperCase()+' :', data.toString());
});
});
console.log(manager.processes);
}
module.exports = GatewayProcessManager;
|
Add - Simplest code to turn the Given into concrete actions (HTTP request to check that a POST resource exists)
|
/*
We use the output messages from the cucumber runner to create Step Definitions:
the glue between features written in Gherkin and the actual system under test.
Use Given, When, Then.
*/
let request = require('request');
const {defineSupportCode} = require('cucumber');
defineSupportCode(function({Given, Then, When}) {
Given('I have an employee insert resource', function (callback) {
// Write code here that turns the phrase above into concrete actions
//Simplest HTTP request to check that a POST resource exists
request.post('http://localhost:3000/api_mpayroll/employees',
function(error, response){
if (error) {
console.log(error);
callback(null, 'pending');
}
else {
response.statusCode = 201;
callback();
}
}
)
});
When('I submit the employee record', function (callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
Then('A new hourly employee is Created', function (callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
});
|
/*
We use the output messages from the cucumber runner to create Step Definitions:
the glue between features written in Gherkin and the actual system under test.
Use Given, When, Then.
*/
let request = require('request');
const {defineSupportCode} = require('cucumber');
defineSupportCode(function({Given, Then, When}) {
Given('I have an employee insert resource', function (callback) {
// Write code here that turns the phrase above into concrete actions
//Simplest HTTP request to check that a POST resource exists
request.post('http://localhost:3000/api_mpayroll/employees',
function(error, response){
if (error) {
console.log(error);
callback(null, 'pending');
}
else {
response.statusCode = 201;
callback();
}
}
)
});
When('I submit the employee record', function (callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
Then('A new hourly employee is Created', function (callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
});
|
Enable filtering when scaling NPOT textures; minor optimizations
|
package com.rabenauge.gl;
import android.graphics.Bitmap;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
/*
* Wrapper class for 2D texture objects.
*/
public class Texture2D extends Texture {
public Texture2D(GL11 gl) {
super(gl, GL10.GL_TEXTURE_2D, GL11.GL_TEXTURE_BINDING_2D);
}
public void setData(Bitmap bitmap, int level, boolean border) {
int w=bitmap.getWidth(), h=bitmap.getHeight();
int w2=ceilPOT(w), h2=ceilPOT(h);
if (w!=w2 || h!=h2) {
bitmap=Bitmap.createScaledBitmap(bitmap, w2, h2, true);
}
makeCurrent();
android.opengl.GLUtils.texImage2D(target, level, bitmap, border?1:0);
}
public void setData(Bitmap bitmap) {
setData(bitmap, 0, false);
}
}
|
package com.rabenauge.gl;
import android.graphics.Bitmap;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
/*
* Wrapper class for 2D texture objects.
*/
public class Texture2D extends Texture {
public Texture2D(GL11 gl) {
super(gl, GL10.GL_TEXTURE_2D, GL11.GL_TEXTURE_BINDING_2D);
}
public void setData(Bitmap bitmap, int level, boolean border) {
makeCurrent();
if (!isPOT(bitmap.getWidth()) || !isPOT(bitmap.getHeight())) {
bitmap=Bitmap.createScaledBitmap(bitmap, ceilPOT(bitmap.getWidth()), ceilPOT(bitmap.getHeight()), false);
}
android.opengl.GLUtils.texImage2D(target, level, bitmap, border?1:0);
}
public void setData(Bitmap bitmap) {
setData(bitmap, 0, false);
}
}
|
Fix pytest when pyfakefs + future is installed
`python-future` is notorious for breaking modules which use `try:` / `except:`
to import modules based on version. In this case, `pyfakefs` imported the
backported `builtins` module which changes the semantics of the `open()`
function. `pyfakefs` then monkeypatches `linecache` which breaks any module
which attempts to use `linecache` (in this case `pytest`).
The downstream issue is https://github.com/pytest-dev/pytest/pull/4074
|
"""A pytest plugin for using pyfakefs as a fixture
When pyfakefs is installed, the "fs" fixture becomes available.
:Usage:
def my_fakefs_test(fs):
fs.create_file('/var/data/xx1.txt')
assert os.path.exists('/var/data/xx1.txt')
"""
import linecache
import sys
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
if sys.version_info >= (3,):
import builtins
else:
import __builtin__ as builtins
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
# The "linecache" module is used to read the test file in case of test failure
# to get traceback information before test tear down.
# In order to make sure that reading the test file is not faked,
# we both skip faking the module, and add the build-in open() function
# as a local function in the module
Patcher.SKIPMODULES.add(linecache)
linecache.open = builtins.open
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
|
"""A pytest plugin for using pyfakefs as a fixture
When pyfakefs is installed, the "fs" fixture becomes available.
:Usage:
def my_fakefs_test(fs):
fs.create_file('/var/data/xx1.txt')
assert os.path.exists('/var/data/xx1.txt')
"""
import linecache
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
try:
import builtins
except ImportError:
import __builtin__ as builtins
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
# The "linecache" module is used to read the test file in case of test failure
# to get traceback information before test tear down.
# In order to make sure that reading the test file is not faked,
# we both skip faking the module, and add the build-in open() function
# as a local function in the module
Patcher.SKIPMODULES.add(linecache)
linecache.open = builtins.open
@pytest.fixture
def fs(request):
""" Fake filesystem. """
patcher = Patcher()
patcher.setUp()
request.addfinalizer(patcher.tearDown)
return patcher.fs
|
Add charset to connect mysql
|
import MySQLdb
import MySQLdb.cursors
from hakoblog.config import CONFIG
class DB():
def __init__(self):
self.conn = MySQLdb.connect(
db=CONFIG.DATABASE,
host=CONFIG.DATABASE_HOST,
user=CONFIG.DATABASE_USER,
password=CONFIG.DATABASE_PASS,
cursorclass=MySQLdb.cursors.DictCursor,
charset='utf-8',
)
self.conn.autocommit(True)
def cursor(self):
return self.conn.cursor()
def close(self):
self.conn.close()
def uuid_short(self):
with self.conn.cursor() as cursor:
cursor.execute('SELECT UUID_SHORT() as uuid')
return cursor.fetchone().get('uuid')
|
import MySQLdb
import MySQLdb.cursors
from hakoblog.config import CONFIG
class DB():
def __init__(self):
self.conn = MySQLdb.connect(
db=CONFIG.DATABASE,
host=CONFIG.DATABASE_HOST,
user=CONFIG.DATABASE_USER,
password=CONFIG.DATABASE_PASS,
cursorclass=MySQLdb.cursors.DictCursor,
)
self.conn.autocommit(True)
def cursor(self):
return self.conn.cursor()
def close(self):
self.conn.close()
def uuid_short(self):
with self.conn.cursor() as cursor:
cursor.execute('SELECT UUID_SHORT() as uuid')
return cursor.fetchone().get('uuid')
|
Use readable stream instead of pass through
|
'use strict'
const stream = require('stream')
const Transform = stream.Transform
const Readable = stream.Readable
/**
* Returns a transform stream that branches
* the input stream to several streams given by argument.
*/
module.exports = function selectTask (config) {
/**
* (inputStream) -> transform -> each task -> transform -> (outputStream)
*/
return new Transform({
objectMode: true,
transform (file, encoding, callback) {
const rule = config.findRuleByInput(file.path)
if (rule === null) {
callback(null, file)
return
}
const src = new Readable({ objectMode: true })
src.push(file)
src.push(null)
rule.task(src).on('data', file => {
file.extname = '.' + rule.outputExt
callback(null, file)
})
}
})
}
|
'use strict'
const stream = require('stream')
const Transform = stream.Transform
const PassThrough = stream.PassThrough
/**
* Returns a transform stream that branches
* the input stream to several streams given by argument.
*/
module.exports = function selectTask (config) {
/**
* (inputStream) -> transform -> each task -> transform -> (outputStream)
*/
return new Transform({
objectMode: true,
transform (file, encoding, callback) {
const rule = config.findRuleByInput(file.path)
if (rule === null) {
callback(null, file)
return
}
const src = new PassThrough({ objectMode: true })
rule.task(src).on('data', file => {
file.extname = '.' + rule.outputExt
callback(null, file)
})
src.end(file)
}
})
}
|
Call getResults() instead of accessing the get() method manually for the IteratorAggregate and Countable functions
|
<?php namespace Elegant\Relations;
use Countable;
use ArrayIterator;
use IteratorAggregate;
use Elegant\Model;
use Elegant\Result;
use Elegant\Row;
abstract class Relation implements Countable, IteratorAggregate {
protected $parent;
protected $related;
function __construct(Model $parent, Model $related)
{
$this->parent = $parent;
$this->related = $related;
}
abstract public function getResults();
// Implements IteratorAggregate function so the result can be looped without needs to call get() first.
public function getIterator()
{
return $this->getResults();
}
// Implements Countable function
public function count()
{
return count( $this->getResults() );
}
function __call($name, $param)
{
if(is_callable( array($this->related, $name) ))
{
$return = call_user_func_array(array( $this->related, $name ), $param);
if($return instanceof Result or $return instanceof Row) return $return;
return $this;
}
}
}
|
<?php namespace Elegant\Relations;
use Countable;
use ArrayIterator;
use IteratorAggregate;
use Elegant\Model;
use Elegant\Result;
use Elegant\Row;
abstract class Relation implements Countable, IteratorAggregate {
protected $parent;
protected $related;
protected $related_items = null;
function __construct(Model $parent, Model $related)
{
$this->parent = $parent;
$this->related = $related;
}
abstract public function getResults();
// Implements IteratorAggregate function
public function getIterator()
{
if(empty($this->related_items)) $this->related_items = $this->related->get();
return $this->related_items;
}
// Implements Countable function
public function count()
{
if(empty($this->related_items)) $this->related_items = $this->related->get();
return count($this->related_items);
}
function __call($name, $param)
{
if(is_callable( array($this->related, $name) ))
{
$return = call_user_func_array(array( $this->related, $name ), $param);
if($return instanceof Result or $return instanceof Row) return $return;
return $this;
}
}
}
|
Use IRC server on localhost by default
|
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
import importlib
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'localhost',
server_port = 6667,
use_ssl = False,
password = None,
silent_bot = False,
log_channels = [],
other_channels = [],
places = ['London', 'Tokyo', 'New York'],
feed_interval = 15, # minutes
feeds = [dict(
name = 'pmxbot bitbucket',
channel = '#inane',
linkurl = 'http://bitbucket.org/yougov/pmxbot',
url = 'http://bitbucket.org/yougov/pmxbot',
),
],
librarypaste = 'http://paste.jaraco.com',
)
"The config object"
if __name__ == '__main__':
importlib.import_module('pmxbot.core').run()
|
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
import importlib
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'irc.freenode.net',
server_port = 6667,
use_ssl = False,
password = None,
silent_bot = False,
log_channels = [],
other_channels = [],
places = ['London', 'Tokyo', 'New York'],
feed_interval = 15, # minutes
feeds = [dict(
name = 'pmxbot bitbucket',
channel = '#inane',
linkurl = 'http://bitbucket.org/yougov/pmxbot',
url = 'http://bitbucket.org/yougov/pmxbot',
),
],
librarypaste = 'http://paste.jaraco.com',
)
"The config object"
if __name__ == '__main__':
importlib.import_module('pmxbot.core').run()
|
Remove unnecessary assignment and cast
|
package heroku.template.service;
import heroku.template.model.Person;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import java.util.List;
@Service
public class PersonServiceImpl implements PersonService {
@PersistenceContext
EntityManager em;
@Transactional
public void addPerson(Person person) {
em.persist(person);
}
@Transactional
public List<Person> listPeople() {
CriteriaQuery<Person> c = em.getCriteriaBuilder().createQuery(Person.class);
c.from(Person.class);
return em.createQuery(c).getResultList();
}
@Transactional
public void removePerson(Integer id) {
Person person = em.find(Person.class, id);
if (null != person) {
em.remove(person);
}
}
}
|
package heroku.template.service;
import heroku.template.model.Person;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class PersonServiceImpl implements PersonService {
@PersistenceContext
EntityManager em;
@Transactional
public void addPerson(Person person) {
em.persist(person);
}
@Transactional
public List<Person> listPeople() {
CriteriaQuery<Person> c = em.getCriteriaBuilder().createQuery(Person.class);
Root<Person> p = c.from(Person.class);
return em.createQuery(c).getResultList();
}
@Transactional
public void removePerson(Integer id) {
Person person = (Person) em.find(Person.class, id);
if (null != person) {
em.remove(person);
}
}
}
|
Allow meta and debug tasks to not be named
Fixes #176
|
# Copyright (c) 2016 Will Thames <will@thames.id.au>
#
# 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.
from ansiblelint import AnsibleLintRule
class TaskHasNameRule(AnsibleLintRule):
id = 'ANSIBLE0011'
shortdesc = 'All tasks should be named'
description = 'All tasks should have a distinct name for readability ' + \
'and for --start-at-task to work'
tags = ['readability']
_nameless_tasks = ['meta', 'debug']
def matchtask(self, file, task):
return task.get('name', '') == '' and \
task["action"]["__ansible_module__"] not in self._nameless_tasks
|
# Copyright (c) 2016 Will Thames <will@thames.id.au>
#
# 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.
from ansiblelint import AnsibleLintRule
class TaskHasNameRule(AnsibleLintRule):
id = 'ANSIBLE0011'
shortdesc = 'All tasks should be named'
description = 'All tasks should have a distinct name for readability ' + \
'and for --start-at-task to work'
tags = ['readability']
def matchtask(self, file, task):
return task.get('name', '') == ''
|
Improve wording of screen reader text so the user knows how to switch to a table view
|
$(window).on('load', function() {
if ($('.timeseries__chart').length == 0) {
// Enhance markdown charts
$('.highcharts-container').each(function () {
highchartsAccessibilityAttrs($(this), 'Chart representing data available in following XLS or CSV download');
});
} else {
// Do accessibility goodness to T5
timeseriesAccessibilityAttrs()
}
});
function highchartsAccessibilityAttrs(selector, labelText, removeAttrs) {
if (!removeAttrs) {
selector.attr('aria-label', labelText);
selector.find('svg').attr('aria-hidden', 'true').attr('focusable', 'false');
} else {
selector.attr('aria-label', '');
selector.find('svg').attr('aria-hidden', 'false');
}
}
function timeseriesAccessibilityAttrs(removeAttrs) {
highchartsAccessibilityAttrs($('.timeseries__chart'), 'Chart representing data available. Select "table" in show data as to display data as a table', removeAttrs);
}
|
$(window).on('load', function() {
if ($('.timeseries__chart').length == 0) {
// Enhance markdown charts
$('.highcharts-container').each(function () {
highchartsAccessibilityAttrs($(this), 'Chart representing data available in following XLS or CSV download');
});
} else {
// Do accessibility goodness to T5
timeseriesAccessibilityAttrs()
}
});
function highchartsAccessibilityAttrs(selector, labelText, removeAttrs) {
if (!removeAttrs) {
selector.attr('aria-label', labelText);
selector.find('svg').attr('aria-hidden', 'true').attr('focusable', 'false');
} else {
selector.attr('aria-label', '');
selector.find('svg').attr('aria-hidden', 'false');
}
}
function timeseriesAccessibilityAttrs(removeAttrs) {
highchartsAccessibilityAttrs($('.timeseries__chart'), 'Chart representing data available in table alternative. Select "table" in filters to display table', removeAttrs);
}
|
Use registration form to prevent duplicate emails
Fixes #725.
We enforce this both at the database level, and here, using django
registration's ready-made form class.
|
from django.conf.urls import patterns
from django.conf.urls import include
from django.conf.urls import url
from django.views.generic.base import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from views import RegistrationView, ActivationView
urlpatterns = patterns('',
url(r'^activate/complete/$',
TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get
# to the view; that way it can return a sensible "invalid key"
# message instead of a confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(),
name='registration_activate'),
url(r'^register/$',
RegistrationView.as_view(form_class=RegistrationFormUniqueEmail),
name='registration_register'),
url(r'^register/complete/$',
TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA
name='registration_complete'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'), # NOQA
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
) # NOQA
|
from django.conf.urls import patterns
from django.conf.urls import include
from django.conf.urls import url
from django.views.generic.base import TemplateView
from views import RegistrationView, ActivationView
urlpatterns = patterns('',
url(r'^activate/complete/$',
TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get
# to the view; that way it can return a sensible "invalid key"
# message instead of a confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(),
name='registration_activate'),
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
url(r'^register/complete/$',
TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA
name='registration_complete'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'), # NOQA
name='registration_disallowed'),
(r'', include('registration.auth_urls')),
) # NOQA
|
Allow root access for mock jdk in introduce variable test
|
package org.jetbrains.plugins.scala.refactoring.introduceVariable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess;
import junit.framework.Test;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.plugins.scala.base.ScalaLibraryLoader;
import org.jetbrains.plugins.scala.util.TestUtils;
import scala.Option$;
/**
* @author Alexander Podkhalyuzin
*/
public class IntroduceVariableTest extends AbstractIntroduceVariableTestBase {
@NonNls
private static final String DATA_PATH = "/introduceVariable/data";
public IntroduceVariableTest() {
super(TestUtils.getTestDataPath() + DATA_PATH);
}
public static Test suite() {
return new IntroduceVariableTest();
}
@Override
protected void setUp(Project project) {
super.setUp(project);
Module[] modules = ModuleManager.getInstance(project).getModules();
String mockJdk = TestUtils.getMockJdk();
VfsRootAccess.allowRootAccess(mockJdk);
Sdk sdk = JavaSdk.getInstance().createJdk("java sdk", mockJdk, false);
ScalaLibraryLoader loader = new ScalaLibraryLoader(project, modules[0], null, false, false, Option$.MODULE$.apply(sdk));
loader.loadLibrary(TestUtils.DEFAULT_SCALA_SDK_VERSION);
}
}
|
package org.jetbrains.plugins.scala.refactoring.introduceVariable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.Sdk;
import junit.framework.Test;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.plugins.scala.base.ScalaLibraryLoader;
import org.jetbrains.plugins.scala.util.TestUtils;
import scala.Option$;
/**
* @author Alexander Podkhalyuzin
*/
public class IntroduceVariableTest extends AbstractIntroduceVariableTestBase {
@NonNls
private static final String DATA_PATH = "/introduceVariable/data";
public IntroduceVariableTest() {
super(TestUtils.getTestDataPath() + DATA_PATH);
}
public static Test suite() {
return new IntroduceVariableTest();
}
@Override
protected void setUp(Project project) {
super.setUp(project);
Module[] modules = ModuleManager.getInstance(project).getModules();
Sdk sdk = JavaSdk.getInstance().createJdk("java sdk", TestUtils.getMockJdk(), false);
ScalaLibraryLoader loader = new ScalaLibraryLoader(project, modules[0], null, false, false, Option$.MODULE$.apply(sdk));
loader.loadLibrary(TestUtils.DEFAULT_SCALA_SDK_VERSION);
}
}
|
Add pacman (commit missing file)
|
var gulp = require('gulp');
var notify = require('gulp-notify'); // unused
var browserSync = require('browser-sync').create();
var projectName;
// projectName = 'flappy-bird';
projectName = 'space-hipster';
// projectName = 'tank';
// projectName = 'webfont';
// projectName = 'flappy-bird-2';
// projectName = 'doodle-jump';
projectName = '2048';
projectName = 'brick';
projectName = 'move-the-box';
projectName = 'platformer';
projectName = 'platformer-2';
projectName = 'car';
projectName = 'pacman';
/*================================================================
# HELPER
================================================================*/
// unused
function handleError(err) {
var msg = 'Error: ' + err.message;
console.error('Error', err.message);
browserSync.notify('Error: ' + err.message);
var args = Array.prototype.slice.call(arguments);
notify.onError({
title: 'Compile Error',
message: '<%= error.message %>'
}).apply(this, args);
if (typeof this.emit === 'function') this.emit('end')
}
/*================================================================
# TASK
================================================================*/
gulp.task('serve', function() {
browserSync.init({
'server': './',
'startPath': '/' + projectName,
'open': true
});
gulp.watch('./' + projectName + '/**/*.html').on('change', browserSync.reload);
gulp.watch('./' + projectName + '/**/*.js').on('change', browserSync.reload);
});
gulp.task('default', ['serve']);
|
var gulp = require('gulp');
var notify = require('gulp-notify'); // unused
var browserSync = require('browser-sync').create();
var projectName;
// projectName = 'flappy-bird';
projectName = 'space-hipster';
// projectName = 'tank';
// projectName = 'webfont';
// projectName = 'flappy-bird-2';
// projectName = 'doodle-jump';
projectName = '2048';
projectName = 'brick';
projectName = 'move-the-box';
projectName = 'platformer';
projectName = 'platformer-2';
projectName = 'car';
/*================================================================
# HELPER
================================================================*/
// unused
function handleError(err) {
var msg = 'Error: ' + err.message;
console.error('Error', err.message);
browserSync.notify('Error: ' + err.message);
var args = Array.prototype.slice.call(arguments);
notify.onError({
title: 'Compile Error',
message: '<%= error.message %>'
}).apply(this, args);
if (typeof this.emit === 'function') this.emit('end')
}
/*================================================================
# TASK
================================================================*/
gulp.task('serve', function() {
browserSync.init({
'server': './',
'startPath': '/' + projectName,
'open': true
});
gulp.watch('./' + projectName + '/**/*.html').on('change', browserSync.reload);
gulp.watch('./' + projectName + '/**/*.js').on('change', browserSync.reload);
});
gulp.task('default', ['serve']);
|
packet: Add all submodules to import *
You can now access pox.lib.packet.icmp as pox.lib.packet.ICMP if
you import the whole package (e.g., import pox.lib.packet as pkg).
--HG--
extra : rebase_source : b48d05949977468a669bdd55caab7ac898689441
|
"""
The POX packet library for packet parsing and creation.
This is based heavily on NOX's packet library, though it has undergone
some signficant change, particularly with regard to making packet
assembly easier.
Could still use more work.
"""
# None of this is probably that big, and almost all of it gets loaded
# under most circumstances anyway. Let's just load all of it.
import arp as ARP
import dhcp as DHCP
import dns as DNS
import eap as EAP
import eapol as EAPOL
import ethernet as ETHERNET
import icmp as ICMP
import ipv4 as IPV4
import lldp as LLDP
import tcp as TCP
import udp as UDP
import vlan as VLAN
from arp import *
from dhcp import *
from dns import *
from eap import *
from eapol import *
from ethernet import *
from icmp import *
from ipv4 import *
from lldp import *
from tcp import *
from udp import *
from vlan import *
__all__ = [
'arp',
'dhcp',
'dns',
'eap',
'eapol',
'ethernet',
'icmp',
'ipv4',
'lldp',
'tcp',
'tcp_opt',
'udp',
'vlan',
'ARP',
'DHCP',
'DNS',
'EAP',
'EAPOL',
'ETHERNET',
'ICMP',
'IPV4',
'LLDP',
'TCP',
'UDP',
'VLAN',
]
|
"""
The POX packet library for packet parsing and creation.
This is based heavily on NOX's packet library, though it has undergone
some signficant change, particularly with regard to making packet
assembly easier.
Could still use more work.
"""
# None of this is probably that big, and almost all of it gets loaded
# under most circumstances anyway. Let's just load all of it.
from arp import *
from dhcp import *
from dns import *
from eap import *
from eapol import *
from ethernet import *
from icmp import *
from ipv4 import *
from lldp import *
from tcp import *
from udp import *
from vlan import *
__all__ = [
'arp',
'dhcp',
'dns',
'eap',
'eapol',
'ethernet',
'icmp',
'ipv4',
'lldp',
'tcp',
'tcp_opt',
'udp',
'vlan',
]
|
Make widget independent from jquery
|
(function() {
// Success handler
var successHandler = function(status){
if (window.console != undefined) {
console.log("Purchase completed successfully: ", status);
}
window.location = document.getElementById('google-wallet-id').getAttribute('data-success-url');
};
// Failure handler
var failureHandler = function(status){
if (window.console != undefined) {
console.log("Purchase failed ", status);
}
window.location = document.getElementById('google-wallet-id').getAttribute('data-failure-url');
};
function purchase() {
var generated_jwt = document.getElementById('google-wallet-id').getAttribute('data-jwt');
google.payments.inapp.buy({
'jwt' : generated_jwt,
'success' : successHandler,
'failure' : failureHandler
});
return false
}
$ = this.jQuery || this.Zepto || this.ender || this.$;
if($) {
$(purchase)
} else {
window.onload = purchase
}
})()
|
// Success handler
var successHandler = function(status){
if (window.console != undefined) {
console.log("Purchase completed successfully: ", status);
}
window.location = $('input#google-wallet-id').data('success-url');
};
// Failure handler
var failureHandler = function(status){
if (window.console != undefined) {
console.log("Purchase failed ", status);
}
window.location = $('input#google-wallet-id').data('failure-url');
};
function purchase() {
var generated_jwt = $('input#google-wallet-id').data('jwt');
google.payments.inapp.buy({
'jwt' : generated_jwt,
'success' : successHandler,
'failure' : failureHandler
});
return false
}
jQuery(document).ready(function() {
purchase();
});
|
Fix for the "More at..." link to correct lineId
The sourceUrl link which controls the "More at tfl.gov.uk" href is now
fixed to link to the correct anchor for the line in question. This will
open the further information accordion and zoom the SVG map to the
correct line. (There appears to be an issue with the lineIds being incorrect on the
map on tfl.gov.uk at the moment?)
|
(function (env) {
"use strict";
env.ddg_spice_tfl_status = function(api_result){
Spice.add({
id: "tfl_status",
name: "Travel",
data: api_result,
meta: {
sourceName: "tfl.gov.uk",
sourceUrl: 'http://tfl.gov.uk/tube-dlr-overground/status/#line-' + api_result[0].id,
},
templates: {
group: 'base',
options: {
content: Spice.tfl_status.content,
moreAt: true
}
}
});
};
}(this));
|
(function (env) {
"use strict";
env.ddg_spice_tfl_status = function(api_result){
Spice.add({
id: "tfl_status",
name: "Travel",
data: api_result,
meta: {
sourceName: "tfl.gov.uk",
sourceUrl: 'http://tfl.gov.uk/tube-dlr-overground/status/#line-' + api_result.id,
},
templates: {
group: 'base',
options: {
content: Spice.tfl_status.content,
moreAt: true
}
}
});
};
}(this));
|
Use promise installer when using CLI
|
#!/usr/bin/env node
var _ = require('lodash')
var yargs = require('yargs')
var installer = require('./installer')
var pkg = require('../package.json')
var argv = yargs
.version(pkg.version)
.usage(pkg.description + '\n\nUsage: $0 --src <inputdir> --dest <outputdir>')
.option('src', {
describe: 'Directory that contains your built Electron app (e.g. with `electron-packager`)',
demand: true
})
.option('dest', {
describe: 'Directory that will contain the resulting Windows installer',
demand: true
})
.option('config', {
describe: 'JSON file that contains the metadata for your application',
config: true
})
.example('$0 --src dist/app/ --dest dist/installer/', 'use metadata from `dist/app/`')
.example('$0 --src dist/app/ --dest dist/installer/ --config config.json', 'use metadata from `config.json`')
.wrap(null)
.argv
console.log('Creating package (this may take a while)')
var options = _.omit(argv, ['$0', '_', 'version'])
installer(options)
.then(() => console.log(`Successfully created package at ${argv.dest}`))
.catch(err => {
console.error(err, err.stack)
process.exit(1)
})
|
#!/usr/bin/env node
var _ = require('lodash')
var yargs = require('yargs')
var installer = require('./installer')
var pkg = require('../package.json')
var argv = yargs
.version(pkg.version)
.usage(pkg.description + '\n\nUsage: $0 --src <inputdir> --dest <outputdir>')
.option('src', {
describe: 'Directory that contains your built Electron app (e.g. with `electron-packager`)',
demand: true
})
.option('dest', {
describe: 'Directory that will contain the resulting Windows installer',
demand: true
})
.option('config', {
describe: 'JSON file that contains the metadata for your application',
config: true
})
.example('$0 --src dist/app/ --dest dist/installer/', 'use metadata from `dist/app/`')
.example('$0 --src dist/app/ --dest dist/installer/ --config config.json', 'use metadata from `config.json`')
.wrap(null)
.argv
console.log('Creating package (this may take a while)')
var options = _.omit(argv, ['$0', '_', 'version'])
installer(options, function (err) {
if (err) {
console.error(err, err.stack)
process.exit(1)
}
console.log('Successfully created package at ' + argv.dest)
})
|
Add utility function for executable checking
|
# -*- coding: utf-8 -*-
"""
pytest_pipeline.utils
~~~~~~~~~~~~~~~~~~~~~
General utilities.
:copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
import gzip
import hashlib
import os
def file_md5sum(fname, unzip=False, mode="r", blocksize=65536):
if unzip:
opener = gzip.open
else:
opener = open
hasher = hashlib.md5()
with opener(fname, mode) as src:
buf = src.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = src.read(blocksize)
return hasher.hexdigest()
def isexecfile(fname):
return os.path.isfile(fname) and os.access(fname, os.X_OK)
def which(program):
# can not do anything meaningful without PATH
if "PATH" not in os.environ:
return
for possible in os.environ["PATH"].split(":"):
qualname = os.path.join(possible, program)
if isexecfile(qualname):
return qualname
return
|
# -*- coding: utf-8 -*-
"""
pytest_pipeline.utils
~~~~~~~~~~~~~~~~~~~~~
General utilities.
:copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
import gzip
import hashlib
def file_md5sum(fname, unzip=False, mode="r", blocksize=65536):
if unzip:
opener = gzip.open
else:
opener = open
hasher = hashlib.md5()
with opener(fname, mode) as src:
buf = src.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = src.read(blocksize)
return hasher.hexdigest()
|
Add a deprecation message to the docstring of image_bytes()
|
"""
Functions for displaying images inline in iTerm2.
See https://iterm2.com/images.html.
"""
from __future__ import print_function, division, absolute_import
import sys
import os
import base64
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def display_image_bytes(b, filename=None, inline=1):
"""
Display the image given by the bytes b in the terminal.
If filename=None the filename defaults to "Unnamed file".
"""
data = {
'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'),
'inline': inline,
'size': len(b),
'base64_img': base64.b64encode(b).decode('ascii'),
}
return (IMAGE_CODE.format(**data))
# Backwards compatibility
def image_bytes(b, filename=None, inline=1):
"""
**DEPRECATED**: Use display_image_bytes.
"""
return display_image_file(b, filename=filename, inline=inline)
def display_image_file(fn):
"""
Display an image in the terminal.
A newline is not printed.
"""
with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f:
sys.stdout.write(display_image_bytes(f.read(), filename=fn))
|
"""
Functions for displaying images inline in iTerm2.
See https://iterm2.com/images.html.
"""
from __future__ import print_function, division, absolute_import
import sys
import os
import base64
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def display_image_bytes(b, filename=None, inline=1):
"""
Display the image given by the bytes b in the terminal.
If filename=None the filename defaults to "Unnamed file".
"""
data = {
'file': base64.b64encode((filename or 'Unnamed file').encode('utf-8')).decode('ascii'),
'inline': inline,
'size': len(b),
'base64_img': base64.b64encode(b).decode('ascii'),
}
return (IMAGE_CODE.format(**data))
def display_image_file(fn):
"""
Display an image in the terminal.
A newline is not printed.
"""
with open(os.path.realpath(os.path.expanduser(fn)), 'rb') as f:
sys.stdout.write(display_image_bytes(f.read(), filename=fn))
# Backwards compatibility
image_bytes = display_image_bytes
|
Make sure constant name is not renamed
|
goog.require('app');
goog.provide('app.constants');
/**
* @const
* Constants for the module.
* Access them like app.constants.SCREEN
*/
app.module.constant('constants', app.constants);
app.constants = {
SCREEN: {
SMARTPHONE : 620,
TABLET : 1099,
DEKTOP : 1400
},
STEPS: {
'climbing_outdoor' : 4,
'climbing_indoor' : 4,
'hut' : 4,
'gite' : 4,
'shelter' : 4,
'access' : 4,
'camp_site' : 4,
'local_product' : 4,
'paragliding_takeoff' : 4,
'paragliding_landing' : 4,
'webcam': 4
},
REQUIRED_FIELDS: {
'waypoints': ['title' , 'lang', 'waypoint_type', 'elevation', 'longitude', 'latitude'],
'routes' : ['title' , 'lang', 'activities', 'waypoints'],
'outings' : ['title' , 'lang', 'date_start', 'routes', 'activities'],
'images': ['image_type']
},
documentEditing: {
FORM_PROJ: 'EPSG:4326',
DATA_PROJ: 'EPSG:3857'
}
};
|
goog.require('app');
goog.provide('app.constants');
/**
* @const
* Constants for the module.
* Access them like app.constants.SCREEN
*/
app.module.constant('constants', app.constants);
app.constants = {
SCREEN : {
SMARTPHONE : 620,
TABLET : 1099,
DEKTOP : 1400
},
STEPS : {
'climbing_outdoor' : 4,
'climbing_indoor' : 4,
'hut' : 4,
'gite' : 4,
'shelter' : 4,
'access' : 4,
'camp_site' : 4,
'local_product' : 4,
'paragliding_takeoff' : 4,
'paragliding_landing' : 4,
'webcam': 4
},
REQUIRED_FIELDS : {
waypoints: ['title' , 'lang', 'waypoint_type', 'elevation', 'longitude', 'latitude'],
routes : ['title' , 'lang', 'activities', 'waypoints'],
outings : ['title' , 'lang', 'date_start', 'routes', 'activities'],
images: ['image_type']
},
documentEditing: {
FORM_PROJ: 'EPSG:4326',
DATA_PROJ: 'EPSG:3857'
}
};
|
Replace Meteor.call with Meteor.apply for supposedly synchronous behavior
|
Keys = new Mongo.Collection("keys");
KeySchema = new SimpleSchema({
keyID: {
type: Number,
label: "Key ID",
min: 0
},
vCode: {
type: String,
label: "Verification Code",
regEx: /^[0-9a-zA-Z]+$/,
custom: function() {
if (this.field("keyID").isSet === false) return "keyIDMissing";
if (this.field("keyID").value < 0) return "keyIDInvalid";
keyValidationResult = Meteor.apply('validateKey', [this.field("keyID").value, this.value], true);
console.log(keyValidationResult);
if (keyValidationResult.ok === true) return 0;
else return "keyFailed";
}
}
});
KeySchema.messages({
"minNumber keyID": "[label] must be a positive number",
"keyIDMissing": "You must enter a Key ID",
"keyIDInvalid": "Key ID is invalid",
"regEx vCode": "[label] must contain only letters and numbers",
"keyFailed": "The API key failed verification with the server"
});
Keys.attachSchema(KeySchema);
|
Keys = new Mongo.Collection("keys");
KeySchema = new SimpleSchema({
keyID: {
type: Number,
label: "Key ID",
min: 0
},
vCode: {
type: String,
label: "Verification Code",
regEx: /^[0-9a-zA-Z]+$/,
custom: function() {
if (this.field("keyID").isSet === false) return "keyIDMissing";
if (this.field("keyID").value < 0) return "keyIDInvalid";
keyValidationResult = Meteor.call('validateKey', this.field("keyID").value, this.value);
console.log(keyValidationResult);
if (keyValidationResult.ok === true) return 0;
else return "keyFailed";
}
}
});
KeySchema.messages({
"minNumber keyID": "[label] must be a positive number",
"keyIDMissing": "You must enter a Key ID",
"keyIDInvalid": "Key ID is invalid",
"regEx vCode": "[label] must contain only letters and numbers",
"keyFailed": "The API key failed verification with the server"
});
Keys.attachSchema(KeySchema);
|
Add questions having access to results
|
importScripts("/app/bower_components/videogular-questions/questions-worker.js");
loadAnnotations({
"first-question": {
time: 4,
questions: [
{
id: "first-question",
type: "single",
question: "What is the moon made of?",
options: [
{
name: "cheese"
},
{
name: "cheeese"
},
{
name: "cheeeeeese"
}
]
},
{
id: "check-question",
type: "single",
question: "Answer incorrect, do you want to review the video",
options: [
{
name: "Yes",
action: function(video) {
video.setTime(0);
}
},
{
name: "No"
}
],
condition: function(questions, result) {
// show if the answer to the previous question is not "cheese"
return result !== "cheese";
}
}
]
}
});
|
importScripts("/app/bower_components/videogular-questions/questions-worker.js");
loadAnnotations({
"first-question": {
time: 8,
questions: [
{
id: "first-question",
type: "single",
question: "What is the moon made of?",
options: [
{
name: "cheese"
},
{
name: "cheeese"
},
{
name: "cheeeeeese"
}
]
},
{
id: "check-question",
type: "single",
question: "Answer incorrect, do you want to review the video",
options: [
{
name: "Yes",
action: function(video) {
video.setTime(0);
}
},
{
name: "No"
}
],
condition: function(questions) {
// show if the answer to the previous question is not "cheese"
return questions[0].answer !== "cheese";
}
}
]
}
});
|
Fix reading of admin status for users
|
import { usingConnect, sql } from './pg-helpers'
import Promise from 'bluebird';
import crypto from 'crypto';
import scmp from 'scmp'
const pbkdf2 = Promise.promisify(crypto.pbkdf2, crypto);
class User {
constructor(userData) {
this.id = userData.id;
this.email = userData.email;
this.passwordHash = userData.passwordhash;
this.salt = userData.salt;
this.isAdmin = userData.admin;
}
validatePassword(password) {
return pbkdf2(password, this.salt, 25000, 512, 'sha256')
.then(hashed => new Buffer(hashed, 'binary').toString('hex'))
.then(hash => scmp(hash, this.passwordHash));
}
}
export class UserRepository {
constructor(connectionString) {
this.connectionString = connectionString;
}
findById(id) {
return usingConnect(this.connectionString, client =>
client.queryAsync(sql`SELECT * FROM users WHERE id=${id}`)
.then(result => result.rows.length === 0
? undefined
: new User(result.rows[0])));
}
findByEmail(email) {
return usingConnect(this.connectionString, client =>
client.queryAsync(sql`SELECT * FROM users WHERE email=${email}`)
.then(result => result.rows.length === 0
? undefined
: new User(result.rows[0])));
}
}
|
import { usingConnect, sql } from './pg-helpers'
import Promise from 'bluebird';
import crypto from 'crypto';
import scmp from 'scmp'
const pbkdf2 = Promise.promisify(crypto.pbkdf2, crypto);
class User {
constructor(userData) {
this.id = userData.id;
this.email = userData.email;
this.passwordHash = userData.passwordhash;
this.salt = userData.salt;
this.isAdmin = userData.isadmin;
}
validatePassword(password) {
return pbkdf2(password, this.salt, 25000, 512, 'sha256')
.then(hashed => new Buffer(hashed, 'binary').toString('hex'))
.then(hash => scmp(hash, this.passwordHash));
}
}
export class UserRepository {
constructor(connectionString) {
this.connectionString = connectionString;
}
findById(id) {
return usingConnect(this.connectionString, client =>
client.queryAsync(sql`SELECT * FROM users WHERE id=${id}`)
.then(result => result.rows.length === 0
? undefined
: new User(result.rows[0])));
}
findByEmail(email) {
return usingConnect(this.connectionString, client =>
client.queryAsync(sql`SELECT * FROM users WHERE email=${email}`)
.then(result => result.rows.length === 0
? undefined
: new User(result.rows[0])));
}
}
|
Update forEach in load function
|
var fs = require('fs');
/**
* Parses vn-license-plates.csv and creates a nodes for fast lookups
* @return object nodes list of license plates
*/
function load() {
var data = fs.readFileSync(__dirname + '/vn-license-plates.csv', 'utf8');
var lines = data.split('\r\n');
var nodes = {};
lines.forEach(function (line) {
var parts = line.split(',');
var node = nodes;
for (var i = 0; i < parts.length - 1; i++) {
node[parts[i]] = parts[i + 1];
}
});
return nodes;
}
/**
* Lookup a license plates
* @param numer code input a license plate
* @return string province province of license plate
*/
module.exports.lookup = function (code) {
if (code.length < 2 || isNaN(code)) {
return null;
}
var nodes = load();
return nodes[code];
};
|
var fs = require('fs');
/**
* Parses vn-license-plates.csv and creates a nodes for fast lookups
* @return object nodes list of license plates
*/
function load() {
var data = fs.readFileSync(__dirname + '/vn-license-plates.csv', 'utf8');
var lines = data.split('\r\n');
var nodes = {};
lines.forEach(function(line) {
var parts = line.split(',');
var node = nodes;
for (var i = 0; i < parts.length - 1; i++) {
node[parts[i]] = parts[i + 1];
}
});
return nodes;
}
/**
* Lookup a license plates
* @param numer code input a license plate
* @return string province province of license plate
*/
module.exports.lookup = function (code) {
if (code.length < 2 || isNaN(code)) {
return null;
}
var nodes = load();
return nodes[code];
};
|
Use location.hash instead of url query params
|
function getLogin(){
return window.location.hash.slice(1)
}
var foundTemplate = $('#template').html();
Mustache.parse(foundTemplate);
var loadData = function(login, cb){
if(login){
var searchURL = 'https://api.github.com/search/issues?q=type:pr+author:'+login+'&sort=created&order=asc&per_page=1'
$.getJSON(searchURL, function(data){
if(data.items.length > 0){
$.getJSON(data.items[0].pull_request.url, function(data){
cb(data)
})
} else {
cb(null)
}
})
}
}
var renderData = function(pullRequestData){
console.log(pullRequestData)
if(pullRequestData){
var output = Mustache.render(foundTemplate, pullRequestData)
} else {
var output = '<p>It doesn\'t look like '+getLogin()+' has sent a pull request yet.</p>'
}
$('#main').html(output)
}
$(window).on('hashchange',function(){
loadData(getLogin(), renderData)
});
$('#user-form').submit(function(){
window.location.hash = $('#login')[0].value
$('#login')[0].value = ""
return false
})
loadData(getLogin(), renderData)
|
function getQueryVariable(variable){
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var login = getQueryVariable('login')
var foundTemplate = $('#template').html();
Mustache.parse(foundTemplate);
var loadData = function(login, cb){
var searchURL = 'https://api.github.com/search/issues?q=type:pr+author:'+login+'&sort=created&order=asc&per_page=1'
$.getJSON(searchURL, function(data){
if(data.items.length > 0){
$.getJSON(data.items[0].pull_request.url, function(data){
cb(data)
})
} else {
cb(null)
}
})
}
var renderData = function(pullRequestData){
if(pullRequestData){
var output = Mustache.render(foundTemplate, pullRequestData)
} else {
var output = '<p>It doesn\'t look like you\'ve sent a pull request yet.</p>'
}
$('#main').html(output)
}
if(login){ loadData(login, renderData) }
|
Use React from root project to avoid duplicate React problem
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js'],
alias: {
'react': path.join(__dirname, '..', '..', 'node_modules', 'react')
}
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/
}, {
test: /\.css?$/,
loaders: ['style', 'raw']
}]
}
};
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
resolve: {
extensions: ['', '.js']
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
exclude: /node_modules/
}, {
test: /\.css?$/,
loaders: ['style', 'raw']
}]
}
};
|
Handle graceful exit and timeout
Timeout was refactored and the defaults work correctly here.
|
# MIT licensed
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import atexit
import asyncio
import aiohttp
connector = aiohttp.TCPConnector(limit=20)
__all__ = ['session', 'HTTPError']
class HTTPError(Exception):
def __init__(self, code, message, response):
self.code = code
self.message = message
self.response = response
class BetterClientSession(aiohttp.ClientSession):
async def _request(self, *args, **kwargs):
if hasattr(self, "nv_config") and self.nv_config.get("proxy"):
kwargs.setdefault("proxy", self.nv_config.get("proxy"))
res = await super(BetterClientSession, self)._request(
*args, **kwargs)
if res.status >= 400:
raise HTTPError(res.status, res.reason, res)
return res
session = BetterClientSession(connector=connector)
@atexit.register
def cleanup():
loop = asyncio.get_event_loop()
loop.run_until_complete(session.close())
|
# MIT licensed
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import atexit
import aiohttp
connector = aiohttp.TCPConnector(limit=20)
__all__ = ['session', 'HTTPError']
class HTTPError(Exception):
def __init__(self, code, message, response):
self.code = code
self.message = message
self.response = response
class BetterClientSession(aiohttp.ClientSession):
async def _request(self, *args, **kwargs):
if hasattr(self, "nv_config") and self.nv_config.get("proxy"):
kwargs.setdefault("proxy", self.nv_config.get("proxy"))
res = await super(BetterClientSession, self)._request(
*args, **kwargs)
if res.status >= 400:
raise HTTPError(res.status, res.reason, res)
return res
session = BetterClientSession(connector=connector, read_timeout=10, conn_timeout=5)
atexit.register(session.close)
|
Add guards for null values. Move address formatting to internal pr
|
DDG.require('maps',function(){
ddg_spice_maps_maps = function(response) {
if (!response || !response.features || !response.features.length) { return Spice.failed('maps'); }
// Mapbox sends back a bunch of places, just want the first one for now
response = response.features[0];
if (response.relevance < 0.9) {
return Spice.failed('maps');
}
Spice.add({
data: response,
id: "maps",
name: "maps",
model: "Place"
});
};
});
|
DDG.require('maps',function(){
ddg_spice_maps_maps = function(response) {
if (!response) { return Spice.failed('maps'); }
// OSM sends back a bunch of places, just want the first one for now
response = response.features[0];
response.address=response.place_name;
if (response.relevance < 0.9) {
return Spice.failed('maps');
}
Spice.add({
data: response,
id: "maps",
name: "maps",
model: "Place"
});
};
});
|
Make .profile.d scripts and hooks compatible
- hooks should come before writing to .profile.d directory
[#145118801]
Signed-off-by: Dave Goddard <bfcdf3e6ca6cef45543bfbb57509c92aec9a39fb@goddard.id.au>
|
package main
import (
"golang/finalize"
_ "golang/hooks"
"os"
"github.com/cloudfoundry/libbuildpack"
)
type config struct {
Config struct {
GoVersion string `yaml:"GoVersion"`
VendorTool string `yaml:"VendorTool"`
Godep string `yaml:"Godep"`
} `yaml:"config"`
}
func main() {
stager, err := libbuildpack.NewStager(os.Args[1:], libbuildpack.NewLogger())
if err := libbuildpack.SetStagingEnvironment(stager.DepsDir); err != nil {
stager.Log.Error("Unable to setup environment variables: %s", err.Error())
os.Exit(10)
}
gf, err := finalize.NewFinalizer(stager)
if err != nil {
os.Exit(11)
}
if err := finalize.Run(gf); err != nil {
os.Exit(12)
}
if err := libbuildpack.RunAfterCompile(stager); err != nil {
stager.Log.Error("After Compile: %s", err.Error())
os.Exit(13)
}
if err := libbuildpack.SetLaunchEnvironment(stager.DepsDir, stager.BuildDir); err != nil {
stager.Log.Error("Unable to setup launch environment: %s", err.Error())
os.Exit(14)
}
stager.StagingComplete()
}
|
package main
import (
"golang/finalize"
_ "golang/hooks"
"os"
"github.com/cloudfoundry/libbuildpack"
)
type config struct {
Config struct {
GoVersion string `yaml:"GoVersion"`
VendorTool string `yaml:"VendorTool"`
Godep string `yaml:"Godep"`
} `yaml:"config"`
}
func main() {
stager, err := libbuildpack.NewStager(os.Args[1:], libbuildpack.NewLogger())
if err := libbuildpack.SetStagingEnvironment(stager.DepsDir); err != nil {
stager.Log.Error("Unable to setup environment variables: %s", err.Error())
os.Exit(10)
}
gf, err := finalize.NewFinalizer(stager)
if err != nil {
os.Exit(11)
}
if err := finalize.Run(gf); err != nil {
os.Exit(12)
}
if err := libbuildpack.SetLaunchEnvironment(stager.DepsDir, stager.BuildDir); err != nil {
stager.Log.Error("Unable to setup launch environment: %s", err.Error())
os.Exit(13)
}
if err := libbuildpack.RunAfterCompile(stager); err != nil {
stager.Log.Error("After Compile: %s", err.Error())
os.Exit(14)
}
stager.StagingComplete()
}
|
Optimize gRPC connection keepalive between services
|
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package manager
import (
"context"
"fmt"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
"openpitrix.io/openpitrix/pkg/logger"
)
func NewClient(ctx context.Context, host string, port int) (*grpc.ClientConn, error) {
endpoint := fmt.Sprintf("%s:%d", host, port)
conn, err := grpc.DialContext(ctx, endpoint,
grpc.WithInsecure(), grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: 10 * time.Second,
Timeout: 5 * time.Second,
PermitWithoutStream: true,
}))
if err != nil {
return nil, err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
logger.Error("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
logger.Error("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return conn, err
}
|
// Copyright 2018 The OpenPitrix Authors. All rights reserved.
// Use of this source code is governed by a Apache license
// that can be found in the LICENSE file.
package manager
import (
"context"
"fmt"
"google.golang.org/grpc"
"openpitrix.io/openpitrix/pkg/logger"
)
func NewClient(ctx context.Context, host string, port int) (*grpc.ClientConn, error) {
endpoint := fmt.Sprintf("%s:%d", host, port)
conn, err := grpc.Dial(endpoint, grpc.WithInsecure())
if err != nil {
return nil, err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
logger.Error("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
logger.Error("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return conn, err
}
|
Use Leaflet container for positioning map controls.
|
import React from 'react'
import { Map, TileLayer } from 'react-leaflet'
import NavigationContainer from '../navigation/NavigationContainer'
import MarkerCluster from './MarkerCluster'
import Search from './Search'
const MapComponent = ({ places, position, zoom, apiKey }) => (
<div className="map-container">
<div className="leaflet-control-container">
<div className="custom-controls">
<Search
defaultValue="Ort, Hof oder Initiative"
onSelect={newPosition => console.log('TODO: zoom to', newPosition)}
/>
</div>
</div>
<Map center={position} zoom={zoom.min} className="map">
<TileLayer
url={`//{s}.tiles.mapbox.com/v3/${apiKey}/{z}/{x}/{y}.png`}
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<MarkerCluster places={places} />
</Map>
<NavigationContainer />
</div>
)
MapComponent.propTypes = {
places: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
position: React.PropTypes.arrayOf(React.PropTypes.number).isRequired,
zoom: React.PropTypes.shape({
default: React.PropTypes.number,
min: React.PropTypes.number,
max: React.PropTypes.number,
searchResult: React.PropTypes.number,
}).isRequired,
apiKey: React.PropTypes.string.isRequired,
}
export default MapComponent
|
import React from 'react'
import { Map, TileLayer } from 'react-leaflet'
import NavigationContainer from '../navigation/NavigationContainer'
import MarkerCluster from './MarkerCluster'
import Search from './Search'
const MapComponent = ({ places, position, zoom, apiKey }) => (
<div className="map-container">
<div className="container">
<div className="custom-controls">
<Search
defaultValue="Ort, Hof oder Initiative"
onSelect={newPosition => console.log('TODO: zoom to', newPosition)}
/>
</div>
</div>
<Map center={position} zoom={zoom.min} className="map">
<TileLayer
url={`//{s}.tiles.mapbox.com/v3/${apiKey}/{z}/{x}/{y}.png`}
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<MarkerCluster places={places} />
</Map>
<NavigationContainer />
</div>
)
MapComponent.propTypes = {
places: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
position: React.PropTypes.arrayOf(React.PropTypes.number).isRequired,
zoom: React.PropTypes.shape({
default: React.PropTypes.number,
min: React.PropTypes.number,
max: React.PropTypes.number,
searchResult: React.PropTypes.number,
}).isRequired,
apiKey: React.PropTypes.string.isRequired,
}
export default MapComponent
|
Make getById() reject the promise if User is not found
Use user id to get the orders
|
/**
* New node file
*/
module.exports = function (app, dao) {
var util = require('../util');
var db = app.db;
var P = app.Promise;
var Order = {};
Order.getById = function (id, t) {
return db.Order.find(util.addTrans(t, {where: {id: id}}))
.then(function(order) {
if (!order) util.throwError(400, util.Error.ERR_ENTITY_NOT_FOUND, 'There is no Order with id: ' + id)
else return order
})
}
Order.getUserOrders = function (userId, options, t) {
var opt = options || {};
return dao.User.getById(userId, t)
.then(function(user) {
if (!user) util.throwError(400, util.Error.ERR_ENTITY_NOT_FOUND, 'There is no User with id: ' + userId);
return user.getOrders(util.addTrans(t, opt));
})
}
Order.create = function (order_data, user, t) {
return db.Order.create(order_data, util.addTrans(t, {}))
.then(function(order) {
return order.setUser(user, util.addTrans(t, {}))
});
}
return Order;
}
|
/**
* New node file
*/
module.exports = function (app, dao) {
var util = require('../util');
var db = app.db;
var P = app.Promise;
var Order = {};
Order.getById = function (id, t) {
return db.Order.find(util.addTrans(t, {where: {id: id}}));
}
Order.getUserOrders = function (username, options, t) {
var opt = options || {};
return dao.User.getByUsername(username, t)
.then(function(user) {
if (!user) util.throwError(200, util.Error.ERR_ENTITY_NOT_FOUND, 'There is no User with username: ' + username);
return user.getOrders(util.addTrans(t, opt));
})
}
Order.create = function (order_data, user, t) {
return db.Order.create(order_data, util.addTrans(t, {}))
.then(function(order) {
return order.setUser(user, util.addTrans(t, {}))
});
}
return Order;
}
|
Add a function for questions to the survey resource
|
from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def questions(self, session):
return session.questions
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
|
from djangorestframework import views
from djangorestframework import resources
from . import models
class RatingResource (resources.ModelResource):
model = models.Rating
class RatingInstanceView (views.InstanceModelView):
resource = RatingResource
class RatingListView (views.ListOrCreateModelView):
resource = RatingResource
class SurveySessionResource (resources.Resource):
# def __init__(self, *args, **kwargs):
# super(SurveySessionResource, self).__init__(*args, **kwargs)
# self.survey_session = models.SurveySession()
model = models.SurveySession # Can I get away with this?
fields = (
'questions',
'segment_id',
'block_index',
'point'
)
def segment_id(self, session):
return session.block.segment.id
def block_index(self, session):
return session.block.index
def point(self, session):
p = session.block.characteristic_point
return { 'lat': p.y, 'lon': p.x }
class SurveySessionView (views.View):
def get(self, request):
survey_session = models.SurveySession()
return SurveySessionResource().serialize_model(survey_session)
|
Fix "sprintf()" args in metadata pool.
|
<?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\AdminBundle\Metadata;
/**
* Metadata pool
*/
class MetadataPool
{
/**
* @var \Darvin\AdminBundle\Metadata\Metadata[]
*/
private $metadata;
/**
* Constructor
*/
public function __construct()
{
$this->metadata = [];
}
/**
* @param \Darvin\AdminBundle\Metadata\Metadata $metadata Metadata
*
* @throws \Darvin\AdminBundle\Metadata\MetadataException
*/
public function addMetadata(Metadata $metadata)
{
if (isset($this->metadata[$metadata->getEntityClass()])) {
throw new MetadataException(sprintf('Metadata for entity "%s" is already added.', $metadata->getEntityClass()));
}
$this->metadata[$metadata->getEntityClass()] = $metadata;
}
/**
* @return \Darvin\AdminBundle\Metadata\Metadata[]
*/
public function getAllMetadata()
{
return $this->metadata;
}
}
|
<?php
/**
* @author Igor Nikolaev <igor.sv.n@gmail.com>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\AdminBundle\Metadata;
/**
* Metadata pool
*/
class MetadataPool
{
/**
* @var \Darvin\AdminBundle\Metadata\Metadata[]
*/
private $metadata;
/**
* Constructor
*/
public function __construct()
{
$this->metadata = [];
}
/**
* @param \Darvin\AdminBundle\Metadata\Metadata $metadata Metadata
*
* @throws \Darvin\AdminBundle\Metadata\MetadataException
*/
public function addMetadata(Metadata $metadata)
{
if (isset($this->metadata[$metadata->getEntityClass()])) {
throw new MetadataException(sprintf('Metadata for entity "%s" is already added.'));
}
$this->metadata[$metadata->getEntityClass()] = $metadata;
}
/**
* @return \Darvin\AdminBundle\Metadata\Metadata[]
*/
public function getAllMetadata()
{
return $this->metadata;
}
}
|
Allow multiple arguments for quantifiers
|
"""
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value, *args):
""" At least one of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAny(value)
def all_of(value, *args):
""" All the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAll(value)
def none_of(value, *args):
""" None of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationNone(value)
|
"""
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value):
""" At least one of the items in value should match """
return ExpectationAny(value)
def all_of(value):
""" All the items in value should match """
return ExpectationAll(value)
def none_of(value):
""" None of the items in value should match """
return ExpectationNone(value)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.