text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Make sure CSS files are watched | import gulp from 'gulp'
import path from 'path'
import BrowserSync from 'browser-sync'
import { compiler, handleWebpackResults } from '../webpack/compiler'
const browserSync = BrowserSync.create()
const args = global.__args
const themeDir = path.resolve(__pkg._themepath)
const themeRelPath = themeDir.replace(process.cwd()+'/', '')
gulp.task('dev', ['build'], ()=> {
compiler.watch({}, handleWebpackResults(true))
gulp.watch(`${themeRelPath}/scss/**/*.scss`, ['styles'])
gulp.watch(`${themeRelPath}/images/**/*`, ['images'])
gulp.watch(`${themeRelPath}/fonts/**/*`, ['static'])
if (args.sync) {
browserSync.init({
proxy: __pkg._criticalUrl,
files: [
`${themeRelPath}/assets/js/*.js`,
`${themeRelPath}/assets/css/*.css`,
`${themeRelPath}/**/*.php`
]
})
}
})
| import gulp from 'gulp'
import path from 'path'
import BrowserSync from 'browser-sync'
import { compiler, handleWebpackResults } from '../webpack/compiler'
const browserSync = BrowserSync.create()
const args = global.__args
const themeDir = path.resolve(__pkg._themepath)
const themeRelPath = themeDir.replace(process.cwd()+'/', '')
gulp.task('dev', ['build'], ()=> {
compiler.watch({}, handleWebpackResults(true))
gulp.watch(`${themeRelPath}/scss/**/*.scss`, ['styles'])
gulp.watch(`${themeRelPath}/images/**/*`, ['images'])
gulp.watch(`${themeRelPath}/fonts/**/*`, ['static'])
if (args.sync) {
browserSync.init({
proxy: __pkg._criticalUrl,
files: [
`${themeRelPath}/assets/js/*.js`,
`${themeRelPath}/**/*.php`
]
})
}
})
|
Use spread operator instead Object.assign | const mainReducer = (state , action) => {
switch (action.type) {
case 'REQUEST_LOCATION':
return {...state, loading: true}
case 'RECEIVE_LOCATION':
return {
...state,
location: {
city: action.city,
latitude: action.latitude,
longitude: action.longitude
},
locationIsChanged: false
}
case 'CHANGE_LOCATION':
return {
...state,
location: {
city: action.city,
latitude: action.latitude,
longitude: action.longitude
},
locationIsChanged: true
}
case 'RECEIVE_WEATHER':
return {
...state,
temperature: action.temperature,
weatherDescription: action.description,
weatherIcon: action.icon,
pageBackground: action.background,
loading: false,
loadingError: false
}
case 'SWITCH_EDIT_MODE':
return {
...state,
editMode: action.value
}
case 'LOADING_FAILED':
return {
...state,
loading: false,
loadingError: true
}
default:
return state;
}
};
export default mainReducer; | const mainReducer = (state , action) => {
switch (action.type) {
case 'REQUEST_LOCATION':
return Object.assign({}, state, {
loading: true
})
case 'RECEIVE_LOCATION':
return Object.assign({}, state, {
location: {
city: action.city,
latitude: action.latitude,
longitude: action.longitude
},
locationIsChanged: false
})
case 'CHANGE_LOCATION':
return Object.assign({}, state, {
location: {
city: action.city,
latitude: action.latitude,
longitude: action.longitude
},
locationIsChanged: true
})
case 'RECEIVE_WEATHER':
return Object.assign({}, state, {
temperature: action.temperature,
weatherDescription: action.description,
weatherIcon: action.icon,
pageBackground: action.background,
loading: false,
loadingError: false
})
case 'SWITCH_EDIT_MODE':
return Object.assign({}, state, {
editMode: action.value
})
case 'LOADING_FAILED':
return Object.assign({}, state, {
loading: false,
loadingError: true
})
default:
return state;
}
};
export default mainReducer; |
Configure webpack to lint automatically | const path = require('path')
// commonjs module
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'eval',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: true
},
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
},
{
include: path.resolve(__dirname, 'js'),
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
url: false
}
}
]
}
]
}
}
| const path = require('path')
// commonjs module
module.exports = {
context: __dirname,
entry: './js/ClientApp.js',
devtool: 'eval',
output: {
path: path.join(__dirname, '/public'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: true
},
module: {
rules: [
{
include: path.resolve(__dirname, 'js'),
test: /\.js$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
url: false
}
}
]
}
]
}
}
|
Send command with date range from web UI. | var param_from_input = function(css) {
return scraperwiki.shellEscape($(css).val())
}
var runScraper = function() {
$(this).attr('disabled', true)
$(this).addClass('loading').html('Scraping…')
var stocks = param_from_input('#stocks_input')
var start_date = param_from_input('#start-date')
var end_date = param_from_input('#end-date')
var command = ['python tool/pandas_finance.py', stocks, start_date, end_date].join(' ')
scraperwiki.exec(command, getStocksSuccess)
}
var getStocksSuccess = function(data) {
$('#submitBtn').attr('disabled', false)
if (data.indexOf('File "tool/pandas_finance.py"') != -1) {
scraperwiki.alert('Error in pandas_finance.py', data, true)
$('#submitBtn').removeClass('loading').html('<i class="icon-remove"></i> Error')
$('#submitBtn').removeClass('btn-primary').addClass('btn-danger')
setTimeout(function() {
$('#submitBtn').html('Get Stocks')
$('#submitBtn').removeClass('btn-danger').addClass('btn-primary')
}, 4000)
} else {
$('#submitBtn').removeClass('loading').html('<i class="icon-ok"></i> Done')
scraperwiki.tool.redirect("/dataset/" + scraperwiki.box)
}
}
$(function() {
$('#submitBtn').on('click', runScraper)
})
| var runScraper = function() {
$(this).attr('disabled', true)
$(this).addClass('loading').html('Scraping…')
var stocks = $('#stocks_input').val()
var escaped_stocks = scraperwiki.shellEscape(stocks)
scraperwiki.exec('python tool/pandas_finance.py ' + escaped_stocks, getStocksSuccess)
}
var getStocksSuccess = function(data) {
$('#submitBtn').attr('disabled', false)
if (data.indexOf('File "tool/pandas_finance.py"') != -1) {
scraperwiki.alert('Error in pandas_finance.py', data, true)
$('#submitBtn').removeClass('loading').html('<i class="icon-remove"></i> Error')
$('#submitBtn').removeClass('btn-primary').addClass('btn-danger')
setTimeout(function() {
$('#submitBtn').html('Get Stocks')
$('#submitBtn').removeClass('btn-danger').addClass('btn-primary')
}, 4000)
} else {
$('#submitBtn').removeClass('loading').html('<i class="icon-ok"></i> Done')
scraperwiki.tool.redirect("/dataset/" + scraperwiki.box)
}
}
$(function() {
$('#submitBtn').on('click', runScraper)
})
|
Remove ok assertion in loadbalancer weight map lookup
I'd thought about raising an error if we looked up a nonexistent weight,
but decided not to. | package lb
import (
"math/rand"
"time"
)
// Implement a load balancer that given a set of requests distributes those
// requests to an arbitrary number of weighted backends
type Backend struct {
Name string
Weight int
Handled int
}
type LoadBalancer struct {
w map[int]*Backend
}
func NewLoadBalancer(backends []*Backend) *LoadBalancer {
rand.Seed(time.Now().UnixNano())
lb := &LoadBalancer{w: make(map[int]*Backend)}
i := 0
for _, b := range backends {
for j := 0; j < b.Weight; j++ {
lb.w[i] = b
i++
}
}
return lb
}
func (lb *LoadBalancer) Next() *Backend {
b := lb.w[rand.Intn(len(lb.w)-1)]
b.Handled++
return b
}
| package lb
import (
"math/rand"
"time"
)
// Implement a load balancer that given a set of requests distributes those
// requests to an arbitrary number of weighted backends
type Backend struct {
Name string
Weight int
Handled int
}
type LoadBalancer struct {
w map[int]*Backend
}
func NewLoadBalancer(backends []*Backend) *LoadBalancer {
rand.Seed(time.Now().UnixNano())
lb := &LoadBalancer{w: make(map[int]*Backend)}
i := 0
for _, b := range backends {
for j := 0; j < b.Weight; j++ {
lb.w[i] = b
i++
}
}
return lb
}
func (lb *LoadBalancer) Next() *Backend {
b, ok := lb.w[rand.Intn(len(lb.w)-1)]
b.Handled++
return b
}
|
Refactor and add circular shape helper | import $ from "cheerio";
const RECTANGULAR_SEQUENCE = ["M", "L", "L", "L", "L"];
const CIRCULAR_SEQUENCE = ["M", "m", "a", "a"];
const SvgTestHelper = {
expectIsRectangular(wrapper) {
expect(exhibitsShapeSequence(wrapper, RECTANGULAR_SEQUENCE)).to.be.true;
},
expectIsCircular(wrapper) {
expect(exhibitsShapeSequence(wrapper, CIRCULAR_SEQUENCE)).to.be.true;
}
};
function exhibitsShapeSequence(wrapper, shapeSequence) {
const commands = getPathCommandsFromWrapper(wrapper);
return commands.every((command, index) => {
return command.name === shapeSequence[index];
});
}
function getPathCommandsFromWrapper(wrapper) {
const commandStr = $(wrapper.html()).attr("d");
return parseSvgPathCommands(commandStr);
}
function parseSvgPathCommands(commandStr) {
const matches = commandStr.match(
/[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g
);
return matches.map(match => {
const name = match.charAt(0);
const args = match.substring(1).split(",").map(arg => parseFloat(arg, 10));
return {
raw: match,
name,
args
}
});
}
export default SvgTestHelper;
| import $ from "cheerio";
const SvgTestHelper = {
RECTANGULAR_SEQUENCE: ["M", "L", "L", "L", "L"],
expectIsRectangular(wrapper) {
expect(exhibitsRectangularDirectionSequence(wrapper)).to.be.true;
}
};
function exhibitsRectangularDirectionSequence(wrapper) {
const commands = getPathCommandsFromWrapper(wrapper);
return commands.every((command, index) => {
return command.name === SvgTestHelper.RECTANGULAR_SEQUENCE[index];
});
}
function getPathCommandsFromWrapper(wrapper) {
const commandStr = $(wrapper.html()).attr("d");
return parseSvgPathCommands(commandStr);
}
function parseSvgPathCommands(commandStr) {
const matches = commandStr.match(
/[MmLlHhVvCcSsQqTtAaZz]+[^MmLlHhVvCcSsQqTtAaZz]*/g
);
return matches.map(match => {
const name = match.charAt(0);
const args = match.substring(1).split(",").map(arg => parseFloat(arg, 10));
return {
raw: match,
name,
args
}
});
}
export default SvgTestHelper;
|
Add front end build step to comment on running manually | """Provide APP constant for the purposes of manually running the flask app
For example, build the front end, then run the app with environment variables::
cd smif/app/
npm run build
cd ../http_api/
FLASK_APP=smif.http_api.app FLASK_DEBUG=1 flask run
"""
import os
from smif.data_layer import DatafileInterface
from smif.http_api import create_app
def get_connection():
"""Return a data_layer connection
"""
return DatafileInterface(
os.path.join(os.path.dirname(__file__), '..', '..', 'tests', 'fixtures', 'single_run')
)
APP = create_app(
static_folder=os.path.join(os.path.dirname(__file__), '..', 'app', 'dist'),
template_folder=os.path.join(os.path.dirname(__file__), '..', 'app', 'dist'),
get_connection=get_connection
)
| """Provide APP constant for the purposes of manually running the flask app
For example, set up environment variables then run the app::
export FLASK_APP=smif.http_api.app
export FLASK_DEBUG=1
flask run
"""
import os
from smif.data_layer import DatafileInterface
from smif.http_api import create_app
def get_connection():
"""Return a data_layer connection
"""
return DatafileInterface(
os.path.join(os.path.dirname(__file__), '..', '..', 'tests', 'fixtures', 'single_run')
)
APP = create_app(
static_folder=os.path.join(os.path.dirname(__file__), '..', 'app', 'dist'),
template_folder=os.path.join(os.path.dirname(__file__), '..', 'app', 'dist'),
get_connection=get_connection
)
|
Add 'it' in front of spec descriptions | const { TerminalReporter } = require('jasmine-tagged')
class JasmineListReporter extends TerminalReporter {
fullDescription (spec) {
let fullDescription = 'it ' + spec.description
let currentSuite = spec.suite
while (currentSuite) {
fullDescription = currentSuite.description + ' > ' + fullDescription
currentSuite = currentSuite.parentSuite
}
return fullDescription
}
reportSpecStarting (spec) {
this.print_(this.fullDescription(spec) + ' ')
}
reportSpecResults (spec) {
const result = spec.results()
if (result.skipped) {
return
}
let msg = ''
if (result.passed()) {
msg = this.stringWithColor_('[pass]', this.color_.pass())
} else {
msg = this.stringWithColor_('[FAIL]', this.color_.fail())
this.addFailureToFailures_(spec)
}
this.printLine_(msg)
}
}
module.exports = { JasmineListReporter }
| const { TerminalReporter } = require('jasmine-tagged')
class JasmineListReporter extends TerminalReporter {
fullDescription (spec) {
let fullDescription = spec.description
let currentSuite = spec.suite
while (currentSuite) {
fullDescription = currentSuite.description + ' > ' + fullDescription
currentSuite = currentSuite.parentSuite
}
return fullDescription
}
reportSpecStarting (spec) {
this.print_(this.fullDescription(spec) + ' ')
}
reportSpecResults (spec) {
const result = spec.results()
if (result.skipped) {
return
}
let msg = ''
if (result.passed()) {
msg = this.stringWithColor_('[pass]', this.color_.pass())
} else {
msg = this.stringWithColor_('[FAIL]', this.color_.fail())
this.addFailureToFailures_(spec)
}
this.printLine_(msg)
}
}
module.exports = { JasmineListReporter }
|
Set default state of ValidatedDateItem to valid. | from yapsy import IPlugin
from postprocessing import PostProcessedDataItem
__author__ = 'aj@springlab.co'
class ValidatedDataItem(PostProcessedDataItem):
"""
Overrides the PostProcessedDataItem class to provide an indication that a
PostProcessedDataItem instance has undergone validation
"""
def __init__(self, seq=None, **kwargs):
self.valid = True
super(ValidatedDataItem, self).__init__(seq, **kwargs)
class ValidationPluginInterface(IPlugin.IPlugin):
"""
Defines an interface for a plugin that validates the processed data items
"""
def can_validate(self, data_model_name, data_model):
"""
Determines whether the plugin can validate data associated with a given data model. Returns a bool.
"""
return False
def validate(self, data_items, data_model_name, data_model):
"""
For a given data model, processes a list of (UID value, ExtractedDataItem instance) tuples and validates
each ExtractedDataItem instance, transforming it into a ValidatedDataItem instance in the process.
Returns a list of (UID value, ValidatedDataItem instance) tuples.
"""
return []
| from yapsy import IPlugin
from postprocessing import PostProcessedDataItem
__author__ = 'aj@springlab.co'
class ValidatedDataItem(PostProcessedDataItem):
"""
Overrides the PostProcessedDataItem class to provide an indication that a
PostProcessedDataItem instance has undergone validation
"""
def __init__(self, seq=None, **kwargs):
self.valid = False
super(ValidatedDataItem, self).__init__(seq, **kwargs)
class ValidationPluginInterface(IPlugin.IPlugin):
"""
Defines an interface for a plugin that validates the processed data items
"""
def can_validate(self, data_model_name, data_model):
"""
Determines whether the plugin can validate data associated with a given data model. Returns a bool.
"""
return False
def validate(self, data_items, data_model_name, data_model):
"""
For a given data model, processes a list of (UID value, ExtractedDataItem instance) tuples and validates
each ExtractedDataItem instance, transforming it into a ValidatedDataItem instance in the process.
Returns a list of (UID value, ValidatedDataItem instance) tuples.
"""
return []
|
Fix method shadowing for marshal in Cookie ack
Sneaky beaky golan not complaining about the missing marshal because
it was fulfilled by a composed struct | package sctp
import (
"github.com/pkg/errors"
)
/*
chunkCookieAck represents an SCTP Chunk of type chunkCookieAck
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type = 11 |Chunk Flags | Length = 4 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
type chunkCookieAck struct {
chunkHeader
}
func (c *chunkCookieAck) unmarshal(raw []byte) error {
if err := c.chunkHeader.unmarshal(raw); err != nil {
return err
}
if c.typ != COOKIEACK {
return errors.Errorf("ChunkType is not of type COOKIEACK, actually is %s", c.typ.String())
}
return nil
}
func (c *chunkCookieAck) marshal() ([]byte, error) {
c.chunkHeader.typ = COOKIEACK
return c.chunkHeader.marshal()
}
func (c *chunkCookieAck) check() (abort bool, err error) {
return false, nil
}
| package sctp
import (
"github.com/pkg/errors"
)
/*
chunkCookieAck represents an SCTP Chunk of type chunkCookieAck
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type = 11 |Chunk Flags | Length = 4 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
type chunkCookieAck struct {
chunkHeader
}
func (c *chunkCookieAck) unmarshal(raw []byte) error {
if err := c.chunkHeader.unmarshal(raw); err != nil {
return err
}
if c.typ != COOKIEACK {
return errors.Errorf("ChunkType is not of type COOKIEACK, actually is %s", c.typ.String())
}
return nil
}
func (c *chunkCookieAck) Marshal() ([]byte, error) {
c.chunkHeader.typ = COOKIEACK
return c.chunkHeader.marshal()
}
func (c *chunkCookieAck) check() (abort bool, err error) {
return false, nil
}
|
Comment out printing of function. | from numba import struct, jit, double
import numpy as np
record_type = struct([('x', double), ('y', double)])
record_dtype = record_type.get_dtype()
a = np.array([(1.0, 2.0), (3.0, 4.0)], dtype=record_dtype)
@jit(argtypes=[record_type[:]])
def hypot(data):
# return types of numpy functions are inferred
result = np.empty_like(data, dtype=np.float64)
# notice access to structure elements 'x' and 'y' via attribute access
# You can also index by field name or field index:
# data[i].x == data[i]['x'] == data[i][0]
for i in range(data.shape[0]):
result[i] = np.sqrt(data[i].x * data[i].x + data[i].y * data[i].y)
return result
print hypot(a)
# Notice inferred return type
print hypot.signature
# Notice native sqrt calls and for.body direct access to memory...
#print hypot.lfunc
| from numba import struct, jit, double
import numpy as np
record_type = struct([('x', double), ('y', double)])
record_dtype = record_type.get_dtype()
a = np.array([(1.0, 2.0), (3.0, 4.0)], dtype=record_dtype)
@jit(argtypes=[record_type[:]])
def hypot(data):
# return types of numpy functions are inferred
result = np.empty_like(data, dtype=np.float64)
# notice access to structure elements 'x' and 'y' via attribute access
# You can also index by field name or field index:
# data[i].x == data[i]['x'] == data[i][0]
for i in range(data.shape[0]):
result[i] = np.sqrt(data[i].x * data[i].x + data[i].y * data[i].y)
return result
print hypot(a)
# Notice inferred return type
print hypot.signature
# Notice native sqrt calls and for.body direct access to memory...
print hypot.lfunc
|
Update migration to use native JSONField | # Generated by Django 1.9 on 2016-11-29 11:35
from django.contrib.postgres.fields import JSONField
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")]
operations = [
migrations.AlterField(
model_name="searchquery",
name="hits",
field=JSONField(
help_text="The list of meta info for each of the query matches returned."
),
),
migrations.AlterField(
model_name="searchquery",
name="query",
field=JSONField(help_text="The raw ElasticSearch DSL query."),
),
]
| # Generated by Django 1.9 on 2016-11-29 11:35
from django.db import migrations
from ..db.fields import JSONField
class Migration(migrations.Migration):
dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")]
operations = [
migrations.AlterField(
model_name="searchquery",
name="hits",
field=JSONField(
help_text="The list of meta info for each of the query matches returned."
),
),
migrations.AlterField(
model_name="searchquery",
name="query",
field=JSONField(help_text="The raw ElasticSearch DSL query."),
),
]
|
Fix webpack config to ensure it outputs a correct umd bundle | const path = require('path');
const webpack = require('webpack');
const distPath = path.join(__dirname, 'dist');
const srcPath = path.join(__dirname, 'src');
const env = process.env.NODE_ENV || 'development';
const minified = env === 'development' ? '' : '.min';
const exclude = [/node_modules/];
const config = {
context: srcPath,
entry: { reduxReuse: 'reduxReuse' },
output: {
path: distPath,
filename: `reduxReuse${minified}.js`,
library: 'reduxReuse',
libraryTarget: 'umd',
},
resolve: {
root: [srcPath]
},
module: {
preloaders: [
{
test: /\.js$/,
loader: 'eslint',
exclude
}
],
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude
}
]
},
};
module.exports = config;
| const path = require('path');
const webpack = require('webpack');
const distPath = path.join(__dirname, 'dist');
const srcPath = path.join(__dirname, 'src');
const env = process.env.NODE_ENV || 'development';
const minified = env === 'development' ? '' : '.min';
const exclude = [/node_modules/];
const config = {
context: srcPath,
entry: {
reduxReuse: ['reduxReuse'],
},
output: {
path: distPath,
filename: `[name]${minified}.js`,
library: ['reduxReuse', '[name]'],
libraryTarget: 'umd',
},
resolve: {
root: [srcPath]
},
module: {
preloaders: [
{
test: /\.js$/,
loader: 'eslint',
exclude
}
],
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude
}
]
},
};
module.exports = [
config,
{
...config,
entry: { reduxReuse: 'reduxReuse' },
output: {
...config.output,
filename: `reduxReuse${minified}.js`,
library: 'reduxReuse',
},
}
];
|
Add get tweet by id | 'use strict';
const Boom = require('boom');
const User = require('../models/user');
const Tweet = require('../models/tweet');
exports.findAll = {
auth: false,
handler: function (request, reply) {
Tweet.find({})
.sort({ createdAt: 'desc' })
.limit(50)
.populate('creator')
.exec().then((tweets) => {
reply(tweets);
}).catch((error) => {
reply(Boom.badImplementation('error accessing db'));
});
},
};
exports.findAllByUser = {
auth: false,
handler: function (request, reply) {
},
};
exports.findOne = {
auth: false,
handler: function (request, reply) {
Tweet.findOne({ _id: request.params.id }).populate('creator').exec().then((tweet) => {
if (tweet) {
reply(tweet);
} else {
reply(Boom.notFound('id not found'));
}
}).catch((error) => {
reply(Boom.notFound('id not found'));
});
},
};
exports.create = {
auth: false,
handler: function (request, reply) {
},
};
exports.deleteOne = {
auth: false,
handler: function (request, reply) {
},
};
| 'use strict';
const Boom = require('boom');
const User = require('../models/user');
const Tweet = require('../models/tweet');
exports.findAll = {
auth: false,
handler: function (request, reply) {
Tweet.find({})
.sort({ createdAt: 'desc' })
.limit(50)
.populate('creator')
.exec().then((tweets) => {
reply(tweets);
}).catch((error) => {
reply(Boom.badImplementation('error accessing db'));
});
},
};
exports.findAllByUser = {
auth: false,
handler: function (request, reply) {
},
};
exports.findOne = {
auth: false,
handler: function (request, reply) {
},
};
exports.create = {
auth: false,
handler: function (request, reply) {
},
};
exports.deleteOne = {
auth: false,
handler: function (request, reply) {
},
};
|
Handle missing port and router data
On some systems routers have no ports and ports
have no fixed IPs, so don't assume they do.
Also includes some pep8 fixes.
Change-Id: I73b5f22754958b897a6ae55e453c294f47bf9539
Signed-off-by: Doug Hellmann <8c845c26a3868dadec615703cd974244eb2ac6d1@dreamhost.com> | import collections
import logging
from django.utils.translation import ugettext as _
from horizon.api import quantum
from horizon import tabs
from akanda.horizon.configuration.tables.publicips import PublicIPsTable
# The table rendering code assumes it is getting an
# object with an "id" property and other properties
# based on the column definitions for the table.
# This is a light-weight data structure that looks
# like what we need for the publicips table.
PublicIP = collections.namedtuple('PublicIP', 'id router_name ipaddr')
class ConfigurationTab(tabs.TableTab):
"""Tab to show the user generic configuration settings.
"""
name = _("Configuration")
slug = "configuration_tab"
template_name = "akanda/configuration/index.html"
table_classes = (PublicIPsTable,)
def get_publicips_data(self):
data = []
c = quantum.quantumclient(self.request)
for router in c.list_routers(
tenant_id=self.request.user.tenant_id).values()[0]:
for port in router.get('ports', []):
if port.get('device_owner') != 'network:router_gateway':
continue
ips = [i['ip_address'] for i in port.get('fixed_ips', [])]
data.append(PublicIP(None, router.get('name'), ', '.join(ips)))
return data
| import collections
import logging
from django.utils.translation import ugettext as _
from horizon.api import quantum
from horizon import tabs
from akanda.horizon.configuration.tables.publicips import PublicIPsTable
# The table rendering code assumes it is getting an
# object with an "id" property and other properties
# based on the column definitions for the table.
# This is a light-weight data structure that looks
# like what we need for the publicips table.
PublicIP = collections.namedtuple('PublicIP', 'id router_name ipaddr')
class ConfigurationTab(tabs.TableTab):
"""Tab to show the user generic configuration settings.
"""
name = _("Configuration")
slug = "configuration_tab"
template_name = "akanda/configuration/index.html"
table_classes = (PublicIPsTable,)
def get_publicips_data(self):
data = []
c = quantum.quantumclient(self.request)
for router in c.list_routers(tenant_id=self.request.user.tenant_id).values()[0]:
for port in router['ports']:
if port['device_owner'] != 'network:router_gateway':
continue
ips = [i['ip_address'] for i in port['fixed_ips']]
data.append(PublicIP(None, router['name'], ', '.join(ips)))
return data
|
Make routes follow JSON API standards | const Debug = require('debug')('iot-home:server:hue')
var HueServer = {}
function HueRoutes (server, middleware) {
server.get('/hue/bridges', middleware.findBridge)
server.get('/hue/lights', middleware.findAllLights)
server.get('/hue/lights/:light', middleware.getState)
server.get('/hue/lights/:light/on', middleware.on)
server.get('/hue/lights/:light/off', middleware.off)
server.put('/hue/lights/:light/set', middleware.setHue)
server.get('/hue/users', middleware.getAllUsers)
server.get('/hue/users/:username', middleware.getUser)
server.post('/hue/users', middleware.newUser)
server.del('/hue/users', middleware.deleteUser)
server.get('/hue/config', middleware.displayConfiguration)
}
HueServer.init = (API, middleware) => {
Debug('Initializing Hue API Routes')
return new HueRoutes(API, middleware)
}
module.exports = HueServer
| const Debug = require('debug')('iot-home:server:hue')
var HueServer = {}
function HueRoutes (server, middleware) {
server.get('/hue/bridges', middleware.findBridge)
server.get('/hue/lights', middleware.findAllLights)
server.get('/hue/light/:light', middleware.getState)
server.get('/hue/light/:light/on', middleware.on)
server.get('/hue/light/:light/off', middleware.off)
server.put('/hue/light/:light/set', middleware.setHue)
server.get('/hue/users', middleware.getAllUsers)
server.get('/hue/user/:username', middleware.getUser)
server.post('/hue/user', middleware.newUser)
server.del('/hue/user', middleware.deleteUser)
server.get('/hue/config', middleware.displayConfiguration)
}
HueServer.init = (API, middleware) => {
Debug('Initializing Hue API Routes')
return new HueRoutes(API, middleware)
}
module.exports = HueServer
|
Allow access to the homepage if authorization is inactive | /*
Apache2 License Notice
Copyright 2017 Alex Barry
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.ao.adrestia.controller;
import java.security.Principal;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@SuppressWarnings("unused")
@Controller
public class HomeController {
@Value(value = "${server.auth.active}")
private boolean authActive;
private final Logger logger = LoggerFactory.getLogger("adrestia.AuthController");
@RequestMapping(value = "/portal/home", method = RequestMethod.GET)
protected String home(final Map<String, Object> model, final Principal principal) {
logger.info("Home page");
if (principal == null && authActive) {
logger.warn("No Principal Detected");
return "redirect:/logout";
}
model.put("userId", principal);
return "home";
}
}
| /*
Apache2 License Notice
Copyright 2017 Alex Barry
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.ao.adrestia.controller;
import java.security.Principal;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@SuppressWarnings("unused")
@Controller
public class HomeController {
private final Logger logger = LoggerFactory.getLogger("adrestia.AuthController");
@RequestMapping(value = "/portal/home", method = RequestMethod.GET)
protected String home(final Map<String, Object> model, final Principal principal) {
logger.info("Home page");
if (principal == null) {
logger.warn("No Principal Detected");
return "redirect:/logout";
}
model.put("userId", principal);
return "home";
}
}
|
Clear websocket data to try and fix Travis | from __future__ import unicode_literals
import json
from test_helpers import MockTrack, get_websocket, make_frontend, patched_bot
from mopidy_tachikoma import Extension
def test_get_default_config():
ext = Extension()
config = ext.get_default_config()
assert '[tachikoma]' in config
assert 'enabled = true' in config
assert 'slack_token = ' in config
def test_get_config_schema():
ext = Extension()
schema = ext.get_config_schema()
assert 'slack_token' in schema
@patched_bot
def test_can_connect():
make_frontend()
@patched_bot
def test_gets_events():
frontend = make_frontend()
frontend.doSlackLoop(
None, MockTrack(),
[{"type": "message", "channel": "mock_channel"}])
data = json.loads(get_websocket().data)
assert {
'channel': 'mock_channel',
'text': 'Now playing *foo* from *bar*',
'type': 'message'} == data
@patched_bot
def test_says_one_thing_per_channel():
frontend = make_frontend()
song = MockTrack()
get_websocket().data = None # make sure it's cleared
frontend.doSlackLoop(
song, song, [{"type": "message", "channel": "mock_channel"}])
assert get_websocket().data is None # same song, no info
| from __future__ import unicode_literals
import json
from test_helpers import MockTrack, get_websocket, make_frontend, patched_bot
from mopidy_tachikoma import Extension
def test_get_default_config():
ext = Extension()
config = ext.get_default_config()
assert '[tachikoma]' in config
assert 'enabled = true' in config
assert 'slack_token = ' in config
def test_get_config_schema():
ext = Extension()
schema = ext.get_config_schema()
assert 'slack_token' in schema
@patched_bot
def test_can_connect():
make_frontend()
@patched_bot
def test_gets_events():
frontend = make_frontend()
frontend.doSlackLoop(
None, MockTrack(),
[{"type": "message", "channel": "mock_channel"}])
data = json.loads(get_websocket().data)
assert {
'channel': 'mock_channel',
'text': 'Now playing *foo* from *bar*',
'type': 'message'} == data
@patched_bot
def test_says_one_thing_per_channel():
frontend = make_frontend()
song = MockTrack()
frontend.doSlackLoop(
song, song, [{"type": "message", "channel": "mock_channel"}])
assert get_websocket().data is None # same song, no info
|
Use widget id as argument for registry.remove as it takes an id and not a widget instance.
Add destroyRecursive method becuase containers check for and call destroyRecursive in their destroyDecendants cleanup. | define(["dojo/_base/declare","dijit/registry"],
function(declare, registry){
/*
* Dijit registry extension for dgrid
*/
return declare([], {
// summary:
// A dgrid extension which will add the grid to the dijit registry
// so that startup() will be successfully called by dijit layout widgets
// with dgrid children via registry.add(this).
buildRendering: function(){
registry.add(this);
this.inherited(arguments);
// Note: for dojo 2.0 may rename widgetId to dojo._scopeName + "_widgetId"
this.domNode.setAttribute("widgetId", this.id);
},
startup: function(){
if(this._started){ return; }
this.inherited(arguments);
// if parent is a widget, assume it will handle resize events, and
// remove the window resize listener added by List
if(registry.getEnclosingWidget(this.domNode.parentNode)){
this._resizeHandle.remove();
}
},
destroyRecursive: function() {
this.destroy();
},
destroy: function(){
this.inherited(arguments);
registry.remove(this.id);
},
getChildren: function(){
// provide hollow implementation for logic which assumes its existence
// (e.g. dijit/form/_FormMixin)
return [];
}
});
});
| define(["dojo/_base/declare","dijit/registry"],
function(declare, registry){
/*
* Dijit registry extension for dgrid
*/
return declare([], {
// summary:
// A dgrid extension which will add the grid to the dijit registry
// so that startup() will be successfully called by dijit layout widgets
// with dgrid children via registry.add(this).
buildRendering: function(){
registry.add(this);
this.inherited(arguments);
// Note: for dojo 2.0 may rename widgetId to dojo._scopeName + "_widgetId"
this.domNode.setAttribute("widgetId", this.id);
},
startup: function(){
if(this._started){ return; }
this.inherited(arguments);
// if parent is a widget, assume it will handle resize events, and
// remove the window resize listener added by List
if(registry.getEnclosingWidget(this.domNode.parentNode)){
this._resizeHandle.remove();
}
},
destroy: function(){
this.inherited(arguments);
registry.remove(this);
},
getChildren: function(){
// provide hollow implementation for logic which assumes its existence
// (e.g. dijit/form/_FormMixin)
return [];
}
});
}); |
Fix the issue that error message still shows up after swithed to another cloud provider
https://github.com/rancher/rancher/issues/10855 | import Controller from '@ember/controller';
import { alias } from '@ember/object/computed';
import NewOrEdit from 'ui/mixins/new-or-edit';
import { set, computed } from '@ember/object';
export default Controller.extend(NewOrEdit, {
driver: 'googlegke',
primaryResource: alias('model.cluster'),
actions: {
switchDriver(name) {
set(this, 'errors', []);
set(this, 'driver', name);
},
cancel() {
this.send('goToPrevious', 'global-admin.clusters');
},
},
sortedDrivers: computed(function() {
return [
{
name: 'googlegke',
displayName: 'Google GKE'
},
{
name: 'amazoneks',
displayName: 'Amazon EKS'
},
{
name: 'azureaks',
displayName: 'Azure AKS'
},
];
}),
doneSaving() {
this.transitionToRoute('clusters.index');
},
});
| import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { alias } from '@ember/object/computed';
import NewOrEdit from 'ui/mixins/new-or-edit';
import { set, computed } from '@ember/object';
export default Controller.extend(NewOrEdit, {
driver: 'googlegke',
primaryResource: alias('model.cluster'),
actions: {
switchDriver(name) {
set(this, 'driver', name);
},
cancel() {
this.send('goToPrevious', 'global-admin.clusters');
},
},
sortedDrivers: computed(function() {
return [
{
name: 'googlegke',
displayName: 'Google GKE'
},
{
name: 'amazoneks',
displayName: 'Amazon EKS'
},
{
name: 'azureaks',
displayName: 'Azure AKS'
},
];
}),
doneSaving() {
this.transitionToRoute('clusters.index');
},
});
|
Use pkg_resources.get_distribution instead of .require for version | """
dj-stripe - Django + Stripe Made Easy
"""
import pkg_resources
from django.apps import AppConfig
__version__ = pkg_resources.get_distribution("dj-stripe").version
default_app_config = "djstripe.DjstripeAppConfig"
class DjstripeAppConfig(AppConfig):
"""
An AppConfig for dj-stripe which loads system checks
and event handlers once Django is ready.
"""
name = "djstripe"
def ready(self):
import stripe
from . import ( # noqa: Register the checks and event handlers
checks,
event_handlers,
)
# Set app info
# https://stripe.com/docs/building-plugins#setappinfo
stripe.set_app_info(
"dj-stripe",
version=__version__,
url="https://github.com/dj-stripe/dj-stripe",
)
| """
dj-stripe - Django + Stripe Made Easy
"""
import pkg_resources
from django.apps import AppConfig
__version__ = pkg_resources.require("dj-stripe")[0].version
default_app_config = "djstripe.DjstripeAppConfig"
class DjstripeAppConfig(AppConfig):
"""
An AppConfig for dj-stripe which loads system checks
and event handlers once Django is ready.
"""
name = "djstripe"
def ready(self):
import stripe
from . import ( # noqa: Register the checks and event handlers
checks,
event_handlers,
)
# Set app info
# https://stripe.com/docs/building-plugins#setappinfo
stripe.set_app_info(
"dj-stripe",
version=__version__,
url="https://github.com/dj-stripe/dj-stripe",
)
|
Fix an Error in Main.js | $(document).ready(function(event){
$('#submit').click(function(event){
getData();
});
$('#formThing').submit(function(event){
event.preventDefault();
getData();
});
});
function getData(){
$.get('https://api.github.com/users/' + $('#inputText').val(), "", function(data){
var Avatar = "https://api.github.com/users/" + data['user']['id'] + "/avatar";
var Username = data['user']['username'];
var url = data['url'];
var lastPlayed = "None";
var joined = data['createdAt'];
var html = '<center><img src="' + Avatar + '"width="100px" height="100px" style="border:3px solid #fff">';
html += '<h1>' + Username + '</h1>';
html += '<br><b>url: </b>' + url;
});;
}
| $(document).ready(function(event){
$('#submit').click(function(event){
getData();
});
$('#formThing').submit(function(event){
event.preventDefault();
getData();
});
});
function getData(){
$.get('https://api.github.com/users' + $('#inputText').val(), "", function(data){
var Avatar = "https://api.github.com/users/" + data['user']['id'] + "/avatar";
var Username = data['user']['username'];
var url = data['url'];
var lastPlayed = "None";
var joined = data['createdAt'];
var html = '<center><img src="' + Avatar + '"width="100px" height="100px" style="border:3px solid #fff">';
html += '<h1>' + Username + '</h1>';
html += '<br><b>url: </b>' + url;
});;
} |
Add a test for the comma-dangle change | // This file should pass linting based on the tweaks made to the standard,
// standard-jsx and standard-react presets.
import React from 'react'
// Allow == for typeof, which always returns a string
// Require Stroustrup brace style - else/catch etc. on a new line
if (typeof global == 'object') {
console.log('global')
}
else if (typeof window == 'object') {
console.log('window')
}
// Braces can be on same line
if (typeof window.__DATA__) { console.log('data') }
// A space after function name convention is not enforced either way
function space () {
return 'space!'
}
function noSpace() {
return 'no space!'
}
// Dangling commas are allowed on multiline literals
let object = {
a: 1,
b: 2,
c: 3,
}
let array = [
1,
2,
3,
]
console.log(object, array)
let OtherComponent = () => <h2>Test</h2>
let TestComponent = React.createClass({
render() {
// Multiline JSX statements don't need wrapping parens
return <div className="test">
{/* Declaration of propTypes is not enforced */}
<h1>Test {this.props.name}</h1>
{/* Self-closing of components without children is not enforced */}
<OtherComponent></OtherComponent>
{`${space()} ${noSpace()}`}
{/* Spacing before self-closing is not enforced */}
<OtherComponent test/>
<OtherComponent test />
</div>
}
})
export default TestComponent
| // This file should pass linting based on the tweaks made to the standard,
// standard-jsx and standard-react presets.
import React from 'react'
// Allow == for typeof, which always returns a string
// Require Stroustrup brace style - else/catch etc. on a new line
if (typeof global == 'object') {
console.log('global')
}
else if (typeof window == 'object') {
console.log('window')
}
// Braces can be on same line
if (typeof window.__DATA__) { console.log('data') }
// A space after function name convention is not enforced either way
function space () {
return 'space!'
}
function noSpace() {
return 'no space!'
}
let OtherComponent = () => <h2>Test</h2>
let TestComponent = React.createClass({
render() {
// Multiline JSX statements don't need wrapping parens
return <div className="test">
{/* Declaration of propTypes is not enforced */}
<h1>Test {this.props.name}</h1>
{/* Self-closing of components without children is not enforced */}
<OtherComponent></OtherComponent>
{`${space()} ${noSpace()}`}
{/* Spacing before self-closing is not enforced */}
<OtherComponent test/>
<OtherComponent test />
</div>
}
})
export default TestComponent
|
Change Ti.Platform.name to Ti.Platform.osname in Anvil for Tizen calls | /*
* Appcelerator Titanium Mobile
* Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
module.exports = new function() {
var finish;
var valueOf;
this.init = function(testUtils) {
finish = testUtils.finish;
valueOf = testUtils.valueOf;
}
this.name = "jss";
this.tests = [
{name: "platform_jss_dirs"}
]
this.platform_jss_dirs = function(testRun) {
var test = Ti.UI.createView({ id: "test" });
valueOf(testRun, test).shouldNotBeNull();
if (Ti.Platform.name == "android") {
valueOf(testRun, test.backgroundColor).shouldBe("red");
} else if (Ti.Platform.osname == "tizen") {
// In Tizen, test.backgroundColor is undefined by default.
valueOf(testRun, test.backgroundColor).shouldBeUndefined();
} else {
valueOf(testRun, test.backgroundColor).shouldBe("blue");
}
finish(testRun);
}
}
| /*
* Appcelerator Titanium Mobile
* Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
module.exports = new function() {
var finish;
var valueOf;
this.init = function(testUtils) {
finish = testUtils.finish;
valueOf = testUtils.valueOf;
}
this.name = "jss";
this.tests = [
{name: "platform_jss_dirs"}
]
this.platform_jss_dirs = function(testRun) {
var test = Ti.UI.createView({ id: "test" });
valueOf(testRun, test).shouldNotBeNull();
if (Ti.Platform.name == "android") {
valueOf(testRun, test.backgroundColor).shouldBe("red");
} else if (Ti.Platform.name == "tizen") {
// In Tizen, test.backgroundColor is undefined by default.
valueOf(testRun, test.backgroundColor).shouldBeUndefined();
} else {
valueOf(testRun, test.backgroundColor).shouldBe("blue");
}
finish(testRun);
}
}
|
Update comments; Remove demo file include | <?php
/*
Plugin Name: ZnWP Entity Collection Taxonomy Plugin
Plugin URI: https://github.com/zionsg/ZnWP-Entity-Collection-Taxonomy-Plugin
Description: This plugin allows multiple 3rd party plugins to easily add custom entity & collection taxonomies and register with custom post types via an action hook. Collections can be color coded and entities can be grouped under multiple collections. Default terms for each taxonomy are added during activation and removed during deactivation of the 3rd party plugin. Posts are linked to entities not collections - the latter is for visual grouping only. Demo plugin included.
Author: Zion Ng
Author URI: http://intzone.com/
Version: 1.0.0
*/
require_once 'ZnWP_Entity_Collection_Taxonomy.php'; // PSR-1 states files should not declare classes AND execute code
$znwp_entity_collection_taxonomy_plugin = new ZnWP_Entity_Collection_Taxonomy();
register_activation_hook(__FILE__, array($znwp_entity_collection_taxonomy_plugin, 'on_activation'));
register_deactivation_hook(__FILE__, array($znwp_entity_collection_taxonomy_plugin, 'on_deactivation'));
register_uninstall_hook(__FILE__, array($znwp_entity_collection_taxonomy_plugin, 'on_uninstall'));
// must be run after theme setup to allow functions.php in theme to add filter hook
add_action('after_setup_theme', array($znwp_entity_collection_taxonomy_plugin, 'init'));
| <?php
/*
Plugin Name: ZnWP Entity Collection Taxonomy Plugin
Plugin URI: https://github.com/zionsg/ZnWP-Entity-Collection-Taxonomy-Plugin
Description: This plugin allows 3rd party plugins to easily add custom taxonomies for entities and collections and register with custom post types via an action hook. Collections can be color coded and entities can be linked to multiple collections. Default terms for each taxonomy can be added during activation and removed during deactivation of the 3rd party plugin. Demo code included at end of main plugin file.
Author: Zion Ng
Author URI: http://intzone.com/
Version: 1.0.0
*/
require_once 'ZnWP_Entity_Collection_Taxonomy.php'; // PSR-1 states files should not declare classes AND execute code
$znwp_entity_collection_taxonomy_plugin = new ZnWP_Entity_Collection_Taxonomy();
register_activation_hook(__FILE__, array($znwp_entity_collection_taxonomy_plugin, 'on_activation'));
register_deactivation_hook(__FILE__, array($znwp_entity_collection_taxonomy_plugin, 'on_deactivation'));
register_uninstall_hook(__FILE__, array($znwp_entity_collection_taxonomy_plugin, 'on_uninstall'));
// must be run after theme setup to allow functions.php in theme to add filter hook
add_action('after_setup_theme', array($znwp_entity_collection_taxonomy_plugin, 'init'));
/* DEMO CODE - Uncomment the following code to see the plugin in action */
// include 'demo.php';
|
Print out inputstream from eksamensplan | import java.net.*;
import udir.types.eksamensplan.*;
import javax.xml.bind.*;
import java.io.*;
public class EksamensplanExample {
private static String baseAddress = "https://eksamen-sas.udir.no";
public static void main(String[] args) throws Exception{
String uri = baseAddress + "/api/ekstern/eksamensplan";
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
JAXBContext jc = JAXBContext.newInstance(EksamensplanResponse.class);
InputStream xml = connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(xml));
String line = null;
while((line = in.readLine()) != null) {
System.out.println(line);
}
connection.disconnect();
}
} | import java.net.*;
import udir.types.eksamensplan.*;
import javax.xml.bind.*;
import java.io.*;
public class EksamensplanExample {
private static String baseAddress = "https://eksamen-sas.udir.no";
public static void main(String[] args) throws Exception{
String uri = baseAddress + "/api/ekstern/eksamensplan";
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
JAXBContext jc = JAXBContext.newInstance(EksamensplanResponse.class);
InputStream xml = connection.getInputStream();
EksamensplanResponse eksamensplaner = (EksamensplanResponse) jc.createUnmarshaller().unmarshal(xml);
System.out.println("Fagkoder i eksamensplanen:");
for(EksamensplanType eksamensplan : eksamensplaner.getEksamensplaner().getEksamensplan())
{
for(EksamenType eksamen : eksamensplan.getEksamener().getEksamen())
{
System.out.println(eksamen.getFagkode());
}
}
connection.disconnect();
}
} |
Adjust dimensions on window resize | document.addEventListener('DOMContentLoaded', onDocumentReady, false);
function onDocumentReady() {
var aside = document.querySelector('aside');
var section = document.querySelector('section');
var resizer = document.querySelector('.vertical-resizer');
resizer.addEventListener('mousedown', startDrag, false);
var startX, startY, startWidth, startHeight;
function startDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(aside).width, 10);
document.documentElement.addEventListener('mousemove', drag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function drag(e) {
aside.style.width = (startWidth + e.clientX - startX) + 'px';
section.style.width = (window.innerWidth - parseInt(document.defaultView.getComputedStyle(aside).width, 10)) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', drag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
window.addEventListener('resize', windowResized, false);
function windowResized() {
var asidePercentage = parseInt(document.defaultView.getComputedStyle(aside).width, 10) * 100 / window.innerWidth;
aside.style.width = asidePercentage + '%';
section.style.width = (100 - asidePercentage) + '%';
}
}
| document.addEventListener('DOMContentLoaded', onDocumentReady, false);
function onDocumentReady() {
var aside = document.querySelector('aside');
var section = document.querySelector('section');
var resizer = document.querySelector('.vertical-resizer');
resizer.addEventListener('mousedown', startDrag, false);
var startX, startY, startWidth, startHeight;
function startDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(aside).width, 10);
document.documentElement.addEventListener('mousemove', drag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function drag(e) {
aside.style.width = (startWidth + e.clientX - startX) + 'px';
section.style.width = (window.innerWidth - parseInt(document.defaultView.getComputedStyle(aside).width, 10)) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', drag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
}
|
Add reload routines to DebianUtils plugin
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk> | # -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
__version__ = "1"
__author__ = 'Chris Lamb <chris@chris-lamb.co.uk>'
__contributors__ = {}
__url__ = ''
basedir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
if basedir not in sys.path:
sys.path.append(basedir)
import DebianDevelChangesBot
reload(DebianDevelChangesBot)
import config
import plugin
reload(plugin)
Class = plugin.Class
configure = config.configure
| # -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
__version__ = "1"
__author__ = 'Chris Lamb <chris@chris-lamb.co.uk>'
__contributors__ = {}
__url__ = ''
basedir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
if basedir not in sys.path:
sys.path.append(basedir)
import config
import plugin
reload(plugin)
Class = plugin.Class
configure = config.configure
|
Read app secret from environment | var process = require('process');
module.exports = {
auth : {
local : {
subnets : [ "192.168.1.0/24", "127.0.0.1/32" ]
},
github : {
/*
* FIXME: Authentication mechanism is improperly implemented.
*
* - Username checkup seems a little strange
* - appSecret should remain secret!
*/
appId: 'edfc013fd01cf9d52a31',
appSecret: process.env.TELLDUS_APP_SECRET,
callbackURL : 'http://akrasia.ujo.guru:7173/auth/github/callback',
username : "Zeukkari"
}
},
/*
* Device bridge
*
* Trigger on/off commands from remotes
*/
bridge : {
5 : { "script" : "bin/alarm.sh" },
8 : { "script" : "bin/alarm.sh" },
7 : { "script" : "bin/pdu.sh" },
6 : { "bridgeTo" : 4 }
}
} | module.exports = {
auth : {
github: {
appId: 'edfc013fd01cf9d52a31',
appSecret: 'a9ebb79267b7d968f10e9004724a9d9ac817a8ee',
callbackURL : 'http://akrasia.ujo.guru:7173/auth/github/callback',
username : "Zeukkari"
},
local : {
subnets : [ "192.168.1.0/24", "127.0.0.1/32" ]
}
},
/*
* Device bridge
*
* Trigger on/off commands from remotes
*/
bridge : {
5 : { "script" : "bin/alarm.sh" },
8 : { "script" : "bin/alarm.sh" },
7 : { "script" : "bin/pdu.sh" },
8 : { "bridgeTo" : 7 },
6 : { "bridgeTo" : 4 }
}
}; |
Tidy types
Make class final and remove unused ctor/setter
git-svn-id: 7c053b8fbd1fb5868f764c6f9536fc6a9bbe7da9@804702 13f79535-47bb-0310-9956-ffa450edef68 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.testelement.property;
import java.util.Collection;
import java.util.Iterator;
public class PropertyIteratorImpl implements PropertyIterator {
private final Iterator<JMeterProperty> iter;
public PropertyIteratorImpl(Collection<JMeterProperty> value) {
iter = value.iterator();
}
/** {@inheritDoc} */
public boolean hasNext() {
return iter.hasNext();
}
/** {@inheritDoc} */
public JMeterProperty next() {
return iter.next();
}
/** {@inheritDoc} */
public void remove() {
iter.remove();
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.testelement.property;
import java.util.Collection;
import java.util.Iterator;
public class PropertyIteratorImpl implements PropertyIterator {
Iterator iter;
public PropertyIteratorImpl(Collection value) {
iter = value.iterator();
}
public PropertyIteratorImpl() {
}
public void setCollection(Collection value) {
iter = value.iterator();
}
public boolean hasNext() {
return iter.hasNext();
}
public JMeterProperty next() {
return (JMeterProperty) iter.next();
}
/**
* @see org.apache.jmeter.testelement.property.PropertyIterator#remove()
*/
public void remove() {
iter.remove();
}
}
|
Fix sqlalchemy import alias in DB migration file | """Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sa.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
| """Add new Indexes for faster searching
Revision ID: 3097d57f3f0b
Revises: 4fe230f7a26e
Create Date: 2021-06-19 20:18:55.332165
"""
# revision identifiers, used by Alembic.
revision = '3097d57f3f0b'
down_revision = '4fe230f7a26e'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_index(
'ix_root_authority_id',
'certificates',
['root_authority_id'],
unique=False,
postgresql_where=sqlalchemy.text("root_authority_id IS NOT NULL"))
op.create_index(
'certificate_associations_certificate_id_idx',
'certificate_associations',
['certificate_id'],
unique=False)
op.create_index(
'ix_certificates_serial',
'certificates',
['serial'],
unique=False)
def downgrade():
op.drop_index(
'ix_root_authority_id',
table_name='certificates')
op.drop_index(
'certificate_associations_certificate_id_idx',
table_name='certificate_associations')
op.drop_index(
'ix_certificates_serial',
table_name='certificates')
|
Add cwd option to sonar client. Update to execFile instead of spawn | const {
execFile
} = require("child_process");
const options = {
sources: function (path) {
return `-Dsonar.sources="${path}"`;
},
projectName: function (name) {
return `-Dsonar.projectName="${name}"`;
},
projectKey: function (owner, name) {
return `-Dsonar.projectKey="${owner}:${name}"`;
}
}
/**
* Make sure to:
* 1. Have sonar-scanner added to PATH
* 2. Update the global settings to point to your SonarQube server by editing <install_directory>/conf/sonar-scanner.properties.
*/
module.exports = {
startSonar: function (repo, pathToSources, cwd) {
return execFile("sonar-scanner", [projectKey(repo.owner, repo.name), projectName(repo.name), sources(pathToSources)], {
cwd: cwd
});
}
}; | const {
spawn
} = require("child_process");
const options = {
sources: function (path) {
return `-Dsonar.sources="${path}"`;
},
projectName: function (name) {
return `-Dsonar.projectName="${name}"`;
},
projectKey: function (owner, name) {
return `-Dsonar.projectKey="${owner}:${name}"`;
}
}
/**
* Make sure to:
* 1. Have sonar-scanner added to PATH
* 2. Update the global settings to point to your SonarQube server by editing <install_directory>/conf/sonar-scanner.properties.
*/
module.exports = {
startSonar: function (repo, pathToSources) {
return spawn("sonar-scanner", [projectKey(repo.owner, repo.name), projectName(repo.name), sources(pathToSources)]);
}
}; |
Comment find() with line comment
The result depends on the running environment of buck command and IDE | package search.tree;// Copyright 2016 The Sawdust 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.
//
import org.junit.Test;
public class FileTreeRecursionTest {
@Test(timeout = 100000L, expected = Test.None.class)
public void test() {
// try {
// String find = "BUCK";
// File from = new File("./../");
// List<File> r = new LinkedList<>();
// FileTreeRecursion.find(from.getCanonicalFile(), find, r);
// for (File f : r) {
// System.out.println(f.getCanonicalPath());
// }
// } catch (IOException e) {
// //
// }
}
}
| package search.tree;// Copyright 2016 The Sawdust 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.
//
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class FileTreeRecursionTest {
@Test(timeout = 100L, expected = Test.None.class)
public void test() {
try {
List<File> r = new LinkedList<>();
FileTreeRecursion.find(new File("../").getCanonicalFile() , "BUCK", r);
Assert.assertEquals(r.get(0).getName(), "BUCK");
} catch (IOException e) {
//
}
}
}
|
Include schdule css into barebone template | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Joutes - Schedule</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
<link href="{{ asset('css/schedule.css') }}" rel="stylesheet" type="text/css" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<title>Laravel</title>
</head>
<body>
<div id="page">
<div id="content">
@yield('content')
</div><!-- content -->
</div><!-- page -->
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Joutes - Schedule</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<title>Laravel</title>
</head>
<body>
<div id="page">
<div id="content">
@yield('content')
</div><!-- content -->
</div><!-- page -->
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
|
[LP-1965] Change authentication classes to cater inactive users | from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from edx_rest_framework_extensions.auth.session.authentication import SessionAuthenticationAllowInactiveUser
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from openedx.features.idea.models import Idea
class FavoriteAPIView(APIView):
"""
FavoriteAPIView is used to toggle favorite idea for the user
"""
authentication_classes = (SessionAuthenticationAllowInactiveUser,)
permission_classes = (IsAuthenticated,)
def post(self, request, idea_id):
response = {'message': 'Idea is added to favorites', 'is_idea_favorite': True}
toggle_status = status.HTTP_201_CREATED
user = request.user
idea = get_object_or_404(Idea, pk=idea_id)
toggle_favorite_status = idea.toggle_favorite(user)
if not toggle_favorite_status:
response['is_idea_favorite'] = False
response['message'] = 'Idea is removed from favorites'
toggle_status = status.HTTP_200_OK
response['favorite_count'] = idea.favorites.count()
return JsonResponse(response, status=toggle_status)
| from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from openedx.features.idea.models import Idea
class FavoriteAPIView(APIView):
"""
FavoriteAPIView is used to toggle favorite idea for the user
"""
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def post(self, request, idea_id):
response = {'message': 'Idea is added to favorites', 'is_idea_favorite': True}
toggle_status = status.HTTP_201_CREATED
user = request.user
idea = get_object_or_404(Idea, pk=idea_id)
toggle_favorite_status = idea.toggle_favorite(user)
if not toggle_favorite_status:
response['is_idea_favorite'] = False
response['message'] = 'Idea is removed from favorites'
toggle_status = status.HTTP_200_OK
response['favorite_count'] = idea.favorites.count()
return JsonResponse(response, status=toggle_status)
|
Trim trailing whitespace, add missing semicolon | function main() {
$('#tabs').tabs();
google.load('visualization', '1', {packages: ['geochart']});
google.setOnLoadCallback(googleReady);
var commodities_select=[];
dojo.ready(chosenDojo);
//Management of the selection
$('select').on('change', function(event) {
var select_object = dojo.byId('select');
var select_div = dojo.byId('msg');
var selected_values = [];
for (var x=0; x<=select_object.length; x++) {
if (select_object[x] && select_object[x].selected) {
selected_values.push(select_object[x].value);
}
}
select_div.innerHTML = 'Selected value = ' + selected_values;
console.log(selected_values);
});
}
//Function to launch the googleAPI
function googleReady() {
init_import_export();
init_hscodes();
worldMap();
usaMap();
}
//Function to configure options of chosen-dojo commodities selector
function chosenDojo() {
dojo.query(".chzn-select").chosen();
dojo.query(".chzn-select-deselect").chosen({allow_single_deselect:true});
dojo.query(".chzn-select-batch").chosen({batch_select:true});
}
$(main);
| function main() {
$('#tabs').tabs();
google.load('visualization', '1', {packages: ['geochart']});
google.setOnLoadCallback(googleReady);
var commodities_select=[];
dojo.ready(chosenDojo);
//Management of the selection
$('select').on('change', function(event) {
var select_object = dojo.byId('select');
var select_div = dojo.byId('msg');
var selected_values = [];
for (x=0;x<=select_object.length;x++) {
if (select_object[x] && select_object[x].selected) {
selected_values.push(select_object[x].value);
}
}
select_div.innerHTML = 'Selected value = ' + selected_values;
console.log(selected_values)
});
}
//Function to launch the googleAPI
function googleReady() {
init_import_export();
init_hscodes();
worldMap();
usaMap();
}
//Function to configure options of chosen-dojo commodities selector
function chosenDojo() {
dojo.query(".chzn-select").chosen();
dojo.query(".chzn-select-deselect").chosen({allow_single_deselect:true});
dojo.query(".chzn-select-batch").chosen({batch_select:true});
}
$(main);
|
Remove useless var in store | import Reflux from 'reflux';
import Actions from './Actions';
import Handlers from './Handlers';
export default class Store extends Reflux.Store {
constructor() {
super();
this.state = {
retrievingLocation: false,
fetchingData: false,
radius: process.env.REACT_APP_DEFAULT_RADIUS,
address: null,
latitude: null,
longitude: null,
restaurant: null
};
this.handlers = new Handlers();
this.listenables = [Actions];
}
onGetCurrentLocation() {
this.handlers.getCurrentLocation(this);
}
onSetCurrentLocation(latitude, longitude) {
this.handlers.setCurrentLocation(this, latitude, longitude);
}
onGetCurrentAddress() {
this.handlers.getCurrentAddress(this);
}
onSetCurrentAddress(address) {
this.handlers.setCurrentAddress(this, address);
}
onSelectRestaurant() {
this.handlers.selectRestaurant(this);
}
onGetRestaurant(id) {
this.handlers.getRestaurant(this, id);
}
onGetDirections() {
this.handlers.getDirections(this);
}
onSetDirectionsLink() {
this.handlers.setDirectionsLink(this);
}
onReduceSearchRadius() {
this.handlers.reduceSearchRadius(this);
}
onExcludeCurrentCategory() {
this.handlers.excludeCurrentCategory(this);
}
}
| import Reflux from 'reflux';
import Actions from './Actions';
import Handlers from './Handlers';
export default class Store extends Reflux.Store {
constructor() {
super();
this.state = {
retrievingLocation: false,
fetchingData: false,
radius: process.env.REACT_APP_DEFAULT_RADIUS,
address: null,
latitude: null,
longitude: null,
restaurant: null,
excludedCategories: []
};
this.handlers = new Handlers();
this.listenables = [Actions];
}
onGetCurrentLocation() {
this.handlers.getCurrentLocation(this);
}
onSetCurrentLocation(latitude, longitude) {
this.handlers.setCurrentLocation(this, latitude, longitude);
}
onGetCurrentAddress() {
this.handlers.getCurrentAddress(this);
}
onSetCurrentAddress(address) {
this.handlers.setCurrentAddress(this, address);
}
onSelectRestaurant() {
this.handlers.selectRestaurant(this);
}
onGetRestaurant(id) {
this.handlers.getRestaurant(this, id);
}
onGetDirections() {
this.handlers.getDirections(this);
}
onSetDirectionsLink() {
this.handlers.setDirectionsLink(this);
}
onReduceSearchRadius() {
this.handlers.reduceSearchRadius(this);
}
onExcludeCurrentCategory() {
this.handlers.excludeCurrentCategory(this);
}
}
|
Add PickleEncoder to the public API | __version__ = '1.16.14'
from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip
from data import \
IdProvider, UuidProvider, UserSpecifiedIdProvider, StaticIdProvider, \
KeyBuilder, StringDelimitedKeyBuilder, Database, FileSystemDatabase, \
InMemoryDatabase
from datawriter import DataWriter
from database_iterator import DatabaseIterator
from encoder import IdentityEncoder, PickleEncoder
from decoder import Decoder, PickleDecoder
from lmdbstore import LmdbDatabase
from objectstore import ObjectStoreDatabase
from persistence import PersistenceSettings
from iteratornode import IteratorNode
from eventlog import EventLog, RedisChannel
try:
from nmpy import NumpyEncoder, PackedNumpyEncoder, StreamingNumpyDecoder, \
BaseNumpyDecoder, NumpyMetaData, NumpyFeature
except ImportError:
pass
| __version__ = '1.16.14'
from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip
from data import \
IdProvider, UuidProvider, UserSpecifiedIdProvider, StaticIdProvider, \
KeyBuilder, StringDelimitedKeyBuilder, Database, FileSystemDatabase, \
InMemoryDatabase
from datawriter import DataWriter
from database_iterator import DatabaseIterator
from encoder import IdentityEncoder
from decoder import Decoder, PickleDecoder
from lmdbstore import LmdbDatabase
from objectstore import ObjectStoreDatabase
from persistence import PersistenceSettings
from iteratornode import IteratorNode
from eventlog import EventLog, RedisChannel
try:
from nmpy import NumpyEncoder, PackedNumpyEncoder, StreamingNumpyDecoder, \
BaseNumpyDecoder, NumpyMetaData, NumpyFeature
except ImportError:
pass
|
Check dashboard stubs based on page-type
Instead of maintaining a regex of blacklisted files, just assume anything that isn't a dashboard isn't a dashboard. | var fs = require('fs'),
path = require('path'),
_ = require('lodash'),
glob = require('glob'),
Q = require('q');
var stagecraftStubDir = path.resolve(__dirname, '..', 'app', 'support', 'stagecraft_stub', 'responses'),
stagecraftStubGlob = path.resolve(stagecraftStubDir, '*.json');
var services = [];
function readModule(file) {
var defer = Q.defer();
fs.readFile(file, 'utf8', function (err, dashboardData) {
if (err) {
if (err.code === 'EISDIR') {
defer.resolve();
return;
} else {
defer.reject(err);
throw err;
}
}
dashboardData = JSON.parse(dashboardData);
if (dashboardData['page-type'] === 'dashboard') {
services.push(_.pick(dashboardData, 'slug', 'title', 'department', 'agency', 'dashboard-type'));
}
defer.resolve();
});
return defer.promise;
}
glob(stagecraftStubGlob, function (err, files) {
if (err) {
throw err;
}
Q.all(_.map(files, function (file) {
return readModule(file);
})).then(function () {
console.log('Writing ' + services.length + ' services into services.json');
fs.writeFileSync(stagecraftStubDir + '/services.json', JSON.stringify({ items: services }, null, 2) + '\n');
});
});
| var fs = require('fs'),
path = require('path'),
_ = require('lodash'),
glob = require('glob'),
Q = require('q');
var stagecraftStubDir = path.resolve(__dirname, '..', 'app', 'support', 'stagecraft_stub', 'responses'),
stagecraftStubGlob = path.resolve(stagecraftStubDir, '*.json'),
ignoreFileRegexp = /services\.json|unimplemented-page-type\.json/;
var services = [];
function readModule(file) {
var defer = Q.defer();
fs.readFile(file, 'utf8', function (err, dashboardData) {
if (err) {
if (err.code === 'EISDIR') {
return;
} else {
defer.reject(err);
throw err;
}
}
dashboardData = JSON.parse(dashboardData);
services.push(_.pick(dashboardData, 'slug', 'title', 'department', 'agency', 'dashboard-type'));
defer.resolve();
});
return defer.promise;
}
glob(stagecraftStubGlob, function (err, files) {
if (err) {
throw err;
}
Q.all(_.map(files, function (file) {
if (!ignoreFileRegexp.test(file)) {
return readModule(file);
}
})).then(function () {
console.log('Writing ' + services.length + ' services into services.json');
fs.writeFileSync(stagecraftStubDir + '/services.json', JSON.stringify({ items: services }, null, 2) + '\n');
});
});
|
Move $session_timeout & $session_path inside the if statement | <?php
namespace Grav\Common;
/**
* Wrapper for Session
*/
class Session extends \RocketTheme\Toolbox\Session\Session
{
protected $grav;
protected $session;
public function __construct(Grav $grav)
{
$this->grav = $grav;
}
public function init()
{
/** @var Uri $uri */
$uri = $this->grav['uri'];
$config = $this->grav['config'];
if ($config->get('system.session.enabled')) {
$session_timeout = $config->get('system.session.timeout', 1800);
$session_path = $config->get('system.session.path', '/' . ltrim($uri->rootUrl(false), '/'));
// Define session service.
parent::__construct(
$session_timeout,
$session_path
);
$site_identifier = $config->get('site.title', 'unkown');
$this->setName($config->get('system.session.name', 'grav_site') . '_' . substr(md5($site_identifier), 0, 7));
$this->start();
setcookie(session_name(), session_id(), time() + $session_timeout, $session_path);
}
}
}
| <?php
namespace Grav\Common;
/**
* Wrapper for Session
*/
class Session extends \RocketTheme\Toolbox\Session\Session
{
protected $grav;
protected $session;
public function __construct(Grav $grav)
{
$this->grav = $grav;
}
public function init()
{
/** @var Uri $uri */
$uri = $this->grav['uri'];
$config = $this->grav['config'];
$session_timeout = $config->get('system.session.timeout', 1800);
$session_path = $config->get('system.session.path', '/' . ltrim($uri->rootUrl(false), '/'));
if ($config->get('system.session.enabled')) {
// Define session service.
parent::__construct(
$session_timeout,
$session_path
);
$site_identifier = $config->get('site.title', 'unkown');
$this->setName($config->get('system.session.name', 'grav_site') . '_' . substr(md5($site_identifier), 0, 7));
$this->start();
setcookie(session_name(), session_id(), time() + $session_timeout, $session_path);
}
}
}
|
Fix flakiness from random seed generator
Signed-off-by: Sebastian Vidrio <68ba84219e4e2d7d15fed3ed668bd2821314e420@pivotal.io> | package randomword_test
import (
"time"
. "code.cloudfoundry.org/cli/util/randomword"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Generator", func() {
var gen Generator
BeforeEach(func() {
gen = Generator{}
})
Describe("RandomAdjective", func() {
It("generates a random adjective each time it is called", func() {
adj := gen.RandomAdjective()
// We wait for 3 millisecond because the seed we use to generate the
// randomness has a unit of 1 nanosecond plus random test flakiness
time.Sleep(3)
Expect(adj).ToNot(Equal(gen.RandomAdjective()))
})
})
Describe("RandomNoun", func() {
It("generates a random noun each time it is called", func() {
noun := gen.RandomNoun()
// We wait for 3 millisecond because the seed we use to generate the
// randomness has a unit of 1 nanosecond plus random test flakiness
time.Sleep(3)
Expect(noun).ToNot(Equal(gen.RandomNoun()))
})
})
Describe("Babble", func() {
It("generates a random adjective noun pair each time it is called", func() {
wordPair := gen.Babble()
Expect(wordPair).To(MatchRegexp("^\\w+-\\w+$"))
})
})
})
| package randomword_test
import (
"time"
. "code.cloudfoundry.org/cli/util/randomword"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Generator", func() {
var gen Generator
BeforeEach(func() {
gen = Generator{}
})
Describe("RandomAdjective", func() {
It("generates a random adjective each time it is called", func() {
adj := gen.RandomAdjective()
// We wait for 1 millisecond because the seed we use to generate the randomness has a unit of 1 nanosecond
time.Sleep(1)
Expect(adj).ToNot(Equal(gen.RandomAdjective()))
})
})
Describe("RandomNoun", func() {
It("generates a random noun each time it is called", func() {
noun := gen.RandomNoun()
// We wait for 1 millisecond because the seed we use to generate the randomness has a unit of 1 nanosecond
time.Sleep(1)
Expect(noun).ToNot(Equal(gen.RandomNoun()))
})
})
Describe("Babble", func() {
It("generates a random adjective noun pair each time it is called", func() {
wordPair := gen.Babble()
Expect(wordPair).To(MatchRegexp("^\\w+-\\w+$"))
})
})
})
|
Fix overriding variable in problem report tag | from collections import defaultdict
from django import template
from ..models import ProblemReport
from ..forms import ProblemReportForm
register = template.Library()
@register.inclusion_tag('problem/message_toolbar_item.html')
def render_problem_button(message):
if not hasattr(message, 'problemreports'):
# Get all problem reports for all messages
request = message.request
reports = ProblemReport.objects.filter(message__in=request.messages)
message_reports = defaultdict(list)
for report in reports:
message_reports[report.message_id].append(report)
for mes in request.messages:
mes.problemreports = message_reports[mes.id]
mes.problemreports_count = len(mes.problemreports)
mes.problemreports_unresolved_count = len([
r for r in mes.problemreports if not r.resolved
])
mes.problemreports_form = ProblemReportForm(message=mes)
return {
'message': message
}
| from collections import defaultdict
from django import template
from ..models import ProblemReport
from ..forms import ProblemReportForm
register = template.Library()
@register.inclusion_tag('problem/message_toolbar_item.html')
def render_problem_button(message):
if not hasattr(message, 'problemreports'):
# Get all problem reports for all messages
request = message.request
reports = ProblemReport.objects.filter(message__in=request.messages)
message_reports = defaultdict(list)
for report in reports:
message_reports[report.message_id].append(report)
for message in request.messages:
message.problemreports = message_reports[message.id]
message.problemreports_count = len(message.problemreports)
message.problemreports_unresolved_count = len([
r for r in message.problemreports if not r.resolved
])
message.problemreports_form = ProblemReportForm(message=message)
return {
'message': message
}
|
Handle another corner case where refreshToken is undefined | import jwt from 'jsonwebtoken';
// Components
import UserDAO from './sql';
import schema from './schema.graphqls';
import createResolvers from './resolvers';
import { refreshTokens } from './auth';
import tokenMiddleware from './token';
import Feature from '../connector';
const SECRET = 'secret, change for production';
const User = new UserDAO();
export default new Feature({
schema,
createResolversFunc: createResolvers,
createContextFunc: async (req, connectionParams) => {
let tokenUser = null;
if (
connectionParams &&
connectionParams.token &&
connectionParams.token !== 'null' &&
connectionParams.token !== 'undefined'
) {
try {
const { user } = jwt.verify(connectionParams.token, SECRET);
tokenUser = user;
} catch (err) {
const newTokens = await refreshTokens(
connectionParams.token,
connectionParams.refreshToken,
User,
SECRET
);
tokenUser = newTokens.user;
}
} else if (req) {
tokenUser = req.user;
}
return {
User,
user: tokenUser,
SECRET,
req
};
},
middleware: tokenMiddleware(SECRET, User)
});
| import jwt from 'jsonwebtoken';
// Components
import UserDAO from './sql';
import schema from './schema.graphqls';
import createResolvers from './resolvers';
import { refreshTokens } from './auth';
import tokenMiddleware from './token';
import Feature from '../connector';
const SECRET = 'secret, change for production';
const User = new UserDAO();
export default new Feature({
schema,
createResolversFunc: createResolvers,
createContextFunc: async (req, connectionParams) => {
let tokenUser = null;
if (
connectionParams &&
connectionParams.token &&
connectionParams.token !== 'null'
) {
try {
const { user } = jwt.verify(connectionParams.token, SECRET);
tokenUser = user;
} catch (err) {
const newTokens = await refreshTokens(
connectionParams.token,
connectionParams.refreshToken,
User,
SECRET
);
tokenUser = newTokens.user;
}
} else if (req) {
tokenUser = req.user;
}
return {
User,
user: tokenUser,
SECRET,
req
};
},
middleware: tokenMiddleware(SECRET, User)
});
|
Adjust image size to 150k. | import capture
from picamera import PiCamera
import time
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (854, 480)
camera.rotation = 90
latest = capture.cap(camera, resolution, status)
status = latest[0]
size = capture.image_size(latest[1])
capture.copy_latest(latest[1])
day = 150000 # image size when light is good
if size > day:
wait = 60
else:
wait = 600
status = capture.shutdown(camera)
print('Next capture begins in {} seconds.'.format(wait))
time.sleep(wait)
# status = capture.shutdown(camera)
image_cap_loop(camera, status)
def main():
camera = PiCamera()
image_cap_loop(camera)
print("Images captured")
if __name__ == '__main__':
main()
| import capture
from picamera import PiCamera
import time
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (854, 480)
camera.rotation = 90
latest = capture.cap(camera, resolution, status)
status = latest[0]
size = capture.image_size(latest[1])
capture.copy_latest(latest[1])
day = 100000 # image size when light is good
if size > day:
wait = 60
else:
wait = 600
status = capture.shutdown(camera)
print('Next capture begins in {} seconds.'.format(wait))
time.sleep(wait)
# status = capture.shutdown(camera)
image_cap_loop(camera, status)
def main():
camera = PiCamera()
image_cap_loop(camera)
print("Images captured")
if __name__ == '__main__':
main()
|
Disable settings to avoid config window popping up on android | /*
* This is the main PebbleJS file. You do not need to modify this file unless
* you want to change the way PebbleJS starts, the script it runs or the libraries
* it loads.
*
* By default, this will initialize all the libraries and run app.js
*/
require('lib/safe');
//Pebble.Settings = require('settings/settings');
Pebble.Accel = require('ui/accel');
Pebble.UI = require('ui');
//Pebble.SmartPackage = require('pebble/smartpackage');
Pebble.addEventListener('ready', function(e) {
// Load the SimplyJS Pebble implementation
require('ui/simply-pebble').init();
//Pebble.Settings.init();
Pebble.Accel.init();
console.log("Done loading PebbleJS - Starting app.");
// Load local file
require('app.js');
//require('ui/tests');
// Or use Smart Package to load a remote JS file
//Pebble.SmartPackage.init('http://www.sarfata.org/myapp.js');
// or Ask the user to enter a URL to run in the Settings
//Pebble.SmartPackage.initWithSettings();
// or Load a list of app and let the user choose in the Settings which one to run.
//Pebble.SmartPackage.loadBundle('http://www.sarfata.org/myapps.json');
});
| /*
* This is the main PebbleJS file. You do not need to modify this file unless
* you want to change the way PebbleJS starts, the script it runs or the libraries
* it loads.
*
* By default, this will initialize all the libraries and run app.js
*/
require('lib/safe');
Pebble.Settings = require('settings/settings');
Pebble.Accel = require('ui/accel');
Pebble.UI = require('ui');
//Pebble.SmartPackage = require('pebble/smartpackage');
Pebble.addEventListener('ready', function(e) {
// Load the SimplyJS Pebble implementation
require('ui/simply-pebble').init();
Pebble.Settings.init();
Pebble.Accel.init();
console.log("Done loading PebbleJS - Starting app.");
// Load local file
require('app.js');
//require('ui/tests');
// Or use Smart Package to load a remote JS file
//Pebble.SmartPackage.init('http://www.sarfata.org/myapp.js');
// or Ask the user to enter a URL to run in the Settings
//Pebble.SmartPackage.initWithSettings();
// or Load a list of app and let the user choose in the Settings which one to run.
//Pebble.SmartPackage.loadBundle('http://www.sarfata.org/myapps.json');
});
|
Update package data and version number. | import os
from setuptools import setup, find_packages
VERSION = '0.2.0a1'
README_FILENAME = 'README.rst'
readme = open(os.path.join(os.path.dirname(__file__), README_FILENAME))
long_description = readme.read()
readme.close()
setup(
name='django-cbv-formpreview',
version=VERSION,
author='Ryan Kaskel',
author_email='dev@ryankaskel.com',
url='https://github.com/ryankask/django-cbv-formpreview',
license='BSD',
description='Django\'s FormPreview updated to use class based views.',
long_description=long_description,
packages=find_packages(),
package_data = {
'cbv_formpreview': ['templates/cbv_formpreview/*.html']
},
zip_safe=False,
classifiers=[
'Environment :: Web Environment',
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
test_suite='cbv_formpreview.tests.runtests.runtests'
)
| import os
from setuptools import setup, find_packages
VERSION = '0.1.3a1'
README_FILENAME = 'README.rst'
readme = open(os.path.join(os.path.dirname(__file__), README_FILENAME))
long_description = readme.read()
readme.close()
setup(
name='django-cbv-formpreview',
version=VERSION,
author='Ryan Kaskel',
author_email='dev@ryankaskel.com',
url='https://github.com/ryankask/django-cbv-formpreview',
license='BSD',
description='Django\'s FormPreview updated to use class based views.',
long_description=long_description,
packages=find_packages(),
package_data = {
'cbv_formpreview': ['templates/*.html', 'templates/formtools/*.html']
},
zip_safe=False,
classifiers=[
'Environment :: Web Environment',
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
test_suite='cbv_formpreview.tests.runtests.runtests'
)
|
Add remove button in template for pivot fields | <script id="realtionship-edit-add" type="text/x-jquery-template">
<tr>
<td>
<select class="form-control select2" name="{{ $row->field }}[]">
@foreach($relationshipOptions as $relationshipOption)
<option value="{{ $relationshipOption->{$options->relationship->key} }}" @if(in_array($relationshipOption->{$options->relationship->key}, $selected_values)){{ 'selected="selected"' }}@endif>{{ $relationshipOption->{$options->relationship->label} }}</option>
@endforeach
</select>
</td>
@foreach ($options->relationship->editablePivotFields as $pivotField)
<td><input type="text" name="pivot_{{$pivotField}}[]" class="form-control" placeholder="{{ $pivotField }}" value=""></td>
@endforeach
<td class="danger">
<button type="button" class="close form-control btn-remove-bread-relationship" aria-label="Close"><span aria-hidden="true" class="glyphicon glyphicon-remove"></span></button>
</td>
</tr>
</tr>
</script> | <script id="realtionship-edit-add" type="text/x-jquery-template">
<tr>
<td>
<select class="form-control select2" name="{{ $row->field }}[]">
@foreach($relationshipOptions as $relationshipOption)
<option value="{{ $relationshipOption->{$options->relationship->key} }}" @if(in_array($relationshipOption->{$options->relationship->key}, $selected_values)){{ 'selected="selected"' }}@endif>{{ $relationshipOption->{$options->relationship->label} }}</option>
@endforeach
</select>
</td>
@foreach ($options->relationship->editablePivotFields as $pivotField)
<td><input type="text" name="pivot_{{$pivotField}}[]" class="form-control" placeholder="{{ $pivotField }}" value=""></td>
@endforeach
</tr>
</tr>
</script> |
Configure TLS for the DockerSpawner. | import os
import re
c = get_config()
c.JupyterHub.hub_ip = '0.0.0.0'
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
c.DockerSpawner.tls_verify = True
c.DockerSpawner.tls_ca = "/etc/docker/ca.pem"
c.DockerSpawner.tls_cert = "/etc/docker/server-cert.pem"
c.DockerSpawner.tls_key = "/etc/docker/server-key.pem"
c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator'
c.JupyterHub.login_url = '/hub/oauth_login'
def userlist(varname):
"""
Interept an environment variable as a whitespace-separated list of GitHub
usernames.
"""
parts = re.split("\s*,\s*", os.environ[varname])
return set([part for part in parts if len(part) > 0])
c.Authenticator.whitelist = userlist("JUPYTERHUB_USERS")
c.Authenticator.admin_users = userlist("JUPYTERHUB_ADMINS")
c.GitHubOAuthenticator.oauth_callback_url = os.environ['OAUTH_CALLBACK_URL']
c.GitHubOAuthenticator.client_id = os.environ['GITHUB_CLIENT_ID']
c.GitHubOAuthenticator.client_secret = os.environ['GITHUB_CLIENT_SECRET']
| import os
import re
c = get_config()
c.JupyterHub.hub_ip = '0.0.0.0'
c.DockerSpawner.use_docker_client_env = True
c.DockerSpawner.tls_assert_hostname = True
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator'
c.JupyterHub.login_url = '/hub/oauth_login'
def userlist(varname):
"""
Interept an environment variable as a whitespace-separated list of GitHub
usernames.
"""
parts = re.split("\s*,\s*", os.environ[varname])
return set([part for part in parts if len(part) > 0])
c.Authenticator.whitelist = userlist("JUPYTERHUB_USERS")
c.Authenticator.admin_users = userlist("JUPYTERHUB_ADMINS")
c.GitHubOAuthenticator.oauth_callback_url = os.environ['OAUTH_CALLBACK_URL']
c.GitHubOAuthenticator.client_id = os.environ['GITHUB_CLIENT_ID']
c.GitHubOAuthenticator.client_secret = os.environ['GITHUB_CLIENT_SECRET']
|
Remove deprecated call to set_command_identifier | var Util = require("util");
var Bot = require("./lib/irc");
var YourBot = function(profile) {
Bot.call(this, profile);
this.set_log_level(this.LOG_ALL);
this.set_trigger("!"); // Exclamation
};
Util.inherits(YourBot, Bot);
YourBot.prototype.init = function() {
Bot.prototype.init.call(this);
this.register_command("ping", this.ping);
this.on('command_not_found', this.unrecognized);
};
YourBot.prototype.ping = function(cx, text) {
cx.channel.send_reply (cx.sender, "Pong!");
};
YourBot.prototype.unrecognized = function(cx, text) {
cx.channel.send_reply(cx.sender, "There is no command: "+text);
};
var profile = [{
host: "irc.freenode.net",
port: 6667,
nick: "mybot",
password: "password_to_authenticate",
user: "username",
real: "Real Name",
channels: ["#channels", "#to", "#join"]
}];
(new YourBot(profile)).init();
| var Util = require("util");
var Bot = require("./lib/irc");
var YourBot = function(profile) {
Bot.call(this, profile);
this.set_log_level(this.LOG_ALL);
this.set_command_identifier("!"); // Exclamation
};
Util.inherits(YourBot, Bot);
YourBot.prototype.init = function() {
Bot.prototype.init.call(this);
this.register_command("ping", this.ping);
this.on('command_not_found', this.unrecognized);
};
YourBot.prototype.ping = function(cx, text) {
cx.channel.send_reply (cx.sender, "Pong!");
};
YourBot.prototype.unrecognized = function(cx, text) {
cx.channel.send_reply(cx.sender, "There is no command: "+text);
};
var profile = [{
host: "irc.freenode.net",
port: 6667,
nick: "mybot",
password: "password_to_authenticate",
user: "username",
real: "Real Name",
channels: ["#channels", "#to", "#join"]
}];
(new YourBot(profile)).init();
|
Add className prop to Stats | import cc from 'classcat'
import React from 'react'
import PropTypes from 'prop-types'
import Mute from 'lib/components/Mute'
import './style'
const valueClasses = value => cc([
'Stats__value',
{ 'Stats__value--empty': !value }
])
const Stats = ({ className, items, placeholder }) => (
<div className={cc(['card-group', 'mb-3', 'Stats', className])}>
{items.map(({ title, value }, index) => (
<div className="card" key={index}>
<div className="card-body">
<div className="Stats__title">{title}</div>
<div className={valueClasses(value)}>{value || placeholder}</div>
</div>
</div>
))}
</div>
)
Stats.propTypes = {
className: PropTypes.string,
items: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.string,
value: PropTypes.any
})),
placeholder: PropTypes.oneOfType([PropTypes.string, PropTypes.node])
}
Stats.defaultProps = {
className: undefined,
items: [],
placeholder: <Mute>–</Mute>
}
export default Stats
| import cc from 'classcat'
import React from 'react'
import PropTypes from 'prop-types'
import Mute from 'lib/components/Mute'
import './style'
const valueClasses = value => cc([
'Stats__value',
{ 'Stats__value--empty': !value }
])
const Stats = ({ items, placeholder }) => (
<div className="card-group mb-3 Stats">
{items.map(({ title, value }, index) => (
<div className="card" key={index}>
<div className="card-body">
<div className="Stats__title">{title}</div>
<div className={valueClasses(value)}>{value || placeholder}</div>
</div>
</div>
))}
</div>
)
Stats.propTypes = {
items: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.string,
value: PropTypes.any
})),
placeholder: PropTypes.oneOfType([PropTypes.string, PropTypes.node])
}
Stats.defaultProps = {
items: [],
placeholder: <Mute>–</Mute>
}
export default Stats
|
Switch enabled and selector columns | import m from 'mithril';
export const OptionsDisplayTableHeader = () => ({
view() {
return m('thead', [
m('tr', [
m('th', 'Name'),
m('th', 'Pattern'),
m('th', 'Selector'),
m('th', 'Enabled'),
]),
]);
},
});
export class OptionsDisplayTableBody {
constructor(vnode) {
this.options = vnode.attrs.options;
}
view() {
return m(
'tbody',
this.options.map(option => {
return m(OptionsDisplayTableRow, { option, key: option.name });
})
);
}
}
export class OptionsDisplayTableRow {
constructor(vnode) {
this.option = vnode.attrs.option;
}
view() {
const { name, pattern, enabled, selector } = this.option;
return m('tr', [
m('td', name),
m('td', m('pre', pattern.toString())),
m('td', selector),
m('td', enabled),
]);
}
}
export class OptionsDisplayTable {
view(vnode) {
const { options } = vnode.attrs;
return m('table.table.table-bordered', [
m(OptionsDisplayTableHeader),
m(OptionsDisplayTableBody, { options }),
]);
}
}
| import m from 'mithril';
export const OptionsDisplayTableHeader = () => ({
view() {
return m('thead', [
m('tr', [
m('th', 'Name'),
m('th', 'Pattern'),
m('th', 'Enabled'),
m('th', 'Selector'),
]),
]);
},
});
export class OptionsDisplayTableBody {
constructor(vnode) {
this.options = vnode.attrs.options;
}
view() {
return m(
'tbody',
this.options.map(option => {
return m(OptionsDisplayTableRow, { option, key: option.name });
})
);
}
}
export class OptionsDisplayTableRow {
constructor(vnode) {
this.option = vnode.attrs.option;
}
view() {
const { name, pattern, enabled, selector } = this.option;
return m('tr', [
m('td', name),
m('td', m('pre', pattern.toString())),
m('td', enabled),
m('td', selector),
]);
}
}
export class OptionsDisplayTable {
view(vnode) {
const { options } = vnode.attrs;
return m('table.table.table-bordered', [
m(OptionsDisplayTableHeader),
m(OptionsDisplayTableBody, { options }),
]);
}
}
|
Remove Regex validation on Throttle | /**
* A rate-limiting Throttle model, by IP address
*
*/
var mongoose = require('mongoose')
var Schema = mongoose.Schema
mongoose.Promise = global.Promise
/**
* Register the Throttle model
*
* @access public
* @param {object} defaults
* @return {object} Mongoose Model
*/
module.exports = function createThrottle (defaults) {
if (defaults.mongoose.uri) {
mongoose.createConnection(defaults.mongoose.uri)
}
if (!mongoose.connection.readyState) {
console.warn('MongoDB connection not set. Skipping. Fix this by specifying the mongoose:uri option.')
}
var Throttle = new Schema({
createdAt: {
type: Date,
required: true,
default: Date.now,
expires: defaults.rateLimit.ttl
},
ip: {
type: String,
required: true,
trim: true
},
hits: {
type: Number,
default: 1,
required: true,
max: defaults.rateLimit.max,
min: 0
}
})
Throttle.index(
{ createdAt: 1 },
{ expireAfterSeconds: defaults.rateLimit.ttl }
)
return mongoose.model('Throttle', Throttle)
}
| /**
* A rate-limiting Throttle model, by IP address
*
*/
var mongoose = require('mongoose')
var ipRegex = require('ip-regex')
var Schema = mongoose.Schema
mongoose.Promise = global.Promise
/**
* Register the Throttle model
*
* @access public
* @param {object} defaults
* @return {object} Mongoose Model
*/
module.exports = function createThrottle (defaults) {
if (defaults.mongoose.uri) {
mongoose.createConnection(defaults.mongoose.uri)
}
if (!mongoose.connection.readyState) {
console.warn('MongoDB connection not set. Skipping. Fix this by specifying the mongoose:uri option.')
}
var Throttle = new Schema({
createdAt: {
type: Date,
required: true,
default: Date.now,
expires: defaults.rateLimit.ttl
},
ip: {
type: String,
required: true,
trim: true,
match: ipRegex()
},
hits: {
type: Number,
default: 1,
required: true,
max: defaults.rateLimit.max,
min: 0
}
})
Throttle.index(
{ createdAt: 1 },
{ expireAfterSeconds: defaults.rateLimit.ttl }
)
return mongoose.model('Throttle', Throttle)
}
|
Update validate func to reflect new signature | /**
Copyright 2015 Covistra Technologies Inc.
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.
*/
"use strict";
module.exports = function(server, log) {
var Users = server.plugins['covistra-security'].Users;
return function (server, username, password, callback) {
log.trace("Authenticating user Basic:", username);
return Users.model.authenticate({username: username, password:password}).then(function(user) {
if(!user) {
log.error("User %s cannot be authenticated", username);
return callback(null, false);
}
return callback(null, true, user.secure() );
}).catch(callback);
};
};
| /**
Copyright 2015 Covistra Technologies Inc.
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.
*/
"use strict";
module.exports = function(server, log) {
var Users = server.plugins['covistra-security'].Users;
return function (username, password, callback) {
log.trace("Authenticating user Basic:", username);
return Users.model.authenticate({username: username, password:password}).then(function(user) {
if(!user) {
log.error("User %s cannot be authenticated", username);
return callback(null, false);
}
return callback(null, true, user.secure() );
}).catch(callback);
};
}
|
Implement basic stats for the dashboard | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Order\Repository;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Sequence\Repository\HashSubjectRepositoryInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface OrderRepositoryInterface extends RepositoryInterface, HashSubjectRepositoryInterface
{
/**
* @return int
*/
public function count();
/**
* @return int
*/
public function getTotalSales();
/**
* @param int $amount
*
* @return OrderInterface[]
*/
public function findRecentOrders($amount = 10);
/**
* @param int|string $number
*
* @return bool
*/
public function isNumberUsed($number);
/**
* @param string $orderNumber
*
* @return OrderInterface|null
*/
public function findOneByNumber($orderNumber);
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Order\Repository;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Sylius\Component\Sequence\Repository\HashSubjectRepositoryInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface OrderRepositoryInterface extends RepositoryInterface, HashSubjectRepositoryInterface
{
/**
* @param int $amount
*
* @return OrderInterface[]
*/
public function findRecentOrders($amount = 10);
/**
* @param int|string $number
*
* @return bool
*/
public function isNumberUsed($number);
/**
* @param string $orderNumber
*
* @return OrderInterface|null
*/
public function findOneByNumber($orderNumber);
}
|
Fix task email recipients list format | from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '',
to=[m[1] for m in settings.MANAGERS])
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
| from decimal import Decimal
from django.conf import settings
from django.core.mail import EmailMessage
from celery.utils.log import get_task_logger
from .csv_attach import CSVAttachmentWriter
from .models import Transaction
from celeryapp import app
logger = get_task_logger(__name__)
@app.task(max_retries=3)
def email_journal_vouchers_import():
"""
"""
try:
credits = Transaction.objects.export_transactions()
debit = Decimal(0)
attachment = CSVAttachmentWriter()
for credit in credits:
attachment.writerow([credit['product__account_number'], '',
credit['price__sum']])
debit += credit['price__sum']
attachment.writerow([settings.SHOPIFY_DEBIT_ACCOUNT_NUMBER, debit, ''])
message = EmailMessage('Journal Vouchers Import', '', to=settings.MANAGERS)
message.attach(attachment.getname(), attachment.getvalue(), 'text/csv')
message.send()
except Exception as exc:
logger.debug("MIP export failed: %s" % exc)
logger.warn('MIP export failed, retrying')
raise email_mip_import_file.retry(exc=exc)
|
Add init tests to CI. | #! /usr/bin/env python
########################################################################
# SimpleFIX
# Copyright (C) 2016, David Arnold.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
########################################################################
import unittest
from test_init import InitTests
from test_message import MessageTests
from test_parser import ParserTests
if __name__ == "__main__":
unittest.main()
| #! /usr/bin/env python
########################################################################
# SimpleFIX
# Copyright (C) 2016, David Arnold.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
########################################################################
import unittest
from test_message import MessageTests
from test_parser import ParserTests
if __name__ == "__main__":
unittest.main()
|
[User] Change user bundle configuration to be able to support multiple entity
[Behat] Separate security context & clean up
[Core][User] replace unused services | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Core\Test\Factory;
use Sylius\Component\Core\Model\UserInterface;
/**
* @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
* @author Magdalena Banasiak <magdalena.banasiak@lakion.com>
*/
interface TestUserFactoryInterface
{
/**
* @param string $email
* @param string $password
* @param string $firstName
* @param string $lastName
* @param string $role
*
* @return UserInterface
*/
public function create($email, $password, $firstName, $lastName, $role);
/**
* @return UserInterface
*/
public function createDefault();
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Core\Test\Factory;
use Sylius\Component\Core\Model\UserInterface;
/**
* @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
* @author Magdalena Banasiak <magdalena.banasiak@lakion.com>
*/
interface TestUserFactoryInterface
{
/**
* @param string $email
* @param string $password
* @param string $firstName
* @param string $lastName
* @param string $role
*
* @return UserInterface
*/
public function create($email, $password, $firstName, $lastName, $role);
/**
* @return UserInterface
*/
public function createDefault();
/**
* @return UserInterface
*/
public function createDefaultAdmin();
}
|
Use is defined to check is a function not has property | define([
'aux/is-defined'
], function (isDefined) {
/**
* Using the browsers console logging options, allowing to use console.error if accessible otherwise fallsback to
* console.log (again if accessible).
*
* @exports console-logger
*
* @requires module:is-defined
*
* @param {*} message Message to log out
* @param {String} type What logging system to use error, log (defaults to log).
*/
function logger (message, type) {
var console = window.console;
type = type || 'log';
if (isDefined(console[type], 'function')) {
console[type](message);
} else if (isDefined(console.log, 'function')) {
console.log(message);
}
}
return logger;
});
| define([
'aux/has-property'
], function (hasProperty) {
/**
* Using the browsers console logging options, allowing to use console.error if accessible otherwise fallsback to
* console.log (again if accessible).
*
* @exports console-logger
*
* @requires module:has-property
*
* @param {*} message Message to log out
* @param {String} type What logging system to use error, log (defaults to log).
*/
function logger (message, type) {
type = type || 'log';
if (hasProperty(window, 'console.' + type)) {
console[type](message);
} else if (hasProperty(window, 'console.log')) {
console.log(message);
}
}
return logger;
});
|
Swap the arguments being passed to trigger_error().
Fixes issue #247
http://symphony-cms.com/discuss/issues/view/247/ | <?php
Class DateTimeObj{
public static function setDefaultTimezone($timezone){
if(!@date_default_timezone_set($timezone)) trigger_error("Invalid timezone '{$timezone}'", E_USER_WARNING);
}
public static function getGMT($format, $timestamp=NULL){
return self::get($format, $timestamp, 'GMT');
}
public static function getTimeAgo($format){
return '<abbr class="timeago" title="'.self::get('r').'">'.self::get($format).'</abbr>';
}
public static function get($format, $timestamp=NULL, $timezone=NULL){
if(!$timestamp || $timestamp == 'now') $timestamp = time();
if(!$timezone) $timezone = date_default_timezone_get();
$current_timezone = date_default_timezone_get();
if($current_timezone != $timezone) self::setDefaultTimezone($timezone);
$ret = date($format, $timestamp);
if($current_timezone != $timezone) self::setDefaultTimezone($current_timezone);
return $ret;
}
}
| <?php
Class DateTimeObj{
public static function setDefaultTimezone($timezone){
if(!@date_default_timezone_set($timezone)) trigger_error(E_USER_WARNING, "Invalid timezone '{$timezone}'");
}
public static function getGMT($format, $timestamp=NULL){
return self::get($format, $timestamp, 'GMT');
}
public static function getTimeAgo($format){
return '<abbr class="timeago" title="'.self::get('r').'">'.self::get($format).'</abbr>';
}
public static function get($format, $timestamp=NULL, $timezone=NULL){
if(!$timestamp || $timestamp == 'now') $timestamp = time();
if(!$timezone) $timezone = date_default_timezone_get();
$current_timezone = date_default_timezone_get();
if($current_timezone != $timezone) self::setDefaultTimezone($timezone);
$ret = date($format, $timestamp);
if($current_timezone != $timezone) self::setDefaultTimezone($current_timezone);
return $ret;
}
}
|
Fix setting reference for FLATMENU_MENU_ICON | # -*- coding: utf-8 -*-
from django.conf import settings
ACTIVE_CLASS = getattr(
settings, 'WAGTAILMENUS_ACTIVE_CLASS', 'active')
ACTIVE_ANCESTOR_CLASS = getattr(
settings, 'WAGTAILMENUS_ACTIVE_ANCESTOR_CLASS', 'ancestor')
MAINMENU_MENU_ICON = getattr(
settings, 'WAGTAILMENUS_MAINMENU_MENU_ICON', 'list-ol')
FLATMENU_MENU_ICON = getattr(
settings, 'WAGTAILMENUS_FLATMENU_MENU_ICON', 'list-ol')
DEFAULT_MAIN_MENU_TEMPLATE = getattr(
settings, 'WAGTAILMENUS_DEFAULT_MAIN_MENU_TEMPLATE',
'menus/main_menu.html')
DEFAULT_FLAT_MENU_TEMPLATE = getattr(
settings, 'WAGTAILMENUS_DEFAULT_FLAT_MENU_TEMPLATE',
'menus/flat_menu.html')
DEFAULT_SECTION_MENU_TEMPLATE = getattr(
settings, 'WAGTAILMENUS_DEFAULT_SECTION_MENU_TEMPLATE',
'menus/section_menu.html')
DEFAULT_CHILDREN_MENU_TEMPLATE = getattr(
settings, 'WAGTAILMENUS_DEFAULT_CHILDREN_MENU_TEMPLATE',
'menus/children_menu.html')
| # -*- coding: utf-8 -*-
from django.conf import settings
ACTIVE_CLASS = getattr(
settings, 'WAGTAILMENUS_ACTIVE_CLASS', 'active')
ACTIVE_ANCESTOR_CLASS = getattr(
settings, 'WAGTAILMENUS_ACTIVE_ANCESTOR_CLASS', 'ancestor')
MAINMENU_MENU_ICON = getattr(
settings, 'WAGTAILMENUS_MAINMENU_MENU_ICON', 'list-ol')
FLATMENU_MENU_ICON = getattr(
settings, 'WAGTAILMENUS_MAINMENU_MENU_ICON', 'list-ol')
DEFAULT_MAIN_MENU_TEMPLATE = getattr(
settings, 'WAGTAILMENUS_DEFAULT_MAIN_MENU_TEMPLATE',
'menus/main_menu.html')
DEFAULT_FLAT_MENU_TEMPLATE = getattr(
settings, 'WAGTAILMENUS_DEFAULT_FLAT_MENU_TEMPLATE',
'menus/flat_menu.html')
DEFAULT_SECTION_MENU_TEMPLATE = getattr(
settings, 'WAGTAILMENUS_DEFAULT_SECTION_MENU_TEMPLATE',
'menus/section_menu.html')
DEFAULT_CHILDREN_MENU_TEMPLATE = getattr(
settings, 'WAGTAILMENUS_DEFAULT_CHILDREN_MENU_TEMPLATE',
'menus/children_menu.html')
|
Exclude react from the build | const path = require('path');
const webpack = require('webpack');
const manifest = require('./package.json');
const mainFile = manifest.main;
const packageName = manifest.name;
const destinationDirectory = path.dirname(mainFile);
const exportFileName = path.basename(mainFile, path.extname(mainFile));
module.exports = {
entry: ['./src/formwood.js'],
output: {
path: path.resolve(__dirname, destinationDirectory),
filename: `${exportFileName}.js`,
library: packageName,
libraryTarget: 'umd'
},
externals: ['react'],
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {loader: 'babel-loader'}
}]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false
}),
new webpack.optimize.UglifyJsPlugin({
beautify: false,
mangle: {keep_fnames: true},
comments: false
})
]
};
| const path = require('path');
const webpack = require('webpack');
const manifest = require('./package.json');
const mainFile = manifest.main;
const packageName = manifest.name;
const destinationDirectory = path.dirname(mainFile);
const exportFileName = path.basename(mainFile, path.extname(mainFile));
module.exports = {
entry: ['./src/formwood.js'],
output: {
path: path.resolve(__dirname, destinationDirectory),
filename: `${exportFileName}.js`,
library: packageName,
libraryTarget: 'umd'
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {loader: 'babel-loader'}
}]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false
}),
new webpack.optimize.UglifyJsPlugin({
beautify: false,
mangle: {keep_fnames: true},
comments: false
})
]
};
|
Allow SCTID in relationship file to be actually null, not just "null" | package org.ihtsdo.buildcloud.service.build.transform;
import org.ihtsdo.buildcloud.service.build.RF2Constants;
import org.ihtsdo.buildcloud.service.helper.Type5UuidFactory;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
public class RepeatableRelationshipUUIDTransform implements LineTransformation {
private Type5UuidFactory type5UuidFactory;
public RepeatableRelationshipUUIDTransform() throws NoSuchAlgorithmException {
type5UuidFactory = new Type5UuidFactory();
}
@Override
public void transformLine(String[] columnValues) throws TransformationException {
// Create repeatable UUID to ensure SCTIDs are reused.
// (Technique lifted from workbench release process.)
// sourceId + destinationId + typeId + relationshipGroup
if (columnValues[0] == null || columnValues[0].equals(RF2Constants.NULL_STRING) || columnValues[0].isEmpty()) {
try {
columnValues[0] = getCalculatedUuidFromRelationshipValues(columnValues);
} catch (UnsupportedEncodingException e) {
throw new TransformationException("Failed to create UUID.", e);
}
}
}
public String getCalculatedUuidFromRelationshipValues(String[] columnValues) throws UnsupportedEncodingException {
return type5UuidFactory.get(columnValues[4] + columnValues[5] + columnValues[7] + columnValues[6]).toString();
}
@Override
public int getColumnIndex() {
return -1;
}
}
| package org.ihtsdo.buildcloud.service.build.transform;
import org.ihtsdo.buildcloud.service.build.RF2Constants;
import org.ihtsdo.buildcloud.service.helper.Type5UuidFactory;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
public class RepeatableRelationshipUUIDTransform implements LineTransformation {
private Type5UuidFactory type5UuidFactory;
public RepeatableRelationshipUUIDTransform() throws NoSuchAlgorithmException {
type5UuidFactory = new Type5UuidFactory();
}
@Override
public void transformLine(String[] columnValues) throws TransformationException {
// Create repeatable UUID to ensure SCTIDs are reused.
// (Technique lifted from workbench release process.)
// sourceId + destinationId + typeId + relationshipGroup
if (columnValues[0].equals(RF2Constants.NULL_STRING) || columnValues[0].isEmpty()) {
try {
columnValues[0] = getCalculatedUuidFromRelationshipValues(columnValues);
} catch (UnsupportedEncodingException e) {
throw new TransformationException("Failed to create UUID.", e);
}
}
}
public String getCalculatedUuidFromRelationshipValues(String[] columnValues) throws UnsupportedEncodingException {
return type5UuidFactory.get(columnValues[4] + columnValues[5] + columnValues[7] + columnValues[6]).toString();
}
@Override
public int getColumnIndex() {
return -1;
}
}
|
Remove cookie banner from cookie settings page | 'use strict';
require('./cookie-functions.js');
require('govuk_publishing_components/components/cookie-banner.js');
window.GOVUK.DEFAULT_COOKIE_CONSENT = {
'essential': true,
'usage': false,
'brexit': false
}
window.GOVUK.setDefaultConsentCookie = function () {
var defaultConsent = {
'essential': true,
'usage': false,
'brexit': false
}
window.GOVUK.setCookie('cookie_policy', JSON.stringify(defaultConsent), { days: 365 })
}
window.GOVUK.approveAllCookieTypes = function () {
var approvedConsent = {
'essential': true,
'usage': true,
'brexit': true
}
window.GOVUK.setCookie('cookie_policy', JSON.stringify(approvedConsent), { days: 365 })
}
window.GOVUK.Modules.CookieBanner.prototype.isInCookiesPage = function () {
return window.location.pathname === '/cookie-settings'
}
| 'use strict';
require('./cookie-functions.js');
require('govuk_publishing_components/components/cookie-banner.js');
window.GOVUK.DEFAULT_COOKIE_CONSENT = {
'essential': true,
'usage': false,
'brexit': false
}
window.GOVUK.setDefaultConsentCookie = function () {
var defaultConsent = {
'essential': true,
'usage': false,
'brexit': false
}
window.GOVUK.setCookie('cookie_policy', JSON.stringify(defaultConsent), { days: 365 })
}
window.GOVUK.approveAllCookieTypes = function () {
var approvedConsent = {
'essential': true,
'usage': true,
'brexit': true
}
window.GOVUK.setCookie('cookie_policy', JSON.stringify(approvedConsent), { days: 365 })
}
|
Change to signup url to allow steps | from django.conf.urls import patterns, url
from . import views
api_urlpatterns = patterns(
# Prefix
'',
(r'auth/signin/$', views.SigninAPIView.as_view()),
(r'auth/signup/$', views.SignupAPIView.as_view()),
(r'auth/username/validate/$', views.ValidateUsernameAPIView.as_view()),
(r'auth/forgot_password/$', views.ForgotPasswordAPIView.as_view()),
(r'auth/reset_password/$', views.ResetPasswordAPIView.as_view()),
(r'users/me/$', views.UserSettingsAPIView.as_view()),
(r'users/me/change_password/$', views.ChangePasswordAPIView.as_view()),
)
urlpatterns = patterns(
# Prefix
'',
url(r'signin/$',
views.SigninValidateTokenHTMLView.as_view(),
name='auth-signin'),
url(r'signup/',
views.SignupValidateTokenHTMLView.as_view(),
name='auth-signup'),
url(r'reset_password/$',
views.ResetPasswordHTMLView.as_view(),
name='auth-reset-password'),
)
| from django.conf.urls import patterns, url
from . import views
api_urlpatterns = patterns(
# Prefix
'',
(r'auth/signin/$', views.SigninAPIView.as_view()),
(r'auth/signup/$', views.SignupAPIView.as_view()),
(r'auth/username/validate/$', views.ValidateUsernameAPIView.as_view()),
(r'auth/forgot_password/$', views.ForgotPasswordAPIView.as_view()),
(r'auth/reset_password/$', views.ResetPasswordAPIView.as_view()),
(r'users/me/$', views.UserSettingsAPIView.as_view()),
(r'users/me/change_password/$', views.ChangePasswordAPIView.as_view()),
)
urlpatterns = patterns(
# Prefix
'',
url(r'signin/$',
views.SigninValidateTokenHTMLView.as_view(),
name='auth-signin'),
url(r'signup/$',
views.SignupValidateTokenHTMLView.as_view(),
name='auth-signup'),
url(r'reset_password/$',
views.ResetPasswordHTMLView.as_view(),
name='auth-reset-password'),
)
|
Add default time out to Kind 2 web example | package jkind.api.examples;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import jkind.api.xml.Kind2WebInputStream;
import jkind.api.xml.LineInputStream;
public class Kind2WebExample {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: Kind2WebExample [url] [filename]");
return;
}
URI uri = new URI(args[0]);
String filename = args[1];
try (LineInputStream lines = new LineInputStream(new Kind2WebInputStream(uri,
getKindArgs(), getLustre(filename)))) {
String line;
while ((line = lines.readLine()) != null) {
System.out.print(line);
}
}
}
private static List<String> getKindArgs() {
List<String> args = new ArrayList<>();
args.add("-xml");
args.add("--timeout_wall");
args.add("100");
return args;
}
private static String getLustre(String filename) throws IOException {
try (FileReader reader = new FileReader(filename)) {
StringBuilder result = new StringBuilder();
int i;
while ((i = reader.read()) != -1) {
result.append((char) i);
}
return result.toString();
}
}
}
| package jkind.api.examples;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import jkind.api.xml.Kind2WebInputStream;
import jkind.api.xml.LineInputStream;
public class Kind2WebExample {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: Kind2WebExample [url] [filename]");
return;
}
URI uri = new URI(args[0]);
String filename = args[1];
try (LineInputStream lines = new LineInputStream(new Kind2WebInputStream(uri,
getKindArgs(), getLustre(filename)))) {
String line;
while ((line = lines.readLine()) != null) {
System.out.print(line);
}
}
}
private static List<String> getKindArgs() {
List<String> args = new ArrayList<>();
args.add("-xml");
return args;
}
private static String getLustre(String filename) throws IOException {
try (FileReader reader = new FileReader(filename)) {
StringBuilder result = new StringBuilder();
int i;
while ((i = reader.read()) != -1) {
result.append((char) i);
}
return result.toString();
}
}
}
|
Add numbers to reddit posts | var express = require('express');
var app = express();
var kanye = require("../../kanye");
var request = require("request");
// The main app can hit this when an SMS is received
app.get('/sms', function(req, res) {
if (req.query.message.toLowerCase() != "reddit") {
res.status(400).end();
return;
}
request("http://reddit.com/top.json?limit=5", function(error, response, body) {
console.log(body);
var json = JSON.parse(body);
var response = "";
var num = 1;
for (var x in json.data.children) {
var child = json.data.children[x].data;
var title = child.title;
response += (num++) + ".) " + title + "\n";
}
console.log(response.length);
kanye.sendMessage(req.query.number, response);
res.status(200).end();
});
// kanye.sendMessage(req.query.number, "You're now browsing reddit!");
});
app.listen(3002);
| var express = require('express');
var app = express();
var kanye = require("../../kanye");
var request = require("request");
// The main app can hit this when an SMS is received
app.get('/sms', function(req, res) {
if (req.query.message.toLowerCase() != "reddit") {
res.status(400).end();
return;
}
request("http://reddit.com/top.json?limit=5", function(error, response, body) {
console.log(body);
var json = JSON.parse(body);
var response = "";
for (var x in json.data.children) {
var child = json.data.children[x].data;
var title = child.title;
response += title + "\n";
}
console.log(response.length);
kanye.sendMessage(req.query.number, response);
res.status(200).end();
});
// kanye.sendMessage(req.query.number, "You're now browsing reddit!");
});
app.listen(3002);
|
Remove commented out conditions for now
We can figure out how to guard against plugins receiving the wrong events later | const handlebars = require('handlebars');
const Plugin = require('../plugin');
module.exports = class Issues extends Plugin {
comment(context, content) {
const template = handlebars.compile(content)(context.payload);
return context.github.issues.createComment(context.payload.toIssue({body: template}));
}
assign(context, ...assignees) {
return context.github.issues.addAssigneesToIssue(context.payload.toIssue({assignees}));
}
unassign(context, ...assignees) {
return context.github.issues.removeAssigneesFromIssue(context.payload.toIssue({body: {assignees}}));
}
label(context, ...labels) {
return context.github.issues.addLabels(context.payload.toIssue({body: labels}));
}
unlabel(context, ...labels) {
return labels.map(label => {
return context.github.issues.removeLabel(
context.payload.toIssue({name: label})
);
});
}
lock(context) {
return context.github.issues.lock(context.payload.toIssue({}));
}
unlock(context) {
return context.github.issues.unlock(context.payload.toIssue({}));
}
open(context) {
return context.github.issues.edit(context.payload.toIssue({state: 'open'}));
}
close(context) {
return context.github.issues.edit(context.payload.toIssue({state: 'closed'}));
}
};
| const handlebars = require('handlebars');
const Plugin = require('../plugin');
module.exports = class Issues extends Plugin {
// checkIfEventApplies(event) {
// return event.issue !== undefined || event.pull_request !== undefined;
// }
comment(context, content) {
const template = handlebars.compile(content)(context.payload);
return context.github.issues.createComment(context.payload.toIssue({body: template}));
}
assign(context, ...assignees) {
return context.github.issues.addAssigneesToIssue(context.payload.toIssue({assignees}));
}
unassign(context, ...assignees) {
return context.github.issues.removeAssigneesFromIssue(context.payload.toIssue({body: {assignees}}));
}
label(context, ...labels) {
return context.github.issues.addLabels(context.payload.toIssue({body: labels}));
}
unlabel(context, ...labels) {
return labels.map(label => {
return context.github.issues.removeLabel(
context.payload.toIssue({name: label})
);
});
}
lock(context) {
return context.github.issues.lock(context.payload.toIssue({}));
}
unlock(context) {
return context.github.issues.unlock(context.payload.toIssue({}));
}
open(context) {
return context.github.issues.edit(context.payload.toIssue({state: 'open'}));
}
close(context) {
return context.github.issues.edit(context.payload.toIssue({state: 'closed'}));
}
};
|
Define error for windows, minor fix pushing in | // +build windows
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs 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 fs
import (
"path/filepath"
"syscall"
)
func normalizePath(path string) string {
if filepath.VolumeName(path) == "" && filepath.HasPrefix(path, "\\") {
var err error
path, err = syscall.FullPath(path)
if err != nil {
panic(err)
}
}
return path
}
| // +build windows
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this fs 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 fs
import (
"path/filepath"
"syscall"
)
func normalizePath(path string) string {
if filepath.VolumeName(path) == "" && filepath.HasPrefix(path, "\\") {
path, err = syscall.FullPath(path)
if err != nil {
panic(err)
}
}
return path
}
|
Fix the Update ECS Service size Lambda | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Change the size of an ECS service.
This is used to schedule our service applications: by setting the desired
size to 0/greater-than-0, Amazon will do the work of spinning up or scaling
down the tasks.
The script is triggered by notifications to an SNS topic, in which the
message should be a JSON string that includes "cluster", "service" and
"desired_count" as attributes.
"""
import json
import boto3
def change_desired_count(cluster, service, desired_count):
"""
Given an ECS cluster, service name and desired instance count, change
the instance count on AWS.
"""
ecs = boto3.client('ecs')
resp = ecs.update_service(
cluster=cluster,
service=service,
desiredCount=desired_count
)
print('ECS response: %r' % resp)
assert resp['ResponseMetadata']['HTTPStatusCode'] == 200
def main(event, _):
print('Received event: %r' % event)
message = event['Records'][0]['Sns']['Message']
message_data = json.loads(message)
change_desired_count(
cluster=message_data['cluster'],
service=message_data['service'],
desired_count=message_data['desired_count']
)
| #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Change the size of an ECS service.
This is used to schedule our service applications: by setting the desired
size to 0/greater-than-0, Amazon will do the work of spinning up or scaling
down the tasks.
The script is triggered by notifications to an SNS topic, in which the
message should be a JSON string that includes "cluster", "service" and
"desired_count" as attributes.
"""
import json
import boto3
def change_desired_count(cluster, service, desired_count):
"""
Given an ECS cluster, service name and desired instance count, change
the instance count on AWS.
"""
ecs = boto3.client('ecs')
resp = ecs.update_service(
cluster=cluster,
service=service,
desiredCount=desired_count
)
print('ECS response: %r' % resp)
assert resp['ResponseMetadata']['HTTPStatusCode'] == 200
def main(event, _):
print('Received event: %r' % event)
message = event['Message']
message_data = json.loads(message)
change_desired_count(
cluster=message_data['cluster'],
service=message_data['service'],
desired_count=message_data['desired_count']
)
|
Add comment for each test cases | package main
import (
"testing"
)
var sourceURITests = []struct {
src string
dst string
}{
//Full URI
{
"https://github.com/sunaku/vim-unbundle",
"https://github.com/sunaku/vim-unbundle",
},
//Short GitHub URI
{
"Shougo/neobundle.vim",
"https://github.com/Shougo/neobundle.vim",
},
{
"thinca/vim-quickrun",
"https://github.com/thinca/vim-quickrun",
},
}
func TestSourceURI(t *testing.T) {
for _, test := range sourceURITests {
expect := test.dst
actual, err := ToSourceURI(test.src)
if err != nil {
t.Errorf("ToSourceURI(%q) returns %q, want nil", err)
}
if actual != expect {
t.Errorf("%q: got %q, want %q",
test.src, actual, expect)
}
}
}
| package main
import (
"testing"
)
var sourceURITests = []struct {
src string
dst string
}{
{
"https://github.com/sunaku/vim-unbundle",
"https://github.com/sunaku/vim-unbundle",
},
{
"Shougo/neobundle.vim",
"https://github.com/Shougo/neobundle.vim",
},
{
"thinca/vim-quickrun",
"https://github.com/thinca/vim-quickrun",
},
}
func TestSourceURI(t *testing.T) {
for _, test := range sourceURITests {
expect := test.dst
actual, err := ToSourceURI(test.src)
if err != nil {
t.Errorf("ToSourceURI(%q) returns %q, want nil", err)
}
if actual != expect {
t.Errorf("%q: got %q, want %q",
test.src, actual, expect)
}
}
}
|
Revert "Clean results task Health Check"
This reverts commit 4d4148ea831d425327a3047ebb9be8c3129eaff6.
Close #269 | from django.conf import settings
from health_check.backends import BaseHealthCheckBackend
from health_check.exceptions import (
ServiceReturnedUnexpectedResult, ServiceUnavailable
)
from .tasks import add
class CeleryHealthCheck(BaseHealthCheckBackend):
def check_status(self):
timeout = getattr(settings, 'HEALTHCHECK_CELERY_TIMEOUT', 3)
try:
result = add.apply_async(
args=[4, 4],
expires=timeout,
queue=self.queue
)
result.get(timeout=timeout)
if result.result != 8:
self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result"))
except IOError as e:
self.add_error(ServiceUnavailable("IOError"), e)
except NotImplementedError as e:
self.add_error(ServiceUnavailable("NotImplementedError: Make sure CELERY_RESULT_BACKEND is set"), e)
except BaseException as e:
self.add_error(ServiceUnavailable("Unknown error"), e)
| from django.conf import settings
from health_check.backends import BaseHealthCheckBackend
from health_check.exceptions import (
ServiceReturnedUnexpectedResult, ServiceUnavailable
)
from .tasks import add
class CeleryHealthCheck(BaseHealthCheckBackend):
def check_status(self):
timeout = getattr(settings, 'HEALTHCHECK_CELERY_TIMEOUT', 3)
try:
result = add.apply_async(
args=[4, 4],
expires=timeout,
queue=self.queue
)
result.get(timeout=timeout)
if result.result != 8:
self.add_error(ServiceReturnedUnexpectedResult("Celery returned wrong result"))
add.forget()
except IOError as e:
self.add_error(ServiceUnavailable("IOError"), e)
except NotImplementedError as e:
self.add_error(ServiceUnavailable("NotImplementedError: Make sure CELERY_RESULT_BACKEND is set"), e)
except BaseException as e:
self.add_error(ServiceUnavailable("Unknown error"), e)
|
Remove Shogi name space and export default. | import Shogi from '../shogi';
export default class Piece {
constructor(type, x, y) {
this.type = type;
this.x = x;
this.y = y;
}
promote() {
this.type = this.usiPromoteTypes(this.type) || this.type;
return this.type;
}
unpromote() {
this.type = this.usiUnPromoteTypes(this.type) || this.type;
return this.type;
}
usiPromoteTypes() {
return {
p: 'p+',
l: 'l+',
n: 'n+',
s: 's+',
b: 'b+',
r: 'r+',
P: 'P+',
L: 'L+',
N: 'N+',
S: 'S+',
B: 'B+',
R: 'R+'
};
}
usiUnPromoteTypes() {
return {
'p+': 'p',
'l+': 'l',
'n+': 'n',
's+': 's',
'b+': 'b',
'r+': 'r',
'P+': 'P',
'L+': 'L',
'N+': 'N',
'S+': 'S',
'B+': 'B',
'R+': 'R'
};
}
};
| import Shogi from '../shogi';
Shogi.Piece = class Piece {
constructor(type, x, y) {
this.type = type;
this.x = x;
this.y = y;
}
promote() {
this.type = this.usiPromoteTypes(this.type) || this.type;
return this.type;
}
unpromote() {
this.type = this.usiUnPromoteTypes(this.type) || this.type;
return this.type;
}
usiPromoteTypes() {
return {
p: 'p+',
l: 'l+',
n: 'n+',
s: 's+',
b: 'b+',
r: 'r+',
P: 'P+',
L: 'L+',
N: 'N+',
S: 'S+',
B: 'B+',
R: 'R+'
};
}
usiUnPromoteTypes() {
return {
'p+': 'p',
'l+': 'l',
'n+': 'n',
's+': 's',
'b+': 'b',
'r+': 'r',
'P+': 'P',
'L+': 'L',
'N+': 'N',
'S+': 'S',
'B+': 'B',
'R+': 'R'
};
}
};
|
Add componentWillReceiveProps for dynamic datasource updates | import React, { Component } from 'react';
import { ListView } from 'react-native';
class ScrollableList extends Component {
constructor(props) {
super(props);
const { data, row, ...other } = props;
this.otherProps = other;
this.row = row;
this._ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.state = {
dataSource: this._ds.cloneWithRows(data),
};
}
componentWillReceiveProps(props){
if(this.props.data !== props.data){
this.setState({
dataSource: this._ds.cloneWithRows(props.data)
});
}
}
render() {
const Row = this.row;
return (
<ListView
{...this.otherProps}
dataSource={this.state.dataSource}
renderRow={(data) => <Row {...data} />}
/>
);
}
}
export default ScrollableList;
| import React, { Component } from 'react';
import { ListView } from 'react-native';
class ScrollableList extends Component {
constructor(props) {
super(props);
const { data, row, ...other } = props;
this.otherProps = other;
this.row = row;
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.state = {
dataSource: ds.cloneWithRows(data),
};
}
render() {
const Row = this.row;
return (
<ListView
{...this.otherProps}
dataSource={this.state.dataSource}
renderRow={(data) => <Row {...data} />}
/>
);
}
}
export default ScrollableList;
|
Fix jscs -- apparently `this` can be unquoted in an object literal? | /* eslint-env node */
'use strict';
var fs = require('fs');
var path = require('path');
// Semantic actions for the `mentionsThis` attribute, which returns true for a node
// if the `this` keyword appears anywhere in the node's subtree, and otherwise false.
var mentionsThisActions = {
this: function(_) { return true; },
_terminal: function() { return false; },
_default: anyNodesMentionThis,
_iter: anyNodesMentionThis
};
function anyNodesMentionThis(nodes) {
return nodes.some(function(n) { return n.mentionsThis; });
}
var modifiedSourceActions = {
ArrowFunction: function(params, _, body) {
var source = 'function ' + params.asES5 + ' ' + body.asES5;
// Only use `bind` if necessary.
return body.mentionsThis ? source + '.bind(this)' : source;
},
ArrowParameters_unparenthesized: function(id) {
return '(' + id.asES5 + ')';
},
ConciseBody_noBraces: function(exp) {
return '{ return ' + exp.asES5 + ' }';
}
};
module.exports = function(ohm, ns, s) {
var g = ohm.grammar(fs.readFileSync(path.join(__dirname, 'es6.ohm')).toString(), ns);
var semantics = g.extendSemantics(s);
semantics.extendAttribute('modifiedSource', modifiedSourceActions);
semantics.addAttribute('mentionsThis', mentionsThisActions);
return {
grammar: g,
semantics: semantics
};
};
| /* eslint-env node */
'use strict';
var fs = require('fs');
var path = require('path');
// Semantic actions for the `mentionsThis` attribute, which returns true for a node
// if the `this` keyword appears anywhere in the node's subtree, and otherwise false.
var mentionsThisActions = {
'this': function(_) { return true; },
_terminal: function() { return false; },
_default: anyNodesMentionThis,
_iter: anyNodesMentionThis
};
function anyNodesMentionThis(nodes) {
return nodes.some(function(n) { return n.mentionsThis; });
}
var modifiedSourceActions = {
ArrowFunction: function(params, _, body) {
var source = 'function ' + params.asES5 + ' ' + body.asES5;
// Only use `bind` if necessary.
return body.mentionsThis ? source + '.bind(this)' : source;
},
ArrowParameters_unparenthesized: function(id) {
return '(' + id.asES5 + ')';
},
ConciseBody_noBraces: function(exp) {
return '{ return ' + exp.asES5 + ' }';
}
};
module.exports = function(ohm, ns, s) {
var g = ohm.grammar(fs.readFileSync(path.join(__dirname, 'es6.ohm')).toString(), ns);
var semantics = g.extendSemantics(s);
semantics.extendAttribute('modifiedSource', modifiedSourceActions);
semantics.addAttribute('mentionsThis', mentionsThisActions);
return {
grammar: g,
semantics: semantics
};
};
|
Update with reference to global nav partial | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-heights/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-heights/tachyons-heights.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_heights.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/heights/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/layout/heights/index.html', html)
| var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-heights/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-heights/tachyons-heights.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_heights.css', 'utf8')
var template = fs.readFileSync('./templates/docs/heights/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/layout/heights/index.html', html)
|
Add texture format to texture loader | (function(){
'use strict';
/**
* Texture loader based on {@link https://github.com/mrdoob/three.js/blob/master/src/loaders/TextureLoader.js}
* @memberOf PANOLENS.Utils
* @namespace
*/
PANOLENS.Utils.TextureLoader = {};
/**
* Load image texture
* @param {string} url - An image url
* @param {function} onLoad - On load callback
* @param {function} onProgress - In progress callback
* @param {function} onError - On error callback
* @return {THREE.Texture} - Image texture
*/
PANOLENS.Utils.TextureLoader.load = function ( url, onLoad, onProgress, onError ) {
var texture = new THREE.Texture();
PANOLENS.Utils.ImageLoader.load( url, function ( image ) {
texture.image = image;
// JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
texture.format = isJPEG ? THREE.RGBFormat : THREE.RGBAFormat;
texture.needsUpdate = true;
onLoad && onLoad( texture );
}, onProgress, onError );
return texture;
};
})(); | (function(){
'use strict';
/**
* Texture loader based on {@link https://github.com/mrdoob/three.js/blob/master/src/loaders/TextureLoader.js}
* @memberOf PANOLENS.Utils
* @namespace
*/
PANOLENS.Utils.TextureLoader = {};
/**
* Load image texture
* @param {string} url - An image url
* @param {function} onLoad - On load callback
* @param {function} onProgress - In progress callback
* @param {function} onError - On error callback
* @return {THREE.Texture} - Image texture
*/
PANOLENS.Utils.TextureLoader.load = function ( url, onLoad, onProgress, onError ) {
var texture = new THREE.Texture();
PANOLENS.Utils.ImageLoader.load( url, function ( image ) {
texture.image = image;
texture.needsUpdate = true;
onLoad && onLoad( texture );
}, onProgress, onError );
return texture;
};
})(); |
Add debug logs to keepalive thread | import threading
import logbook
_logger = logbook.Logger(__name__)
class KeepaliveThread(threading.Thread):
def __init__(self, client, session, interval):
super(KeepaliveThread, self).__init__()
self._client = client
self._session = session
self._interval = interval / 2.0
self._stopped_event = threading.Event()
self.daemon = True
def run(self):
_logger.debug('Backslash keepalive thread started')
try:
while not self._stopped_event.is_set():
self._stopped_event.wait(timeout=self._interval)
self._session.send_keepalive()
except Exception: #pylint: disable=broad-except
_logger.error('Quitting keepalive thread due to exception', exc_info=True)
raise
finally:
_logger.debug('Backslash keepalive thread terminated')
def stop(self):
self._stopped_event.set()
| import threading
import logbook
_logger = logbook.Logger(__name__)
class KeepaliveThread(threading.Thread):
def __init__(self, client, session, interval):
super(KeepaliveThread, self).__init__()
self._client = client
self._session = session
self._interval = interval / 2.0
self._stopped_event = threading.Event()
self.daemon = True
def run(self):
while not self._stopped_event.is_set():
self._stopped_event.wait(timeout=self._interval)
self._session.send_keepalive()
def stop(self):
self._stopped_event.set()
|
Fix up a broken js-test.
This test was asserting that a thing was itself, rather than what it was
supposed to be asserting (that a thing's JSON-serialization was correct).
Testing done:
Ran js-tests.
Reviewed at https://reviews.reviewboard.org/r/8735/ | suite('rb/resources/models/ValidateDiffModel', function() {
var model;
beforeEach(function() {
model = new RB.ValidateDiffModel();
});
describe('methods', function() {
describe('url', function() {
it('Without local site', function() {
expect(_.result(model, 'url')).toBe('/api/validation/diffs/');
});
it('With local site', function() {
model.set('localSitePrefix', 's/test-site/');
expect(_.result(model, 'url')).toBe('/s/test-site/api/validation/diffs/');
});
});
});
describe('toJSON', function() {
it('repository field', function() {
var data;
model.set('repository', 123);
data = model.toJSON();
expect(data.repository).toBe(123);
});
});
});
| suite('rb/resources/models/ValidateDiffModel', function() {
var model;
beforeEach(function() {
model = new RB.ValidateDiffModel();
});
describe('methods', function() {
describe('url', function() {
it('Without local site', function() {
expect(_.result(model, 'url')).toBe('/api/validation/diffs/');
});
it('With local site', function() {
model.set('localSitePrefix', 's/test-site/');
expect(_.result(model, 'url')).toBe('/s/test-site/api/validation/diffs/');
});
});
});
describe('toJSON', function() {
it('repository field', function() {
var data;
model.set('repository', 123);
data = model.toJSON();
expect(model.get('repository')).toBe(123);
});
});
});
|
Allow specifying username and password for HSQLDB | package org.stevewinfield.suja.idk.storage;
import org.stevewinfield.suja.idk.Bootloader;
public class HSQLDBStorageDriver implements StorageDriver {
@Override
public String getDriverName() {
return "hsqldb";
}
@Override
public String getDriverClass() {
return "org.hsqldb.jdbc.JDBCDriver";
}
@Override
public String getConnectionString() {
return "jdbc:hsqldb:file:" + Bootloader.getSettings().getProperty("idk.hsqldb.path", "database");
}
@Override
public String getUsername() {
return Bootloader.getSettings().getProperty("idk.hsqldb.user", "");
}
@Override
public String getPassword() {
return Bootloader.getSettings().getProperty("idk.hsqldb.password", "");
}
}
| package org.stevewinfield.suja.idk.storage;
import org.stevewinfield.suja.idk.Bootloader;
public class HSQLDBStorageDriver implements StorageDriver {
@Override
public String getDriverName() {
return "hsqldb";
}
@Override
public String getDriverClass() {
return "org.hsqldb.jdbc.JDBCDriver";
}
@Override
public String getConnectionString() {
return "jdbc:hsqldb:file:" + Bootloader.getSettings().getProperty("idk.hsqldb.path");
}
@Override
public String getUsername() {
return "sa";
}
@Override
public String getPassword() {
return "";
}
}
|
Use double-quoted string in error message | package stack
import (
"fmt"
"sync"
)
type Context struct {
mu sync.RWMutex
m map[string]interface{}
}
func NewContext() *Context {
m := make(map[string]interface{})
return &Context{m: m}
}
func (c *Context) Get(key string) (interface{}, error) {
c.mu.RLock()
defer c.mu.RUnlock()
val := c.m[key]
if val == nil {
return nil, fmt.Errorf("stack.Context: key %q does not exist", key)
}
return val, nil
}
func (c *Context) Put(key string, val interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[key] = val
}
func (c *Context) Delete(key string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.m, key)
}
| package stack
import (
"fmt"
"sync"
)
type Context struct {
mu sync.RWMutex
m map[string]interface{}
}
func NewContext() *Context {
m := make(map[string]interface{})
return &Context{m: m}
}
func (c *Context) Get(key string) (interface{}, error) {
c.mu.RLock()
defer c.mu.RUnlock()
val := c.m[key]
if val == nil {
return nil, fmt.Errorf("stack.Context: key '%s' does not exist", key)
}
return val, nil
}
func (c *Context) Put(key string, val interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
c.m[key] = val
}
func (c *Context) Delete(key string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.m, key)
}
|
Fix possible mix of ProxyFactory instances.
git-svn-id: d2639776715b8e71e47307c736096cc1ee732949@84 c3c2784b-8cd7-0310-8e00-a8c905b2d8b3 | /*
* Created on 04-Feb-2004
*
* (c) 2003-2004 ThoughtWorks
*
* See license.txt for licence details
*/
package com.thoughtworks.proxy.toys.delegate;
import com.thoughtworks.proxy.ProxyFactory;
import com.thoughtworks.proxy.factory.StandardProxyFactory;
/**
* @author <a href="mailto:dan.north@thoughtworks.com">Dan North</a>
*/
public class Delegating {
/** delegate must implement the method's interface */
public static final boolean STATIC_TYPING = DelegatingInvoker.EXACT_METHOD;
/** delegate must have method with matching signature - not necessarily the same */
public static final boolean DYNAMIC_TYPING = DelegatingInvoker.SAME_SIGNATURE_METHOD;
public static Object object(Class type, Object delegate) {
return object(type, delegate, new StandardProxyFactory());
}
public static Object object(Class type, Object delegate, ProxyFactory factory) {
return factory.createProxy(
new Class[] {type},
new DelegatingInvoker(factory, new SimpleReference(delegate), DYNAMIC_TYPING));
}
/** It's a factory, stupid */
private Delegating(){}
}
| /*
* Created on 04-Feb-2004
*
* (c) 2003-2004 ThoughtWorks
*
* See license.txt for licence details
*/
package com.thoughtworks.proxy.toys.delegate;
import com.thoughtworks.proxy.ProxyFactory;
import com.thoughtworks.proxy.factory.StandardProxyFactory;
/**
* @author <a href="mailto:dan.north@thoughtworks.com">Dan North</a>
*/
public class Delegating {
/** delegate must implement the method's interface */
public static final boolean STATIC_TYPING = DelegatingInvoker.EXACT_METHOD;
/** delegate must have method with matching signature - not necessarily the same */
public static final boolean DYNAMIC_TYPING = DelegatingInvoker.SAME_SIGNATURE_METHOD;
public static Object object(Class type, Object delegate) {
return object(type, delegate, new StandardProxyFactory());
}
public static Object object(Class type, Object delegate, ProxyFactory factory) {
return factory.createProxy(new Class[] {type}, new DelegatingInvoker(delegate));
}
/** It's a factory, stupid */
private Delegating(){}
}
|
Allow for yellow color after specifying y | #!/usr/bin/env python2
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
shows red/green bar to visualize return code of previous command
'''
import sys
if len(sys.argv) >= 2:
code = sys.argv[1]
if code == 'y':
col_char = '3'
else:
value = int(code)
if value:
col_char = '1'
else:
col_char = '2'
cols_limit = int(sys.argv[2])
esc = chr(27)
print (''.join((
esc,
'[4',
col_char,
'm',
' ' * (cols_limit - 2),
esc,
'[0m',
)))
else:
print ('''
Usage: %(prog_name)s status_code number_of_columns
1. status code: 0 - OK (green color), other values - BAD (red color)
2. number of columns: the width of text console
''' % dict(
prog_name=sys.argv[0],
))
| #!/usr/bin/env python2
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
shows red/green bar to visualize return code of previous command
'''
import sys
if len(sys.argv) >= 2:
code = sys.argv[1]
value = int(code)
if value:
col_char = '1'
else:
col_char = '2'
cols_limit = int(sys.argv[2])
esc = chr(27)
print (''.join((
esc,
'[4',
col_char,
'm',
' ' * (cols_limit - 2),
esc,
'[0m',
)))
else:
print ('''
Usage: %(prog_name)s status_code number_of_columns
1. status code: 0 - OK (green color), other values - BAD (red color)
2. number of columns: the width of text console
''' % dict(
prog_name=sys.argv[0],
))
|
[fix] Hide trash folder after regression | import { combineReducers } from 'redux'
import { folder, files } from './folder'
import ui from './ui'
import { TRASH_DIR_ID } from '../constants/config.js'
const filesApp = combineReducers({
folder,
files,
ui
})
const sortFiles = files => files.sort((a, b) => a.name.localeCompare(b.name))
const getSortedFiles = allFiles => {
let folders = allFiles.filter(f => f.type === 'directory' && f.id !== TRASH_DIR_ID)
let files = allFiles.filter(f => f.type !== 'directory')
return sortFiles(folders).concat(sortFiles(files))
}
export const getVisibleFiles = state => {
const { files, ui } = state
return getSortedFiles(files).map(f => {
let additionalProps = {
isUpdating: ui.updating.indexOf(f.id) !== -1,
isOpening: ui.opening === f.id,
selected: ui.selected.indexOf(f.id) !== -1
}
return Object.assign({}, f, additionalProps)
})
}
export const mustShowSelectionBar = state => state.ui.showSelectionBar || state.ui.selected.length !== 0
export default filesApp
| import { combineReducers } from 'redux'
import { folder, files } from './folder'
import ui from './ui'
import { TRASH_DIR_ID } from '../actions'
const filesApp = combineReducers({
folder,
files,
ui
})
const sortFiles = files => files.sort((a, b) => a.name.localeCompare(b.name))
const getSortedFiles = allFiles => {
let folders = allFiles.filter(f => f.type === 'directory' && f.id !== TRASH_DIR_ID)
let files = allFiles.filter(f => f.type !== 'directory')
return sortFiles(folders).concat(sortFiles(files))
}
export const getVisibleFiles = state => {
const { files, ui } = state
return getSortedFiles(files).map(f => {
let additionalProps = {
isUpdating: ui.updating.indexOf(f.id) !== -1,
isOpening: ui.opening === f.id,
selected: ui.selected.indexOf(f.id) !== -1
}
return Object.assign({}, f, additionalProps)
})
}
export const mustShowSelectionBar = state => state.ui.showSelectionBar || state.ui.selected.length !== 0
export default filesApp
|
Make sure promises test assertions are run by test runner thread | var assert = require("assert");
var {defer, promises} = require("ringo/promise");
exports.testPromiseList = function() {
var d1 = defer(), d2 = defer(), d3 = defer(), done = defer();
var l = promises(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise
l.then(function(result) {
done.resolve(result);
}, function(error) {
done.resolve("promises called error callback", true);
});
d2.resolve(1);
d3.resolve("error", true);
d1.resolve("ok");
// make sure promises resovle via wait()
var result = l.wait();
assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
// make sure promises resolve via callback
result = done.promise.wait();
assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
};
// start the test runner if we're called directly from command line
if (require.main == module.id) {
system.exit(require('test').run(exports));
}
| var assert = require("assert");
var {defer, promises} = require("ringo/promise");
exports.testPromiseList = function() {
var d1 = defer(), d2 = defer(), d3 = defer();
var l = promises(d1.promise, d2.promise, d3); // promiseList should convert d3 to promise
l.then(function(result) {
assert.deepEqual(result, [{value: "ok"}, {value: 1}, {error: "error"}]);
}, function(error) {
assert.fail("promiseList called error callback");
});
d2.resolve(1);
d3.resolve("error", true);
d1.resolve("ok");
};
// start the test runner if we're called directly from command line
if (require.main == module.id) {
system.exit(require('test').run(exports));
}
|
Improve regex for getting appid | 'use strict';
var CurrentAppID,
GetCurrentAppID = function()
{
if( !CurrentAppID )
{
CurrentAppID = location.pathname.match( /\/(app|sub)\/([0-9]{1,7})/ );
if( CurrentAppID )
{
CurrentAppID = parseInt( CurrentAppID[ 1 ], 10 );
}
else
{
CurrentAppID = -1;
}
}
return CurrentAppID;
},
GetHomepage = function()
{
return 'https://steamdb.info/';
},
GetOption = function( items, callback )
{
if( typeof chrome !== 'undefined' )
{
chrome.storage.local.get( items, callback );
}
else if( typeof self.options.firefox !== 'undefined' )
{
for( var item in items )
{
items[ item ] = self.options.preferences[ item ];
}
callback( items );
}
},
GetLocalResource = function( res )
{
if( typeof chrome !== 'undefined' )
{
return chrome.extension.getURL( res );
}
else if( typeof self.options.firefox !== 'undefined' )
{
return self.options[ res ];
}
return res;
};
| 'use strict';
var CurrentAppID,
GetCurrentAppID = function()
{
if( !CurrentAppID )
{
CurrentAppID = location.pathname.match( /\/([0-9]{1,6})(?:\/|$)/ );
if( CurrentAppID )
{
CurrentAppID = parseInt( CurrentAppID[ 1 ], 10 );
}
else
{
CurrentAppID = -1;
}
}
return CurrentAppID;
},
GetHomepage = function()
{
return 'https://steamdb.info/';
},
GetOption = function( items, callback )
{
if( typeof chrome !== 'undefined' )
{
chrome.storage.local.get( items, callback );
}
else if( typeof self.options.firefox !== 'undefined' )
{
for( var item in items )
{
items[ item ] = self.options.preferences[ item ];
}
callback( items );
}
},
GetLocalResource = function( res )
{
if( typeof chrome !== 'undefined' )
{
return chrome.extension.getURL( res );
}
else if( typeof self.options.firefox !== 'undefined' )
{
return self.options[ res ];
}
return res;
};
|
Set the hook timeout back to 60 seconds. | /**
* Production environment settings
*
* This file can include shared settings for a production environment,
* such as API keys or remote database passwords. If you're using
* a version control solution for your Sails app, this file will
* be committed to your repository unless you add it to your .gitignore
* file. If your repository will be publicly viewable, don't add
* any private information to this file!
*
*/
module.exports = {
/***************************************************************************
* Set the default database connection for models in the production *
* environment (see config/connections.js and config/models.js ) *
***************************************************************************/
models: {
connection: 'mongo'
},
/***************************************************************************
* Set the port in the production environment to 80 *
***************************************************************************/
port: 80,
/***************************************************************************
* Set the log level in production environment to "silent" *
***************************************************************************/
log: {
level: 'info'
},
/***************************************************************************
* Minification/uglification takes a long time. This is to prevent error. *
***************************************************************************/
hookTimeout: 60000
};
| /**
* Production environment settings
*
* This file can include shared settings for a production environment,
* such as API keys or remote database passwords. If you're using
* a version control solution for your Sails app, this file will
* be committed to your repository unless you add it to your .gitignore
* file. If your repository will be publicly viewable, don't add
* any private information to this file!
*
*/
module.exports = {
/***************************************************************************
* Set the default database connection for models in the production *
* environment (see config/connections.js and config/models.js ) *
***************************************************************************/
models: {
connection: 'mongo'
},
/***************************************************************************
* Set the port in the production environment to 80 *
***************************************************************************/
port: 80,
/***************************************************************************
* Set the log level in production environment to "silent" *
***************************************************************************/
log: {
level: 'info'
},
/***************************************************************************
* Minification/uglification takes a long time. This is to prevent error. *
***************************************************************************/
hookTimeout: 90000
};
|
Refactor to send argument to second variable | import React from 'react';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
class FormInput extends React.Component {
constructor(props) {
super(props);
this.state = {
address:''
};
}
handleAction(actionName) {
this.props.action(actionName, this.state.address.trim())
}
handleInput(e) {
this.setState({
address: e.target.value,
});
}
render() {
return (
<form>
<TextField
hintText="Your Account Address"
value={this.state.address}
onChange={this.handleInput.bind(this)}
/>
<RaisedButton
label="Register"
onClick={this.handleAction.bind(this, 'register')}
/>
<RaisedButton
label="Attend"
onClick={this.handleAction.bind(this, 'attend')}
/>
<RaisedButton
label="Payback"
onClick={this.handleAction.bind(this, 'payback')}
/>
</form>
);
}
}
export default FormInput;
| import React from 'react';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
class FormInput extends React.Component {
constructor(props) {
super(props);
this.state = {
address:''
};
}
handleAction(actionName) {
return function (e) {
this.props.action(actionName, this.state.address.trim())
}.bind(this)
}
handleInput(e) {
this.setState({
address: e.target.value,
});
}
render() {
return (
<form>
<TextField
hintText="Your Account Address"
value={this.state.message}
onChange={this.handleInput.bind(this)}
/>
<RaisedButton
label="Register"
onClick={this.handleAction('register')}
/>
<RaisedButton
label="Attend"
onClick={this.handleAction('attend')}
/>
<RaisedButton
label="Payback"
onClick={this.handleAction('payback')}
/>
</form>
);
}
}
export default FormInput;
|
Test the correct admin page | /*************************GO-LICENSE-START*********************************
* Copyright 2015 ThoughtWorks, Inc.
*
* 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.cruise.page;
import com.thoughtworks.cruise.Urls;
import com.thoughtworks.cruise.state.ScenarioState;
import net.sf.sahi.client.Browser;
public class OnAdministrationPage extends CruisePage {
public OnAdministrationPage(ScenarioState state, Browser browser) {
super(state, browser);
}
@com.thoughtworks.gauge.Step("Verify page title is <pageTitle> - On Administration Page")
public void verifyPageTitleIs(String pageTitle) {
super.verifyPageTitleIs(pageTitle);
}
@Override
protected String url() {
return Urls.urlFor("/admin/config_xml");
}
}
| /*************************GO-LICENSE-START*********************************
* Copyright 2015 ThoughtWorks, Inc.
*
* 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.cruise.page;
import com.thoughtworks.cruise.Urls;
import com.thoughtworks.cruise.state.ScenarioState;
import net.sf.sahi.client.Browser;
public class OnAdministrationPage extends CruisePage {
public OnAdministrationPage(ScenarioState state, Browser browser) {
super(state, browser);
}
@com.thoughtworks.gauge.Step("Verify page title is <pageTitle> - On Administration Page")
public void verifyPageTitleIs(String pageTitle) {
super.verifyPageTitleIs(pageTitle);
}
@Override
protected String url() {
return Urls.urlFor("/tab/admin");
}
}
|
Check if a track is playing | import React from 'react';
import './RecentTracks.css';
import RecentTrack from './RecentTrack.js';
import _map from 'lodash/map';
import _isEqual from 'lodash/isEqual';
import {
fetchRecentTracks
} from '../actions/action-creators';
let RecentTracks = React.createClass ({
shouldComponentUpdate(nextProps){
return !_isEqual(nextProps.recentTracks,this.props.recentTracks);
},
componentWillMount() {
fetchRecentTracks();
// this.updateInterval = setInterval(() => fetchRecentTracks(2), 3000);
},
render() {
const {
recentTracks
} = this.props;
let RecentTrackElement;
if (recentTracks) {
RecentTrackElement = _map(recentTracks, (recentTrack, i) => (
<RecentTrack
key={i}
recentTrack={recentTrack} />
));
}
return (
<section
className="RecentTracks">
{RecentTrackElement}
</section>
);
}
});
export default RecentTracks;
| import React from 'react';
import './RecentTracks.css';
import RecentTrack from './RecentTrack.js';
import _map from 'lodash/map';
import {
fetchRecentTracks
} from '../actions/action-creators';
let RecentTracks = React.createClass ({
componentWillMount() {
fetchRecentTracks();
},
render() {
const {
recentTracks
} = this.props;
let RecentTrackElement;
if (recentTracks) {
RecentTrackElement = _map(recentTracks, (recentTrack, i) => (
<RecentTrack
key={i}
recentTrack={recentTrack} />
));
}
return (
<section
className="RecentTracks">
{RecentTrackElement}
</section>
);
}
});
export default RecentTracks;
|
Use standard binding with context | var cdb = require('cartodb.js');
/**
* Responsible for likes (♥ 123) and its toggling behaviour.
*/
module.exports = cdb.core.View.extend({
tagName: 'a',
events: {
'click': '_toggleLike'
},
initialize: function() {
this.template = cdb.templates.getTemplate('new_common/views/likes/template');
this.model.bind('change:liked change:likes error', this.render, this);
},
render: function() {
this.$el.html(
this.template({
m: this.model
})
)
.attr({
class: this._classNames()
});
return this;
},
_classNames: function() {
var classNames = ['LikesIndicator'];
if (this.model.get('liked')) {
classNames.push('LikesIndicator--liked');
}
if (this._animate) {
classNames.push('LikesIndicator--animated');
this.$el.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
// unset animate and force re-render to avoid race conditions
this._animate = false;
this.render();
}.bind(this));
}
return classNames.join(' ')
},
_toggleLike: function(ev) {
this.killEvent(ev);
this._animate = true;
this.model.toggleLiked();
}
});
| var cdb = require('cartodb.js');
/**
* Responsible for likes (♥ 123) and its toggling behaviour.
*/
module.exports = cdb.core.View.extend({
tagName: 'a',
events: {
'click': '_toggleLike'
},
initialize: function() {
this.template = cdb.templates.getTemplate('new_common/views/likes/template');
this.model.bind('change:liked change:likes error', this.render.bind(this));
},
render: function() {
this.$el.html(
this.template({
m: this.model
})
)
.attr({
class: this._classNames()
});
return this;
},
_classNames: function() {
var classNames = ['LikesIndicator'];
if (this.model.get('liked')) {
classNames.push('LikesIndicator--liked');
}
if (this._animate) {
classNames.push('LikesIndicator--animated');
this.$el.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
// unset animate and force re-render to avoid race conditions
this._animate = false;
this.render();
}.bind(this));
}
return classNames.join(' ')
},
_toggleLike: function(ev) {
this.killEvent(ev);
this._animate = true;
this.model.toggleLiked();
}
});
|
Change long description to be README and CHANGELOG | from setuptools import (
setup,
find_packages,
)
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, "README.md")) as rdme:
with open(path.join(here, "CHANGELOG.md")) as chlog:
readme = rdme.read()
changes = chlog.read()
long_description = readme + "\nCHANGELOG\n--------------------------------------\n" + changes
setup(
name="py_types",
version="0.1.0a",
description="Gradual typing for python 3.",
long_description=long_description,
url="https://github.com/zekna/py-types",
author="Zach Nelson",
author_email="kzacharynelson@gmail.com",
license="MIT",
classifiers=[
"Develpoment Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Topic :: Software Development :: Tools",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
],
keywords="type checking development schema",
packages=find_packages(exclude=["tests*"]),
install_requires=[],
extras_require={},
package_data={},
data_files=[],
entry_points={},
)
| from setuptools import (
setup,
find_packages,
)
#from os import path
#here = path.abspath(path.dirname(__file__))
#with open(path.join(here, "README.md")) as f:
# long_description = f.read()
long_description = "stuff will go here eventually"
setup(
name="py_types",
version="0.1.0a",
description="Gradual typing for python 3.",
long_description=long_description,
url="https://github.com/zekna/py-types",
author="Zach Nelson",
author_email="kzacharynelson@gmail.com",
license="MIT",
classifiers=[
"Develpoment Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Topic :: Software Development :: Tools",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
],
keywords="type checking development schema",
packages=find_packages(exclude=["tests*"]),
install_requires=[],
extras_require={},
package_data={},
data_files=[],
entry_points={},
)
|
Fix build error in test | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure;
import com.microsoft.azure.annotations.AzureHost;
import com.microsoft.rest.annotations.GET;
import com.microsoft.rest.annotations.HostParam;
import com.microsoft.rest.annotations.PathParam;
public class AzureTests {
@AzureHost("{vaultBaseUrl}")
public interface HttpBinService {
@GET("secrets/{secretName}")
String getSecret(@HostParam("vaultBaseUrl") String vaultBaseUrl, @PathParam("secretName") String secretName);
}
// @AzureHost not yet supported.
// @Test
// public void getBytes() throws Exception {
// RestClient client = new RestClient.Builder()
// .withBaseUrl("http://localhost")
// .withSerializerAdapter(new JacksonAdapter())
// .withResponseBuilderFactory(new ServiceResponseBuilder.Factory())
// .build();
// HttpBinService service = RestProxy.create(HttpBinService.class, client);
//
// Assert.assertEquals("http://vault1.vault.azure.net/secrets/{secretName}", service.getSecret("http://vault1.vault.azure.net", "secret1"));
// }
}
| /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure;
import com.microsoft.azure.annotations.AzureHost;
import com.microsoft.rest.annotations.GET;
import com.microsoft.rest.annotations.HostParam;
import com.microsoft.rest.annotations.PathParam;
public class AzureTests {
@AzureHost("{vaultBaseUrl}")
public interface HttpBinService {
@GET("secrets/{secretName}")
String getSecret(@HostParam String vaultBaseUrl, @PathParam("secretName") String secretName);
}
// @AzureHost not yet supported.
// @Test
// public void getBytes() throws Exception {
// RestClient client = new RestClient.Builder()
// .withBaseUrl("http://localhost")
// .withSerializerAdapter(new JacksonAdapter())
// .withResponseBuilderFactory(new ServiceResponseBuilder.Factory())
// .build();
// HttpBinService service = RestProxy.create(HttpBinService.class, client);
//
// Assert.assertEquals("http://vault1.vault.azure.net/secrets/{secretName}", service.getSecret("http://vault1.vault.azure.net", "secret1"));
// }
}
|
Set default mode for webpack to none. | var path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
mode: "none",
entry: {
"zinc": "./src/zinc.js",
"zinc.min": "./src/zinc.js",
},
output: {
path: path.resolve(__dirname, 'build'),
filename: "[name].js",
library: 'Zinc',
libraryTarget: 'umd'
},
plugins: [
new UglifyJsPlugin({
include: /\.min\.js$/,
uglifyOptions: {
compress: true
}
})
],
externals: {
three: {
commonjs: 'THREE',
commonjs2: 'THREE',
amd: 'THREE',
root: 'THREE'
}
}
};
| var path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: {
"zinc": "./src/zinc.js",
"zinc.min": "./src/zinc.js",
},
output: {
path: path.resolve(__dirname, 'build'),
filename: "[name].js",
library: 'Zinc',
libraryTarget: 'umd'
},
plugins: [
new UglifyJsPlugin({
include: /\.min\.js$/,
uglifyOptions: {
compress: true
}
})
],
externals: {
three: {
commonjs: 'THREE',
commonjs2: 'THREE',
amd: 'THREE',
root: 'THREE'
}
}
};
|
Test file existence for brain-dead Jaguar. | # Print embeddable python library, as well as other libs it requires.
# Will prefer static linkage unless invoked with "shared" argument.
# JGG, 8/4/04
import sys, distutils.sysconfig
static_link = 1
nargs = len(sys.argv)
if nargs == 2 and sys.argv[1] == "shared":
static_link = 0
# Note that this adds libraries we've certainly already linked to.
libs = distutils.sysconfig.get_config_var("LIBS")
libs += " " + distutils.sysconfig.get_config_var("SYSLIBS")
if static_link:
prefix = distutils.sysconfig.get_config_var("LIBPL")
pythonlib = distutils.sysconfig.get_config_var("BLDLIBRARY")
if len(pythonlib) > 0:
import os.path
plib = prefix + '/' + pythonlib
# Must see if file exists, because it doesn't in Jaguar!
if os.path.exists(plib):
print plib, libs
sys.exit(0)
# else try shared linkage
linkshared = distutils.sysconfig.get_config_vars("LINKFORSHARED")[0]
# FIXME: Will this sanity test work for all platforms??
# NB: sys.platform can help us if we need to test for platform
if linkshared.find("ython") != -1:
print linkshared, libs
sys.exit(0)
print >> sys.stderr, "***ERROR: Can't find a python to embed."
sys.exit(1)
| # Print embeddable python library, as well as other libs it requires.
# Will prefer static linkage unless invoked with "shared" argument.
# JGG, 8/4/04
import sys, distutils.sysconfig
static_link = 1
nargs = len(sys.argv)
if nargs == 2 and sys.argv[1] == "shared":
static_link = 0
# Note that this adds libraries we've certainly already linked to.
libs = distutils.sysconfig.get_config_var("LIBS")
libs += " " + distutils.sysconfig.get_config_var("SYSLIBS")
if static_link:
prefix = distutils.sysconfig.get_config_var("LIBPL")
pythonlib = distutils.sysconfig.get_config_var("BLDLIBRARY")
if len(pythonlib) > 0:
print prefix + '/' + pythonlib, libs
sys.exit(0)
# else try shared linkage
linkshared = distutils.sysconfig.get_config_vars("LINKFORSHARED")[0]
# FIXME: Will this sanity test work for all platforms??
# NB: sys.platform can help us if we need to test for platform
if linkshared.find("ython") != -1:
print linkshared, libs
sys.exit(0)
print >> sys.stderr, "***ERROR: Can't find a python to embed."
sys.exit(1)
|
Add opbeat tokens to config | /**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
// Exports configuration for use by app.js
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
mongoUrl: process.env.MONGO_URL || process.env.MONGOLAB_URI,
redisUrl: process.env.REDIS_URL || process.env.REDISCLOUD_URL,
googleId: process.env.GCONTACTS_API_ID,
googleSecret: process.env.GCONTACTS_API_SECRET,
appId: process.env.ANYFETCH_API_ID,
appSecret: process.env.ANYFETCH_API_SECRET,
providerUrl: process.env.PROVIDER_URL,
testRefreshToken: process.env.GCONTACTS_TEST_REFRESH_TOKEN,
opbeat: {
organization_id: process.env.OPBEAT_ORGANIZATION_ID,
app_id: process.env.OPBEAT_APP_ID,
secret_token: process.env.OPBEAT_SECRET_TOKEN,
silent: true
}
};
| /**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
// Exports configuration for use by app.js
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
mongoUrl: process.env.MONGO_URL || process.env.MONGOLAB_URI,
redisUrl: process.env.REDIS_URL || process.env.REDISCLOUD_URL,
googleId: process.env.GCONTACTS_API_ID,
googleSecret: process.env.GCONTACTS_API_SECRET,
appId: process.env.ANYFETCH_API_ID,
appSecret: process.env.ANYFETCH_API_SECRET,
providerUrl: process.env.PROVIDER_URL,
testRefreshToken: process.env.GCONTACTS_TEST_REFRESH_TOKEN
};
|
Fix skinning precision issue on iOS
On iOS, by default the bones that are sampled from the bone texture look
like they are using mediump. This can result in noticeable jitter or
other more severe issues depending on the bone transformation matrix.
Fix this by explicitly declaring the sampler as highp. | export default /* glsl */`
#ifdef USE_SKINNING
uniform mat4 bindMatrix;
uniform mat4 bindMatrixInverse;
#ifdef BONE_TEXTURE
uniform highp sampler2D boneTexture;
uniform int boneTextureSize;
mat4 getBoneMatrix( const in float i ) {
float j = i * 4.0;
float x = mod( j, float( boneTextureSize ) );
float y = floor( j / float( boneTextureSize ) );
float dx = 1.0 / float( boneTextureSize );
float dy = 1.0 / float( boneTextureSize );
y = dy * ( y + 0.5 );
vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );
vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );
vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );
vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );
mat4 bone = mat4( v1, v2, v3, v4 );
return bone;
}
#else
uniform mat4 boneMatrices[ MAX_BONES ];
mat4 getBoneMatrix( const in float i ) {
mat4 bone = boneMatrices[ int(i) ];
return bone;
}
#endif
#endif
`;
| export default /* glsl */`
#ifdef USE_SKINNING
uniform mat4 bindMatrix;
uniform mat4 bindMatrixInverse;
#ifdef BONE_TEXTURE
uniform sampler2D boneTexture;
uniform int boneTextureSize;
mat4 getBoneMatrix( const in float i ) {
float j = i * 4.0;
float x = mod( j, float( boneTextureSize ) );
float y = floor( j / float( boneTextureSize ) );
float dx = 1.0 / float( boneTextureSize );
float dy = 1.0 / float( boneTextureSize );
y = dy * ( y + 0.5 );
vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );
vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );
vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );
vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );
mat4 bone = mat4( v1, v2, v3, v4 );
return bone;
}
#else
uniform mat4 boneMatrices[ MAX_BONES ];
mat4 getBoneMatrix( const in float i ) {
mat4 bone = boneMatrices[ int(i) ];
return bone;
}
#endif
#endif
`;
|
Add special character name test case | import unittest
from tailor.utils import charformat
class MyTestCase(unittest.TestCase):
def is_upper_camel_case_test_upper_camel_case_name(self):
self.assertTrue(charformat.is_upper_camel_case('HelloWorld'))
def is_upper_camel_case_test_lower_camel_case_name(self):
self.assertFalse(charformat.is_upper_camel_case('helloWorld'))
def is_upper_camel_case_test_blank_name(self):
self.assertFalse(charformat.is_upper_camel_case(''))
def is_upper_camel_case_test_snake_case_name(self):
self.assertFalse(charformat.is_upper_camel_case('Hello_World'))
def is_upper_camel_case_test_numeric_name(self):
self.assertFalse(charformat.is_upper_camel_case('1ello_world'))
def is_upper_camel_case_test_special_character_name(self):
self.assertFalse(charformat.is_upper_camel_case('!ello_world'))
if __name__ == '__main__':
unittest.main()
| import unittest
from tailor.utils import charformat
class MyTestCase(unittest.TestCase):
def is_upper_camel_case_test_upper_camel_case_name(self):
self.assertTrue(charformat.is_upper_camel_case('HelloWorld'))
def is_upper_camel_case_test_lower_camel_case_name(self):
self.assertFalse(charformat.is_upper_camel_case('helloWorld'))
def is_upper_camel_case_test_blank_name(self):
self.assertFalse(charformat.is_upper_camel_case(''))
def is_upper_camel_case_test_snake_case_name(self):
self.assertFalse(charformat.is_upper_camel_case('Hello_World'))
def is_upper_camel_case_test_numeric_name(self):
self.assertFalse(charformat.is_upper_camel_case('1ello_world'))
if __name__ == '__main__':
unittest.main()
|
Use text instead of json as mysql type. Json is not fully supported in laravel | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddB3ServerTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
\Schema::create('b3servers', function (Blueprint $table){
$table->increments('id');
$table->string('name');
$table->string('rcon')->nullable();
$table->string('identifier');
$table->string('host')->nullable();
$table->integer('port')->nullable();
$table->text('dbSettings');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
\Schema::dropIfExists('b3servers');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddB3ServerTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
\Schema::create('b3servers', function (Blueprint $table){
$table->increments('id');
$table->string('name');
$table->string('rcon')->nullable();
$table->string('identifier');
$table->string('host')->nullable();
$table->integer('port')->nullable();
$table->json('dbSettings');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
\Schema::dropIfExists('b3servers');
}
}
|
Fix bug in blurred context recognition | import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, img[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, img[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
img = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
if img is None or obj_mask is None:
return None
return vertical_blur(img, obj_mask, extracted_object) or \
horizontal_blur(img, obj_mask, extracted_object)
| import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, obj_mask[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, obj_mask[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
return vertical_blur(obj_mask, extracted_object) or \
horizontal_blur(obj_mask, extracted_object)
|
Clean up the command output | var fs = require('fs');
var path = require('path');
var semver = require('semver');
var execSync = require('child_process').execSync;
var packageJSONPath = path.join(process.cwd(), 'package.json');
var packageJSON = require(packageJSONPath);
module.exports = function(newVersion, commitMessage){
var newSemver = packageJSON.version = getNewSemver(newVersion);
fs.writeFileSync(packageJSONPath, JSON.stringify(packageJSON, null, 2));
commitMessage = (commitMessage || 'Release v%s').replace(/%s/g, newSemver);
execCmd('git commit -am "' + commitMessage + '"');
execCmd('git tag v' + newSemver);
execCmd('git push origin --all');
execCmd('git push origin --tags');
if (!packageJSON.private) execCmd('npm publish');
};
function getNewSemver(newVersion) {
var newSemver = semver.valid(newVersion);
if (!newSemver) newSemver = semver.inc(packageJSON.version, newVersion);
if (!newSemver) throw new Error('Invalid new version');
return newSemver;
}
function execCmd(cmd) {
console.log(execSync(cmd).toString().trim());
}
| var fs = require('fs');
var path = require('path');
var semver = require('semver');
var execSync = require('child_process').execSync;
var packageJSONPath = path.join(process.cwd(), 'package.json');
var packageJSON = require(packageJSONPath);
module.exports = function(newVersion, commitMessage){
var newSemver = packageJSON.version = getNewSemver(newVersion);
fs.writeFileSync(packageJSONPath, JSON.stringify(packageJSON, null, 2));
commitMessage = (commitMessage || 'Release v%s').replace(/%s/g, newSemver);
execCmd('git commit -am "' + commitMessage + '"');
execCmd('git tag v' + newSemver);
execCmd('git push origin --all');
execCmd('git push origin --tags');
if (!packageJSON.private) execCmd('npm publish');
};
function getNewSemver(newVersion) {
var newSemver = semver.valid(newVersion);
if (!newSemver) newSemver = semver.inc(packageJSON.version, newVersion);
if (!newSemver) throw new Error('Invalid new version');
return newSemver;
}
function execCmd(cmd) {
console.log(execSync(cmd).toString());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.