text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add openBasicModal reducer method to customer invoice | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Method using a factory pattern variant to get a reducer
* for a particular page or page style.
*
* For a new page - create a constant object with the
* methods from reducerMethods which are composed to create
* a reducer. Add to PAGE_REDUCERS.
*
* Each key value pair in a reducer object should be in the form
* action type: reducer function, returning a new state object
*
*/
import {
filterData,
editTotalQuantity,
focusNextCell,
selectRow,
deselectRow,
deselectAll,
focusCell,
sortData,
openBasicModal,
} from './reducerMethods';
/**
* Used for actions that should be in all pages using a data table.
*/
const BASE_TABLE_PAGE_REDUCER = {
focusNextCell,
focusCell,
sortData,
};
const customerInvoice = {
...BASE_TABLE_PAGE_REDUCER,
filterData,
editTotalQuantity,
selectRow,
deselectRow,
deselectAll,
openBasicModal,
};
const PAGE_REDUCERS = {
customerInvoice,
};
const getReducer = page => {
const reducer = PAGE_REDUCERS[page];
return (state, action) => {
const { type } = action;
if (!reducer[type]) return state;
return reducer[type](state, action);
};
};
export default getReducer;
| /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
/**
* Method using a factory pattern variant to get a reducer
* for a particular page or page style.
*
* For a new page - create a constant object with the
* methods from reducerMethods which are composed to create
* a reducer. Add to PAGE_REDUCERS.
*
* Each key value pair in a reducer object should be in the form
* action type: reducer function, returning a new state object
*
*/
import {
filterData,
editTotalQuantity,
focusNextCell,
selectRow,
deselectRow,
deselectAll,
focusCell,
sortData,
} from './reducerMethods';
/**
* Used for actions that should be in all pages using a data table.
*/
const BASE_TABLE_PAGE_REDUCER = {
focusNextCell,
focusCell,
sortData,
};
const customerInvoice = {
...BASE_TABLE_PAGE_REDUCER,
filterData,
editTotalQuantity,
selectRow,
deselectRow,
deselectAll,
};
const PAGE_REDUCERS = {
customerInvoice,
};
const getReducer = page => {
const reducer = PAGE_REDUCERS[page];
return (state, action) => {
const { type } = action;
if (!reducer[type]) return state;
return reducer[type](state, action);
};
};
export default getReducer;
|
Add support for FullCalendar's month view. | /*!
* fullcalendar-rightclick v1.2
* Docs & License: https://github.com/mherrmann/fullcalendar-rightclick
* (c) 2015 Michael Herrmann
*/
(function($) {
function monkeyPatchViewClass(View, dayCssClass) {
var originalRender = View.prototype.render;
View.prototype.render = function() {
originalRender.call(this);
this.registerDayRightclickListener();
this.registerEventRightclickListener();
};
View.prototype.registerDayRightclickListener = function() {
var that = this;
this.el.on('contextmenu', '.fc-widget-content ' + dayCssClass,
function(ev) {
that.coordMap.build();
var cell = that.coordMap.getCell(ev.pageX, ev.pageY);
if (cell)
return that.trigger(
'dayRightclick', null, cell.start, ev
);
}
);
};
View.prototype.registerEventRightclickListener = function() {
var that = this;
this.el.on('contextmenu', '.fc-event-container > *', function(ev) {
var seg = $(this).data('fc-seg');
return that.trigger('eventRightclick', this, seg.event, ev);
});
}
}
var fc = $.fullCalendar;
monkeyPatchViewClass(fc.views.agenda, '.fc-slats');
monkeyPatchViewClass(fc.views.basic, '.fc-content-skeleton');
})(jQuery); | /*!
* fullcalendar-rightclick v1.1
* Docs & License: https://github.com/mherrmann/fullcalendar-rightclick
* (c) 2015 Michael Herrmann
*/
(function($) {
var fc = $.fullCalendar;
var AgendaView = fc.views.agenda;
var originalRender = AgendaView.prototype.render;
AgendaView.prototype.render = function() {
originalRender.call(this);
this.registerDayRightclickListener();
this.registerEventRightclickListener();
};
AgendaView.prototype.registerDayRightclickListener = function() {
var that = this;
this.el.on('contextmenu', '.fc-widget-content .fc-slats',
function(ev) {
that.coordMap.build();
var cell = that.coordMap.getCell(ev.pageX, ev.pageY);
if (cell)
return that.trigger('dayRightclick', null, cell.start, ev);
}
);
};
AgendaView.prototype.registerEventRightclickListener = function() {
var that = this;
this.el.on('contextmenu', '.fc-event-container > *', function(ev) {
var seg = $(this).data('fc-seg');
return that.trigger('eventRightclick', this, seg.event, ev);
});
}
})(jQuery); |
Remove the current episode from the series episodes list
`Episode.find` uses `UitzendingGemist.Series.find` to first get the
`Series`, which holds a list of `Episodes`. The `Episode` returned by
`Episode.find` comes from that list.
The `Episode.series` is the `Series` from
`UitzendingGemist.Series.find`, including the episode list. Now, the
`Episode` is removed from that list before creating the `Series`, so the
`Episode` isn't listed in the shelf on the episode view. | var Episode = function(data, series_data){
this.id = data.mid
this.name = data.name.replace('&', '&')
this.description = data.description
this.image = data.stills ? data.stills[0].url : data.image
this.broadcasters = data.broadcasters.join(', ')
this.genres = data.genres.join(', ')
this.duration = Math.round(data.duration / 60)
if(series_data){
this.series = new Series(series_data)
}
}
Episode.popular = function(callback) {
UitzendingGemist.Episode.popular(function(episodes){
callback(
episodes.map(function(episode){
return new Episode(episode, episode.series)
})
)
})
}
Episode.find = function(episode_id, series_id, callback) {
UitzendingGemist.Series.find(series_id, function(series){
episode = series.episodes.filter(function(episode){
return episode.mid == episode_id
})[0]
series.episodes.splice(series.episodes.indexOf(episode), 1)
callback(new Episode(episode, series))
})
}
| var Episode = function(data, series_data){
this.id = data.mid
this.name = data.name.replace('&', '&')
this.description = data.description
this.image = data.stills ? data.stills[0].url : data.image
this.broadcasters = data.broadcasters.join(', ')
this.genres = data.genres.join(', ')
this.duration = Math.round(data.duration / 60)
if(series_data){
this.series = new Series(series_data)
}
}
Episode.popular = function(callback) {
UitzendingGemist.Episode.popular(function(episodes){
callback(
episodes.map(function(episode){
return new Episode(episode, episode.series)
})
)
})
}
Episode.find = function(episode_id, series_id, callback) {
UitzendingGemist.Series.find(series_id, function(series){
episode = series.episodes.filter(function(episode){
return episode.mid == episode_id
})[0]
callback(new Episode(episode, series))
})
}
|
Fix LoggerMixin test
Branch: feature/bulk-messaging-api | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
# There should be 8 messages: 7 from above, plus
# one more for LoggerMixin's own deprecation warning
assert_equals(len(handler.buffer), 7 + 1)
assert_equals(handler.buffer[3].name, "loggablestub")
assert_equals(handler.buffer[3].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
| #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
from nose.tools import assert_equals, assert_raises
from ..log.mixin import LoggerMixin
class LoggableStub(object, LoggerMixin):
pass
def test_logger_mixin():
obj = LoggableStub()
from logging.handlers import MemoryHandler
import logging
log = logging.getLogger()
handler = MemoryHandler(999)
log.setLevel(logging.DEBUG)
log.addHandler(handler)
obj.debug("This is a DEBUG message")
obj.info("This is an INFORMATIVE message")
obj.warning("This is a WARNING")
obj.error("This is an ERROR")
obj.critical("This is a CRITICAL error")
obj.exception("This is an exception")
obj.exception()
assert_equals(len(handler.buffer), 7)
assert_equals(handler.buffer[2].name, "loggablestub")
assert_equals(handler.buffer[2].msg, "This is a WARNING")
log.removeHandler(handler)
def test_logger_raises_on_invalid_name_type():
class BrokenLoggableStub(object, LoggerMixin):
def _logger_name(self):
return 123
broken_logger = BrokenLoggableStub()
assert_raises(
TypeError,
broken_logger.debug,
"This shouldn't work")
|
Fix l0 dc field name. | from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
field = self.name.replace('m', 's')
self._delegate._push_value(field, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
| from __future__ import division
from .module import Module
class DCMotor(object):
def __init__(self, name, delegate):
self._name = name
self._delegate = delegate
self._speed = None
@property
def name(self):
return self._name
@property
def speed(self):
self._speed
@speed.setter
def speed(self, s):
s = min(max(s, -1.0), 1.0)
if s != self._speed:
self._speed = s
self._delegate._push_value(self.name, self._speed)
class L0DCMotor(Module):
def __init__(self, id, alias, robot):
Module.__init__(self, 'L0DCMotor', id, alias, robot)
self.m1 = DCMotor('m1', self)
self.m2 = DCMotor('m2', self)
|
Make production build exit the process normally | const path = require('path');
const config = require('../config/server.env');
const nodeExternals = require('webpack-node-externals');
function resolve(dir) {
return path.join(__dirname, '..', dir);
}
module.exports = {
entry: {
server: './src/server.js',
},
output: {
path: config.server.assetsRoot,
filename: '[name].js',
publicPath: config.server.assetsPublicPath,
libraryTarget: 'commonjs',
library: '',
},
externals: [nodeExternals()],
resolve: {
extensions: ['.js'],
alias: {
'@': resolve('src'),
server: resolve('src/server'),
handlebars: 'handlebars/runtime.js',
},
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')],
exclude: ['node_modules'],
},
],
},
target: 'node',
watch: process.env.NODE_ENV !== 'production',
bail: true,
};
| const path = require('path');
const config = require('../config/server.env');
const nodeExternals = require('webpack-node-externals');
function resolve(dir) {
return path.join(__dirname, '..', dir);
}
module.exports = {
entry: {
server: './src/server.js',
},
output: {
path: config.server.assetsRoot,
filename: '[name].js',
publicPath: config.server.assetsPublicPath,
libraryTarget: 'commonjs',
library: '',
},
externals: [nodeExternals()],
resolve: {
extensions: ['.js'],
alias: {
'@': resolve('src'),
server: resolve('src/server'),
handlebars: 'handlebars/runtime.js',
},
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')],
exclude: ['node_modules'],
},
],
},
target: 'node',
watch: true,
bail: true,
};
|
Make PermissionHandler more robust to missing permission directive | "use strict";
const Handler = require('./handler');
class PermissionHandler extends Handler {
constructor(data={}) {
super(data);
['permissions'].map(val => this[val] = data[val] ? data[val] : (this[val] ? this[val] : this.constructor[val]));
}
async allowAccess(context) {
if (!this.Account) {
// Cache the location to the Account plugin, because this portion of code
// will be run many, many times!
this.Account = context.engine.pluginRegistry.get('Account');
}
for (let permission of (this.permissions || [])) {
if (await this.Account.accountHasPermission(context.account, permission)) {
return true;
}
}
// Give the user an Access Denied code.
context.httpResponse = 403;
return false;
}
}
PermissionHandler.permissions = [];
module.exports = PermissionHandler;
| "use strict";
const Handler = require('./handler');
class PermissionHandler extends Handler {
constructor(data={}) {
super(data);
['permissions'].map(val => this[val] = data[val] ? data[val] : (this[val] ? this[val] : this.constructor[val]));
}
async allowAccess(context) {
if (!this.Account) {
// Cache the location to the Account plugin, because this portion of code
// will be run many, many times!
this.Account = context.engine.pluginRegistry.get('Account');
}
for (let permission of this.permissions) {
if (await this.Account.accountHasPermission(context.account, permission)) {
return true;
}
}
// Give the user an Access Denied code.
context.httpResponse = 403;
return false;
}
}
PermissionHandler.permissions = [];
module.exports = PermissionHandler;
|
Rename "not-italic" utility to "roman" | import defineClasses from '../util/defineClasses'
export default function() {
return defineClasses({
'italic': { 'font-style': 'italic' },
'roman': { 'font-style': 'normal' },
'uppercase': { 'text-transform': 'uppercase' },
'lowercase': { 'text-transform': 'lowercase' },
'capitalize': { 'text-transform': 'capitalize' },
'normal-case': { 'text-transform': 'none' },
'underline': { 'text-decoration': 'underline' },
'line-through': { 'text-decoration': 'line-through' },
'no-underline': { 'text-decoration': 'none' },
'antialiased': {
'-webkit-font-smoothing': 'antialiased',
'-moz-osx-font-smoothing': 'grayscale'
},
'subpixel-antialiased': {
'-webkit-font-smoothing': 'auto',
'-moz-osx-font-smoothing': 'auto'
}
})
}
| import defineClasses from '../util/defineClasses'
export default function() {
return defineClasses({
'italic': { 'font-style': 'italic' },
'not-italic': { 'font-style': 'normal' },
'uppercase': { 'text-transform': 'uppercase' },
'lowercase': { 'text-transform': 'lowercase' },
'capitalize': { 'text-transform': 'capitalize' },
'normal-case': { 'text-transform': 'none' },
'underline': { 'text-decoration': 'underline' },
'line-through': { 'text-decoration': 'line-through' },
'no-underline': { 'text-decoration': 'none' },
'antialiased': {
'-webkit-font-smoothing': 'antialiased',
'-moz-osx-font-smoothing': 'grayscale'
},
'subpixel-antialiased': {
'-webkit-font-smoothing': 'auto',
'-moz-osx-font-smoothing': 'auto'
}
})
}
|
Add default loss for RNNOutput
Former-commit-id: bb723e819949ca911702dff1bcae3f1507df92d5 | package org.deeplearning4j.nn.conf.layers;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction;
@Data @NoArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class RnnOutputLayer extends BaseOutputLayer {
private RnnOutputLayer(Builder builder){
super(builder);
}
@NoArgsConstructor
public static class Builder extends BaseOutputLayer.Builder<Builder> {
protected LossFunction lossFunction = LossFunction.MCXENT;
public Builder(LossFunction lossFunction) {
this.lossFunction = lossFunction;
}
@Override
@SuppressWarnings("unchecked")
public RnnOutputLayer build() {
return new RnnOutputLayer(this);
}
}
}
| package org.deeplearning4j.nn.conf.layers;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction;
@Data @NoArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class RnnOutputLayer extends BaseOutputLayer {
private RnnOutputLayer(Builder builder){
super(builder);
}
@NoArgsConstructor
public static class Builder extends BaseOutputLayer.Builder<Builder> {
public Builder(LossFunction lossFunction) {
this.lossFunction = lossFunction;
}
@Override
@SuppressWarnings("unchecked")
public RnnOutputLayer build() {
return new RnnOutputLayer(this);
}
}
}
|
Prepare for release of 0.0.3 | #!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.3',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
| #!/usr/bin/env python
from setuptools import setup
setup(name='tap-awin',
version='0.0.2',
description='Singer.io tap for extracting data from the Affiliate Window API',
author='Onedox',
url='https://github.com/onedox/tap-awin',
classifiers=['Programming Language :: Python :: 3 :: Only'],
py_modules=['tap_awin'],
install_requires=[
'zeep>=1.4.1',
'singer-python>=3.6.3',
'tzlocal>=1.3',
],
entry_points='''
[console_scripts]
tap-awin=tap_awin:main
''',
packages=['tap_awin'],
package_data = {
'tap_awin/schemas': [
"transactions.json",
"merchants.json",
],
},
include_package_data=True,
)
|
Move extension loading to boot method
This will likely have to be reverted, to make things like $this->app->extend() work
reasonably well in extensions' service providers.
For now, since we fetch the enabled extensions from the config, there is no other way
for us to guarantee that the config is already available. | <?php namespace Flarum\Support\Extensions;
use Flarum\Core;
use Illuminate\Support\ServiceProvider;
class ExtensionsServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
}
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
// Extensions will not be registered if Flarum is not installed yet
if (!Core::isInstalled()) {
return;
}
$config = $this->app->make('Flarum\Core\Settings\SettingsRepository')->get('extensions_enabled');
$extensions = json_decode($config, true);
$providers = [];
foreach ($extensions as $extension) {
if (file_exists($file = public_path().'/extensions/'.$extension.'/bootstrap.php') ||
file_exists($file = base_path().'/extensions/'.$extension.'/bootstrap.php')) {
$providers[$extension] = require $file;
}
}
// @todo store $providers somewhere (in Core?) so that extensions can talk to each other
}
}
| <?php namespace Flarum\Support\Extensions;
use Flarum\Core;
use Illuminate\Support\ServiceProvider;
class ExtensionsServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
// Extensions will not be registered if Flarum is not installed yet
if (!Core::isInstalled()) {
return;
}
$extensions = json_decode(Core::config('extensions_enabled'), true);
$providers = [];
foreach ($extensions as $extension) {
if (file_exists($file = public_path().'/extensions/'.$extension.'/bootstrap.php') ||
file_exists($file = base_path().'/extensions/'.$extension.'/bootstrap.php')) {
$providers[$extension] = require $file;
}
}
// @todo store $providers somewhere (in Core?) so that extensions can talk to each other
}
}
|
KickstarterSideKick: Fix for new Kickstarter layout | // ==UserScript==
// @name Kickstarter - Sidekick link
// @namespace localhost
// @description Adds a Sidekick link to Kickstarter projects
// @include https://www.kickstarter.com/projects/*
// @version 1
// @grant none
// ==/UserScript==
window.addEventListener("load", function(){
// If the project is live
if( document.querySelectorAll("#button-back-this-proj").length > 0 )
{
var projectId = document.querySelector("#watching-widget").children[0].className.match(/Project([0-9]+)/);
var div = document.createElement("div");
var link = document.createElement("a");
div.appendChild(link);
link.appendChild(document.createTextNode("View Sidekick page"));
link.href = "http://sidekick.epfl.ch/campaign/" + projectId[1] + "-project";
div.style.marginTop = "20px";
document.querySelector(".NS_campaigns__stats").parentNode.insertBefore(div, null);
}
}); | // ==UserScript==
// @name Kickstarter - Sidekick link
// @namespace localhost
// @description Adds a Sidekick link to Kickstarter projects
// @include https://www.kickstarter.com/projects/*
// @version 1
// @grant none
// ==/UserScript==
window.addEventListener("load", function(){
// If the project is live
if(document.querySelector("#main_content").className.indexOf("Project-state-live") > -1)
{
var projectId = document.querySelector("#main_content").className.match(/Project([0-9]+)/);
var div = document.createElement("div");
var link = document.createElement("a");
div.appendChild(link);
link.appendChild(document.createTextNode("View Sidekick page"));
link.href = "http://sidekick.epfl.ch/campaign/" + projectId[1] + "-project";
div.style.marginBottom = "40px";
document.querySelector(".NS_projects__deadline_copy").parentNode.insertBefore(div, document.querySelector(".NS_projects__deadline_copy"));
}
}); |
Use actions directly rather than proxy through another func. | var h = require('virtual-dom/h')
module.exports = CreateColumn
function CreateColumn (props) {
var actions = props.actions
var name, type
return h('div', [
h('h1', 'Create new column'),
h('h2', 'Set the column name & type'),
h('div', [
h('input.small', {
type: 'text',
name: 'column-name',
onchange: function (e) {
name = e.target.value
}
})
]),
h('div', [
h('select.small', {
name: 'column-type',
onchange: function (e) {
type = e.target.options[e.target.selectedIndex].text
}
}, [
h('option', 'string'),
h('option', 'number')
])
]),
h('div', [
h('button.button-blue', {
onclick: function () {
actions.newColumn(name, type)
}
}, 'Create column')
])
])
}
| var h = require('virtual-dom/h')
module.exports = CreateColumn
function CreateColumn (props) {
var name, type
return h('div', [
h('h1', 'Create new column'),
h('h2', 'Set the column name & type'),
h('div', [
h('input.small', {
type: 'text',
name: 'column-name',
onchange: function (e) {
name = e.target.value
}
})
]),
h('div', [
h('select.small', {
name: 'column-type',
onchange: function (e) {
type = e.target.options[e.target.selectedIndex].text
}
}, [
h('option', 'string'),
h('option', 'number')
])
]),
h('div', [
h('button.button-blue', {
onclick: function () {
props.onsubmit(name, type)
}
}, 'Create column')
])
])
}
|
Fix the license header regex.
Most of the files are attributed to Google Inc so I used this instead of
Chromium Authors.
R=mark@chromium.org
BUG=
TEST=
Review URL: http://codereview.chromium.org/7108074 | # Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Top-level presubmit script for GYP.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
def CheckChangeOnUpload(input_api, output_api):
report = []
report.extend(input_api.canned_checks.PanProjectChecks(
input_api, output_api))
return report
def CheckChangeOnCommit(input_api, output_api):
report = []
license = (
r'.*? Copyright \(c\) %(year)s Google Inc\. All rights reserved\.\n'
r'.*? Use of this source code is governed by a BSD-style license that '
r'can be\n'
r'.*? found in the LICENSE file\.\n'
) % {
'year': input_api.time.strftime('%Y'),
}
report.extend(input_api.canned_checks.PanProjectChecks(
input_api, output_api, license_header=license))
report.extend(input_api.canned_checks.CheckTreeIsOpen(
input_api, output_api,
'http://gyp-status.appspot.com/status',
'http://gyp-status.appspot.com/current'))
return report
def GetPreferredTrySlaves():
return ['gyp-win32', 'gyp-win64', 'gyp-linux', 'gyp-mac']
| # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Top-level presubmit script for GYP.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""
def CheckChangeOnUpload(input_api, output_api):
report = []
report.extend(input_api.canned_checks.PanProjectChecks(
input_api, output_api))
return report
def CheckChangeOnCommit(input_api, output_api):
report = []
report.extend(input_api.canned_checks.PanProjectChecks(
input_api, output_api))
report.extend(input_api.canned_checks.CheckTreeIsOpen(
input_api, output_api,
'http://gyp-status.appspot.com/status',
'http://gyp-status.appspot.com/current'))
return report
def GetPreferredTrySlaves():
return ['gyp-win32', 'gyp-win64', 'gyp-linux', 'gyp-mac']
|
Move promisify require to top of file | const { promisify } = require("util");
const command = {
command: "console",
description:
"Run a console with contract abstractions and commands available",
builder: {},
help: {
usage: "truffle console [--network <name>] [--verbose-rpc]",
options: [
{
option: "--network <name>",
description:
"Specify the network to use. Network name must exist in the configuration."
},
{
option: "--verbose-rpc",
description:
"Log communication between Truffle and the Ethereum client."
}
]
},
run: async function (options) {
const Config = require("@truffle/config");
const Console = require("../console");
const { Environment } = require("@truffle/environment");
const config = Config.detect(options);
// This require a smell?
const commands = require("./index");
const excluded = new Set(["console", "init", "watch", "develop"]);
const consoleCommands = Object.keys(commands).reduce((acc, name) => {
return !excluded.has(name)
? Object.assign(acc, {[name]: commands[name]})
: acc;
}, {});
await Environment.detect(config);
const c = new Console(consoleCommands, config.with({noAliases: true}));
return await promisify(c.start)();
}
};
module.exports = command;
| const command = {
command: "console",
description:
"Run a console with contract abstractions and commands available",
builder: {},
help: {
usage: "truffle console [--network <name>] [--verbose-rpc]",
options: [
{
option: "--network <name>",
description:
"Specify the network to use. Network name must exist in the configuration."
},
{
option: "--verbose-rpc",
description:
"Log communication between Truffle and the Ethereum client."
}
]
},
run: async function (options) {
const { promisify } = require("util");
const Config = require("@truffle/config");
const Console = require("../console");
const { Environment } = require("@truffle/environment");
const config = Config.detect(options);
// This require a smell?
const commands = require("./index");
const excluded = new Set(["console", "init", "watch", "develop"]);
const consoleCommands = Object.keys(commands).reduce((acc, name) => {
return !excluded.has(name)
? Object.assign(acc, {[name]: commands[name]})
: acc;
}, {});
await Environment.detect(config);
const c = new Console(consoleCommands, config.with({noAliases: true}));
return await promisify(c.start)();
}
};
module.exports = command;
|
Fix glyphicons font path for dist | module.exports = function(grunt) {
"use strict";
var getThemeConfig = require('../lib/get-theme-config')
, happyplan = grunt.config.get('happyplan')
, glyphicons = []
getThemeConfig(grunt, ['path', 'assets', 'glyphicons'], { merge: true } ).forEach(function(src) {
glyphicons.push(src + '/**/*.svg')
});
return {
glyphicons: {
src: glyphicons,
dest: '<%= happyplan.path.dist.assets.fonts %>',
destCss: '<%= happyplan.path.build.assets.styles %>',
options: {
relativeFontPath: require('path').relative(
happyplan.cwd + '/' + grunt.config.get(['happyplan', 'path', 'dist', 'assets', 'styles']),
happyplan.cwd + '/' + grunt.config.get(['happyplan', 'path', 'dist', 'assets', 'fonts'])
),
stylesheet: 'scss',
hashes: false,
htmlDemo: false,
engine: '<%= happyplan.glyphicons.engine %>'
}
}
}
}
| module.exports = function(grunt) {
"use strict";
var getThemeConfig = require('../lib/get-theme-config')
, happyplan = grunt.config.get('happyplan')
, glyphicons = []
getThemeConfig(grunt, ['path', 'assets', 'glyphicons'], { merge: true } ).forEach(function(src) {
glyphicons.push(src + '/**/*.svg')
});
return {
glyphicons: {
src: glyphicons,
dest: '<%= happyplan.path.build.assets.fonts %>',
destCss: '<%= happyplan.path.build.assets.styles %>',
options: {
relativeFontPath: require('path').relative(
happyplan.cwd + '/' + grunt.config.get(['happyplan', 'path', 'dist', 'assets', 'styles']),
happyplan.cwd + '/' + grunt.config.get(['happyplan', 'path', 'dist', 'assets', 'fonts'])
),
stylesheet: 'scss',
hashes: false,
htmlDemo: false,
engine: '<%= happyplan.glyphicons.engine %>'
}
}
}
}
|
Fix missing log lib by just panicing | package main
import (
"github.com/wjessop/go-piglow"
)
func main() {
var p *piglow.Piglow
var err error
// Create a new Piglow
p, err = piglow.NewPiglow()
if err != nil {
panic(err)
}
// Set LED to brightness 10
p.SetLED(0, 10)
// Set LED to max brightness
p.SetLED(2, 255)
// Set all LEDs to brightness 10
p.SetAll(10)
// Set the white LEDs to 15
p.SetWhite(15)
// Set the red LEDs to 20
p.SetRed(20)
// Other functions are available for the other colours.
// Set all LEDs on tentacle 0 to brightness 15
p.SetTentacle(0, 15)
// Set all LEDs on tentacle 2 to brightness 150
p.SetTentacle(2, 150)
// Display a value on a tentacle at brightness 10
// See code comments for more info on parameters
p.DisplayValueOnTentacle(0, 727.0, 1000.0, uint8(10), true)
}
| package main
import (
"github.com/wjessop/go-piglow"
)
func main() {
var p *piglow.Piglow
var err error
// Create a new Piglow
p, err = piglow.NewPiglow()
if err != nil {
log.Fatal("Couldn't create a Piglow: ", err)
}
// Set LED to brightness 10
p.SetLED(0, 10)
// Set LED to max brightness
p.SetLED(2, 255)
// Set all LEDs to brightness 10
p.SetAll(10)
// Set the white LEDs to 15
p.SetWhite(15)
// Set the red LEDs to 20
p.SetRed(20)
// Other functions are available for the other colours.
// Set all LEDs on tentacle 0 to brightness 15
p.SetTentacle(0, 15)
// Set all LEDs on tentacle 2 to brightness 150
p.SetTentacle(2, 150)
// Display a value on a tentacle at brightness 10
// See code comments for more info on parameters
p.DisplayValueOnTentacle(0, 727.0, 1000.0, uint8(10), true)
}
|
Add debug info to the test | import unittest
import http.client
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
self.assertEqual(response.status, 404)
connRouter.close()
connConfig.close()
def test_200NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
connConfig.request("GET","/configure?location=/google&upstream=http://www.google.com&ttl=10")
response = connConfig.getresponse()
print("Body:" + response.read())
self.assertEqual(response.status, 200)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
self.assertEqual(response.status, 200)
connRouter.close()
connConfig.close()
if __name__ == '__main__':
unittest.main()
| import unittest
import http.client
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
self.assertEqual(response.status, 404)
connRouter.close()
connConfig.close()
def test_200NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
connConfig.request("GET","/configure?location=/google&upstream=http://www.google.com&ttl=10")
response = connConfig.getresponse()
self.assertEqual(response.status, 200)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
self.assertEqual(response.status, 200)
connRouter.close()
connConfig.close()
if __name__ == '__main__':
unittest.main()
|
test: Add test to allow null/undefined
As is like to happen with bindings |
describe('Filter: ivhPluckAndJoin', function() {
'use strict';
beforeEach(module('ivh.pluckAndJoin'));
var ivhPluckAndJoinFilter, items;
beforeEach(inject(function(_ivhPluckAndJoinFilter_) {
ivhPluckAndJoinFilter = _ivhPluckAndJoinFilter_;
items = [{name: 'Justin'}, {name: 'Bella'}];
}));
it('should return the empty string for empty collections', function() {
var actual = ivhPluckAndJoinFilter([], 'name');
expect(actual).toBe('');
});
it('should join items by ", " by default', function() {
var actual = ivhPluckAndJoinFilter(items, 'name');
expect(actual).toBe('Justin, Bella');
});
it('should accept a custom delimiter', function() {
var actual = ivhPluckAndJoinFilter(items, 'name', ' - ');
expect(actual).toBe('Justin - Bella');
});
it('should return an empty string when given null', function() {
var actual = ivhPluckAndJoinFilter(null, 'name');
expect(actual).toEqual('');
});
it('should return the empty string when given undefined', function() {
var actual = ivhPluckAndJoinFilter(undefined, 'name');
expect(actual).toBe('');
});
});
|
describe('Filter: ivhPluckAndJoin', function() {
'use strict';
beforeEach(module('ivh.pluckAndJoin'));
var ivhPluckAndJoinFilter, items;
beforeEach(inject(function(_ivhPluckAndJoinFilter_) {
ivhPluckAndJoinFilter = _ivhPluckAndJoinFilter_;
items = [{name: 'Justin'}, {name: 'Bella'}];
}));
it('should return the empty string for empty collections', function() {
var actual = ivhPluckAndJoinFilter([], 'name');
expect(actual).toBe('');
});
it('should join items by ", " by default', function() {
var actual = ivhPluckAndJoinFilter(items, 'name');
expect(actual).toBe('Justin, Bella');
});
it('should accept a custom delimiter', function() {
var actual = ivhPluckAndJoinFilter(items, 'name', ' - ');
expect(actual).toBe('Justin - Bella');
});
});
|
Fix the bad jobboard path.
Change-Id: I3281babfa835d7d4b76f7f299887959fa5342e85 | """One-line documentation for backend_helper module.
A detailed description of backend_helper.
"""
from taskflow.jobs import backends as job_backends
from taskflow.persistence import backends as persistence_backends
# Default host/port of ZooKeeper service.
ZK_HOST = '104.197.150.171:2181'
# Default jobboard configuration.
JB_CONF = {
'hosts': ZK_HOST,
'board': 'zookeeper',
'path': '/taskflow/dev',
}
# Default persistence configuration.
PERSISTENCE_CONF = {
'connection': 'zookeeper',
'hosts': ZK_HOST,
'path': '/taskflow/persistence',
}
def default_persistence_backend():
return persistence_backends.fetch(PERSISTENCE_CONF)
def default_jobboard_backend(name):
return job_backends.fetch(name,
JB_CONF,
persistence=default_persistence_backend())
| """One-line documentation for backend_helper module.
A detailed description of backend_helper.
"""
from taskflow.jobs import backends as job_backends
from taskflow.persistence import backends as persistence_backends
# Default host/port of ZooKeeper service.
ZK_HOST = '104.197.150.171:2181'
# Default jobboard configuration.
JB_CONF = {
'hosts': ZK_HOST,
'board': 'zookeeper',
'path': '/taskflow/99-bottles-demo',
}
# Default persistence configuration.
PERSISTENCE_CONF = {
'connection': 'zookeeper',
'hosts': ZK_HOST,
'path': '/taskflow/persistence',
}
def default_persistence_backend():
return persistence_backends.fetch(PERSISTENCE_CONF)
def default_jobboard_backend(name):
return job_backends.fetch(name,
JB_CONF,
persistence=default_persistence_backend())
|
Adjust to changes in Gerrit core
Change-Id: I76bfd3ebc04f7f094cefd3c169efbb579ec403ae | // Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.replication;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.account.GroupMembership;
public class RemoteSiteUser extends CurrentUser {
private final GroupMembership effectiveGroups;
public RemoteSiteUser(GroupMembership authGroups) {
effectiveGroups = authGroups;
}
@Override
public GroupMembership getEffectiveGroups() {
return effectiveGroups;
}
}
| // Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.replication;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.account.GroupMembership;
public class RemoteSiteUser extends CurrentUser {
private final GroupMembership effectiveGroups;
public RemoteSiteUser(GroupMembership authGroups) {
effectiveGroups = authGroups;
}
@Override
public GroupMembership getEffectiveGroups() {
return effectiveGroups;
}
@Override
public Object getCacheKey() {
// Never cache a remote user
return new Object();
}
}
|
Allow to pass custom instance of Gson object | /*
* Copyright (C) 2015 Piotr Wittchen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pwittchen.prefser.library.rx2;
import android.support.annotation.NonNull;
import com.google.gson.Gson;
import java.lang.reflect.Type;
public final class GsonConverter implements JsonConverter {
private final Gson gson;
public GsonConverter(@NonNull Gson gson) {
this.gson = gson;
}
public GsonConverter() {
gson = new Gson();
}
@Override public <T> T fromJson(String json, Type typeOfT) {
return gson.fromJson(json, typeOfT);
}
@Override public <T> String toJson(T object, Type typeOfT) {
return gson.toJson(object, typeOfT);
}
}
| /*
* Copyright (C) 2015 Piotr Wittchen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pwittchen.prefser.library.rx2;
import com.google.gson.Gson;
import java.lang.reflect.Type;
public final class GsonConverter implements JsonConverter {
private final Gson gson = new Gson();
@Override public <T> T fromJson(String json, Type typeOfT) {
return gson.fromJson(json, typeOfT);
}
@Override public <T> String toJson(T object, Type typeOfT) {
return gson.toJson(object, typeOfT);
}
}
|
Add session manager by default | <?php
return array(
'module_layouts' => array(
'ZfcUser' => 'layout/layout-small-header.phtml',
'ZfModule' => 'layout/layout-small-header.phtml',
),
'asset_manager' => array(
'caching' => array(
'default' => array(
'cache' => 'FilePath', // Apc, FilePath, FileSystem etc.
'options' => array(
'dir' => 'public',
),
),
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
'invokables' => array(
'Zend\Session\SessionManager' => 'Zend\Session\SessionManager',
),
),
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=modules;host=localhost',
'username' => 'modules',
'password' => 'modules',
),
);
| <?php
return array(
'module_layouts' => array(
'ZfcUser' => 'layout/layout-small-header.phtml',
'ZfModule' => 'layout/layout-small-header.phtml',
),
'asset_manager' => array(
'caching' => array(
'default' => array(
'cache' => 'FilePath', // Apc, FilePath, FileSystem etc.
'options' => array(
'dir' => 'public',
),
),
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=modules;host=localhost',
'username' => 'modules',
'password' => 'modules',
),
);
|
Move javadoc description for Overriding from class level to method | package com.yelp.clientlib.connection;
import com.squareup.okhttp.Request;
import oauth.signpost.http.HttpRequest;
import se.akerfeldt.okhttp.signpost.OkHttpOAuthConsumer;
/**
* {@link HttpOAuthConsumer} is an {@link oauth.signpost.OAuthConsumer} implementation to sign OkHttp {@link Request}s.
*/
public class HttpOAuthConsumer extends OkHttpOAuthConsumer {
public HttpOAuthConsumer(String consumerKey, String consumerSecret) {
super(consumerKey, consumerSecret);
}
/**
* {@link OkHttpOAuthConsumer} doesn't handle characters required for encoding {@link com.yelp.clientlib.entities
* .options.BoundingBoxOptions}, {@link HttpRequestAdapter} encodes those characters so oauth-signpost can sign
* requests correctly.
*
* @param request the native HTTP request instance
* @return the adapted request
*/
@Override
protected HttpRequest wrap(Object request) {
return new HttpRequestAdapter((Request) request);
}
} | package com.yelp.clientlib.connection;
import com.squareup.okhttp.Request;
import oauth.signpost.http.HttpRequest;
import se.akerfeldt.okhttp.signpost.OkHttpOAuthConsumer;
/**
* {@link HttpOAuthConsumer} is an {@link oauth.signpost.OAuthConsumer} implementation to sign OkHttp {@link Request}s.
*
* {@link OkHttpOAuthConsumer} doesn't handle characters required for encoding {@link com.yelp.clientlib.entities
* .options.BoundingBoxOptions}, {@link HttpRequestAdapter} encodes those characters so oauth-signpost can sign
* requests correctly.
*/
public class HttpOAuthConsumer extends OkHttpOAuthConsumer {
public HttpOAuthConsumer(String consumerKey, String consumerSecret) {
super(consumerKey, consumerSecret);
}
@Override
protected HttpRequest wrap(Object request) {
return new HttpRequestAdapter((Request) request);
}
} |
Resolve class via app property | <?php
namespace App\Providers;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
});
}
}
| <?php
namespace App\Providers;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
Auth::viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
});
}
}
|
Update the default version to the current one. | package rs.emulate.lynx.net;
/**
* Contains constants used as part of the js5 protocol.
*
* @author Major
*/
public final class Js5Constants {
/**
* The amount of times to attempt a connection to the server (incrementing the major version each unsuccessful
* connection) before stopping.
*/
public static final int DEFAULT_ATTEMPT_COUNT = 100;
/**
* The port the js5 worker should connect to.
*/
public static final int DEFAULT_PORT = 43594;
/**
* The major version (i.e. client version).
*/
public static final int MAJOR_VERSION = 816;
/**
* The minor version.
*/
public static final int MINOR_VERSION = 1;
/**
* The host to connect to.
*/
public static final String HOST = "world1.runescape.com";
/**
* Default private constructor to prevent instantiation.
*/
private Js5Constants() {
}
} | package rs.emulate.lynx.net;
/**
* Contains constants used as part of the js5 protocol.
*
* @author Major
*/
public final class Js5Constants {
/**
* The amount of times to attempt a connection to the server (incrementing the major version each unsuccessful
* connection) before stopping.
*/
public static final int DEFAULT_ATTEMPT_COUNT = 100;
/**
* The port the js5 worker should connect to.
*/
public static final int DEFAULT_PORT = 43594;
/**
* The major version (i.e. client version).
*/
public static final int MAJOR_VERSION = 814;
/**
* The minor version.
*/
public static final int MINOR_VERSION = 1;
/**
* The host to connect to.
*/
public static final String HOST = "world1.runescape.com";
/**
* Default private constructor to prevent instantiation.
*/
private Js5Constants() {
}
} |
Fix rule parser to allow certain rules
Specifically, rules that have control characters as their "variable"
(thse should always be "constant" rules). An example is (+ -> +). | // L-System Rule Parser
function RuleParser(str) {
this.str = str;
this.rules = {};
this.parse = function() {
var c, d;
var env = 0;
var rule_str;
var variable;
var variable_regex = /[A-Z]/;
var control_regex = /[\+-\[\]]/;
for (var i = 0; i < this.str.length; i++) {
c = this.str[i];
if (i > 0) {
d = this.str[i-1];
} else {
d = null;
}
if (c == '(') {
env = 1;
rule_str = "";
} else if (c == '>' && d == '-') {
env = 3;
} else if ((c.search(variable_regex) == 0 || c.search(control_regex) == 0)
&& env == 1) {
variable = c;
env = 2;
} else if ((c.search(variable_regex) == 0 || c.search(control_regex) == 0)
&& env == 3) {
rule_str += c;
} else if (c == ')') {
this.rules[variable] = rule_str;
env = 0;
}
}
return this.rules;
}
}
module.exports = RuleParser;
| // L-System Rule Parser
function RuleParser(str) {
this.str = str;
this.rules = {};
this.parse = function() {
var c, d;
var env = 0;
var rule_str;
var variable;
for (var i = 0; i < this.str.length; i++) {
c = this.str[i];
if (i > 0) {
d = this.str[i-1];
} else {
d = null;
}
if (c == '(') {
env = 1;
rule_str = "";
} else if ((c.search(/[A-Z]/) == 0 || c.search(/[\+\-\[\]]/) == 0)
&& env == 1) {
variable = c;
} else if (c == '>' && d == '-') {
env = 2;
} else if ((c.search(/[A-Z]/) == 0 || c.search(/[\+-\[\]]/) == 0)
&& env == 2) {
rule_str += c;
} else if (c == ')') {
this.rules[variable] = rule_str;
env = 0;
}
}
return this.rules;
}
}
module.exports = RuleParser;
|
Update testSetCustomChromeFlags to only append to chrome flags, not override
This is in keeping with the spirit of the ExtraChromeFlags() method. Whenever
it's overridden, it should only ever append to the list of chrome flags,
never completely override it.
BUG=None
TEST=None
R=dennisjeffrey@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10041001
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@131597 0039d316-1c4b-4281-b951-d872f2087c98 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
import pyauto_functional # Must be imported before pyauto
import pyauto
class PyAutoTest(pyauto.PyUITest):
"""Test functionality of the PyAuto framework."""
_EXTRA_CHROME_FLAGS = [
'--scooby-doo=123',
'--donald-duck=cool',
'--super-mario',
'--marvin-the-martian',
]
def ExtraChromeFlags(self):
"""Ensures Chrome is launched with some custom flags.
Overrides the default list of extra flags passed to Chrome. See
ExtraChromeFlags() in pyauto.py.
"""
return pyauto.PyUITest.ExtraChromeFlags(self) + self._EXTRA_CHROME_FLAGS
def testSetCustomChromeFlags(self):
"""Ensures that Chrome can be launched with custom flags."""
self.NavigateToURL('about://version')
for flag in self._EXTRA_CHROME_FLAGS:
self.assertEqual(self.FindInPage(flag)['match_count'], 1,
msg='Missing expected Chrome flag "%s"' % flag)
if __name__ == '__main__':
pyauto_functional.Main()
| #!/usr/bin/env python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
import pyauto_functional # Must be imported before pyauto
import pyauto
class PyAutoTest(pyauto.PyUITest):
"""Test functionality of the PyAuto framework."""
_EXTRA_CHROME_FLAGS = [
'--scooby-doo=123',
'--donald-duck=cool',
'--super-mario',
'--marvin-the-martian',
]
def ExtraChromeFlags(self):
"""Ensures Chrome is launched with some custom flags.
Overrides the default list of extra flags passed to Chrome. See
ExtraChromeFlags() in pyauto.py.
"""
return self._EXTRA_CHROME_FLAGS
def testSetCustomChromeFlags(self):
"""Ensures that Chrome can be launched with custom flags."""
self.NavigateToURL('about://version')
for flag in self._EXTRA_CHROME_FLAGS:
self.assertEqual(self.FindInPage(flag)['match_count'], 1,
msg='Missing expected Chrome flag "%s"' % flag)
if __name__ == '__main__':
pyauto_functional.Main()
|
Add issue key to log message about posting to Slack | 'use strict';
const config = require('./config');
const JiraTicket = require('./jira-ticket');
const JiraBot = require('./jira-bot');
const log = require('winston');
const jiraTicket = new JiraTicket(config.jira);
const jiraBot = new JiraBot(config.slack);
jiraBot.on('ticketKeyFound', (key, channel) => {
jiraBot.sendTyping(channel.id);
jiraTicket.get(key, function(error, ticket) {
if (error) {
return;
}
const message = `>*${ticket.key}*\n>${ticket.summary}\n>Status: ${ticket.status}\n>${ticket.url}`;
jiraBot.sendMessage(message, channel.id, (error) => {
if (error) {
log.error('Error while posting issue info to Slack', error);
return;
}
log.info(`Posted Jira ${ticket.key} info to channel #${channel.name}`);
});
});
});
jiraBot.login();
| 'use strict';
const config = require('./config');
const JiraTicket = require('./jira-ticket');
const JiraBot = require('./jira-bot');
const log = require('winston');
const jiraTicket = new JiraTicket(config.jira);
const jiraBot = new JiraBot(config.slack);
jiraBot.on('ticketKeyFound', (key, channel) => {
jiraBot.sendTyping(channel.id);
jiraTicket.get(key, function(error, ticket) {
if (error) {
return;
}
const message = `>*${ticket.key}*\n>${ticket.summary}\n>Status: ${ticket.status}\n>${ticket.url}`;
jiraBot.sendMessage(message, channel.id, (error) => {
if (error) {
log.error('Error while posting issue info to Slack', error);
return;
}
log.info(`Posted Jira issue info to channel #${channel.name}`);
});
});
});
jiraBot.login();
|
Fix redusers like & dislike | import createReducer from 'borex-reducers/createReducer';
import actionCreator from 'borex-actions/actionCreator';
import setMetaStatic from 'borex-actions/setMetaStatic';
import appendIn from 'borex-reducers/appendIn';
import initialState from 'vclub/redux/initialClubState';
export const toggleModal = actionCreator(
setMetaStatic('remote', true),
setMetaStatic('broadcast', true)
);
export const like = actionCreator(
setMetaStatic('remote', true),
setMetaStatic('broadcast', true)
);
export const dislike = actionCreator(
setMetaStatic('remote', true),
setMetaStatic('broadcast', true)
);
export default createReducer((on) => {
on(toggleModal, (state) => {
if (state.showModalVote === true) return initialState.vote;
return {
...state,
showModalVote: !state.showModalVote,
};
});
on(like, appendIn('pros'));
on(dislike, appendIn('cons'));
});
| import createReducer from 'borex-reducers/createReducer';
import actionCreator from 'borex-actions/actionCreator';
import setMetaStatic from 'borex-actions/setMetaStatic';
import initialState from 'vclub/redux/initialClubState';
export const toggleModal = actionCreator(
setMetaStatic('remote', true),
setMetaStatic('broadcast', true)
);
export const like = actionCreator(
setMetaStatic('remote', true),
setMetaStatic('broadcast', true)
);
export const dislike = actionCreator(
setMetaStatic('remote', true),
setMetaStatic('broadcast', true)
);
export default createReducer((on) => {
on(toggleModal, (state) => {
if (state.showModalVote === true) return initialState.vote;
return {
...state,
showModalVote: !state.showModalVote,
};
});
on(like, (state, action) => ({ ...state, pros: [...state.pros, action.payload] }));
on(dislike, (state, action) => ({ ...state, cons: [...state.cons, action.payload] }));
});
|
Update Ctrl+Alt+Del Sillies crawler with new URL | from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.ctrlaltdel-online.com/comics/Lite%(date)s.gif' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
| from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.cad-comic.com/comics/Lite%(date)s.jpg' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
|
Allow example tree component to display any data structure | import React, { Component } from 'react';
import Header from '../containers/Header';
import Visualizer from './Visualizer';
import { flatten, augment, pause, highlight } from '../utils/vertTreeUtils';
import * as structures from '../utils/TreeStructures';
export default class ExampleTree extends Component {
constructor(props) {
super(props);
this.augmentDataStructure();
}
augmentDataStructure() {
const { treeData, dataStructure, callAsync, updateStructure, highlightNode } = this.props;
const exampleTree = structures[dataStructure](
pause.bind(null, callAsync.bind(null, updateStructure)),
highlight.bind(null, callAsync.bind(null, highlightNode))
);
this.augmentedState = augment(treeData.present.toJS()[0], exampleTree);
pause(updateStructure, this.augmentedState.root);
}
execute(method, ...args) {
this.augmentedState[method](...args);
}
render() {
const { treeData, delay } = this.props;
const treeArray = flatten(treeData.present).toJS();
return (
<div>
<Header
dataType='verticalTreeData'
headerType='example'
execute={this.execute.bind(this)}
/>
<Visualizer
treeArray={treeArray}
delay={delay}
/>
</div>
);
}
} | import React, { Component } from 'react';
import { Link } from 'react-router';
import Header from '../containers/Header';
import Visualizer from './Visualizer';
import { flatten, augment, pause, highlight } from '../utils/vertTreeUtils';
import * as structures from '../utils/TreeStructures';
export default class ExampleTree extends Component {
constructor(props) {
super(props);
this.augmentDataStructure();
}
augmentDataStructure() {
const { treeData, callAsync, updateStructure, highlightNode } = this.props;
const AVLTree = structures.AVLCreator(
pause.bind(null, callAsync.bind(null, updateStructure)),
highlight.bind(null, callAsync.bind(null, highlightNode))
);
this.augmentedState = augment(treeData.present.toJS()[0], AVLTree);
}
execute(method, ...args) {
this.augmentedState[method](...args);
}
render() {
const { treeData, delay } = this.props;
const treeArray = flatten(treeData.present).toJS();
return (
<div>
<Header
dataType='verticalTreeData'
headerType='example'
execute={this.execute.bind(this)}
/>
<Visualizer
treeArray={treeArray}
delay={delay}
/>
<Link to="/">Main Menu</Link>
</div>
);
}
} |
Set pageX/pageY according to quirksmode's rules. | 'use strict';
'browser-only';
/**
* @license
* (c) 2014 Cluster Labs, Inc. https://cluster.co/
* License: MIT
*/
var ElementWrapper = skit.browser.ElementWrapper;
var Event = function(evt) {
this.evt_ = evt;
this.target = new ElementWrapper(evt.srcElement || evt.target);
this.currentTarget = null;
this.type = evt.type;
this.keyCode = evt.keyCode || null;
this.shiftKey = evt.shiftKey || false;
var posX = 0;
var posY = 0;
if (evt.pageX || evt.pageY) {
posX = evt.pageX;
posY = evt.pageY;
} else if (evt.clientX || evt.clientY) {
posX = evt.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posY = evt.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
this.pageX = posX;
this.pageY = posY;
};
Event.prototype.stopPropagation = function() {
if (this.evt_.stopPropagation) {
this.evt_.stopPropagation();
} else {
this.evt_.cancelBubble = true;
}
};
Event.prototype.preventDefault = function() {
if (this.evt_.preventDefault) {
this.evt_.preventDefault();
} else {
this.evt_.returnValue = false;
}
};
return Event;
| 'use strict';
'browser-only';
/**
* @license
* (c) 2014 Cluster Labs, Inc. https://cluster.co/
* License: MIT
*/
var ElementWrapper = skit.browser.ElementWrapper;
var Event = function(evt) {
this.evt_ = evt;
this.target = new ElementWrapper(evt.srcElement || evt.target);
this.currentTarget = null;
this.type = evt.type;
this.keyCode = evt.keyCode || null;
this.shiftKey = evt.shiftKey || false;
// mouseX, mouseY, keyCode, etc.
};
Event.prototype.stopPropagation = function() {
if (this.evt_.stopPropagation) {
this.evt_.stopPropagation();
} else {
this.evt_.cancelBubble = true;
}
};
Event.prototype.preventDefault = function() {
if (this.evt_.preventDefault) {
this.evt_.preventDefault();
} else {
this.evt_.returnValue = false;
}
};
return Event;
|
Remove Highlights.GetAll and make Items public | package models
import (
"path"
"io/ioutil"
"os"
"encoding/json"
"ghighlighter/utils"
)
type GhHighlights struct {
Items []GhHighlight
}
func highlightsFilePath() string {
return path.Join(utils.DataDir(), "highlights.json")
}
func (m *GhHighlights) Read() {
data, error := ioutil.ReadFile(highlightsFilePath())
if error != nil && !os.IsExist(error) {
m.Write()
m.Read()
}
var tmpItems []GhHighlight
json.Unmarshal(data, &tmpItems)
for _, highlight := range tmpItems {
m.Items = append(m.Items, highlight)
}
}
func (m *GhHighlights) Write() {
if m.Items == nil {
m.Items = make([]GhHighlight, 0)
}
data, error := json.Marshal(m.Items)
if error != nil { return }
error = ioutil.WriteFile(highlightsFilePath(), data, 0755)
}
func Highlights() *GhHighlights {
highlights := &GhHighlights{}
highlights.Read()
return highlights
}
| package models
import (
"path"
"io/ioutil"
"os"
"encoding/json"
"ghighlighter/utils"
)
type GhHighlights struct {
items []GhHighlight
}
func (m *GhHighlights) GetAll() []GhHighlight {
m.Read()
return m.items
}
func highlightsFilePath() string {
return path.Join(utils.DataDir(), "highlights.json")
}
func (m *GhHighlights) Read() {
data, error := ioutil.ReadFile(highlightsFilePath())
if error != nil && !os.IsExist(error) {
m.Write()
m.Read()
}
var tmpItems []GhHighlight
json.Unmarshal(data, &tmpItems)
m.items = make([]GhHighlight, len(tmpItems))
for _, highlight := range tmpItems {
m.items = append(m.items, highlight)
}
}
func (m *GhHighlights) Write() {
if m.items == nil {
m.items = make([]GhHighlight, 0)
}
data, error := json.Marshal(m.items)
if error != nil { return }
error = ioutil.WriteFile(highlightsFilePath(), data, 0755)
}
func Highlights() *GhHighlights {
highlights := &GhHighlights{}
highlights.Read()
return highlights
}
|
Support new and old Django urlconf imports | try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import * # In case of Django<=1.3
urlpatterns = patterns(
'premis_event_service.views',
# begin CODA Family url structure >
(r'^APP/$', 'app'),
# node urls
# (r'^APP/node/$', 'node'),
# (r'^APP/node/(?P<identifier>.+?)/$', 'node'),
# event urls
(r'^APP/event/$', 'app_event'),
(r'^APP/event/(?P<identifier>.+?)/$', 'app_event'),
# agent urls
(r'^APP/agent/$', 'app_agent'),
(r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'),
# html view urls
(r'^event/$', 'recent_event_list'),
(r'^event/search/$', 'event_search'),
(r'^event/search.json$', 'json_event_search'),
(r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'),
(r'^event/(?P<identifier>.+?)/$', 'humanEvent'),
(r'^agent/$', 'humanAgent'),
(r'^agent/(?P<identifier>.+?).xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).json$', 'json_agent'),
(r'^agent/(?P<identifier>.+?)/$', 'humanAgent'),
)
| from django.conf.urls.defaults import *
urlpatterns = patterns(
'premis_event_service.views',
# begin CODA Family url structure >
(r'^APP/$', 'app'),
# node urls
# (r'^APP/node/$', 'node'),
# (r'^APP/node/(?P<identifier>.+?)/$', 'node'),
# event urls
(r'^APP/event/$', 'app_event'),
(r'^APP/event/(?P<identifier>.+?)/$', 'app_event'),
# agent urls
(r'^APP/agent/$', 'app_agent'),
(r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'),
# html view urls
(r'^event/$', 'recent_event_list'),
(r'^event/search/$', 'event_search'),
(r'^event/search.json$', 'json_event_search'),
(r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'),
(r'^event/(?P<identifier>.+?)/$', 'humanEvent'),
(r'^agent/$', 'humanAgent'),
(r'^agent/(?P<identifier>.+?).xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'),
(r'^agent/(?P<identifier>.+?).json$', 'json_agent'),
(r'^agent/(?P<identifier>.+?)/$', 'humanAgent'),
)
|
Add comment to mystic null check :P | import {TODO_TRX_PATH, DONE_TRX_PATH} from './settings'
import {push} from './firebase_useful'
export function getClient(firebase, options = {}) {
let {todoTrxPath = TODO_TRX_PATH, doneTrxPath = DONE_TRX_PATH} = options
let submitRef = firebase.child(todoTrxPath)
return (data) => {
const trxId = push(submitRef, data).key()
let resultRef = firebase.child(doneTrxPath).child(trxId)
return new Promise((resolve, reject) => {
let fn = resultRef.on('value', (snap) => {
// after subscription, we first got 'null' value so
// we have to ignore this
if (snap.val() != null) {
resolve(snap.val().result)
resultRef.off('value', fn)
}
})
})
}
}
| import {TODO_TRX_PATH, DONE_TRX_PATH} from './settings'
import {push} from './firebase_useful'
export function getClient(firebase, options = {}) {
let {todoTrxPath = TODO_TRX_PATH, doneTrxPath = DONE_TRX_PATH} = options
let submitRef = firebase.child(todoTrxPath)
return (data) => {
const trxId = push(submitRef, data).key()
let resultRef = firebase.child(doneTrxPath).child(trxId)
return new Promise((resolve, reject) => {
let fn = resultRef.on('value', (snap) => {
if (snap.val() != null) {
resolve(snap.val().result)
resultRef.off('value', fn)
}
})
})
}
}
|
Clear the body for test fixtures. | /* global vfs */
import {
TextureConfigurator, ArticlePackage,
ArticleEditorSession,
ArticleAPI, createEditorContext,
VfsStorageClient, TextureArchive, InMemoryDarBuffer
} from '../index'
export default function setupTestArticleSession (docInitializer) {
let configurator = new TextureConfigurator()
configurator.import(ArticlePackage)
// TODO: this could be a little easier
let config = configurator.getConfiguration('article').getConfiguration('manuscript')
// load the empty archive
let storage = new VfsStorageClient(vfs, './data/')
let archive = new TextureArchive(storage, new InMemoryDarBuffer())
// ATTENTION: in case of the VFS loading is synchronous
// TODO: make sure that this is always the case
archive.load('blank', () => {})
let session = archive.getEditorSession('manuscript')
let doc = session.getDocument()
if (docInitializer) {
// clear the body
let body = doc.get('body')
body.removeAt(0)
}
if (docInitializer) {
docInitializer(doc)
}
// NOTE: this indirection is necessary because we need to pass the context to parts of the context
let contextProvider = {}
let editorSession = new ArticleEditorSession(doc, config, contextProvider)
let api = new ArticleAPI(editorSession, config, archive)
let context = Object.assign(createEditorContext(config, editorSession), { api })
// ... after the context is ready we can store it into the provider
contextProvider.context = context
return { context, editorSession, doc, archive }
}
| /* global vfs */
import {
TextureConfigurator, ArticlePackage,
ArticleEditorSession,
ArticleAPI, createEditorContext,
VfsStorageClient, TextureArchive, InMemoryDarBuffer
} from '../index'
export default function setupTestArticleSession (docInitializer) {
let configurator = new TextureConfigurator()
configurator.import(ArticlePackage)
// TODO: this could be a little easier
let config = configurator.getConfiguration('article').getConfiguration('manuscript')
// load the empty archive
let storage = new VfsStorageClient(vfs, './data/')
let archive = new TextureArchive(storage, new InMemoryDarBuffer())
// ATTENTION: in case of the VFS loading is synchronous
// TODO: make sure that this is always the case
archive.load('blank', () => {})
let session = archive.getEditorSession('manuscript')
let doc = session.getDocument()
if (docInitializer) {
docInitializer(doc)
}
// NOTE: this indirection is necessary because we need to pass the context to parts of the context
let contextProvider = {}
let editorSession = new ArticleEditorSession(doc, config, contextProvider)
let api = new ArticleAPI(editorSession, config, archive)
let context = Object.assign(createEditorContext(config, editorSession), { api })
// ... after the context is ready we can store it into the provider
contextProvider.context = context
return { context, editorSession, doc, archive }
}
|
Add missing import to utility python script
BUG=
R=kustermann@google.com
Review URL: https://codereview.chromium.org//1222793010. | #!/usr/bin/env python
#
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
import shutil
import sys
import subprocess
import utils
def Main():
build_root = utils.GetBuildRoot(utils.GuessOS())
print 'Deleting %s' % build_root
if sys.platform != 'win32':
shutil.rmtree(build_root, ignore_errors=True)
else:
# Intentionally ignore return value since a directory might be in use.
subprocess.call(['rmdir', '/Q', '/S', build_root],
env=os.environ.copy(),
shell=True)
return 0
if __name__ == '__main__':
sys.exit(Main())
| #!/usr/bin/env python
#
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
#
import shutil
import sys
import utils
def Main():
build_root = utils.GetBuildRoot(utils.GuessOS())
print 'Deleting %s' % build_root
if sys.platform != 'win32':
shutil.rmtree(build_root, ignore_errors=True)
else:
# Intentionally ignore return value since a directory might be in use.
subprocess.call(['rmdir', '/Q', '/S', build_root],
env=os.environ.copy(),
shell=True)
return 0
if __name__ == '__main__':
sys.exit(Main())
|
fix(): Check for existence of window object
https://github.com/rcdexta/react-trello/issues/15 | import React, {Component, PropTypes} from 'react'
import BoardContainer from './BoardContainer'
import {Provider} from 'react-redux'
import {createStore} from 'redux'
import boardReducer from '../reducers/BoardReducer'
let store = createStore(boardReducer, window && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
export default class Board extends Component {
render () {
return <Provider store={store}>
<BoardContainer {...this.props} />
</Provider>
}
}
Board.propTypes = {
data: PropTypes.object.isRequired,
onLaneScroll: PropTypes.func,
onCardClick: PropTypes.func,
eventBusHandle: PropTypes.func,
laneSortFunction: PropTypes.func,
draggable: PropTypes.bool,
handleDragStart: PropTypes.func,
handleDragEnd: PropTypes.func,
onDataChange: PropTypes.func
}
| import React, {Component, PropTypes} from 'react'
import BoardContainer from './BoardContainer'
import {Provider} from 'react-redux'
import {createStore} from 'redux'
import boardReducer from '../reducers/BoardReducer'
let store = createStore(boardReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
export default class Board extends Component {
render () {
return <Provider store={store}>
<BoardContainer {...this.props} />
</Provider>
}
}
Board.propTypes = {
data: PropTypes.object.isRequired,
onLaneScroll: PropTypes.func,
onCardClick: PropTypes.func,
eventBusHandle: PropTypes.func,
laneSortFunction: PropTypes.func,
draggable: PropTypes.bool,
handleDragStart: PropTypes.func,
handleDragEnd: PropTypes.func,
onDataChange: PropTypes.func
}
|
Make number of vertices configurable | <?php
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Loader\CompleteGraph;
class CompleteGraphTest extends TestCase
{
public function testOne(){
$loader = new CompleteGraph(1);
$graph = $loader->createGraph();
$expected = new Graph();
$expected->createVertex();
$this->assertGraphEquals($expected,$graph);
}
public function testUndirected(){
$n = 9;
$loader = new CompleteGraph($n);
$graph = $loader->createGraph();
$this->assertEquals($n,$graph->getNumberOfVertices());
$this->assertEquals($n*($n-1)/2,$graph->getNumberOfEdges());
}
public function testDirected(){
$n = 8;
$loader = new CompleteGraph($n);
$loader->setEnableDirectedEdges(true);
$graph = $loader->createGraph();
$this->assertEquals($n,$graph->getNumberOfVertices());
$this->assertEquals($n*($n-1),$graph->getNumberOfEdges()); // n*(n-1) for directed graphs
$this->assertTrue($graph->isDirected());
$this->assertTrue($graph->isComplete());
}
}
| <?php
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Loader\CompleteGraph;
class CompleteGraphTest extends TestCase
{
public function testOne(){
$loader = new CompleteGraph(1);
$graph = $loader->createGraph();
$expected = new Graph();
$expected->createVertex();
$this->assertGraphEquals($expected,$graph);
}
public function testTen(){
$loader = new CompleteGraph(10);
$graph = $loader->createGraph();
$this->assertEquals(10,$graph->getNumberOfVertices()); // $n
$this->assertEquals(45,$graph->getNumberOfEdges()); // n*(n-1)/2
}
public function testDirected(){
$loader = new CompleteGraph(5);
$loader->setEnableDirectedEdges(true);
$graph = $loader->createGraph();
$this->assertEquals(5,$graph->getNumberOfVertices());
$this->assertEquals(20,$graph->getNumberOfEdges()); // n*(n-1) for directed graphs
$this->assertTrue($graph->isDirected());
$this->assertTrue($graph->isComplete());
}
}
|
Add docstring explaining the parametrization of data files | """Base for all tests with definitions of fixtures"""
import glob
import os
TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data")
TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt"))
DATA_FILES_FIXTURE_NAME = "data_file"
def _load_files_contents(*files):
for file_ in files:
with open(file_) as source:
yield source.read()
def pytest_generate_tests(metafunc):
"""All tests that take a fixture named ``data_file`` will be parameterized
with all the testing data files.
This means, the test can be made to work with a single test file as an
input, but instead it will run once per every file present in the directory
``TEST_DATA_FILES_LOCATION``.
"""
if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames:
metafunc.parametrize(
DATA_FILES_FIXTURE_NAME,
_load_files_contents(*TEST_DATA_FILES),
ids=TEST_DATA_FILES,
)
| """Base for all tests with definitions of fixtures"""
import glob
import os
TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data")
TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt"))
DATA_FILES_FIXTURE_NAME = "data_file"
def _load_files_contents(*files):
for file_ in files:
with open(file_) as source:
yield source.read()
def pytest_generate_tests(metafunc): # pylint: disable=C0111
if DATA_FILES_FIXTURE_NAME in metafunc.fixturenames:
metafunc.parametrize(
DATA_FILES_FIXTURE_NAME,
_load_files_contents(*TEST_DATA_FILES),
ids=TEST_DATA_FILES,
)
|
Return 400 when state is invalid | from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from countylimits.models import CountyLimit
@api_view(['GET'])
def county_limits(request):
""" Return all counties with their limits per state. """
if request.method == 'GET':
package = {'request': {}, 'data': []}
if 'state' in request.GET:
state = request.GET['state']
data = CountyLimit.county_limits_by_state(state)
if data:
package['request']['state'] = request.GET['state']
package['data'] = data
return Response(package)
else:
return Response({'state': 'Invalid state'}, status=status.HTTP_400_BAD_REQUEST)
else:
return Response({'detail': 'Required parameter state is missing'}, status=status.HTTP_400_BAD_REQUEST)
| from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from countylimits.models import CountyLimit
@api_view(['GET'])
def county_limits(request):
""" Return all counties with their limits per state. """
if request.method == 'GET':
package = {'request': {}, 'data': []}
if 'state' in request.GET:
state = package['request']['state'] = request.GET['state']
package['data'] = CountyLimit.county_limits_by_state(state)
return Response(package)
else:
return Response({'detail': 'Required parameter state is missing'}, status=status.HTTP_400_BAD_REQUEST)
|
Use find packages to recursively search | from setuptools import setup
from setuptools import find_packages
setup(
name="spare5",
version='0.1',
description="Spare 5 Python API client",
license="MIT",
author="John Williams, Philip Kimmey",
author_email="john@rover.com, philip@rover.com",
packages=find_packages(),
keywords=['spare5'],
install_requires=[],
classifiers=[
'Environment :: Other Environment',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries'
],
)
| from setuptools import setup
setup(
name="spare5",
version='0.1',
description="Spare 5 Python API client",
license="MIT",
author="John Williams, Philip Kimmey",
author_email="john@rover.com, philip@rover.com",
packages=['spare5'],
keywords=['spare5'],
install_requires=[],
classifiers=[
'Environment :: Other Environment',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries'
],
)
|
Throw errors that are not ENOENT | var fs = require('fs');
exports.directory = function(path) {
var stats;
try {
stats = fs.statSync(path);
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('No such directory ' + path);
} else {
throw new Error(err.message);
}
}
if (!stats.isDirectory()) {
throw new Error(path + ' is not a directory');
}
};
exports.file = function(path) {
var stats;
try {
stats = fs.statSync(path);
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('No such file ' + path);
} else {
throw err;
}
}
if (!stats.isFile()) {
throw new Error(path + ' is not a file');
}
};
| var fs = require('fs');
exports.directory = function(path) {
var stats;
try {
stats = fs.statSync(path);
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('No such directory ' + path);
}
}
if (!stats.isDirectory()) {
throw new Error(path + ' is not a directory');
}
};
exports.file = function(path) {
var stats;
try {
stats = fs.statSync(path);
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('No such file ' + path);
} else {
throw err;
}
}
if (!stats.isFile()) {
throw new Error(path + ' is not a file');
}
};
|
Make all API resource collection endpoints plural
/api/job/ -> /api/jobs/
/api/metric/ -> /api/metrics/
It's a standard convention in RESTful APIs to make endpoints for
collections plural. | from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
<<<<<<< HEAD
router = DefaultRouter()
router.register(r'job', views.JobViewSet)
router.register(r'metric', views.MetricViewSet)
=======
api_router = DefaultRouter()
api_router.register(r'jobs', views.JobViewSet)
api_router.register(r'metrics', views.MetricViewSet)
api_router.register(r'packages', views.PackageViewSet)
>>>>>>> b962845... Make all API resource collection endpoints plural
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api/token/', obtain_auth_token, name='api-token'),
url(r'^(?P<pk>[0-9]+)/dashboard/',
views.MetricDashboardView.as_view(),
name='metric-detail'),
url(r'^$', views.HomeView.as_view(), name='home'),
]
| from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'job', views.JobViewSet)
router.register(r'metric', views.MetricViewSet)
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api/token/', obtain_auth_token, name='api-token'),
url(r'^(?P<pk>[0-9]+)/dashboard/',
views.MetricDashboardView.as_view(),
name='metric-detail'),
url(r'^$', views.HomeView.as_view(), name='home'),
]
|
Remove not found script message | #!/usr/bin/python
# from setuptools
# import setup
import os
__author__ = "Andre Christoga"
input = raw_input("> (eg plus, minus, divide...)")
if input == "plus":
os.system("pymain/plus.py")
if input == "minus":
os.system("pymain/minus.py")
if input == "multi":
os.system("pymain/multi.py")
if input == "divide":
os.system("pymain/divide.py")
if input == "modulos":
os.system("pymain/modulos.py")
# setup(
# name="PyMaIn",
# version="1.0.0",
# author="Coding Smart School",
# author_email="codingsmartschool@gmail.com",
# url="https://github.com/codingsmartschool/pymain",
# description="Python Math Input",
# long_description=("PyMaIn is a python program that takes maths number"
# " and give user the answer."),
# classifiers=[
# 'Development Status :: 4 - Beta',
# 'Programming Language :: Python',
# ],
# license="MIT",
# packages=['pymain'],
# ) | #!/usr/bin/python
# from setuptools
# import setup
import os
__author__ = "Andre Christoga"
input = raw_input("> (eg plus, minus, divide...)")
if input == "plus":
os.system("pymain/plus.py")
if input == "minus":
os.system("pymain/minus.py")
if input == "multi":
os.system("pymain/multi.py")
if input == "divide":
os.system("pymain/divide.py")
if input == "modulos":
os.system("pymain/modulos.py")
else :
print "The script does not exists"
# setup(
# name="PyMaIn",
# version="1.0.0",
# author="Coding Smart School",
# author_email="codingsmartschool@gmail.com",
# url="https://github.com/codingsmartschool/pymain",
# description="Python Math Input",
# long_description=("PyMaIn is a python program that takes maths number"
# " and give user the answer."),
# classifiers=[
# 'Development Status :: 4 - Beta',
# 'Programming Language :: Python',
# ],
# license="MIT",
# packages=['pymain'],
# ) |
Update test_connect to read password from env. variable | # unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
self.password = os.environ.get('RP_PASSWORD') or 'root'
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_password(self):
self.assertIsNotNone(
self.password,
msg="Set RP_PASSWORD=<your redpitaya password> to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname, password=self.password)
self.assertEqual(r.hk.led, 0)
| # unitary test for the pyrpl module
import unittest
import os
from pyrpl import RedPitaya
class RedPitayaTestCases(unittest.TestCase):
def setUp(self):
self.hostname = os.environ.get('REDPITAYA')
def tearDown(self):
pass
def test_hostname(self):
self.assertIsNotNone(
self.hostname,
msg="Set REDPITAYA=localhost or the ip of your board to proceed!")
def test_connect(self):
if self.hostname != "localhost":
r = RedPitaya(hostname=self.hostname)
self.assertEqual(r.hk.led, 0)
|
Add user to raw_id_fields, drastically improves UX on sites with many users | from django.conf.urls import url
from django.contrib import admin
from admin_sso import settings
from admin_sso.models import Assignment
class AssignmentAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'username', 'username_mode', 'domain',
'user', 'weight')
list_editable = ('username', 'username_mode', 'domain', 'user', 'weight')
raw_id_fields = ('user',)
def get_urls(self):
from admin_sso.views import start, end
info = (self.model._meta.app_label, self.model._meta.model_name)
return [
url(r'^start/$', start,
name='%s_%s_start' % info),
url(r'^end/$', end,
name='%s_%s_end' % info),
] + super(AssignmentAdmin, self).get_urls()
admin.site.register(Assignment, AssignmentAdmin)
if settings.DJANGO_ADMIN_SSO_ADD_LOGIN_BUTTON:
admin.site.login_template = 'admin_sso/login.html'
| from django.conf.urls import url
from django.contrib import admin
from admin_sso import settings
from admin_sso.models import Assignment
class AssignmentAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'username', 'username_mode', 'domain',
'user', 'weight')
list_editable = ('username', 'username_mode', 'domain', 'user', 'weight')
def get_urls(self):
from admin_sso.views import start, end
info = (self.model._meta.app_label, self.model._meta.model_name)
return [
url(r'^start/$', start,
name='%s_%s_start' % info),
url(r'^end/$', end,
name='%s_%s_end' % info),
] + super(AssignmentAdmin, self).get_urls()
admin.site.register(Assignment, AssignmentAdmin)
if settings.DJANGO_ADMIN_SSO_ADD_LOGIN_BUTTON:
admin.site.login_template = 'admin_sso/login.html'
|
Fix problem where overwriteStyle fail if source is empty | export default {
/**
* Get computed style of an element.
* @param {Element} element
* @return {Object} computerd style object
*/
getComputedStyle(element) {
return element.currentStyle || getComputedStyle(element);
},
/**
* Overwrite existing node's style with the given style
*/
overwriteStyle(target, source) {
source = source || {};
Object.keys(source).forEach((styleKey) => {
target[styleKey] = source[styleKey];
});
},
computeElementHeight(element) {
const nodeStyle = this.getComputedStyle(element);
// Get node's height
const nodeStyleHeight = parseFloat(nodeStyle.height, 10) || 0;
const nodeHeight = Math.max(
element.clientHeight,
element.offsetHeight,
nodeStyleHeight
);
// Get node's margin
const nodeMargin = parseFloat(nodeStyle.marginTop, 10) +
parseFloat(nodeStyle.marginBottom, 10);
const totalHeight = nodeHeight + nodeMargin;
if (isNaN(totalHeight)) {
throw new Error('Error calculating element\'s height');
}
return totalHeight;
},
};
| export default {
/**
* Get computed style of an element.
* @param {Element} element
* @return {Object} computerd style object
*/
getComputedStyle(element) {
return element.currentStyle || getComputedStyle(element);
},
/**
* Overwrite existing node's style with the given style
*/
overwriteStyle(target, source) {
Object.keys(source).forEach((styleKey) => {
target[styleKey] = source[styleKey];
});
},
computeElementHeight(element) {
const nodeStyle = this.getComputedStyle(element);
// Get node's height
const nodeStyleHeight = parseFloat(nodeStyle.height, 10) || 0;
const nodeHeight = Math.max(
element.clientHeight,
element.offsetHeight,
nodeStyleHeight
);
// Get node's margin
const nodeMargin = parseFloat(nodeStyle.marginTop, 10) +
parseFloat(nodeStyle.marginBottom, 10);
const totalHeight = nodeHeight + nodeMargin;
if (isNaN(totalHeight)) {
throw new Error('Error calculating element\'s height');
}
return totalHeight;
},
};
|
Add test for Swig template compile | 'use strict';
var should = require('chai').should(); // eslint-disable-line
describe('swig', function() {
var r = require('../../../lib/plugins/renderer/swig');
it('normal', function() {
var body = [
'Hello {{ name }}!'
].join('\n');
r({text: body}, {
name: 'world'
}).should.eql('Hello world!');
});
it('override "for" tag', function() {
var body = [
'{% for x in arr %}',
'{{ x }}',
'{% endfor %}'
].join('');
var data = {
arr: {
toArray: function() {
return [1, 2, 3];
}
}
};
r({text: body}, data).should.eql('123');
});
it('compile', function() {
var body = [
'Hello {{ name }}!'
].join('\n');
var render = r.compile({
text: body
});
render({
name: 'world'
}).should.eql('Hello world!');
});
});
| 'use strict';
var should = require('chai').should(); // eslint-disable-line
describe('swig', function() {
var r = require('../../../lib/plugins/renderer/swig');
it('normal', function() {
var body = [
'Hello {{ name }}!'
].join('\n');
r({text: body}, {
name: 'world'
}).should.eql('Hello world!');
});
it('override "for" tag', function() {
var body = [
'{% for x in arr %}',
'{{ x }}',
'{% endfor %}'
].join('');
var data = {
arr: {
toArray: function() {
return [1, 2, 3];
}
}
};
r({text: body}, data).should.eql('123');
});
});
|
Make use of outputcontroller for caching js resonse | <?php
namespace MyTravel\Core\Controller;
use Patchwork\JSqueeze;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use MyTravel\Core\OutputInterface;
class Js implements OutputInterface {
public function viewJsBundle(Request $request) {
$sq = new JSqueeze();
$minifiedJs = array();
// Fetch all js files from view
$dirFiles = Finder::create()
->files()
->in(Config::get()->directories['views'] . '/' . Config::get()->view . '/js')
->name('*.js');
foreach ($dirFiles as $splFile) {
if (App::get()->inDevelopment()) {
array_push($minifiedJs, $splFile->getContents() . PHP_EOL);
} else {
array_push($minifiedJs, $sq->squeeze($splFile->getContents()));
}
}
return implode('', $minifiedJs);
}
public function output(GetResponseForControllerResultEvent $event) {
$response = new Response($event->getControllerResult());
$response->headers->set('Content-Type', 'application/javascript');
return $response;
}
}
| <?php
namespace MyTravel\Core\Controller;
use Patchwork\JSqueeze;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class Js {
public function viewJsBundle(Request $request) {
$sq = new JSqueeze();
$minifiedJs = array();
// Fetch all js files from view
$dirFiles = Finder::create()
->files()
->in(Config::get()->directories['views'] . '/' . Config::get()->view . '/js')
->name('*.js');
foreach ($dirFiles as $splFile) {
if (App::get()->inDevelopment()) {
array_push($minifiedJs, $splFile->getContents() . PHP_EOL);
} else {
array_push($minifiedJs, $sq->squeeze($splFile->getContents()));
}
}
$response = new Response(implode('', $minifiedJs));
$response->headers->set('Content-Type', 'application/javascript');
return $response;
}
}
|
Fix webpack config bug with babel-loader | var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'bootstrap-loader',
'webpack-hot-middleware/client', // Lets HMR know to re-render
'./src/index'
],
resolve: {
extensions: ['', '.js']
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel-loader'],
exclude: path.join(__dirname, 'node_modules')
},
{
test: /\.scss$/,
loaders: ['style', 'css?sourceMap', 'sass?sourceMap'],
include: path.join(__dirname, 'src')
},
{ test: /bootstrap-sass\/assets\/javascripts\//, loader: 'imports?jQuery=jquery' },
{ test: /\.(woff2?|svg)$/, loader: 'url?limit=10000' },
{ test: /\.(ttf|eot)$/, loader: 'file' },
]
}
};
| var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'bootstrap-loader',
'webpack-hot-middleware/client', // Lets HMR know to re-render
'./src/index'
],
resolve: {
extensions: ['', '.js']
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel-loader'],
},
{
test: /\.scss$/,
loaders: ['style', 'css?sourceMap', 'sass?sourceMap'],
include: path.join(__dirname, 'src')
},
{ test: /bootstrap-sass\/assets\/javascripts\//, loader: 'imports?jQuery=jquery' },
{ test: /\.(woff2?|svg)$/, loader: 'url?limit=10000' },
{ test: /\.(ttf|eot)$/, loader: 'file' },
]
}
};
|
Make TwG Settings Edit view consistent. | /**
* Thank with Google Settings Form component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { Fragment } from '@wordpress/element';
/**
* Internal dependencies
*/
import StoreErrorNotices from '../../../../components/StoreErrorNotices';
import { MODULES_THANK_WITH_GOOGLE } from '../../datastore/constants';
import {
CTAPlacement,
ColorRadio,
PostTypesSelect,
SupporterWall,
} from '../common';
export default function SettingsForm() {
return (
<Fragment>
<StoreErrorNotices
moduleSlug="thank-with-google"
storeName={ MODULES_THANK_WITH_GOOGLE }
/>
<div className="googlesitekit-setup-module__inputs">
<CTAPlacement />
<ColorRadio />
<PostTypesSelect />
<SupporterWall />
</div>
</Fragment>
);
}
| /**
* Thank with Google Settings Form component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { Fragment } from '@wordpress/element';
/**
* Internal dependencies
*/
import StoreErrorNotices from '../../../../components/StoreErrorNotices';
import { MODULES_THANK_WITH_GOOGLE } from '../../datastore/constants';
import {
CTAPlacement,
ColorRadio,
PostTypesSelect,
SupporterWall,
} from '../common';
export default function SettingsForm() {
return (
<Fragment>
<StoreErrorNotices
moduleSlug="thank-with-google"
storeName={ MODULES_THANK_WITH_GOOGLE }
/>
<div className="googlesitekit-setup-module__inputs">
<CTAPlacement />
<SupporterWall />
<ColorRadio />
<PostTypesSelect />
</div>
</Fragment>
);
}
|
Correct last-modified if equals to 1970-01-01 | <?php declare(strict_types=1);
/*
* This file is part of the feed-io package.
*
* (c) Alexandre Debril <alex.debril@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FeedIo\Reader\Fixer;
use FeedIo\FeedInterface;
use FeedIo\Reader\FixerAbstract;
use FeedIo\Reader\Result;
class HttpLastModified extends FixerAbstract
{
/**
* @param Result $result
* @return FixerAbstract
*/
public function correct(Result $result): FixerAbstract
{
$feed = $result->getFeed();
$response = $result->getResponse();
if ($this->isInvalid($feed) && $response->getLastModified() instanceof \DateTime) {
$this->logger->debug("found last modified: " . $response->getLastModified()->format(\DateTime::RSS));
$feed->setLastModified($response->getLastModified());
}
return $this;
}
/**
* @param FeedInterface $feed
* @return bool
*/
protected function isInvalid(FeedInterface $feed): bool
{
return is_null($feed->getLastModified()) || $feed->getLastModified() == new \DateTime('@0');
}
}
| <?php declare(strict_types=1);
/*
* This file is part of the feed-io package.
*
* (c) Alexandre Debril <alex.debril@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FeedIo\Reader\Fixer;
use FeedIo\Reader\FixerAbstract;
use FeedIo\Reader\Result;
class HttpLastModified extends FixerAbstract
{
/**
* @param Result $result
* @return FixerAbstract
*/
public function correct(Result $result): FixerAbstract
{
$feed = $result->getFeed();
$response = $result->getResponse();
if ($feed->getLastModified() === null && $response->getLastModified() instanceof \DateTime) {
$this->logger->debug("found last modified: " . $response->getLastModified()->format(\DateTime::RSS));
$feed->setLastModified($response->getLastModified());
}
return $this;
}
}
|
Fix L2BD arp termination Test Case
==============================================================================
L2BD arp termination Test Case
==============================================================================
12:02:21,850 Couldn't stat : /tmp/vpp-unittest-TestL2bdArpTerm-_h44qo/stats.sock
L2BD arp term - add 5 hosts, verify arp responses OK
L2BD arp term - delete 3 hosts, verify arp responses OK
L2BD arp term - recreate BD1, readd 3 hosts, verify arp responses OK
L2BD arp term - 2 IP4 addrs per host OK
L2BD arp term - create and update 10 IP4-mac pairs OK
L2BD arp/ND term - hosts with both ip4/ip6 OK
L2BD ND term - Add and Del hosts, verify ND replies OK
L2BD ND term - Add and update IP+mac, verify ND replies OK
L2BD arp term - send garps, verify arp event reports OK
L2BD arp term - send duplicate garps, verify suppression OK
L2BD arp term - disable ip4 arp events,send garps, verify no events OK
L2BD ND term - send NS packets verify reports OK
L2BD ND term - send duplicate ns, verify suppression OK
L2BD ND term - disable ip4 arp events,send ns, verify no events OK
==============================================================================
TEST RESULTS:
Scheduled tests: 14
Executed tests: 14
Passed tests: 14
==============================================================================
Test run was successful
Change-Id: I6bb1ced11b88080ffaa845d22b0bc471c4f91683
Signed-off-by: Paul Vinciguerra <b92f79aabe4c9c18085c7347110a52af0898a0ef@vinciconsulting.com> | """
MAC Types
"""
from util import mactobinary
class VppMacAddress():
def __init__(self, addr):
self.address = addr
def encode(self):
return {
'bytes': self.bytes
}
@property
def bytes(self):
return mactobinary(self.address)
@property
def address(self):
return self.address
@address.setter
def address(self, value):
self.address = value
def __str__(self):
return self.address
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.address == other.address
elif hasattr(other, "bytes"):
# vl_api_mac_addres_t
return self.bytes == other.bytes
else:
raise TypeError("Comparing VppMacAddress:%s"
"with unknown type: %s" %
(self, other))
return False
| """
MAC Types
"""
from util import mactobinary
class VppMacAddress():
def __init__(self, addr):
self.address = addr
def encode(self):
return {
'bytes': self.bytes
}
@property
def bytes(self):
return mactobinary(self.address)
@property
def address(self):
return self.addr.address
def __str__(self):
return self.address
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.address == other.addres
elif hasattr(other, "bytes"):
# vl_api_mac_addres_t
return self.bytes == other.bytes
else:
raise Exception("Comparing VppMacAddress:%s"
"with unknown type: %s" %
(self, other))
return False
|
Use getOwner polyfill in instance initializer | /* globals requirejs */
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import ENV from '../config/environment';
import getOwner from 'ember-getowner-polyfill';
function filterBy(type) {
return Object.keys(requirejs._eak_seen).filter((key) => {
return key.indexOf(`${ENV.modulePrefix}\/${type}\/`) === 0;
});
}
export function instanceInitializer(instance) {
const service = getOwner(instance).lookup('service:intl');
filterBy('cldrs').forEach((key) => {
service.addLocaleData(require(key, null, null, true)['default']);
});
filterBy('translations').forEach((key) => {
const localeSplit = key.split('\/');
const localeName = localeSplit[localeSplit.length - 1];
service.addTranslations(localeName, require(key, null, null, true)['default']);
});
}
export default {
name: 'ember-intl',
initialize: instanceInitializer
}
| /**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import ENV from '../config/environment';
function filterBy(type) {
return Object.keys(requirejs._eak_seen).filter((key) => {
return key.indexOf(`${ENV.modulePrefix}\/${type}\/`) === 0;
});
}
export function instanceInitializer(instance) {
const container = instance.lookup ? instance : instance.container;
const service = container.lookup('service:intl');
filterBy('cldrs').forEach((key) => {
service.addLocaleData(require(key, null, null, true)['default']);
});
filterBy('translations').forEach((key) => {
const localeSplit = key.split('\/');
const localeName = localeSplit[localeSplit.length - 1];
service.addTranslations(localeName, require(key, null, null, true)['default']);
});
}
export default {
name: 'ember-intl',
initialize: instanceInitializer
}
|
Make the `cb` callback optional | 'use strict';
var aps = Array.prototype.slice;
var segue = function(cb) {
cb = cb || function() {}; // no op
var running = false;
var queue = [];
var nextArgs = [];
var next = function() {
var args = aps.call(arguments);
var err = args.shift(); // `err` is the first argument of the `this` callback
var arr;
if (err) { // exit on `err`
return cb(err);
}
if (queue.length) { // call the next function in the `queue`
arr = queue.shift();
args = args.concat(arr[1]);
arr[0].apply(next, args);
} else {
nextArgs = args; // save the arguments passed to the `this` callback
running = false;
}
};
var enqueue = function() {
var args = aps.call(arguments);
var fn = args.shift();
if (!queue.length && !running) {
running = true;
fn.apply(next, nextArgs.concat(args));
nextArgs = [];
} else {
queue.push([fn, args]);
}
return enqueue;
};
return enqueue;
};
module.exports = exports = segue;
| 'use strict';
var aps = Array.prototype.slice;
var segue = function(cb) {
var running = false;
var queue = [];
var nextArgs = [];
var next = function() {
var args = aps.call(arguments);
var err = args.shift(); // `err` is the first argument of the `this` callback
var arr;
if (err) { // exit on `err`
return cb(err);
}
if (queue.length) { // call the next function in the `queue`
arr = queue.shift();
args = args.concat(arr[1]);
arr[0].apply(next, args);
} else {
nextArgs = args; // save the arguments passed to the `this` callback
running = false;
}
};
var enqueue = function() {
var args = aps.call(arguments);
var fn = args.shift();
if (!queue.length && !running) {
running = true;
fn.apply(next, nextArgs.concat(args));
nextArgs = [];
} else {
queue.push([fn, args]);
}
return enqueue;
};
return enqueue;
};
module.exports = exports = segue;
|
Add back missing comment rule
Prettier doesn't enforce anything in regards to comments | module.exports = {
plugins: [
"filenames",
"prettier"
],
rules: {
// ERRORS
// No more bikeshedding on style; just use prettier
// https://github.com/not-an-aardvark/eslint-plugin-prettier
"prettier/prettier": ["error", { useTabs: true }],
// enforce lowercase kebab case for filenames
// we have had issues in the past with case sensitivity & module resolution
// https://github.com/selaux/eslint-plugin-filenames
"filenames/match-regex": ["error", "^[a-z\-\.]+$"],
// don't concatenate strings like a n00b
// http://eslint.org/docs/rules/prefer-template
"prefer-template": ["error"],
// put a space after the comment slashes
// http://eslint.org/docs/rules/spaced-comment
"spaced-comment": ["error", "always"],
// =======================================================================================
// WARNINGS
// don't write a whole application in one single js file (default 301 lines is too big)
// http://eslint.org/docs/rules/max-lines
"max-lines": ["warn"],
// don't make ridiculous functions that take billions upon billions of arguments
// http://eslint.org/docs/rules/max-params
"max-params": ["warn", { max: 4 }]
}
}; | module.exports = {
plugins: [
"filenames",
"prettier"
],
rules: {
// ERRORS
// No more bikeshedding on style; just use prettier
// https://github.com/not-an-aardvark/eslint-plugin-prettier
"prettier/prettier": ["error", { useTabs: true }],
// enforce lowercase kebab case for filenames
// we have had issues in the past with case sensitivity & module resolution
// https://github.com/selaux/eslint-plugin-filenames
"filenames/match-regex": ["error", "^[a-z\-\.]+$"],
// don't concatenate strings like a n00b
// http://eslint.org/docs/rules/prefer-template
"prefer-template": ["error"],
// =======================================================================================
// WARNINGS
// don't write a whole application in one single js file (default 301 lines is too big)
// http://eslint.org/docs/rules/max-lines
"max-lines": ["warn"],
// don't make ridiculous functions that take billions upon billions of arguments
// http://eslint.org/docs/rules/max-params
"max-params": ["warn", { max: 4 }]
}
}; |
Remove use of Math.truc() which isn't available in IE 11. | /*
* @license
* Copyright 2016 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.
*/
foam.CLASS({
package: 'foam.core',
name: 'Int',
extends: 'Property',
properties: [
'units',
[ 'value', 0 ],
[ 'adapt', function adaptInt(_, v) {
return typeof v === 'number' ? ( v > 0 ? Math.floor(v) : Math.ceil(v) ) :
v ? parseInt(v) :
0 ;
}
]
]
});
| /*
* @license
* Copyright 2016 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.
*/
foam.CLASS({
package: 'foam.core',
name: 'Int',
extends: 'Property',
properties: [
'units',
[ 'value', 0 ],
[ 'adapt', function adaptInt(_, v) {
return typeof v === 'number' ?
Math.trunc(v) : v ? parseInt(v) : 0 ;
}
]
]
});
|
Check for the existence of model.objects without calling it; may fix some weird buggy behaviour involving database migrations. | # Copyright (c) Ecometrica. All rights reserved.
# Distributed under the BSD license. See LICENSE for details.
from collections import namedtuple
from decorator import decorator
from functools import wraps
from django.db.models import get_apps
from piston.utils import rc
from wapiti.conf import ID_RE
_RegisteredType = namedtuple('RegisteredType', ('api', ))
_registered_types = {}
def register(name, modelapi):
"""Register a model with the API"""
global _registered_types
if modelapi.__name__ in _registered_types:
return
if not hasattr(modelapi, 'objects'):
modelapi.objects = modelapi.model.objects
_registered_types[name] = _RegisteredType(api=modelapi)
def _api_method(f, *args, **kwargs):
return f(*args, **kwargs)
def api_method(f):
"""Decorator to declare a method api-accessible"""
f.api = True
return decorator(_api_method, f)
def _is_id(id):
return ID_RE.match(id)
def _register_models():
"""Find app api submodules and register models"""
for a in get_apps():
try:
_temp = __import__('.'.join(a.__name__.split('.')[:-1] + ['api']),
globals(), locals())
except ImportError:
pass
| # Copyright (c) Ecometrica. All rights reserved.
# Distributed under the BSD license. See LICENSE for details.
from collections import namedtuple
from decorator import decorator
from functools import wraps
from django.db.models import get_apps
from piston.utils import rc
from wapiti.conf import ID_RE
_RegisteredType = namedtuple('RegisteredType', ('api', ))
_registered_types = {}
def register(name, modelapi):
"""Register a model with the API"""
global _registered_types
if modelapi.__name__ in _registered_types:
return
if not modelapi.objects:
modelapi.objects = modelapi.model.objects
_registered_types[name] = _RegisteredType(api=modelapi)
def _api_method(f, *args, **kwargs):
return f(*args, **kwargs)
def api_method(f):
"""Decorator to declare a method api-accessible"""
f.api = True
return decorator(_api_method, f)
def _is_id(id):
return ID_RE.match(id)
def _register_models():
"""Find app api submodules and register models"""
for a in get_apps():
try:
_temp = __import__('.'.join(a.__name__.split('.')[:-1] + ['api']),
globals(), locals())
except ImportError:
pass
|
Use a random server port in the Couchbase sample’s tests | package sample.data.couchbase;
import java.net.ConnectException;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.OutputCapture;
import org.springframework.core.NestedCheckedException;
import static org.assertj.core.api.Assertions.assertThat;
public class SampleCouchbaseApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testDefaultSettings() throws Exception {
try {
new SpringApplicationBuilder(SampleCouchbaseApplication.class)
.run("--server.port=0");
}
catch (RuntimeException ex) {
if (serverNotRunning(ex)) {
return;
}
}
String output = this.outputCapture.toString();
assertThat(output).contains("firstName='Alice', lastName='Smith'");
}
private boolean serverNotRunning(RuntimeException ex) {
@SuppressWarnings("serial")
NestedCheckedException nested = new NestedCheckedException("failed", ex) {
};
if (nested.contains(ConnectException.class)) {
Throwable root = nested.getRootCause();
if (root.getMessage().contains("Connection refused")) {
return true;
}
}
return false;
}
}
| package sample.data.couchbase;
import java.net.ConnectException;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.OutputCapture;
import org.springframework.core.NestedCheckedException;
import static org.assertj.core.api.Assertions.assertThat;
public class SampleCouchbaseApplicationTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
@Test
public void testDefaultSettings() throws Exception {
try {
new SpringApplicationBuilder(SampleCouchbaseApplication.class)
.run();
}
catch (RuntimeException ex) {
if (serverNotRunning(ex)) {
return;
}
}
String output = this.outputCapture.toString();
assertThat(output).contains("firstName='Alice', lastName='Smith'");
}
private boolean serverNotRunning(RuntimeException ex) {
@SuppressWarnings("serial")
NestedCheckedException nested = new NestedCheckedException("failed", ex) {
};
if (nested.contains(ConnectException.class)) {
Throwable root = nested.getRootCause();
if (root.getMessage().contains("Connection refused")) {
return true;
}
}
return false;
}
}
|
Remove unused args to ping endpoint | package client
import (
"fmt"
"github.com/keybase/cli"
"github.com/keybase/client/go/libcmdline"
"github.com/keybase/client/go/libkb"
)
type CmdPing struct{}
func (v *CmdPing) Run() error {
_, err := G.API.Post(libkb.APIArg{Endpoint: "ping"})
if err != nil {
return err
}
_, err = G.API.Get(libkb.APIArg{Endpoint: "ping"})
if err != nil {
return err
}
G.Log.Info(fmt.Sprintf("API Server at %s is up", G.Env.GetServerURI()))
return nil
}
func NewCmdPing(cl *libcmdline.CommandLine) cli.Command {
return cli.Command{
Name: "ping",
Usage: "ping the keybase API server",
Action: func(c *cli.Context) {
cl.ChooseCommand(&CmdPing{}, "ping", c)
},
}
}
func (v *CmdPing) ParseArgv(*cli.Context) error { return nil }
func (v *CmdPing) GetUsage() libkb.Usage {
return libkb.Usage{
Config: true,
API: true,
}
}
| package client
import (
"fmt"
"github.com/keybase/cli"
"github.com/keybase/client/go/libcmdline"
"github.com/keybase/client/go/libkb"
)
type CmdPing struct{}
func (v *CmdPing) Run() error {
_, err := G.API.Post(libkb.APIArg{
Endpoint: "ping",
Args: libkb.HTTPArgs{
"alice": libkb.S{Val: "hi alice"},
"bob": libkb.I{Val: 1000},
"charlie": libkb.B{Val: true},
},
})
if err != nil {
return err
}
_, err = G.API.Get(libkb.APIArg{Endpoint: "ping"})
if err != nil {
return err
}
G.Log.Info(fmt.Sprintf("API Server at %s is up", G.Env.GetServerURI()))
return nil
}
func NewCmdPing(cl *libcmdline.CommandLine) cli.Command {
return cli.Command{
Name: "ping",
Usage: "ping the keybase API server",
Action: func(c *cli.Context) {
cl.ChooseCommand(&CmdPing{}, "ping", c)
},
}
}
func (v *CmdPing) ParseArgv(*cli.Context) error { return nil }
func (v *CmdPing) GetUsage() libkb.Usage {
return libkb.Usage{
Config: true,
API: true,
}
}
|
Add throughput metrics to benchmark. | package raft
import (
"bytes"
"encoding/json"
"testing"
)
func BenchmarkAppendEntriesEncoding(b *testing.B) {
req, tmp := createTestAppendEntriesRequest(2000)
for i := 0; i < b.N; i++ {
var buf bytes.Buffer
json.NewEncoder(&buf).Encode(req)
}
b.SetBytes(int64(len(tmp)))
}
func BenchmarkAppendEntriesDecoding(b *testing.B) {
req, buf := createTestAppendEntriesRequest(2000)
for i := 0; i < b.N; i++ {
json.NewDecoder(bytes.NewReader(buf)).Decode(req)
}
b.SetBytes(int64(len(buf)))
}
func createTestAppendEntriesRequest(entryCount int) (*AppendEntriesRequest, []byte) {
entries := make([]*LogEntry, 0)
for i := 0; i < entryCount; i++ {
entries = append(entries, newLogEntry(nil, 1, 2, &joinCommand{Name: "localhost:1000"}))
}
req := newAppendEntriesRequest(1, "leader", 1, 1, entries, 1)
buf, _ := json.Marshal(req)
return req, buf
}
| package raft
import (
"bytes"
"encoding/json"
"testing"
)
func BenchmarkAppendEntriesEncoding(b *testing.B) {
req, _ := createTestAppendEntriesRequest(2000)
for i := 0; i < b.N; i++ {
var buf bytes.Buffer
json.NewEncoder(&buf).Encode(req)
}
}
func BenchmarkAppendEntriesDecoding(b *testing.B) {
req, buf := createTestAppendEntriesRequest(2000)
for i := 0; i < b.N; i++ {
json.NewDecoder(bytes.NewReader(buf)).Decode(req)
}
}
func createTestAppendEntriesRequest(entryCount int) (*AppendEntriesRequest, []byte) {
entries := make([]*LogEntry, 0)
for i := 0; i < entryCount; i++ {
entries = append(entries, newLogEntry(nil, 1, 2, &joinCommand{Name: "localhost:1000"}))
}
req := newAppendEntriesRequest(1, "leader", 1, 1, entries, 1)
buf, _ := json.Marshal(req)
return req, buf
}
|
Fix Attempting to Display Blank Errors
Fix attempting to display blank errors in single pages
- This is particularly apparent with the newer `Controller::$error`
property.
Former-commit-id: 19cb81a07b9cd71433f633c539a2d2759121b282 | <?php
defined('C5_EXECUTE') or die(_("Access Denied."));
if (isset($error) && $error != '') {
if ($error instanceof Exception) {
$_error[] = $error->getMessage();
} else if ($error instanceof ValidationErrorHelper) {
$_error = $error->getList();
} else if (is_array($error)) {
$_error = $error;
} else if (is_string($error)) {
$_error[] = $error;
}
?>
<? if($_error) { ?>
<? if ($format == 'block') { ?>
<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">×</button>
<?php foreach($_error as $e): ?>
<?php echo $e?><br/>
<?php endforeach; ?>
</div>
<? } else { ?>
<ul class="ccm-error">
<?php foreach($_error as $e): ?>
<li><?php echo $e?></li>
<?php endforeach; ?>
</ul>
<? } ?>
<? } ?>
<?php } ?>
| <?php
defined('C5_EXECUTE') or die(_("Access Denied."));
if (isset($error) && $error != '') {
if ($error instanceof Exception) {
$_error[] = $error->getMessage();
} else if ($error instanceof ValidationErrorHelper) {
$_error = $error->getList();
} else if (is_array($error)) {
$_error = $error;
} else if (is_string($error)) {
$_error[] = $error;
}
?>
<? if ($format == 'block') { ?>
<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">×</button>
<?php foreach($_error as $e): ?>
<?php echo $e?><br/>
<?php endforeach; ?>
</div>
<? } else { ?>
<ul class="ccm-error">
<?php foreach($_error as $e): ?>
<li><?php echo $e?></li>
<?php endforeach; ?>
</ul>
<? } ?>
<?php } ?>
|
Add sections to connection request | <?php
namespace Transport\Entity\Schedule;
use Transport\Entity;
/**
* Connection
*/
class Connection
{
public $date;
/**
* @var Transport\Entity\Schedule\Stop
*/
public $from;
/**
* @var Transport\Entity\Schedule\Stop
*/
public $to;
/**
* @var array of Transport\Entity\Schedule\Stop 's
*/
public $sections;
static public function createFromXml(\SimpleXMLElement $xml, Connection $obj = null)
{
if (!$obj) {
$obj = new Connection();
}
$obj->date = date('Y-m-d', strtotime((string) $xml->Overview->Date));
$obj->from = Entity\Schedule\Stop::createFromXml($xml->Overview->Departure->BasicStop);
$obj->to = Entity\Schedule\Stop::createFromXml($xml->Overview->Arrival->BasicStop);
foreach ($xml->ConSectionList->ConSection AS $section) {
$obj->sections[] = array(
'departure' => Entity\Schedule\Stop::createFromXml($section->Departure->BasicStop),
'arrival' => Entity\Schedule\Stop::createFromXml($section->Arrival->BasicStop)
);
}
return $obj;
}
}
| <?php
namespace Transport\Entity\Schedule;
use Transport\Entity;
/**
* Connection
*/
class Connection
{
public $date;
/**
* @var Transport\Entity\Schedule\Stop
*/
public $from;
/**
* @var Transport\Entity\Schedule\Stop
*/
public $to;
static public function createFromXml(\SimpleXMLElement $xml, Connection $obj = null)
{
if (!$obj) {
$obj = new Connection();
}
$obj->date = date('Y-m-d', strtotime((string) $xml->Overview->Date));
$obj->from = Entity\Schedule\Stop::createFromXml($xml->Overview->Departure->BasicStop);
$obj->to = Entity\Schedule\Stop::createFromXml($xml->Overview->Arrival->BasicStop);
return $obj;
}
}
|
Update dependency declarations to line up = | 'use strict';
var assert = require('assert')
, fs = require('fs')
, path = require('path')
, handlebars = require('handlebars')
, cssInjector = require('../wrappers/cssInjector')
var assetsPath = __dirname + '/../config/assets'
/**
* Class to handle css and html template for a layers popup generation
* Css is injected into the dom and a function is returned via 'present'
* that can be used by the map on a per geosjon feature basis
*/
class PopupPresenter {
/**
* Creates a template function from config and injects given layer css
* file into the dom
*/
constructor(config) {
assert.equal(typeof (config), 'object', '\'config\' arg must be an object')
var templatePath = path.join(assetsPath, 'templates', config.template)
this.template = handlebars.compile(fs.readFileSync(templatePath, 'utf-8'))
var cssPath = path.join(assetsPath, 'css', config.css)
cssInjector(fs.readFileSync(cssPath, 'utf-8'))
}
/**
* Renders properties into a template string using template function
* created in the constructor
* @param {object} properties
* @return {string}
*/
present(properties) {
assert.equal(typeof (properties), 'object', '\'properties\' arg must be an object')
return this.template(properties)
}
}
module.exports = (config) => new PopupPresenter(config)
| 'use strict';
var assert = require('assert')
, fs = require('fs')
, path = require('path')
, handlebars = require('handlebars')
, cssInjector = require('../wrappers/cssInjector')
var assetsPath = __dirname + '/../config/assets'
/**
* Class to handle css and html template for a layers popup generation
* Css is injected into the dom and a function is returned via 'present'
* that can be used by the map on a per geosjon feature basis
*/
class PopupPresenter {
/**
* Creates a template function from config and injects given layer css
* file into the dom
*/
constructor(config) {
assert.equal(typeof (config), 'object', '\'config\' arg must be an object')
var templatePath = path.join(assetsPath, 'templates', config.template)
this.template = handlebars.compile(fs.readFileSync(templatePath, 'utf-8'))
var cssPath = path.join(assetsPath, 'css', config.css)
cssInjector(fs.readFileSync(cssPath, 'utf-8'))
}
/**
* Renders properties into a template string using template function
* created in the constructor
* @param {object} properties
* @return {string}
*/
present(properties) {
assert.equal(typeof (properties), 'object', '\'properties\' arg must be an object')
return this.template(properties)
}
}
module.exports = (config) => new PopupPresenter(config)
|
Remove whitespace between use statements | <?php
namespace Jmikola\ImagineBundle\Imagine\Filter;
use Imagine\Exception\InvalidArgumentException;
use Imagine\Filter\FilterInterface;
use Imagine\Image\ImageInterface;
use Imagine\Image\BoxInterface;
class RelativeResize implements FilterInterface
{
private $method;
private $parameter;
/**
* Constructs a RelativeResize filter with the given method and argument.
*
* @param string $method BoxInterface method
* @param mixed $parameter Parameter for BoxInterface method
*/
public function __construct($method, $parameter)
{
if (!in_array($method, array('heighten', 'increase', 'scale', 'widen'))) {
throw new InvalidArgumentException(sprintf('Unsupported method: ', $method));
}
$this->method = $method;
$this->parameter = $parameter;
}
/**
* @see Imagine\Filter\FilterInterface::apply()
*/
public function apply(ImageInterface $image)
{
return $image->resize(call_user_func(array($image->getSize(), $this->method), $this->parameter));
}
}
| <?php
namespace Jmikola\ImagineBundle\Imagine\Filter;
use Imagine\Exception\InvalidArgumentException;
use Imagine\Filter\FilterInterface;
use Imagine\Image\ImageInterface;
use Imagine\Image\BoxInterface;
class RelativeResize implements FilterInterface
{
private $method;
private $parameter;
/**
* Constructs a RelativeResize filter with the given method and argument.
*
* @param string $method BoxInterface method
* @param mixed $parameter Parameter for BoxInterface method
*/
public function __construct($method, $parameter)
{
if (!in_array($method, array('heighten', 'increase', 'scale', 'widen'))) {
throw new InvalidArgumentException(sprintf('Unsupported method: ', $method));
}
$this->method = $method;
$this->parameter = $parameter;
}
/**
* @see Imagine\Filter\FilterInterface::apply()
*/
public function apply(ImageInterface $image)
{
return $image->resize(call_user_func(array($image->getSize(), $this->method), $this->parameter));
}
}
|
Add relevant Customer section changes to main.router.js | 'use strict';
angular.module('StudentApp').config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.when('/studentPage', {
templateUrl: 'views/student/student.list.html',
controller: 'StudentController'
}).when('/comments/:id', {
templateUrl: 'views/comment/comments.list.html',
controller: 'CommentsController'
}).when('/stockPage', {
templateUrl: 'views/Stock/StockManagment.html',
controller: 'StockController'
}).when('/orderPage', {
templateUrl: 'views/Stock/OrderManagment.html',
controller: 'OrderController'
}).when('/customerPage', {
templateUrl: 'views/Customer/Customer.html',
controller: 'CustomerController'
}).otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]); | 'use strict';
angular.module('StudentApp').config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider.when('/studentPage', {
templateUrl: 'views/student/student.list.html',
controller: 'StudentController'
}).when('/comments/:id', {
templateUrl: 'views/comment/comments.list.html',
controller: 'CommentsController'
}).when('/stockPage', {
templateUrl: 'views/Stock/StockManagment.html',
controller: 'StockController'
}).when('/orderPage', {
templateUrl: 'views/Stock/OrderManagment.html',
controller: 'OrderController'
}).otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]); |
Configure composer - working edition | <?php
require_once __DIR__ . '/deployer/recipe/configure.php';
require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php';
serverList(__DIR__ . '/stage/servers.yml');
set('repository', '{{repository}}');
set('keep_releases', 2);
set('shared_files', [
'config/db.php'
]);
task('deploy:build_assets', function () {
runLocally('gulp build');
upload(__DIR__ . '/web/css', '{{release_path}}/web/css');
upload(__DIR__ . '/web/js', '{{release_path}}/web/js');
upload(__DIR__ . '/web/fonts', '{{release_path}}/web/fonts');
})->desc('Build assets');
task('deploy:configure_composer', function () {
$stage = env('app.stage');
if($stage == 'dev') {
env('composer_options', 'install --verbose --no-progress --no-interaction');
}
})->desc('Configure composer');
after('deploy:shared', 'deploy:configure');
before('deploy:vendors', 'deploy:configure_composer');
after('deploy:run_migrations', 'deploy:build_assets');
| <?php
require_once __DIR__ . '/deployer/recipe/configure.php';
require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php';
serverList(__DIR__ . '/stage/servers.yml');
set('repository', '{{repository}}');
set('keep_releases', 2);
set('shared_files', [
'config/db.php'
]);
task('deploy:build_assets', function () {
runLocally('gulp build');
upload(__DIR__ . '/web/css', '{{release_path}}/web/css');
upload(__DIR__ . '/web/js', '{{release_path}}/web/js');
upload(__DIR__ . '/web/fonts', '{{release_path}}/web/fonts');
})->desc('Build assets');
task('deploy:configure_composer', function () {
$stage = env('stage');
if($stage == 'local') {
env('composer_options', 'install --verbose --no-progress --no-interaction');
}
})->desc('Configure composer');
after('deploy:shared', 'deploy:configure');
before('deploy:vendors', 'deploy:configure_composer');
after('deploy:run_migrations', 'deploy:build_assets');
|
Mark article read as it comes into view, rather than when it leaves
The last article in a feed was difficult to mark as read | package net.elprespufferfish.rssreader;
import android.support.v4.view.ViewPager;
/**
* Handles marking articles as read
*/
public class ArticleReadListener implements ViewPager.OnPageChangeListener {
private final ArticlePagerAdapter articlePagerAdapter;
public ArticleReadListener(ArticlePagerAdapter articlePagerAdapter) {
this.articlePagerAdapter = articlePagerAdapter;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// unused
}
@Override
public void onPageSelected(int position) {
ArticleFragment articleFragment = (ArticleFragment) articlePagerAdapter.getItem(position);
Article article = articleFragment.getArguments().getParcelable(ArticleFragment.ARTICLE_KEY);
Feeds.getInstance().markArticleRead(article);
}
@Override
public void onPageScrollStateChanged(int state) {
// unused
}
}
| package net.elprespufferfish.rssreader;
import android.support.v4.view.ViewPager;
/**
* Handles marking articles as read
*/
public class ArticleReadListener implements ViewPager.OnPageChangeListener {
private final ArticlePagerAdapter articlePagerAdapter;
private int lastPosition = 0;
public ArticleReadListener(ArticlePagerAdapter articlePagerAdapter) {
this.articlePagerAdapter = articlePagerAdapter;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// unused
}
@Override
public void onPageSelected(int position) {
ArticleFragment articleFragment = (ArticleFragment) articlePagerAdapter.getItem(lastPosition);
Article article = articleFragment.getArguments().getParcelable(ArticleFragment.ARTICLE_KEY);
Feeds.getInstance().markArticleRead(article);
lastPosition = position;
}
@Override
public void onPageScrollStateChanged(int state) {
// unused
}
}
|
Fix Activity CSV field test | import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='1', learning_obj='1,2,3',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
| import datetime
from django.test import TestCase
from journal.models import Activity, Entry
from journal.serializers import ActivitySerializer
class ActivityTestCase(TestCase):
"""Sanity checks for activity"""
def setUp(self):
cat_e = Entry.objects.create(entry='I like walking the cat')
Activity.objects.create(name='Walking the cat',
description='Walking the cat around the block',
activity_type='CA', learning_obj='123',
entries=cat_e,
start_date=datetime.date.today)
def test_activity_serializer(self):
cat_activity = Activity.objects.get(name='Walking the cat')
self.assertEqual(cat_activity.name, 'Walking the cat')
cat_serializer = ActivitySerializer(cat_activity)
self.assertEqual(cat_serializer.data['description'],
'Walking the cat around the block')
|
Add missing dependency on Blinker | from setuptools import setup, find_packages
setup(
name='Flask-DebugToolbar',
version='0.6dev',
url='http://github.com/mvantellingen/flask-debugtoolbar',
license='BSD',
author='Michael van Tellingen',
author_email='michaelvantellingen@gmail.com',
description='A port of the Django debug toolbar to Flask',
long_description=__doc__,
zip_safe=False,
platforms='any',
include_package_data=True,
packages=['flask_debugtoolbar',
'flask_debugtoolbar.panels'
],
install_requires=[
'setuptools',
'simplejson',
'Flask>=0.8',
'Blinker',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| from setuptools import setup, find_packages
setup(
name='Flask-DebugToolbar',
version='0.6dev',
url='http://github.com/mvantellingen/flask-debugtoolbar',
license='BSD',
author='Michael van Tellingen',
author_email='michaelvantellingen@gmail.com',
description='A port of the Django debug toolbar to Flask',
long_description=__doc__,
zip_safe=False,
platforms='any',
include_package_data=True,
packages=['flask_debugtoolbar',
'flask_debugtoolbar.panels'
],
install_requires=[
'setuptools',
'simplejson',
'Flask>=0.8',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
Add lazy conversation context parameter | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.servlet.api;
/**
* Names of init parameters that can be used in web.xml to configure Weld's Servlet integration.
*
* @author Jozef Hartinger
*
*/
public interface InitParameters {
String CONTEXT_IGNORE_FORWARD = "org.jboss.weld.context.ignore.forward";
String CONTEXT_IGNORE_INCLUDE = "org.jboss.weld.context.ignore.include";
String CONTEXT_MAPPING = "org.jboss.weld.context.mapping";
/**
* Enable / disable lazy initialization of the conversation context.
*/
String CONVERSATION_CONTEXT_LAZY_PARAM = "org.jboss.weld.context.conversation.lazy";
}
| /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.servlet.api;
/**
* Names of init parameters that can be used in web.xml to configure Weld's Servlet integration.
*
* @author Jozef Hartinger
*
*/
public interface InitParameters {
String CONTEXT_IGNORE_FORWARD = "org.jboss.weld.context.ignore.forward";
String CONTEXT_IGNORE_INCLUDE = "org.jboss.weld.context.ignore.include";
String CONTEXT_MAPPING = "org.jboss.weld.context.mapping";
}
|
Increase Timeout to 30 Seconds | <?php
namespace Screeenly\Services;
use Screeenly\Entities\Url;
use Screeenly\Entities\Screenshot;
use Spatie\Browsershot\Browsershot;
use Screeenly\Contracts\CanCaptureScreenshot;
class ChromeBrowser extends Browser implements CanCaptureScreenshot
{
public function capture(Url $url, $storageUrl)
{
$browser = Browsershot::url($url->getUrl())
->ignoreHttpsErrors()
->windowSize($this->width, is_null($this->height) ? 768 : $this->height)
->timeout(30)
->setDelay($this->delay * 100)
->userAgent('screeenly-bot 2.0');
if (is_null($this->height)) {
$browser->fullPage();
}
$browser->save($storageUrl);
return new Screenshot($storageUrl);
}
}
| <?php
namespace Screeenly\Services;
use Screeenly\Entities\Url;
use Screeenly\Entities\Screenshot;
use Spatie\Browsershot\Browsershot;
use Screeenly\Contracts\CanCaptureScreenshot;
class ChromeBrowser extends Browser implements CanCaptureScreenshot
{
public function capture(Url $url, $storageUrl)
{
$browser = Browsershot::url($url->getUrl())
->ignoreHttpsErrors()
->windowSize($this->width, is_null($this->height) ? 768 : $this->height)
->timeout(10)
->setDelay($this->delay * 100)
->userAgent('screeenly-bot 2.0');
if (is_null($this->height)) {
$browser->fullPage();
}
$browser->save($storageUrl);
return new Screenshot($storageUrl);
}
}
|
Fix a typo in the project URL
Signed-off-by: Kalman Olah <aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d@kalmanolah.net> | #!/usr/bin/env python3
"""Setup module."""
from setuptools import setup, find_packages
import os
def read(fname):
"""Read and return the contents of a file."""
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='macmond',
version='0.0.1',
description='MACMond - MAC address Monitoring daemon.',
long_description=read('README'),
author='Kalman Olah',
author_email='hello@kalmanolah.net',
url='https://github.com/kalmanolah/macmond',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: System Administrators',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
],
packages=find_packages(),
entry_points={
'console_scripts': [
'macmond = macmond:macmond',
],
},
install_requires=[
'scapy-python3',
'python-daemon',
'netifaces',
'click'
],
dependency_links=[
],
)
| #!/usr/bin/env python3
"""Setup module."""
from setuptools import setup, find_packages
import os
def read(fname):
"""Read and return the contents of a file."""
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='macmond',
version='0.0.1',
description='MACMond - MAC address Monitoring daemon.',
long_description=read('README'),
author='Kalman Olah',
author_email='hello@kalmanolah.net',
url='https://github.io/kalmanolah/macmond',
license='MIT',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: System Administrators',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
],
packages=find_packages(),
entry_points={
'console_scripts': [
'macmond = macmond:macmond',
],
},
install_requires=[
'scapy-python3',
'python-daemon',
'netifaces',
'click'
],
dependency_links=[
],
)
|
Remove function that is no longer needed | <?php
/**
* Skeleton subclass for representing a row from the 'edge_server' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package Core
* @subpackage model
*/
class EdgeServer extends BaseEdgeServer {
const CUSTOM_DATA_DELIVERY_IDS = 'delivery_profile_ids';
/**
* Initializes internal state of EdgeServer object.
* @see parent::__construct()
*/
public function __construct()
{
// Make sure that parent constructor is always invoked, since that
// is where any default values for this object are set.
parent::__construct();
}
/* Delivery Settings */
public function setDeliveryProfileIds($params)
{
$this->putInCustomData(self::CUSTOM_DATA_DELIVERY_IDS, $params);
}
public function getDeliveryProfileIds()
{
return $this->getFromCustomData(self::CUSTOM_DATA_DELIVERY_IDS, null, array());
}
} // EdgeServer
| <?php
/**
* Skeleton subclass for representing a row from the 'edge_server' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package Core
* @subpackage model
*/
class EdgeServer extends BaseEdgeServer {
const CUSTOM_DATA_DELIVERY_IDS = 'delivery_profile_ids';
const CUSTOM_DATA_PLAYBACK_HOST_NAME = 'playback_host_name';
/**
* Initializes internal state of EdgeServer object.
* @see parent::__construct()
*/
public function __construct()
{
// Make sure that parent constructor is always invoked, since that
// is where any default values for this object are set.
parent::__construct();
}
/* Delivery Settings */
public function setDeliveryProfileIds($params)
{
$this->putInCustomData(self::CUSTOM_DATA_DELIVERY_IDS, $params);
}
public function getDeliveryProfileIds()
{
return $this->getFromCustomData(self::CUSTOM_DATA_DELIVERY_IDS, null, array());
}
public function setPlaybackHostName($playbackUrl)
{
$this->putInCustomData(self::CUSTOM_DATA_PLAYBACK_HOST_NAME, $playbackUrl);
}
public function getPlaybackHostName($playbackUrl)
{
return $this->getFromCustomData(self::CUSTOM_DATA_PLAYBACK_HOST_NAME, null, $this->getHostName());
}
} // EdgeServer
|
Fix a bug in the quadrules. | # -*- coding: utf-8 -*-
import re
from pyfr.quadrules.base import BaseQuadRule, BaseTabulatedQuadRule
from pyfr.quadrules.line import BaseLineQuadRule
from pyfr.util import subclass_map
def get_quadrule(basecls, rule, npts):
# See if rule looks like the name of a scheme
if re.match(r'[a-zA-Z0-9\-+_]+$', rule):
rule_map = subclass_map(basecls, 'name')
return rule_map[rule](npts)
# Otherwise see if it looks like a tabulation
elif 'PTS' in rule.upper():
# Create a suitable subclass
rulecls = type(basecls.eletype, (BaseTabulatedQuadRule, basecls), {})
# Instantiate and validate
r = rulecls(rule)
if len(r.points) != npts:
raise ValueError('Invalid number of points for quad rule')
return r
# Invalid
else:
raise ValueError('Invalid quadrature rule')
| # -*- coding: utf-8 -*-
import re
from pyfr.quadrules.base import BaseQuadRule, BaseTabulatedQuadRule
from pyfr.quadrules.line import BaseLineQuadRule
from pyfr.quadrules.tri import BaseTriQuadRule
from pyfr.util import subclass_map
def get_quadrule(basecls, rule, npts):
# See if rule looks like the name of a scheme
if re.match(r'[a-zA-Z0-9\-+_]+$', rule):
rule_map = subclass_map(basecls, 'name')
return rule_map[rule](npts)
# Otherwise see if it looks like a tabulation
elif 'PTS' in rule.upper():
# Create a suitable subclass
rulecls = type(basecls.eletype, (BaseTabulatedQuadRule, basecls), {})
# Instantiate and validate
r = rulecls(rule)
if len(r.points) != npts:
raise ValueError('Invalid number of points for quad rule')
return r
# Invalid
else:
raise ValueError('Invalid quadrature rule')
|
Use supervisor name from config | var console = require('better-console');
var bot = require('./bot');
var async = require('async');
console.info("Loading configuration...");
require('./config').init(function(config) {
console.info("Loading plugins...");
var plugins = require('./plugins').init(config.get("plugins"));
var supervisor = new bot(config, config.get("bot.name"), 3);
supervisor.send_channel_message("testing one", function() {
supervisor.send_channel_message("testing two", function() {
supervisor.change_username("AlsoDobby", function() {
supervisor.send_channel_message("testing THREE", function() {
console.log("done");
})
})
})
})
}) | var console = require('better-console');
var bot = require('./bot');
var async = require('async');
console.info("Loading configuration...");
require('./config').init(function(config) {
console.info("Loading plugins...");
var plugins = require('./plugins').init(config.get("plugins"));
var supervisor = new bot(config, "Dobby", 3);
supervisor.send_channel_message("testing one", function() {
supervisor.send_channel_message("testing two", function() {
supervisor.change_username("AlsoDobby", function() {
supervisor.send_channel_message("testing THREE", function() {
console.log("done");
})
})
})
})
}) |
Set msvs_version to 2019 when rebuilding
Change-type: patch | 'use strict'
const cp = require('child_process');
const rimraf = require('rimraf');
const process = require('process');
// Rebuild native modules for ia32 and run webpack again for the ia32 part of windows packages
exports.default = function(context) {
if (['windows', 'mac'].includes(context.platform.name)) {
const run = context.platform.name === 'windows' ? 'sh' : 'node';
cp.execFileSync(
run,
['node_modules/.bin/electron-rebuild', '--types', 'dev', '--arch', context.arch],
{
env: {
...process.env,
npm_config_msvs_version: '2019',
},
},
);
rimraf.sync('generated');
cp.execFileSync(
run,
['node_modules/.bin/webpack'],
{
env: {
...process.env,
npm_config_target_arch: context.arch,
},
},
);
}
}
| 'use strict'
const cp = require('child_process');
const rimraf = require('rimraf');
const process = require('process');
// Rebuild native modules for ia32 and run webpack again for the ia32 part of windows packages
exports.default = function(context) {
if (['windows', 'mac'].includes(context.platform.name)) {
const run = context.platform.name === 'windows' ? 'sh' : 'node';
cp.execFileSync(
run,
['node_modules/.bin/electron-rebuild', '--types', 'dev', '--arch', context.arch],
);
rimraf.sync('generated');
cp.execFileSync(
run,
['node_modules/.bin/webpack'],
{
env: {
...process.env,
npm_config_target_arch: context.arch,
},
},
);
}
}
|
Send an id in all API request | function makeRequest(authToken, path, data) {
const d = $.extend({}, { format: 'json', auth_token: authToken, id: 'pinboard-plusplus' }, data);
const u = `https://api.pinboard.in/v1/${path}`;
console.log('%cmakeRequest url: %s $data: %o', 'background: blue; color: white', u, d);
return new Promise((resolve, reject) => {
$.ajax({
url: u,
method: 'GET',
data: d,
timeout: 3000,
}).done((response) => {
console.log('response: %o', response);
try {
resolve(JSON.parse(response));
} catch (e) {
console.error(e);
reject();
}
}).fail((_, textStatus, error) => {
console.error('textStatus: %s error: %s', textStatus, error);
reject();
});
});
}
const Api = {};
Api.getLastUpdated = (authToken) => makeRequest(authToken, 'posts/update');
Api.addBookmark = (authToken, data) => makeRequest(authToken, 'posts/add', data);
Api.deleteBookmark = (authToken, url) => makeRequest(authToken, 'posts/delete', { url });
Api.getBookmark = (authToken, url) => makeRequest(authToken, 'posts/get', { url });
Api.getTags = (authToken) => makeRequest(authToken, 'tags/get');
export default Api;
| function makeRequest(authToken, path, data) {
const d = $.extend({}, { format: 'json', auth_token: authToken }, data);
const u = `https://api.pinboard.in/v1/${path}`;
console.log('%cmakeRequest url: %s $data: %o', 'background: blue; color: white', u, d);
return new Promise((resolve, reject) => {
$.ajax({
url: u,
method: 'GET',
data: d,
timeout: 3000,
}).done((response) => {
console.log('response: %o', response);
try {
resolve(JSON.parse(response));
} catch (e) {
console.error(e);
reject();
}
}).fail((_, textStatus, error) => {
console.error('textStatus: %s error: %s', textStatus, error);
reject();
});
});
}
const Api = {};
Api.getLastUpdated = (authToken) => makeRequest(authToken, 'posts/update');
Api.addBookmark = (authToken, data) => makeRequest(authToken, 'posts/add', data);
Api.deleteBookmark = (authToken, url) => makeRequest(authToken, 'posts/delete', { url });
Api.getBookmark = (authToken, url) => makeRequest(authToken, 'posts/get', { url });
Api.getTags = (authToken) => makeRequest(authToken, 'tags/get');
export default Api;
|
build(lint): Drop Gulp ES Lint for now. | 'use strict';
var gulp = require('gulp'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
size = require('gulp-size'),
jasmine = require('gulp-jasmine-phantom');
var source = './src/nanofeed.js';
var dest = 'nanofeed.min.js';
gulp.task('test', function () {
return gulp.src('spec/*.js')
.pipe(jasmine({
integration: true,
specHtml: './spec/specRunner.html'
}));
});
gulp.task('build', ['test'], function () {
return gulp.src(source)
.pipe(gulp.dest('./dist'))
.pipe(rename(dest))
.pipe(uglify())
.pipe(size())
.pipe(gulp.dest('./dist'));
});
gulp.task('default', ['build']);
| 'use strict';
var gulp = require('gulp'),
eslint = require('gulp-eslint'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
size = require('gulp-size'),
jasmine = require('gulp-jasmine-phantom');
var source = './src/nanofeed.js';
var dest = 'nanofeed.min.js';
gulp.task('test', function () {
return gulp.src('spec/*.js')
.pipe(jasmine({
integration: true,
specHtml: './spec/specRunner.html'
}));
});
gulp.task('lint', function () {
return gulp.src(source)
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError())
.pipe(eslint.results(function (results) {
console.log('Total Files: ' + results.length);
console.log('Total Warnings: ' + results.warningCount);
console.log('Total Errors: ' + results.errorCount);
}));
});
gulp.task('build', ['test', 'lint'], function () {
return gulp.src(source)
.pipe(gulp.dest('./dist'))
.pipe(rename(dest))
.pipe(uglify())
.pipe(size())
.pipe(gulp.dest('./dist'));
});
gulp.task('default', ['build']);
|
Clean up and fix grammar. | /*
* Copyright 2015 the Mimu Authors (Dan Bornstein et alia).
* Licensed AS IS and WITHOUT WARRANTY under the Apache License,
* Version 2.0. Details: <http://www.apache.org/licenses/LICENSE-2.0>
*/
"use strict";
// Utilities for interacting with styles. Instances are constructed with
// a node from which to get the "original" CSS style. From there, you can
// modify properties of the instance and then extract the modified properties,
// including computed properties.
class StyleUtil {
// Clones the computed style of the given node. The result can be modified
// freely without affecting the original.
static cloneComputedStyle(orig) {
// We make a fresh element, apply the original's style to it by
// using the text representation (which seems to be the simplest way
// to achieve that), and then return the style object.
var doc = orig.ownerDocument;
var node = doc.createElement("span");
node.style.cssText = doc.defaultView.getComputedStyle(orig).cssText;
return node.style;
}
}
| /*
* Copyright 2015 the Mimu Authors (Dan Bornstein et alia).
* Licensed AS IS and WITHOUT WARRANTY under the Apache License,
* Version 2.0. Details: <http://www.apache.org/licenses/LICENSE-2.0>
*/
"use strict";
// Utilities for interacting with styles. Instances are constructed with
// a node from which to get the "original" CSS style. From there, you can
// modify properties of the
// instance and then extract the modified properties, included computed
// properties.
class StyleUtil {
// Clones the computed style of the given node. The result can be modified
// freely without affecting the original.
static cloneComputedStyle(orig) {
// We make a fresh element, apply the original's style to it by
// using the text representation (which seems to be the simplest way
// to achieve that), and then return the style object.
var doc = orig.ownerDocument;
var node = doc.createElement("span");
node.style.cssText = doc.defaultView.getComputedStyle(orig).cssText;
return node.style;
}
}
|
Set up console email backend in debug mode | from .default import * # NOQA
#
# Django Development
# ..........................
DEBUG = True
TEMPLATE_DEBUG = True
SOUTH_TESTS_MIGRATE = False # Tested at settings.tests
#
# Developper Toolbar
# ..........................
INSTALLED_APPS = (
# 'debug_toolbar',
'django_extensions',
) + INSTALLED_APPS
#
# Use some default tiles
# ..........................
LEAFLET_CONFIG['TILES'] = [
(gettext_noop('Scan'), 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', '(c) OpenStreetMap Contributors'),
(gettext_noop('Ortho'), 'http://{s}.tiles.mapbox.com/v3/openstreetmap.map-4wvf9l0l/{z}/{x}/{y}.jpg', '(c) MapBox'),
]
LEAFLET_CONFIG['OVERLAYS'] = [
(gettext_noop('Coeur de parc'), 'http://{s}.tilestream.makina-corpus.net/v2/coeur-ecrins/{z}/{x}/{y}.png', 'Ecrins'),
]
LEAFLET_CONFIG['SRID'] = 3857
LOGGING['loggers']['geotrek']['level'] = 'DEBUG'
LOGGING['loggers']['']['level'] = 'DEBUG'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
| from .default import * # NOQA
#
# Django Development
# ..........................
DEBUG = True
TEMPLATE_DEBUG = True
SOUTH_TESTS_MIGRATE = False # Tested at settings.tests
#
# Developper Toolbar
# ..........................
INSTALLED_APPS = (
# 'debug_toolbar',
'django_extensions',
) + INSTALLED_APPS
#
# Use some default tiles
# ..........................
LEAFLET_CONFIG['TILES'] = [
(gettext_noop('Scan'), 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', '(c) OpenStreetMap Contributors'),
(gettext_noop('Ortho'), 'http://{s}.tiles.mapbox.com/v3/openstreetmap.map-4wvf9l0l/{z}/{x}/{y}.jpg', '(c) MapBox'),
]
LEAFLET_CONFIG['OVERLAYS'] = [
(gettext_noop('Coeur de parc'), 'http://{s}.tilestream.makina-corpus.net/v2/coeur-ecrins/{z}/{x}/{y}.png', 'Ecrins'),
]
LEAFLET_CONFIG['SRID'] = 3857
LOGGING['loggers']['geotrek']['level'] = 'DEBUG'
LOGGING['loggers']['']['level'] = 'DEBUG'
|
Edit code to fix bugs | import passport from 'passport';
import passportLocal from 'passport-local';
import bcrypt from 'bcrypt';
import user from '../models';
import helpers from '../helpers';
const LocalStrategy = passportLocal.Strategy;
passport.serializeUser((sessionUser, done) => {
done(null, sessionUser.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, sessionUser) => done(err, sessionUser));
});
passport.use(new LocalStrategy({ passReqToCallback: true }, (req, username, password, done) => {
user.User.findOne({
where: {
username
}
}).then((users) => {
if (!users) {
return done(null, false, { message: 'Incorrect username' });
}
// Compare database salt to the hash of incoming password
const reqPasswordHash = bcrypt.hashSync(req.body.password, users.salt);
if (users.password === reqPasswordHash) {
return done(null, users);
}
return done(null, false, { message: ' Incorrect password.' });
}).catch(err => done(err));
}
));
module.exports = passport;
| import passport from 'passport';
import passportLocal from 'passport-local';
import bcrypt from 'bcrypt';
import user from '../models';
import helpers from '../helpers';
const LocalStrategy = passportLocal.Strategy;
passport.serializeUser((sessionUser, done) => {
done(null, sessionUser.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, sessionUser) => done(err, sessionUser));
});
passport.use(new LocalStrategy({ passReqToCallback: true }, (req, username, password, done) => {
user.User.findOne({
where: {
username
}
}).then((users) => {
if (!users) {
return done(null, false, { message: 'Incorrect username' });
}
// Compare database salt to the hash of incoming password
const reqPasswordHash = bcrypt.hashSync(req.body.password, users.salt);
console.log('The request password hash', reqPasswordHash);
console.log('The database password is' , users.password);
if (users.password === reqPasswordHash) {
return done(null, users);
}
return done(null, false, { message: ' Incorrect password.' });
}).catch(err => done(err));
}
));
module.exports = passport;
|
Update docs ref example so as to not promote bad practices | import md from 'components/md'
const Refs = () => md`
## Refs
Passing a \`ref\` prop to a styled component will give you an instance of
the \`StyledComponent\` wrapper, but not to the underlying DOM node.
This is due to how refs work.
It's not possible to call DOM methods, like \`focus\`, on our wrappers directly.
To get a ref to the actual, wrapped DOM node, pass the callback to the \`innerRef\` prop instead.
> We don't support string refs (i.e. \`innerRef="node"\`), since they're already deprecated in React.
This example uses \`innerRef\` to save a ref to the styled input and focuses it once the user
hovers over it.
\`\`\`react
const Input = styled.input\`
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
\`;
class Form extends React.Component {
render() {
return (
<Input
placeholder="Hover here..."
innerRef={x => this.input = x}
onMouseEnter={() => this.input.focus()}
/>
);
}
}
render(
<Form />
);
\`\`\`
`
export default Refs
| import md from 'components/md'
const Refs = () => md`
## Refs
Passing a \`ref\` prop to a styled component will give you an instance of
the \`StyledComponent\` wrapper, but not to the underlying DOM node.
This is due to how refs work.
It's not possible to call DOM methods, like \`focus\`, on our wrappers directly.
To get a ref to the actual, wrapped DOM node, pass the callback to the \`innerRef\` prop instead.
> We don't support string refs (i.e. \`innerRef="node"\`), since they're already deprecated in React.
This example uses \`innerRef\` to save a ref to the styled input and focuses it once the user
hovers over it.
\`\`\`react
const Input = styled.input\`
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
\`;
const Form = () => (
<Input
placeholder="Hover here..."
innerRef={x => this.input = x}
onMouseEnter={() => this.input.focus()}
/>
);
render(
<Form />
);
\`\`\`
`
export default Refs
|
Fix Package name in Test Class | package clinic.programming.training;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
public class ApplicationTest {
private Application app;
@Before
public void setup() {
app = new Application();
}
@Test
public void testWordCountString() {
int count = app.countWords("this is a test");
assertTrue(count == 4);
}
@Test
public void testWordCountEmpty() {
int count = app.countWords("");
assertTrue(count == 0);
}
@Test
public void testWordCountNull() {
int count = app.countWords(null);
assertTrue(count == 0);
}
@Test
@Ignore
public void testWordCountMore() {
int count = app.countWords("this will be skipped");
assertTrue(count == 3);
}
@Test
public void testWordCountSingle() {
int count = app.countWords("test");
assertTrue(count == 1);
}
} | package clinic.programming.trainig;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
public class ApplicationTest {
private Application app;
@Before
public void setup() {
app = new Application();
}
@Test
public void testWordCountString() {
int count = app.countWords("this is a test");
assertTrue(count == 4);
}
@Test
public void testWordCountEmpty() {
int count = app.countWords("");
assertTrue(count == 0);
}
@Test
public void testWordCountNull() {
int count = app.countWords(null);
assertTrue(count == 0);
}
@Test
@Ignore
public void testWordCountMore() {
int count = app.countWords("this will be skipped");
assertTrue(count == 3);
}
@Test
public void testWordCountSingle() {
int count = app.countWords("test");
assertTrue(count == 1);
}
} |
Use the correct class name.
svn commit r7882 | <?php
require_once 'Swat/SwatContainer.php';
/**
* Base class for containers that display an XHTML element
*
* @package Swat
* @copyright 2006 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatDisplayableContainer extends SwatContainer
{
// {{{ public properties
/**
* The custom CSS class of this container
*
* This optional class is added on top of the default 'swat-displayable-container'
* class.
*
* @var string
*/
public $class = null;
// }}}
// {{{ protected function getCssClasses()
/**
* Get CSS classes for outer XHTML element
*/
protected function getCssClasses($class)
{
if ($this->class !== null)
$class.= ' '.$this->class;
return $class;
}
// }}}
// {{{ public function display()
/**
* Displays this container
*/
public function display()
{
if (!$this->visible)
return;
$div = new SwatHtmlTag('div');
$div->class = $this->getCssClasses('swat-displayable-container');
if ($this->id !== null)
$div->id = $this->id;
$div->open();
$this->displayChildren();
$div->close();
}
// }}}
}
?>
| <?php
require_once 'Swat/SwatContainer.php';
/**
* Base class for containers that display an XHTML element
*
* @package Swat
* @copyright 2006 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatDisplayableContainer extends SwatContainer
{
// {{{ public properties
/**
* The custom CSS class of this frame
*
* This optional class is added on top of the default 'swat-frame'
* class.
*
* @var string
*/
public $class = null;
// }}}
// {{{ protected function getCssClasses()
/**
* Get CSS classes for outer XHTML element
*/
protected function getCssClasses($class)
{
if ($this->class !== null)
$class.= ' '.$this->class;
return $class;
}
// }}}
// {{{ public function display()
/**
* Displays this container
*/
public function display()
{
if (!$this->visible)
return;
$div = new SwatHtmlTag('div');
$div->class = $this->getCssClasses('swat-displayable-container');
if ($this->id !== null)
$div->id = $this->id;
$div->open();
$this->displayChildren();
$div->close();
}
// }}}
}
?>
|
Update the migration with the right user table name and defaults | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('email')->unique();
$table->string('firstname');
$table->string('lastname');
$table->string('google_accesstoken');
$table->boolean('is_admin')->default(0);
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateUserTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user', function(Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('firstname');
$table->string('lastname');
$table->string('goggle_accesstoken');
$table->boolean('is_admin');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('user');
}
}
|
Enable refresh on focus by env var.
So in dev and staging we can try to fix bugs without losing critical
state. | const REFRESH_PERIOD = 30 * 60 * 1000 // 30 minutes in microseconds
const focusEnabled = ENV.ENABLE_REFRESH_ON_FOCUS
const focusSupported = typeof document !== 'undefined' &&
typeof document.addEventListener !== 'undefined' &&
typeof document.visibilityState !== 'undefined'
let hiddenAt = null
function onHide() {
hiddenAt = new Date()
}
function onShow() {
const drift = new Date() - hiddenAt
if (hiddenAt && (drift >= REFRESH_PERIOD)) {
document.location.reload()
}
}
function handleChange() {
if (document.visibilityState === 'hidden') {
onHide()
} else if (document.visibilityState === 'visible') {
onShow()
}
}
export const startRefreshTimer = () => {
if (focusEnabled && focusSupported) {
document.addEventListener('visibilitychange', handleChange)
}
}
| const REFRESH_PERIOD = 30 * 60 * 1000 // 30 minutes in microseconds
const focusSupported = typeof document !== 'undefined' &&
typeof document.addEventListener !== 'undefined' &&
typeof document.visibilityState !== 'undefined'
let hiddenAt = null
function onHide() {
hiddenAt = new Date()
}
function onShow() {
const drift = new Date() - hiddenAt
if (hiddenAt && (drift >= REFRESH_PERIOD)) {
document.location.reload()
}
}
function handleChange() {
if (document.visibilityState === 'hidden') {
onHide()
} else if (document.visibilityState === 'visible') {
onShow()
}
}
export const startRefreshTimer = () => {
if (focusSupported) {
document.addEventListener('visibilitychange', handleChange)
}
}
|
docs(website): Add search powered by Algolia | // See https://docusaurus.io/docs/site-config.html for all the possible
// site configuration options.
const siteConfig = {
algolia: {
apiKey: "7c4587628ca223f7abcd82db137ad7b4",
indexName: "fuse_box",
},
baseUrl: "/",
colors: {
primaryColor: "#223351",
secondaryColor: "#3160af",
},
cleanUrl: true,
copyright: "Copyright © " + new Date().getFullYear() + " FuseBox",
favicon: "img/favicon.ico",
footerIcon: "img/logo.svg",
headerIcon: "img/logo.svg",
headerLinks: [
{
doc: "getting-started/installation",
label: "Documentation",
},
{
doc: "plugins/babel-plugin",
label: "Plugins",
},
{
href: "https://github.com/fuse-box/fuse-box/releases",
label: "Release notes",
},
],
highlight: {
theme: "default",
},
gaTrackingId: "UA-124354958-1",
ogImage: "img/docusaurus.png",
onPageNav: "separate",
organizationName: "FuseBox",
projectName: "fuse-box",
tagline: "A bundler that does it right",
title: "FuseBox",
twitterImage: "img/docusaurus.png",
url: "https://fuse-box.org",
};
module.exports = siteConfig;
| // See https://docusaurus.io/docs/site-config.html for all the possible
// site configuration options.
const siteConfig = {
baseUrl: "/",
colors: {
primaryColor: "#223351",
secondaryColor: "#3160af",
},
cleanUrl: true,
copyright: "Copyright © " + new Date().getFullYear() + " FuseBox",
favicon: "img/favicon.ico",
footerIcon: "img/logo.svg",
headerIcon: "img/logo.svg",
headerLinks: [
{
doc: "getting-started/installation",
label: "Documentation",
},
{
doc: "plugins/babel-plugin",
label: "Plugins",
},
{
href: "https://github.com/fuse-box/fuse-box/releases",
label: "Release notes",
},
],
highlight: {
theme: "default",
},
gaTrackingId: "UA-124354958-1",
ogImage: "img/docusaurus.png",
onPageNav: "separate",
organizationName: "FuseBox",
projectName: "fuse-box",
tagline: "A bundler that does it right",
title: "FuseBox",
twitterImage: "img/docusaurus.png",
url: "https://fuse-box.org",
};
module.exports = siteConfig;
|
Fix typo: identifier should be 'id' not 'bugId' | <?php
namespace Tienvx\Bundle\MbtBundle\Message;
class QueuedLoopMessage
{
protected $id;
protected $length;
protected $pair;
public function __construct(int $id, int $length, array $pair)
{
$this->id = $id;
$this->length = $length;
$this->pair = $pair;
}
public function getId(): int
{
return $this->id;
}
public function getLength(): int
{
return $this->length;
}
public function getPair(): array
{
return $this->pair;
}
public function __toString()
{
return json_encode([
'id' => $this->id,
'length' => $this->length,
'pair' => $this->pair,
]);
}
public static function fromString(string $message)
{
$decoded = json_decode($message, true);
return new static($decoded['id'], $decoded['length'], $decoded['pair']);
}
}
| <?php
namespace Tienvx\Bundle\MbtBundle\Message;
class QueuedLoopMessage
{
protected $bugId;
protected $length;
protected $pair;
public function __construct(int $bugId, int $length, array $pair)
{
$this->bugId = $bugId;
$this->length = $length;
$this->pair = $pair;
}
public function getBugId(): int
{
return $this->bugId;
}
public function getLength(): int
{
return $this->length;
}
public function getPair(): array
{
return $this->pair;
}
public function __toString()
{
return json_encode([
'bugId' => $this->bugId,
'length' => $this->length,
'pair' => $this->pair,
]);
}
public static function fromString(string $message)
{
$decoded = json_decode($message, true);
return new static($decoded['bugId'], $decoded['length'], $decoded['pair']);
}
}
|
Change static directory, commented mongo dev stuff | """
Main entry point of the logup-factory
"""
from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask import request
from flask import render_template
app = Flask(__name__, static_url_path='', static_folder='frontend/dist')
app.config.from_pyfile('flask-conf.cfg')
# db = MongoEngine(app)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'GET':
return render_template('signup.html')
else:
return 'ok'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
return 'ok'
@app.route('/forgot-password', methods=['GET', 'POST'])
def forgot_password():
if request.method == 'GET':
return render_template('forgot-password.html')
else:
return 'ok'
@app.route('/password-reset/<token>', methods=['GET', 'POST'])
def password_reset(token):
if request.method == 'GET':
return render_template('password-reset.html')
else:
return 'ok'
if __name__ == '__main__':
app.run()
| """
Main entry point of the logup-factory
"""
from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask import request
from flask import render_template
app = Flask(__name__)
app.config.from_pyfile('flask-conf.cfg')
db = MongoEngine(app)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'GET':
return render_template('signup.html')
else:
return 'ok'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
else:
return 'ok'
@app.route('/forgot-password', methods=['GET', 'POST'])
def forgot_password():
if request.method == 'GET':
return render_template('forgot-password.html')
else:
return 'ok'
@app.route('/password-reset/<token>', methods=['GET', 'POST'])
def password_reset(token):
if request.method == 'GET':
return render_template('password-reset.html')
else:
return 'ok'
if __name__ == '__main__':
app.run()
|
Fix version clasifier to one of the pypi allowed ones. | import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-etesync-journal',
version='0.5.0',
packages=find_packages(),
include_package_data=True,
license='AGPLv3',
description='The server side implementation of the EteSync protocol.',
long_description=README,
url='https://www.etesync.com/',
author='EteSync',
author_email='development@etesync.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-etesync-journal',
version='0.5.0',
packages=find_packages(),
include_package_data=True,
license='AGPLv3',
description='The server side implementation of the EteSync protocol.',
long_description=README,
url='https://www.etesync.com/',
author='EteSync',
author_email='development@etesync.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: AGPLv3',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Raise exception if version does not exist | from setuptools import setup, find_packages
import codecs
import os
import re
root_dir = os.path.abspath(os.path.dirname(__file__))
PACKAGE = 'hackernews_scraper'
def get_version(package_name):
version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$")
package_components = package_name.split('.')
init_path = os.path.join(root_dir, *(package_components + ['__init__.py']))
with codecs.open(init_path, 'r', 'utf-8') as f:
for line in f:
match = version_re.match(line[:-1])
if match:
return match.groups()[0]
raise Exception("No package version found!")
setup(name=PACKAGE
description='Python library for retrieving comments and stories from HackerNews',
packages=find_packages(),
version=get_version(PACKAGE),
install_requires=['requests'],
url='https://github.com/NiGhTTraX/hackernews-scraper',
license='MIT',
platforms='any',
tests_require=['nose', 'factory_boy', 'httpretty'],
)
| from setuptools import setup, find_packages
import codecs
import os
import re
root_dir = os.path.abspath(os.path.dirname(__file__))
PACKAGE = 'hackernews_scraper'
def get_version(package_name):
version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$")
package_components = package_name.split('.')
init_path = os.path.join(root_dir, *(package_components + ['__init__.py']))
with codecs.open(init_path, 'r', 'utf-8') as f:
for line in f:
match = version_re.match(line[:-1])
if match:
return match.groups()[0]
return '0.1.0'
setup(name=PACKAGE
description='Python library for retrieving comments and stories from HackerNews',
packages=find_packages(),
version=get_version(PACKAGE),
install_requires=['requests'],
url='https://github.com/NiGhTTraX/hackernews-scraper',
license='MIT',
platforms='any',
tests_require=['nose', 'factory_boy', 'httpretty'],
)
|
Move CMS admin panel to /cms. | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtailcore import urls as wagtail_urls
from wagtail.wagtaildocs import urls as wagtaildocs_urls
from coss.search import views as search_views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^cms-admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^search/$', search_views.search, name='search'),
# For anything not caught by a more specific rule above, hand over to
# Wagtail's page serving mechanism. This should be the last pattern in
# the list:
url(r'', include(wagtail_urls)),
# Alternatively, if you want Wagtail pages to be served from a subpath
# of your site, rather than the site root:
# url(r'^pages/', include(wagtail_urls)),
]
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtailcore import urls as wagtail_urls
from wagtail.wagtaildocs import urls as wagtaildocs_urls
from coss.search import views as search_views
urlpatterns = [
url(r'^django-admin/', include(admin.site.urls)),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^search/$', search_views.search, name='search'),
# For anything not caught by a more specific rule above, hand over to
# Wagtail's page serving mechanism. This should be the last pattern in
# the list:
url(r'', include(wagtail_urls)),
# Alternatively, if you want Wagtail pages to be served from a subpath
# of your site, rather than the site root:
# url(r'^pages/', include(wagtail_urls)),
]
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
Put the script loading in test in a try/catch because it was causing an error in certain cases with Opera. | var loadScripts = function(js_files, onComplete){
var len = js_files.length;
var head = document.getElementsByTagName('head')[0];
function loadScript(index){
if (index >= len){
onComplete();
return;
}
try {
testOk = js_files[index].test();
} catch (e) {
// with certain browsers like opera the above test can fail
// because of undefined variables...
testOk = true;
}
if (testOk) {
var s = document.createElement('script');
s.src = js_files[index].src;
s.type = 'text/javascript';
head.appendChild(s);
s.onload = function(){
loadScript(index+1);
}
} else {
loadScript(index+1);
}
}
loadScript(0);
}
| var loadScripts = function(js_files, onComplete){
var len = js_files.length;
var head = document.getElementsByTagName('head')[0];
function loadScript(index){
if (index >= len){
onComplete();
return;
}
if (js_files[index].test()){
// console.log('Loading ' + js_files[index].src);
var s = document.createElement('script');
s.src = js_files[index].src;
s.type = 'text/javascript';
head.appendChild(s);
s.onload = function(){
loadScript(index+1);
}
}
else{
loadScript(index+1);
}
}
loadScript(0);
}
|
Use agnostic protocol urls to support both http/https. | # http://robohash.org/
from django import template
from md5 import md5
register = template.Library()
@register.inclusion_tag("robotars/robotar.html")
def robotar(user, size=None, gravatar_fallback=False, hashed=False):
url = "//robohash.org/"
if gravatar_fallback:
if hashed:
url += "%s?gravatar=hashed&" % md5(user.email).hexdigest()
else:
url += "%s?gravatar=yes&" % user.email
else:
url += "%s?" % user
if size is not None:
url += 'size=%s' % size
return {"robotar_url": url, "robotar_user": user}
| # http://robohash.org/
from django import template
from md5 import md5
register = template.Library()
@register.inclusion_tag("robotars/robotar.html")
def robotar(user, size=None, gravatar_fallback=False, hashed=False):
url = "http://robohash.org/"
if gravatar_fallback:
if hashed:
url += "%s?gravatar=hashed&" % md5(user.email).hexdigest()
else:
url += "%s?gravatar=yes&" % user.email
else:
url += "%s?" % user
if size is not None:
url += 'size=%s' % size
return {"robotar_url": url, "robotar_user": user}
|
Handle illegal namedtuple field names, if found in a csv file. | from setuptools import setup, find_packages
setup(
version='0.36',
name="pydvkbiology",
packages=find_packages(),
description='Python scripts used in my biology/bioinformatics research',
author='DV Klopfenstein',
author_email='music_pupil@yahoo.com',
scripts=['./pydvkbiology/NCBI/cols.py'],
license='BSD',
url='http://github.com/dvklopfenstein/biocode',
download_url='http://github.com/dvklopfenstein/biocode/tarball/0.1',
keywords=['NCBI', 'biology', 'bioinformatics'],
classifiers = [
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Topic :: Scientific/Engineering :: Bio-Informatics'],
#install_requires=['sys', 're', 'os', 'collections']
# Potential other requires:
# Entrez
# math
# matplotlib
# numpy
# requests
# shutil
)
| from setuptools import setup, find_packages
setup(
version='0.35',
name="pydvkbiology",
packages=find_packages(),
description='Python scripts used in my biology/bioinformatics research',
author='DV Klopfenstein',
author_email='music_pupil@yahoo.com',
scripts=['./pydvkbiology/NCBI/cols.py'],
license='BSD',
url='http://github.com/dvklopfenstein/biocode',
download_url='http://github.com/dvklopfenstein/biocode/tarball/0.1',
keywords=['NCBI', 'biology', 'bioinformatics'],
classifiers = [
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Topic :: Scientific/Engineering :: Bio-Informatics'],
#install_requires=['sys', 're', 'os', 'collections']
# Potential other requires:
# Entrez
# math
# matplotlib
# numpy
# requests
# shutil
)
|
Fix migrations 002 for monthly grouping
@gtrogers | """
Add _week_start_at field to all documents in all collections
"""
from backdrop.core.bucket import utc
from backdrop.core.records import Record
import logging
log = logging.getLogger(__name__)
def up(db):
for name in db.collection_names():
log.info("Migrating collection: {0}".format(name))
collection = db[name]
query = {
"_timestamp": {"$exists": True},
"_month_start_at": {"$exists": False}
}
for document in collection.find(query):
document['_timestamp'] = utc(document['_timestamp'])
if '_week_start_at' in document:
document.pop('_week_start_at')
record = Record(document)
collection.save(record.to_mongo())
| """
Add _week_start_at field to all documents in all collections
"""
from backdrop.core.bucket import utc
from backdrop.core.records import Record
import logging
log = logging.getLogger(__name__)
def up(db):
for name in db.collection_names():
log.info("Migrating collection: {0}".format(name))
collection = db[name]
query = {
"_timestamp": {"$exists": True},
"_month_start_at": {"$exists": False}
}
for document in collection.find(query):
document['_timestamp'] = utc(document['_timestamp'])
record = Record(document)
collection.save(record.to_mongo())
|
Remove page status on empty results | @extends('layouts.app')
@section('content')
<div class="card card--section">
<div class="card-header">Students enrolled in {{ $course->name }}</div>
@if($enrollments->isEmpty())
@include('students.shared.table.empty')
@else
@include('students.shared.table.index')
@endif
<div class="row">
<div class="col">
{{ $enrollments->links() }}
</div>
<div class="col-auto align-self-center">
@if ($enrollments->lastPage() > 0)
Page {{ $enrollments->currentPage() }} of {{ $enrollments->lastPage() }}
@endif
</div>
</div>
</div>
@endsection
| @extends('layouts.app')
@section('content')
<div class="card card--section">
<div class="card-header">Students enrolled in {{ $course->name }}</div>
@if($enrollments->isEmpty())
@include('students.shared.table.empty')
@else
@include('students.shared.table.index')
@endif
<div class="row">
<div class="col">
{{ $enrollments->links() }}
</div>
<div class="col-auto align-self-center">
Page {{ $enrollments->currentPage() }} of {{ $enrollments->lastPage() }}
</div>
</div>
</div>
@endsection
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.