text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update dsub version to 0.3.10.dev0
PiperOrigin-RevId: 319887839 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.10.dev0'
| # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.9'
|
Fix minor code style issues | Dashboard.TickerWidget = Dashboard.Widget.extend({
sourceData: "",
templateName: 'ticker_widget',
classNames: ['widget', 'widget-ticker'],
widgetView: function() {
var widget = this;
return this._super().reopen({
didInsertElement: function() {
var scaleFactor = 0.7;
var widgetHeight = this.$().height();
var fontSize = widgetHeight * scaleFactor;
var widgetUnitWidth = (DashboardConfig.grid.width - DashboardConfig.widgetMargins) /
DashboardConfig.dim[0] - DashboardConfig.widgetMargins;
var widgetWidth = widgetUnitWidth * widget.get('sizex') +
DashboardConfig.widgetMargins * (widget.get('sizex') - 1) - 5;
this.$().css('font-size', fontSize + 'px');
this.$('.marquee').css('max-width', widgetWidth + 'px');
}
});
}.property()
});
| Dashboard.TickerWidget = Dashboard.Widget.extend({
sourceData: "",
templateName: 'ticker_widget',
classNames: ['widget', 'widget-ticker'],
widgetView: function() {
var widget = this;
return this._super().reopen({
didInsertElement: function() {
var scaleFactor = 0.7;
var widgetHeight = this.$().height();
var fontSize = widgetHeight * scaleFactor;
var widgetUnitWidth = (DashboardConfig.grid.width - DashboardConfig.widgetMargins) /
DashboardConfig.dim[0] - DashboardConfig.widgetMargins;
var widgetWidth = widgetUnitWidth * widget.get('sizex') +
DashboardConfig.widgetMargins * (widget.get('sizex') - 1) - 5;
this.$().css('font-size', fontSize + 'px');
this.$('.marquee').css('max-width', widgetWidth + 'px');
}
});
}.property()
});
|
Remove NoErrorsPlugin until webpack-hot-middleware learns to display syntax error overlay after reload as well | var path = require('path');
var webpack = require('webpack');
module.exports = {
// or devtool: 'eval' to debug issues with compiled output:
devtool: 'cheap-module-eval-source-map',
entry: [
// necessary for hot reloading with IE:
'eventsource-polyfill',
// listen to code updates emitted by hot middleware:
'webpack-hot-middleware/client',
// your code:
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'src')
}]
}
};
| var path = require('path');
var webpack = require('webpack');
module.exports = {
// or devtool: 'eval' to debug issues with compiled output:
devtool: 'cheap-module-eval-source-map',
entry: [
// necessary for hot reloading with IE:
'eventsource-polyfill',
// listen to code updates emitted by hot middleware:
'webpack-hot-middleware/client',
// your code:
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/dist/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'src')
}]
}
};
|
Add notifiers to task list | from celery import Celery
from tornado.options import options
from tasks.helpers import create_mq_url
queue_conf = {
'CELERY_TASK_SERIALIZER': 'json',
'CELERY_ACCEPT_CONTENT': ['json'],
'CELERY_RESULT_SERIALIZER': 'json',
'CELERY_TASK_RESULT_EXPIRES': 3600
}
selftest_task_queue = Celery(
'selftest_task_queue',
backend='rpc',
broker=create_mq_url(options.mq_hostname, options.mq_port,
username=options.mq_username,
password=options.mq_password),
include=[
"tasks.message_tasks",
"tasks.notifiers",
])
selftest_task_queue.conf.update(**queue_conf) | from celery import Celery
from tornado.options import options
from tasks.helpers import create_mq_url
queue_conf = {
'CELERY_TASK_SERIALIZER': 'json',
'CELERY_ACCEPT_CONTENT': ['json'],
'CELERY_RESULT_SERIALIZER': 'json',
'CELERY_TASK_RESULT_EXPIRES': 3600
}
selftest_task_queue = Celery(
'selftest_task_queue',
backend='rpc',
broker=create_mq_url(options.mq_hostname, options.mq_port,
username=options.mq_username,
password=options.mq_password),
include=[
"tasks.message_tasks"
])
selftest_task_queue.conf.update(**queue_conf) |
Fix whitespace at the end of the URL breaking routing | <?php
require __DIR__.'/../includes/init.php';
use App\RegExp;
use App\HTTP;
use App\Users;
use App\CoreUtils;
$permRedirectPattern = new RegExp('^\s*(.*?)\.php(\?.*)?$','i');
if (preg_match($permRedirectPattern, $_SERVER['REQUEST_URI']))
HTTP::redirect(preg_replace($permRedirectPattern, '$1$2', $_SERVER['REQUEST_URI']));
$decoded_uri = CoreUtils::trim(urldecode($_SERVER['REQUEST_URI']));
if (!preg_match($REWRITE_REGEX,strtok($decoded_uri,'?'),$matches)){
Users::authenticate();
CoreUtils::notFound();
}
$do = empty($matches[1]) ? 'index' : $matches[1];
$data = $matches[2] ?? '';
require INCPATH.'routes.php';
/** @var $match array */
$match = $router->match($decoded_uri);
if (!isset($match['target']))
CoreUtils::notFound();
(\App\RouteHelper::processHandler($match['target']))($match['params']);
| <?php
require __DIR__.'/../includes/init.php';
use App\RegExp;
use App\HTTP;
use App\Users;
use App\CoreUtils;
$permRedirectPattern = new RegExp('^\s*(.*?)\.php(\?.*)?$','i');
if (preg_match($permRedirectPattern, $_SERVER['REQUEST_URI']))
HTTP::redirect(preg_replace($permRedirectPattern, '$1$2', $_SERVER['REQUEST_URI']));
$decoded_uri = urldecode(CoreUtils::trim($_SERVER['REQUEST_URI']));
if (!preg_match($REWRITE_REGEX,strtok($decoded_uri,'?'),$matches)){
Users::authenticate();
CoreUtils::notFound();
}
$do = empty($matches[1]) ? 'index' : $matches[1];
$data = $matches[2] ?? '';
require INCPATH.'routes.php';
/** @var $match array */
$match = $router->match($decoded_uri);
if (!isset($match['target']))
CoreUtils::notFound();
(\App\RouteHelper::processHandler($match['target']))($match['params']);
|
Add a public modifier to an interface method | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
/**
* AuthenticationProviderInterface is the interface for all authentication
* providers.
*
* Concrete implementations processes specific Token instances.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface AuthenticationProviderInterface extends AuthenticationManagerInterface
{
/**
* Checks whether this provider supports the given token.
*
* @param TokenInterface $token A TokenInterface instance
*
* @return Boolean true if the implementation supports the Token, false otherwise
*/
public function supports(TokenInterface $token);
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
/**
* AuthenticationProviderInterface is the interface for all authentication
* providers.
*
* Concrete implementations processes specific Token instances.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface AuthenticationProviderInterface extends AuthenticationManagerInterface
{
/**
* Checks whether this provider supports the given token.
*
* @param TokenInterface $token A TokenInterface instance
*
* @return Boolean true if the implementation supports the Token, false otherwise
*/
function supports(TokenInterface $token);
}
|
Add dep on toolz 0.7.2 for imperative extra | #!/usr/bin/env python
from os.path import exists
from setuptools import setup
import dask
extras_require = {
'array': ['numpy', 'toolz >= 0.7.2'],
'bag': ['cloudpickle', 'toolz >= 0.7.2', 'partd >= 0.3.2'],
'dataframe': ['numpy', 'pandas >= 0.16.0', 'toolz >= 0.7.2', 'partd >= 0.3.2'],
'imperative': ['toolz >= 0.7.2'],
}
extras_require['complete'] = sorted(set(sum(extras_require.values(), [])))
setup(name='dask',
version=dask.__version__,
description='Minimal task scheduling abstraction',
url='http://github.com/dask/dask/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='task-scheduling parallelism',
packages=['dask', 'dask.array', 'dask.bag', 'dask.store',
'dask.dataframe', 'dask.diagnostics'],
long_description=(open('README.rst').read() if exists('README.rst')
else ''),
extras_require=extras_require,
zip_safe=False)
| #!/usr/bin/env python
from os.path import exists
from setuptools import setup
import dask
extras_require = {
'array': ['numpy', 'toolz >= 0.7.2'],
'bag': ['cloudpickle', 'toolz >= 0.7.2', 'partd >= 0.3.2'],
'dataframe': ['numpy', 'pandas >= 0.16.0', 'toolz >= 0.7.2', 'partd >= 0.3.2'],
}
extras_require['complete'] = sorted(set(sum(extras_require.values(), [])))
setup(name='dask',
version=dask.__version__,
description='Minimal task scheduling abstraction',
url='http://github.com/dask/dask/',
maintainer='Matthew Rocklin',
maintainer_email='mrocklin@gmail.com',
license='BSD',
keywords='task-scheduling parallelism',
packages=['dask', 'dask.array', 'dask.bag', 'dask.store',
'dask.dataframe', 'dask.diagnostics'],
long_description=(open('README.rst').read() if exists('README.rst')
else ''),
extras_require=extras_require,
zip_safe=False)
|
Add log statement on ignore | package org.rmatil.sync.event.aggregator.core.modifier;
import org.rmatil.sync.event.aggregator.core.events.IEvent;
import org.rmatil.sync.event.aggregator.core.events.ModifyEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Modifies the list of events in such a way, that notifications
* about a change in a directory do not get propagated further.
*/
public class IgnoreDirectoryModifier implements IModifier {
final static Logger logger = LoggerFactory.getLogger(IgnoreDirectoryModifier.class);
@Override
public List<IEvent> modify(List<IEvent> events) {
List<IEvent> modifiedEvents = new ArrayList<>();
for (IEvent event : events) {
if (! (event instanceof ModifyEvent && event.getPath().toFile().isDirectory())) {
modifiedEvents.add(event);
} else {
logger.trace("Ignoring modify event for directory " + event.getPath());
}
}
return modifiedEvents;
}
}
| package org.rmatil.sync.event.aggregator.core.modifier;
import org.rmatil.sync.event.aggregator.core.events.IEvent;
import org.rmatil.sync.event.aggregator.core.events.ModifyEvent;
import java.util.ArrayList;
import java.util.List;
/**
* Modifies the list of events in such a way, that notifications
* about a change in a directory do not get propagated further.
*/
public class IgnoreDirectoryModifier implements IModifier {
@Override
public List<IEvent> modify(List<IEvent> events) {
List<IEvent> modifiedEvents = new ArrayList<>();
for (IEvent event : events) {
if (! (event instanceof ModifyEvent && event.getPath().toFile().isDirectory())) {
modifiedEvents.add(event);
}
}
return modifiedEvents;
}
}
|
Reset destroyed flag on reset | import Phaser from 'phaser';
import { tile, nextTile, alignToGrid, pixelToTile } from '../../tiles';
import { clone } from '../../utils';
import objectPool from '../../object-pool';
import tween from './tween';
export default class extends Phaser.Image {
constructor(game, x, y, sprite, frame, id, objectType) {
const alignedCoords = alignToGrid({ x, y });
x = alignedCoords.x;
y = alignedCoords.y;
super(game, x, y, sprite, frame);
this.anchor.setTo(0.5, 0.5);
// use a bunch of different properties to hopefully achieve a unique id
this.id = id || this.key + this.frame + this.x + this.y + (Math.floor(Math.random() * 100) + 1);
this.objectType = objectType || 'generic';
this.timers = [];
this.tile = {};
this.setTile();
}
move(nextPixelCoord, callback) {
this.moving = true;
tween.call(this, nextPixelCoord, 35, function() {
this.moving = false;
this.setTile();
if (callback) callback.call(this);
});
}
setTile() {
this.tile = tile.call(this);
}
resetObject() {
this.setTile();
this.timers = [];
this.destroyed = false;
}
destroy() {
this.kill();
this.destroyed = true;
objectPool.remove(this);
}
}
| import Phaser from 'phaser';
import { tile, nextTile, alignToGrid, pixelToTile } from '../../tiles';
import { clone } from '../../utils';
import objectPool from '../../object-pool';
import tween from './tween';
export default class extends Phaser.Image {
constructor(game, x, y, sprite, frame, id, objectType) {
const alignedCoords = alignToGrid({ x, y });
x = alignedCoords.x;
y = alignedCoords.y;
super(game, x, y, sprite, frame);
this.anchor.setTo(0.5, 0.5);
// use a bunch of different properties to hopefully achieve a unique id
this.id = id || this.key + this.frame + this.x + this.y + (Math.floor(Math.random() * 100) + 1);
this.objectType = objectType || 'generic';
this.timers = [];
this.tile = {};
this.setTile();
}
move(nextPixelCoord, callback) {
this.moving = true;
tween.call(this, nextPixelCoord, 35, function() {
this.moving = false;
this.setTile();
if (callback) callback.call(this);
});
}
setTile() {
this.tile = tile.call(this);
}
resetObject() {
this.setTile();
this.timers = [];
}
destroy() {
this.kill();
this.destroyed = true;
objectPool.remove(this);
}
}
|
Load location chooser separately from options and everything
So that we don’t have to wait for locations list to load to start
loading events | import ru from 'moment/locale/ru';
import lazysizes from 'lazysizes';
import Locations from './locations';
import Options from './options';
import LocationChooser from './location-chooser';
import EventsView from './events';
import {show, hide} from './utils';
document.addEventListener('DOMContentLoaded', function(event) {
const options = new Options();
const locations = new Locations();
locations.fetch().then(() => {
const locationContainer = document.querySelector('#city');
const locationChooser = new LocationChooser(locations, options);
locationChooser.render();
locationContainer.appendChild(locationChooser.element);
show(locationContainer);
});
options.fetch().then(() => {
const viewContainer = document.querySelector('#view-container');
const eventsView = new EventsView(options);
eventsView.render();
viewContainer.appendChild(eventsView.element);
});
});
| import ru from 'moment/locale/ru';
import lazysizes from 'lazysizes';
import Locations from './locations';
import Options from './options';
import LocationChooser from './location-chooser';
import EventsView from './events';
import {show, hide} from './utils';
document.addEventListener('DOMContentLoaded', function(event) {
const options = new Options();
const locations = new Locations();
Promise.all([
locations.fetch(),
options.fetch()
]).then(() => {
const locationContainer = document.querySelector('#city');
const viewContainer = document.querySelector('#view-container');
const locationChooser = new LocationChooser(locations, options);
locationChooser.render();
locationContainer.appendChild(locationChooser.element);
const eventsView = new EventsView(options);
eventsView.render();
viewContainer.appendChild(eventsView.element);
show(locationContainer);
});
});
|
Use stanford search logic only if configured | """
Custom override of SearchFilterGenerator to use course tiles for
discovery search.
"""
from search.filter_generator import SearchFilterGenerator
from branding_stanford.models import TileConfiguration
from lms.lib.courseware_search.lms_filter_generator import LmsSearchFilterGenerator
class TileSearchFilterGenerator(LmsSearchFilterGenerator):
"""
SearchFilterGenerator for LMS Search.
"""
def field_dictionary(self, **kwargs):
"""
Return field filter dictionary for search.
"""
field_dictionary = super(TileSearchFilterGenerator, self).field_dictionary(**kwargs)
if not kwargs.get('user'):
# Adds tile courses for discovery search
course_tiles_ids = TileConfiguration.objects.filter(
enabled=True,
).values_list('course_id', flat=True).order_by('-change_date')
courses = list(course_tiles_ids)
if len(courses):
field_dictionary['course'] = courses
return field_dictionary
| """
Custom override of SearchFilterGenerator to use course tiles for
discovery search.
"""
from search.filter_generator import SearchFilterGenerator
from branding_stanford.models import TileConfiguration
from lms.lib.courseware_search.lms_filter_generator import LmsSearchFilterGenerator
class TileSearchFilterGenerator(LmsSearchFilterGenerator):
"""
SearchFilterGenerator for LMS Search.
"""
def field_dictionary(self, **kwargs):
"""
Return field filter dictionary for search.
"""
field_dictionary = super(TileSearchFilterGenerator, self).field_dictionary(**kwargs)
if not kwargs.get('user'):
# Adds tile courses for discovery search
course_tiles_ids = TileConfiguration.objects.filter(
enabled=True,
).values_list('course_id', flat=True).order_by('-change_date')
field_dictionary['course'] = list(course_tiles_ids)
return field_dictionary
|
FIX disable product supplier pricelist | # -*- coding: utf-8 -*-
{
'name': 'Product Supplier Pricelist',
'version': '1.0',
'category': 'Product',
'sequence': 14,
'summary': '',
'description': """
Product Supplier Pricelist
==========================
Add sql constraint to restrict:
1. That you can only add one supplier to a product per company
2. That you can add olny one record of same quantity for a supplier pricelist
It also adds to more menus (and add some related fields) on purchase/product.
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'purchase',
],
'data': [
'product_view.xml',
],
'demo': [
],
'test': [
],
# TODO fix this module and make installable
'installable': False,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | # -*- coding: utf-8 -*-
{
'name': 'Product Supplier Pricelist',
'version': '1.0',
'category': 'Product',
'sequence': 14,
'summary': '',
'description': """
Product Supplier Pricelist
==========================
Add sql constraint to restrict:
1. That you can only add one supplier to a product per company
2. That you can add olny one record of same quantity for a supplier pricelist
It also adds to more menus (and add some related fields) on purchase/product.
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'purchase',
],
'data': [
'product_view.xml',
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
Remove CRUD methods from interface | <?php
namespace BrianFaust\Addressable\Interfaces;
interface HasAddresses
{
/**
* @return mixed
*/
public function addresses();
/**
* @param $address
*
* @return mixed
*/
public function primaryAddress($address);
/**
* @param $address
*
* @return mixed
*/
public function billingAddress($address);
/**
* @param $address
*
* @return mixed
*/
public function shippingAddress($address);
/**
* @param $distance
* @param $type
* @param $lat
* @param $lng
*
* @return mixed
*/
public static function findByDistance($distance, $type, $lat, $lng);
}
| <?php
namespace BrianFaust\Addressable\Interfaces;
interface HasAddresses
{
/**
* @return mixed
*/
public function addresses();
/**
* @param $address
*
* @return mixed
*/
public function primaryAddress($address);
/**
* @param $address
*
* @return mixed
*/
public function billingAddress($address);
/**
* @param $address
*
* @return mixed
*/
public function shippingAddress($address);
/**
* @param $data
*
* @return mixed
*/
public function createAddress($data);
/**
* @param $address
* @param $data
*
* @return mixed
*/
public function updateAddress($address, $data);
/**
* @param $address
*
* @return mixed
*/
public function deleteAddress($address);
/**
* @param $distance
* @param $type
* @param $lat
* @param $lng
*
* @return mixed
*/
public static function findByDistance($distance, $type, $lat, $lng);
}
|
Fix incorrect CD condition for passing build. | // Continuous delivery server
const { spawn } = require('child_process')
const { resolve } = require('path')
const { createServer } = require('http')
const { parse } = require('qs')
const hostname = '127.0.0.1'
const port = 80
const server = createServer((req, res) => {
const { headers, method, url } = req
// When a successful build has happened, kill the process, triggering a restart
if (req.method === 'POST' && req.url === '/webhook') {
// Send response
res.statusCode = 200
res.end()
let body = []
req
.on('error', err => {
console.error(err)
})
.on('data', chunk => {
body.push(chunk)
})
.on('end', () => {
body = Buffer.concat(body).toString()
const { payload } = parse(body)
const passed = payload.status == 0
const master = payload.branch == 'master'
if (passed && master) {
process.exit(0)
}
})
}
res.statusCode = 404
res.end()
}).listen(port)
| // Continuous delivery server
const { spawn } = require('child_process')
const { resolve } = require('path')
const { createServer } = require('http')
const { parse } = require('qs')
const hostname = '127.0.0.1'
const port = 80
const server = createServer((req, res) => {
const { headers, method, url } = req
// When a successful build has happened, kill the process, triggering a restart
if (req.method === 'POST' && req.url === '/webhook') {
// Send response
res.statusCode = 200
res.end()
let body = []
req
.on('error', err => {
console.error(err)
})
.on('data', chunk => {
body.push(chunk)
})
.on('end', () => {
body = Buffer.concat(body).toString()
const { payload } = parse(body)
const passed = payload.status == 1
const master = payload.branch == 'master'
console.log(payload.passed)
console.log(payload.branch)
if (passed && master) {
process.exit(0)
}
})
}
res.statusCode = 404
res.end()
}).listen(port)
|
Add req. files to run tests using chai | // Karma configuration
// Generated on Fri May 10 2013 21:56:54 GMT+0200 (CEST)
// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
MOCHA,
MOCHA_ADAPTER,
'test/browser/chai.js',
'js/app.js',
'test/spec/app.js'
];
// list of files to exclude
exclude = [
];
// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];
// web server port
port = 9876;
// cli runner port
runnerPort = 9100;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
| // Karma configuration
// Generated on Fri May 10 2013 21:56:54 GMT+0200 (CEST)
// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
MOCHA,
MOCHA_ADAPTER,
'js/*.js'
];
// list of files to exclude
exclude = [
];
// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];
// web server port
port = 9876;
// cli runner port
runnerPort = 9100;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
|
Add possibility to choose how many versions to show | <?php
/**
* Model
*
* @author: Michal Hojgr <michal.hojgr@gmail.com>
*
*/
class ModLoader {
/**
* @var Cache
*/
private $cache;
/**
* @var ModMapper
*/
private $modMapper;
/**
* @param Cache $cache
* @param ModMapper $modMapper
*/
public function __construct(Cache $cache, ModMapper $modMapper)
{
$this->cache = $cache;
$this->modMapper = $modMapper;
}
/**
* Loads all versions, caches them and in case that
* cache was made recently, it reads from cache
*
* @param int $count how many versions to show
* @param int $start
* @return array
*/
public function getVersions($count, $start = 0) {
/**
* Load from cache
*/
$files = $this->cache->getCachedVersions($this->modMapper);
/**
* Get latest version and the others
*/
$latest = $files[0];
unset($files[0]);
$others = array_values($files);
// buffer count so it must not count every loop
$buffer_count = count($others);
for($i = 0; $i < $count; $i++) {
if($i < $start || $i > $start + $count)
unset($others[$i]);
}
return array("latest" => $latest, "others" => $others);
}
} | <?php
/**
* Model
*
* @author: Michal Hojgr <michal.hojgr@gmail.com>
*
*/
class ModLoader {
/**
* @var Cache
*/
private $cache;
/**
* @var ModMapper
*/
private $modMapper;
/**
* @param Cache $cache
* @param ModMapper $modMapper
*/
public function __construct(Cache $cache, ModMapper $modMapper)
{
$this->cache = $cache;
$this->modMapper = $modMapper;
}
/**
* Loads all versions, caches them and in case that
* cache was made recently, it reads from cache
*
* @return array
*/
public function getVersions() {
/**
* Load from cache
*/
$files = $this->cache->getCachedVersions($this->modMapper);
/**
* Get latest version and the others
*/
$latest = $files[0];
unset($files[0]);
$others = array_values($files);
return array("latest" => $latest, "others" => $others);
}
} |
Add use strict to satisfy jshint | 'use strict';
module.exports = (url, cb) => {
cb(null, {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
id: 'way/4243736',
properties: {
highway: 'trunk'
},
geometry: {
type: 'LineString',
coordinates: [
[
172.5498622,
-43.4932694
],
[
172.5498622,
-43.4932694
]
]
}
}
]
})
}
| module.exports = (url, cb) => {
cb(null, {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
id: 'way/4243736',
properties: {
highway: 'trunk'
},
geometry: {
type: 'LineString',
coordinates: [
[
172.5498622,
-43.4932694
],
[
172.5498622,
-43.4932694
]
]
}
}
]
})
}
|
Fix wrong letter case in namespace | <?php
declare (strict_types = 1);
namespace GrottoPress\Jentil\Setups\Customizer\Layout\Settings;
use GrottoPress\Jentil\Setups\Customizer\Layout\Layout;
use GrottoPress\Jentil\Utilities\ThemeMods\Layout as LayoutMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;
abstract class AbstractSetting extends Setting
{
/**
* @var LayoutMod
*/
protected $themeMod;
public function __construct(Layout $layout)
{
parent::__construct($layout);
$this->args['sanitize_callback'] = 'sanitize_title';
$this->control['section'] = $this->section->id;
$this->control['label'] = \esc_html__('Select layout', 'jentil');
$this->control['type'] = 'select';
$this->control['choices'] = $this->section->customizer->app
->utilities->page->layouts->IDs();
}
protected function themeMod(array $args): LayoutMod
{
return $this->section->customizer->app->utilities->themeMods->layout(
$args
);
}
}
| <?php
declare (strict_types = 1);
namespace GrottoPress\Jentil\Setups\Customizer\Layout\Settings;
use GrottoPress\Jentil\Setups\Customizer\Layout\Layout;
use GrottoPress\Jentil\utilities\ThemeMods\Layout as LayoutMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;
abstract class AbstractSetting extends Setting
{
/**
* @var LayoutMod
*/
protected $themeMod;
public function __construct(Layout $layout)
{
parent::__construct($layout);
$this->args['sanitize_callback'] = 'sanitize_title';
$this->control['section'] = $this->section->id;
$this->control['label'] = \esc_html__('Select layout', 'jentil');
$this->control['type'] = 'select';
$this->control['choices'] = $this->section->customizer->app
->utilities->page->layouts->IDs();
}
protected function themeMod(array $args): LayoutMod
{
return $this->section->customizer->app->utilities->themeMods->layout(
$args
);
}
}
|
Fix a typo in an error message
integeer -> integer | # This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003-2008 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module that provides the delay class."""
_errmsg = "arg of delay constructor should be a natural integer"
class delay(object):
""" Class to model delay in yield statements. """
def __init__(self, val):
""" Return a delay instance.
Required parameters:
val -- a natural integer representing the desired delay
"""
if not isinstance(val, int) or val < 0:
raise TypeError(_errmsg)
self._time = val
| # This file is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003-2008 Jan Decaluwe
#
# The myhdl library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" Module that provides the delay class."""
_errmsg = "arg of delay constructor should be a natural integeer"
class delay(object):
""" Class to model delay in yield statements. """
def __init__(self, val):
""" Return a delay instance.
Required parameters:
val -- a natural integer representing the desired delay
"""
if not isinstance(val, int) or val < 0:
raise TypeError(_errmsg)
self._time = val
|
Add algolia in site config | // See https://docusaurus.io/docs/site-config for all the possible
// site configuration options.
const siteConfig = {
title: 'Coursier',
tagline: 'Pure Scala Artifact Fetching',
// wiped when relativizing stuff
url: 'https://get-coursier.io',
baseUrl: '/',
projectName: 'coursier',
organizationName: 'coursier',
customDocsPath: 'processed-docs',
headerLinks: [
{doc: 'overview', label: 'Docs'},
{blog: true, label: 'Blog'},
{href: 'https://github.com/coursier/coursier', label: 'GitHub'},
],
users: [],
colors: {
primaryColor: '#58B8C1',
secondaryColor: '#3498DB',
},
copyright: `Copyright © ${new Date().getFullYear()} coursier contributors`,
highlight: {
theme: 'default',
},
scripts: ['https://buttons.github.io/buttons.js'],
onPageNav: 'separate',
cleanUrl: true,
enableUpdateTime: true, // doesn't seem to work
editUrl: 'https://github.com/coursier/coursier/edit/master/doc/docs/',
twitter: true,
algolia: {
apiKey: '53a7a919d6905f94dafd59e25d0f5e5d',
indexName: 'get-coursier',
algoliaOptions: {
// seems we should need that
// facetFilters: [ "version:VERSION" ]
},
},
};
module.exports = siteConfig;
| // See https://docusaurus.io/docs/site-config for all the possible
// site configuration options.
const siteConfig = {
title: 'Coursier',
tagline: 'Pure Scala Artifact Fetching',
// wiped when relativizing stuff
url: 'https://get-coursier.io',
baseUrl: '/',
projectName: 'coursier',
organizationName: 'coursier',
customDocsPath: 'processed-docs',
headerLinks: [
{doc: 'overview', label: 'Docs'},
{blog: true, label: 'Blog'},
{href: 'https://github.com/coursier/coursier', label: 'GitHub'},
],
users: [],
colors: {
primaryColor: '#58B8C1',
secondaryColor: '#3498DB',
},
copyright: `Copyright © ${new Date().getFullYear()} coursier contributors`,
highlight: {
theme: 'default',
},
scripts: ['https://buttons.github.io/buttons.js'],
onPageNav: 'separate',
cleanUrl: true,
enableUpdateTime: true, // doesn't seem to work
editUrl: 'https://github.com/coursier/coursier/edit/master/doc/docs/',
twitter: true,
};
module.exports = siteConfig;
|
Rename paramater arguments as inputs | <?php
/**
* @file
* Contains Drupal\AppConsole\Command\Helper\ChainCommandHelper.
*/
namespace Drupal\AppConsole\Command\Helper;
use Symfony\Component\Console\Helper\Helper;
class ChainCommandHelper extends Helper
{
/** @var $commands array */
private $commands;
/**
* @param $name string
* @param $inputs array
*/
public function addCommand($name, $inputs = [])
{
array_unshift($inputs, ['command' => $name]);
$this->commands[] = ['name' => $name, 'inputs' => $inputs];
}
/**
* @return array
*/
public function getCommands()
{
return $this->commands;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'chain';
}
}
| <?php
/**
* @file
* Contains Drupal\AppConsole\Command\Helper\ChainCommandHelper.
*/
namespace Drupal\AppConsole\Command\Helper;
use Symfony\Component\Console\Helper\Helper;
class ChainCommandHelper extends Helper
{
/** @var $commands array */
private $commands;
/**
* @param $name string
* @param $arguments array
*/
public function addCommand($name, $arguments)
{
array_unshift($arguments, ['command' => $name]);
$this->commands[] = ['name' => $name, 'arguments' => $arguments];
}
/**
* @return array
*/
public function getCommands()
{
return $this->commands;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'chain';
}
}
|
Hotels: Remove border radius from room image overlay | // @flow
import * as React from 'react';
import { View } from 'react-native';
import { Touchable, NetworkImage, StyleSheet } from '@kiwicom/mobile-shared';
import GalleryButton from '../galleryButton/GalleryButton';
type Props = {|
+thumbnailUrl: ?string,
+photoCount: number,
+openGallery: () => void,
|};
export default function RoomImage({
thumbnailUrl,
photoCount,
openGallery,
}: Props) {
return (
<Touchable onPress={openGallery} disabled={thumbnailUrl == null}>
<View>
<NetworkImage source={{ uri: thumbnailUrl }} style={styles.thumbnail} />
<View style={styles.galleryButton}>
<GalleryButton
count={photoCount}
style={{ container: styles.galleryButtonContainer }}
/>
</View>
</View>
</Touchable>
);
}
const styles = StyleSheet.create({
galleryButton: {
position: 'absolute',
bottom: 0,
end: 0,
start: 0,
},
galleryButtonContainer: {
justifyContent: 'center',
backgroundColor: 'rgba(0, 0, 0, 0.3)',
borderRadius: 0,
},
thumbnail: {
width: 60,
height: 80,
borderRadius: 2,
},
});
| // @flow
import * as React from 'react';
import { View } from 'react-native';
import { Touchable, NetworkImage, StyleSheet } from '@kiwicom/mobile-shared';
import GalleryButton from '../galleryButton/GalleryButton';
type Props = {|
+thumbnailUrl: ?string,
+photoCount: number,
+openGallery: () => void,
|};
export default function RoomImage({
thumbnailUrl,
photoCount,
openGallery,
}: Props) {
return (
<Touchable onPress={openGallery} disabled={thumbnailUrl == null}>
<View>
<NetworkImage source={{ uri: thumbnailUrl }} style={styles.thumbnail} />
<View style={styles.galleryButton}>
<GalleryButton
count={photoCount}
style={{ container: styles.galleryButtonContainer }}
/>
</View>
</View>
</Touchable>
);
}
const styles = StyleSheet.create({
galleryButton: {
position: 'absolute',
bottom: 0,
end: 0,
start: 0,
},
galleryButtonContainer: {
justifyContent: 'center',
backgroundColor: 'rgba(0, 0, 0, 0.3)',
},
thumbnail: {
width: 60,
height: 80,
borderRadius: 2,
},
});
|
Migrate script ot Python 3 | #!/usr/bin/env python3
# Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
# This program reads a Unicode database and emits all letters in lower
# and upper case.
# Refer to http://www.unicode.org/ucd/ to download new files.
import sys
def add_character(unicodespec, characterstore):
characterstora
def main(raw, out):
# Fetch upper and lower case characters in Unicode
characters = [x for x in raw if x[2] == 'Lu' or x[2] == 'Ll']
image = [chr(int(c[0], 16)) for c in characters]
output = "\n".join(image)
out.write(output.encode("UTF-8"))
out.write(u"\n".encode("UTF-8"))
if __name__ == '__main__':
try:
raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()]
except:
sys.stderr.write("Problems reading ./UnicodeData.txt.\n")
sys.exit(1)
main(raw, sys.stdout)
| #! /usr/bin/env python
# Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
# This program reads a Unicode database and emits all letters in lower
# and upper case.
# Refer to http://www.unicode.org/ucd/ to download new files.
import sys
def add_character(unicodespec, characterstore):
characterstora
def main(raw, out):
# Fetch upper and lower case characters in Unicode
characters = filter(lambda x: x[2] == 'Lu' or x[2] == 'Ll', raw)
image = [unichr(int(c[0], 16)) for c in characters]
output = u"\n".join(image)
out.write(output.encode("UTF-8"))
out.write(u"\n".encode("UTF-8"))
if __name__ == '__main__':
try:
raw = [x.split(";") for x in open("./UnicodeData.txt", "r").readlines()]
except:
sys.stderr.write("Problems reading ./UnicodeData.txt.\n")
sys.exit(1)
main(raw, sys.stdout)
|
Exclude reflections with -ve sigma (needed when reading XDS_ASCII.HKL as input) | from iotbx.xds.read_ascii import reader
import sys
for n, argv in enumerate(sys.argv[1:]):
r = reader(open(argv))
mas = r.as_miller_arrays(merge_equivalents = False)
assert(len(mas) == 1)
ma = mas[0].apply_scaling(target_max = 9.99e5)
i = ma.data()
s = ma.sigmas()
hkl = ma.indices()
for j, h in enumerate(hkl):
_i = ('%f' % i[j])[:7]
assert('.' in _i)
_s = ('%f' % s[j])[:7]
assert('.' in _s)
if s[j] >= 0.0:
print '%4d%4d%4d%8s%8s%4d' % (h[0], h[1], h[2],
_i, _s, n + 1)
| from iotbx.xds.read_ascii import reader
import sys
for n, argv in enumerate(sys.argv[1:]):
r = reader(open(argv))
mas = r.as_miller_arrays(merge_equivalents = False)
assert(len(mas) == 1)
ma = mas[0].apply_scaling(target_max = 9.99e5)
i = ma.data()
s = ma.sigmas()
hkl = ma.indices()
for j, h in enumerate(hkl):
_i = ('%f' % i[j])[:7]
assert('.' in _i)
_s = ('%f' % s[j])[:7]
assert('.' in _s)
print '%4d%4d%4d%8s%8s%4d' % (h[0], h[1], h[2],
_i, _s, n + 1)
|
Remove extraneous `{` in migration
It looks like we inadvertently got an extra `{` in here - I noticed it because my IDE threw a big red dot on this migration. We must've accidentally put that in when we were adding the 'id' column. | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCustomFieldCustomFieldset extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('custom_field_custom_fieldset', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('custom_field_id');
$table->integer('custom_fieldset_id');
$table->integer('order');
$table->boolean('required');
$table->engine = 'InnoDB';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('custom_field_custom_fieldset');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCustomFieldCustomFieldset extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('custom_field_custom_fieldset', function (Blueprint $table) {
{
$table->bigIncrements('id');
$table->integer('custom_field_id');
$table->integer('custom_fieldset_id');
$table->integer('order');
$table->boolean('required');
$table->engine = 'InnoDB';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('custom_field_custom_fieldset');
}
}
|
Modify a function call argument | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import abc
from ._common import _validate_null_string, is_pathlike_obj
from ._six import add_metaclass, text_type
@add_metaclass(abc.ABCMeta)
class NameSanitizer(object):
@abc.abstractproperty
def reserved_keywords(self): # pragma: no cover
pass
@abc.abstractmethod
def validate(self): # pragma: no cover
pass
@abc.abstractmethod
def sanitize(self, replacement_text=""): # pragma: no cover
pass
@property
def _str(self):
return text_type(self._value)
def __init__(self, value):
self._validate_null_string(value)
if is_pathlike_obj(value):
self._value = value
else:
self._value = value.strip()
def _is_pathlike_obj(self):
return is_pathlike_obj(self._value)
def _is_reserved_keyword(self, value):
return value in self.reserved_keywords
@staticmethod
def _validate_null_string(text):
_validate_null_string(text, error_msg="null name")
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import abc
from ._common import _validate_null_string, is_pathlike_obj
from ._six import add_metaclass, text_type
@add_metaclass(abc.ABCMeta)
class NameSanitizer(object):
@abc.abstractproperty
def reserved_keywords(self): # pragma: no cover
pass
@abc.abstractmethod
def validate(self): # pragma: no cover
pass
@abc.abstractmethod
def sanitize(self, replacement_text=""): # pragma: no cover
pass
@property
def _str(self):
return text_type(self._value)
def __init__(self, value):
self._validate_null_string(value)
if is_pathlike_obj(value):
self._value = value
else:
self._value = value.strip()
def _is_pathlike_obj(self):
return is_pathlike_obj(self._value)
def _is_reserved_keyword(self, value):
return value in self.reserved_keywords
@staticmethod
def _validate_null_string(text, error_msg="null name"):
_validate_null_string(text)
|
Add support for ipv6 (which has colons in the IP address) | package main
import "net/http"
import "os"
import "strings"
import "fmt"
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
http.HandleFunc("/", IpResponse)
http.ListenAndServe(":" + port, nil)
}
func IpResponse(response http.ResponseWriter, request *http.Request) {
ip := request.Header.Get("X-Forwarded-For")
if ip == "" {
ip = request.RemoteAddr
}
colonPosition := strings.LastIndex(ip, ":")
if colonPosition > -1 {
ip = ip[:colonPosition]
}
commaPosition := strings.Index(ip, ",")
if commaPosition > -1 {
ip = ip[:commaPosition]
}
fmt.Println(ip)
response.Write([]byte(ip))
}
| package main
import "net/http"
import "os"
import "strings"
import "fmt"
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
http.HandleFunc("/", IpResponse)
http.ListenAndServe(":" + port, nil)
}
func IpResponse(response http.ResponseWriter, request *http.Request) {
ip := request.Header.Get("X-Forwarded-For")
if ip == "" {
ip = request.RemoteAddr
}
colonPosition := strings.Index(ip, ":")
if colonPosition > -1 {
ip = ip[:colonPosition]
}
commaPosition := strings.Index(ip, ",")
if commaPosition > -1 {
ip = ip[:commaPosition]
}
fmt.Println(ip)
response.Write([]byte(ip))
}
|
Support hours place in colonSeparateDuration | var cbus = {};
var xhr = function(url, callback) {
var oReq = new XMLHttpRequest();
oReq.onload = function(e){
callback(this.responseText, e);
};
oReq.open("get", url, true);
oReq.send();
};
var colonSeparateDuration = function(num) { // in seconds
if (typeof num == "number" && !(Number.isNaN || isNaN)(num)) {
var hours = Math.floor(num / 60 / 60);
var minutes = Math.floor(num / 60) - hours * 60;
var seconds = Math.floor(num % 60);
return (hours !== 0 ? "" + hours + ":" : "") + zpad(minutes, 2) + ":" + zpad(seconds, 2);
} else {
return "--:--";
}
};
var zpad = function pad(n, width, z) { // by user Pointy on SO: stackoverflow.com/a/10073788
z = z || "0";
n = n + "";
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
};
var mergeObjects = function(a, b){
var result = {};
for (var key in a) {
result[key] = a[key];
}
for (var key in b) {
result[key] = b[key];
}
return result;
};
window.AudioContext = window.AudioContext || window.webkitAudioContext;
| var cbus = {};
var xhr = function(url, callback) {
var oReq = new XMLHttpRequest();
oReq.onload = function(e){
callback(this.responseText, e);
};
oReq.open("get", url, true);
oReq.send();
};
var colonSeparateDuration = function(num) { // in seconds
if (typeof num == "number" && !(Number.isNaN || isNaN)(num)) {
var minutes = Math.floor(num / 60);
var seconds = Math.floor(num % 60);
return "" + minutes + ":" + zpad(seconds, 2);
} else {
return "--:--";
}
};
var zpad = function pad(n, width, z) { // by user Pointy on SO: stackoverflow.com/a/10073788
z = z || "0";
n = n + "";
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
};
var mergeObjects = function(a, b){
var result = {};
for (var key in a) {
result[key] = a[key];
}
for (var key in b) {
result[key] = b[key];
}
return result;
};
window.AudioContext = window.AudioContext || window.webkitAudioContext;
|
Fix priority on bad request route
Higher put this at the top of the list, we want it last. | <?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class BadRequestController
*/
class BadRequestController extends AbstractController
{
/**
* This is the catch-all action for the api.
* It sends a 404 and dies.
*/
#[Route(
'/api/{url}',
requirements: [
'url' => '(?!doc).+',
],
defaults: [
'url' => null,
],
methods: ['GET'],
priority: -1,
)]
public function indexAction()
{
throw $this->createNotFoundException();
}
}
| <?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class BadRequestController
*/
class BadRequestController extends AbstractController
{
/**
* This is the catch-all action for the api.
* It sends a 404 and dies.
*/
#[Route(
'/api/{url}',
requirements: [
'url' => '(?!doc).+',
],
defaults: [
'url' => null,
],
methods: ['GET'],
priority: 2,
)]
public function indexAction()
{
throw $this->createNotFoundException();
}
}
|
Fix real keyboard tab navigation between KeyboardedInput elements
* Current react-generated KeyboardedInput "input" elements will not navigate to
the next KeyboardedInput element upon pressing tab with a real keyboard.
* This happens because the next element in the DOM is actually a KeyboardButton
"button". Mark these elements as non-navigable by the tab button. | import React, {PureComponent, PropTypes} from 'react';
export default class KeyboardButton extends PureComponent {
static propTypes = {
value: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.node.isRequired]),
classes: PropTypes.string,
onClick: PropTypes.func.isRequired,
autofocus: PropTypes.bool,
isDisabled: PropTypes.bool,
};
static defaultProps = {
autofocus: false,
isDisabled: false,
};
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.onClick(this.props.value);
}
render() {
return (
<button
type="button"
tabIndex="-1"
className={'keyboard-button' + ' ' + this.props.classes}
onClick={this.props.isDisabled ? null : this.handleClick}
autoFocus={this.props.autofocus}
disabled={this.props.isDisabled}
>
{this.props.value}
</button>
);
}
}
| import React, {PureComponent, PropTypes} from 'react';
export default class KeyboardButton extends PureComponent {
static propTypes = {
value: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.node.isRequired]),
classes: PropTypes.string,
onClick: PropTypes.func.isRequired,
autofocus: PropTypes.bool,
isDisabled: PropTypes.bool,
};
static defaultProps = {
autofocus: false,
isDisabled: false,
};
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.onClick(this.props.value);
}
render() {
return (
<button
type="button"
className={'keyboard-button' + ' ' + this.props.classes}
onClick={this.props.isDisabled ? null : this.handleClick}
autoFocus={this.props.autofocus}
disabled={this.props.isDisabled}
>
{this.props.value}
</button>
);
}
}
|
Fix bug introduced from messed up merge. | 'use strict';
const Handlers = require('../util').Handlers;
const Err = require('../util').Err;
const VerifyHeaders = require('../util').VerifyHeaders;
exports.attach = function(app, storage) {
app.use(VerifyHeaders(['POST', 'PUT'], {
'Content-Type': 'application/json; charset=utf-8'
}));
app.get('/v1/health', require('./health')(storage));
app.get('/v1/token/default', require('./token')(storage));
// Backend endpoints
app.get('/v1/secret/:token/:path(*)', require('./secret')(storage));
app.get('/v1/cubbyhole/:token/:path(*)', require('./cubbyhole')(storage));
app.get('/v1/credential/:token/:mount/:role', require('./credential')(storage));
app.post('/v1/transit/:token/decrypt', require('./transit')(storage));
app.use('/v1/transit', Handlers.allowed('POST'));
app.use(Handlers.allowed('GET'));
app.use(Err);
};
| 'use strict';
const Handlers = require('../util').Handlers;
const Err = require('../util').Err;
const VerifyHeaders = require('../util').VerifyHeaders;
exports.attach = function(app, storage) {
app.get('/v1/health', require('./health')(storage));
app.get('/v1/token/default', require('./token')(storage));
// Backend endpoints
app.get('/v1/secret/:token/:path(*)', require('./secret')(storage));
app.get('/v1/cubbyhole/:token/:path(*)', require('./cubbyhole')(storage));
app.get('/v1/credential/:token/:mount/:role', require('./credential')(storage));
app.post('/v1/transit/:token/decrypt', require('./transit')(storage));
app.use('/v1/transit', Handlers.allowed('POST'));
app.use(Handlers.allowed('GET'));
app.use(Err);
};
|
Add center and increase suggested value font size | /**
* window.c.ProjectSuggestedContributions component
* A Project-show page helper to show suggested amounts of contributions
*
* Example of use:
* view: () => {
* ...
* m.component(c.ProjectSuggestedContributions, {project: project})
* ...
* }
*/
import m from 'mithril';
import _ from 'underscore';
import projectVM from '../vms/project-vm';
const projectSuggestedContributions = {
view: function({attrs}) {
const project = attrs.project();
const subscriptionSuggestionUrl = amount => `/projects/${project.project_id}/subscriptions/start?value=${amount * 100}`,
contributionSuggestionUrl = amount => `/projects/${project.project_id}/contributions/new?value=${amount * 100}`,
suggestionUrl = projectVM.isSubscription(project) ? subscriptionSuggestionUrl : contributionSuggestionUrl,
suggestedValues = [10, 25, 50, 100];
return m('#suggestions', _.map(suggestedValues, amount => project ? m(`${project.open_for_contributions ? `a[href="${suggestionUrl(amount)}"].card-reward` : ''}.card-big.u-text-center.card-secondary.u-marginbottom-20`, [
m('.fontsize-jumbo', `R$ ${amount}`)
]) : ''));
}
};
export default projectSuggestedContributions;
| /**
* window.c.ProjectSuggestedContributions component
* A Project-show page helper to show suggested amounts of contributions
*
* Example of use:
* view: () => {
* ...
* m.component(c.ProjectSuggestedContributions, {project: project})
* ...
* }
*/
import m from 'mithril';
import _ from 'underscore';
import projectVM from '../vms/project-vm';
const projectSuggestedContributions = {
view: function({attrs}) {
const project = attrs.project();
const subscriptionSuggestionUrl = amount => `/projects/${project.project_id}/subscriptions/start?value=${amount * 100}`,
contributionSuggestionUrl = amount => `/projects/${project.project_id}/contributions/new?value=${amount * 100}`,
suggestionUrl = projectVM.isSubscription(project) ? subscriptionSuggestionUrl : contributionSuggestionUrl,
suggestedValues = [10, 25, 50, 100];
return m('#suggestions', _.map(suggestedValues, amount => project ? m(`${project.open_for_contributions ? `a[href="${suggestionUrl(amount)}"].card-reward` : ''}.card-big.card-secondary.u-marginbottom-20`, [
m('.fontsize-larger', `R$ ${amount}`)
]) : ''));
}
};
export default projectSuggestedContributions;
|
Modify label with select tag | <div class="field" style="text-align: center">
@if(Laramin::model('Category')->count() == 0)
<p class="help is-danger">You Need To Add A Category For Adding a Post</p>
@else
<label for="{{ $name }}" class="label">{{ title_case($name) }}</label>
<div class="select is-primary">
<select id="{{ $name }}" name="{{ $name }}">
@foreach(Laramin::model('Category')->all() as $category)
<option @if(old($name) == $category->id || $value == $category->id) selected="selected" @endif value="{{ $category->id }}">{{ ucfirst($category->name) }}</option>
@endforeach
</select>
</div>
@endif
</div>
| <div class="field" style="text-align: center">
@if(Laramin::model('Category')->count() == 0)
<p class="help is-danger">You Need To Add A Category For Adding a Post</p>
@else
<label class="label">{{ title_case($name) }}</label>
<div class="select is-primary">
<select name="{{ $name }}">
@foreach(Laramin::model('Category')->all() as $category)
<option @if(old($name) == $category->id || $value == $category->id) selected="selected" @endif value="{{ $category->id }}">{{ ucfirst($category->name) }}</option>
@endforeach
</select>
</div>
@endif
</div>
|
Add TODO to later add keyword campaign input settings. | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import java.util.ArrayList;
public class KeywordCampaign {
public int keywordCampaignId;
public int userId;
public int impressions;
public int clicks;
public int cost;
public ArrayList<Integer> DSACampaignIds;
// TODO: add the keyword campaign input settings
public KeywordCampaign(int keywordCampaignId, int userId, int impressions, int clicks, int cost, ArrayList<Integer> DSACampaignIds) {
this.keywordCampaignId = keywordCampaignId;
this.userId = userId;
this.impressions = impressions;
this.clicks = clicks;
this.DSACampaignIds = DSACampaignIds;
}
} | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import java.util.ArrayList;
public class KeywordCampaign {
public int keywordCampaignId;
public int userId;
public int impressions;
public int clicks;
public int cost;
public ArrayList<Integer> DSACampaignIds;
public KeywordCampaign(int keywordCampaignId, int userId, int impressions, int clicks, int cost, ArrayList<Integer> DSACampaignIds) {
this.keywordCampaignId = keywordCampaignId;
this.userId = userId;
this.impressions = impressions;
this.clicks = clicks;
this.DSACampaignIds = DSACampaignIds;
}
} |
Fix tests for the `lowest` stability | <?php
namespace Illuminated\Testing\Tests\Asserts;
use Illuminated\Testing\Tests\App\Post;
use Illuminated\Testing\Tests\TestCase;
class DatabaseAssertsTest extends TestCase
{
/** @test */
public function it_has_database_has_table_assertion()
{
$this->assertDatabaseHasTable('posts');
}
/** @test */
public function it_has_database_missing_table_assertion()
{
$this->assertDatabaseMissingTable('unicorns');
}
/** @test */
public function it_has_database_has_many_assertion()
{
Post::factory()->create(['title' => 'First Post']);
Post::factory()->create(['title' => 'Second Post']);
Post::factory()->create(['title' => 'Third Post']);
$this->assertDatabaseHasMany('posts', [
['title' => 'First Post'],
['title' => 'Second Post'],
['title' => 'Third Post'],
]);
}
/** @test */
public function it_has_database_missing_many_assertion()
{
$this->assertDatabaseMissingMany('posts', [
['title' => 'Fourth Post'],
['title' => 'Fifth Post'],
]);
}
}
| <?php
namespace Illuminated\Testing\Tests\Asserts;
use Illuminated\Testing\Tests\App\Post;
use Illuminated\Testing\Tests\TestCase;
class DatabaseAssertsTest extends TestCase
{
/** @test */
public function it_has_database_has_table_assertion()
{
$this->assertDatabaseHasTable('posts');
}
/** @test */
public function it_has_database_missing_table_assertion()
{
$this->assertDatabaseMissingTable('unicorns');
}
/** @test */
public function it_has_database_has_many_assertion()
{
Post::factory()->createMany([
['title' => 'First Post'],
['title' => 'Second Post'],
['title' => 'Third Post'],
]);
$this->assertDatabaseHasMany('posts', [
['title' => 'First Post'],
['title' => 'Second Post'],
['title' => 'Third Post'],
]);
}
/** @test */
public function it_has_database_missing_many_assertion()
{
$this->assertDatabaseMissingMany('posts', [
['title' => 'Fourth Post'],
['title' => 'Fifth Post'],
]);
}
}
|
Update toJSON method to be compatable with json api |
function createModel(resource) {
// Dynamically create constructor for model
// TODO: Type checking + required vs non-required
var _createModel = function(obj) {
obj = obj || {};
for (var prop in resource.structure) {
if (resource.structure.hasOwnProperty(prop)) {
this[prop] = obj[prop];
}
}
};
_createModel.prototype.toJSON = function() {
return this.__toJSON();
};
_createModel.prototype.__toJSON = function() {
var json = {
data: {
type: resource.name
}
};
for (var prop in resource.structure) {
if (resource.structure.hasOwnProperty(prop)) {
json.data[prop] = this[prop];
}
}
return json;
};
return _createModel;
}
module.exports = createModel; |
function createModel(resource) {
// Dynamically create constructor for model
// TODO: Type checking + required vs non-required
var _createModel = function(obj) {
obj = obj || {};
for (var prop in resource.structure) {
if (resource.structure.hasOwnProperty(prop)) {
this[prop] = obj[prop];
}
}
};
_createModel.prototype.toJSON = function() {
return this.__toJSON();
};
_createModel.prototype.__toJSON = function() {
var json = {
type: resource.name
};
for (var prop in resource.structure) {
if (resource.structure.hasOwnProperty(prop)) {
json[prop] = this[prop];
}
}
return json;
};
return _createModel;
}
module.exports = createModel; |
Fix end_date management with Question Page | from django.contrib.postgres.fields import ArrayField
from django.db import models
class Track(models.Model):
"""
This model help us to store midi files.
It will be easier for everyone to have one place to listen
to the midi without having to install codecs, timidity or whatever
"""
title = models.CharField(max_length=255)
midi_file = models.FileField()
def __str__(self):
return self.title
class QuestionPage(models.Model):
"""
To avoid to write again and again stupid view for urls:
est-ce-que-cest-bientot-xxxxxx
with some response
"""
slug = models.SlugField(max_length=255)
start_date = models.DateField()
end_date = models.DateField()
answers = ArrayField(models.CharField(max_length=1024, blank=True))
answers_before = ArrayField(models.CharField(max_length=1024, blank=True))
answers_expired = ArrayField(models.CharField(max_length=1024, blank=True))
def __str__(self):
return self.slug
def get_answers(self, date):
if date < self.start_date:
return self.answers_before
elif date <= self.end_date:
return self.answers
else:
return self.answers_expired
| from django.contrib.postgres.fields import ArrayField
from django.db import models
class Track(models.Model):
"""
This model help us to store midi files.
It will be easier for everyone to have one place to listen
to the midi without having to install codecs, timidity or whatever
"""
title = models.CharField(max_length=255)
midi_file = models.FileField()
def __str__(self):
return self.title
class QuestionPage(models.Model):
"""
To avoid to write again and again stupid view for urls:
est-ce-que-cest-bientot-xxxxxx
with some response
"""
slug = models.SlugField(max_length=255)
start_date = models.DateField()
end_date = models.DateField()
answers = ArrayField(models.CharField(max_length=1024, blank=True))
answers_before = ArrayField(models.CharField(max_length=1024, blank=True))
answers_expired = ArrayField(models.CharField(max_length=1024, blank=True))
def __str__(self):
return self.slug
def get_answers(self, date):
if date < self.start_date:
return self.answers_before
elif date < self.end_date:
return self.answers
else:
return self.answers_expired
|
Rename the Facebook service to userService
Signed-off-by: Henrique Vicente <d390f26e2f50ad5716a9c69c58de1f5df9730e3b@gmail.com> | /*global angular */
/*jslint browser: true */
(function () {
'use strict';
var app;
app = angular.module('thin.gsApp', ['ngRoute', 'ngSanitize', 'alerts', 'auth'])
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
}]);
app.run(function ($rootScope, userService, alert) {
$rootScope.userService = userService;
});
}());
| /*global angular */
/*jslint browser: true */
(function () {
'use strict';
var app;
app = angular.module('thin.gsApp', ['ngRoute', 'ngSanitize', 'alerts', 'auth'])
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('!');
}]);
app.run(function ($rootScope, Facebook, alert) {
$rootScope.Facebook = Facebook;
});
}());
|
Reduce timeout for hiding the info box | function eventsourcetest() {
var alInfo = $("#alInfo");
var alSuccess = $("#alSuccess");
var ta = document.getElementById('output');
var source = new EventSource('php/gravity.sh.php');
alInfo.show();
alSuccess.hide();
source.addEventListener('message', function(e) {
if(e.data == "START"){
alInfo.show();
}
else if(e.data == "SUCCESS"){
alSuccess.show();
alInfo.delay(1000).fadeOut(2000, function() { alInfo.hide(); });
}
else if (e.data !== '')
{
ta.innerHTML += e.data;
}
}, false);
// Will be called when script has finished
source.addEventListener('error', function(e) {
source.close();
}, false);
}
$(function(){
eventsourcetest();
});
| function eventsourcetest() {
var alInfo = $("#alInfo");
var alSuccess = $("#alSuccess");
var ta = document.getElementById('output');
var source = new EventSource('php/gravity.sh.php');
alInfo.show();
alSuccess.hide();
source.addEventListener('message', function(e) {
if(e.data == "START"){
alInfo.show();
}
else if(e.data == "SUCCESS"){
alSuccess.show();
alInfo.delay(5000).fadeOut(2000, function() { alInfo.hide(); });
}
else if (e.data !== '')
{
ta.innerHTML += e.data;
}
}, false);
// Will be called when script has finished
source.addEventListener('error', function(e) {
source.close();
}, false);
}
$(function(){
eventsourcetest();
});
|
Update clean project jobs command | from django.core.management import BaseCommand
from django.db import ProgrammingError
from django.db.models import Q
from projects.models import Project
from runner.schedulers import notebook_scheduler, tensorboard_scheduler
class Command(BaseCommand):
@staticmethod
def _clean():
filters = Q(tensorboard_jobs=None) | Q(notebook_jobs=None)
for project in Project.objects.exclude(filters):
if project.has_notebook:
notebook_scheduler.stop_notebook(project, update_status=False)
if project.has_tensorboard:
tensorboard_scheduler.stop_tensorboard(project, update_status=False)
def handle(self, *args, **options):
try:
self._clean()
except ProgrammingError:
pass
| from django.core.management import BaseCommand
from django.db import ProgrammingError
from django.db.models import Q
from projects.models import Project
from runner.schedulers import notebook_scheduler, tensorboard_scheduler
class Command(BaseCommand):
@staticmethod
def _clean():
for project in Project.objects.exclude(Q(tensorboard=None) | Q(notebook=None)):
if project.has_notebook:
notebook_scheduler.stop_notebook(project, update_status=False)
if project.has_tensorboard:
tensorboard_scheduler.stop_tensorboard(project, update_status=False)
def handle(self, *args, **options):
try:
self._clean()
except ProgrammingError:
pass
|
Allow to access prices without auth. | import time
from django.utils import timezone
from rest_framework.decorators import (
api_view,
permission_classes,
)
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK
from codepot.models import Product
@api_view(['GET', ])
@permission_classes((AllowAny,))
def get_prices(request, **kwargs):
products = Product.objects.all()
now = timezone.now()
return Response(
data={
'prices': [
{
'id': p.id,
'name': p.name,
'dateTo': int(time.mktime(p.price_tier.date_to.timetuple()) * 1000),
'priceNet': p.price_net,
'priceVat': p.price_vat,
'active': p.price_tier.date_from < now < p.price_tier.date_to,
} for p in products
],
},
status=HTTP_200_OK
) | import time
from django.utils import timezone
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK
from codepot.models import Product
@api_view(['GET', ])
def get_prices(request, **kwargs):
products = Product.objects.all()
now = timezone.now()
return Response(
data={
'prices': [
{
'id': p.id,
'name': p.name,
'dateTo': int(time.mktime(p.price_tier.date_to.timetuple()) * 1000),
'priceNet': p.price_net,
'priceVat': p.price_vat,
'active': p.price_tier.date_from < now < p.price_tier.date_to,
} for p in products
],
},
status=HTTP_200_OK
) |
Fix test for upgrade-node command parser
Change-Id: I87746a3806f7dada04f5e650e17796fd4e65f55b | # 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.
def test_parser(mocker, octane_app):
m = mocker.patch('octane.commands.upgrade_node.upgrade_node')
octane_app.run(["upgrade-node", "--isolated", "1", "2", "3"])
assert not octane_app.stdout.getvalue()
assert not octane_app.stderr.getvalue()
m.assert_called_once_with(1, [2, 3], isolated=True, network_template=None)
| # 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.
def test_parser(mocker, octane_app):
m = mocker.patch('octane.commands.upgrade_node.upgrade_node')
octane_app.run(["upgrade-node", "--isolated", "1", "2", "3"])
assert not octane_app.stdout.getvalue()
assert not octane_app.stderr.getvalue()
m.assert_called_once_with(1, [2, 3], isolated=True, template=None)
|
Use sync fs method (to suppress no callback error) | 'use strict'
const fs = require('fs')
const gulp = require('gulp')
const lessModule = require('less')
const less = require('gulp-less')
const sourcemaps = require('gulp-sourcemaps')
const rename = require('gulp-rename')
const mkdirp = require('mkdirp')
const postcss = require('gulp-postcss')
const autoprefixer = require('autoprefixer')
const config = require('../config').less
const errorHandler = require('../util/error-handler')
lessModule.functions.functionRegistry.addMultiple(config.functions)
const processors = [
autoprefixer(),
]
if (process.env.NODE_ENV === 'production') {
const csswring = require('csswring')
processors.push(csswring())
}
gulp.task('less', () => {
mkdirp.sync(config.dest)
if (config.suffix) {
fs.writeFileSync(`${config.dest}.json`, JSON.stringify({ suffix: config.suffix }))
}
let pipe = gulp.src(config.src)
.pipe(sourcemaps.init())
.pipe(less(config.options).on('error', errorHandler))
.pipe(postcss(processors))
if (config.suffix) {
pipe = pipe.pipe(rename({ suffix: config.suffix }))
}
return pipe.pipe(sourcemaps.write('./maps'))
// .on('error', errorHandler)
.pipe(gulp.dest(config.dest))
})
| 'use strict'
const fs = require('fs')
const gulp = require('gulp')
const lessModule = require('less')
const less = require('gulp-less')
const sourcemaps = require('gulp-sourcemaps')
const rename = require('gulp-rename')
const mkdirp = require('mkdirp')
const postcss = require('gulp-postcss')
const autoprefixer = require('autoprefixer')
const config = require('../config').less
const errorHandler = require('../util/error-handler')
lessModule.functions.functionRegistry.addMultiple(config.functions)
const processors = [
autoprefixer(),
]
if (process.env.NODE_ENV === 'production') {
const csswring = require('csswring')
processors.push(csswring())
}
gulp.task('less', () => {
mkdirp.sync(config.dest)
if (config.suffix) {
fs.writeFile(`${config.dest}.json`, JSON.stringify({ suffix: config.suffix }))
}
let pipe = gulp.src(config.src)
.pipe(sourcemaps.init())
.pipe(less(config.options).on('error', errorHandler))
.pipe(postcss(processors))
if (config.suffix) {
pipe = pipe.pipe(rename({ suffix: config.suffix }))
}
return pipe.pipe(sourcemaps.write('./maps'))
// .on('error', errorHandler)
.pipe(gulp.dest(config.dest))
})
|
Make code of Qrcode unique | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateQrcodesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('qrcodes', function (Blueprint $table) {
$table->increments('id');
$table->string('code')->unique()->comment('代碼');
$table->unsignedInteger('student_id')->nullable()->comment('對應學生');
$table->timestamp('bind_at')->nullable()->comment('綁定時間');
$table->timestamps();
$table->foreign('student_id')->references('id')->on('students')
->onUpdate('cascade')->onDelete('set null');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('qrcodes');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateQrcodesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('qrcodes', function (Blueprint $table) {
$table->increments('id');
$table->string('code')->comment('代碼');
$table->unsignedInteger('student_id')->nullable()->comment('對應學生');
$table->timestamp('bind_at')->nullable()->comment('綁定時間');
$table->timestamps();
$table->foreign('student_id')->references('id')->on('students')
->onUpdate('cascade')->onDelete('set null');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('qrcodes');
}
}
|
Update splash view to use visible() method. | from django.shortcuts import get_object_or_404
import jingo
from challenges.models import Submission, Category
from projects.models import Project
def splash(request, project, slug, template_name='challenges/show.html'):
"""Show an individual project challenge."""
project = get_object_or_404(Project, slug=project)
challenge = get_object_or_404(project.challenge_set, slug=slug)
entries = (Submission.objects.visible()
.filter(phase__challenge=challenge)
.order_by("?"))
return jingo.render(request, 'ignite/splash.html', {
'challenge': challenge,
'project': project,
'phases': list(enumerate(challenge.phases.all(), start=1)),
'entries': entries[:10],
'categories': Category.objects.get_active_categories(),
})
| from django.shortcuts import get_object_or_404
import jingo
from challenges.models import Submission, Category
from projects.models import Project
def splash(request, project, slug, template_name='challenges/show.html'):
"""Show an individual project challenge."""
project = get_object_or_404(Project, slug=project)
challenge = get_object_or_404(project.challenge_set, slug=slug)
entries = Submission.objects.filter(
phase__challenge=challenge
).exclude(
is_draft=True
).extra(
order_by="?"
)
return jingo.render(request, 'ignite/splash.html', {
'challenge': challenge,
'project': project,
'phases': list(enumerate(challenge.phases.all(), start=1)),
'entries': entries[:10],
'categories': Category.objects.get_active_categories(),
})
|
Remove default slice length of null
There's already a check if it's null, so this seems superfluous. | <?php
namespace Haystack\Container;
use Haystack\HArray;
class HaystackArraySlice
{
private $arr;
/**
* @param HArray $array
*/
public function __construct(HArray $array)
{
$this->arr = $array->toArray();
}
/**
* @param $start
* @param integer|null $length
* @return array
*/
public function slice($start, $length)
{
if (is_null($start) || !is_numeric($start)) {
throw new \InvalidArgumentException("Slice parameter 1, \$start, must be an integer");
}
if (!is_null($length) && !is_numeric($length)) {
throw new \InvalidArgumentException("Slice parameter 2, \$length, must be null or an integer");
}
$maintainIndices = false;
return array_slice($this->arr, $start, $length, $maintainIndices);
}
}
| <?php
namespace Haystack\Container;
use Haystack\HArray;
class HaystackArraySlice
{
private $arr;
/**
* @param HArray $array
*/
public function __construct(HArray $array)
{
$this->arr = $array->toArray();
}
/**
* @param $start
* @param null $length
* @return array
*/
public function slice($start, $length = null)
{
if (is_null($start) || !is_numeric($start)) {
throw new \InvalidArgumentException("Slice parameter 1, \$start, must be an integer");
}
if (!is_null($length) && !is_numeric($length)) {
throw new \InvalidArgumentException("Slice parameter 2, \$length, must be null or an integer");
}
$maintainIndices = false;
return array_slice($this->arr, $start, $length, $maintainIndices);
}
}
|
Use the built in getters | package main
import (
"context"
"log"
"fmt"
"encoding/json"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
var Configuration = Config{}
func main() {
Configuration = Configuration.Init()
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: Configuration.GitHubToken},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
events, _, err := client.Activity.ListRepositoryEvents(ctx, Configuration.UpstreamOwner, Configuration.UpstreamRepo, nil)
if _, ok := err.(*github.RateLimitError); ok {
log.Println("hit rate limit")
}
for _, event := range events {
if *event.Type == "PullRequestEvent" {
prEvent := github.PullRequestEvent{}
err = json.Unmarshal(event.GetRawPayload(), &prEvent)
if err != nil {
panic(err)
}
prAction := prEvent.GetAction()
fmt.Printf("%s\n", prEvent.PullRequest.GetURL())
if prAction == "opened" {
//TODO: Check if we already have an open PR for this and add a comment saying upstream reopened it and remove the upsteam closed tag
MirrorPR(&prEvent)
} else if prAction == "closed" {
//AddLabel("Upstream Closed")
}
}
}
}
| package main
import (
"context"
"log"
"fmt"
"encoding/json"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
var Configuration = Config{}
func main() {
Configuration = Configuration.Init()
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: Configuration.GitHubToken},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
events, _, err := client.Activity.ListRepositoryEvents(ctx, Configuration.UpstreamOwner, Configuration.UpstreamRepo, nil)
if _, ok := err.(*github.RateLimitError); ok {
log.Println("hit rate limit")
}
for _, event := range events {
if *event.Type == "PullRequestEvent" {
prEvent := github.PullRequestEvent{}
err = json.Unmarshal(event.GetRawPayload(), &prEvent)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", *prEvent.PullRequest.URL)
if *prEvent.Action == "opened" {
MirrorPR(&prEvent) //TODO: Check if we already have an open PR for this and add a comment saying upstream reopened it
} else if *prEvent.Action == "closed" {
//AddLabel("Upstream Closed")
}
}
}
}
|
Add throws IOException to getCredentials | package org.bouncycastle.crypto.tls;
import java.io.IOException;
import java.util.Hashtable;
public interface TlsServer {
void init(TlsServerContext context);
ProtocolVersion selectVersion(ProtocolVersion clientVersion) throws IOException;
int selectCipherSuite(int[] offeredCipherSuites) throws IOException;
short selectCompressionMethod(short[] offeredCompressionMethods) throws IOException;
void notifySecureRenegotiation(boolean secureNegotiation) throws IOException;
// Hashtables are (Integer -> byte[])
Hashtable processClientExtensions(Hashtable serverExtensions) throws IOException;
TlsCredentials getCredentials() throws IOException;
TlsKeyExchange getKeyExchange() throws IOException;
CertificateRequest getCertificateRequest();
TlsCompression getCompression() throws IOException;
TlsCipher getCipher() throws IOException;
}
| package org.bouncycastle.crypto.tls;
import java.io.IOException;
import java.util.Hashtable;
public interface TlsServer {
void init(TlsServerContext context);
ProtocolVersion selectVersion(ProtocolVersion clientVersion) throws IOException;
int selectCipherSuite(int[] offeredCipherSuites) throws IOException;
short selectCompressionMethod(short[] offeredCompressionMethods) throws IOException;
void notifySecureRenegotiation(boolean secureNegotiation) throws IOException;
// Hashtables are (Integer -> byte[])
Hashtable processClientExtensions(Hashtable serverExtensions) throws IOException;
TlsCredentials getCredentials();
TlsKeyExchange getKeyExchange() throws IOException;
CertificateRequest getCertificateRequest();
TlsCompression getCompression() throws IOException;
TlsCipher getCipher() throws IOException;
}
|
Add comments and fix formatting. | 'use strict';
app.controller('party/profile', [
'$scope', 'displayService', 'party', 'pageService',
function ($scope, display, party, page) {
// This function takes in a user, and loops through
// volumes, and attaches a "volumeSelected" class
// to all the pertinent volumes.
$scope.clickUser = function(user) {
_.each($scope.volumes, function(v, i) {
$scope.volumes[i].selectedClass = (v.users.indexOf(user.id) > -1) ? "volumeSelected" : "" ;
});
};
// This function takes in a volume, and loops
// through the users and attaches a class
// called "userSelected"
$scope.clickVolume = function(volume) {
_.each($scope.users, function(u, i) {
$scope.users[i].selectedClass = (u.volumes.indexOf(volume.id) > -1) ? "userSelected" : "" ;
});
};
$scope.party = party;
$scope.volumes = party.volumes;
$scope.page = page;
$scope.profile = page.$location.path() === '/profile';
display.title = party.name;
}
]);
| 'use strict';
app.controller('party/profile', [
'$scope', 'displayService', 'party', 'pageService',
function ($scope, display, party, page) {
$scope.clickUser = function(user){
_.each($scope.volumes, function(v, i){
$scope.volumes[i].selectedClass = (v.users.indexOf(user.id) > -1) ? "volumeSelected" : "" ;
});
};
$scope.clickVolume = function(volume){
_.each($scope.users, function(u, i){
$scope.users[i].selectedClass = (u.volumes.indexOf(volume.id) > -1) ? "userSelected" : "" ;
});
};
$scope.party = party;
$scope.volumes = party.volumes;
$scope.page = page;
$scope.profile = page.$location.path() === '/profile';
display.title = party.name;
}
]);
|
Add credentials to psql production. | const databaseName = 'awstest';
module.exports = {
development: {
client: 'postgresql',
connection: `postgres://localhost:5432/${databaseName}`,
migrations: {
directory: __dirname + '/src/server/db/migrations'
},
seeds: {
directory: __dirname + '/src/server/db/seeds'
}
},
test: {
client: 'postgresql',
connection: `postgres://localhost:5432/${databaseName}_test`,
migrations: {
directory: __dirname + '/src/server/db/migrations'
},
seeds: {
directory: __dirname + '/src/server/db/seeds'
}
},
production: {
client: 'postgresql',
connection: `postgres://${process.env.RDS_USERNAME}:${process.env.RDS_PASSWORD}:${process.env.RDS_HOSTNAME}:${process.env.RDS_PORT}/${databaseName}`,
migrations: {
directory: __dirname + '/src/server/db/migrations'
},
seeds: {
directory: __dirname + '/src/server/db/seeds'
}
}
};
| const databaseName = 'awstest';
module.exports = {
development: {
client: 'postgresql',
connection: `postgres://localhost:5432/${databaseName}`,
migrations: {
directory: __dirname + '/src/server/db/migrations'
},
seeds: {
directory: __dirname + '/src/server/db/seeds'
}
},
test: {
client: 'postgresql',
connection: `postgres://localhost:5432/${databaseName}_test`,
migrations: {
directory: __dirname + '/src/server/db/migrations'
},
seeds: {
directory: __dirname + '/src/server/db/seeds'
}
},
production: {
client: 'postgresql',
connection: `postgres://${process.env.RDS_HOSTNAME}:${process.env.RDS_PORT}/${databaseName}`,
migrations: {
directory: __dirname + '/src/server/db/migrations'
},
seeds: {
directory: __dirname + '/src/server/db/seeds'
}
}
};
|
Fix --help examples to include '='
Fixes #9 | #!/usr/bin/env node
var argv = require('argv');
var polyjuice = require('./polyjuice');
var options = [
{
name: 'jshint',
type: 'string',
description: 'Defines the source file for jshint',
example: '\'polyjuice --jshint=.jshintrc\''
},
{
name: 'jscs',
type: 'string',
description: 'Defines the source file for jscs',
example: '\'polyjuice --jscs=.jscsrc\''
}
];
var src = argv.option(options).run();
var output = {};
if (src.options.jshint && src.options.jscs) {
output = polyjuice.to.eslint(src.options.jshint, src.options.jscs);
} else if (src.options.jshint) {
output = polyjuice.from.jshint(src.options.jshint);
} else if (src.options.jscs) {
output = polyjuice.from.jscs(src.options.jscs);
}
console.log(JSON.stringify(output, null, 2));
| #!/usr/bin/env node
var argv = require('argv');
var polyjuice = require('./polyjuice');
var options = [
{
name: 'jshint',
type: 'string',
description: 'Defines the source file for jshint',
example: '\'polyjuice --jshint .jshintrc\''
},
{
name: 'jscs',
type: 'string',
description: 'Defines the source file for jscs',
example: '\'polyjuice --jscs .jscsrc\''
}
];
var src = argv.option(options).run();
var output = {};
if (src.options.jshint && src.options.jscs) {
output = polyjuice.to.eslint(src.options.jshint, src.options.jscs);
} else if (src.options.jshint) {
output = polyjuice.from.jshint(src.options.jshint);
} else if (src.options.jscs) {
output = polyjuice.from.jscs(src.options.jscs);
}
console.log(JSON.stringify(output, null, 2));
|
Allow regexp for authorized array. | var env = require('../lib/environment');
var persona = require('../lib/persona');
var util = require('util');
exports.login = function(req, res){
if (req.method === 'GET')
return res.render("login.html");
var assertion = req.body.assertion;
persona.verify(assertion, function (err, email) {
if (err)
return res.send(util.inspect(err));
if (!userIsAuthorized(email))
return res.send(403, 'not authorized')
req.session.user = email;
return res.redirect('/admin');
});
};
exports.logout = function (req, res) {
req.session.destroy(function () {
return res.redirect('/login');
});
};
var middleware = exports.middleware = {};
middleware.requireAuth = function requireAuth(options) {
var whitelist = options.whitelist || [];
return function (req, res, next) {
var path = req.path;
var user = req.session.user;
if (whitelist.indexOf(path) > -1)
return next();
if (!user || !userIsAuthorized(user))
return res.redirect(options.redirectTo);
return next();
};
};
function userIsAuthorized(email) {
var admins = env.get('admins');
var authorized = false;
admins.forEach(function (admin) {
if (authorized) return;
var adminRe = new RegExp(admin.replace('*', '.+?'));
if (adminRe.test(email))
return authorized = true;
});
return authorized;
} | var env = require('../lib/environment');
var persona = require('../lib/persona');
var util = require('util');
exports.login = function(req, res){
if (req.method === 'GET')
return res.render("login.html");
var assertion = req.body.assertion;
persona.verify(assertion, function (err, email) {
if (err)
return res.send(util.inspect(err));
if (!userIsAuthorized(email))
return res.send(403, 'not authorized')
req.session.user = email;
return res.redirect('/admin');
});
};
exports.logout = function (req, res) {
req.session.destroy(function () {
return res.redirect('/login');
});
};
var middleware = exports.middleware = {};
middleware.requireAuth = function requireAuth(options) {
var whitelist = options.whitelist || [];
return function (req, res, next) {
var path = req.path;
var user = req.session.user;
if (whitelist.indexOf(path) > -1)
return next();
if (!user || !userIsAuthorized(user))
return res.redirect(options.redirectTo);
return next();
};
};
function userIsAuthorized(email) {
var admins = env.get('admins');
return admins.indexOf(email) >= -1;
} |
Add comment about the motivation behind YunohostError | # -*- coding: utf-8 -*-
""" License
Copyright (C) 2018 YUNOHOST.ORG
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses
"""
from moulinette.core import MoulinetteError
from moulinette import m18n
class YunohostError(MoulinetteError):
"""
Yunohost base exception
The (only?) main difference with MoulinetteError being that keys
are translated via m18n.n (namespace) instead of m18n.g (global?)
"""
def __init__(self, key, __raw_msg__=False, *args, **kwargs):
if __raw_msg__:
msg = key
else:
msg = m18n.n(key, *args, **kwargs)
super(YunohostError, self).__init__(msg, __raw_msg__=True)
| # -*- coding: utf-8 -*-
""" License
Copyright (C) 2018 YUNOHOST.ORG
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses
"""
from moulinette.core import MoulinetteError
from moulinette import m18n
class YunohostError(MoulinetteError):
"""Yunohost base exception"""
def __init__(self, key, __raw_msg__=False, *args, **kwargs):
if __raw_msg__:
msg = key
else:
msg = m18n.n(key, *args, **kwargs)
super(YunohostError, self).__init__(msg, __raw_msg__=True)
|
Use latest version of EuPy
The latest version of EuPy has better connection handling and improved
exponential backoff behavior. | #!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.1',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.2, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@75777c49503acb32e09f4c36f6f65cc35157694a#egg=eupy-1.2', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
| #!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.5.0',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.0, <2.0', 'simpleeval >=0.9, <0.10'],
dependency_links=['git+https://github.com/ArkaneMoose/EuPy.git@a569c35ea76a40b241a57669054b3247c3b4f960#egg=eupy-1.1', 'git+https://github.com/ArkaneMoose/simpleeval.git@ac33b805645ca616f11e64bb3330a12bc5fba658#egg=simpleeval-0.9.2'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
|
Refactor mutation to only return connection | import Relay from 'react-relay';
export default class extends Relay.Mutation {
getMutation() {
return Relay.QL`mutation{ ConnectOauth }`;
}
getFatQuery() {
return Relay.QL`
fragment on ConnectOauthPayload {
connection {
id,
importing,
expired,
connected,
}
}
`;
}
getConfigs() {
return [
{
type: 'FIELDS_CHANGE',
fieldIDs: {
connection: this.props.id,
},
},
];
}
getVariables() {
return {
...this.props,
};
}
}
| import Relay from 'react-relay';
export default class extends Relay.Mutation {
getMutation() {
return Relay.QL`mutation{ ConnectOauth }`;
}
getFatQuery() {
return Relay.QL`
fragment on ConnectOauthPayload {
developer {
connections
}
}
`;
}
getConfigs() {
return [
{
type: 'FIELDS_CHANGE',
fieldIDs: {
developer: this.props.id,
},
},
];
}
getVariables() {
return {
...this.props,
};
}
}
|
Fix for IE11 custom event | import assign from 'object-assign';
import { store } from './helpers';
export const MENU_SHOW = 'REACT_CONTEXTMENU_SHOW';
export const MENU_HIDE = 'REACT_CONTEXTMENU_HIDE';
export function dispatchGlobalEvent(eventName, opts, target = window) {
// Compatibale with IE
// @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work
let event;
if (typeof window.CustomEvent === 'function') {
event = new window.CustomEvent(eventName, { detail: opts });
} else {
event = document.createEvent('Event');
event.initCustomEvent(eventName, false, true, opts);
}
if (target) {
target.dispatchEvent(event);
assign(store, opts);
}
}
export function showMenu(opts = {}, target) {
dispatchGlobalEvent(MENU_SHOW, assign({}, opts, {type: MENU_SHOW}), target);
}
export function hideMenu(opts = {}, target) {
dispatchGlobalEvent(MENU_HIDE, assign({}, opts, {type: MENU_HIDE}), target);
}
| import assign from 'object-assign';
import { store } from './helpers';
export const MENU_SHOW = 'REACT_CONTEXTMENU_SHOW';
export const MENU_HIDE = 'REACT_CONTEXTMENU_HIDE';
export function dispatchGlobalEvent(eventName, opts, target = window) {
// Compatibale with IE
// @see http://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work
let event;
if (typeof window.CustomEvent === 'function') {
event = new window.CustomEvent(eventName, { detail: opts });
} else {
event = document.createEvent('Event');
event.initEvent(eventName, false, true, opts);
}
if (target) {
target.dispatchEvent(event);
assign(store, opts);
}
}
export function showMenu(opts = {}, target) {
dispatchGlobalEvent(MENU_SHOW, assign({}, opts, {type: MENU_SHOW}), target);
}
export function hideMenu(opts = {}, target) {
dispatchGlobalEvent(MENU_HIDE, assign({}, opts, {type: MENU_HIDE}), target);
}
|
Add better indentation (shorter line) | <?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / User / Controller
*/
namespace PH7;
use PH7\Framework\Module\Various as SysMod;
use PH7\Framework\Mvc\Router\Uri;
use PH7\Framework\Url\Header;
class AccountController extends Controller
{
public function index()
{
// Redirect this page to the user homepage
if (SysMod::isEnabled('user-dashboard')) {
$sUrl = Uri::get('user-dashboard', 'main', 'index');
} else {
$sUrl = Uri::get('user', 'main', 'index');
}
Header::redirect($sUrl);
}
/**
* @param string $sMail
* @param string $sHash
*
* @return void
*/
public function activate($sMail, $sHash)
{
(new UserCore)->activateAccount(
$sMail,
$sHash,
$this->config,
$this->registry
);
}
}
| <?php
/**
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
* @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / App / System / Module / User / Controller
*/
namespace PH7;
use PH7\Framework\Module\Various as SysMod;
use PH7\Framework\Mvc\Router\Uri;
use PH7\Framework\Url\Header;
class AccountController extends Controller
{
public function index()
{
// Redirect this page to the user homepage
if (SysMod::isEnabled('user-dashboard')) {
$sUrl = Uri::get('user-dashboard', 'main', 'index');
} else {
$sUrl = Uri::get('user', 'main', 'index');
}
Header::redirect($sUrl);
}
/**
* @param string $sMail
* @param string $sHash
*
* @return void
*/
public function activate($sMail, $sHash)
{
(new UserCore)->activateAccount($sMail, $sHash, $this->config, $this->registry);
}
}
|
Hide the root panel during the looper post to avoid rendering widgets while computing the layout | package org.nibiru.ui.gwt.loop;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.user.client.ui.RootPanel;
import org.nibiru.ui.core.api.loop.Looper;
import javax.inject.Inject;
import static com.google.common.base.Preconditions.checkNotNull;
public class SchedulerLooper implements Looper {
private final Scheduler scheduler;
@Inject
public SchedulerLooper(Scheduler scheduler) {
this.scheduler = checkNotNull(scheduler);
}
@Override
public void post(final Runnable runnable) {
checkNotNull(runnable);
RootPanel.get().setVisible(false);
scheduler.scheduleDeferred(() -> {
runnable.run();
RootPanel.get().setVisible(true);
});
}
}
| package org.nibiru.ui.gwt.loop;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Inject;
import org.nibiru.ui.core.api.loop.Looper;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
public class SchedulerLooper implements Looper {
private final Scheduler scheduler;
@Inject
public SchedulerLooper(Scheduler scheduler) {
this.scheduler = checkNotNull(scheduler);
}
@Override
public void post(final Runnable runnable) {
checkNotNull(runnable);
scheduler.scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
runnable.run();
}
});
}
}
|
Check returns logged in user array. | <?php
class Auth {
public $session;
public function __construct() {
$this->session = new \SlimSession\Helper;
}
public function login( $user ) {
$this->session->set('authenticated', [
'name' => $user->title,
'email' => $user->email,
'id' => $user->id
]);
}
public function logout() {
$this->session->delete('authenticated');
}
/**
* Check if logged in user has right properties. Throws an exception if not.
*
* @var string[] $allowed String with single id or array with allowed user id's
*
* @return string[] Array with logged in user name, email and id.
*/
public function check( $allowed ) {
if ( isset( $this->session->authenticated ) ) {
if (
( is_array( $allowed ) && in_array( $app->session->authenticated['id'], $allowed ) )
||
$this->session->authenticated['id'] == $allowed
) {
return $this->session->authenticated;
} else {
throw new \Exception('You are not allowed to perform this action.');
}
} else {
throw new \Exception('You need to log in to perform this action.');
}
}
}
?> | <?php
class Auth {
public $session;
public function __construct() {
$this->session = new \SlimSession\Helper;
}
public function login( $user ) {
$this->session->set('authenticated', [
'name' => $user->title,
'email' => $user->email,
'id' => $user->id
]);
}
public function logout() {
$this->session->delete('authenticated');
}
/**
* Check if logged in user has right properties
*
* @var string[] $allowed String with single id or array with allowed user id's
*
* @return boolean Returns true if logged in user id is in $allowed, false otherwise
*/
public function check( $allowed ) {
if ( isset( $this->session->authenticated ) ) {
if (
( is_array( $allowed ) && !in_array( $app->session->authenticated['id'], $allowed ) )
||
$this->session->authenticated['id'] != $allowed
) {
throw new \Exception('You are not allowed to perform this action.');
}
} else {
throw new \Exception('You need to log in to perform this action.');
}
}
}
?> |
Remove --disable-gpu flag when starting headless chrome
The `--disable-gpu` flag is [no longer
necessary](https://bugs.chromium.org/p/chromium/issues/detail?id=737678) and, at
least in some cases, is [causing
issues](https://bugs.chromium.org/p/chromium/issues/detail?id=982977).
This flag has already been [removed from ember-cli's
blueprints](https://github.com/ember-cli/ember-cli/pull/8774)
As you may already know, this project's test suite is run as part of [Ember
Data](https://github.com/emberjs/data)'s test suite to help catch regressions.
The flag has already been [removed from Ember Data's own testem
config](https://github.com/emberjs/data/pull/6298) but Ember Data's complete
test suite cannot successfully run until all of our external integration
partners have also removed this flag. | module.exports = {
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: [
'Chrome'
],
launch_in_dev: [
'Chrome'
],
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? '--no-sandbox' : null,
'--headless',
'--disable-dev-shm-usage',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900'
].filter(Boolean)
}
}
};
| module.exports = {
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: [
'Chrome'
],
launch_in_dev: [
'Chrome'
],
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? '--no-sandbox' : null,
'--headless',
'--disable-gpu',
'--disable-dev-shm-usage',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900'
].filter(Boolean)
}
}
};
|
lxd/lifecycle/network/load/balancer: Fix load balancer lifecycle types
Signed-off-by: Thomas Parrott <6b778ce645fb0e3dde76d79eccad490955b1ae74@canonical.com> | package lifecycle
import (
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/version"
)
// NetworkLoadBalancerAction represents a lifecycle event action for network load balancers.
type NetworkLoadBalancerAction string
// All supported lifecycle events for network load balancers.
const (
NetworkLoadBalancerCreated = NetworkLoadBalancerAction(api.EventLifecycleNetworkLoadBalancerCreated)
NetworkLoadBalancerDeleted = NetworkLoadBalancerAction(api.EventLifecycleNetworkLoadBalancerDeleted)
NetworkLoadBalancerUpdated = NetworkLoadBalancerAction(api.EventLifecycleNetworkLoadBalancerUpdated)
)
// Event creates the lifecycle event for an action on a network load balancer.
func (a NetworkLoadBalancerAction) Event(n network, listenAddress string, requestor *api.EventLifecycleRequestor, ctx map[string]any) api.EventLifecycle {
u := api.NewURL().Path(version.APIVersion, "networks", n.Name(), "load-balancers", listenAddress).Project(n.Project())
return api.EventLifecycle{
Action: string(a),
Source: u.String(),
Context: ctx,
Requestor: requestor,
}
}
| package lifecycle
import (
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/version"
)
// NetworkLoadBalancerAction represents a lifecycle event action for network load balancers.
type NetworkLoadBalancerAction string
// All supported lifecycle events for network forwards.
const (
NetworkLoadBalancerCreated = NetworkForwardAction(api.EventLifecycleNetworkLoadBalancerCreated)
NetworkLoadBalancerDeleted = NetworkForwardAction(api.EventLifecycleNetworkLoadBalancerDeleted)
NetworkLoadBalancerUpdated = NetworkForwardAction(api.EventLifecycleNetworkLoadBalancerUpdated)
)
// Event creates the lifecycle event for an action on a network forward.
func (a NetworkLoadBalancerAction) Event(n network, listenAddress string, requestor *api.EventLifecycleRequestor, ctx map[string]any) api.EventLifecycle {
u := api.NewURL().Path(version.APIVersion, "networks", n.Name(), "load-balancers", listenAddress).Project(n.Project())
return api.EventLifecycle{
Action: string(a),
Source: u.String(),
Context: ctx,
Requestor: requestor,
}
}
|
Add a bit of logging | /* eslint-env mocha */
const assert = require('assert')
const cm = require('cucumber-messages').io.cucumber.messages
const Gherkin = require('../src/Gherkin')
describe('Gherkin', () => {
it('parses gherkin from the file system', async () => {
const messages = await streamToArray(
Gherkin.fromPaths(['testdata/good/minimal.feature'])
)
assert.strictEqual(messages.length, 3)
})
it('parses gherkin from STDIN', async () => {
const source = cm.Source.fromObject({
uri: 'test.feature',
data: `Feature: Minimal
Scenario: minimalistic
Given the minimalism
`,
media: cm.Media.fromObject({
encoding: 'UTF-8',
contentType: 'text/x.cucumber.gherkin+plain',
}),
})
const messages = await streamToArray(Gherkin.fromSources([source]))
console.log('Messages', messages)
assert.strictEqual(messages.length, 3)
})
})
function streamToArray(readableStream) {
return new Promise((resolve, reject) => {
const items = []
readableStream.on('data', items.push.bind(items))
readableStream.on('error', reject)
readableStream.on('end', () => resolve(items))
})
}
| /* eslint-env mocha */
const assert = require('assert')
const cm = require('cucumber-messages').io.cucumber.messages
const Gherkin = require('../src/Gherkin')
describe('Gherkin', () => {
it('parses gherkin from the file system', async () => {
const messages = await streamToArray(
Gherkin.fromPaths(['testdata/good/minimal.feature'])
)
assert.strictEqual(messages.length, 3)
})
it('parses gherkin from STDIN', async () => {
const source = cm.Source.fromObject({
uri: 'test.feature',
data: `Feature: Minimal
Scenario: minimalistic
Given the minimalism
`,
media: cm.Media.fromObject({
encoding: 'UTF-8',
contentType: 'text/x.cucumber.gherkin+plain',
}),
})
const messages = await streamToArray(Gherkin.fromSources([source]))
assert.strictEqual(messages.length, 3)
})
})
function streamToArray(readableStream) {
return new Promise((resolve, reject) => {
const items = []
readableStream.on('data', items.push.bind(items))
readableStream.on('error', reject)
readableStream.on('end', () => resolve(items))
})
}
|
Remove unused constants from initial state. | import { Map, fromJS } from 'immutable';
export const initialTask = fromJS({
waypoints: [
{
name: 'Bicester Airfield',
position: {
lat: 51.9203333333333,
lng: -1.13141666666667
}
},
{
name: 'Bidford',
position: {
lat: 51.9203333333333,
lng: -1.84755000000000
}
},
{
name: 'Towcester',
position: {
lat: 52.1396333333333,
lng: -0.996850000000000
}
},
{
name: 'Bicester Airfield',
position: {
lat: 51.9203333333333,
lng: -1.13141666666667
}
}
],
defaultMapLocation: {
center: { lat: 51.9203333333333, lng: -1.13141666666667 },
zoom: 8
}
});
export const emptyLoggerTrace = Map();
| import { List, Map, fromJS } from 'immutable';
import moment from 'moment';
export const initialTask = fromJS({
waypoints: [
{
name: 'Bicester Airfield',
position: {
lat: 51.9203333333333,
lng: -1.13141666666667
}
},
{
name: 'Bidford',
position: {
lat: 51.9203333333333,
lng: -1.84755000000000
}
},
{
name: 'Towcester',
position: {
lat: 52.1396333333333,
lng: -0.996850000000000
}
},
{
name: 'Bicester Airfield',
position: {
lat: 51.9203333333333,
lng: -1.13141666666667
}
}
],
defaultMapLocation: {
center: { lat: 51.9203333333333, lng: -1.13141666666667 },
zoom: 8
}
});
export const emptyLoggerTrace = Map();
const now = moment.utc();
export const defaultTime = Map({
timeZoneName: "Coordinated Universal Time",
timestamps: List.of(now),
currentTimestamp: now
});
|
Add doc synopsis for the app factory. | """
.. module:: app_factory
:platform: linux
:synopsis: The class factory to create the application App.
.. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com>
.. modulecreated:: 6/27/15
"""
from zope.interface import implements
from planet_alignment.app.app import App
from planet_alignment.app.interface import IAppFactory
from planet_alignment.config.bunch_parser import BunchParser
from planet_alignment.data.system_data import SystemData
from planet_alignment.mgr.plugins_mgr import PluginsManager
class AppFactory(object):
"""This is the class factory for the App.
- **parameters** and **types**::
:param cmd_args: The command-line args.
:type cmd_args: argparse Namespace
"""
implements(IAppFactory)
def __init__(self, cmd_args):
data = BunchParser().parse(cmd_args.config)
self._system_data = SystemData(data)
self._plugins = PluginsManager(cmd_args.plugins)
self._time = cmd_args.time
def create(self):
"""Returns the created App object.
:return: Returns the App object.
:rtype: App class.
"""
return App(self._system_data, self._plugins, self._time)
| """
.. module:: app_factory
:platform: linux
:synopsis:
.. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com>
.. modulecreated:: 6/27/15
"""
from zope.interface import implements
from planet_alignment.app.app import App
from planet_alignment.app.interface import IAppFactory
from planet_alignment.config.bunch_parser import BunchParser
from planet_alignment.data.system_data import SystemData
from planet_alignment.mgr.plugins_mgr import PluginsManager
class AppFactory(object):
"""This is the class factory for the App.
- **parameters** and **types**::
:param cmd_args: The command-line args.
:type cmd_args: argparse Namespace
"""
implements(IAppFactory)
def __init__(self, cmd_args):
data = BunchParser().parse(cmd_args.config)
self._system_data = SystemData(data)
self._plugins = PluginsManager(cmd_args.plugins)
self._time = cmd_args.time
def create(self):
"""Returns the created App object.
:return: Returns the App object.
:rtype: App class.
"""
return App(self._system_data, self._plugins, self._time)
|
Fix non-ASCII characters that are problematic when building with ant in Ubuntu | package net.floodlightcontroller.core;
import org.projectfloodlight.openflow.protocol.OFMessage;
/**
* Copyright (c) 2014, NetIDE Consortium (Create-Net (CN), Telefonica Investigacion Y Desarrollo SA (TID), Fujitsu
* Technology Solutions GmbH (FTS), Thales Communications & Security SAS (THALES), Fundacion Imdea Networks (IMDEA),
* Universitaet Paderborn (UPB), Intel Research & Innovation Ireland Ltd (IRIIL), Fraunhofer-Institut fur
* Produktionstechnologie (IPT), Telcaria Ideas SL (TELCA) )
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Authors:
* Pedro A. Aranda Gutierrez, pedroa.aranda@telefonica.com
*/
public interface IControllerCompletionListener {
/**
* This mimics the behaviour of the IOFMessageListener. Will be called at the end of the message processing loop
* Modules implementing this interface will know when the message processing queue has digested an input event
*
* @param sw
* @param msg
* @param cntx
*
*/
public void onMessageConsumed(IOFSwitch sw, OFMessage msg, FloodlightContext cntx);
public String getName();
}
| package net.floodlightcontroller.core;
import org.projectfloodlight.openflow.protocol.OFMessage;
/**
* Copyright (c) 2014, NetIDE Consortium (Create-Net (CN), Telefonica Investigacion Y Desarrollo SA (TID), Fujitsu
* Technology Solutions GmbH (FTS), Thales Communications & Security SAS (THALES), Fundacion Imdea Networks (IMDEA),
* Universitaet Paderborn (UPB), Intel Research & Innovation Ireland Ltd (IRIIL), Fraunhofer-Institut für
* Produktionstechnologie (IPT), Telcaria Ideas SL (TELCA) )
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Authors:
* Pedro A. Aranda Gutiérrez, pedroa.aranda@telefonica.com
*/
public interface IControllerCompletionListener {
/**
* This mimics the behaviour of the IOFMessageListener. Will be called at the end of the message processing loop
* Modules implementing this interface will know when the message processing queue has digested an input event
*
* @param sw
* @param msg
* @param cntx
*
*/
public void onMessageConsumed(IOFSwitch sw, OFMessage msg, FloodlightContext cntx);
public String getName();
}
|
[UTL-69] Use the OpenGammaFudgeContext.getInstance() rather than GLOBAL_DEFAULT. | /**
* Copyright (C) 2009 - 2010 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.transport.jaxrs;
import org.fudgemsg.FudgeContext;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.fudge.OpenGammaFudgeContext;
/**
* Base class for the Fudge JAX-RS objects.
*/
/* package */abstract class FudgeBase {
/**
* The Fudge context.
*/
private FudgeContext _fudgeContext;
/**
* Creates an instance.
*/
protected FudgeBase() {
setFudgeContext(OpenGammaFudgeContext.getInstance());
}
//-------------------------------------------------------------------------
/**
* Gets the Fudge context.
* @return the context, not null
*/
public FudgeContext getFudgeContext() {
return _fudgeContext;
}
/**
* Sets the Fudge context.
* @param fudgeContext the context to use, not null
*/
public void setFudgeContext(final FudgeContext fudgeContext) {
ArgumentChecker.notNull(fudgeContext, "fudgeContext");
_fudgeContext = fudgeContext;
}
}
| /**
* Copyright (C) 2009 - 2010 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.transport.jaxrs;
import org.fudgemsg.FudgeContext;
import com.opengamma.util.ArgumentChecker;
/**
* Base class for the Fudge JAX-RS objects.
*/
/* package */abstract class FudgeBase {
/**
* The Fudge context.
*/
private FudgeContext _fudgeContext;
/**
* Creates an instance.
*/
protected FudgeBase() {
setFudgeContext(FudgeContext.GLOBAL_DEFAULT);
}
//-------------------------------------------------------------------------
/**
* Gets the Fudge context.
* @return the context, not null
*/
public FudgeContext getFudgeContext() {
return _fudgeContext;
}
/**
* Sets the Fudge context.
* @param fudgeContext the context to use, not null
*/
public void setFudgeContext(final FudgeContext fudgeContext) {
ArgumentChecker.notNull(fudgeContext, "fudgeContext");
_fudgeContext = fudgeContext;
}
}
|
Access property `default` using bracket notation | /**
* power-assert.js - Power Assert in JavaScript.
*
* https://github.com/power-assert-js/power-assert
*
* Copyright (c) 2013-2016 Takuto Wada
* Licensed under the MIT license.
* https://github.com/power-assert-js/power-assert/blob/master/MIT-LICENSE.txt
*/
'use strict';
var baseAssert = require('assert');
var empower = require('empower');
var formatter = require('power-assert-formatter');
var extend = require('xtend');
var define = require('define-properties');
var empowerOptions = {
modifyMessageOnRethrow: true,
saveContextOnRethrow: true
};
function customize (customOptions) {
var options = customOptions || {};
var poweredAssert = empower(
baseAssert,
formatter(options.output),
extend(empowerOptions, options.assertion)
);
poweredAssert.customize = customize;
return poweredAssert;
}
var defaultAssert = customize();
define(defaultAssert, { '__esModule': true });
defaultAssert['default'] = defaultAssert;
module.exports = defaultAssert;
| /**
* power-assert.js - Power Assert in JavaScript.
*
* https://github.com/power-assert-js/power-assert
*
* Copyright (c) 2013-2016 Takuto Wada
* Licensed under the MIT license.
* https://github.com/power-assert-js/power-assert/blob/master/MIT-LICENSE.txt
*/
'use strict';
var baseAssert = require('assert');
var empower = require('empower');
var formatter = require('power-assert-formatter');
var extend = require('xtend');
var define = require('define-properties');
var empowerOptions = {
modifyMessageOnRethrow: true,
saveContextOnRethrow: true
};
function customize (customOptions) {
var options = customOptions || {};
var poweredAssert = empower(
baseAssert,
formatter(options.output),
extend(empowerOptions, options.assertion)
);
poweredAssert.customize = customize;
return poweredAssert;
}
var defaultAssert = customize();
define(defaultAssert, { '__esModule': true });
defaultAssert.default = defaultAssert;
module.exports = defaultAssert;
|
Rename core method to drawSecretSantas | /* @flow */
type Category =
'Electronics' |
'Games' |
'Home Decoration';
type Wish = string | Array<Category>;
type User = {
name: string,
email: string,
wish?: Wish,
};
export type Selection = {
gifter: User,
recipient: User,
};
const drawSecretSantas = (users: Array<User>): Array<Selection> => {
// Shuffle all the users
const shuffled = users.sort(() => Math.floor(Math.random() * users.length));
// Create new list and just take all the shuffled users
const gifters = [...shuffled];
// Create a second list that takes the shuffled gifters ...
const recipients = [...shuffled];
// ... and move the first one to the last! We
// don't want pairs or small groups of the raffle. This keeps it snaky 🐍!
recipients.push(recipients.shift());
// Boom, let's raffle! 🎫
const raffle = users.map((user, raffleRound) => {
const gifter = gifters[raffleRound];
const recipient = recipients[raffleRound];
return {
gifter,
recipient,
};
});
return raffle;
};
export default drawSecretSantas;
| /* @flow */
type Category =
'Electronics' |
'Games' |
'Home Decoration';
type Wish = string | Array<Category>;
type User = {
name: string,
email: string,
wish?: Wish,
};
export type Selection = {
gifter: User,
recipient: User,
};
const raffleSecretSanta = (users: Array<User>): Array<Selection> => {
// Shuffle all the users
const shuffled = users.sort(() => Math.floor(Math.random() * users.length));
// Create new list and just take all the shuffled users
const gifters = [...shuffled];
// Create a second list that takes the shuffled gifters ...
const recipients = [...shuffled];
// ... and move the first one to the last! We
// don't want pairs or small groups of the raffle. This keeps it snaky 🐍!
recipients.push(recipients.shift());
// Boom, let's raffle! 🎫
const raffle = users.map((user, raffleRound) => {
const gifter = gifters[raffleRound];
const recipient = recipients[raffleRound];
return {
gifter,
recipient,
};
});
return raffle;
};
export default raffleSecretSanta;
|
Change linac mode pv to fake pvs |
from . import families as _families
def get_record_names(subsystem=None):
"""Return a dictionary of record names for given subsystem
each entry is another dictionary of model families whose
values are the indices in the pyaccel model of the magnets
that belong to the family. The magnet models ca be segmented,
in which case the value is a python list of lists."""
_dict = {}
return _dict
def get_family_names(family=None, prefix=''):
_dict = {}
return _dict
def get_element_names(element=None, prefix=''):
_dict = {}
return _dict
def get_magnet_names():
# return get_record_names('boma')
_dict = {}
return _dict
def get_pulsed_magnet_names():
# return get_record_names('boma')
_dict = {}
return _dict
|
from . import families as _families
def get_record_names(subsystem=None):
"""Return a dictionary of record names for given subsystem
each entry is another dictionary of model families whose
values are the indices in the pyaccel model of the magnets
that belong to the family. The magnet models ca be segmented,
in which case the value is a python list of lists."""
_dict = {'LIPA-MODE':{}}
return _dict
def get_family_names(family=None, prefix=''):
_dict = {}
return _dict
def get_element_names(element=None, prefix=''):
_dict = {}
return _dict
def get_magnet_names():
# return get_record_names('boma')
_dict = {}
return _dict
def get_pulsed_magnet_names():
# return get_record_names('boma')
_dict = {}
return _dict
|
Use settings from conf file | <?php
require __DIR__ . '/src/Vlc.php';
require file_exists(__DIR__ . '/conf.php') ? __DIR__ . '/conf.php' : __DIR__ . '/default.conf.php';
$vlc = new \jcisio\Karaoke\Vlc($host, $port, $password, $paths);
$items = $vlc->getFileList();
$action = isset($_GET['action']) ? $_GET['action'] : 'list';
switch ($action) {
case 'list':
$data = array();
foreach ($items as $uri) {
$data[] = array(pathinfo(urldecode($uri), PATHINFO_FILENAME));
}
die(json_encode(array('data' => $data)));
break;
case 'fullscreen':
$vlc->send('status', array('command' => 'fullscreen'));
return;
case 'audio':
$status = $vlc->send('status');
foreach ($status->Streams as $s){};return;
case 'play':
case 'queue':
$id = (int) $_GET['id'];
$command = $action == 'play' ? 'in_play' : 'in_enqueue';
$vlc->send('status', array(
'command' => $command,
'input' => $items[$id],
));
break;
}
| <?php
require __DIR__ . '/src/Vlc.php';
require file_exists(__DIR__ . '/conf.php') ? __DIR__ . '/conf.php' : __DIR__ . '/default.conf.php';
$vlc = new \jcisio\Karaoke\Vlc('127.0.0.1', 8080, '1234', array('/media/hd2/Karaoke'));
$items = $vlc->getFileList();
$action = isset($_GET['action']) ? $_GET['action'] : 'list';
switch ($action) {
case 'list':
$data = array();
foreach ($items as $uri) {
$data[] = array(pathinfo(urldecode($uri), PATHINFO_FILENAME));
}
die(json_encode(array('data' => $data)));
break;
case 'fullscreen':
$vlc->send('status', array('command' => 'fullscreen'));
return;
case 'audio':
$status = $vlc->send('status');
foreach ($status->Streams as $s){};return;
case 'play':
case 'queue':
$id = (int) $_GET['id'];
$command = $action == 'play' ? 'in_play' : 'in_enqueue';
$vlc->send('status', array(
'command' => $command,
'input' => $items[$id],
));
break;
}
|
Allow selectedLabel to be func | import React, { Component } from 'react'
export default (props) => {
let {
selectedOption,
selectedLabel,
placeholder,
disabled,
onClick,
handleOnChange,
handleKeyDown,
handleOnFocus,
} = props
let value = props.searchTerm
if (value === null) {
value = ''
if (selectedOption) {
if (typeof selectedLabel === 'function') {
value = selectedLabel(selectedOption)
} else {
value = selectedOption[selectedLabel]
}
}
}
return (
<div
className='powerselect__trigger'
onClick={onClick}
>
<input
className='powerselect__trigger-input'
autoComplete='off'
spellCheck='false'
placeholder={props.placeholder}
value={value}
disabled={disabled}
onChange={handleOnChange}
onKeyDown={handleKeyDown}
onFocus={handleOnFocus}
/>
<span
className='powerselect__trigger-status'
></span>
</div>
)
}
| import React, { Component } from 'react'
export default (props) => {
let {
selectedOption,
selectedLabel,
placeholder,
disabled,
onClick,
handleOnChange,
handleKeyDown,
handleOnFocus,
} = props
let value = props.searchTerm
if (value === null) {
value = selectedOption ? (selectedOption[selectedLabel] || '') : ''
}
return (
<div
className='powerselect__trigger'
onClick={onClick}
>
<input
className='powerselect__trigger-input'
autoComplete='off'
spellCheck='false'
placeholder={props.placeholder}
value={value}
disabled={disabled}
onChange={handleOnChange}
onKeyDown={handleKeyDown}
onFocus={handleOnFocus}
/>
<span
className='powerselect__trigger-status'
></span>
</div>
)
}
|
Add return value to Ember.TargetActionSupport.triggerAction() | var get = Ember.get, set = Ember.set;
Ember.TargetActionSupport = Ember.Mixin.create({
target: null,
action: null,
targetObject: Ember.computed(function() {
var target = get(this, 'target');
if (Ember.typeOf(target) === "string") {
return Ember.getPath(this, target);
} else {
return target;
}
}).property('target').cacheable(),
triggerAction: function() {
var action = get(this, 'action'),
target = get(this, 'targetObject');
if (target && action) {
if (typeof target.send === 'function') {
target.send(action, this);
} else {
if (typeof action === 'string') {
action = target[action];
}
action.call(target, this);
}
return true;
} else {
return false;
}
}
});
| var get = Ember.get, set = Ember.set;
Ember.TargetActionSupport = Ember.Mixin.create({
target: null,
action: null,
targetObject: Ember.computed(function() {
var target = get(this, 'target');
if (Ember.typeOf(target) === "string") {
return Ember.getPath(this, target);
} else {
return target;
}
}).property('target').cacheable(),
triggerAction: function() {
var action = get(this, 'action'),
target = get(this, 'targetObject');
if (target && action) {
if (typeof target.send === 'function') {
target.send(action, this);
} else {
if (typeof action === 'string') {
action = target[action];
}
action.call(target, this);
}
}
}
});
|
Swap positions of "contact us" and partner text in Info Bar. | <?php
/**
* Generates info bar footer.
**/
?>
<?php if (isset($zendesk_form) || isset($formatted_partners)): ?>
<footer class="info-bar">
<div class="wrapper">
<?php if (isset($formatted_partners)): ?>
<?php print t("In partnership with"); ?> <?php print $formatted_partners; ?>
<?php endif; ?>
<?php if (isset($zendesk_form)): ?>
<div class="info-bar__secondary">
<?php print t('Questions?'); ?> <a href="#" data-modal-href="#modal-contact-form"><?php print t('Contact Us'); ?></a>
<div data-modal id="modal-contact-form" class="modal--contact" role="dialog">
<h2 class="heading -banner"><?php print t('Contact Us'); ?></h2>
<div class="modal__block">
<p><?php print $zendesk_form_header; ?></p>
</div>
<div class="modal__block">
<?php print render($zendesk_form); ?>
</div>
</div>
</div>
<?php endif; ?>
</div>
</footer>
<?php endif; ?>
| <?php
/**
* Generates info bar footer.
**/
?>
<?php if (isset($zendesk_form) || isset($formatted_partners)): ?>
<footer class="info-bar">
<div class="wrapper">
<?php if (isset($zendesk_form)): ?>
<?php print t('Questions?'); ?> <a href="#" data-modal-href="#modal-contact-form"><?php print t('Contact Us'); ?></a>
<div data-modal id="modal-contact-form" class="modal--contact" role="dialog">
<h2 class="heading -banner"><?php print t('Contact Us'); ?></h2>
<div class="modal__block">
<p><?php print $zendesk_form_header; ?></p>
</div>
<div class="modal__block">
<?php print render($zendesk_form); ?>
</div>
</div>
<?php endif; ?>
<?php if (isset($formatted_partners)): ?>
<div class="info-bar__secondary">
<?php print t("In partnership with"); ?> <?php print $formatted_partners; ?>
</div>
<?php endif; ?>
</div>
</footer>
<?php endif; ?>
|
Handle refactoring manufacturers with spaces in their name. | #!/usr/bin/python
import copy
import os
import os.path
import sys
import merge
def setManufacturer(manufacturer, destinations, test=False):
base_part = {u'category': "", u'name': "", u'subpart': [], u'equivalent': [], u'urls': {u'store': [], u'related': [], u'manufacturer': []}, u'manufacturer': manufacturer, u'replacement': []}
for destination in destinations:
destination = destination.decode("utf-8")
new_destination = os.path.join(manufacturer.replace(" ", "-"), os.path.basename(destination))
if test:
print(destination, new_destination)
else:
merge.mergeFiles([destination], new_destination, part=copy.deepcopy(base_part))
if __name__ == "__main__":
manufacturer = sys.argv[1].decode("utf-8")
destinations = sys.argv[2:]
setManufacturer(manufacturer, destinations)
| #!/usr/bin/python
import copy
import os
import os.path
import sys
import merge
def setManufacturer(manufacturer, destinations, test=False):
base_part = {u'category': "", u'name': "", u'subpart': [], u'equivalent': [], u'urls': {u'store': [], u'related': [], u'manufacturer': []}, u'manufacturer': manufacturer, u'replacement': []}
for destination in destinations:
destination = destination.decode("utf-8")
new_destination = os.path.join(manufacturer, os.path.basename(destination))
if test:
print(destination, new_destination)
else:
merge.mergeFiles([destination], new_destination, part=copy.deepcopy(base_part))
if __name__ == "__main__":
manufacturer = sys.argv[1].decode("utf-8")
destinations = sys.argv[2:]
setManufacturer(manufacturer, destinations)
|
Fix visibility in head look packet. | package org.spacehq.mc.protocol.packet.ingame.server.entity;
import org.spacehq.packetlib.io.NetInput;
import org.spacehq.packetlib.io.NetOutput;
import org.spacehq.packetlib.packet.Packet;
import java.io.IOException;
public class ServerEntityHeadLookPacket implements Packet {
private int entityId;
private float headYaw;
@SuppressWarnings("unused")
private ServerEntityHeadLookPacket() {
}
public ServerEntityHeadLookPacket(int entityId, float headYaw) {
this.entityId = entityId;
this.headYaw = headYaw;
}
public int getEntityId() {
return this.entityId;
}
public float getHeadYaw() {
return this.headYaw;
}
@Override
public void read(NetInput in) throws IOException {
this.entityId = in.readVarInt();
this.headYaw = in.readByte() * 360 / 256f;
}
@Override
public void write(NetOutput out) throws IOException {
out.writeVarInt(this.entityId);
out.writeByte((byte) (this.headYaw * 256 / 360));
}
@Override
public boolean isPriority() {
return false;
}
}
| package org.spacehq.mc.protocol.packet.ingame.server.entity;
import org.spacehq.packetlib.io.NetInput;
import org.spacehq.packetlib.io.NetOutput;
import org.spacehq.packetlib.packet.Packet;
import java.io.IOException;
public class ServerEntityHeadLookPacket implements Packet {
protected int entityId;
protected float headYaw;
@SuppressWarnings("unused")
private ServerEntityHeadLookPacket() {
}
public ServerEntityHeadLookPacket(int entityId, float headYaw) {
this.entityId = entityId;
this.headYaw = headYaw;
}
public int getEntityId() {
return this.entityId;
}
public float getHeadYaw() {
return this.headYaw;
}
@Override
public void read(NetInput in) throws IOException {
this.entityId = in.readVarInt();
this.headYaw = in.readByte() * 360 / 256f;
}
@Override
public void write(NetOutput out) throws IOException {
out.writeVarInt(this.entityId);
out.writeByte((byte) (this.headYaw * 256 / 360));
}
@Override
public boolean isPriority() {
return false;
}
}
|
Add forked slackpy as a dependency | from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
version = '0.1'
setup(name='zrunner',
version=version,
description="Utilities for running and benchmarking Zonation",
long_description="""\
""",
classifiers=[],
keywords='zonation test cbig',
author='Joona Lehtom\xc3\xa4ki',
author_email='joona.lehtomaki@gmail.com',
url='',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
"pyyaml"
],
dependency_links = ['https://github.com/jlehtoma/slackpy/tarball/master#egg=slackpy-0.1.4'],
entry_points={'console_scripts': [
'zrunner = zrunner.runner:main',
'zreader = zrunner.reader:main'
]
},
)
| from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
version = '0.1'
setup(name='zrunner',
version=version,
description="Utilities for running and benchmarking Zonation",
long_description="""\
""",
classifiers=[],
keywords='zonation test cbig',
author='Joona Lehtom\xc3\xa4ki',
author_email='joona.lehtomaki@gmail.com',
url='',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
"pyyaml"
],
entry_points={'console_scripts': [
'zrunner = zrunner.runner:main',
'zreader = zrunner.reader:main'
]
},
)
|
Add none webpack mode for unit tests | import path from 'path';
import nodeExternals from 'webpack-node-externals';
export default {
mode: 'none',
entry: {
js: [path.resolve(__dirname, './suite/index.js')],
},
output: {
path: __dirname,
filename: 'testBundle.js',
},
target: 'node',
externals: [nodeExternals()],
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ['null-loader'],
},
],
},
resolve: {
extensions: ['.js', '.css'],
},
};
| import path from 'path';
import nodeExternals from 'webpack-node-externals';
export default {
entry: {
js: [path.resolve(__dirname, './suite/index.js')],
},
output: {
path: __dirname,
filename: 'testBundle.js',
},
target: 'node',
externals: [nodeExternals()],
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.css$/,
exclude: /node_modules/,
use: ['null-loader'],
},
],
},
resolve: {
extensions: ['.js', '.css'],
},
};
|
Add login and logout to allowed views in DEMO_MODE. | """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
'main.views.reference_genome_list_view',
'main.views.reference_genome_view',
'main.views.sample_list_view',
'main.views.alignment_list_view',
'main.views.alignment_view',
'main.views.sample_alignment_error_view',
'main.views.variant_set_list_view',
'main.views.variant_set_view',
'main.views.single_variant_view',
'main.xhr_handlers.get_variant_list',
'main.xhr_handlers.get_variant_set_list',
'main.xhr_handlers.get_gene_list',
'main.xhr_handlers.get_alignment_groups',
'main.xhr_handlers.is_materialized_view_valid',
'main.xhr_handlers.get_ref_genomes',
'main.xhr_handlers.compile_jbrowse_and_redirect',
'main.template_xhrs.variant_filter_controls',
'main.demo_view_overrides.login_demo_account',
'django.contrib.auth.views.logout'
]
| """
Settings for DEMO_MODE.
Must set DEMO_MODE = True in local_settings.py.
"""
# Views that are visible in demo mode.
DEMO_SAFE_VIEWS = [
'main.views.home_view',
'main.views.project_list_view',
'main.views.project_view',
'main.views.tab_root_analyze',
'main.views.reference_genome_list_view',
'main.views.reference_genome_view',
'main.views.sample_list_view',
'main.views.alignment_list_view',
'main.views.alignment_view',
'main.views.sample_alignment_error_view',
'main.views.variant_set_list_view',
'main.views.variant_set_view',
'main.views.single_variant_view',
'main.xhr_handlers.get_variant_list',
'main.xhr_handlers.get_variant_set_list',
'main.xhr_handlers.get_gene_list',
'main.xhr_handlers.get_alignment_groups',
'main.xhr_handlers.is_materialized_view_valid',
'main.xhr_handlers.get_ref_genomes',
'main.xhr_handlers.compile_jbrowse_and_redirect',
'main.template_xhrs.variant_filter_controls',
]
|
Remove extraneous vim configuration comments
Remove line containing
comment - # vim: tabstop=4 shiftwidth=4 softtabstop=4
Change-Id: I31e4ee4112285f0daa5f2dd50db0344f4876820d
Closes-Bug:#1229324 | # Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pkg_resources
try:
# First, try to get our version out of PKG-INFO. If we're installed,
# this'll let us find our version without pulling in pbr. After all, if
# we're installed on a system, we're not in a Git-managed source tree, so
# pbr doesn't really buy us anything.
version_string = pkg_resources.get_provider(
pkg_resources.Requirement.parse('python-swiftclient')).version
except pkg_resources.DistributionNotFound:
# No PKG-INFO? We're probably running from a checkout, then. Let pbr do
# its thing to figure out a version number.
import pbr.version
version_string = str(pbr.version.VersionInfo('python-swiftclient'))
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pkg_resources
try:
# First, try to get our version out of PKG-INFO. If we're installed,
# this'll let us find our version without pulling in pbr. After all, if
# we're installed on a system, we're not in a Git-managed source tree, so
# pbr doesn't really buy us anything.
version_string = pkg_resources.get_provider(
pkg_resources.Requirement.parse('python-swiftclient')).version
except pkg_resources.DistributionNotFound:
# No PKG-INFO? We're probably running from a checkout, then. Let pbr do
# its thing to figure out a version number.
import pbr.version
version_string = str(pbr.version.VersionInfo('python-swiftclient'))
|
Move imports to beginning of code | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import os
from IPython.lib import passwd
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.MultiKernelManager.default_kernel_name = 'python2'
# sets a password if PASSWORD is set in the environment
if 'PASSWORD' in os.environ:
c.NotebookApp.password = passwd(os.environ['PASSWORD'])
del os.environ['PASSWORD']
| # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.MultiKernelManager.default_kernel_name = 'python2'
# sets a password if PASSWORD is set in the environment
if 'PASSWORD' in os.environ:
import os
from IPython.lib import passwd
c.NotebookApp.password = passwd(os.environ['PASSWORD'])
del os.environ['PASSWORD']
|
Move namedtuple definition outside of argspec function | import sys
import itertools
import inspect
from collections import namedtuple
_PY2 = sys.version_info.major == 2
if _PY2:
range_ = xrange
zip_ = itertools.izip
def iteritems(d):
return d.iteritems()
def itervalues(d):
return d.itervalues()
def iterkeys(d):
return d.iterkeys()
zip_longest = itertools.izip_longest
def getargspec(f):
return inspect.getargspec(f)
else:
range_ = range
zip_ = zip
def iteritems(d):
return iter(d.items())
def itervalues(d):
return iter(d.values())
def iterkeys(d):
return iter(d.keys())
zip_longest = itertools.zip_longest
_ArgSpec = namedtuple('ArgSpec', ('args', 'varargs', 'keywords', 'defaults'))
def getargspec(f):
argspec = inspect.getfullargspec(f)
# FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
return _ArgSpec(argspec.args, argspec.varargs, argspec.varkw, argspec.defaults)
| import sys
import itertools
import inspect
from collections import namedtuple
_PY2 = sys.version_info.major == 2
if _PY2:
range_ = xrange
zip_ = itertools.izip
def iteritems(d):
return d.iteritems()
def itervalues(d):
return d.itervalues()
def iterkeys(d):
return d.iterkeys()
zip_longest = itertools.izip_longest
def getargspec(f):
return inspect.getargspec(f)
else:
range_ = range
zip_ = zip
def iteritems(d):
return iter(d.items())
def itervalues(d):
return iter(d.values())
def iterkeys(d):
return iter(d.keys())
zip_longest = itertools.zip_longest
def getargspec(f):
ArgSpec = namedtuple('ArgSpec', ('args', 'varargs', 'keywords', 'defaults'))
# FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)
argspec = inspect.getfullargspec(f)
return ArgSpec(argspec.args, argspec.varargs, argspec.varkw, argspec.defaults)
|
Update deps for initial release | __version__ = '0.1'
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
setup(name='retools',
version=__version__,
description='Redis Tools',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
],
keywords='cache redis queue lock',
author="Ben Bangert",
author_email="ben@groovie.org",
url="",
license="MIT",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
tests_require = ['pkginfo', 'Mock>=0.7', 'nose'],
install_requires=[
# "setproctitle>=1.1.2",
"redis>=2.4.5",
# "venusian>=0.9",
# "cmdln>=1.1",
],
)
| __version__ = '0.1'
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
setup(name='retools',
version=__version__,
description='Redis Tools',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Intended Audience :: Developers",
"Programming Language :: Python",
],
keywords='cache redis queue',
author="Ben Bangert",
author_email="ben@groovie.org",
url="",
license="MIT",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
tests_require = ['pkginfo', 'Mock>=0.7', 'nose'],
install_requires=[
"setproctitle>=1.1.2",
"redis>=2.4.5",
"venusian>=0.9",
"decorator>=3.3.0",
],
)
|
Add a watcher for the index.html file | var gulp = require('gulp');
var $ = require('gulp-load-plugins')({
pattern: '*'
});
var port = process.env.SERVER_PORT || 3000;
$.requireDir('../../gulp');
// Builds the documentation and framework files
gulp.task('build', ['sass', 'javascript']);
// Starts a BrowerSync instance
gulp.task('serve', ['build'], function(){
$.browserSync.init({server: './dist', port: port});
});
// Watch files for changes
gulp.task('watch', function() {
gulp.watch('lib/scss/**/*.scss', ['sass:lib', $.browserSync.reload]);
gulp.watch('assets/scss/**/*.scss', ['sass:theme', $.browserSync.reload]);
gulp.watch('lib/js/**/*.js', ['javascript:lib', $.browserSync.reload]);
gulp.watch('assets/js/**/*.js', ['javascript:theme', $.browserSync.reload]);
gulp.watch('dist/index.html', [$.browserSync.reload]);
});
// Runs all of the above tasks and then waits for files to change
gulp.task('default', ['serve', 'watch']);
| var gulp = require('gulp');
var $ = require('gulp-load-plugins')({
pattern: '*'
});
var port = process.env.SERVER_PORT || 3000;
$.requireDir('../../gulp');
// Builds the documentation and framework files
gulp.task('build', ['sass', 'javascript']);
// Starts a BrowerSync instance
gulp.task('serve', ['build'], function(){
$.browserSync.init({server: './dist', port: port});
});
// Watch files for changes
gulp.task('watch', function() {
gulp.watch('lib/scss/**/*.scss', ['sass:lib', $.browserSync.reload]);
gulp.watch('assets/scss/**/*.scss', ['sass:theme', $.browserSync.reload]);
gulp.watch('lib/js/**/*.js', ['javascript:lib', $.browserSync.reload]);
gulp.watch('assets/js/**/*.js', ['javascript:theme', $.browserSync.reload]);
});
// Runs all of the above tasks and then waits for files to change
gulp.task('default', ['serve', 'watch']);
|
Check for duration before saving to db | export default log
import Entry from '../entry'
import prompt from 'prompt'
import chrono from 'chrono-node'
import {write} from './output'
import chalk from 'chalk'
import db from '../db'
function log (yargs) {
let argv = yargs
.usage('Usage: tick log [options]')
.option('d', {
alias: 'date',
describe: 'date for tick'
})
.option('m', {
alias: 'message',
describe: 'entry message. E.g. 8am-12pm fixing bugs #tickbin'
})
.help('h')
.alias('h', 'help')
.argv
let {message, date} = argv
date = chrono.parseDate(date)
if (!message) {
prompt.message = ''
prompt.delimiter = ''
prompt.start()
prompt.get('message', function(err, res) {
if (!err) createEntry(res.message, {date})
})
} else {
createEntry(message, {date})
}
}
function createEntry (message, opts = {}) {
let entry = new Entry(message, opts)
if (!entry.duration) {
console.error(chalk.bgRed('error'), 'You must specify a time in your message')
return
}
db.put(entry.toJSON())
.then(doc => {
console.log(chalk.bgGreen('saved'))
write(entry)
})
.catch(err => {
console.error(chalk.bgRed('error'), err)
})
}
| export default log
import Entry from '../entry'
import prompt from 'prompt'
import chrono from 'chrono-node'
import {write} from './output'
import chalk from 'chalk'
import db from '../db'
function log (yargs) {
let argv = yargs
.usage('Usage: tick log [options]')
.option('d', {
alias: 'date',
describe: 'date for tick'
})
.option('m', {
alias: 'message',
describe: 'entry message. E.g. 8am-12pm fixing bugs #tickbin'
})
.help('h')
.alias('h', 'help')
.argv
let {message, date} = argv
date = chrono.parseDate(date)
if (!message) {
prompt.message = ''
prompt.delimiter = ''
prompt.start()
prompt.get('message', function(err, res) {
if (!err) createEntry(res.message, {date})
})
} else {
createEntry(message, {date})
}
}
function createEntry (message, opts = {}) {
let entry = new Entry(message, opts)
db.put(entry.toJSON())
.then(doc => {
if (!entry.duration) {
throw('You must specify a time in your message')
}
console.log(chalk.bgGreen('saved'))
write(entry)
})
.catch(err => {
console.error(chalk.bgRed('error'), err)
})
}
|
Implement the getInstance() for the factory. | /*
* 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.jsmpp.session.connection.socket;
import java.io.IOException;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import org.jsmpp.session.connection.Connection;
import org.jsmpp.session.connection.ConnectionFactory;
/**
* @author pmoerenhout
*
* -Djavax.net.ssl.trustStore=/path/to/your/cacerts
* -Djavax.net.ssl.trustStorePassword=password
* -Djavax.net.ssl.trustStoreType=PKCS12
*/
public class SSLSocketConnectionFactory implements ConnectionFactory {
private static final SSLSocketConnectionFactory connFactory = new SSLSocketConnectionFactory();
private SocketFactory socketFactory;
public SSLSocketConnectionFactory() {
socketFactory = SSLSocketFactory.getDefault();
}
public static SSLSocketConnectionFactory getInstance() {
return connFactory;
}
@Override
public Connection createConnection(String host, int port)
throws IOException {
return new SocketConnection(socketFactory.createSocket(host, port));
}
} | /*
* 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.jsmpp.session.connection.socket;
import java.io.IOException;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import org.jsmpp.session.connection.Connection;
import org.jsmpp.session.connection.ConnectionFactory;
/**
* @author pmoerenhout
*
* -Djavax.net.ssl.trustStore=/path/to/your/cacerts
* -Djavax.net.ssl.trustStorePassword=password
* -Djavax.net.ssl.trustStoreType=PKCS12
*/
public class SSLSocketConnectionFactory implements ConnectionFactory {
private SocketFactory socketFactory;
private SSLSocketConnectionFactory() {
socketFactory = SSLSocketFactory.getDefault();
}
@Override
public Connection createConnection(String host, int port)
throws IOException {
return new SocketConnection(socketFactory.createSocket(host, port));
}
} |
Check new peripheral names against regex | import React from 'react';
import InlineEdit from 'react-edit-inline';
import Ansible from '../../utils/Ansible';
var NameEdit = React.createClass({
propTypes: {
name: React.PropTypes.string,
id: React.PropTypes.string
},
dataChange(data) {
var x = new RegExp("^[A-Za-z][A-Za-z0-9]+$");
if (x.test(data.name)) {
Ansible.sendMessage('custom_names', {
id: this.props.id,
name: data.name
});
}
},
render() {
return (
<div>
<InlineEdit
className="static"
activeClassName="editing"
text={this.props.name}
change={this.dataChange}
paramName="name"
style = {{
backgroundColor: 'white',
minWidth: 150,
display: 'inline-block',
margin: 0,
padding: 0,
fontSize:15
}}
/>
</div>
);
}
});
export default NameEdit;
| import React from 'react';
import InlineEdit from 'react-edit-inline';
import Ansible from '../../utils/Ansible';
var NameEdit = React.createClass({
propTypes: {
name: React.PropTypes.string,
id: React.PropTypes.string
},
dataChange(data) {
Ansible.sendMessage('custom_names', {
id: this.props.id,
name: data.name
});
},
render() {
return (
<div>
<InlineEdit
className="static"
activeClassName="editing"
text={this.props.name}
change={this.dataChange}
paramName="name"
style = {{
backgroundColor: 'white',
minWidth: 150,
display: 'inline-block',
margin: 0,
padding: 0,
fontSize:15
}}
/>
</div>
);
}
});
export default NameEdit;
|
Add approved set to gmu | """
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13',
'com_1920_2811'
]
| """
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http://mars.gmu.edu/oai/request'
timezone_granularity = True
property_list = [
'type', 'source', 'setSpec',
'format', 'identifier'
]
approved_sets = [
'col_1920_6102',
'col_1920_6039',
'com_1920_262',
'com_1920_466',
'com_1920_1320',
'com_1920_2852',
'com_1920_2869',
'com_1920_2883',
'com_1920_3011',
'com_1920_7520',
'com_1920_8132',
'com_1920_8138',
'col_1920_13'
]
|
Add the `author` annotation in the documentation. | /*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.base;
import com.google.common.base.Converter;
/**
* Serves as converter from {@code I} to {@code String} with an associated
* reverse function from {@code String} to {@code I}.
*
* <p>It is used for converting back and forth between the different
* representations of the same information.
*
* @author Alexander Yevsyukov
* @author Illia Shepilov
* @see #convert(Object)
* @see #reverse()
*/
public abstract class Stringifier<I> extends Converter<I, String> {
}
| /*
* Copyright 2017, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.base;
import com.google.common.base.Converter;
/**
* Serves as converter from {@code I} to {@code String} with an associated
* reverse function from {@code String} to {@code I}.
*
* <p>It is used for converting back and forth between the different
* representations of the same information.
*
* @author Alexander Yevsyukov
* @see #convert(Object)
* @see #reverse()
*/
public abstract class Stringifier<I> extends Converter<I, String> {
}
|
Add Odoo Community Association (OCA) in authors | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "Move existing attachments to filesystem",
"version": "1.0",
"author": "Therp BV,Odoo Community Association (OCA)",
"license": "AGPL-3",
"complexity": "normal",
"category": "Knowledge Management",
"depends": [
'base',
],
"data": [
"data/ir_cron.xml",
"data/init.xml",
],
"test": [
],
"auto_install": False,
"installable": True,
"application": False,
"external_dependencies": {
'python': ['dateutil', 'pytz'],
},
}
| # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name": "Move existing attachments to filesystem",
"version": "1.0",
"author": "Therp BV",
"license": "AGPL-3",
"complexity": "normal",
"category": "Knowledge Management",
"depends": [
'base',
],
"data": [
"data/ir_cron.xml",
"data/init.xml",
],
"test": [
],
"auto_install": False,
"installable": True,
"application": False,
"external_dependencies": {
'python': ['dateutil', 'pytz'],
},
}
|
Remove unnecessary use of underscore
It's clearer to just use the map function on an array directly, since
it's always there in node. | "use strict";
var util = require('util');
var validate = require('../validate');
var Storage = require('../storage');
function validateBody (req, res, next) {
var collectionName = req.params.collection;
var body = req.body;
// If there is no id create one
if (!body.id) {
body.id = req.params.id || Storage.generateID();
}
validate(collectionName, body, function (err, errors) {
if (err) {
return next(err);
} else if (errors.length === 0) {
return next(null);
} else {
var details = errors.map(function (error) {
return util.format(
"Error '%s' with '%s'.",
error.message,
error.schemaUri
);
});
res
.status(400)
.send({errors: details});
}
});
}
module.exports = validateBody;
| "use strict";
var util = require('util');
var _ = require('underscore');
var validate = require('../validate');
var Storage = require('../storage');
function validateBody (req, res, next) {
var collectionName = req.params.collection;
var body = req.body;
// If there is no id create one
if (!body.id) {
body.id = req.params.id || Storage.generateID();
}
validate(collectionName, body, function (err, errors) {
if (err) {
return next(err);
} else if (errors.length === 0) {
return next(null);
} else {
var details = _.map(errors, function (error) {
return util.format(
"Error '%s' with '%s'.",
error.message,
error.schemaUri
);
});
res
.status(400)
.send({errors: details});
}
});
}
module.exports = validateBody;
|
Fix path in bootstrap script | <?php
use Zend\Mvc\Application;
use Zend\Stdlib\ArrayUtils;
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server') {
$path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
if (__FILE__ !== $path && is_file($path)) {
return false;
}
unset($path);
}
// Composer autoloading
include __DIR__ . '/../vendor/autoload.php';
if (! class_exists(Application::class)) {
throw new RuntimeException(
"Unable to load application.\n"
. "- Type `composer install` if you are developing locally.\n"
. "- Type `vagrant ssh -c 'composer install'` if you are using Vagrant.\n"
. "- Type `docker-compose run zf composer install` if you are using Docker.\n"
);
}
// Retrieve configuration
$appConfig = require __DIR__ . '/../config/application.config.php';
if (file_exists(__DIR__ . '/../config/development.config.php')) {
$appConfig = ArrayUtils::merge($appConfig, require __DIR__ . '/../config/development.config.php');
}
// Run the application!
Application::init($appConfig)->run();
| <?php
use Zend\Mvc\Application;
use Zend\Stdlib\ArrayUtils;
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === 'cli-server') {
$path = realpath(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
if (__FILE__ !== $path && is_file($path)) {
return false;
}
unset($path);
}
// Composer autoloading
include __DIR__ . '/../vendor/autoload.php';
if (! class_exists(Application::class)) {
throw new RuntimeException(
"Unable to load application.\n"
. "- Type `composer install` if you are developing locally.\n"
. "- Type `vagrant ssh -c 'composer install'` if you are using Vagrant.\n"
. "- Type `docker-compose run zf composer install` if you are using Docker.\n"
);
}
// Retrieve configuration
$appConfig = require __DIR__ . '/../config/application.config.php';
if (file_exists(__DIR__ . '/config/development.config.php')) {
$appConfig = ArrayUtils::merge($appConfig, require __DIR__ . '/../config/development.config.php');
}
// Run the application!
Application::init($appConfig)->run();
|
Allow to change the leaflet imageOverlay. | var React = require("react");
var Leaflet = require("leaflet");
var boundsType = require("./types/bounds");
var mapLayerMixin = require("./mixins/mapLayer");
module.exports = React.createClass({
displayName: "ImageOverlay",
mixins: [mapLayerMixin],
propTypes: {
url: React.PropTypes.string.isRequired,
bounds: boundsType.isRequired
},
setInitial: function(properties){
var $__0= properties,bounds=$__0.bounds,map=$__0.map,url=$__0.url,props=(function(source, exclusion) {var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) {throw new TypeError();}for (var key in source) {if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {rest[key] = source[key];}}return rest;})($__0,{bounds:1,map:1,url:1});
this.setState({url:url,bounds:bounds,props:props});
},
componentWillMount:function() {
this.setInitial(this.props);
},
componentWillReceiveProps: function(nextProps){
this.setInitial(nextProps);
},
render:function() {
if(this._leafletElement){
this._leafletElement.initialize(this.state.url, this.state.bounds, this.state.props);
this._leafletElement.reset();
}else{
this._leafletElement = Leaflet.imageOverlay(this.state.url, this.state.bounds, this.state.props);
}
return null;
}
});
| var React = require("react");
var Leaflet = require("leaflet");
var boundsType = require("./types/bounds");
var mapLayerMixin = require("./mixins/mapLayer");
module.exports = React.createClass({
displayName: "ImageOverlay",
mixins: [mapLayerMixin],
propTypes: {
url: React.PropTypes.string.isRequired,
bounds: boundsType.isRequired
},
componentWillMount:function() {
var $__0= this.props,bounds=$__0.bounds,map=$__0.map,url=$__0.url,props=(function(source, exclusion) {var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) {throw new TypeError();}for (var key in source) {if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {rest[key] = source[key];}}return rest;})($__0,{bounds:1,map:1,url:1});
this._leafletElement = Leaflet.imageOverlay(url, bounds, props);
},
render:function() {
return null;
}
});
|
Save file name as hash to avoid errors | const crypto = require('crypto')
const { ALLOWED_CSV_FIELD_PATHS } = require('./constants')
const getAllowedCSVFieldPaths = fieldPaths => {
const allowed = fieldPaths.reduce((agg, x) => (
ALLOWED_CSV_FIELD_PATHS.indexOf(x) > -1 ? [...agg, x] : agg
), [])
return allowed
}
const getFileName = (queryParams, fileType) => {
const fileExtension = fileType === 'JSON' ? 'jsonl' : 'csv'
const { limit, skip, frozen, view, download, ...other } = queryParams
const filterNames = Object.keys(other)
if (filterNames.length === 0) {
return `all.${fileExtension}.gz`
}
const fileName = `${filterNames.reduce((agg, x) => `${agg}_${x}=${other[x]}`, '')}`
const hexFileName = crypto.createHmac('sha256', 'my-secret').update(fileName).digest('hex')
return `${hexFileName}.${fileExtension}.gz`
}
const getDescendantProp = obj => path => (
path.split('.').reduce((acc, part) => acc ? acc[part] : '', obj)
)
module.exports = { getAllowedCSVFieldPaths, getDescendantProp, getFileName }
| const { ALLOWED_CSV_FIELD_PATHS } = require('./constants')
const getAllowedCSVFieldPaths = fieldPaths => {
const allowed = fieldPaths.reduce((agg, x) => (
ALLOWED_CSV_FIELD_PATHS.indexOf(x) > -1 ? [...agg, x] : agg
), [])
return allowed
}
const getFileName = (queryParams, fileType) => {
const fileExtension = fileType === 'JSON' ? 'jsonl' : 'csv'
const { limit, skip, frozen, view, download, ...other } = queryParams
const filterNames = Object.keys(other)
if (filterNames.length === 0) {
return `all.${fileExtension}.gz`
}
return `${filterNames.reduce((agg, x) => `${agg}_${x}=${other[x]}`, '')}.${fileExtension}.gz`
}
const getDescendantProp = obj => path => (
path.split('.').reduce((acc, part) => acc ? acc[part] : '', obj)
)
module.exports = { getAllowedCSVFieldPaths, getDescendantProp, getFileName }
|
Add initial widget and dashboard collections | /**
* @fileoverview
* Provides methods for connecting the app's frontend to the endpoints API.
*
* @author trevor.nelson1@gmail.com (Trevor Nelson)
* Based off of the hello-endpoints-archectype.
*/
/**
* Initialize the app namespace on pageload
*/
(function() {
window.App = {
Models: {},
Collections: {},
Views: {}
};
/**
* function for returning a template underscore object.
*/
window.template = function(id) {
return _.template( $('#' + id).html() );
};
/**
* Account MVC
*/
App.Models.Account = Backbone.Model.extend({
defaults: {
id: '',
username: '',
email: '',
dashboards: []
}
});
/**
* Dashboard MVC
*/
App.Models.Dashboard = Backbone.Model.extend({
defaults: {
widgets: []
}
});
App.Collections.Dasboard = Backbone.Collection.extend({
model: App.Models.Dashboard
});
/**
* Widget MVC
*/
App.Models.Widget = Backbone.Model.extend({
defaults: {
title: ''
}
});
App.Collections.Widget = Backbone.Collection.extend({
model: App.Models.Widget
});
});
| /**
* @fileoverview
* Provides methods for connecting the app's frontend to the endpoints API.
*
* @author trevor.nelson1@gmail.com (Trevor Nelson)
* Based off of the hello-endpoints-archectype.
*/
/**
* Initialize the app namespace on pageload
*/
(function() {
window.App = {
Models: {},
Collections: {},
Views: {}
};
/**
* function for returning a template underscore object.
*/
window.template = function(id) {
return _.template( $('#' + id).html() );
};
App.Models.Account = Backbone.Model.extend({
defaults: {
'id': '',
'username': '',
'email': '',
'dashboards': []
}
});
App.Models.Dashboard = Backbone.Model.extend({
defaults: {
'widgets': []
}
});
App.Models.Widget = Backbone.Model.extend({
defaults: {
'title': ''
}
});
});
|
Watch source files to rerun tests on change | /* jshint node: true */
'use strict';
var webpackLoadersConfig = require('./webpack/loaders.config');
var webpackPluginsConfig = require('./webpack/plugins.config');
var webpackResolveConfig = require('./webpack/resolve.config');
module.exports = function(config) {
config.set({
browsers: [
'Chrome'
],
frameworks: [
'jasmine'
],
files: [
{pattern: 'src/**/*.{css,jsx,js,less}', included:false, served:false, watched:true},
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap']
},
reporters: [
'dots'
],
webpack: {
devtool: 'inline-source-map',
module: {
loaders: webpackLoadersConfig
},
plugins: webpackPluginsConfig,
resolve: webpackResolveConfig
},
webpackServer: {
noInfo: true // no "spam" in the console when running in Karma?
}
});
};
| /* jshint node: true */
'use strict';
var webpackLoadersConfig = require('./webpack/loaders.config');
var webpackPluginsConfig = require('./webpack/plugins.config');
var webpackResolveConfig = require('./webpack/resolve.config');
module.exports = function(config) {
config.set({
browsers: [
'Chrome'
],
frameworks: [
'jasmine'
],
files: [
'tests.webpack.js'
],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap']
},
reporters: [
'dots'
],
webpack: {
devtool: 'inline-source-map',
module: {
loaders: webpackLoadersConfig
},
plugins: webpackPluginsConfig,
resolve: webpackResolveConfig
},
webpackServer: {
noInfo: true // no "spam" in the console when running in Karma?
}
});
};
|
Drop Python 2.5 support, add support for Python 3.2 | import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-coffeescript',
version='0.1',
url='https://github.com/gears/gears-coffeescript',
license='ISC',
author='Mike Yumatov',
author_email='mike@yumatov.org',
description='CoffeeScript compiler for Gears',
long_description=read('README.rst'),
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
],
)
| import os
from setuptools import setup, find_packages
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setup(
name='gears-coffeescript',
version='0.1',
url='https://github.com/gears/gears-coffeescript',
license='ISC',
author='Mike Yumatov',
author_email='mike@yumatov.org',
description='CoffeeScript compiler for Gears',
long_description=read('README.rst'),
packages=find_packages(),
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
)
|
Add a message for the wait multiplier | /*******************************************************************************
* Copyright (c) 2017 Red Hat Inc and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat Inc - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.qa.steps;
import static java.time.Duration.ofSeconds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cucumber.api.java.Before;
import cucumber.api.java.en.When;
import cucumber.runtime.java.guice.ScenarioScoped;
@ScenarioScoped
public class BasicSteps {
private static final Logger logger = LoggerFactory.getLogger(BasicSteps.class);
private static final double WAIT_MULTIPLIER = Double.parseDouble(System.getProperty("org.eclipse.kapua.qa.waitMultiplier", "1.0"));
@Before
public void checkWaitMultipier() {
if (WAIT_MULTIPLIER != 1.0d) {
logger.info("Wait multiplier active: {}", WAIT_MULTIPLIER);
}
}
@When("I wait (\\d+) seconds?.*")
public void waitSeconds(int seconds) throws InterruptedException {
double effectiveSeconds = ((double) seconds) * WAIT_MULTIPLIER;
Thread.sleep(ofSeconds((long) Math.ceil(effectiveSeconds)).toMillis());
}
}
| /*******************************************************************************
* Copyright (c) 2017 Red Hat Inc and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat Inc - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.qa.steps;
import static java.time.Duration.ofSeconds;
import cucumber.api.java.en.When;
import cucumber.runtime.java.guice.ScenarioScoped;
@ScenarioScoped
public class BasicSteps {
private static final double WAIT_MULTIPLIER = Double.parseDouble(System.getProperty("org.eclipse.kapua.qa.waitMultiplier", "1.0"));
@When("I wait (\\d+) seconds?.*")
public void waitSeconds(int seconds) throws InterruptedException {
double effectiveSeconds = ((double) seconds) * WAIT_MULTIPLIER;
Thread.sleep(ofSeconds((long) Math.ceil(effectiveSeconds)).toMillis());
}
}
|
[FIX] Handle the case when node is falsey | export default function expandCache(cache) {
function followPath(path) {
return path.reduce((acc, part) => {
if (acc && acc[part]) {
return acc[part];
}
return undefined;
}, cache);
}
function expandChild(child) {
if (child.$type === 'atom') return child.value;
if (child.$type === 'ref') return createNode(followPath(child.value));
if (child.$type === 'error') return new Error(child.value);
// Unknown Sentinel
if (child.$type) return undefined;
return createNode(child);
}
function createNode(data) {
if (!data) return undefined;
if (data.$type) return expandChild(data);
const node = {};
const nodeCache = {};
Object.keys(data).forEach(key => {
Object.defineProperty(node, key, {
enumerable: true,
get: () => {
if (key in nodeCache) {
return nodeCache[key];
}
nodeCache[key] = expandChild(data[key]);
return nodeCache[key];
},
});
});
return node;
}
return createNode(cache);
}
| export default function expandCache(cache) {
function followPath(path) {
return path.reduce((acc, part) => {
if (acc && acc[part]) {
return acc[part];
}
return undefined;
}, cache);
}
function expandChild(child) {
if (child.$type === 'atom') return child.value;
if (child.$type === 'ref') return createNode(followPath(child.value));
if (child.$type === 'error') return new Error(child.value);
// Unknown Sentinel
if (child.$type) return undefined;
return createNode(child);
}
function createNode(data) {
if (data.$type) return expandChild(data);
const node = {};
const nodeCache = {};
Object.keys(data).forEach(key => {
Object.defineProperty(node, key, {
enumerable: true,
get: () => {
if (key in nodeCache) {
return nodeCache[key];
}
nodeCache[key] = expandChild(data[key]);
return nodeCache[key];
},
});
});
return node;
}
return createNode(cache);
}
|
Add sub-header to reports's index view | @extends('layout')
@section('body')
<h1>Reports</h1>
<p class="spacing-top-small spacing-bottom-large">Your monthly reports summarizing budgets, earnings and spendings</p>
<div class="box">
<table>
<tbody>
@foreach ($budgets as $budget)
<tr>
<td>
<a href="/reports/{{ $budget->year }}/{{ $budget->month }}">@lang('months.' . $budget->month), {{ $budget->year }}<a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
| @extends('layout')
@section('body')
<h1 class="spacing-bottom-large">Reports</h1>
<div class="box">
<table>
<tbody>
@foreach ($budgets as $budget)
<tr>
<td>
<a href="/reports/{{ $budget->year }}/{{ $budget->month }}">@lang('months.' . $budget->month), {{ $budget->year }}<a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
|
Remove adding php path to the command | <?php
namespace RMiller\LazyBin;
use RMiller\LazyBin\Process\CommandRunner\CliFunctionChecker;
use RMiller\LazyBin\Process\CommandRunner\PassthruCommandRunner;
use RMiller\LazyBin\Process\CommandRunner\PcntlCommandRunner;
class CommandRunner
{
public function runCommand($command)
{
foreach ($this->getProcessRunners() as $runner) {
if ($runner->isSupported()) {
$commandArgs = explode(' ', $command);
$runner->runCommand(array_shift($commandArgs), $commandArgs);
}
}
}
private function getProcessRunners()
{
$functionChecker = new CliFunctionChecker($this->getExecutableFinder());
return [
new PassthruCommandRunner($functionChecker),
new PcntlCommandRunner($functionChecker),
];
}
} | <?php
namespace RMiller\LazyBin;
use RMiller\LazyBin\Process\CachingExecutableFinder;
use RMiller\LazyBin\Process\CommandRunner\CliFunctionChecker;
use RMiller\LazyBin\Process\CommandRunner\PassthruCommandRunner;
use RMiller\LazyBin\Process\CommandRunner\PcntlCommandRunner;
use Symfony\Component\Process\PhpExecutableFinder;
class CommandRunner
{
public function runCommand($command)
{
foreach ($this->getProcessRunners() as $runner) {
if ($runner->isSupported()) {
$runner->runCommand($this->getExecutableFinder()->getExecutablePath(), explode(' ', $command));
}
}
}
/**
* @return CachingExecutableFinder
*/
private function getExecutableFinder()
{
return new CachingExecutableFinder(new PhpExecutableFinder());
}
private function getProcessRunners()
{
$functionChecker = new CliFunctionChecker($this->getExecutableFinder());
return [
new PassthruCommandRunner($functionChecker),
new PcntlCommandRunner($functionChecker),
];
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.