text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Allow user colour to be 'default' | /** @module */
import * as TextFormatting from '@/helpers/TextFormatting';
import { def } from './common';
export default class UserState {
constructor(user) {
this.nick = user.nick;
this.host = user.host || '';
this.username = user.username || '';
this.realname = user.realname || '';
this.modes = user.modes || '';
this.away = user.away || '';
this.colour = user.colour || '';
this.buffers = Object.create(null);
this.account = '';
this.hasWhois = false;
// Whois details are non-enumerable properties (vues $watch won't cover these properties)
def(this, 'actual_host', '', true);
def(this, 'helpop', '', true);
def(this, 'bot', '', true);
def(this, 'server', '', true);
def(this, 'server_info', '', true);
def(this, 'operator', '', true);
def(this, 'channels', '', true);
def(this, 'modes', '', true);
def(this, 'idle', '', true);
def(this, 'logon', '', true);
def(this, 'registered_nick', '', true);
def(this, 'secure', '', true);
def(this, 'special', '', true);
}
getColour() {
if (!this.colour) {
this.colour = TextFormatting.createNickColour(this.nick);
}
// default will use the themes default text colour
return this.colour === 'default' ? '' : this.colour;
}
}
| /** @module */
import * as TextFormatting from '@/helpers/TextFormatting';
import { def } from './common';
export default class UserState {
constructor(user) {
this.nick = user.nick;
this.host = user.host || '';
this.username = user.username || '';
this.realname = user.realname || '';
this.modes = user.modes || '';
this.away = user.away || '';
this.colour = user.colour || '';
this.buffers = Object.create(null);
this.account = '';
this.hasWhois = false;
// Whois details are non-enumerable properties (vues $watch won't cover these properties)
def(this, 'actual_host', '', true);
def(this, 'helpop', '', true);
def(this, 'bot', '', true);
def(this, 'server', '', true);
def(this, 'server_info', '', true);
def(this, 'operator', '', true);
def(this, 'channels', '', true);
def(this, 'modes', '', true);
def(this, 'idle', '', true);
def(this, 'logon', '', true);
def(this, 'registered_nick', '', true);
def(this, 'secure', '', true);
def(this, 'special', '', true);
}
getColour() {
if (!this.colour) {
this.colour = TextFormatting.createNickColour(this.nick);
}
return this.colour;
}
}
|
Add filter for limiting to one account | from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):
class Meta:
queryset = PeriodicTask.objects.all()
resource_name = 'periodic_task'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class MessageSetResource(ModelResource):
class Meta:
queryset = MessageSet.objects.all()
resource_name = 'message_set'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class SubscriptionResource(ModelResource):
schedule = fields.ToOneField(PeriodicTaskResource, 'schedule')
message_set = fields.ToOneField(MessageSetResource, 'message_set')
class Meta:
queryset = Subscription.objects.all()
resource_name = 'subscription'
list_allowed_methods = ['post', 'get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
filtering = {
'to_addr': ALL,
'user_account': ALL
}
| from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):
class Meta:
queryset = PeriodicTask.objects.all()
resource_name = 'periodic_task'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class MessageSetResource(ModelResource):
class Meta:
queryset = MessageSet.objects.all()
resource_name = 'message_set'
list_allowed_methods = ['get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
class SubscriptionResource(ModelResource):
schedule = fields.ToOneField(PeriodicTaskResource, 'schedule')
message_set = fields.ToOneField(MessageSetResource, 'message_set')
class Meta:
queryset = Subscription.objects.all()
resource_name = 'subscription'
list_allowed_methods = ['post', 'get']
include_resource_uri = True
always_return_data = True
authentication = ApiKeyAuthentication()
authorization = Authorization()
filtering = {
'to_addr': ALL
}
|
Change info to warning if files not renamed | #!/usr/bin/python3
# tv_namer.py - Renames passed media files of TV shows
import shutil
import os
import sys
import logging
import videoLister
import scrapeTVDB
import regSplit
logger = logging.getLogger(__name__)
logging.basicConfig(filename='tv_namer.log',level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
in_path = ' '.join(sys.argv[1:])
for item in videoLister.videoDir(in_path):
logger.info("Working on: ", item)
reg_dict = regSplit.Split(item)
ext = os.path.splitext(item)[1]
if reg_dict['type'] == 'tv':
med_info = scrapeTVDB.theTVDB(reg_dict['title'], reg_dict['season'],
reg_dict['episode'])
new_name = (reg_dict['title'] + ' S' + reg_dict['season'].zfill(2) +
'E' + reg_dict['episode'].zfill(2) + ' - ' +
med_info['data'][0]['episodeName'] + ext)
logger.info("Renaming: %s, as: %s" % (item, new_name))
shutil.move(item, (os.path.join(os.path.dirname(item), new_name)))
else:
logger.warning("File not renamed: ", item)
| #!/usr/bin/python3
# tv_namer.py - Renames passed media files of TV shows
import shutil
import os
import sys
import logging
import videoLister
import scrapeTVDB
import regSplit
logger = logging.getLogger(__name__)
logging.basicConfig(filename='tv_namer.log',level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
in_path = ' '.join(sys.argv[1:])
for item in videoLister.videoDir(in_path):
logger.info("Working on: ", item)
reg_dict = regSplit.Split(item)
ext = os.path.splitext(item)[1]
if reg_dict['type'] == 'tv':
med_info = scrapeTVDB.theTVDB(reg_dict['title'], reg_dict['season'],
reg_dict['episode'])
new_name = (reg_dict['title'] + ' S' + reg_dict['season'].zfill(2) +
'E' + reg_dict['episode'].zfill(2) + ' - ' +
med_info['data'][0]['episodeName'] + ext)
logger.info("Renaming: %s, as: %s" % (item, new_name))
shutil.move(item, (os.path.join(os.path.dirname(item), new_name)))
else:
logger.info("File not renamed: ", item)
|
Add fetch polyfill to entry file | import 'babel-polyfill'
import 'whatwg-fetch'
import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import AppContainer from './containers/AppContainer'
// import fetchApiKeyifNeeded from './store/auth'
// ========================================================
// Store Instantiation
// ========================================================
export const initialState = Object.assign(window.___INITIAL_STATE__, { initLocation: 'schritt/1/2/spendenbestaetigung' })
const store = createStore(initialState)
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const routes = require('./routes/index').createRoutes(store)
ReactDOM.render(
<AppContainer store={store} routes={routes} />,
MOUNT_NODE
)
}
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
// Wrap render in try/catch
render = () => {
try {
renderApp()
} catch (error) {
renderError(error)
}
}
// Setup hot module replacement
module.hot.accept('./routes/index', () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
// ========================================================
// Go!
// ========================================================
render()
| import 'babel-polyfill'
import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import AppContainer from './containers/AppContainer'
// import fetchApiKeyifNeeded from './store/auth'
// ========================================================
// Store Instantiation
// ========================================================
export const initialState = Object.assign(window.___INITIAL_STATE__, { initLocation: 'schritt/1/2/spendenbestaetigung' })
const store = createStore(initialState)
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const routes = require('./routes/index').createRoutes(store)
ReactDOM.render(
<AppContainer store={store} routes={routes} />,
MOUNT_NODE
)
}
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
// Wrap render in try/catch
render = () => {
try {
renderApp()
} catch (error) {
renderError(error)
}
}
// Setup hot module replacement
module.hot.accept('./routes/index', () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
// ========================================================
// Go!
// ========================================================
render()
|
Add custom header for AJAX requests | import config from '../../config';
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
const apiPath = `/api/${config.apiVersion}${adjustedPath}`;
return apiPath;
}
class ApiAjax {
constructor() {
['get', 'post', 'put', 'patch', 'del'].forEach((method) =>
this[method] = (path, { data, header } = {}) => new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
const url = formatUrl(path);
req.onload = () => {
if (req.status === 500) {
reject(req.response);
return;
}
if (req.response.length > 0) {
resolve(JSON.parse(req.response));
return;
}
resolve(null);
};
/**
* Only covers network errors between the browser and the Express HTTP proxy
*/
req.onerror = () => {
reject(null);
};
req.open(method, url);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Content-Type', 'application/json');
if (Object.keys(header || {}).length) {
req.setRequestHeader(header.key, header.value);
}
req.send(JSON.stringify(data));
})
);
}
}
export default ApiAjax;
| import config from '../../config';
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
const apiPath = `/api/${config.apiVersion}${adjustedPath}`;
return apiPath;
}
class ApiAjax {
constructor() {
['get', 'post', 'put', 'patch', 'del'].forEach((method) =>
this[method] = (path, { data } = {}) => new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
const url = formatUrl(path);
req.onload = () => {
if (req.status === 500) {
reject(req.response);
return;
}
if (req.response.length > 0) {
resolve(JSON.parse(req.response));
return;
}
resolve(null);
};
/**
* Only covers network errors between the browser and the Express HTTP proxy
*/
req.onerror = () => {
reject(null);
};
req.open(method, url);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(data));
})
);
}
}
export default ApiAjax;
|
Make run_tests a function to make it fully backwards compatible | class TestRunner(object):
def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs):
self.verbosity = verbosity
self.interactive = interactive
self.failfast = failfast
def run_tests(self, test_labels, extra_tests=None):
import pytest
import sys
if test_labels is None:
print ('Not yet implemented: py.test is still not able to '
'discover the tests in all the INSTALLED_APPS as Django '
'requires.')
exit(1)
if extra_tests:
print ('Not yet implemented: py.test is still not able to '
'run extra_tests as Django requires.')
exit(1)
pytest_args = []
if self.failfast:
pytest_args.append('--exitfirst')
if self.verbosity == 0:
pytest_args.append('--quiet')
elif self.verbosity > 1:
pytest_args.append('--verbose')
# Remove arguments before (--). This separates Django command options
# from py.test ones.
try:
pytest_args_index = sys.argv.index('--') + 1
pytest_args.extend(sys.argv[pytest_args_index:])
except ValueError:
pass
sys.exit(pytest.main(pytest_args))
# Keep the old name to be backwards-compatible
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=None):
runner = TestRunner(verbosity, interactive, failfast=False)
runner.run_tests(test_labels, extra_tests)
| class TestRunner(object):
def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs):
self.verbosity = verbosity
self.interactive = interactive
self.failfast = failfast
def run_tests(self, test_labels):
import pytest
import sys
if test_labels is None:
print ('Not yet implemented: py.test is still not able to '
'discover the tests in all the INSTALLED_APPS as Django '
'requires.')
exit(1)
pytest_args = []
if self.failfast:
pytest_args.append('--exitfirst')
if self.verbosity == 0:
pytest_args.append('--quiet')
elif self.verbosity > 1:
pytest_args.append('--verbose')
# Remove arguments before (--). This separates Django command options
# from py.test ones.
try:
pytest_args_index = sys.argv.index('--') + 1
pytest_args.extend(sys.argv[pytest_args_index:])
except ValueError:
pass
sys.exit(pytest.main(pytest_args))
# Keep the old name to be backwards-compatible
def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
runner = TestRunner(verbosity, interactive, failfast=False)
runner.run_tests(test_labels)
|
Remove bash lang def for prismjs | // Grunt configuration
module.exports = {
autoprefixer: {
browsers: ['> 1%', 'last 2 versions']
},
concat: {
src: [
'node_modules/svg4everybody/dist/svg4everybody.js',
'node_modules/jquery-collapse/src/jquery.collapse.js',
'node_modules/prismjs/prism.js',
'node_modules/prismjs/plugins/show-language/prism-show-language.js',
'node_modules/prismjs/components/prism-php.js',
'node_modules/prismjs/components/prism-scss.js',
'node_modules/prismjs/components/prism-smarty.js',
'src/scripts/main.js'
],
dest: 'src/scripts/master.js'
},
copy: {
src: [
'*.php',
'*.tpl',
'info.txt',
'UTF-8/*.php'
],
dest: 'dist/<%= pkg.name %>'
},
modernizr: {
dev: 'src/scripts/modernizr/modernizr.js',
dest: 'dist/<%= pkg.name %>/scripts/modernizr/modernizr.js',
srcfiles: [
'src/scss/**/*.scss',
'src/scripts/master.js'
]
}
};
| // Grunt configuration
module.exports = {
autoprefixer: {
browsers: ['> 1%', 'last 2 versions']
},
concat: {
src: [
'node_modules/svg4everybody/dist/svg4everybody.js',
'node_modules/jquery-collapse/src/jquery.collapse.js',
'node_modules/prismjs/prism.js',
'node_modules/prismjs/plugins/show-language/prism-show-language.js',
'node_modules/prismjs/components/prism-bash.js',
'node_modules/prismjs/components/prism-php.js',
'node_modules/prismjs/components/prism-scss.js',
'node_modules/prismjs/components/prism-smarty.js',
'src/scripts/main.js'
],
dest: 'src/scripts/master.js'
},
copy: {
src: [
'*.php',
'*.tpl',
'info.txt',
'UTF-8/*.php'
],
dest: 'dist/<%= pkg.name %>'
},
modernizr: {
dev: 'src/scripts/modernizr/modernizr.js',
dest: 'dist/<%= pkg.name %>/scripts/modernizr/modernizr.js',
srcfiles: [
'src/scss/**/*.scss',
'src/scripts/master.js'
]
}
};
|
Update form definition in tests to demonstrate functionality | define(function () {
return [
{
"default": {
name: "TestForm",
label: "TestForm",
_elements: [
{
"default": {
name: "Name",
type: "text",
label: "Name"
}
},
{
"default": {
name: "Photo",
type: "file",
label: "Photo",
accept: "image/*",
capture: true
}
},
{
"default": {
name: "Photo1",
type: "file",
label: "Photo1",
accept: "image/*",
capture: false
}
},
{
"default": {
name: "Photo2",
type: "file",
label: "Photo2",
accept: "image/*",
capture: true
}
},
{
'default': {
name: 'location',
label: 'Location',
type: 'location'
}
},
{
'default': {
name: 'draw',
label: 'Sign',
type: 'draw',
size: 'signature'
}
},
{
"default": {
name: "Rank",
type: "number",
label: "Rank"
}
},
{
"default": {
name: "Details",
type: "text",
label: "Details"
}
}
]
}
}
];
});
| define(function () {
return [
{
"default": {
name: "TestForm",
label: "TestForm",
_elements: [
{
"default": {
name: "Name",
type: "text",
label: "Name"
}
},
{
"default": {
name: "Photo",
type: "file",
label: "Photo",
accept: "image/*"
}
},
{
"default": {
name: "Photo1",
type: "file",
label: "Photo1",
accept: "image/*"
}
},
{
"default": {
name: "Photo2",
type: "file",
label: "Photo2",
accept: "image/*"
}
},
{
'default': {
name: 'location',
label: 'Location',
type: 'location'
}
},
{
'default': {
name: 'draw',
label: 'Sign',
type: 'draw',
size: 'signature'
}
},
{
"default": {
name: "Rank",
type: "number",
label: "Rank"
}
},
{
"default": {
name: "Details",
type: "text",
label: "Details"
}
}
]
}
}
];
});
|
Update grid field count view able on each page for staff | <?php
/**
*
*
* @package silverstripe
* @subpackage sections
*/
class PeopleSection extends Section
{
private static $title = "List of people";
private static $description = "";
/**
* Database fields
* @var array
*/
private static $db = array(
'Title' => 'Varchar(40)',
'Content' => 'HTMLText'
);
/**
* Many_many relationship
* @var array
*/
private static $many_many = array(
'People' => 'SectionsPerson'
);
/**
* {@inheritdoc }
* @var array
*/
private static $many_many_extraFields = array(
'People' => array(
'Sort' => 'Int'
)
);
/**
* CMS Fields
* @return array
*/
public function getCMSFields()
{
$fields = parent::getCMSFields();
$PeopleConfig = GridFieldConfig_RecordEditor::create(100);
if ($this->People()->Count() > 0) {
$PeopleConfig->addComponent(new GridFieldOrderableRows());
}
$fields->addFieldsToTab(
'Root.Main',
array(
TextareaField::create(
'Title'
)->setRows(1),
HTMLEditorField::create(
'Content'
),
GridField::create(
'People',
'Current People(s)',
$this->People(),
$PeopleConfig
)
)
);
$this->extend('updateCMSFields', $fields);
return $fields;
}
}
| <?php
/**
*
*
* @package silverstripe
* @subpackage sections
*/
class PeopleSection extends Section
{
private static $title = "List of people";
private static $description = "";
/**
* Database fields
* @var array
*/
private static $db = array(
'Title' => 'Varchar(40)',
'Content' => 'HTMLText'
);
/**
* Many_many relationship
* @var array
*/
private static $many_many = array(
'People' => 'SectionsPerson'
);
/**
* {@inheritdoc }
* @var array
*/
private static $many_many_extraFields = array(
'People' => array(
'Sort' => 'Int'
)
);
/**
* CMS Fields
* @return array
*/
public function getCMSFields()
{
$fields = parent::getCMSFields();
$PeopleConfig = GridFieldConfig_RecordEditor::create();
if ($this->People()->Count() > 0) {
$PeopleConfig->addComponent(new GridFieldOrderableRows());
}
$fields->addFieldsToTab(
'Root.Main',
array(
TextareaField::create(
'Title'
)->setRows(1),
HTMLEditorField::create(
'Content'
),
GridField::create(
'People',
'Current People(s)',
$this->People(),
$PeopleConfig
)
)
);
$this->extend('updateCMSFields', $fields);
return $fields;
}
}
|
Remove unnecessary default parameter values | <?php
namespace Amp\Internal;
use Interop\Async\Loop;
/**
* Stores a set of functions to be invoked when an awaitable is resolved.
*
* @internal
*/
class WhenQueue {
/**
* @var callable[]
*/
private $queue = [];
/**
* @param callable|null $callback Initial callback to add to queue.
*/
public function __construct(callable $callback = null) {
if (null !== $callback) {
$this->push($callback);
}
}
/**
* Calls each callback in the queue, passing the provided values to the function.
*
* @param \Throwable|null $exception
* @param mixed $value
*/
public function __invoke($exception, $value) {
foreach ($this->queue as $callback) {
try {
$callback($exception, $value);
} catch (\Throwable $exception) {
Loop::defer(static function () use ($exception) {
throw $exception;
});
}
}
}
/**
* Unrolls instances of self to avoid blowing up the call stack on resolution.
*
* @param callable $callback
*/
public function push(callable $callback) {
if ($callback instanceof self) {
$this->queue = \array_merge($this->queue, $callback->queue);
return;
}
$this->queue[] = $callback;
}
}
| <?php
namespace Amp\Internal;
use Interop\Async\Loop;
/**
* Stores a set of functions to be invoked when an awaitable is resolved.
*
* @internal
*/
class WhenQueue {
/**
* @var callable[]
*/
private $queue = [];
/**
* @param callable|null $callback Initial callback to add to queue.
*/
public function __construct(callable $callback = null) {
if (null !== $callback) {
$this->push($callback);
}
}
/**
* Calls each callback in the queue, passing the provided values to the function.
*
* @param \Throwable|null $exception
* @param mixed $value
*/
public function __invoke($exception = null, $value = null) {
foreach ($this->queue as $callback) {
try {
$callback($exception, $value);
} catch (\Throwable $exception) {
Loop::defer(static function () use ($exception) {
throw $exception;
});
}
}
}
/**
* Unrolls instances of self to avoid blowing up the call stack on resolution.
*
* @param callable $callback
*/
public function push(callable $callback) {
if ($callback instanceof self) {
$this->queue = \array_merge($this->queue, $callback->queue);
return;
}
$this->queue[] = $callback;
}
}
|
Fix acceptance tests to match correct shape from API repsonse | "use strict"
const path = require('path')
const OperationHelper = require('../../').OperationHelper
require('dotenv').config({
silent: true,
path: path.join(__dirname, '.env')
})
const e = process.env
let config = {
AWS_ACCESS_KEY_ID: e.AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY: e.AWS_SECRET_ACCESS_KEY,
AWS_ASSOCIATE_ID: e.AWS_ASSOCIATE_ID
}
describe('OperationHelper', () => {
describe('execute a typical query', () => {
let result
before(() => {
let opHelper = new OperationHelper({
awsId: config.AWS_ACCESS_KEY_ID,
awsSecret: config.AWS_SECRET_ACCESS_KEY,
assocId: config.AWS_ASSOCIATE_ID
})
return opHelper.execute('ItemSearch', {
'SearchIndex': 'Books',
'Keywords': 'harry potter',
'ResponseGroup': 'ItemAttributes,Offers'
}).then((response) => {
result = response.result
})
})
it('returns a sane looking response', () => {
expect(result.ItemSearchResponse).to.exist
expect(result.ItemSearchResponse.Items.Item.length).to.be.at.least(1)
expect(result.ItemSearchResponse.Items.Item[0].ItemAttributes.Author[0]).to.equal('J.K. Rowling')
})
})
})
| "use strict"
const path = require('path')
const OperationHelper = require('../../').OperationHelper
require('dotenv').config({
silent: true,
path: path.join(__dirname, '.env')
})
const e = process.env
let config = {
AWS_ACCESS_KEY_ID: e.AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY: e.AWS_SECRET_ACCESS_KEY,
AWS_ASSOCIATE_ID: e.AWS_ASSOCIATE_ID
}
describe('OperationHelper', () => {
describe('execute a typical query', () => {
let result
before(() => {
let opHelper = new OperationHelper({
awsId: config.AWS_ACCESS_KEY_ID,
awsSecret: config.AWS_SECRET_ACCESS_KEY,
assocId: config.AWS_ASSOCIATE_ID
})
return opHelper.execute('ItemSearch', {
'SearchIndex': 'Books',
'Keywords': 'harry potter',
'ResponseGroup': 'ItemAttributes,Offers'
}).then((response) => {
result = response.result
})
})
it('returns a sane looking response', () => {
expect(result.ItemSearchResponse).to.exist
expect(result.ItemSearchResponse.Items.length).to.equal(1)
expect(result.ItemSearchResponse.Items[0].Item[0].ItemAttributes[0].Author[0]).to.equal('J.K. Rowling')
})
})
}) |
Use env var for API URL when adding bookmarks | ;(function(){
'use strict';
var modalCtrl = function($scope, $uibModalInstance, $http, messageParts){
$scope.modalTitle = messageParts.title;
$scope.modalHeading = messageParts.heading;
$scope.message = messageParts.message;
$scope.messageTemplate = messageParts.messageTemplate;
$scope.valid = messageParts.valid;
$scope.buttonSet = messageParts.buttonSet;
$scope.fields = {};
$scope.apiBaseUrl = process.env.API_BASE_URL;
$scope.ok = ok;
$scope.cancel = cancel;
$scope.dismiss = dismiss;
$scope.submit = submit;
// Functions
function ok() {
$uibModalInstance.close(true);
}
function cancel() {
$uibModalInstance.close(false);
}
function dismiss() {
$uibModalInstance.dismiss();
}
function submit() {
console.log('Submitted');
console.log($scope.fields);
$http.post(
$scope.apiBaseUrl + 'api/bookmarks/bookmarks/',
$scope.fields
).then(function success(response){
console.log('Success');
$scope.ok();
}, function error(response){
console.log('Error');
});
}
};
module.exports = modalCtrl;
})();
| ;(function(){
'use strict';
var modalCtrl = function($scope, $uibModalInstance, $http, messageParts){
$scope.modalTitle = messageParts.title;
$scope.modalHeading = messageParts.heading;
$scope.message = messageParts.message;
$scope.messageTemplate = messageParts.messageTemplate;
$scope.valid = messageParts.valid;
$scope.buttonSet = messageParts.buttonSet;
$scope.fields = {};
$scope.ok = ok;
$scope.cancel = cancel;
$scope.dismiss = dismiss;
$scope.submit = submit;
// Functions
function ok() {
$uibModalInstance.close(true);
}
function cancel() {
$uibModalInstance.close(false);
}
function dismiss() {
$uibModalInstance.dismiss();
}
function submit() {
console.log('Submitted');
console.log($scope.fields);
$http.post(
'http://api.waypoints.local/api/bookmarks/bookmarks/',
$scope.fields
).then(function success(response){
console.log('Success');
$scope.ok();
}, function error(response){
console.log('Error');
});
}
};
module.exports = modalCtrl;
})();
|
ZON-4070: Fix typo (belongs to commit:9ec5886) | from setuptools import setup, find_packages
setup(
name='zeit.brightcove',
version='2.10.2.dev0',
author='gocept, Zeit Online',
author_email='[email protected]',
url='http://www.zeit.de/',
description='Brightcove HTTP interface',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
license='BSD',
namespace_packages=['zeit'],
install_requires=[
'gocept.runner>0.5.3',
'grokcore.component',
'grokcore.view',
'lxml',
'pytz',
'setuptools',
'zeit.addcentral',
'zeit.cms>=2.104.0.dev0',
'zeit.content.video>=2.7.4.dev0',
'zeit.solr>=2.2.0.dev0',
'zope.cachedescriptors',
'zope.component',
'zope.interface',
'zope.schema',
],
extras_require=dict(test=[
'zeit.content.author',
]),
entry_points="""
[console_scripts]
update-brightcove-repository=zeit.brightcove.update:_update_from_brightcove
brightcove-import-playlists=zeit.brightcove.update2:import_playlists
"""
)
| from setuptools import setup, find_packages
setup(
name='zeit.brightcove',
version='2.10.2.dev0',
author='gocept, Zeit Online',
author_email='[email protected]',
url='http://www.zeit.de/',
description='Brightcove HTTP interface',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
license='BSD',
namespace_packages=['zeit'],
install_requires=[
'gocept.runner>0.5.3',
'grokcore.component',
'grokcore.view',
'lxml',
'pytz',
'setuptools',
'zeit.addcentral',
'zeit.cms>=2.104.0.dev0',
'zeit.content.video>=2.7.4.dev0',
'zeit.solr>=2.2.0.dev0',
'zope.cachedescriptors',
'zope.component',
'zope.interface',
'zope.schema',
],
extras_require=dict(test=[
'zeit.content.author',
]),
entry_points="""
[console_scripts]
update-brightcove-repository=zeit.brightcove.update:_update_from_brightcove
brightcove-import-playlists=zeit.brightcove.update2:_import_playlists
"""
)
|
Add identifier to log entry | <?php namespace Nathanmac\InstantMessenger\Services;
use Nathanmac\InstantMessenger\Message;
use Psr\Log\LoggerInterface;
class LogService implements MessengerService {
/**
* The Logger instance.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* Create a new log transport instance.
*
* @param \Psr\Log\LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Create a new LogService instance.
*
* @param \Psr\Log\LoggerInterface $logger
*
* @return LogService
*/
public static function newInstance(LoggerInterface $logger)
{
return new self($logger);
}
/**
* Send message to the external service
*
* @param Message $message
* @return mixed
*/
public function send(Message $message)
{
$this->logger->debug($this->buildMessage($message));
}
/**
* Construct message ready for formatting and transmission.
*
* @param Message $message
*
* @return string
*/
protected function buildMessage(Message $message)
{
$from = $message->getFrom();
$content = $message->getBody();
// Auto Notifier : Hello this is a simple notification.
// John Smith [[email protected]] : Hello this is a simple notification.
return "[MESSENGER] {$from['name']}" . ($from['email'] != "" ? "[{$from['email']}]" : "") . " : {$content}";
}
} | <?php namespace Nathanmac\InstantMessenger\Services;
use Nathanmac\InstantMessenger\Message;
use Psr\Log\LoggerInterface;
class LogService implements MessengerService {
/**
* The Logger instance.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* Create a new log transport instance.
*
* @param \Psr\Log\LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Create a new LogService instance.
*
* @param \Psr\Log\LoggerInterface $logger
*
* @return LogService
*/
public static function newInstance(LoggerInterface $logger)
{
return new self($logger);
}
/**
* Send message to the external service
*
* @param Message $message
* @return mixed
*/
public function send(Message $message)
{
$this->logger->debug($this->buildMessage($message));
}
/**
* Construct message ready for formatting and transmission.
*
* @param Message $message
*
* @return string
*/
protected function buildMessage(Message $message)
{
$from = $message->getFrom();
$content = $message->getBody();
// Auto Notifier : Hello this is a simple notification.
// John Smith [[email protected]] : Hello this is a simple notification.
return "{$from['name']}" . ($from['email'] != "" ? "[{$from['email']}]" : "") . " : {$content}";
}
} |
Add a timestamp to each report | /*global Firebase, grecaptcha*/
;(function() {
var form = document.querySelector('.al-form > form');
var captchaIsValid = false;
window.initCaptcha = function() {
var captcha = document.querySelector('#captcha');
grecaptcha.render(captcha, {
sitekey: '6Ld9nwATAAAAACdsGH5foKWLUwuICMWrtevg1Gch',
callback: function() {
captchaIsValid = true;
}
});
};
form.addEventListener('submit', function(evt) {
evt.preventDefault();
if (captchaIsValid) {
(function() {
var reportes = new Firebase('https://reportes-accesolibre.firebaseio.com/reportes/'),
tipos = form.elements.tipo_falla,
indexTipo = tipos.selectedIndex,
tipo = tipos.options[indexTipo].value;
reportes.push({
tipo: tipo,
ubicacion: form.elements.ubicacion.value,
tiempo: form.elements.tiempo.value,
detalles: form.elements.detalles.value,
timestamp: Date.now().valueOf()
}, function() {
document.querySelector('.al-form').style.display = 'none';
document.querySelector('.gracias').style.display = 'block';
});
})();
}
});
})();
| /*global Firebase, grecaptcha*/
;(function() {
var form = document.querySelector('.al-form > form');
var captchaIsValid = false;
window.initCaptcha = function() {
var captcha = document.querySelector('#captcha');
grecaptcha.render(captcha, {
sitekey: '6Ld9nwATAAAAACdsGH5foKWLUwuICMWrtevg1Gch',
callback: function() {
captchaIsValid = true;
}
});
};
form.addEventListener('submit', function(evt) {
evt.preventDefault();
if (captchaIsValid) {
(function() {
var reportes = new Firebase('https://reportes-accesolibre.firebaseio.com/reportes/'),
tipos = form.elements.tipo_falla,
indexTipo = tipos.selectedIndex,
tipo = tipos.options[indexTipo].value;
reportes.push({
tipo: tipo,
ubicacion: form.elements.ubicacion.value,
tiempo: form.elements.tiempo.value,
detalles: form.elements.detalles.value
}, function() {
document.querySelector('.al-form').style.display = 'none';
document.querySelector('.gracias').style.display = 'block';
});
})();
}
});
})();
|
Use data-active=true instead of data-start-active | (function(){
"use strict";
xtag.register("sam-tabbar", {
lifecycle: {
created: function() {
if (!this.role) {
this.role = "tablist";
}
},
inserted: function() {
this.activeTabId = this.querySelector("[role='tab'][data-active=true]").id;
},
removed: function() {},
attributeChanged: function() {}
},
events: {
"press": function (event) {
var el = event.originalTarget;
//Checks if a tab was pressed
if (!el || el.getAttribute("role") !== "tab") return;
this.setTab(el.id, true);
}
},
accessors: {
role: {
attribute: {}
}
},
methods: {
setTab: function (tabid, fireEvent) {
var eventName = "tabChange";
if (!this.querySelector("[id='"+tabid+"'][role='tab']")) {
console.error("Cannot set to unknown tabid");
return false;
}
//Checks if person is trying to set to currently active tab
if (this.activeTabId === tabid) {
eventName = "activeTabPress"
} else {
document.getElementById(this.activeTabId).dataset.active = false;
this.activeTabId = tabid;
document.getElementById(this.activeTabId).dataset.active = true;
}
if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId});
return true;
}
}
});
})();
| (function(){
"use strict";
xtag.register("sam-tabbar", {
lifecycle: {
created: function() {
if (!this.role) {
this.role = "tablist";
}
},
inserted: function() {
this.activeTabId = this.querySelector("[role='tab'][data-start-active]").id;
},
removed: function() {},
attributeChanged: function() {}
},
events: {
"press": function (event) {
var el = event.originalTarget;
//Checks if a tab was pressed
if (!el || el.getAttribute("role") !== "tab") return;
this.setTab(el.id, true);
}
},
accessors: {
role: {
attribute: {}
}
},
methods: {
setTab: function (tabid, fireEvent) {
var eventName = "tabChange";
if (!this.querySelector("[id='"+tabid+"'][role='tab']")) {
console.error("Cannot set to unknown tabid");
return false;
}
//Checks if person is trying to set to currently active tab
if (this.activeTabId === tabid) {
eventName = "activeTabPress"
} else {
document.getElementById(this.activeTabId).dataset.active = false;
this.activeTabId = tabid;
document.getElementById(this.activeTabId).dataset.active = true;
}
if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId});
return true;
}
}
});
})();
|
Make sure that output is text in Python 2 & 3. | import os
import unittest
import subprocess
import utils
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
test_dir = utils.set_search_paths(TOPDIR)
utils.set_search_paths(TOPDIR)
from allosmod.util import check_output
class Tests(unittest.TestCase):
def test_bad(self):
"""Test wrong arguments to get_rest"""
for args in ([], [''] * 2):
out = check_output(['allosmod', 'get_rest'] + args,
stderr=subprocess.STDOUT, retcode=2)
out = check_output(['python', '-m',
'allosmod.get_rest'] + args,
stderr=subprocess.STDOUT, retcode=2)
def test_simple(self):
"""Simple complete run of get_rest"""
with open('get_rest.in', 'w') as fh:
pass
out = check_output(['allosmod', 'get_rest',
os.path.join(test_dir, 'input',
'asite_pdb1.pdb')],
universal_newlines=True)
os.unlink('get_rest.in')
# PDB file contains no sugars, so no restraints should be output
self.assertEqual(out, '')
if __name__ == '__main__':
unittest.main()
| import os
import unittest
import subprocess
import utils
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
test_dir = utils.set_search_paths(TOPDIR)
utils.set_search_paths(TOPDIR)
from allosmod.util import check_output
class Tests(unittest.TestCase):
def test_bad(self):
"""Test wrong arguments to get_rest"""
for args in ([], [''] * 2):
out = check_output(['allosmod', 'get_rest'] + args,
stderr=subprocess.STDOUT, retcode=2)
out = check_output(['python', '-m',
'allosmod.get_rest'] + args,
stderr=subprocess.STDOUT, retcode=2)
def test_simple(self):
"""Simple complete run of get_rest"""
with open('get_rest.in', 'w') as fh:
pass
out = check_output(['allosmod', 'get_rest',
os.path.join(test_dir, 'input',
'asite_pdb1.pdb')])
os.unlink('get_rest.in')
# PDB file contains no sugars, so no restraints should be output
self.assertEqual(out, '')
if __name__ == '__main__':
unittest.main()
|
Remove the extra setNotModified function call.
Signed-off-by: Hunter Skrasek <[email protected]> | <?php namespace Aranw\ETagsMiddleware;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
class ETags implements HttpKernelInterface {
/**
* The wrapped kernel implementation.
*
* @var \Symfony\Component\HttpKernel\HttpKernelInterface
*/
protected $app;
/**
* Create a new RateLimiter instance.
*
* @param \Symfony\Component\HttpKernel\HttpKernelInterface $app
* @return void
*/
public function __construct(HttpKernelInterface $app)
{
$this->app = $app;
}
/**
* Handle the given request and get the response.
*
* @implements HttpKernelInterface::handle
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param int $type
* @param bool $catch
* @return \Symfony\Component\HttpFoundation\Response
*/
public function handle(SymfonyRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
// Handle on passed down request
$response = $this->app->handle($request, $type, $catch);
if ( ! $response->headers->has('etag')) {
$responseETag = md5($response->getContent());
$response->setEtag($responseETag);
}
if ($response->isNotModified($request)) {
return $response; // Return our empty 304 not modified response
// Return 304 if ETag matches given response
}
return $response;
}
} | <?php namespace Aranw\ETagsMiddleware;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
class ETags implements HttpKernelInterface {
/**
* The wrapped kernel implementation.
*
* @var \Symfony\Component\HttpKernel\HttpKernelInterface
*/
protected $app;
/**
* Create a new RateLimiter instance.
*
* @param \Symfony\Component\HttpKernel\HttpKernelInterface $app
* @return void
*/
public function __construct(HttpKernelInterface $app)
{
$this->app = $app;
}
/**
* Handle the given request and get the response.
*
* @implements HttpKernelInterface::handle
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param int $type
* @param bool $catch
* @return \Symfony\Component\HttpFoundation\Response
*/
public function handle(SymfonyRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
// Handle on passed down request
$response = $this->app->handle($request, $type, $catch);
if ( ! $response->headers->has('etag')) {
$responseETag = md5($response->getContent());
$response->setEtag($responseETag);
}
if ($response->isNotModified($request)) {
$response->setNotModified();
return $response; // Return our empty 304 not modified response
// Return 304 if ETag matches given response
}
return $response;
}
} |
Use sqlite if no DEV_DATABASE specified in development env | import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
if os.environ.get('DEV_DATABASE_URL'):
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL')
else:
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
class TestingConfig(Config):
TESTING = True
if os.environ.get('TEST_DATABASE_URL'):
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL')
else:
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
@classmethod
def init_app(cls, app):
pass
class HerokuConfig(ProductionConfig):
@classmethod
def init_app(cls, app):
ProductionConfig.init_app(app)
# # log to stderr
# import logging
# from logging import StreamHandler
# file_handler = StreamHandler()
# file_handler.setLevel(logging.WARNING)
# app.logger.addHandler(file_handler)
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'heroku': HerokuConfig,
'default': DevelopmentConfig
} | import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL')
class TestingConfig(Config):
TESTING = True
if os.environ.get('TEST_DATABASE_URL'):
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL')
else:
basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
@classmethod
def init_app(cls, app):
pass
class HerokuConfig(ProductionConfig):
@classmethod
def init_app(cls, app):
ProductionConfig.init_app(app)
# # log to stderr
# import logging
# from logging import StreamHandler
# file_handler = StreamHandler()
# file_handler.setLevel(logging.WARNING)
# app.logger.addHandler(file_handler)
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'heroku': HerokuConfig,
'default': DevelopmentConfig
} |
Set initial slug length to 3 | <?php
class Helpers
{
const SUPERUSER_ID = 1;
const PAGINATION_DEFAULT_ITEMS = 15;
const UPLOAD_SLUG_INITIAL_LENGTH = 3;
const NEW_USER_DAYS = 7; // How long is a user considered "new"
const API_KEY_LENGTH = 64;
const DB_CACHE_TIME = 5; // Minutes
// http://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes
/**
* @param $bytes
* @param int $precision
* @return string
*/
public static function formatBytes($bytes, $precision = 2)
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1000));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1000, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
/**
* @param $file
* @return bool
*/
public static function canHaveExif(SplFileInfo $file)
{
$hasExif = false;
if (function_exists('exif_imagetype')) {
$hasExif = (exif_imagetype($file) != 0);
}
return $hasExif;
}
} | <?php
class Helpers
{
const SUPERUSER_ID = 1;
const PAGINATION_DEFAULT_ITEMS = 15;
const UPLOAD_SLUG_INITIAL_LENGTH = 4;
const NEW_USER_DAYS = 7; // How long is a user considered "new"
const API_KEY_LENGTH = 64;
const DB_CACHE_TIME = 5; // Minutes
// http://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes
/**
* @param $bytes
* @param int $precision
* @return string
*/
public static function formatBytes($bytes, $precision = 2)
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1000));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1000, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
/**
* @param $file
* @return bool
*/
public static function canHaveExif(SplFileInfo $file)
{
$hasExif = false;
if (function_exists('exif_imagetype')) {
$hasExif = (exif_imagetype($file) != 0);
}
return $hasExif;
}
} |
Set a type for deleteSession() | <?php
interface OAuth2ServerDatabase
{
public function validateClient(
string $clientId,
string $clientSecret = null,
string $redirectUri = null
);
public function newSession(
string $clientId,
string $redirectUri,
$type = 'user',
string $typeId = null,
string $authCode = null,
string $accessToken = null,
$stage = 'request'
);
public function updateSession(
string $clientId,
$type = 'user',
string $typeId = null,
string $authCode = null,
string $accessToken = null,
string $stage
);
public function deleteSession(
string $clientId,
string $type,
string $typeId
);
public function validateAuthCode(
string $clientId,
string $redirectUri,
string $authCode
);
public function getAccessToken(int $sessionId);
public function removeAuthCode(int $sessionId);
public function setAccessToken(
int $sessionId,
string $accessToken
);
public function addSessionScope(
int $sessionId,
string $scope
);
public function getScope(string $scope);
public function updateSessionScopeAccessToken(
int $sesstionId,
string $accessToken
);
public function accessTokenScopes(string $accessToken);
} | <?php
interface OAuth2ServerDatabase
{
public function validateClient(
string $clientId,
string $clientSecret = null,
string $redirectUri = null
);
public function newSession(
string $clientId,
string $redirectUri,
$type = 'user',
string $typeId = null,
string $authCode = null,
string $accessToken = null,
$stage = 'request'
);
public function updateSession(
string $clientId,
$type = 'user',
string $typeId = null,
string $authCode = null,
string $accessToken = null,
string $stage
);
public function deleteSession(
string $clientId,
string $typeId
);
public function validateAuthCode(
string $clientId,
string $redirectUri,
string $authCode
);
public function getAccessToken(int $sessionId);
public function removeAuthCode(int $sessionId);
public function setAccessToken(
int $sessionId,
string $accessToken
);
public function addSessionScope(
int $sessionId,
string $scope
);
public function getScope(string $scope);
public function updateSessionScopeAccessToken(
int $sesstionId,
string $accessToken
);
public function accessTokenScopes(string $accessToken);
} |
Return tree to prevent breaking builds | var JSCSFilter = require('broccoli-jscs');
var mergeTrees = require('broccoli-merge-trees');
var pickFiles = require('broccoli-static-compiler');
var checker = require('ember-cli-version-checker');
module.exports = {
name: 'broccoli-jscs',
shouldSetupRegistryInIncluded: function() {
return !checker.isAbove(this, '0.1.10');
},
lintTree: function(type, tree) {
var jscsTree = new JSCSFilter(tree, this.app.options.jscsOptions);
if (!jscsTree.enabled || jscsTree.bypass || jscsTree.disableTestGenerator) {
return tree;
}
return jscsTree;
},
included: function(app) {
var addonContext = this;
this.app = app;
this._super.included.apply(this, arguments);
if (app.tests && this.shouldSetupRegistryInIncluded()) {
app.registry.add('js', {
name: 'broccoli-jscs',
ext: 'js',
toTree: function(tree, inputPath, outputPath, options) {
var jscsTree = addonContext.lintTree('unknown-type', tree);
if (!jscsTree) {
return tree;
}
return mergeTrees([
tree,
pickFiles(jscsTree, {
srcDir: '/',
destDir: outputPath + '/tests/'
})
], { overwrite: true });
}
});
}
}
};
| var JSCSFilter = require('broccoli-jscs');
var mergeTrees = require('broccoli-merge-trees');
var pickFiles = require('broccoli-static-compiler');
var checker = require('ember-cli-version-checker');
module.exports = {
name: 'broccoli-jscs',
shouldSetupRegistryInIncluded: function() {
return !checker.isAbove(this, '0.1.10');
},
lintTree: function(type, tree) {
var jscsTree = new JSCSFilter(tree, this.app.options.jscsOptions);
if (!jscsTree.enabled || jscsTree.bypass || jscsTree.disableTestGenerator) {
return;
}
return jscsTree;
},
included: function(app) {
var addonContext = this;
this.app = app;
this._super.included.apply(this, arguments);
if (app.tests && this.shouldSetupRegistryInIncluded()) {
app.registry.add('js', {
name: 'broccoli-jscs',
ext: 'js',
toTree: function(tree, inputPath, outputPath, options) {
var jscsTree = addonContext.lintTree('unknown-type', tree);
if (!jscsTree) {
return tree;
}
return mergeTrees([
tree,
pickFiles(jscsTree, {
srcDir: '/',
destDir: outputPath + '/tests/'
})
], { overwrite: true });
}
});
}
}
};
|
Update the error messaging to be more useful and use the correct exit codes | <?php
require_once __DIR__ . '/../../abstract.php';
class Meanbee_Configpoweredcss_Regenerate extends Mage_Shell_Abstract
{
/**
* Run script
*
*/
public function run()
{
/**
* Shell script regenerate the configpowered css for all stores
*/
try {
/** @var Meanbee_ConfigPoweredCss_Model_Css $css */
$css = Mage::getModel('meanbee_configpoweredcss/css');
$stores = Mage::app()->getStores();
foreach ($stores as $storeId => $store) {
try {
Mage::app()->setCurrentStore($storeId);
$css->publish($storeId);
} catch (Exception $e) {
fwrite(STDERR, sprintf('There was an error when regenerating the config powered css: %s',
$e->getTraceAsString()));
exit(1);
}
}
fwrite(STDOUT,
"Config powered css has been regenerated successfully.\n");
exit(0);
} catch (Exception $e) {
fwrite(STDERR,
sprintf('There was an error when regenerating the config powered css: %s', $e->getTraceAsString()));
exit(1);
}
}
}
$shell = new Meanbee_Configpoweredcss_Regenerate();
$shell->run(); | <?php
require_once __DIR__ . '/../../abstract.php';
class Meanbee_Configpoweredcss_Regenerate extends Mage_Shell_Abstract
{
/**
* Run script
*
*/
public function run()
{
/**
* Shell script regenerate the configpowered css for all stores
*/
try {
/** @var Meanbee_ConfigPoweredCss_Model_Css $css */
$css = Mage::getModel('meanbee_configpoweredcss/css');
$stores = Mage::app()->getStores();
foreach ($stores as $storeId => $store) {
try {
Mage::app()->setCurrentStore($storeId);
$css->publish($storeId);
} catch (Exception $e) {
Mage::logException($e);
return;
}
}
fwrite(STDERR,
"Config powered css has been regenerated successfully.\n");
exit(0);
} catch (Exception $e) {
Mage::logException($e);
fwrite(STDERR,
"There was an error when regenerating the config powered css, it has been logged.\n");
exit(1);
}
}
}
$shell = new Meanbee_Configpoweredcss_Regenerate();
$shell->run(); |
Print actual error, not [object Object] | const pageConfig = require('../config');
const fs = require('fs');
module.exports = {
// Switch to welder-web iframe if welder-web is integrated with Cockpit.
// Cockpit web service is listening on TCP port 9090.
gotoURL: (nightmare, page) => {
if (pageConfig.root.includes('9090')) {
nightmare
.goto(page.url)
.wait(page.iframeLoadingTime)
.enterIFrame(page.iframeSelector);
} else {
nightmare
.goto(page.url);
}
},
gotoError: (error, nightmare, testSpec) => {
console.error(`Failed on case ${testSpec.result.fullName} - ${error.toString()} - ${JSON.stringify(error)}`);
const dtStr = new Date().toISOString()
.replace(/T/, '-')
.replace(/:/g, '-')
.replace(/\..+/, '');
const imageDir = '/tmp/failed-image/';
if (!fs.existsSync(imageDir)) fs.mkdirSync(imageDir);
nightmare
.screenshot(`${imageDir}${testSpec.result.fullName.replace(/ /g, '-')}.${dtStr}.fail.png`)
.end()
.then(
() => console.error(`Screenshot Saved at ${imageDir}${testSpec.result.fullName.replace(/ /g, '-')}.${dtStr}.fail.png`),
);
},
};
| const pageConfig = require('../config');
const fs = require('fs');
module.exports = {
// Switch to welder-web iframe if welder-web is integrated with Cockpit.
// Cockpit web service is listening on TCP port 9090.
gotoURL: (nightmare, page) => {
if (pageConfig.root.includes('9090')) {
nightmare
.goto(page.url)
.wait(page.iframeLoadingTime)
.enterIFrame(page.iframeSelector);
} else {
nightmare
.goto(page.url);
}
},
gotoError: (error, nightmare, testSpec) => {
console.error(`Failed on case ${testSpec.result.fullName} - ${error}`);
const dtStr = new Date().toISOString()
.replace(/T/, '-')
.replace(/:/g, '-')
.replace(/\..+/, '');
const imageDir = '/tmp/failed-image/';
if (!fs.existsSync(imageDir)) fs.mkdirSync(imageDir);
nightmare
.screenshot(`${imageDir}${testSpec.result.fullName.replace(/ /g, '-')}.${dtStr}.fail.png`)
.end()
.then(
() => console.error(`Screenshot Saved at ${imageDir}${testSpec.result.fullName.replace(/ /g, '-')}.${dtStr}.fail.png`),
);
},
};
|
Create mapCategories on ndcs reducer | export const initialState = {
loading: false,
loaded: false,
error: false,
data: {}
};
const setLoading = (state, loading) => ({ ...state, loading });
const setError = (state, error) => ({ ...state, error });
const setLoaded = (state, loaded) => ({ ...state, loaded });
export default {
fetchNDCSInit: state => setLoading(state, true),
fetchNDCSReady: (state, { payload }) =>
setLoaded(
setLoading(
{
...state,
data: {
categories: payload.categories,
mapCategories: state.data.mapCategories || {},
sectors: payload.sectors,
mapIndicators: state.data.mapIndicators || [],
indicators: payload.indicators
}
},
false
),
true
),
fetchNDCSMapIndicatorsReady: (state, { payload }) =>
setLoaded(
setLoading(
{
...state,
data: {
categories: state.data.categories || {},
mapCategories: payload.categories,
sectors: payload.sectors,
indicators: state.data.indicators || [],
mapIndicators: payload.indicators
}
},
false
),
true
),
fetchNDCSFail: state => setError(state, true)
};
| export const initialState = {
loading: false,
loaded: false,
error: false,
data: {}
};
const setLoading = (state, loading) => ({ ...state, loading });
const setError = (state, error) => ({ ...state, error });
const setLoaded = (state, loaded) => ({ ...state, loaded });
export default {
fetchNDCSInit: state => setLoading(state, true),
fetchNDCSReady: (state, { payload }) =>
setLoaded(
setLoading(
{
...state,
data: {
categories: payload.categories,
sectors: payload.sectors,
mapIndicators: state.data.mapIndicators || [],
indicators: payload.indicators
}
},
false
),
true
),
fetchNDCSMapIndicatorsReady: (state, { payload }) =>
setLoaded(
setLoading(
{
...state,
data: {
categories: payload.categories,
sectors: payload.sectors,
indicators: state.data.indicators || [],
mapIndicators: payload.indicators
}
},
false
),
true
),
fetchNDCSFail: state => setError(state, true)
};
|
Hide mobile (also hidden in styles.css) when css is not loaded | import config from "config";
import ReactDOMServer from "react-dom/server";
import serialize from "serialize-javascript";
import "cookie-parser";
import Helmet from "react-helmet";
export default function renderPage(element, fetcher, userAgent) {
const elementRendered = ReactDOMServer.renderToString(element);
const helmet = Helmet.renderStatic();
let link = "";
if (config.get("html.style")) {
link = helmet.link.toString();
}
global.navigator = { userAgent };
return `
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="manifest" href="/manifest.json" />
<link rel="icon" sizes="192x192" href="/img/logo.blue.transparent.192.png" />
<link rel="apple-touch-icon" href="/img/logo.blue.white.192.png">
<meta name="theme-color" content="#1a237e" />
${helmet.title.toString()}
${helmet.meta.toString()}
${link}
<style type="text/css">
.flex-menu-mobile {
display: none;
}
</style>
</head>
<body>
<div id="app">${elementRendered}</div>
<script>
window.__INITIAL_STATE__ = ${serialize(fetcher, { isJSON: true })};
</script>
<script src="/javascript.js"></script>
</body>
</html>
`;
}
| import config from "config";
import ReactDOMServer from "react-dom/server";
import serialize from "serialize-javascript";
import "cookie-parser";
import Helmet from "react-helmet";
export default function renderPage(element, fetcher, userAgent) {
const elementRendered = ReactDOMServer.renderToString(element);
const helmet = Helmet.renderStatic();
let link = "";
if (config.get("html.style")) {
link = helmet.link.toString();
}
global.navigator = { userAgent };
return `
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="manifest" href="/manifest.json" />
<link rel="icon" sizes="192x192" href="/img/logo.blue.transparent.192.png" />
<link rel="apple-touch-icon" href="/img/logo.blue.white.192.png">
<meta name="theme-color" content="#1a237e" />
${helmet.title.toString()}
${helmet.meta.toString()}
${link}
</head>
<body>
<div id="app">${elementRendered}</div>
<script>
window.__INITIAL_STATE__ = ${serialize(fetcher, { isJSON: true })};
</script>
<script src="/javascript.js"></script>
</body>
</html>
`;
}
|
Work around Node <v6 bug where shorthand props named `get` do not parse | import got from 'got'
import createDebug from 'debug'
const debug = createDebug('miniplug:http')
export default function httpPlugin (httpOpts) {
httpOpts = {
backoff: (fn) => fn,
...httpOpts
}
return (mp) => {
const request = httpOpts.backoff(
// wait until connections are complete before sending off requests
(url, opts) => mp.connected
.tap(() => debug(opts.method, url, opts.body || opts.query))
.then((session) =>
got(`${httpOpts.host}/_/${url}`, {
headers: {
cookie: session.cookie,
'content-type': 'application/json'
},
json: true,
...opts,
body: opts.body ? JSON.stringify(opts.body) : undefined
})
)
.then((resp) => {
if (resp.body.status !== 'ok') {
throw new Error(resp.body.data.length ? resp.body.data[0] : resp.body.status)
}
return resp.body.data
})
)
const post = (url, data) => request(url, { method: 'post', body: data })
const get = (url, data) => request(url, { method: 'get', query: data })
const put = (url, data) => request(url, { method: 'put', body: data })
const del = (url, data) => request(url, { method: 'delete', body: data })
mp.request = request
mp.post = post
mp.get = get
mp.put = put
mp.del = del
}
}
| import got from 'got'
import createDebug from 'debug'
const debug = createDebug('miniplug:http')
export default function httpPlugin (httpOpts) {
httpOpts = {
backoff: (fn) => fn,
...httpOpts
}
return (mp) => {
const request = httpOpts.backoff(
// wait until connections are complete before sending off requests
(url, opts) => mp.connected
.tap(() => debug(opts.method, url, opts.body || opts.query))
.then((session) =>
got(`${httpOpts.host}/_/${url}`, {
headers: {
cookie: session.cookie,
'content-type': 'application/json'
},
json: true,
...opts,
body: opts.body ? JSON.stringify(opts.body) : undefined
})
)
.then((resp) => {
if (resp.body.status !== 'ok') {
throw new Error(resp.body.data.length ? resp.body.data[0] : resp.body.status)
}
return resp.body.data
})
)
const post = (url, data) => request(url, { method: 'post', body: data })
const get = (url, data) => request(url, { method: 'get', query: data })
const put = (url, data) => request(url, { method: 'put', body: data })
const del = (url, data) => request(url, { method: 'delete', body: data })
Object.assign(mp, {
request,
post,
get,
put,
del
})
}
}
|
chore: Fix grunt-bump config to include the changelog. | module.exports = function (grunt) {
grunt.initConfig({
pkgFile: 'package.json',
simplemocha: {
options: {
ui: 'bdd',
reporter: 'dot'
},
unit: {
src: [
'test/mocha-globals.coffee',
'test/*.spec.coffee'
]
}
},
'npm-contributors': {
options: {
commitMessage: 'chore: update contributors'
}
},
bump: {
options: {
commitMessage: 'chore: release v%VERSION%',
pushTo: 'upstream',
commitFiles: [
'package.json',
'CHANGELOG.md'
]
}
},
eslint: {
target: [
'lib/*.js',
'gruntfile.js',
'karma.conf.js'
]
}
})
require('load-grunt-tasks')(grunt)
grunt.registerTask('test', ['simplemocha'])
grunt.registerTask('default', ['eslint', 'test'])
grunt.registerTask('release', 'Bump the version and publish to NPM.', function (type) {
grunt.task.run([
'npm-contributors',
'bump-only:' + (type || 'patch'),
'changelog',
'bump-commit',
'npm-publish'
])
})
}
| module.exports = function (grunt) {
grunt.initConfig({
pkgFile: 'package.json',
simplemocha: {
options: {
ui: 'bdd',
reporter: 'dot'
},
unit: {
src: [
'test/mocha-globals.coffee',
'test/*.spec.coffee'
]
}
},
'npm-contributors': {
options: {
commitMessage: 'chore: update contributors'
}
},
bump: {
options: {
commitMessage: 'chore: release v%VERSION%',
pushTo: 'upstream'
}
},
eslint: {
target: [
'lib/*.js',
'gruntfile.js',
'karma.conf.js'
]
}
})
require('load-grunt-tasks')(grunt)
grunt.registerTask('test', ['simplemocha'])
grunt.registerTask('default', ['eslint', 'test'])
grunt.registerTask('release', 'Bump the version and publish to NPM.', function (type) {
grunt.task.run([
'npm-contributors',
'bump-only:' + (type || 'patch'),
'changelog',
'bump-commit',
'npm-publish'
])
})
}
|
Update default formatting for bar chart module | define([
'extensions/controllers/module',
'common/views/visualisations/bar_chart_with_number',
'common/collections/bar_chart_with_number'
],
function (ModuleController, BarChartWithNumberView, BarChartWithNumberCollection) {
var BarChartWithNumberModule = ModuleController.extend({
visualisationClass: BarChartWithNumberView,
collectionClass: BarChartWithNumberCollection,
clientRenderOnInit: true,
requiresSvg: true,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute');
var options = {
queryParams: this.model.get('query-params'),
valueAttr: valueAttr,
axisPeriod: this.model.get('axis-period')
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'dateRange'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return _.defaults(ModuleController.prototype.visualisationOptions.apply(this, arguments), {
valueAttr: 'uniqueEvents',
formatOptions: this.model.get('format')
});
}
});
return BarChartWithNumberModule;
});
| define([
'extensions/controllers/module',
'common/views/visualisations/bar_chart_with_number',
'common/collections/bar_chart_with_number'
],
function (ModuleController, BarChartWithNumberView, BarChartWithNumberCollection) {
var BarChartWithNumberModule = ModuleController.extend({
visualisationClass: BarChartWithNumberView,
collectionClass: BarChartWithNumberCollection,
clientRenderOnInit: true,
requiresSvg: true,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute');
var options = {
queryParams: this.model.get('query-params'),
valueAttr: valueAttr,
axisPeriod: this.model.get('axis-period')
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3 };
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'dateRange'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return _.defaults(ModuleController.prototype.visualisationOptions.apply(this, arguments), {
valueAttr: 'uniqueEvents',
formatOptions: this.model.get('format')
});
}
});
return BarChartWithNumberModule;
});
|
Update web client swagger test for swagger-ui 2.1.4 | function jasmineTests() {
var jasmineEnv = jasmine.getEnv();
var consoleReporter = new jasmine.ConsoleReporter();
window.jasmine_phantom_reporter = consoleReporter;
jasmineEnv.addReporter(consoleReporter);
function waitAndExecute() {
if (!jasmineEnv.currentRunner().suites_.length) {
window.setTimeout(waitAndExecute, 10);
return;
}
jasmineEnv.execute();
}
waitAndExecute();
describe('Test the swagger pages', function () {
it('Test swagger', function () {
waitsFor(function () {
return $('li#resource_system.resource').length > 0;
}, 'swagger docs to appear');
runs(function () {
$('li#resource_system.resource .heading h2 a').click();
});
waitsFor(function () {
return $('#system_system_getVersion:visible').length > 0;
}, 'end points to be visible');
runs(function () {
$('#system_system_getVersion h3 a').click();
});
waitsFor(function () {
return $('#system_system_getVersion .sandbox_header input.submit:visible').length > 0;
}, 'version try out button to be visible');
runs(function () {
$('#system_system_getVersion .sandbox_header input.submit').click();
});
waitsFor(function () {
return $('#system_system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0;
}, 'version information was returned');
});
});
}
$(function () {
$.getScript('/static/built/testing-no-cover.min.js', jasmineTests);
});
| function jasmineTests() {
var jasmineEnv = jasmine.getEnv();
var consoleReporter = new jasmine.ConsoleReporter();
window.jasmine_phantom_reporter = consoleReporter;
jasmineEnv.addReporter(consoleReporter);
function waitAndExecute() {
if (!jasmineEnv.currentRunner().suites_.length) {
window.setTimeout(waitAndExecute, 10);
return;
}
jasmineEnv.execute();
}
waitAndExecute();
describe('Test the swagger pages', function () {
it('Test swagger', function () {
waitsFor(function () {
return $('li#resource_system.resource').length > 0;
}, 'swagger docs to appear');
runs(function () {
$('li#resource_system.resource .heading h2 a').click();
});
waitsFor(function () {
return $('#system_getVersion:visible').length > 0;
}, 'end points to be visible');
runs(function () {
$('#system_getVersion h3 a').click();
});
waitsFor(function () {
return $('#system_getVersion .sandbox_header input.submit[name="commit"]:visible').length > 0;
}, 'version try out button to be visible');
runs(function () {
$('#system_getVersion .sandbox_header input.submit[name="commit"]').click();
});
waitsFor(function () {
return $('#system_getVersion .response_body.json').text().indexOf('apiVersion') >= 0;
}, 'version information was returned');
});
});
}
$(function () {
$.getScript('/static/built/testing-no-cover.min.js', jasmineTests);
});
|
Fix scrollbar showing. Auto-calculate the pixels inside calc().
The scrollbar fix is actually just line 21 | import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import '../styles/video.css'
class Tutorial extends Component {
constructor (props) {
super(props)
this.state = {
topCoord: null
}
}
componentDidMount () {
const thisElement = ReactDOM.findDOMNode(this)
const top = thisElement.getBoundingClientRect().top
this.setState({ topCoord: top })
}
render () {
return (
<div className='container'>
<div className='row' style={{ marginBottom: 0 }}>
{/* Guess 64px the first render, then immediately adjust
to a proper calculated value.
This prevents the layout from breaking should the AppBar
ever change to anything other than 64px. */}
<div
className='col s12 valign-wrapper'
style={{
minHeight: `calc(100vh - ${this.state.topCoord || '64'}px)`
}}
>
<div style={{ width: '100%' }}>
<div className='video-container z-depth-1'>
<iframe
src='https://www.youtube.com/embed/WQt0GDsL8ZU?rel=0'
width='853'
height='480'
frameBorder='0'
allowFullScreen='allowfullscreen'
title='tutorial-video'
/>
</div>
<p style={{ marginTop: '20px' }}>
If you have any problems using the MarCom Resource Center,
please contact Jesse Weigel at{' '}
<a href='mailto:[email protected]'>
[email protected]
</a>{' '}
or <a href='tel:17402845305'> 740-284-5305</a>.
</p>
</div>
</div>
</div>
</div>
)
}
}
export default Tutorial
| import React from 'react'
import '../styles/video.css'
const Tutorial = props =>
<div className='container'>
<div className='row' style={{ marginBottom: 0 }}>
<div
className='col s12 valign-wrapper'
style={{ minHeight: 'calc(100vh - 64px)' }}
>
<div style={{ width: '100%' }}>
<div className='video-container z-depth-1'>
<iframe
src='https://www.youtube.com/embed/WQt0GDsL8ZU?rel=0'
width='853'
height='480'
frameBorder='0'
allowFullScreen='allowfullscreen'
title='tutorial-video'
/>
</div>
<p style={{ marginTop: '20px' }}>
If you have any problems using the MarCom Resource Center, please
contact Jesse Weigel at{' '}
<a href='mailto:[email protected]'>
[email protected]
</a>{' '}
or <a href='tel:17402845305'> 740-284-5305</a>.
</p>
</div>
</div>
</div>
</div>
export default Tutorial
|
Make ball light blink at 10Hz instead of 5Hz when a ball is at top | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.commands;
import edu.wpi.first.wpilibj.Timer;
/**
*
* @author admin
*/
public class BallLightUpdate extends CommandBase {
private int BLINK_FREQUENCY_HZ = 10;
private double lastTime = 0;
public BallLightUpdate() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(ballLight);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
double time = Timer.getFPGATimestamp();
if (conveyor.ballAtTop()) {
if (time - lastTime > (1.0 / BLINK_FREQUENCY_HZ)) {
ballLight.setLight(!ballLight.isOn()); // Invert ball light every 1/frequency (period) seconds
lastTime = time;
}
}
else if (conveyor.ballAtBottom()) {
ballLight.setLight(true);
}
else {
ballLight.setLight(false);
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.commands;
import edu.wpi.first.wpilibj.Timer;
/**
*
* @author admin
*/
public class BallLightUpdate extends CommandBase {
private int BLINK_FREQUENCY_HZ = 5;
private double lastTime = 0;
public BallLightUpdate() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(ballLight);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
double time = Timer.getFPGATimestamp();
if (conveyor.ballAtTop()) {
if (time - lastTime > (1.0 / BLINK_FREQUENCY_HZ)) {
ballLight.setLight(!ballLight.isOn()); // Invert ball light every 1/frequency (period) seconds
lastTime = time;
}
}
else if (conveyor.ballAtBottom()) {
ballLight.setLight(true);
}
else {
ballLight.setLight(false);
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
Add a accesor for size | <?php
namespace Datenknoten\LigiBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @Gedmo\Uploadable(pathMethod="getDefaultPath", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
*/
class File
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\Column(name="path", type="string")
* @Gedmo\UploadableFilePath
*/
private $path;
/**
* @ORM\Column(name="name", type="string")
* @Gedmo\UploadableFileName
*/
private $name;
/**
* @ORM\Column(name="mime_type", type="string")
* @Gedmo\UploadableFileMimeType
*/
private $mimeType;
/**
* @ORM\Column(name="size", type="decimal")
* @Gedmo\UploadableFileSize
*/
private $size;
public function getDefaultPath()
{
return realpath(__DIR__ . '/../../../../media');
}
public function getId()
{
return $this->id;
}
public function getPath()
{
return $this->path;
}
public function getName()
{
return $this->name;
}
public function getMimeType()
{
return $this->mimeType;
}
public function getSize()
{
return $this->size;
}
} | <?php
namespace Datenknoten\LigiBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @Gedmo\Uploadable(pathMethod="getDefaultPath", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
*/
class File
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORM\Column(name="path", type="string")
* @Gedmo\UploadableFilePath
*/
private $path;
/**
* @ORM\Column(name="name", type="string")
* @Gedmo\UploadableFileName
*/
private $name;
/**
* @ORM\Column(name="mime_type", type="string")
* @Gedmo\UploadableFileMimeType
*/
private $mimeType;
/**
* @ORM\Column(name="size", type="decimal")
* @Gedmo\UploadableFileSize
*/
private $size;
public function getDefaultPath()
{
return realpath(__DIR__ . '/../../../../media');
}
public function getId()
{
return $this->id;
}
public function getPath()
{
return $this->path;
}
public function getName()
{
return $this->name;
}
public function getMimeType()
{
return $this->mimeType;
}
} |
Make result object local to function | var serviceName = "facebook";
var request = require("request");
var serviceConfig = require("./../config/services.config.json");
function facebook (cb) {
var result = {
service: serviceName,
status: false
};
request({
url: serviceConfig[serviceName],
method: "GET",
headers: {
"User-Agent": 'request'
}
}, function(error, response, body) {
if(error) {
result["message"] = "Problem with the connection.";
result["data"] = error;
return cb(result);
}
if(body) {
try {
body = JSON.parse(body);
} catch (e) {
result["message"] = "Could not parse the response.";
return cb(result);
}
if(body.current.health != 1) {
result["message"] = body.current.subject;
return cb(result);
}
result["status"] = true;
result["message"] = body.current.subject;
return cb(result);
}
result["message"] = "Empty response. Try Again.";
return cb(result);
});
}
module.exports = facebook;
| var serviceName = "facebook";
var request = require("request");
var serviceConfig = require("./../config/services.config.json");
var result = {
service: serviceName,
status: false
}
function facebook (cb) {
request({
url: serviceConfig[serviceName],
method: "GET",
headers: {
"User-Agent": 'request'
}
}, function(error, response, body) {
if(error) {
result["message"] = "Problem with the connection.";
result["data"] = error;
return cb(result);
}
if(body) {
try {
body = JSON.parse(body);
} catch (e) {
result["message"] = "Could not parse the response.";
return cb(result);
}
if(body.current.health != 1) {
result["status"] = false;
result["message"] = body.current.subject;
return cb(result);
}
result["status"] = true;
result["message"] = body.current.subject;
return cb(result);
}
result["message"] = "Empty response. Try Again.";
return cb(result);
});
}
module.exports = facebook;
|
Add an interface to update global context | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Template"""
import peanut
import jinja2
from os import path
from jinja2 import FileSystemLoader
from jinja2.exceptions import TemplateNotFound
class SmartLoader(FileSystemLoader):
"""A smart template loader"""
available_extension = ['.html', '.xml']
def get_source(self, environment, template):
if template is None:
raise TemplateNotFound(template)
if '.' in template:
return super(SmartLoader, self).get_source(environment, template)
for extension in SmartLoader.available_extension:
try:
filename = template + extension
return super(SmartLoader, self).get_source(environment, filename)
except TemplateNotFound:
pass
raise TemplateNotFound(template)
class Template(object):
"""Template"""
def __init__(self, path, filters=None, **kwargs):
loader = SmartLoader(path)
self.env = jinja2.Environment(
loader=loader,
)
# Update filters
if isinstance(filters, dict):
self.env.filters.update(filters)
# Update global namesapce
self.env.globals.update(kwargs)
def update_context(self, **kwargs):
"""Update global context
"""
self.env.globals.update(kwargs)
def render(self, name, **context):
"""Render template with name and context"""
template = self.env.get_template(name)
return template.render(**context)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Template"""
import peanut
import jinja2
from os import path
from jinja2 import FileSystemLoader
from jinja2.exceptions import TemplateNotFound
class SmartLoader(FileSystemLoader):
"""A smart template loader"""
available_extension = ['.html', '.xml']
def get_source(self, environment, template):
if template is None:
raise TemplateNotFound(template)
if '.' in template:
return super(SmartLoader, self).get_source(environment, template)
for extension in SmartLoader.available_extension:
try:
filename = template + extension
return super(SmartLoader, self).get_source(environment, filename)
except TemplateNotFound:
pass
raise TemplateNotFound(template)
class Template(object):
"""Template"""
def __init__(self, path, filters=None, **kwargs):
loader = SmartLoader(path)
self.env = jinja2.Environment(
loader=loader,
)
# Update filters
if isinstance(filters, dict):
self.env.filters.update(filters)
# Update global namesapce
self.env.globals.update(kwargs)
def render(self, name, **context):
"""Render template with name and context"""
template = self.env.get_template(name)
return template.render(**context)
|
Fix error PHP <= 5.6 | <?php
namespace PDOSimpleMigration\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class MigrationMigrateCommand extends AbstractCommand
{
protected function configure()
{
$this
->setName('migrate')
->setDescription('Upgrade to latest migration class')
;
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->loadConfig($input, $output);
$availables = $this->getAvailables();
$executeds = $this->getExecuteds();
$diff = array_diff($availables, $executeds);
foreach ($diff as $version) {
$executor = new MigrationExecuteCommand();
$executor->executeUp($version, $input, $output);
$stmt = $this->pdo->prepare(
'INSERT INTO '
. $this->tableName
. ' SET version = :version, description = :description'
);
$migrationClass = $this->loadMigrationClass($version);
$stmt->bindParam('version', $version);
$stmt->bindParam('description', $migrationClass::$description);
$stmt->execute();
}
$output->writeln('<info>Everything updated</info>');
}
}
| <?php
namespace PDOSimpleMigration\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class MigrationMigrateCommand extends AbstractCommand
{
protected function configure()
{
$this
->setName('migrate')
->setDescription('Upgrade to latest migration class')
;
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->loadConfig($input, $output);
$availables = $this->getAvailables();
$executeds = $this->getExecuteds();
$diff = array_diff($availables, $executeds);
foreach ($diff as $version) {
$executor = new MigrationExecuteCommand();
$executor->executeUp($version, $input, $output);
$stmt = $this->pdo->prepare(
'INSERT INTO '
. $this->tableName
. ' SET version = :version, description = :description'
);
$stmt->bindParam('version', $version);
$stmt->bindParam('description', $this->loadMigrationClass($version)::$description);
$stmt->execute();
}
$output->writeln('<info>Everything updated</info>');
}
}
|
Remove version limit on sphinx | import setuptools
import versioneer
if __name__ == "__main__":
setuptools.setup(
name='basis_set_exchange',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='The Quantum Chemistry Basis Set Exchange',
author='The Molecular Sciences Software Institute',
author_email='[email protected]',
url="https://github.com/MolSSI/basis_set_exchange",
license='BSD-3C',
packages=setuptools.find_packages(),
install_requires=[
'jsonschema',
],
extras_require={
'docs': [
'sphinx',
'sphinxcontrib-napoleon',
'sphinx_rtd_theme',
'numpydoc',
],
'tests': [
'pytest',
'pytest-cov'
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'Programming Language :: Python :: 3',
],
zip_safe=True,
)
| import setuptools
import versioneer
if __name__ == "__main__":
setuptools.setup(
name='basis_set_exchange',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='The Quantum Chemistry Basis Set Exchange',
author='The Molecular Sciences Software Institute',
author_email='[email protected]',
url="https://github.com/MolSSI/basis_set_exchange",
license='BSD-3C',
packages=setuptools.find_packages(),
install_requires=[
'jsonschema',
],
extras_require={
'docs': [
'sphinx==1.2.3', # autodoc was broken in 1.3.1
'sphinxcontrib-napoleon',
'sphinx_rtd_theme',
'numpydoc',
],
'tests': [
'pytest',
'pytest-cov'
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
'Programming Language :: Python :: 3',
],
zip_safe=True,
)
|
Fix roles relation of Permission | <?php namespace Klaravel\Ntrust\Traits;
use Illuminate\Cache\TaggableStore;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cache;
trait NtrustPermissionTrait
{
/**
* Many-to-Many relations with role model.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function roles()
{
return $this->belongsToMany(Config::get('ntrust.profiles.' . self::$roleProfile . '.role'),
Config::get('ntrust.profiles.' . self::$roleProfile . '.permission_role_table'),
Config::get('ntrust.profiles.' . self::$roleProfile . '.permission_foreign_key'),
Config::get('ntrust.profiles.' . self::$roleProfile . '.role_foreign_key')
);
}
/**
* Trait boot method
*
* @return void
*/
protected static function bootNtrustPermissionTrait()
{
/**
* Attach event listener to remove the many-to-many records when trying to delete
* Will NOT delete any records if the permission model uses soft deletes.
*/
static::deleted(function($permission)
{
if(Cache::getStore() instanceof TaggableStore) {
Cache::tags(Config::get('ntrust.profiles.' . self::$roleProfile . '.permission'))
->flush();
$permission->roles()->sync([]);
}
});
}
}
| <?php namespace Klaravel\Ntrust\Traits;
use Illuminate\Cache\TaggableStore;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cache;
trait NtrustPermissionTrait
{
/**
* Many-to-Many relations with role model.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function roles()
{
return $this->belongsToMany(Config::get('ntrust.profiles.' . self::$roleProfile . '.role'),
Config::get('ntrust.profiles.' . self::$roleProfile . '.permission_role_table'),
Config::get('ntrust.profiles.' . self::$roleProfile . '.role_foreign_key'),
Config::get('ntrust.profiles.' . self::$roleProfile . '.permission_foreign_key')
);
}
/**
* Trait boot method
*
* @return void
*/
protected static function bootNtrustPermissionTrait()
{
/**
* Attach event listener to remove the many-to-many records when trying to delete
* Will NOT delete any records if the permission model uses soft deletes.
*/
static::deleted(function($permission)
{
if(Cache::getStore() instanceof TaggableStore) {
Cache::tags(Config::get('ntrust.profiles.' . self::$roleProfile . '.permission'))
->flush();
$permission->roles()->sync([]);
}
});
}
}
|
Set the baseURL for development | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'hash',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
contentSecurityPolicy: {
"script-src": "'self' 'unsafe-inline'",
"font-src": "'self'",
"style-src": "'self' 'unsafe-inline'",
"img-src": "'self' data:"
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
ENV.baseURL = '';
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.baseURL = '/gloit-component';
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'hash',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
contentSecurityPolicy: {
"script-src": "'self' 'unsafe-inline'",
"font-src": "'self'",
"style-src": "'self' 'unsafe-inline'",
"img-src": "'self' data:"
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.baseURL = '/gloit-component';
}
return ENV;
};
|
Fix translation_replace for translations dryrun | package com.crowdin.cli.commands.functionality;
import com.crowdin.cli.properties.PropertiesBean;
import com.crowdin.cli.utils.CommandUtils;
import com.crowdin.cli.utils.PlaceholderUtil;
import com.crowdin.cli.utils.Utils;
import org.apache.commons.lang3.StringUtils;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class DryrunTranslations extends Dryrun {
private PropertiesBean pb;
private PlaceholderUtil placeholderUtil;
public DryrunTranslations(PropertiesBean pb, PlaceholderUtil placeholderUtil) {
this.pb = pb;
this.placeholderUtil = placeholderUtil;
}
@Override
protected List<String> getFiles() {
return pb.getFiles()
.stream()
.flatMap(file -> CommandUtils.getFileSourcesWithoutIgnores(file, pb.getBasePath(), placeholderUtil)
.stream()
.map(source -> placeholderUtil.replaceFileDependentPlaceholders(file.getTranslation(), source))
.flatMap(translation -> ((file.getLanguagesMapping() != null)
? placeholderUtil.replaceLanguageDependentPlaceholders(translation, file.getLanguagesMapping())
: placeholderUtil.replaceLanguageDependentPlaceholders(translation)).stream())
.map(translation -> (file.getTranslationReplace() != null ? file.getTranslationReplace() : Collections.<String, String>emptyMap())
.keySet()
.stream()
.reduce(translation, (trans, k) -> StringUtils.replace(
trans,
k.replaceAll("[\\\\/]+", Utils.PATH_SEPARATOR_REGEX),
file.getTranslationReplace().get(k)))
)
)
.map(source -> StringUtils.removeStart(source, pb.getBasePath()))
.collect(Collectors.toList());
}
}
| package com.crowdin.cli.commands.functionality;
import com.crowdin.cli.properties.PropertiesBean;
import com.crowdin.cli.utils.CommandUtils;
import com.crowdin.cli.utils.PlaceholderUtil;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
public class DryrunTranslations extends Dryrun {
private PropertiesBean pb;
private PlaceholderUtil placeholderUtil;
public DryrunTranslations(PropertiesBean pb, PlaceholderUtil placeholderUtil) {
this.pb = pb;
this.placeholderUtil = placeholderUtil;
}
@Override
protected List<String> getFiles() {
return pb.getFiles()
.stream()
.flatMap(file -> CommandUtils.getFileSourcesWithoutIgnores(file, pb.getBasePath(), placeholderUtil)
.stream()
.map(source -> placeholderUtil.replaceFileDependentPlaceholders(file.getTranslation(), source))
.flatMap(translation -> ((file.getLanguagesMapping() != null)
? placeholderUtil.replaceLanguageDependentPlaceholders(translation, file.getLanguagesMapping())
: placeholderUtil.replaceLanguageDependentPlaceholders(translation)).stream()))
.map(source -> StringUtils.removeStart(source, pb.getBasePath()))
.collect(Collectors.toList());
}
}
|
COM-212: Add a grid to popup
- added possibility to render number cell as an editable field | define([
'underscore',
'backgrid',
'orodatagrid/js/datagrid/formatter/number-formatter'
], function(_, Backgrid, NumberFormatter) {
'use strict';
var NumberCell;
/**
* Number column cell.
*
* @export oro/datagrid/cell/number-cell
* @class oro.datagrid.cell.NumberCell
* @extends Backgrid.NumberCell
*/
NumberCell = Backgrid.NumberCell.extend({
/** @property {orodatagrid.datagrid.formatter.NumberFormatter} */
formatterPrototype: NumberFormatter,
/** @property {String} */
style: 'decimal',
/**
* @inheritDoc
*/
initialize: function(options) {
_.extend(this, options);
NumberCell.__super__.initialize.apply(this, arguments);
this.formatter = this.createFormatter();
},
/**
* Creates number cell formatter
*
* @return {orodatagrid.datagrid.formatter.NumberFormatter}
*/
createFormatter: function() {
return new this.formatterPrototype({style: this.style});
},
/**
* @inheritDoc
*/
render: function() {
var render = NumberCell.__super__.render.apply(this, arguments);
this.enterEditMode();
return render;
},
/**
* @inheritDoc
*/
enterEditMode: function() {
if (this.column.get('editable')) {
NumberCell.__super__.enterEditMode.apply(this, arguments);
}
},
/**
* @inheritDoc
*/
exitEditMode: function() {
if (!this.column.get('editable')) {
NumberCell.__super__.exitEditMode.apply(this, arguments);
}
}
});
return NumberCell;
});
| define([
'underscore',
'backgrid',
'orodatagrid/js/datagrid/formatter/number-formatter'
], function(_, Backgrid, NumberFormatter) {
'use strict';
var NumberCell;
/**
* Number column cell.
*
* @export oro/datagrid/cell/number-cell
* @class oro.datagrid.cell.NumberCell
* @extends Backgrid.NumberCell
*/
NumberCell = Backgrid.NumberCell.extend({
/** @property {orodatagrid.datagrid.formatter.NumberFormatter} */
formatterPrototype: NumberFormatter,
/** @property {String} */
style: 'decimal',
/**
* @inheritDoc
*/
initialize: function(options) {
_.extend(this, options);
NumberCell.__super__.initialize.apply(this, arguments);
this.formatter = this.createFormatter();
},
/**
* Creates number cell formatter
*
* @return {orodatagrid.datagrid.formatter.NumberFormatter}
*/
createFormatter: function() {
return new this.formatterPrototype({style: this.style});
}
});
return NumberCell;
});
|
Update the task according to Autoprefixer API changes | /*
* grunt-autoprefixer
*
*
* Copyright (c) 2013 Dmitry Nikitenko
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
var autoprefixer = require('autoprefixer');
grunt.registerMultiTask('autoprefixer', 'Parse CSS and add prefixed properties and values by Can I Use database for actual browsers.', function () {
var options = this.options(),
compiler = autoprefixer(options.browsers);
// Iterate over all specified file groups.
this.files.forEach(function (f) {
// Concat specified files.
var src = f.src.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function (filepath) {
// Read file source.
return grunt.file.read(filepath);
}
).join('');
// Write the destination file.
grunt.file.write(f.dest, compiler.compile(src));
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
| /*
* grunt-autoprefixer
*
*
* Copyright (c) 2013 Dmitry Nikitenko
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
var autoprefixer = require('autoprefixer');
grunt.registerMultiTask('autoprefixer', 'Parse CSS and add prefixed properties and values by Can I Use database for actual browsers.', function () {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options();
// Iterate over all specified file groups.
this.files.forEach(function (f) {
// Concat specified files.
var src = f.src.filter(function (filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function (filepath) {
// Read file source.
return grunt.file.read(filepath);
}
).join('');
// Write the destination file.
grunt.file.write(f.dest, autoprefixer.compile(src, options.browsers));
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
|
Remove code which should never have made it in | """
This module implements python classes which inherit from
and extend the functionality of the ROOT canvas classes.
"""
import ROOT
from ..core import Object
from .. import rootpy_globals as _globals
from .. import defaults, QROOT
class _PadBase(Object):
def _post_init(self):
self.members = []
_globals.pad = self
def Clear(self, *args, **kwargs):
self.members = []
self.ROOT_base.Clear(self, *args, **kwargs)
def OwnMembers(self):
for thing in self.GetListOfPrimitives():
if thing not in self.members:
self.members.append(thing)
def cd(self, *args):
_globals.pad = self
return self.ROOT_base.cd(self, *args)
class Pad(_PadBase, QROOT.TPad):
def __init__(self, *args, **kwargs):
ROOT.TPad.__init__(self, *args, **kwargs)
self._post_init()
class Canvas(_PadBase, QROOT.TCanvas):
def __init__(self,
width=defaults.CANVAS_WIDTH,
height=defaults.CANVAS_HEIGHT,
xpos=0, ypos=0, name=None, title=None):
Object.__init__(self, name, title, xpos, ypos, width, height)
self._post_init()
| """
This module implements python classes which inherit from
and extend the functionality of the ROOT canvas classes.
"""
import ctypes, ctypes.util
ctypes.cdll.LoadLibrary(ctypes.util.find_library("Gui"))
import ROOT
from ..core import Object
from .. import rootpy_globals as _globals
from .. import defaults, QROOT
class _PadBase(Object):
def _post_init(self):
self.members = []
_globals.pad = self
def Clear(self, *args, **kwargs):
self.members = []
self.ROOT_base.Clear(self, *args, **kwargs)
def OwnMembers(self):
for thing in self.GetListOfPrimitives():
if thing not in self.members:
self.members.append(thing)
def cd(self, *args):
_globals.pad = self
return self.ROOT_base.cd(self, *args)
class Pad(_PadBase, QROOT.TPad):
def __init__(self, *args, **kwargs):
ROOT.TPad.__init__(self, *args, **kwargs)
self._post_init()
class Canvas(_PadBase, QROOT.TCanvas):
def __init__(self,
width=defaults.CANVAS_WIDTH,
height=defaults.CANVAS_HEIGHT,
xpos=0, ypos=0, name=None, title=None):
Object.__init__(self, name, title, xpos, ypos, width, height)
self._post_init()
|
Rename to something more sensible | <?php
namespace eien\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use NotificationChannels\Telegram\TelegramChannel;
use NotificationChannels\Telegram\TelegramMessage;
class sendTelegram extends Notification implements ShouldQueue
{
use Queueable;
protected $telemessage;
protected $userId;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($telemessage)
{
$this->telemessage = $telemessage;
$this->userId = auth()->user();
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return [TelegramChannel::class];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toTelegram($notifiable)
{
return TelegramMessage::create()
->to($this->userId->telegram_id)
->content("*hello* \n xD" . "\n" . $this->telemessage);
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
| <?php
namespace eien\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use NotificationChannels\Telegram\TelegramChannel;
use NotificationChannels\Telegram\TelegramMessage;
class TelegramTest extends Notification implements ShouldQueue
{
use Queueable;
protected $telemessage;
protected $userId;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($telemessage)
{
$this->telemessage = $telemessage;
$this->userId = auth()->user();
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return [TelegramChannel::class];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toTelegram($notifiable)
{
return TelegramMessage::create()
->to($this->userId->telegram_id)
->content("*hello* \n xD" . "\n" . $this->telemessage);
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
|
Test getting comment for Mime type | from xdg import Mime
import unittest
import os.path
import tempfile, shutil
import resources
class MimeTest(unittest.TestCase):
def test_get_type_by_name(self):
appzip = Mime.get_type_by_name("foo.zip")
self.assertEqual(appzip.media, "application")
self.assertEqual(appzip.subtype, "zip")
def test_get_type_by_data(self):
imgpng = Mime.get_type_by_data(resources.png_data)
self.assertEqual(imgpng.media, "image")
self.assertEqual(imgpng.subtype, "png")
def test_get_type_by_contents(self):
tmpdir = tempfile.mkdtemp()
try:
test_file = os.path.join(tmpdir, "test")
with open(test_file, "wb") as f:
f.write(resources.png_data)
imgpng = Mime.get_type_by_contents(test_file)
self.assertEqual(imgpng.media, "image")
self.assertEqual(imgpng.subtype, "png")
finally:
shutil.rmtree(tmpdir)
def test_lookup(self):
pdf1 = Mime.lookup("application/pdf")
pdf2 = Mime.lookup("application", "pdf")
self.assertEqual(pdf1, pdf2)
self.assertEqual(pdf1.media, "application")
self.assertEqual(pdf1.subtype, "pdf")
pdf1.get_comment()
| from xdg import Mime
import unittest
import os.path
import tempfile, shutil
import resources
class MimeTest(unittest.TestCase):
def test_get_type_by_name(self):
appzip = Mime.get_type_by_name("foo.zip")
self.assertEqual(appzip.media, "application")
self.assertEqual(appzip.subtype, "zip")
def test_get_type_by_data(self):
imgpng = Mime.get_type_by_data(resources.png_data)
self.assertEqual(imgpng.media, "image")
self.assertEqual(imgpng.subtype, "png")
def test_get_type_by_contents(self):
tmpdir = tempfile.mkdtemp()
try:
test_file = os.path.join(tmpdir, "test")
with open(test_file, "wb") as f:
f.write(resources.png_data)
imgpng = Mime.get_type_by_contents(test_file)
self.assertEqual(imgpng.media, "image")
self.assertEqual(imgpng.subtype, "png")
finally:
shutil.rmtree(tmpdir)
def test_lookup(self):
pdf1 = Mime.lookup("application/pdf")
pdf2 = Mime.lookup("application", "pdf")
self.assertEqual(pdf1, pdf2)
self.assertEqual(pdf1.media, "application")
self.assertEqual(pdf1.subtype, "pdf")
|
Fix compile error in android example app. | package com.seatgeek.sixpack.android;
import com.seatgeek.sixpack.Alternative;
import com.seatgeek.sixpack.Experiment;
import com.seatgeek.sixpack.Sixpack;
import com.seatgeek.sixpack.SixpackBuilder;
import com.seatgeek.sixpack.log.LogLevel;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import okhttp3.HttpUrl;
@Module(
injects = {
SixpackActivity.class
}
)
public class SixpackModule {
public static final String BUTTON_COLOR = "button-color";
public static final String BUTTON_COLOR_RED = "red";
public static final String BUTTON_COLOR_BLUE = "blue";
@Singleton @Provides Sixpack provideSixpack() {
Sixpack sixpack = new SixpackBuilder()
.setClientId(Sixpack.generateRandomClientId())
.setSixpackUrl(HttpUrl.parse("http://10.0.3.2:5000/")) // genymotion host
.build();
sixpack.setLogLevel(LogLevel.VERBOSE);
return sixpack;
}
@Singleton @Provides @Named(BUTTON_COLOR) Experiment provideButtonColorExperiment(Sixpack sixpack) {
return sixpack.experiment()
.withName(BUTTON_COLOR)
.withAlternatives(
new Alternative(BUTTON_COLOR_RED),
new Alternative(BUTTON_COLOR_BLUE)
)
.build();
}
}
| package com.seatgeek.sixpack.android;
import com.seatgeek.sixpack.Alternative;
import com.seatgeek.sixpack.Experiment;
import com.seatgeek.sixpack.Sixpack;
import com.seatgeek.sixpack.SixpackBuilder;
import com.seatgeek.sixpack.log.LogLevel;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module(
injects = {
SixpackActivity.class
}
)
public class SixpackModule {
public static final String BUTTON_COLOR = "button-color";
public static final String BUTTON_COLOR_RED = "red";
public static final String BUTTON_COLOR_BLUE = "blue";
@Singleton @Provides Sixpack provideSixpack() {
Sixpack sixpack = new SixpackBuilder()
.setClientId(Sixpack.generateRandomClientId())
.setSixpackUrl("http://10.0.3.2:5000/") // genymotion host
.build();
sixpack.setLogLevel(LogLevel.VERBOSE);
return sixpack;
}
@Singleton @Provides @Named(BUTTON_COLOR) Experiment provideButtonColorExperiment(Sixpack sixpack) {
return sixpack.experiment()
.withName(BUTTON_COLOR)
.withAlternatives(
new Alternative(BUTTON_COLOR_RED),
new Alternative(BUTTON_COLOR_BLUE)
)
.build();
}
}
|
Fix style issues with previous commit | <?php
namespace Illuminate\Database\Query\Processors;
use Illuminate\Database\Query\Builder;
class SqlServerProcessor extends Processor
{
/**
* Process an "insert get ID" query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $sql
* @param array $values
* @param string $sequence
* @return int
*/
public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
{
$connection = $query->getConnection();
$connection->insert($sql, $values);
if ($connection->getConfig('odbc') === true) {
$result = $connection->select('SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid');
if (! $result) {
throw new Exception('Error retrieving lastInsertId');
}
$id = $result[0]->insertid;
} else {
$id = $connection->getPdo()->lastInsertId();
}
return is_numeric($id) ? (int) $id : $id;
}
/**
* Process the results of a column listing query.
*
* @param array $results
* @return array
*/
public function processColumnListing($results)
{
$mapping = function ($r) {
$r = (object) $r;
return $r->name;
};
return array_map($mapping, $results);
}
}
| <?php
namespace Illuminate\Database\Query\Processors;
use Illuminate\Database\Query\Builder;
class SqlServerProcessor extends Processor
{
/**
* Process an "insert get ID" query.
*
* @param \Illuminate\Database\Query\Builder $query
* @param string $sql
* @param array $values
* @param string $sequence
* @return int
*/
public function processInsertGetId(Builder $query, $sql, $values, $sequence = null)
{
$connection = $query->getConnection();
$connection->insert($sql, $values);
if ($connection->getConfig('odbc') === true) {
$result = $connection->select("SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int) AS insertid");
if (!$result) {
throw new Exception('Error retrieving lastInsertId');
}
$id = $result[0]->insertid;
}
else {
$id = $connection->getPdo()->lastInsertId();
}
return is_numeric($id) ? (int) $id : $id;
}
/**
* Process the results of a column listing query.
*
* @param array $results
* @return array
*/
public function processColumnListing($results)
{
$mapping = function ($r) {
$r = (object) $r;
return $r->name;
};
return array_map($mapping, $results);
}
}
|
Update the port to be an integer.
Fix the port to be an integer. Use the format function for string formatting. | from flask import request, Flask
from st2reactor.sensor.base import Sensor
class EchoFlaskSensor(Sensor):
def __init__(self, sensor_service, config):
super(EchoFlaskSensor, self).__init__(
sensor_service=sensor_service,
config=config
)
self._host = '127.0.0.1'
self._port = 5000
self._path = '/echo'
self._log = self._sensor_service.get_logger(__name__)
self._app = Flask(__name__)
def setup(self):
pass
def run(self):
@self._app.route(self._path, methods=['POST'])
def echo():
payload = request.get_json(force=True)
self._sensor_service.dispatch(trigger="examples.echo_flask",
payload=payload)
return request.data
self._log.info('Listening for payload on http://{}:{}{}'.format(
self._host, self._port, self._path))
self._app.run(host=self._host, port=self._port, threaded=True)
def cleanup(self):
pass
def add_trigger(self, trigger):
# This method is called when trigger is created
pass
def update_trigger(self, trigger):
# This method is called when trigger is updated
pass
def remove_trigger(self, trigger):
# This method is called when trigger is deleted
pass
| from flask import request, Flask
from st2reactor.sensor.base import Sensor
class EchoFlaskSensor(Sensor):
def __init__(self, sensor_service, config):
super(EchoFlaskSensor, self).__init__(
sensor_service=sensor_service,
config=config
)
self._host = '127.0.0.1'
self._port = '5000'
self._path = '/echo'
self._log = self._sensor_service.get_logger(__name__)
self._app = Flask(__name__)
def setup(self):
pass
def run(self):
@self._app.route(self._path, methods=['POST'])
def echo():
payload = request.get_json(force=True)
self._sensor_service.dispatch(trigger="examples.echo_flask",
payload=payload)
return request.data
self._log.info('Listening for payload on http://%s:%s%s' %
(self._host, self._port, self._path))
self._app.run(host=self._host, port=self._port, threaded=True)
def cleanup(self):
pass
def add_trigger(self, trigger):
# This method is called when trigger is created
pass
def update_trigger(self, trigger):
# This method is called when trigger is updated
pass
def remove_trigger(self, trigger):
# This method is called when trigger is deleted
pass
|
Include bad actor list check in to column for transfering, include new warning for phishing accounts | export function validate_account_name(value) {
const badActorList = /(polonox|poloneix|blocktrads|blocktrade|bittrexx)/;
let i, label, len, length, ref, suffix;
suffix = 'Account name should ';
if (!value) {
return suffix + 'not be empty.';
}
length = value.length;
if (length < 3) {
return suffix + 'be longer.';
}
if (length > 16) {
return suffix + 'be shorter.';
}
if (/\./.test(value)) {
suffix = 'Each account segment should ';
}
if (badActorList.test(value)) {
return suffix = 'Use caution sending to this account. Please double check your spelling for possible phishing. ';
}
ref = value.split('.');
for (i = 0, len = ref.length; i < len; i++) {
label = ref[i];
if (!/^[a-z]/.test(label)) {
return suffix + 'start with a letter.';
}
if (!/^[a-z0-9-]*$/.test(label)) {
return suffix + 'have only letters, digits, or dashes.';
}
if (/--/.test(label)) {
return suffix + 'have only one dash in a row.';
}
if (!/[a-z0-9]$/.test(label)) {
return suffix + 'end with a letter or digit.';
}
if (!(label.length >= 3)) {
return suffix + 'be longer';
}
}
return null;
}
|
export function validate_account_name(value) {
let i, label, len, length, ref, suffix;
suffix = 'Account name should ';
if (!value) {
return suffix + 'not be empty.';
}
length = value.length;
if (length < 3) {
return suffix + 'be longer.';
}
if (length > 16) {
return suffix + 'be shorter.';
}
if (/\./.test(value)) {
suffix = 'Each account segment should ';
}
ref = value.split('.');
for (i = 0, len = ref.length; i < len; i++) {
label = ref[i];
if (!/^[a-z]/.test(label)) {
return suffix + 'start with a letter.';
}
if (!/^[a-z0-9-]*$/.test(label)) {
return suffix + 'have only letters, digits, or dashes.';
}
if (/--/.test(label)) {
return suffix + 'have only one dash in a row.';
}
if (!/[a-z0-9]$/.test(label)) {
return suffix + 'end with a letter or digit.';
}
if (!(label.length >= 3)) {
return suffix + 'be longer';
}
}
return null;
} |
Make the 0012 migration reversible | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from distutils.version import LooseVersion
from django.db import models, migrations
def set_position_value_for_levin_classes(apps, schema_editor):
i = 0
LevinClass = apps.get_model('syntacticframes', 'LevinClass')
levin_class_list = sorted(LevinClass.objects.all(), key=lambda l: int(l.number))
for levin_class in levin_class_list:
verbnet_classes = sorted(
levin_class.verbnetclass_set.all(),
key=lambda v: LooseVersion(v.name.split('-')[1]))
for v in verbnet_classes:
v.position = i
v.save()
i += 10
class Migration(migrations.Migration):
dependencies = [
('syntacticframes', '0011_auto_20150121_1600'),
]
operations = [
migrations.AlterModelOptions(
name='verbnetclass',
options={'ordering': ['position']},
),
migrations.AddField(
model_name='verbnetclass',
name='position',
field=models.PositiveSmallIntegerField(default=0),
preserve_default=False,
),
migrations.RunPython(
code=set_position_value_for_levin_classes,
# Nothing to reverse since this is about a new field
reverse_code=lambda apps, schema_editor: None),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from distutils.version import LooseVersion
from django.db import models, migrations
def set_position_value_for_levin_classes(apps, schema_editor):
i = 0
LevinClass = apps.get_model('syntacticframes', 'LevinClass')
levin_class_list = sorted(LevinClass.objects.all(), key=lambda l: int(l.number))
for levin_class in levin_class_list:
verbnet_classes = sorted(
levin_class.verbnetclass_set.all(),
key=lambda v: LooseVersion(v.name.split('-')[1]))
for v in verbnet_classes:
v.position = i
v.save()
i += 10
class Migration(migrations.Migration):
dependencies = [
('syntacticframes', '0011_auto_20150121_1600'),
]
operations = [
migrations.AlterModelOptions(
name='verbnetclass',
options={'ordering': ['position']},
),
migrations.AddField(
model_name='verbnetclass',
name='position',
field=models.PositiveSmallIntegerField(default=0),
preserve_default=False,
),
migrations.RunPython(set_position_value_for_levin_classes),
]
|
Change comment to reference backend as such. | <?php
namespace Orbt\ResourceManager;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Guzzle\Common\Collection;
use Guzzle\Http\Client;
/**
* A generic resource manager.
*
* A resource manager takes care of fetching resources and processing them by dispatching event using the Symfony Event
* Dispatcher component.
*/
class ResourceManager
{
/**
* Event dispatcher.
* @var EventDispatcherInterface
*/
private $dispatcher;
/**
* Backend server base.
* @var string
*/
private $backendBaseUrl;
/**
* Guzzle backend client.
* @var Client
*/
private $client;
/**
* Creates a resource manager for a backend server.
*
* @param EventDispatcherInterface $dispatcher
* Event dispatcher.
* @param string $backendBaseUrl
* Backend server base URL.
* @param array|Collection $clientConfig
* Backend Guzzle client options.
*/
public function __construct(EventDispatcherInterface $dispatcher, $backendBaseUrl, $clientConfig = NULL)
{
$this->dispatcher = $dispatcher;
$this->backendBaseUrl = $backendBaseUrl;
$this->client = new Client($backendBaseUrl, $clientConfig);
}
/**
* Returns the backend client for this manager.
*/
public function getClient()
{
return $this->client;
}
}
| <?php
namespace Orbt\ResourceManager;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Guzzle\Common\Collection;
use Guzzle\Http\Client;
/**
* A generic resource manager.
*
* A resource manager takes care of fetching resources and processing them by dispatching event using the Symfony Event
* Dispatcher component.
*/
class ResourceManager
{
/**
* Event dispatcher.
* @var EventDispatcherInterface
*/
private $dispatcher;
/**
* Backend server base.
* @var string
*/
private $backendBaseUrl;
/**
* Guzzle client.
* @var Client
*/
private $client;
/**
* Creates a resource manager for a backend server.
*
* @param EventDispatcherInterface $dispatcher
* Event dispatcher.
* @param string $backendBaseUrl
* Backend server base URL.
* @param array|Collection $clientConfig
* Backend Guzzle client options.
*/
public function __construct(EventDispatcherInterface $dispatcher, $backendBaseUrl, $clientConfig = NULL)
{
$this->dispatcher = $dispatcher;
$this->backendBaseUrl = $backendBaseUrl;
$this->client = new Client($backendBaseUrl, $clientConfig);
}
/**
* Returns the HTTP client for this manager.
*/
public function getClient()
{
return $this->client;
}
}
|
Change scan_type and artifacts fields to enums | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCtdailyqcTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ctdailyqc', function (Blueprint $table) {
$table->increments('id');
$table->integer('machine_id')->unsigned()->nullable();
$table->date('qcdate')->nullable();
$table->enum('scan_type', ['Axial', 'Helical'])->nullable();
$table->float('water_hu', 4, 1)->nullable();
$table->float('water_sd', 4, 1)->nullable();
$table->enum('artifacts', ['Y', 'N'])->nullable();
$table->text('notes')->nullable();
$table->index(['machine_id', 'id']);
$table->index('qcdate');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('ctdailyqc');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCtdailyqcTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ctdailyqc', function (Blueprint $table) {
$table->increments('id');
$table->integer('machine_id')->unsigned()->nullable();
$table->date('qcdate')->nullable();
$table->enum('scan_type', ['A', 'H'])->nullable();
$table->float('water_hu', 4, 1)->nullable();
$table->float('water_sd', 4, 1)->nullable();
$table->boolean('artifacts')->nullable();
$table->text('notes')->nullable();
$table->index(['machine_id', 'id']);
$table->index('qcdate');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('ctdailyqc');
}
}
|
Replace setenv with putenv. Reported by Dietmar Schwertberger. | """A more or less complete user-defined wrapper around dictionary objects."""
import riscos
class _Environ:
def __init__(self, initial = None):
pass
def __repr__(self):
return repr(riscos.getenvdict())
def __cmp__(self, dict):
if isinstance(dict, UserDict):
return cmp(riscos.getenvdict(), dict)
def __len__(self):
return len(riscos.getenvdict())
def __getitem__(self, key):
ret = riscos.getenv(key)
if ret<>None:
return ret
else:
raise KeyError
def __setitem__(self, key, item):
riscos.putenv(key, item)
def __delitem__(self, key):
riscos.delenv(key)
def clear(self):
# too dangerous on RISC OS
pass
def copy(self):
return riscos.getenvdict()
def keys(self): return riscos.getenvdict().keys()
def items(self): return riscos.getenvdict().items()
def values(self): return riscos.getenvdict().values()
def has_key(self, key):
value = riscos.getenv(key)
return value<>None
def update(self, dict):
for k, v in dict.items():
riscos.putenv(k, v)
def get(self, key, failobj=None):
value = riscos.getenv(key)
if value<>None:
return value
else:
return failobj
| """A more or less complete user-defined wrapper around dictionary objects."""
import riscos
class _Environ:
def __init__(self, initial = None):
pass
def __repr__(self):
return repr(riscos.getenvdict())
def __cmp__(self, dict):
if isinstance(dict, UserDict):
return cmp(riscos.getenvdict(), dict)
def __len__(self):
return len(riscos.getenvdict())
def __getitem__(self, key):
ret = riscos.getenv(key)
if ret<>None:
return ret
else:
raise KeyError
def __setitem__(self, key, item):
riscos.setenv(key, item)
def __delitem__(self, key):
riscos.delenv(key)
def clear(self):
# too dangerous on RISC OS
pass
def copy(self):
return riscos.getenvdict()
def keys(self): return riscos.getenvdict().keys()
def items(self): return riscos.getenvdict().items()
def values(self): return riscos.getenvdict().values()
def has_key(self, key):
value = riscos.getenv(key)
return value<>None
def update(self, dict):
for k, v in dict.items():
riscos.putenv(k, v)
def get(self, key, failobj=None):
value = riscos.getenv(key)
if value<>None:
return value
else:
return failobj
|
Fix printing template when value is an array. | <!DOCTYPE html>
<html lang="en">
<head>
<title>Print Table</title>
<meta charset="UTF-8">
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<style>
body {margin: 20px}
</style>
</head>
<body>
<table class="table table-bordered table-condensed">
@foreach($data as $row)
@if ($row == reset($data))
<tr>
@foreach($row as $key => $value)
<th>{!! $key !!}</th>
@endforeach
</tr>
@endif
<tr>
@foreach($row as $key => $value)
@if(is_string($value) || is_numeric($value))
<td>{!! $value !!}</td>
@else
<td></td>
@endif
@endforeach
</tr>
@endforeach
</table>
</body>
</html>
| <!DOCTYPE html>
<html lang="en">
<head>
<title>Print Table</title>
<meta charset="UTF-8">
<meta name=description content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<style>
body {margin: 20px}
</style>
</head>
<body>
<table class="table table-bordered table-condensed">
@foreach($data as $row)
@if ($row == reset($data))
<tr>
@foreach($row as $key => $value)
<th>{!! $key !!}</th>
@endforeach
</tr>
@endif
<tr>
@foreach($row as $key => $value)
@if (is_string($value) || trim($value)==='' || is_numeric($value))
<td>{!! $value !!}</td>
@endif
@endforeach
</tr>
@endforeach
</table>
</body>
</html>
|
Correct bug on chapters when playing a chapter
The chapter wasn't playing due to the wrong reference of the exposed function setTime. | (function(app){
"use strict"
/**
* Creates a new HTML element ov-index to create an openVeo player
* index, with a list of presentation slides.
* It requires ovPlayerDirectory global variable to be defined and have
* a value corresponding to the path of the openVeo Player
* root directory.
*
* e.g.
* <ov-index></ov-index>
*/
app.directive("ovChapters", ovChapters);
ovChapters.$inject = ["ovChaptersLink"];
function ovChapters(ovChaptersLink){
return {
require : "^ovPlayer",
restrict : "E",
templateUrl : ovPlayerDirectory + "templates/chapters.html",
scope : true,
link : ovChaptersLink
}
}
app.factory("ovChaptersLink", function(){
return function(scope, element, attrs, playerCtrl){
scope.chapters = scope.data.chapter;
scope.open = function(chapter){
if(!chapter.isOpen)
angular.forEach(scope.chapters, function (value, key) {
value.isOpen = false;
});
chapter.isOpen = !chapter.isOpen;
}
/**
* Seeks media to the given timecode.
* @param Number timecode The timecode to seek to
*/
scope.goToTimecode = function(time){
if(time <= 1)
playerCtrl.setTime(time * scope.duration);
};
};
});
})(angular.module("ov.player")); | (function(app){
"use strict"
/**
* Creates a new HTML element ov-index to create an openVeo player
* index, with a list of presentation slides.
* It requires ovPlayerDirectory global variable to be defined and have
* a value corresponding to the path of the openVeo Player
* root directory.
*
* e.g.
* <ov-index></ov-index>
*/
app.directive("ovChapters", ovChapters);
ovChapters.$inject = ["ovChaptersLink"];
function ovChapters(ovChaptersLink){
return {
require : "^ovPlayer",
restrict : "E",
templateUrl : ovPlayerDirectory + "templates/chapters.html",
scope : true,
link : ovChaptersLink
}
}
app.factory("ovChaptersLink", function(){
return function(scope, element, attrs, playerCtrl){
scope.chapters = scope.data.chapter;
scope.open = function(chapter){
if(!chapter.isOpen)
angular.forEach(scope.chapters, function (value, key) {
value.isOpen = false;
});
chapter.isOpen = !chapter.isOpen;
}
/**
* Seeks media to the given timecode.
* @param Number timecode The timecode to seek to
*/
scope.goToTimecode = function(time){
if(time <= 1)
playerCtrl.player.setTime(time * scope.duration);
};
};
});
})(angular.module("ov.player")); |
Use proprer name to create the mixin | const createPolobxMixin = function(stores) {
let appState = {};
Object.keys(stores).forEach( key => {
const store = mobx.observable(stores[key].store);
const actions = stores[key].actions;
appState[key] = {
store,
actions
};
});
function dispatch({store, action, payload}) {
if (appState[store] && appState[store].actions && appState[store].actions[action]) {
const storeAction = appState[store].actions[action];
mobx.action(storeAction.bind(appState[store], [payload]))();
return appState[store];
}
console.warn(`No action "${action}" for "${store}" store`);
};
mobx.useStrict(true);
return subclass => class extends subclass {
constructor() {
super();
this._appState = appState;
this.dispatch = dispatch;
}
connectedCallback() {
super.connectedCallback();
const properties = this.constructor.config.properties;
if (properties) {
for (let property in properties) {
const statePath = properties[property].statePath;
if (statePath && this._appState[statePath.store]) {
mobx.autorun(() => {
const store = this._appState[statePath.store].store;
this[property] = store[statePath.path];
});
}
}
}
}
};
};
| const MobxMixin = function(stores) {
let appState = {};
Object.keys(stores).forEach( key => {
const store = mobx.observable(stores[key].store);
const actions = stores[key].actions;
appState[key] = {
store,
actions
};
});
function dispatch({store, action, payload}) {
if (appState[store] && appState[store].actions && appState[store].actions[action]) {
const storeAction = appState[store].actions[action];
mobx.action(storeAction.bind(appState[store], [payload]))();
return appState[store];
}
console.warn(`No action "${action}" for "${store}" store`);
};
mobx.useStrict(true);
return subclass => class extends subclass {
constructor() {
super();
this._appState = appState;
this.dispatch = dispatch;
}
connectedCallback() {
super.connectedCallback();
const properties = this.constructor.config.properties;
if (properties) {
for (let property in properties) {
const statePath = properties[property].statePath;
if (statePath && this._appState[statePath.store]) {
mobx.autorun(() => {
const store = this._appState[statePath.store].store;
this[property] = store[statePath.path];
});
}
}
}
}
};
};
|
Make images clickable on members search | import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
class MembersPreview extends Component {
render() {
const {displayName, searchImg, intro, slug} = this.props;
return (
<div className="col-xs-12 col-sm-4 col-md-3">
<div className="thumbnail" style={{
height: '300px',
background: 'rgba(243,243,243,1)',
border: '0',
borderRadius: '0',
padding: '20px 10px',
}}>
<div style={{
maxHeight: '95%',
overflowY: 'auto',
}}>
{
searchImg &&
<Link to={ `/members/${slug}` }>
<img
src={searchImg.url}
style={{
maxHeight: '125px',
margin: 'auto',
display: 'block',
}}
/>
</Link>
}
<div className="caption">
<h4 className="nomargin" style={{
textAlign: 'center',
}}>
<Link to={ `/members/${slug}` }>{displayName}</Link>
</h4>
<p dangerouslySetInnerHTML={{ __html: intro }} />
</div>
</div>
</div>
</div>
);
}
}
MembersPreview.propTypes = {
displayName: PropTypes.string.isRequired,
searchImg: PropTypes.shape({
url: PropTypes.string.isRequired,
height: PropTypes.number,
width: PropTypes.number,
}),
intro: PropTypes.string,
slug: PropTypes.string.isRequired,
usState: PropTypes.string,
};
export default MembersPreview;
| import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
class MembersPreview extends Component {
render() {
const {displayName, searchImg, intro, slug} = this.props;
return (
<div className="col-xs-12 col-sm-4 col-md-3">
<div className="thumbnail" style={{
height: '300px',
background: 'rgba(243,243,243,1)',
border: '0',
borderRadius: '0',
padding: '20px 10px',
}}>
<div style={{
maxHeight: '95%',
overflowY: 'auto',
}}>
{
searchImg &&
<img src={searchImg.url} style={{
maxHeight: '125px',
margin: 'auto',
display: 'block',
}}/>
}
<div className="caption">
<h4 className="nomargin" style={{
textAlign: 'center',
}}>
<Link to={ `/members/${slug}` }>{displayName}</Link>
</h4>
<p dangerouslySetInnerHTML={{ __html: intro }} />
</div>
</div>
</div>
</div>
);
}
}
MembersPreview.propTypes = {
displayName: PropTypes.string.isRequired,
searchImg: PropTypes.shape({
url: PropTypes.string.isRequired,
height: PropTypes.number,
width: PropTypes.number,
}),
intro: PropTypes.string,
slug: PropTypes.string.isRequired,
usState: PropTypes.string,
};
export default MembersPreview;
|
Make RECENT mode title consistent. | import {ChangeEmitter} from "../utils/ChangeEmitter.js";
import AppDispatcher from "../dispatcher/AppDispatcher.js";
import ContainerConstants from "../constants/ContainerConstants.js";
import SearchConstants from "../constants/SearchConstants.js";
var _defaultMode = ContainerConstants.ALL;
function setMode(m) {
if (m === null) {
m = _defaultMode;
}
localStorage.setItem("mode", m);
}
function mode() {
var m = localStorage.getItem("mode");
if (m === null) {
m = _defaultMode;
}
return m;
}
var _titles = {};
_titles[ContainerConstants.ALL] = "Library";
_titles[ContainerConstants.RECENT] = "Recently Added";
_titles[ContainerConstants.RETRO] = "";
class ContainerStore extends ChangeEmitter {
getMode() {
return mode();
}
getTitle() {
var m = mode();
if (_titles.hasOwnProperty(m)) {
return _titles[m];
}
return m.toLowerCase();
}
}
var _containerStore = new ContainerStore();
_containerStore.dispatchToken = AppDispatcher.register(function(payload) {
var action = payload.action;
var source = payload.source;
if (source === "VIEW_ACTION") {
switch (action.actionType) {
case ContainerConstants.MODE:
setMode(action.mode);
_containerStore.emitChange();
break;
case SearchConstants.SEARCH:
setMode(ContainerConstants.SEARCH);
_containerStore.emitChange();
break;
}
}
return true;
});
export default _containerStore;
| import {ChangeEmitter} from "../utils/ChangeEmitter.js";
import AppDispatcher from "../dispatcher/AppDispatcher.js";
import ContainerConstants from "../constants/ContainerConstants.js";
import SearchConstants from "../constants/SearchConstants.js";
var _defaultMode = ContainerConstants.ALL;
function setMode(m) {
if (m === null) {
m = _defaultMode;
}
localStorage.setItem("mode", m);
}
function mode() {
var m = localStorage.getItem("mode");
if (m === null) {
m = _defaultMode;
}
return m;
}
var _titles = {};
_titles[ContainerConstants.ALL] = "Library";
_titles[ContainerConstants.RETRO] = "";
class ContainerStore extends ChangeEmitter {
getMode() {
return mode();
}
getTitle() {
var m = mode();
if (_titles.hasOwnProperty(m)) {
return _titles[m];
}
return m.toLowerCase();
}
}
var _containerStore = new ContainerStore();
_containerStore.dispatchToken = AppDispatcher.register(function(payload) {
var action = payload.action;
var source = payload.source;
if (source === "VIEW_ACTION") {
switch (action.actionType) {
case ContainerConstants.MODE:
setMode(action.mode);
_containerStore.emitChange();
break;
case SearchConstants.SEARCH:
setMode(ContainerConstants.SEARCH);
_containerStore.emitChange();
break;
}
}
return true;
});
export default _containerStore;
|
Make an example package private | /*
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.aerogear.webpush;
final class Example {
public static void main(String[] args) throws Exception {
WebPushClient webPushClient = new WebPushClient("https://localhost:8443", true);
try {
webPushClient.connect();
webPushClient.subscribe(subscription -> {
System.out.println(subscription);
//check new push messages and close the stream (nowait == true)
webPushClient.monitor(subscription, true, pushMessage -> {
if (pushMessage.isPresent()) {
System.out.println(pushMessage.get());
} else { //possible only if nowait == true
System.out.println("204 No Content");
}
});
//monitor all new push messages
webPushClient.monitor(subscription, System.out::println);
});
Thread.sleep(30 * 1000);
} finally {
webPushClient.disconnect();
}
}
}
| /*
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.aerogear.webpush;
public final class Example {
public static void main(String[] args) throws Exception {
WebPushClient webPushClient = new WebPushClient("https://localhost:8443", true);
try {
webPushClient.connect();
webPushClient.subscribe(subscription -> {
System.out.println(subscription);
//check new push messages and close the stream (nowait == true)
webPushClient.monitor(subscription, true, pushMessage -> {
if (pushMessage.isPresent()) {
System.out.println(pushMessage.get());
} else { //possible only if nowait == true
System.out.println("204 No Content");
}
});
//monitor all new push messages
webPushClient.monitor(subscription, System.out::println);
});
Thread.sleep(30 * 1000);
} finally {
webPushClient.disconnect();
}
}
}
|
Set webpack public path so file URLs become absolute | import path from 'path'
import webpack from 'webpack'
import StaticSiteGeneratorPlugin from 'static-site-generator-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
const config = {
entry: './index.js',
output: {
filename: 'main.[hash].js',
path: path.join(__dirname, 'build'),
publicPath: '/',
libraryTarget: 'umd'
},
externals: [
'./site/server',
],
devtool: 'source-map',
module: {
loaders: [
{
test: /\.less$/,
loader: 'css!autoprefixer!less',
},
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel'],
},
{
test: /\.json$/,
loader: 'json',
},
{
test: /\/static\/favicon\.png$/,
loader: 'file?name=[name].[ext]',
},
{
test: /\.mid$/,
loader: 'file?name=[path][name].[hash].[ext]',
},
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
new StaticSiteGeneratorPlugin('main', ['/'], {data: {}}),
],
}
if (process.env.NODE_ENV === 'production') {
const lessLoader = config.module.loaders[0]
lessLoader.loader = ExtractTextPlugin.extract(lessLoader.loader)
config.plugins.push(new ExtractTextPlugin('main.[contenthash].css'))
}
export default config
| import path from 'path'
import webpack from 'webpack'
import StaticSiteGeneratorPlugin from 'static-site-generator-webpack-plugin'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
const config = {
entry: './index.js',
output: {
filename: 'main.[hash].js',
path: path.join(__dirname, 'build'),
libraryTarget: 'umd'
},
externals: [
'./site/server',
],
devtool: 'source-map',
module: {
loaders: [
{
test: /\.less$/,
loader: 'css!autoprefixer!less',
},
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel'],
},
{
test: /\.json$/,
loader: 'json',
},
{
test: /\/static\/favicon\.png$/,
loader: 'file?name=[name].[ext]',
},
{
test: /\.mid$/,
loader: 'file?name=[path][name].[hash].[ext]',
},
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
new StaticSiteGeneratorPlugin('main', ['/'], {data: {}}),
],
}
if (process.env.NODE_ENV === 'production') {
const lessLoader = config.module.loaders[0]
lessLoader.loader = ExtractTextPlugin.extract(lessLoader.loader)
config.plugins.push(new ExtractTextPlugin('main.[contenthash].css'))
}
export default config
|
Fix getToken rename issue in 5.4 | <?php
namespace Collective\Html;
use Illuminate\Support\ServiceProvider;
class HtmlServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerHtmlBuilder();
$this->registerFormBuilder();
$this->app->alias('html', 'Collective\Html\HtmlBuilder');
$this->app->alias('form', 'Collective\Html\FormBuilder');
}
/**
* Register the HTML builder instance.
*
* @return void
*/
protected function registerHtmlBuilder()
{
$this->app->singleton('html', function ($app) {
return new HtmlBuilder($app['url'], $app['view']);
});
}
/**
* Register the form builder instance.
*
* @return void
*/
protected function registerFormBuilder()
{
$this->app->singleton('form', function ($app) {
$form = new FormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->token());
return $form->setSessionStore($app['session.store']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['html', 'form', 'Collective\Html\HtmlBuilder', 'Collective\Html\FormBuilder'];
}
}
| <?php
namespace Collective\Html;
use Illuminate\Support\ServiceProvider;
class HtmlServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerHtmlBuilder();
$this->registerFormBuilder();
$this->app->alias('html', 'Collective\Html\HtmlBuilder');
$this->app->alias('form', 'Collective\Html\FormBuilder');
}
/**
* Register the HTML builder instance.
*
* @return void
*/
protected function registerHtmlBuilder()
{
$this->app->singleton('html', function ($app) {
return new HtmlBuilder($app['url'], $app['view']);
});
}
/**
* Register the form builder instance.
*
* @return void
*/
protected function registerFormBuilder()
{
$this->app->singleton('form', function ($app) {
$form = new FormBuilder($app['html'], $app['url'], $app['view'], $app['session.store']->getToken());
return $form->setSessionStore($app['session.store']);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['html', 'form', 'Collective\Html\HtmlBuilder', 'Collective\Html\FormBuilder'];
}
}
|
Change title of history page depend on the current page | <div class="panel <?php echo (isset($single)?'single':''); ?>">
<div class="warp">
<?php if (isset($single)): ?>
<b>Last Read</b>
<?php else: ?>
<b>My Reading History</b>
<?php endif; ?>
</div>
<div class="<?php echo (isset($single)?'':'warp'); ?>">
<?php while ($row = $history->row()): ?>
<div <?php echo (isset($single)?'class="list"':''); ?>>
<a href="<?php echo baseUrl().
"manga/$row->fmanga/chapter/$row->fchapter" ?>"
<?php echo (isset($single)?'class="clearfix"':''); ?>>
<?php if (isset($single)): ?>
<div class="left hwarp">
<?php echo $row->chapter; ?>
</div>
<div class="right desc">
<?php echo page()->date->relative($row->update_at); ?>
</div>
<?php else: ?>
<?php echo $row->chapter;?>
<?php endif; ?>
</a>
</div>
<?php endwhile; ?>
</div>
</div>
| <div class="panel <?php echo (isset($single)?'single':''); ?>">
<div class="warp">
<b>My Reading History</b>
</div>
<div class="<?php echo (isset($single)?'':'warp'); ?>">
<?php while ($row = $history->row()): ?>
<div <?php echo (isset($single)?'class="list"':''); ?>>
<a href="<?php echo baseUrl().
"manga/$row->fmanga/chapter/$row->fchapter" ?>"
<?php echo (isset($single)?'class="clearfix"':''); ?>>
<?php if (isset($single)): ?>
<div class="left hwarp">
<?php echo $row->chapter; ?>
</div>
<div class="right desc">
<?php echo page()->date->relative($row->update_at); ?>
</div>
<?php else: ?>
<?php echo $row->chapter;?>
<?php endif; ?>
</a>
</div>
<?php endwhile; ?>
</div>
</div>
|
Edit dedupe campus slugs code | from django.core.management.base import BaseCommand
from django.db.models import Count
from django.utils.text import slugify
from scuole.campuses.models import Campus
class Command(BaseCommand):
help = "Dedupe Campus slugs by adding the county name to the end."
def handle(self, *args, **options):
duplicate_slugs = (
Campus.objects.values("slug")
.annotate(total=Count("slug"))
.filter(total__gt=1)
)
# loop through all duplicate slugs
for duplicate in duplicate_slugs:
slug = duplicate['slug']
campuses_dup_slug = Campus.objects.filter(slug=slug)
# if the district and county are the same, but the city of the campuses are different
if all(obj.district == campuses_dup_slug[0].district for obj in campuses_dup_slug) and all(obj.county == campuses_dup_slug[0].county for obj in campuses_dup_slug):
for campus in campuses_dup_slug:
if campus.city != None:
city_slug = slugify(campus.city, allow_unicode=True)
campus.slug = f"{campus.slug}-{city_slug}"
campus.save()
# if the district, county, and city of the campuses are the same
if all(obj.district == campuses_dup_slug[0].district for obj in campuses_dup_slug) and all(obj.county == campuses_dup_slug[0].county for obj in campuses_dup_slug) and all(obj.city == campuses_dup_slug[0].city for obj in campuses_dup_slug):
for campus in campuses_dup_slug:
campus.slug = f"{campus.slug}-{campus.tea_id}"
campus.save()
| from django.core.management.base import BaseCommand
from django.db.models import Count
from django.utils.text import slugify
from scuole.campuses.models import Campus
class Command(BaseCommand):
help = "Dedupe Campus slugs by adding the county name to the end."
def handle(self, *args, **options):
duplicate_slugs = (
Campus.objects.values("slug")
.annotate(total=Count("slug"))
.filter(total__gt=1)
)
print('DUPLICATE SLUGS', duplicate_slugs)
# loop through all duplicate slugs
for duplicate in duplicate_slugs:
slug = duplicate['slug']
# for campus in Campus.objects.filter(slug=slug):
# if campus.city != None:
# city_slug = slugify(campus.city, allow_unicode=True)
# campus.slug = f"{campus.slug}-{city_slug}"
# campus.save()
# city_slug = slugify(campus.city, allow_unicode=True)
# campus.slug = f"{campus.slug}-{city_slug}"
# print(slugify(campus.city, allow_unicode=True))
# print('SLUG', campus.slug)
# campus.save()
|
Remove the hard coded process name now that the process name has been set. | (function (module) {
module.controller('ProjectHomeController', ProjectHomeController);
ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state", "Restangular"];
function ProjectHomeController(project, mcmodal, templates, $state, Restangular) {
var ctrl = this;
ctrl.project = project;
ctrl.chooseTemplate = chooseTemplate;
ctrl.chooseExistingProcess = chooseExistingProcess;
ctrl.templates = templates;
ctrl.hasFavorites = _.partial(_.any, ctrl.templates, _.matchesProperty('favorite', true));
/////////////////////////
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
$state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''});
});
}
function chooseExistingProcess() {
Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) {
mcmodal.chooseExistingProcess(processes).then(function (existingProcess) {
$state.go('projects.project.processes.create',
{process: existingProcess.process_name, process_id: existingProcess.id});
});
});
}
}
}(angular.module('materialscommons')));
| (function (module) {
module.controller('ProjectHomeController', ProjectHomeController);
ProjectHomeController.$inject = ["project", "mcmodal", "templates", "$state", "Restangular"];
function ProjectHomeController(project, mcmodal, templates, $state, Restangular) {
var ctrl = this;
ctrl.project = project;
ctrl.chooseTemplate = chooseTemplate;
ctrl.chooseExistingProcess = chooseExistingProcess;
ctrl.templates = templates;
ctrl.hasFavorites = _.partial(_.any, ctrl.templates, _.matchesProperty('favorite', true));
/////////////////////////
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project, templates).then(function (processTemplateName) {
$state.go('projects.project.processes.create', {process: processTemplateName, process_id: ''});
});
}
function chooseExistingProcess() {
Restangular.one('v2').one("projects", project.id).one("processes").getList().then(function(processes) {
mcmodal.chooseExistingProcess(processes).then(function (existingProcess) {
var processName = existingProcess.process_name ? existingProcess.process_name : 'TEM';
$state.go('projects.project.processes.create', {process: processName, process_id: existingProcess.id});
});
});
}
}
}(angular.module('materialscommons')));
|
Use simple cache for known transactions | package io.debezium.examples.cacheinvalidation.persistence;
import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.DefaultCacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Keeps track of transactions initiated by this application, so we can tell
* them apart from transactions initiated externally, e.g. via other DB clients.
*/
@ApplicationScoped
public class KnownTransactions {
private static final Logger LOG = LoggerFactory.getLogger( KnownTransactions.class );
private final DefaultCacheManager cacheManager;
private final Cache<Long, Boolean> applicationTransactions;
public KnownTransactions() {
cacheManager = new DefaultCacheManager();
cacheManager.defineConfiguration(
"tx-id-cache",
new ConfigurationBuilder()
.simpleCache(true)
.expiration()
.lifespan(60, TimeUnit.SECONDS)
.build()
);
applicationTransactions = cacheManager.getCache("tx-id-cache");
}
@PreDestroy
public void stopCacheManager() {
cacheManager.stop();
}
public void register(long txId) {
LOG.info("Registering TX {} started by this application", txId);
applicationTransactions.put(txId, true);
}
public boolean isKnown(long txId) {
return Boolean.TRUE.equals(applicationTransactions.get(txId));
}
}
| package io.debezium.examples.cacheinvalidation.persistence;
import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.DefaultCacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Keeps track of transactions initiated by this application, so we can tell
* them apart from transactions initiated externally, e.g. via other DB clients.
*/
@ApplicationScoped
public class KnownTransactions {
private static final Logger LOG = LoggerFactory.getLogger( KnownTransactions.class );
private final DefaultCacheManager cacheManager;
private final Cache<Long, Boolean> applicationTransactions;
public KnownTransactions() {
cacheManager = new DefaultCacheManager();
cacheManager.defineConfiguration(
"tx-id-cache",
new ConfigurationBuilder()
.expiration()
.lifespan(60, TimeUnit.SECONDS)
.build()
);
applicationTransactions = cacheManager.getCache("tx-id-cache");
}
@PreDestroy
public void stopCacheManager() {
cacheManager.stop();
}
public void register(long txId) {
LOG.info("Registering TX {} started by this application", txId);
applicationTransactions.put(txId, true);
}
public boolean isKnown(long txId) {
return Boolean.TRUE.equals(applicationTransactions.get(txId));
}
}
|
Store reference to player, dim lights | elation.require(['engine.engine', 'engine.things.player', 'engine.things.light', 'janusweb.janusweb'], function() {
elation.component.add('janusweb.client', function() {
this.initEngine = function() {
//this.enginecfg.systems.push('admin');
}
this.initWorld = function() {
var things = this.world.load({
name: 'janusweb',
type: 'janusweb',
properties: {
},
things: {
ambient: {
name: 'ambient',
type: 'light_ambient',
properties: {
color: 0x444444
}
},
sun: {
name: 'sun',
type: 'light_directional',
properties: {
position: [-20,50,25],
intensity: 0.1
}
},
point: {
name: 'point01',
type: 'light_point',
properties: {
position: [22,19,-15],
intensity: 0.1
}
},
player: {
name: 'player',
type: 'player',
properties: {
position: [0,0,0],
mass: 10
}
},
}
});
this.player = things.children.janusweb.children.player;
}
}, elation.engine.client);
});
| elation.require(['engine.engine', 'engine.things.light', 'janusweb.janusweb'], function() {
elation.component.add('janusweb.client', function() {
this.initEngine = function() {
//this.enginecfg.systems.push('admin');
}
this.initWorld = function() {
var things = this.world.load({
name: 'janusweb',
type: 'janusweb',
properties: {
},
things: {
ambient: {
name: 'ambient',
type: 'light_ambient',
properties: {
color: 0x444444
}
},
sun: {
name: 'sun',
type: 'light_directional',
properties: {
position: [-20,50,25],
intensity: 0.2
}
},
point: {
name: 'point01',
type: 'light_point',
properties: {
position: [22,19,-15],
intensity: 0.2
}
},
player: {
name: 'player',
type: 'player',
properties: {
position: [0,0,0],
mass: 10
}
},
}
});
}
}, elation.engine.client);
});
|
CRM-4194: Fix "You have a new email" message
fixed compositions concept | require([
'oroui/js/app/controllers/base/controller'
], function(BaseController) {
'use strict';
BaseController.loadBeforeAction([
'jquery',
'oroemail/js/app/components/email-notification-component',
'oroemail/js/app/models/email-notification/email-notification-count-model'
], function($, EmailNotificationComponent, EmailNotificationCountModel) {
BaseController.addToReuse('emailNotification', {
compose: function() {
var $menu = $('.email-notification-menu');
if ($menu.length !== 0) {
var options = $menu.data('page-component-options');
options._sourceElement = $menu.find('.dropdown-menu');
options._iconElement = $menu.find('.email-notification-icon');
options.countModel = new EmailNotificationCountModel({'unreadEmailsCount': options.count});
this.component = new EmailNotificationComponent(options);
}
}
});
});
BaseController.loadBeforeAction([
'jquery',
'oroemail/js/app/components/new-email-message-component'
], function($, NewEmailMessageComponent) {
BaseController.addToReuse('mewEmailMessage', {
compose: function() {
var $notification = $('.email-notification-menu .new-email-notification');
this.component = new NewEmailMessageComponent({
notificationElement: $notification.length > 0 ? $notification : null
});
}
});
});
});
| require([
'oroui/js/app/controllers/base/controller'
], function(BaseController) {
'use strict';
BaseController.loadBeforeAction([
'jquery',
'oroemail/js/app/components/email-notification-component',
'oroemail/js/app/components/new-email-message-component',
'oroemail/js/app/models/email-notification/email-notification-count-model'
], function($, EmailNotificationComponent, NewEmailMessageComponent, EmailNotificationCountModel) {
BaseController.addToReuse('emailNotification', {
compose: function() {
var $menu = $('.email-notification-menu');
var $notification = $menu.find('.new-email-notification');
if ($menu.length !== 0) {
var options = $menu.data('page-component-options');
options._sourceElement = $menu.find('.dropdown-menu');
options._iconElement = $menu.find('.email-notification-icon');
options.countModel = new EmailNotificationCountModel({'unreadEmailsCount': options.count});
this.component = new EmailNotificationComponent(options);
}
this.emailNotificationComponent = new NewEmailMessageComponent({
notificationElement: $notification.length > 0 ? $notification : null
});
}
});
});
});
|
Remove duplicated record plain get | const jwt = require('jsonwebtoken')
const config = require('config')
const bcrypt = require('bcrypt')
const _ = require('lodash')
const User = require('./../models/user')
const Messages = require('./../messages')
const Authenticate = (user) => {
return new Promise((resolve, reject) => {
User.findOne({ 'where': { 'email': user.email } })
.then((record) => {
if (!record) {
return reject({ 'errors': {
'user': { 'not_found': Messages.errors.user.not_found }
}})
}
record = record.get({ plain: true })
bcrypt.compare(user.password, record.password)
.then((result) => {
if (result) {
return jwt.sign(_.omit(record, ['password']), config.get('secret'), { expiresIn: '1d' }, (error, token) => {
if (error) {
console.error('[JWT ERROR] ' + error)
return reject({ 'errors': {
'token': { 'unavailable': Messages.errors.token.unavailable }
}})
}
return resolve({ 'token': token })
})
}
return reject({ 'errors': {
'user': { 'password': Messages.errors.user.password }
}})
})
})
})
}
module.exports = Authenticate
| const jwt = require('jsonwebtoken')
const config = require('config')
const bcrypt = require('bcrypt')
const _ = require('lodash')
const User = require('./../models/user')
const Messages = require('./../messages')
const Authenticate = (user) => {
return new Promise((resolve, reject) => {
User.findOne({ 'where': { 'email': user.email } })
.then((record) => {
if (!record) {
return reject({ 'errors': {
'user': { 'not_found': Messages.errors.user.not_found }
}})
}
record = record.get({ plain: true })
bcrypt.compare(user.password, record.password)
.then((result) => {
if (result) {
return jwt.sign(_.omit(record.get({ 'plain': true }), ['password']), config.get('secret'), { expiresIn: '1d' }, (error, token) => {
if (error) {
console.error('[JWT ERROR] ' + error)
return reject({ 'errors': {
'token': { 'unavailable': Messages.errors.token.unavailable }
}})
}
return resolve({ 'token': token })
})
}
return reject({ 'errors': {
'user': { 'password': Messages.errors.user.password }
}})
})
})
})
}
module.exports = Authenticate
|
:fire: Remove function wrapping around js includes | 'use strict'
const FS = require('fs')
const Path = require('path')
const Base = require('./base')
class GenericPlugin extends Base {
constructor() {
super()
this.registerTag(['Compiler-Include'], function(name, value, options) {
value = Path.resolve(options.internal.file.directory, value)
options.internal.imports.push(value)
return new Promise(function(resolve, reject) {
FS.readFile(value, function (err, data) {
if (err) return reject(err)
data = data.toString('utf8')
const extension = options.internal.file.extension
if (extension === '.js' || extension === '.coffee') {
resolve('; ' + data + ' ;')
} else resolve(data)
})
})
})
this.registerTag(['Compiler-Output'], function(name, value, options) {
options.Output = Path.resolve(options.internal.file.directory, value)
})
this.registerTag(['Compiler-Compress', 'Compiler-Uglify', 'Compiler-Minify'], function(name, value, options) {
options.Uglify = value === 'true'
})
this.registerTag(['Compiler-Babel', 'Compiler-Transpile'], function(name, value, options) {
options.Babel = value === 'true'
})
}
compile(contents, options) {
return this.executeTags(contents, options)
}
}
module.exports = GenericPlugin
| 'use strict'
const FS = require('fs')
const Path = require('path')
const Base = require('./base')
class GenericPlugin extends Base {
constructor() {
super()
this.registerTag(['Compiler-Include'], function(name, value, options) {
value = Path.resolve(options.internal.file.directory, value)
options.internal.imports.push(value)
return new Promise(function(resolve, reject) {
FS.readFile(value, function (err, data) {
if (err) return reject(err)
data = data.toString('utf8')
const extension = options.internal.file.extension
if (extension === '.js' || extension === '.coffee') {
resolve(';(function(){ ' + data + ' })();')
} else resolve(data)
})
})
})
this.registerTag(['Compiler-Output'], function(name, value, options) {
options.Output = Path.resolve(options.internal.file.directory, value)
})
this.registerTag(['Compiler-Compress', 'Compiler-Uglify', 'Compiler-Minify'], function(name, value, options) {
options.Uglify = value === 'true'
})
this.registerTag(['Compiler-Babel', 'Compiler-Transpile'], function(name, value, options) {
options.Babel = value === 'true'
})
}
compile(contents, options) {
return this.executeTags(contents, options)
}
}
module.exports = GenericPlugin
|
Set the computed value on the View-Model itself, the way Vue does it | const prefix = '_async_computed$'
export default {
install (Vue, options) {
options = options || {}
Vue.config
.optionMergeStrategies
.asyncComputed = Vue.config.optionMergeStrategies.computed
Vue.mixin({
created () {
Object.keys(this.$options.asyncComputed || {}).forEach(key => {
const fn = this.$options.asyncComputed[key]
if (!this.$options.computed) this.$options.computed = {}
Vue.set(this.$options.computed, prefix + key, fn)
Vue.set(this, key, null)
})
this._initComputed()
Object.keys(this.$options.asyncComputed || {}).forEach(key => {
let promiseId = 0
this.$watch(prefix + key, newPromise => {
const thisPromise = ++promiseId
newPromise.then(value => {
if (thisPromise !== promiseId) return
this[key] = value
}).catch(err => {
if (thisPromise !== promiseId) return
if (options.errorHandler === false) return
const handler = (options.errorHandler === undefined)
? console.error.bind(console, 'Error evaluating async computed property:')
: options.errorHandler
handler(err.stack)
})
}, { immediate: true })
})
}
})
}
}
| const prefix = '_async_computed$'
export default {
install (Vue, options) {
options = options || {}
Vue.config
.optionMergeStrategies
.asyncComputed = Vue.config.optionMergeStrategies.computed
Vue.mixin({
created () {
Object.keys(this.$options.asyncComputed || {}).forEach(key => {
const fn = this.$options.asyncComputed[key]
if (!this.$options.computed) this.$options.computed = {}
Vue.set(this.$options.computed, prefix + key, fn)
Vue.set(this.$data, key, null)
})
this._initComputed()
Object.keys(this.$options.asyncComputed || {}).forEach(key => {
let promiseId = 0
this.$watch(prefix + key, newPromise => {
const thisPromise = ++promiseId
newPromise.then(value => {
if (thisPromise !== promiseId) return
this[key] = value
}).catch(err => {
if (thisPromise !== promiseId) return
if (options.errorHandler === false) return
const handler = (options.errorHandler === undefined)
? console.error.bind(console, 'Error evaluating async computed property:')
: options.errorHandler
handler(err.stack)
})
}, { immediate: true })
})
}
})
}
}
|
Remove the security bypass hack. It's not needed anymore. | // Security.java
package ed.security;
import ed.js.engine.*;
public class Security {
public final static boolean OFF = Boolean.getBoolean( "NO-SECURITY" );
final static String SECURE[] = new String[]{
Convert.DEFAULT_PACKAGE + "._data_corejs_" ,
Convert.DEFAULT_PACKAGE + "._data_sites_admin_" ,
Convert.DEFAULT_PACKAGE + "._data_sites_www_" ,
Convert.DEFAULT_PACKAGE + ".lastline"
};
public static boolean isCoreJS(){
if ( OFF )
return true;
String topjs = getTopJS();
if ( topjs == null ) {
return false;
}
for ( int i=0; i<SECURE.length; i++ )
if ( topjs.startsWith( SECURE[i] ) )
return true;
return false;
}
public static String getTopJS(){
StackTraceElement[] st = Thread.currentThread().getStackTrace();
for ( int i=0; i<st.length; i++ ){
StackTraceElement e = st[i];
if ( e.getClassName().startsWith( Convert.DEFAULT_PACKAGE + "." ) )
return e.getClassName();
}
return null;
}
}
| // Security.java
package ed.security;
import ed.js.engine.*;
public class Security {
public final static boolean OFF = Boolean.getBoolean( "NO-SECURITY" );
final static boolean TEST_BYPASS = Boolean.getBoolean("ed.js.engine.SECURITY_BYPASS");
final static String SECURE[] = new String[]{
Convert.DEFAULT_PACKAGE + "._data_corejs_" ,
Convert.DEFAULT_PACKAGE + "._data_sites_admin_" ,
Convert.DEFAULT_PACKAGE + "._data_sites_www_" ,
Convert.DEFAULT_PACKAGE + ".lastline"
};
public static boolean isCoreJS(){
if ( OFF )
return true;
String topjs = getTopJS();
if ( topjs == null ) {
return false;
}
if (TEST_BYPASS && _isTestFrameworkHack()) {
return true;
}
for ( int i=0; i<SECURE.length; i++ )
if ( topjs.startsWith( SECURE[i] ) )
return true;
return false;
}
static boolean _isTestFrameworkHack() {
StackTraceElement[] st = Thread.currentThread().getStackTrace();
for(StackTraceElement e : st) {
if ( e.getClassName().startsWith("ed.js.engine.JSTestInstance"))
return true;
}
return false;
}
public static String getTopJS(){
StackTraceElement[] st = Thread.currentThread().getStackTrace();
for ( int i=0; i<st.length; i++ ){
StackTraceElement e = st[i];
if ( e.getClassName().startsWith( Convert.DEFAULT_PACKAGE + "." ) )
return e.getClassName();
}
return null;
}
}
|
Fix phones in update profile form | <?php
namespace Furniture\FrontendBundle\Form\Type\UserProfile;
use Furniture\CommonBundle\Form\DataTransformer\ArrayToStringTransformer;
use Furniture\RetailerBundle\Entity\RetailerUserProfile;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class RetailerUserProfileType extends AbstractType
{
/**
* {@inheritDoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => RetailerUserProfile::class
]);
}
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('position', 'text', [
'label' => 'frontend.position',
'required' => false
])
->add('phones', 'text', [
'label' => 'frontend.phones_contact',
'required' => false
]);
$builder->get('phones')->addModelTransformer(new ArrayToStringTransformer(','));
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'retailer_user_profile';
}
}
| <?php
namespace Furniture\FrontendBundle\Form\Type\UserProfile;
use Furniture\RetailerBundle\Entity\RetailerUserProfile;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class RetailerUserProfileType extends AbstractType
{
/**
* {@inheritDoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => RetailerUserProfile::class
]);
}
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('position', 'text', [
'label' => 'frontend.position',
'required' => false
])
->add('phones', 'text', [
'label' => 'frontend.phones_contact',
'required' => false
]);
$builder->get('phones')->addModelTransformer(new ArrayToStringTransformer(','));
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'retailer_user_profile';
}
}
|
Fix issue with Query.parse_chain being broken in InsertRelationCommand | class Query:
def __init__(self, ident, name, oper, value):
self.ident = ident
self.name = name
self.oper = oper
self.value = value
def test(self, prop_dict):
if self.ident is not None:
key = "%s.%s" % (self.ident, self.name)
else:
key = self.name
try:
value, tt = prop_dict[key]
except KeyError:
raise Exception("%s is not a valid property name." % key)
if self.oper == '=':
return value == self.value
if self.oper == '!=':
return value != self.value
if self.oper == '>=':
return value >= self.value
if self.oper == '>':
return value > self.value
if self.oper == '<=':
return value <= self.value
if self.oper == '<':
return value < self.value
return False
@staticmethod
def parse_chain(storage_manager, chain, type_schema, alias=None):
qc = []
for q in chain:
if type(q) == tuple:
# actual query
ident, name, oper, value = q
ident = ident or alias
tt = filter(lambda t: t[1] == name, type_schema)
if len(tt) == 0:
# no such named property
raise Exception("%s is not a valid property name." % name)
ttype = tt[0][2]
qc.append(Query(ident, name, oper, storage_manager.convert_to_value(value, ttype)))
else:
qc.append(q)
return qc
| class Query:
def __init__(self, ident, name, oper, value):
self.ident = ident
self.name = name
self.oper = oper
self.value = value
def test(self, prop_dict):
if self.ident is not None:
key = "%s.%s" % (self.ident, self.name)
else:
key = self.name
try:
value, tt = prop_dict[key]
except KeyError:
raise Exception("%s is not a valid property name." % key)
if self.oper == '=':
return value == self.value
if self.oper == '!=':
return value != self.value
if self.oper == '>=':
return value >= self.value
if self.oper == '>':
return value > self.value
if self.oper == '<=':
return value <= self.value
if self.oper == '<':
return value < self.value
return False
@staticmethod
def parse_chain(storage_manager, chain, type_schema, alias):
qc = []
for q in chain:
if type(q) == tuple:
# actual query
ident, name, oper, value = q
ident = ident or alias
tt = filter(lambda t: t[1] == name, type_schema)
if len(tt) == 0:
# no such named property
raise Exception("%s is not a valid property name." % name)
ttype = tt[0][2]
qc.append(Query(ident, name, oper, storage_manager.convert_to_value(value, ttype)))
else:
qc.append(q)
return qc
|
Send request_count and error_count outside sensor_data | import json
import requests
import time
from collections import Counter
from multiprocessing import Process, Queue
from queue import Empty
shared_queue = None
def datetime_by_minute(dt):
return dt.replace(second=0, microsecond=0).isoformat() + 'Z'
def process_jobs(url, app_id, queue):
while True:
time.sleep(60)
by_minute = {}
while True:
try:
i = queue.get_nowait()
except Empty:
break
minute = datetime_by_minute(i['timestamp'])
endpoint = i['endpoint']
if (minute, endpoint) not in by_minute:
by_minute[(minute, endpoint)] = {
'sensor_data': Counter(),
'timestamp': minute,
'endpoint': endpoint,
'request_count': 0,
'error_count': 0,
}
minute_data = by_minute[(minute, endpoint)]
minute_data['request_count'] += i['request_count']
minute_data['error_count'] += i['error_count']
minute_data['sensor_data']['total_time'] += i['total_time']
if not by_minute:
continue
data = {
'app_name': app_id,
'by_minute': list(by_minute.values()),
}
requests.post(url, data=json.dumps(data))
def start_worker(url, app_id):
q = Queue()
p = Process(target=process_jobs, args=(url, app_id, q, ))
p.start()
global shared_queue
shared_queue = q
| import json
import requests
import time
from collections import Counter
from multiprocessing import Process, Queue
from queue import Empty
shared_queue = None
def datetime_by_minute(dt):
return dt.replace(second=0, microsecond=0).isoformat() + 'Z'
def process_jobs(url, app_id, queue):
while True:
time.sleep(60)
by_minute = {}
while True:
try:
i = queue.get_nowait()
except Empty:
break
minute = datetime_by_minute(i['timestamp'])
endpoint = i['endpoint']
if (minute, endpoint) not in by_minute:
by_minute[(minute, endpoint)] = {
'sensor_data': Counter(),
'timestamp': minute,
'endpoint': endpoint,
}
sensor_data = by_minute[(minute, endpoint)]['sensor_data']
sensor_data['request_count'] += i['request_count']
sensor_data['error_count'] += i['error_count']
sensor_data['total_time'] += i['total_time']
if not by_minute:
continue
data = {
'app_name': app_id,
'by_minute': list(by_minute.values()),
}
requests.post(url, data=json.dumps(data))
def start_worker(url, app_id):
q = Queue()
p = Process(target=process_jobs, args=(url, app_id, q, ))
p.start()
global shared_queue
shared_queue = q
|
Create with reusable builder functions.
Use `new Function`, but use it to build a builder you can reuse instead
of building a function each time. Got this from Cadence fiddling.
% node benchmark/increment/create.js
_adhere create 1 x 467,669 ops/sec ยฑ0.66% (97 runs sampled)
adhere create 1 x 5,753,834 ops/sec ยฑ1.31% (88 runs sampled)
_adhere create 2 x 492,043 ops/sec ยฑ1.13% (94 runs sampled)
adhere create 2 x 5,946,135 ops/sec ยฑ0.54% (98 runs sampled)
_adhere create 3 x 491,064 ops/sec ยฑ1.03% (94 runs sampled)
adhere create 3 x 5,883,240 ops/sec ยฑ0.26% (97 runs sampled)
_adhere create 4 x 492,675 ops/sec ยฑ0.91% (94 runs sampled)
adhere create 4 x 5,878,618 ops/sec ยฑ0.41% (96 runs sampled)
Fastest is adhere create 2 | var builders = []
module.exports = function (method, additional, f) {
if (arguments.length == 2) {
f = additional
additional = 0
}
// Preserving arity costs next to nothing; the call to `execute` in
// these functions will be inlined. The airty function itself will never
// be inlined because it is in a different context than that of our
// dear user, but it will be compiled.
// Avert your eyes if you're squeamish.
while (builders.length < method.length + additional + 1) {
var args = []
for (var i = 0, I = builders.length; i < I; i++) {
args[i] = '_' + i
}
var builder = (new Function('', ' \n\
return function (f) { \n\
return function (' + args.join(',') + ') { \n\
var vargs = new Array \n\
for (var i = 0, I = arguments.length; i < I; i++) { \n\
vargs.push(arguments[i]) \n\
} \n\
f(this, vargs) \n\
} \n\
} \n\
'))()
builders.push(builder)
}
var adherence = builders[method.length + additional](f)
adherence.toString = function () { return method.toString() }
return adherence
}
| module.exports = function (method, additional, f) {
if (arguments.length == 2) {
f = additional
additional = 0
}
// Preserving arity costs next to nothing; the call to `execute` in
// these functions will be inlined. The airty function itself will never
// be inlined because it is in a different context than that of our
// dear user, but it will be compiled.
// Avert your eyes if you're squeamish.
var args = []
for (var i = 0, I = method.length + additional; i < I; i++) {
args[i] = '_' + i
}
var adherence = (new Function('f', ' \n\
return function (' + args.join(',') + ') { \n\
var vargs = new Array \n\
for (var i = 0, I = arguments.length; i < I; i++) { \n\
vargs.push(arguments[i]) \n\
} \n\
f(this, vargs) \n\
} \n\
'))(f)
adherence.toString = function () { return method.toString() }
return adherence
}
|
Use open and close function | angular.module('mwUI.UiComponents')
//TODO rename to mwCollapsible
.directive('mwCollapsable', function () {
return {
transclude: true,
scope: {
mwCollapsable: '=',
title: '@mwTitle'
},
templateUrl: 'uikit/mw-ui-components/directives/templates/mw_collapsible.html',
link: function (scope, el) {
scope.viewModel = {};
scope.viewModel.collapsed = false;
var getHeight = function (el) {
var totalHeight = 0;
el.children().filter(':visible').each(function () {
totalHeight += angular.element(this).outerHeight(true);
});
return totalHeight;
};
var open = function(){
var collapsedBody = el.find('.mw-collapsible-body');
collapsedBody.css('max-height', getHeight(collapsedBody));
scope.viewModel.collapsed = false;
};
var close = function(){
var collapsedBody = el.find('.mw-collapsible-body');
collapsedBody.css('max-height', 0);
scope.viewModel.collapsed = true;
};
scope.toggle = function () {
if (scope.mwCollapsable === false) {
close();
} else {
open();
}
};
scope.$watch('mwCollapsable', function () {
if (scope.mwCollapsable === false) {
close();
} else {
open();
}
});
}
};
}); | angular.module('mwUI.UiComponents')
//TODO rename to mwCollapsible
.directive('mwCollapsable', function () {
return {
transclude: true,
scope: {
mwCollapsable: '=',
title: '@mwTitle'
},
templateUrl: 'uikit/mw-ui-components/directives/templates/mw_collapsible.html',
link: function (scope, el) {
scope.viewModel = {};
scope.viewModel.collapsed = false;
var getHeight = function (el) {
var totalHeight = 0;
el.children().filter(':visible').each(function () {
totalHeight += angular.element(this).outerHeight(true);
});
return totalHeight;
};
scope.toggle = function () {
var collapsedBody = el.find('.mw-collapsible-body'),
maxHeight;
if (!scope.viewModel.collapsed) {
maxHeight = getHeight(collapsedBody);
} else {
maxHeight = 0;
}
collapsedBody.css('max-height', maxHeight);
scope.viewModel.collapsed = !scope.viewModel.collapsed;
};
scope.$watch('mwCollapsable', function () {
if (scope.mwCollapsable === false) {
scope.viewModel.collapsed = true;
} else {
scope.viewModel.collapsed = false;
}
});
}
};
}); |
Read and write as binary. | <?php
namespace Orbt\ResourceMirror\Resource;
use Orbt\ResourceMirror\Exception\ReplicatorException;
/**
* Basic replicator implementation using file operations to replicate.
*/
class FileReplicator implements Replicator
{
/**
* Base URL.
* @var string
*/
protected $baseUrl;
/**
* Target directory.
* @var string
*/
protected $directory;
/**
* Constructs a file replicator.
*/
public function __construct($baseUrl, $directory)
{
$this->baseUrl = rtrim($baseUrl, '/').'/';
$this->directory = rtrim($directory, '\\/').'/';
}
/**
* {@inheritdoc}
*/
public function replicate($resource)
{
$url = $this->baseUrl.$resource->getPath();
if (!$source = @fopen($url, 'rb')) {
throw new ReplicatorException('Cannot open URL for reading.');
}
$file = $this->directory.$resource->getPath();
@mkdir(dirname($file), 0777, true);
if (!$target = @fopen($file, 'wb')) {
fclose($source);
throw new ReplicatorException('Cannot open local file for writing.');
}
stream_copy_to_stream($source, $target);
fclose($source);
fclose($target);
}
}
| <?php
namespace Orbt\ResourceMirror\Resource;
use Orbt\ResourceMirror\Exception\ReplicatorException;
/**
* Basic replicator implementation using file operations to replicate.
*/
class FileReplicator implements Replicator
{
/**
* Base URL.
* @var string
*/
protected $baseUrl;
/**
* Target directory.
* @var string
*/
protected $directory;
/**
* Constructs a file replicator.
*/
public function __construct($baseUrl, $directory)
{
$this->baseUrl = rtrim($baseUrl, '/').'/';
$this->directory = rtrim($directory, '\\/').'/';
}
/**
* {@inheritdoc}
*/
public function replicate($resource)
{
$url = $this->baseUrl.$resource->getPath();
if (!$source = @fopen($url, 'r')) {
throw new ReplicatorException('Cannot open URL for reading.');
}
$file = $this->directory.$resource->getPath();
@mkdir(dirname($file), 0777, true);
if (!$target = @fopen($file, 'w')) {
fclose($source);
throw new ReplicatorException('Cannot open local file for writing.');
}
stream_copy_to_stream($source, $target);
fclose($source);
fclose($target);
}
}
|
Replace %(module)s with %(pathname)s in DEFAULT_KVP_FORMAT
The pathname gives more context in large projects that contains repeated module
names (eg models, base, etc). |
DEFAULT_LOGGING_CONF = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {'format': '%(asctime)s %(module)s %(message)s'},
},
'filters': {
'logger_filter': {
'()': 'belogging.filters.LoggerFilter',
},
},
'handlers': {
'default': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'default',
'filters': ['logger_filter'],
},
'null': {
'class': 'logging.NullHandler',
},
},
'root': {
'handlers': ['default'],
'level': 'DEBUG',
},
'loggers': {},
}
DEFAULT_KVP_FORMAT = 'asctime=%(asctime)s level=%(levelname)s pathname=%(pathname)s line=%(lineno)s message=%(message)s'
LEVEL_MAP = {'DISABLED': 60,
'CRITICAL': 50,
'FATAL': 50,
'ERROR': 40,
'WARNING': 30,
'WARN': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0}
|
DEFAULT_LOGGING_CONF = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {'format': '%(asctime)s %(module)s %(message)s'},
},
'filters': {
'logger_filter': {
'()': 'belogging.filters.LoggerFilter',
},
},
'handlers': {
'default': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'default',
'filters': ['logger_filter'],
},
'null': {
'class': 'logging.NullHandler',
},
},
'root': {
'handlers': ['default'],
'level': 'DEBUG',
},
'loggers': {},
}
DEFAULT_KVP_FORMAT = 'asctime=%(asctime)s level=%(levelname)s module=%(module)s line=%(lineno)s message=%(message)s'
LEVEL_MAP = {'DISABLED': 60,
'CRITICAL': 50,
'FATAL': 50,
'ERROR': 40,
'WARNING': 30,
'WARN': 30,
'INFO': 20,
'DEBUG': 10,
'NOTSET': 0}
|
Add negative delta to avoid stopping the processor immediately | package org.yamcs.studio.ui.archive;
import java.util.List;
import javax.swing.SwingUtilities;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.yamcs.studio.core.TimeCatalogue;
public class CreateReplayHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchPart part = HandlerUtil.getActivePartChecked(event);
SwingUtilities.invokeLater(() -> {
ArchiveView view = (ArchiveView) part;
long missionTime = TimeCatalogue.getInstance().getMissionTime(true);
missionTime -= 30 * 1000;
TimeInterval interval = TimeInterval.starting(missionTime);
List<String> packets = view.archivePanel.getSelectedPackets("tm");
List<String> pps = view.archivePanel.getSelectedPackets("pp");
Display.getDefault().asyncExec(() -> {
CreateReplayDialog dialog = new CreateReplayDialog(Display.getCurrent().getActiveShell());
dialog.initialize(interval, packets, pps);
dialog.open();
});
});
return null;
}
}
| package org.yamcs.studio.ui.archive;
import java.util.List;
import javax.swing.SwingUtilities;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.yamcs.studio.core.TimeCatalogue;
public class CreateReplayHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchPart part = HandlerUtil.getActivePartChecked(event);
SwingUtilities.invokeLater(() -> {
ArchiveView view = (ArchiveView) part;
long missionTime = TimeCatalogue.getInstance().getMissionTime(true);
TimeInterval interval = TimeInterval.starting(missionTime);
List<String> packets = view.archivePanel.getSelectedPackets("tm");
List<String> pps = view.archivePanel.getSelectedPackets("pp");
Display.getDefault().asyncExec(() -> {
CreateReplayDialog dialog = new CreateReplayDialog(Display.getCurrent().getActiveShell());
dialog.initialize(interval, packets, pps);
dialog.open();
});
});
return null;
}
}
|
Add opt in/out keywords for tropo | from urllib import urlencode
from urllib2 import urlopen
from corehq.apps.sms.util import clean_phone_number
from corehq.apps.sms.models import SQLSMSBackend
from dimagi.ext.couchdbkit import *
from corehq.messaging.smsbackends.tropo.forms import TropoBackendForm
from django.conf import settings
class SQLTropoBackend(SQLSMSBackend):
class Meta:
app_label = 'sms'
proxy = True
@classmethod
def get_available_extra_fields(cls):
return [
'messaging_token',
]
@classmethod
def get_api_id(cls):
return 'TROPO'
@classmethod
def get_generic_name(cls):
return "Tropo"
@classmethod
def get_form_class(cls):
return TropoBackendForm
def get_sms_rate_limit(self):
return 60
@classmethod
def get_opt_in_keywords(cls):
return ['START']
@classmethod
def get_opt_out_keywords(cls):
return ['STOP']
def send(self, msg, *args, **kwargs):
phone_number = clean_phone_number(msg.phone_number)
text = msg.text.encode('utf-8')
config = self.config
params = urlencode({
'action': 'create',
'token': config.messaging_token,
'numberToDial': phone_number,
'msg': text,
'_send_sms': 'true',
})
url = 'https://api.tropo.com/1.0/sessions?%s' % params
response = urlopen(url, timeout=settings.SMS_GATEWAY_TIMEOUT).read()
return response
| from urllib import urlencode
from urllib2 import urlopen
from corehq.apps.sms.util import clean_phone_number
from corehq.apps.sms.models import SQLSMSBackend
from dimagi.ext.couchdbkit import *
from corehq.messaging.smsbackends.tropo.forms import TropoBackendForm
from django.conf import settings
class SQLTropoBackend(SQLSMSBackend):
class Meta:
app_label = 'sms'
proxy = True
@classmethod
def get_available_extra_fields(cls):
return [
'messaging_token',
]
@classmethod
def get_api_id(cls):
return 'TROPO'
@classmethod
def get_generic_name(cls):
return "Tropo"
@classmethod
def get_form_class(cls):
return TropoBackendForm
def get_sms_rate_limit(self):
return 60
def send(self, msg, *args, **kwargs):
phone_number = clean_phone_number(msg.phone_number)
text = msg.text.encode('utf-8')
config = self.config
params = urlencode({
'action': 'create',
'token': config.messaging_token,
'numberToDial': phone_number,
'msg': text,
'_send_sms': 'true',
})
url = 'https://api.tropo.com/1.0/sessions?%s' % params
response = urlopen(url, timeout=settings.SMS_GATEWAY_TIMEOUT).read()
return response
|
[BUGFIX] Check for existance of $releasesList[0] before using | <?php
namespace Deployer;
task('buffer:stop', function () {
$releasesList = get('releases_list');
// Remove lock files also from previous release because it can be still read by apache/nginx after switching.
// get('releases_list') is cached by deployer on first call in other task so it does not have the latest release
// this is why $releasesList[0] have last release and not current.
$overwriteReleases = ['current'];
if (isset($releasesList[0])) {
$overwriteReleases[] = 'releases/' . $releasesList[0];
}
foreach ($overwriteReleases as $overwriteRelease) {
$overwriteReleasePath = get('deploy_path') . '/' . $overwriteRelease;
foreach (get('buffer_config') as $key => $buffer) {
if (!isset($buffer['entrypoint_filename'])) {
throw new \RuntimeException('entrypoint_filename not set for buffer_data');
}
$entrypointFilename = $buffer['entrypoint_filename'];
if (isset($buffer['locker_filename'])) {
$lockerFilename = $buffer['locker_filename'];
} else {
$lockerFilename = 'buffer.lock';
}
if (dirname($entrypointFilename) != '.') {
$entrypointDirectory = dirname($entrypointFilename) . '/';
} else {
$entrypointDirectory = '';
}
run('cd ' . $overwriteReleasePath . ' && rm -f {{web_path}}' . $entrypointDirectory . $lockerFilename);
}
}
})->desc('Stop buffering reqests to application entrypoints.');
| <?php
namespace Deployer;
task('buffer:stop', function () {
$releasesList = get('releases_list');
// Remove lock files also from previous release because it can be still read by apache/nginx after switching.
// get('releases_list') is cached by deployer on first call in other task so it does not have the latest release
// this is why $releasesList[0] have last release and not current.
$overwriteReleases = ['current'];
if (!empty($releasesList[0])) {
$overwriteReleases[] = $releasesList[0];
}
foreach ($overwriteReleases as $overwriteRelease) {
$overwriteReleasePath = get('deploy_path') . '/' . $overwriteRelease;
foreach (get('buffer_config') as $key => $buffer) {
if (!isset($buffer['entrypoint_filename'])) {
throw new \RuntimeException('entrypoint_filename not set for buffer_data');
}
$entrypointFilename = $buffer['entrypoint_filename'];
if (isset($buffer['locker_filename'])) {
$lockerFilename = $buffer['locker_filename'];
} else {
$lockerFilename = 'buffer.lock';
}
if (dirname($entrypointFilename) != '.') {
$entrypointDirectory = dirname($entrypointFilename) . '/';
} else {
$entrypointDirectory = '';
}
run('cd ' . $overwriteReleasePath . ' && rm -f {{web_path}}' . $entrypointDirectory . $lockerFilename);
}
}
})->desc('Stop buffering reqests to application entrypoints.');
|
Set completions meta-text styling to match | from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.Meta.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Meta: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
| from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style = pygments.styles.get_style_by_name('native')
class PGStyle(Style):
styles = {}
styles.update(style.styles)
styles.update(default_style_extensions)
styles.update({
Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
Token.Menu.Completions.ProgressButton: 'bg:#003333',
Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
Token.SelectedText: '#ffffff bg:#6666aa',
Token.IncrementalSearchMatch: '#ffffff bg:#4444aa',
Token.IncrementalSearchMatch.Current: '#ffffff bg:#44aa44',
Token.Toolbar: 'bg:#440044 #ffffff',
Token.Toolbar: 'bg:#222222 #aaaaaa',
Token.Toolbar.Off: 'bg:#222222 #888888',
Token.Toolbar.On: 'bg:#222222 #ffffff',
})
return PGStyle
|
Update SystemMessage, replace existing message with new payload | // Copyright 2016 David Lavieri. All rights reserved.
// Use of this source code is governed by a MIT License
// License that can be found in the LICENSE file.
import * as types from './../constants/system_message';
const initialState = [];
export {initialState};
export default (state = initialState, action) => {
switch(action.type) {
case types.ADD: {
let match = false;
const newState = state.map(message => {
if(message.code === action.payload.code) {
match = true;
return {
...action.payload,
count: message.count ? message.count + 1 : 1
}
}
return message;
});
if(match) {
return newState;
}
return [{
...action.payload,
count: 1
},
...newState
];
}
case types.DELETE:
return state.filter(message => message.code !== action.payload);
default:
return state;
}
}
| // Copyright 2016 David Lavieri. All rights reserved.
// Use of this source code is governed by a MIT License
// License that can be found in the LICENSE file.
import * as types from './../constants/system_message';
const initialState = [];
export {initialState};
export default (state = initialState, action) => {
switch(action.type) {
case types.ADD: {
let match = false;
const newState = state.map(message => {
if(message.code === action.payload.code) {
match = true;
return {
...message,
count: message.count ? message.count + 1 : 1
}
}
return message;
});
if(match) {
return newState;
}
return [{
...action.payload,
count: 1
},
...newState
];
}
case types.DELETE:
return state.filter(message => message.code !== action.payload);
default:
return state;
}
}
|
Use the webserver module, which means the script is now cross-platform. Hooray, Python\! | #!/usr/bin/env python
import re
import webbrowser
import urlparse
import platform
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class OpenRemoteHandler(BaseHTTPRequestHandler):
def do_GET(self):
url = ''
try:
request_url = urlparse.urlsplit(self.path)
if re.search('openurl', request_url.path):
query = urlparse.parse_qs(request_url.query)
url = query["url"][0]
webbrowser.open_new_tab(url)
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("Opened %s on %s" % (url, platform.node()))
else:
self.send_error(404)
except:
self.send_error(500,'Failed to open url: %s, error: %s' % (url, str(sys.exc_info()[1])))
def main():
try:
server = HTTPServer(('', 8080), OpenRemoteHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
import sys
import re
import subprocess
import urlparse
import platform
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class OpenRemoteHandler(BaseHTTPRequestHandler):
def do_GET(self):
url = ''
try:
request_url = urlparse.urlsplit(self.path)
if re.search('openurl', request_url.path):
query = urlparse.parse_qs(request_url.query)
url = query["url"][0]
subprocess.check_call(["xdg-open", url])
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("Opened %s on %s" % (url, platform.node()))
else:
self.send_error(404)
except:
self.send_error(500,'Failed to open url: %s, error: %s' % (url, str(sys.exc_info()[1])))
def main():
try:
server = HTTPServer(('', 8080), OpenRemoteHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
if __name__ == '__main__':
main()
|
Remove Emulation logs directory one time at the beggining of the test suite | <?php
namespace Ivory\GoogleMapBundle\Tests\Emulation;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\HttpKernel\Util\Filesystem;
/**
* Web test case
*
* @author GeLo <[email protected]>
*/
class WebTestCase extends BaseWebTestCase
{
/**
* @var boolean TRUE if the web test case has been initialized else FALSE
*/
protected static $initialize = array();
/**
* Remove emulation cache & logs directories for the given environment
*
* @param string $environment
*/
protected static function initialize($environment)
{
if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment]))
{
$filesystem = new Filesystem();
$filesystem->remove(__DIR__.'/cache/'.$environment);
if(empty(self::$initialize))
$filesystem->remove(__DIR__.'/logs');
self::$initialize[$environment] = true;
}
}
/**
*@override
*/
protected static function getKernelClass()
{
$kernelClass = 'AppKernel';
require_once __DIR__.'/'.$kernelClass.'.php';
return $kernelClass;
}
/**
* Gets the kernel container
*
* @return Symfony\Component\DependencyInjection\ContainerInterface
*/
public static function createContainer(array $options = array('environment' => 'default'))
{
self::initialize($options['environment']);
$kernel = self::createKernel($options);
$kernel->boot();
return $kernel->getContainer();
}
}
| <?php
namespace Ivory\GoogleMapBundle\Tests\Emulation;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\HttpKernel\Util\Filesystem;
/**
* Web test case
*
* @author GeLo <[email protected]>
*/
class WebTestCase extends BaseWebTestCase
{
/**
* @var boolean TRUE if the web test case has been initialized else FALSE
*/
protected static $initialize = array();
/**
* Remove emulation cache & logs directories
*
* @param string $environment
*/
protected static function initialize($environment)
{
if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment]))
{
$filesystem = new Filesystem();
$filesystem->remove(__DIR__.'/cache/'.$environment);
$filesystem->remove(__DIR__.'/logs');
self::$initialize[$environment] = true;
}
}
/**
*@override
*/
protected static function getKernelClass()
{
$kernelClass = 'AppKernel';
require_once __DIR__.'/'.$kernelClass.'.php';
return $kernelClass;
}
/**
* Gets the kernel container
*
* @return Symfony\Component\DependencyInjection\ContainerInterface
*/
public static function createContainer(array $options = array('environment' => 'default'))
{
self::initialize($options['environment']);
$kernel = self::createKernel($options);
$kernel->boot();
return $kernel->getContainer();
}
}
|
Revert omission of image size
Turns out this is still required in SVG mode :D | <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Emoji\Listener;
use Flarum\Event\ConfigureFormatter;
use Illuminate\Contracts\Events\Dispatcher;
class FormatEmoticons
{
/**
* @param Dispatcher $events
*/
public function subscribe(Dispatcher $events)
{
$events->listen(ConfigureFormatter::class, [$this, 'addEmoticons']);
}
/**
* @param ConfigureFormatter $event
*/
public function addEmoticons(ConfigureFormatter $event)
{
$event->configurator->Emoji->useEmojiOne();
$event->configurator->Emoji->omitImageSize();
$event->configurator->Emoji->useSVG();
$event->configurator->Emoji->addAlias(':)', '๐');
$event->configurator->Emoji->addAlias(':D', '๐');
$event->configurator->Emoji->addAlias(':P', '๐');
$event->configurator->Emoji->addAlias(':(', '๐');
$event->configurator->Emoji->addAlias(':|', '๐');
$event->configurator->Emoji->addAlias(';)', '๐');
$event->configurator->Emoji->addAlias(':\'(', '๐ข');
$event->configurator->Emoji->addAlias(':O', '๐ฎ');
$event->configurator->Emoji->addAlias('>:(', '๐ก');
}
}
| <?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Emoji\Listener;
use Flarum\Event\ConfigureFormatter;
use Illuminate\Contracts\Events\Dispatcher;
class FormatEmoticons
{
/**
* @param Dispatcher $events
*/
public function subscribe(Dispatcher $events)
{
$events->listen(ConfigureFormatter::class, [$this, 'addEmoticons']);
}
/**
* @param ConfigureFormatter $event
*/
public function addEmoticons(ConfigureFormatter $event)
{
$event->configurator->Emoji->useEmojiOne();
$event->configurator->Emoji->useSVG();
$event->configurator->Emoji->addAlias(':)', '๐');
$event->configurator->Emoji->addAlias(':D', '๐');
$event->configurator->Emoji->addAlias(':P', '๐');
$event->configurator->Emoji->addAlias(':(', '๐');
$event->configurator->Emoji->addAlias(':|', '๐');
$event->configurator->Emoji->addAlias(';)', '๐');
$event->configurator->Emoji->addAlias(':\'(', '๐ข');
$event->configurator->Emoji->addAlias(':O', '๐ฎ');
$event->configurator->Emoji->addAlias('>:(', '๐ก');
}
}
|
Exit if no accounts need to be repaired | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Entities\Accounts\Models\Account;
use App\Entities\Groups\Models\Group;
use Illuminate\Support\Facades\DB;
final class RepairMissingGroupsCOmmand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'groups:assign';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Finds any accounts without a group assigned, and assigns them to the default groups';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$accountsWithoutGroups = Account::doesntHave('groups')->get();
if (count($accountsWithoutGroups) === 0) {
$this->info('No accounts need to be assigned a group');
return;
}
$defaultGroupIds = Group::where('is_default', 1)->get()->pluck('group_id');
$progressBar = $this->output->createProgressBar(count($accountsWithoutGroups));
$progressBar->start();
DB::transaction(function() use($accountsWithoutGroups, $defaultGroupIds, &$progressBar) {
foreach ($accountsWithoutGroups as $account) {
$account->groups()->attach($defaultGroupIds);
$progressBar->advance();
}
});
$this->info(count($accountsWithoutGroups) . ' accounts assigned to a default group');
$progressBar->finish();
}
} | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Entities\Accounts\Models\Account;
use App\Entities\Groups\Models\Group;
use Illuminate\Support\Facades\DB;
final class RepairMissingGroupsCOmmand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'groups:assign';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Finds any accounts without a group assigned, and assigns them to the default groups';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$accountsWithoutGroups = Account::doesntHave('groups')->get();
$defaultGroupIds = Group::where('is_default', 1)->get()->pluck('group_id');
$progressBar = $this->output->createProgressBar(count($accountsWithoutGroups));
$progressBar->start();
DB::transaction(function() use($accountsWithoutGroups, $defaultGroupIds, &$progressBar) {
foreach ($accountsWithoutGroups as $account) {
$account->groups()->attach($defaultGroupIds);
$progressBar->advance();
}
});
$this->info(count($accountsWithoutGroups) . ' accounts assigned to a default group');
$progressBar->finish();
}
} |
Set the default bouncetime value to -666
Set the default bouncetime to -666 (the default value -666 is in Rpi.GPIO source code).
As-Is: if the bouncetime is not set, your setting for event detecting is silently down. And there is no notification that bouncetime is required. | from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
'BOTH': self.gpio.BOTH
}
def build_event_callback(self, num, name, event):
def event_callback(num):
data = {
'num': num,
'name': name,
'event': event
}
self.socketio.emit('pin:event', data)
print(data)
return event_callback
def register_gpio_events(self):
for num, config in self.pins.items():
event = config.get('event', None)
name = config.get('name', '')
if event:
edge = self.edge[event]
bounce = config.get('bounce', -666)
cb = self.build_event_callback(num, name, event)
self.gpio.add_event_detect(num, edge, callback=cb, bouncetime=bounce)
| from pi_gpio import socketio
from config.pins import PinManager
class PinEventManager(PinManager):
def __init__(self):
super(PinEventManager, self).__init__()
self.socketio = socketio
self.edge = {
'RISING': self.gpio.RISING,
'FALLING': self.gpio.FALLING,
'BOTH': self.gpio.BOTH
}
def build_event_callback(self, num, name, event):
def event_callback(num):
data = {
'num': num,
'name': name,
'event': event
}
self.socketio.emit('pin:event', data)
print(data)
return event_callback
def register_gpio_events(self):
for num, config in self.pins.items():
event = config.get('event', None)
name = config.get('name', '')
if event:
edge = self.edge[event]
bounce = config['bounce']
cb = self.build_event_callback(num, name, event)
self.gpio.add_event_detect(num, edge, callback=cb, bouncetime=bounce)
|
Attach the current timestamp to each RTI model | define(['MoxieModel', 'underscore', 'moxie.conf'], function(MoxieModel, _, conf) {
var testDelayed = function(estTime) {
return !((estTime.indexOf('On time') === 0) || (estTime.indexOf('Starts here') === 0));
};
var RTIModel = MoxieModel.extend({
url: function() {
return conf.endpoint + this.get('href');
},
parse: function(data) {
data.lastUpdated = new Date().getTime();
return data;
}
});
var RTIModels = {
'bus': RTIModel,
'rail-arrivals': RTIModel.extend({
parse: function(data) {
_.each(data.services, function(service) {
service.delayed = false;
if (service.etd) {
service.delayed = testDelayed(service.etd);
} else if (service.eta) {
service.delayed = testDelayed(service.eta);
}
});
return RTIModel.prototype.parse.apply(this, [data]);
}
}),
'p-r': RTIModel
};
// Departures uses the same model as arrivals
RTIModels['rail-departures'] = RTIModels['rail-arrivals'];
return RTIModels;
});
| define(['MoxieModel', 'underscore', 'moxie.conf'], function(MoxieModel, _, conf) {
var testDelayed = function(estTime) {
return !((estTime.indexOf('On time') === 0) || (estTime.indexOf('Starts here') === 0));
};
var RTIModel = MoxieModel.extend({
url: function() {
return conf.endpoint + this.get('href');
}
});
var RTIModels = {
'bus': RTIModel,
'rail-arrivals': RTIModel.extend({
parse: function(data) {
_.each(data.services, function(service) {
service.delayed = false;
if (service.etd) {
service.delayed = testDelayed(service.etd);
} else if (service.eta) {
service.delayed = testDelayed(service.eta);
}
});
return data;
}
}),
'p-r': RTIModel
};
// Departures uses the same model as arrivals
RTIModels['rail-departures'] = RTIModels['rail-arrivals'];
return RTIModels;
});
|
Fix test.We have new default handler, so handlers list size must updated.
git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@1808 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba | package org.codehaus.xfire.transport.http;
import org.codehaus.xfire.addressing.AddressingInHandler;
import org.codehaus.xfire.addressing.AddressingOutHandler;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.ServiceRegistry;
import org.codehaus.xfire.test.AbstractServletTest;
import com.meterware.httpunit.HttpNotFoundException;
public class XFireConfigurableServletNewTest
extends AbstractServletTest
{
public void testServlet()
throws Exception
{
try
{
newClient().getResponse("http://localhost/services/");
}
catch(HttpNotFoundException e) {}
ServiceRegistry reg = getXFire().getServiceRegistry();
assertTrue(reg.hasService("Echo"));
Service echo = reg.getService("Echo");
assertNotNull(echo.getName());
assertNotSame("", echo.getName().getNamespaceURI());
assertTrue(reg.hasService("Echo1"));
Service echo1 = reg.getService("Echo1");
assertNotNull(echo1.getBinding(SoapHttpTransport.SOAP12_HTTP_BINDING));
assertEquals(3, echo1.getInHandlers().size());
assertTrue(echo1.getInHandlers().get(2) instanceof AddressingInHandler);
assertEquals(2, echo1.getOutHandlers().size());
assertTrue(echo1.getOutHandlers().get(1) instanceof AddressingOutHandler);
assertEquals(2, getXFire().getInHandlers().size());
}
protected String getConfiguration()
{
return "/org/codehaus/xfire/transport/http/configurable-web.xml";
}
} | package org.codehaus.xfire.transport.http;
import org.codehaus.xfire.addressing.AddressingInHandler;
import org.codehaus.xfire.addressing.AddressingOutHandler;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.ServiceRegistry;
import org.codehaus.xfire.test.AbstractServletTest;
import com.meterware.httpunit.HttpNotFoundException;
public class XFireConfigurableServletNewTest
extends AbstractServletTest
{
public void testServlet()
throws Exception
{
try
{
newClient().getResponse("http://localhost/services/");
}
catch(HttpNotFoundException e) {}
ServiceRegistry reg = getXFire().getServiceRegistry();
assertTrue(reg.hasService("Echo"));
Service echo = reg.getService("Echo");
assertNotNull(echo.getName());
assertNotSame("", echo.getName().getNamespaceURI());
assertTrue(reg.hasService("Echo1"));
Service echo1 = reg.getService("Echo1");
assertNotNull(echo1.getBinding(SoapHttpTransport.SOAP12_HTTP_BINDING));
assertEquals(2, echo1.getInHandlers().size());
assertTrue(echo1.getInHandlers().get(1) instanceof AddressingInHandler);
assertEquals(2, echo1.getOutHandlers().size());
assertTrue(echo1.getOutHandlers().get(1) instanceof AddressingOutHandler);
assertEquals(2, getXFire().getInHandlers().size());
}
protected String getConfiguration()
{
return "/org/codehaus/xfire/transport/http/configurable-web.xml";
}
} |
Fix link to medias in UserCard | import React from 'react'
import style from './style.styl'
import avatarUrl from '../../utils/avatarUrl.js'
import Link from 'react-router/Link'
const UserCard = ({id, name, gender, mediaCount, likeCount, dislikeCount}) => (
<div className={style.card}>
<img src={avatarUrl(id)} />
<div className={style.content}>
<h1>{name}</h1>
<div className={style.infos}>
<Link
className={style.boxCount}
activeClassName={style.active}
to={`/u/${id}`}
>
<div className={style.count}>{mediaCount}</div>
<div className={style.label}>Posts</div>
</Link>
<Link
className={style.boxCount}
activeClassName={style.active}
to={`/u/${id}/likes`}
>
<div className={style.count}>{likeCount}</div>
<div className={style.label}>Likes ๐</div>
</Link>
<Link
className={style.boxCount}
activeClassName={style.active}
to={`/u/${id}/dislikes`}
>
<div className={style.count}>{dislikeCount}</div>
<div className={style.label}>Dislikes ๐</div>
</Link>
</div>
</div>
</div>
)
export default UserCard
| import React from 'react'
import style from './style.styl'
import avatarUrl from '../../utils/avatarUrl.js'
import Link from 'react-router/Link'
const UserCard = ({id, name, gender, mediaCount, likeCount, dislikeCount}) => (
<div className={style.card}>
<img src={avatarUrl(id)} />
<div className={style.content}>
<h1>{name}</h1>
<div className={style.infos}>
<Link
className={style.boxCount}
activeClassName={style.active}
to={`/u/${id}/`}
>
<div className={style.count}>{mediaCount}</div>
<div className={style.label}>Posts</div>
</Link>
<Link
className={style.boxCount}
activeClassName={style.active}
to={`/u/${id}/likes`}
>
<div className={style.count}>{likeCount}</div>
<div className={style.label}>Likes ๐</div>
</Link>
<Link
className={style.boxCount}
activeClassName={style.active}
to={`/u/${id}/dislikes`}
>
<div className={style.count}>{dislikeCount}</div>
<div className={style.label}>Dislikes ๐</div>
</Link>
</div>
</div>
</div>
)
export default UserCard
|
Remove extra parenthesis on subscribe page | @extends('layout.master')
@section('title', trans('cachet.subscriber.subscribe'). " | ". $siteTitle)
@section('description', trans('cachet.meta.description.subscribe', ['app' => $siteTitle]))
@section('content')
<div class="pull-right">
<p><a class="btn btn-success btn-outline" href="{{ cachet_route('status-page') }}"><i class="ion ion-home"></i></a></p>
</div>
<div class="clearfix"></div>
@include('partials.errors')
<div class="row">
<div class="col-xs-12 col-lg-offset-2 col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">{{ trans('cachet.subscriber.subscribe') }}</div>
<div class="panel-body">
<form action="{{ cachet_route('subscribe', [], 'post') }}" method="POST" class="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success">{{ trans('cachet.subscriber.button') }}</button>
</form>
</div>
</div>
</div>
</div>
@stop
| @extends('layout.master')
@section('title', trans('cachet.subscriber.subscribe'). " | ". $siteTitle))
@section('description', trans('cachet.meta.description.subscribe', ['app' => $siteTitle]))
@section('content')
<div class="pull-right">
<p><a class="btn btn-success btn-outline" href="{{ cachet_route('status-page') }}"><i class="ion ion-home"></i></a></p>
</div>
<div class="clearfix"></div>
@include('partials.errors')
<div class="row">
<div class="col-xs-12 col-lg-offset-2 col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">{{ trans('cachet.subscriber.subscribe') }}</div>
<div class="panel-body">
<form action="{{ cachet_route('subscribe', [], 'post') }}" method="POST" class="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success">{{ trans('cachet.subscriber.button') }}</button>
</form>
</div>
</div>
</div>
</div>
@stop
|
Stop the madness and put things back | (function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
return {status: 2, msg: 'Ready'};
} else {
return {status: 0, msg: 'The File APIs are not fully supported by your browser.'};
}
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
['r', '%m.k', 'k', 'heady']
],
menus: {
k: ['headx', 'heady']
}
};
ext.my_first_block = function() {
console.log("hello, world.");
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
ext.k = function(m) {
switch(m){
case 'headx': return 1;
case 'heady': return 2;
}
};
var start = function() {
alert("hello!");
};
window.onload = start;
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})({}); | (function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
return {status: 2, msg: 'Ready'};
} else {
return {status: 0, msg: 'The File APIs are not fully supported by your browser.'};
}
};
// Block and block menu descriptions
var descriptor = {
blocks: [
['', 'My First Block', 'my_first_block'],
['r', '%n ^ %n', 'power', 2, 3],
['r', '%m.k', 'k', 'heady']
],
menus: {
k: ['headx', 'heady']
}
};
ext.my_first_block = function() {
console.log("hello, world.");
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
ext.k = function(m) {
switch(m){
case 'headx': return 1;
case 'heady': return 2;
}
};
// Register the extension
ScratchExtensions.register('Kinect2Scratch', descriptor, ext);
})
({ var start = function() {
alert("hello!");
};
window.onload = start;}); |
Refactor PostgresContainer to use JDBC for database and role creation | package io.ebean.docker.commands;
import java.sql.Connection;
import java.sql.SQLException;
public abstract class JdbcBaseDbContainer extends DbContainer {
JdbcBaseDbContainer(DbConfig config) {
super(config);
this.checkConnectivityUsingAdmin = true;
}
abstract void createDatabase();
abstract void dropCreateDatabase();
@Override
public boolean startWithCreate() {
startMode = Mode.Create;
if (!startContainerWithWait()) {
return false;
}
createDatabase();
return true;
}
@Override
public boolean startWithDropCreate() {
startMode = Mode.DropCreate;
if (!startContainerWithWait()) {
return false;
}
dropCreateDatabase();
return true;
}
private boolean startContainerWithWait() {
if (singleAdminConnection()) {
return true;
}
startIfNeeded();
if (!waitForConnectivity()) {
log.warn("Failed waiting for connectivity");
return false;
}
return true;
}
protected boolean singleAdminConnection() {
try (Connection connection = dbConfig.createAdminConnection()) {
return true;
} catch (SQLException e) {
// no connectivity
return false;
}
}
@Override
public boolean waitForDatabaseReady() {
// Just rely on waitForConnectivity() instead
return true;
}
@Override
protected boolean isDatabaseReady() {
// Just rely on waitForConnectivity() instead
return true;
}
@Override
protected boolean isDatabaseAdminReady() {
// Just rely on waitForConnectivity() instead
return true;
}
}
| package io.ebean.docker.commands;
import java.sql.Connection;
import java.sql.SQLException;
public abstract class JdbcBaseDbContainer extends DbContainer {
JdbcBaseDbContainer(DbConfig config) {
super(config);
this.checkConnectivityUsingAdmin = true;
}
abstract void createDatabase();
abstract void dropCreateDatabase();
@Override
public boolean startWithCreate() {
startMode = Mode.Create;
if (!startContainerWithWait()) {
return false;
}
createDatabase();
return true;
}
@Override
public boolean startWithDropCreate() {
startMode = Mode.DropCreate;
if (!startContainerWithWait()) {
return false;
}
dropCreateDatabase();
return true;
}
private boolean startContainerWithWait() {
if (singleAdminConnection()) {
return true;
}
startIfNeeded();
if (!waitForConnectivity()) {
log.warn("Failed waiting for connectivity");
return false;
}
return true;
}
protected boolean singleAdminConnection() {
System.out.println("start" + System.currentTimeMillis());
try (Connection connection = dbConfig.createAdminConnection()) {
System.out.println("success" + System.currentTimeMillis());
return true;
} catch (SQLException e) {
System.out.println("fail" + System.currentTimeMillis());
// no connectivity
return false;
}
}
@Override
public boolean waitForDatabaseReady() {
// Just rely on waitForConnectivity() instead
return true;
}
@Override
protected boolean isDatabaseReady() {
// Just rely on waitForConnectivity() instead
return true;
}
@Override
protected boolean isDatabaseAdminReady() {
// Just rely on waitForConnectivity() instead
return true;
}
}
|
Include doubles.targets in packages list. | from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
import doubles
with open('README.md') as f:
long_description = f.read()
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
setup(
name='doubles',
version=doubles.__version__,
description='Test doubles for Python.',
long_description=long_description,
author='Jimmy Cuadra',
author_email='[email protected]',
url='https://github.com/uber/doubles',
license='MIT',
packages=['doubles', 'doubles.targets'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
entry_points = {
'pytest11': ['doubles = doubles.pytest'],
'nose.plugins.0.10': ['doubles = doubles.nose:NoseIntegration']
},
zip_safe=True,
keywords=['testing', 'test doubles', 'mocks', 'mocking', 'stubs', 'stubbing'],
classifiers=[
'Development Status :: 1 - Planning',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Testing',
]
)
| from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
import doubles
with open('README.md') as f:
long_description = f.read()
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
setup(
name='doubles',
version=doubles.__version__,
description='Test doubles for Python.',
long_description=long_description,
author='Jimmy Cuadra',
author_email='[email protected]',
url='https://github.com/uber/doubles',
license='MIT',
packages=['doubles'],
tests_require=['pytest'],
cmdclass={'test': PyTest},
entry_points = {
'pytest11': ['doubles = doubles.pytest'],
'nose.plugins.0.10': ['doubles = doubles.nose:NoseIntegration']
},
zip_safe=True,
keywords=['testing', 'test doubles', 'mocks', 'mocking', 'stubs', 'stubbing'],
classifiers=[
'Development Status :: 1 - Planning',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: Software Development :: Testing',
]
)
|
Allow Renderable name to be included in initialization data | "use strict";
const merge = require('../../../util/merge');
const {coroutine: co} = require('bluebird');
class Renderable {
constructor(data) {
this.parent = undefined;
this.data = data || {};
this.id = this.constructor.id;
this.name = (data && data.name) ? data.name : this.constructor.name;
this.templateFile = this.constructor.templateFile;
this.variables = this.constructor.variables;
}
commit() {
return this.templateFunction(this.data);
}
templateFunction() {
return this.constructor.templateFunction(this.data);
}
getTopmostParent() {
return this.parent ? this.parent.getTopmostParent() : this;
}
init(context, data={}) {
this.context = context;
this.data = merge(this.data, data);
return Promise.resolve();
}
static compileTemplate(variables, code, boilerplate) {
code = ('%>' + code + '<%')
.replace(/(<%=)(([^%]|%(?!>))*)(%>)/g, (...args) => `<% templateOut += (${args[2]});\n%>`)
.replace(/(%>)(([^<]|<(?!%))*)(<%)/g, (...args) => `templateOut += ${JSON.stringify(args[2])};\n`);
boilerplate = boilerplate || '';
return new Function(`"use strict";
return function({${variables.join()}}) {
let templateOut = '';
${boilerplate}
${code}
return templateOut;
};`)();
}
}
module.exports = Renderable;
| "use strict";
const merge = require('../../../util/merge');
const {coroutine: co} = require('bluebird');
class Renderable {
constructor(data) {
this.parent = undefined;
this.data = data || {};
this.id = this.constructor.id;
this.name = this.constructor.name;
this.templateFile = this.constructor.templateFile;
this.variables = this.constructor.variables;
}
commit() {
return this.templateFunction(this.data);
}
templateFunction() {
return this.constructor.templateFunction(this.data);
}
getTopmostParent() {
return this.parent ? this.parent.getTopmostParent() : this;
}
init(context, data={}) {
this.context = context;
this.data = merge(this.data, data);
return Promise.resolve();
}
static compileTemplate(variables, code, boilerplate) {
code = ('%>' + code + '<%')
.replace(/(<%=)(([^%]|%(?!>))*)(%>)/g, (...args) => `<% templateOut += (${args[2]});\n%>`)
.replace(/(%>)(([^<]|<(?!%))*)(<%)/g, (...args) => `templateOut += ${JSON.stringify(args[2])};\n`);
boilerplate = boilerplate || '';
return new Function(`"use strict";
return function({${variables.join()}}) {
let templateOut = '';
${boilerplate}
${code}
return templateOut;
};`)();
}
}
module.exports = Renderable;
|
Add resolve target entity to listener instead of configuration in the add resolve target entities compiler pass. | <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2017, 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\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Add resolve target entities to resolve target entity listener compiler pass
*/
class AddResolveTargetEntitiesPass implements CompilerPassInterface
{
const RESOLVE_TARGET_ENTITY_LISTENER_ID = 'doctrine.orm.listeners.resolve_target_entity';
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition(self::RESOLVE_TARGET_ENTITY_LISTENER_ID)) {
return;
}
$listenerDefinition = $container->getDefinition(self::RESOLVE_TARGET_ENTITY_LISTENER_ID);
foreach ($container->getExtensionConfig('darvin_admin') as $config) {
if (!isset($config['entity_override'])) {
continue;
}
foreach ($config['entity_override'] as $target => $replacement) {
foreach (class_implements($target) as $interface) {
if ($interface === $target.'Interface') {
$listenerDefinition->addMethodCall('addResolveTargetEntity', [
$interface,
$replacement,
[],
]);
}
}
}
}
}
}
| <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2017, 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\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Add resolve target entities compiler pass
*/
class AddResolveTargetEntitiesPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasExtension('doctrine')) {
return;
}
$resolveTargetEntities = [];
foreach ($container->getExtensionConfig('darvin_admin') as $config) {
if (!isset($config['entity_override'])) {
continue;
}
foreach ($config['entity_override'] as $target => $replacement) {
foreach (class_implements($target) as $interface) {
if ($interface === $target.'Interface') {
$resolveTargetEntities[$interface] = $replacement;
}
}
}
}
if (!empty($resolveTargetEntities)) {
$container->prependExtensionConfig('doctrine', [
'orm' => [
'resolve_target_entities' => $resolveTargetEntities,
],
]);
}
}
}
|
Replace deprecated ConfigureClientView with ConfigureWebApp again | <?php
namespace Flagrow\Analytics\Listeners;
use DirectoryIterator;
use Flarum\Event\ConfigureWebApp;
use Illuminate\Contracts\Events\Dispatcher;
use Flarum\Event\ConfigureLocales;
class AddClientAssets
{
public function subscribe(Dispatcher $events)
{
$events->listen(ConfigureWebApp::class, [$this, 'addAssets']);
$events->listen(ConfigureLocales::class, [$this, 'addLocales']);
}
public function addAssets(ConfigureWebApp $event)
{
if($event->isAdmin()) {
$event->addAssets([
__DIR__ . '/../../less/admin/analyticsPage.less',
__DIR__ . '/../../js/admin/dist/extension.js',
]);
$event->addBootstrapper('flagrow/analytics/main');
} elseif($event->isForum())
{
$event->addAssets([
__DIR__ . '/../../js/forum/dist/extension.js'
]);
$event->addBootstrapper('flagrow/analytics/main');
}
}
public function addLocales(ConfigureLocales $event)
{
foreach (new DirectoryIterator(__DIR__.'/../../locale') as $file) {
if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) {
$event->locales->addTranslations($file->getBasename('.'.$file->getExtension()), $file->getPathname());
}
}
}
}
| <?php
namespace Flagrow\Analytics\Listeners;
use DirectoryIterator;
use Flarum\Event\ConfigureClientView;
use Illuminate\Contracts\Events\Dispatcher;
use Flarum\Event\ConfigureLocales;
class AddClientAssets
{
public function subscribe(Dispatcher $events)
{
$events->listen(ConfigureClientView::class, [$this, 'addAssets']);
$events->listen(ConfigureLocales::class, [$this, 'addLocales']);
}
public function addAssets(ConfigureClientView $event)
{
if($event->isAdmin()) {
$event->addAssets([
__DIR__ . '/../../less/admin/analyticsPage.less',
__DIR__ . '/../../js/admin/dist/extension.js',
]);
$event->addBootstrapper('flagrow/analytics/main');
} elseif($event->isForum())
{
$event->addAssets([
__DIR__ . '/../../js/forum/dist/extension.js'
]);
$event->addBootstrapper('flagrow/analytics/main');
}
}
public function addLocales(ConfigureLocales $event)
{
foreach (new DirectoryIterator(__DIR__.'/../../locale') as $file) {
if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) {
$event->locales->addTranslations($file->getBasename('.'.$file->getExtension()), $file->getPathname());
}
}
}
}
|
Enhance cache to one week | 'use strict';
var express = require('express');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var passport = require('passport');
var config = require('./environment');
module.exports = function(app) {
var env = app.get('env');
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' === req.method) {
res.send(200);
} else {
next();
}
});
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
// passport config
app.use(passport.initialize());
app.use(passport.session());
// serve the files out of ./dist as our main files
app.use(express.static(__dirname + config.server.staticDir, { maxAge: '7d' }));
if ('development' === env || 'test' === env) {
app.use(morgan('dev'));
}
};
| 'use strict';
var express = require('express');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var passport = require('passport');
var config = require('./environment');
module.exports = function(app) {
var env = app.get('env');
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' === req.method) {
res.send(200);
} else {
next();
}
});
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
// passport config
app.use(passport.initialize());
app.use(passport.session());
// serve the files out of ./dist as our main files
app.use(express.static(__dirname + config.server.staticDir, { maxAge: '1d' }));
if ('development' === env || 'test' === env) {
app.use(morgan('dev'));
}
};
|
Remove error handling for now. | var fs = require('fs');
var path = require('path');
var Stream = require('stream');
function statdir(dir, names, cb) {
var entries = [];
names.forEach(function(name) {
var relName = path.join(dir, name);
fs.lstat(relName, function(err, stats) {
entries.push({name: relName, isDir: stats && stats.isDirectory()});
if (entries.length == names.length) cb(entries);
});
});
}
module.exports = function(root) {
var s = new Stream;
s.readable = true
function recurse(dir, done) {
fs.readdir(dir, function (err, names) {
// TODO: emit err
statdir(dir, names, function(entries) {
var files = entries.filter(function(entry) {
return !entry.isDir;
});
var subdirs = entries.filter(function(entry) {
return entry.isDir;
});
files.forEach(function(entry) {
s.emit('data', entry.name);
});
if (!subdirs.length) done();
subdirs.forEach(function(subdir, i) {
recurse(subdir.name, function() {
if (i == subdirs.length - 1) done();
});
});
});
});
}
recurse(root, function() {
s.emit('end');
});
return s;
}
| var fs = require('fs');
var path = require('path');
var Stream = require('stream');
function statdir(dir, names, cb) {
var entries = [];
names.forEach(function(name) {
var relName = path.join(dir, name);
fs.lstat(relName, function(err, stats) {
entries.push({name: relName, isDir: stats && stats.isDirectory()});
if (entries.length == names.length) cb(entries);
});
});
}
module.exports = function(root) {
var s = new Stream;
s.readable = true
function recurse(dir, done) {
fs.readdir(dir, function (err, names) {
// TODO: emit err
if (!names) {
done();
return;
}
statdir(dir, names, function(entries) {
var files = entries.filter(function(entry) {
return !entry.isDir;
});
var subdirs = entries.filter(function(entry) {
return entry.isDir;
});
files.forEach(function(entry) {
s.emit('data', entry.name);
});
if (!subdirs.length) done();
subdirs.forEach(function(subdir, i) {
recurse(subdir.name, function() {
if (i == subdirs.length - 1) done();
});
});
});
});
}
recurse(root, function() {
s.emit('end');
});
return s;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.