text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Support an array of arguments. | var _ = require('lodash');
var os = require('os');
var path = require('path');
var crypto = require('crypto');
var commands = require('./commands.json');
/**
* Look up the command for executing a file in any language.
*
* @param {String} language
* @param {String} file
* @param {Array} args
* @return {String}
*/
module.exports = function (language, file, args) {
// Unsupported language.
if (!commands[language]) {
return;
}
// Render the language using EJS to enable support for inline JavaScript.
return _.template(commands[language], {
file: file,
tmpdir: os.tmpdir(),
tmpfile: path.join(os.tmpdir(), crypto.randomBytes(32).toString('hex')),
dirname: path.dirname,
extname: path.extname,
basename: path.basename,
type: os.type(),
arch: os.arch(),
platform: os.platform(),
sep: path.sep,
join: path.join,
delimiter: path.delimiter,
args: Array.isArray(args) ? args.map(JSON.stringify).join(' ') : args
});
};
| var _ = require('lodash');
var os = require('os');
var path = require('path');
var crypto = require('crypto');
var commands = require('./commands.json');
/**
* Look up the command for executing a file in any language.
*
* @param {String} language
* @param {String} file
* @param {String} args
* @return {String}
*/
module.exports = function (language, file, args) {
// Unsupported language.
if (!commands[language]) {
return;
}
// Render the language using EJS to enable support for inline JavaScript.
return _.template(commands[language], {
file: file,
tmpdir: os.tmpdir(),
tmpfile: path.join(os.tmpdir(), crypto.randomBytes(32).toString('hex')),
dirname: path.dirname,
extname: path.extname,
basename: path.basename,
type: os.type(),
arch: os.arch(),
platform: os.platform(),
sep: path.sep,
join: path.join,
delimiter: path.delimiter,
args: args
});
};
|
Refactor social accounts module (use more of ES6) | 'use strict';
class SocialAccounts {
constructor(obj) {
this.config = obj && obj.config;
this.validator = obj && obj.validator;
this.helperName = obj && obj.helperName;
}
getItemData(account) {
return {
account,
url: this.config.get(`${account}PageUrl`),
icon: `icon-${account}`
}
}
getData(accounts) {
var items = [];
accounts.forEach((account) => {
var item = this.getItemData(account);
items.push(item);
});
return { items }
}
get(accounts) {
this.validator.validate(accounts);
return this.getData(accounts);
}
}
module.exports = SocialAccounts; | 'use strict';
class SocialAccounts {
constructor(obj) {
this.config = obj && obj.config;
this.validator = obj && obj.validator;
this.helperName = obj && obj.helperName;
}
getData(accounts) {
var arr = [];
accounts.forEach((account) => {
arr.push({
account: account,
url: this.config.get(`${account}PageUrl`),
icon: `icon-${account}`
});
});
return {
items: arr
}
}
get(accounts) {
this.validator.validate(accounts);
return this.getData(accounts);
}
}
module.exports = SocialAccounts; |
Fix not awaited ProgressTracker bug | STEP_COUNTS = {
"delete_reference": 2,
"import_reference": 0,
"setup_remote_reference": 0,
"update_remote_reference": 0,
"update_software": 0,
"install_hmms": 0
}
FIRST_STEPS = {
"delete_reference": "delete_indexes",
"import_reference": "load_file",
"setup_remote_reference": "",
"update_remote_reference": "",
"update_software": "",
"install_hmms": ""
}
UNIQUES = [
"update_software",
"install_hmms"
]
class ProgressTracker:
def __init__(self, total, db=None, increment=0.05, factor=1):
self.total = total
self.db = db
self.increment = increment
self.factor = factor
self.count = 0
self.last_reported = 0
def add(self, value):
count = self.count + value
if count > self.total:
raise ValueError("Count cannot exceed total")
self.count = count
return self.progress
def reported(self):
self.last_reported = self.progress
@property
def progress(self):
return round(self.count / self.total * self.factor, 2)
| STEP_COUNTS = {
"delete_reference": 2,
"import_reference": 0,
"setup_remote_reference": 0,
"update_remote_reference": 0,
"update_software": 0,
"install_hmms": 0
}
FIRST_STEPS = {
"delete_reference": "delete_indexes",
"import_reference": "load_file",
"setup_remote_reference": "",
"update_remote_reference": "",
"update_software": "",
"install_hmms": ""
}
UNIQUES = [
"update_software",
"install_hmms"
]
class ProgressTracker:
def __init__(self, total, db=None, increment=0.05, factor=1):
self.total = total
self.db = db
self.increment = increment
self.factor = factor
self.count = 0
self.last_reported = 0
def add(self, value):
count = self.count + value
if count > self.total:
raise ValueError("Count cannot exceed total")
self.count = count
return self.progress
async def reported(self):
self.last_reported = self.progress
@property
def progress(self):
return round(self.count / self.total * self.factor, 2)
|
Add test sample of 404 method | <?php
/**
* Part of CI PHPUnit Test
*
* @author Kenji Suzuki <https://github.com/kenjis>
* @license MIT License
* @copyright 2015 Kenji Suzuki
* @link https://github.com/kenjis/ci-phpunit-test
*/
class Welcome_test extends TestCase
{
public function test_index()
{
$output = $this->request('GET', ['welcome', 'index']);
$this->assertContains('<title>Welcome to CodeIgniter</title>', $output);
}
/**
* @expectedException PHPUnit_Framework_Exception
* @expectedExceptionCode 404
*/
public function test_method_404()
{
$output = $this->request('GET', ['welcome', 'method_not_exist']);
}
public function test_APPPATH()
{
$actual = realpath(APPPATH);
$expected = realpath(__DIR__ . '/../..');
$this->assertEquals(
$expected,
$actual,
'Your APPPATH seems to be wrong. Check your $application_folder in tests/Bootstrap.php'
);
}
}
| <?php
/**
* Part of CI PHPUnit Test
*
* @author Kenji Suzuki <https://github.com/kenjis>
* @license MIT License
* @copyright 2015 Kenji Suzuki
* @link https://github.com/kenjis/ci-phpunit-test
*/
class Welcome_test extends TestCase
{
public function test_index()
{
$output = $this->request('GET', ['welcome', 'index']);
$this->assertContains('<title>Welcome to CodeIgniter</title>', $output);
}
public function test_APPPATH()
{
$actual = realpath(APPPATH);
$expected = realpath(__DIR__ . '/../..');
$this->assertEquals(
$expected,
$actual,
'Your APPPATH seems to be wrong. Check your $application_folder in tests/Bootstrap.php'
);
}
}
|
Add the PAM_SERVICE setting to select a custom pam service for authentication | import pam
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
class PAMBackend(ModelBackend):
SERVICE = getattr(settings, 'PAM_SERVICE', 'login')
def authenticate(self, username=None, password=None):
if pam.authenticate(username, password, service=service):
try:
user = User.objects.get(username=username)
except:
user = User(username=username, password='not stored here')
user.set_unusable_password()
if getattr(settings, 'PAM_IS_SUPERUSER', False):
user.is_superuser = True
if getattr(settings, 'PAM_IS_STAFF', user.is_superuser):
user.is_staff = True
user.save()
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
| import pam
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
class PAMBackend(ModelBackend):
def authenticate(self, username=None, password=None):
if pam.authenticate(username, password):
try:
user = User.objects.get(username=username)
except:
user = User(username=username, password='not stored here')
user.set_unusable_password()
if getattr(settings, 'PAM_IS_SUPERUSER', False):
user.is_superuser = True
if getattr(settings, 'PAM_IS_STAFF', user.is_superuser):
user.is_staff = True
user.save()
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
|
Fix 'boot script' serializer to allow 'created_by' to be inferred as the request.user | from core.models.boot_script import BootScript, ScriptType
from core.models.user import AtmosphereUser
from rest_framework import serializers
class BootScriptSerializer(serializers.HyperlinkedModelSerializer):
created_by = serializers.SlugRelatedField(
slug_field='username', queryset=AtmosphereUser.objects.all(),
required=False)
text = serializers.CharField(source='script_text')
type = serializers.SlugRelatedField(
source='script_type',
slug_field='name',
queryset=ScriptType.objects.all())
def create(self, validated_data):
if 'created_by' not in validated_data:
request = self.context.get('request')
if request and request.user:
validated_data['created_by'] = request.user
return super(BootScriptSerializer, self).create(validated_data)
class Meta:
model = BootScript
# view_name = 'api:v2:boot_script-detail' -- not needed?
fields = ('id', 'created_by', 'title', 'text', 'type')
| from core.models.boot_script import BootScript, ScriptType
from core.models.user import AtmosphereUser
from rest_framework import serializers
class BootScriptSerializer(serializers.HyperlinkedModelSerializer):
created_by = serializers.SlugRelatedField(
slug_field='username', queryset=AtmosphereUser.objects.all())
text = serializers.CharField(source='script_text')
type = serializers.SlugRelatedField(
source='script_type',
slug_field='name',
queryset=ScriptType.objects.all())
def create(self, validated_data):
if 'created_by' not in validated_data:
request = self.context.get('request')
if request and request.user:
validated_data['created_by'] = request.user
return super(BootScriptSerializer, self).create(validated_data)
class Meta:
model = BootScript
# view_name = 'api:v2:boot_script-detail' -- not needed?
fields = ('id', 'created_by', 'title', 'text', 'type')
|
Move comments in above config fields.
This should help avoid confusions as it matches the class' annotation layout and almost every other plugin does it like this. | package com.Acrobot.Breeze.Configuration;
import com.Acrobot.Breeze.Configuration.Annotations.ConfigurationComment;
import java.lang.reflect.Field;
/**
* @author Acrobot
*/
public class FieldParser {
/**
* Parses a field into a YAML-compatible string
*
* @param field Field to parse
* @return Parsed field
*/
public static String parse(Field field) {
StringBuilder builder = new StringBuilder(50);
if (field.isAnnotationPresent(ConfigurationComment.class)) {
builder.append('#').append(field.getAnnotation(ConfigurationComment.class).value()).append('\n');
}
try {
builder.append(field.getName()).append(": ").append(ValueParser.parseToYAML(field.get(null)));
} catch (IllegalAccessException e) {
e.printStackTrace();
return "";
}
return builder.toString();
}
}
| package com.Acrobot.Breeze.Configuration;
import com.Acrobot.Breeze.Configuration.Annotations.ConfigurationComment;
import java.lang.reflect.Field;
/**
* @author Acrobot
*/
public class FieldParser {
/**
* Parses a field into a YAML-compatible string
*
* @param field Field to parse
* @return Parsed field
*/
public static String parse(Field field) {
StringBuilder builder = new StringBuilder(50);
try {
builder.append(field.getName()).append(": ").append(ValueParser.parseToYAML(field.get(null)));
} catch (IllegalAccessException e) {
e.printStackTrace();
return "";
}
if (field.isAnnotationPresent(ConfigurationComment.class)) {
builder.append('\n').append('#').append(field.getAnnotation(ConfigurationComment.class).value());
}
return builder.toString();
}
}
|
Add docblock and format source to PSR-2 | <?php
namespace Loct\Pinger\Provider;
use \Illuminate\Config\FileLoader;
use \Illuminate\Config\Repository;
use \Illuminate\Filesystem\Filesystem;
use \Pimple\Container;
use \Pimple\ServiceProviderInterface;
/**
* Service provider for configuration related classes and parameters.
*
* @author herloct <herloct@gmail.com>
*/
class ConfigProvider implements ServiceProviderInterface
{
/**
* Registers services on the given container.
*
* This method should only be used to configure services and parameters.
* It should not get services.
*
* @param Container $pimple An Container instance
*/
public function register(Container $pimple)
{
$pimple['config_path'] = function ($pimple)
{
return $pimple['app_path'] . '/config';
};
$pimple['environment'] = function ($pimple)
{
return file_exists($pimple['config_path'] . '/dev') ? 'dev' : 'production';
};
$pimple['config'] = function ($pimple)
{
$filesystem = new Filesystem();
$loader = new FileLoader($filesystem, $pimple['config_path']);
return new Repository($loader, $pimple['environment']);
};
}
}
| <?php
namespace Loct\Pinger\Provider;
use \Illuminate\Config\FileLoader;
use \Illuminate\Config\Repository;
use \Illuminate\Filesystem\Filesystem;
use \Pimple\Container;
use \Pimple\ServiceProviderInterface;
class ConfigProvider implements ServiceProviderInterface
{
public function register(Container $pimple)
{
$pimple['config_path'] = function ($pimple) {
return $pimple['app_path'] . '/config';
};
$pimple['environment'] = function ($pimple) {
return file_exists($pimple['config_path'] . '/dev') ? 'dev' : 'production';
};
$pimple['config'] = function ($pimple) {
$filesystem = new Filesystem();
$loader = new FileLoader($filesystem, $pimple['config_path']);
return new Repository($loader, $pimple['environment']);
};
}
} |
Remove debugging statement from CheckPermSetLicenses | import json
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
class CheckPermSetLicenses(BaseSalesforceApiTask):
task_options = {
"permission_sets": {
"description": "List of permission set names to check for, (ex: EinsteinAnalyticsUser)",
"required": True,
}
}
def _run_task(self):
query = self._get_query()
result = self.tooling.query(query)
return result["size"] > 0
def _get_query(self):
where_targets = [f"'{name}'" for name in self.options["permission_sets"]]
return f"""
SELECT Name FROM PermissionSet WHERE Name IN ({','.join(where_targets)})
"""
| import json
from cumulusci.tasks.salesforce import BaseSalesforceApiTask
class CheckPermSetLicenses(BaseSalesforceApiTask):
task_options = {
"permission_sets": {
"description": "List of permission set names to check for, (ex: EinsteinAnalyticsUser)",
"required": True,
}
}
def _run_task(self):
query = self._get_query()
print(query)
result = self.tooling.query(query)
return result["size"] > 0
def _get_query(self):
where_targets = [f"'{name}'" for name in self.options["permission_sets"]]
return f"""
SELECT Name FROM PermissionSet WHERE Name IN ({','.join(where_targets)})
"""
|
Fix logic condition mess in request header checks | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const models = require('../models/index')
const insecurity = require('../lib/insecurity')
const utils = require('../lib/utils')
const cache = require('../data/datacache')
const challenges = cache.challenges
module.exports = function updateUserProfile () {
return (req, res, next) => {
const loggedInUser = insecurity.authenticatedUsers.get(req.cookies.token)
if (loggedInUser) {
models.User.findByPk(loggedInUser.data.id).then(user => {
utils.solveIf(challenges.csrfChallenge, () => {
return ((req.headers.origin && req.headers.origin.includes('://htmledit.squarefree.com'))
|| (req.headers.referrer && req.headers.referrer.includes('://htmledit.squarefree.com')))
&& req.body.username !== user.username })
return user.update({ username: req.body.username })
}).catch(error => {
next(error)
})
} else {
next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress))
}
res.location(process.env.BASE_PATH + '/profile')
res.redirect(process.env.BASE_PATH + '/profile')
}
}
| /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const models = require('../models/index')
const insecurity = require('../lib/insecurity')
const utils = require('../lib/utils')
const cache = require('../data/datacache')
const challenges = cache.challenges
module.exports = function updateUserProfile () {
return (req, res, next) => {
const loggedInUser = insecurity.authenticatedUsers.get(req.cookies.token)
if (loggedInUser) {
models.User.findByPk(loggedInUser.data.id).then(user => {
utils.solveIf(challenges.csrfChallenge, () => { return (req.headers.origin && req.headers.origin.includes('://htmledit.squarefree.com') || req.headers.referrer && req.headers.referrer.includes('://htmledit.squarefree.com')) && req.body.username !== user.username })
return user.update({ username: req.body.username })
}).catch(error => {
next(error)
})
} else {
next(new Error('Blocked illegal activity by ' + req.connection.remoteAddress))
}
res.location(process.env.BASE_PATH + '/profile')
res.redirect(process.env.BASE_PATH + '/profile')
}
}
|
Fix error in enclosed mass calculation and fix unit handling. | #!/usr/bin/env python
# -----------------------------------------------------------------------------
# GENHERNQUIST.ENCMASS
# Laura L Watkins [lauralwatkins@gmail.com]
# -----------------------------------------------------------------------------
import numpy as np
from astropy import units as u
from scipy import special
def encmass(r, norm, rs, alpha, beta, gamma):
"""
Enclosed mass profile of a generalised Hernquist model.
INPUTS
r : radial variable (requires unit)
norm : normalisation (requires unit)
rs : scale radius of model (requires unit)
alpha : sharpness of transition between inner and outer
beta : outer logarithmic slope
gamma : inner logarithmic slope
"""
a = (3.-gamma)/alpha
b = (gamma-beta)/alpha
y = ((r/rs).to(u.dimensionless_unscaled).value)**alpha
fn = lambda x: x**a * special.hyp2f1(a, -b, 1+a, -x)/a
encmass = (4*np.pi*norm*rs**3*fn(y)/alpha).to(u.Msun)
return encmass
| #!/usr/bin/env python
# -----------------------------------------------------------------------------
# GENHERNQUIST.ENCMASS
# Laura L Watkins [lauralwatkins@gmail.com]
# -----------------------------------------------------------------------------
import numpy as np
from astropy import units as u
from scipy import special
def encmass(r, norm, rs, alpha, beta, gamma):
"""
Enclosed mass profile of a generalised Hernquist model.
INPUTS
r : radial variable (requires unit)
norm : normalisation (requires unit)
rs : scale radius of model (requires unit)
alpha : sharpness of transition between inner and outer
beta : outer logarithmic slope
gamma : inner logarithmic slope
"""
a = (3.-gamma)/alpha
b = (gamma-beta)/alpha
y = (r/rs)**alpha
fn = lambda x: x**a * special.hyp2f1(a, -b, 1+a, -x)/a
encmass = (4*np.pi*norm*rs**3*fn(y.value)).to(u.Msun)
return encmass
|
Include address information in unit fetch | import {createAction} from 'redux-actions';
import values from 'lodash/values';
import {UnitActions} from './constants';
import {Action} from '../common/constants';
import {ApiResponse, UnitServices} from './constants';
export const fetchUnits = (/*params: Object*/): Action =>
createAction(UnitActions.FETCH)({params: {
service: `${values(UnitServices).join(',')}`,
only: 'id,name,location,street_address,address_zip',
include: 'observations,services',
page_size: 1000
}});
export const receiveUnits = (data: ApiResponse): Action =>
createAction(UnitActions.RECEIVE)(data);
export const clearSearch = () =>
createAction(UnitActions.SEARCH_CLEAR)();
export const searchUnits = (input: string, params: Object): Action => {
const init = {
input,
service: `${values(UnitServices).join(',')}`
};
params = Object.assign({}, init, params);
return createAction(UnitActions.SEARCH_REQUEST)({params});
};
export const fetchSearchSuggestions = (input: string): Action =>
createAction(UnitActions.FETCH_SEARCH_SUGGESTIONS)({params: {
input,
service: `${values(UnitServices).join(',')}`,
page_size: 5
}});
export const receiveSearchResults = (results: Array<Object>) =>
createAction(UnitActions.SEARCH_RECEIVE)(results);
export const receiveSearchSuggestions = (results: Array<Object>) =>
createAction(UnitActions.RECEIVE_SEARCH_SUGGESTIONS)(results);
| import {createAction} from 'redux-actions';
import values from 'lodash/values';
import {UnitActions} from './constants';
import {Action} from '../common/constants';
import {ApiResponse, UnitServices} from './constants';
export const fetchUnits = (/*params: Object*/): Action =>
createAction(UnitActions.FETCH)({params: {
service: `${values(UnitServices).join(',')}`,
only: 'id,name,location',
include: 'observations,services',
page_size: 1000
}});
export const receiveUnits = (data: ApiResponse): Action =>
createAction(UnitActions.RECEIVE)(data);
export const clearSearch = () =>
createAction(UnitActions.SEARCH_CLEAR)();
export const searchUnits = (input: string, params: Object): Action => {
const init = {
input,
service: `${values(UnitServices).join(',')}`
};
params = Object.assign({}, init, params);
return createAction(UnitActions.SEARCH_REQUEST)({params});
};
export const fetchSearchSuggestions = (input: string): Action =>
createAction(UnitActions.FETCH_SEARCH_SUGGESTIONS)({params: {
input,
service: `${values(UnitServices).join(',')}`,
page_size: 5
}});
export const receiveSearchResults = (results: Array<Object>) =>
createAction(UnitActions.SEARCH_RECEIVE)(results);
export const receiveSearchSuggestions = (results: Array<Object>) =>
createAction(UnitActions.RECEIVE_SEARCH_SUGGESTIONS)(results);
|
[Bundle] Make getPath() less error prone by allowing both backward and forward slashes | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\TwigBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\TwigEnvironmentPass;
/**
* Bundle.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class TwigBundle extends Bundle
{
public function registerExtensions(ContainerBuilder $container)
{
parent::registerExtensions($container);
$container->addCompilerPass(new TwigEnvironmentPass());
}
/**
* {@inheritdoc}
*/
public function getNamespace()
{
return __NAMESPACE__;
}
/**
* {@inheritdoc}
*/
protected function getPath()
{
return __DIR__;
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\TwigBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\TwigEnvironmentPass;
/**
* Bundle.
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class TwigBundle extends Bundle
{
public function registerExtensions(ContainerBuilder $container)
{
parent::registerExtensions($container);
$container->addCompilerPass(new TwigEnvironmentPass());
}
/**
* {@inheritdoc}
*/
public function getNamespace()
{
return __NAMESPACE__;
}
/**
* {@inheritdoc}
*/
public function getPath()
{
return strtr(__DIR__, '\\', '/');
}
}
|
Return data in dict form | #!/usr/bin/env python3
import os
from flask import Flask, jsonify, send_from_directory, abort, Response, request
import psycopg2
import psycopg2.extras
app = Flask(__name__)
conn = psycopg2.connect("dbname='rivers' user='nelson' host='localhost' password='NONE'")
#@app.route('/')
#def index():
# return send_from_directory('.', 'index.html')
@app.route('/gauges/list/<string:xmin>/<string:ymin>/<string:xmax>/<string:ymax>', methods=['GET'])
def show_gaugelist(xmin,ymin,xmax,ymax):
cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
cur.execute("""
SELECT *, ST_X(the_geom) as lng, ST_Y(the_geom) as lat
FROM gageloc
WHERE geom
@ -- contained by, gets fewer rows -- ONE YOU NEED!
ST_MakeEnvelope (
%(xmin)s, %(ymin)s, -- bounding
%(xmax)s, %(ymax)s, -- box limits
900913)
""", {"xmin":xmin,"ymin":ymin,"xmax":xmax,"ymax":ymax})
return jsonify(cur.fetchall())
if __name__ == '__main__':
app.run(debug=True)
| #!/usr/bin/env python3
import os
from flask import Flask, jsonify, send_from_directory, abort, Response, request
import psycopg2
app = Flask(__name__)
conn = psycopg2.connect("dbname='rivers' user='nelson' host='localhost' password='NONE'")
#@app.route('/')
#def index():
# return send_from_directory('.', 'index.html')
@app.route('/gauges/list/<string:xmin>/<string:ymin>/<string:xmax>/<string:ymax>', methods=['GET'])
def show_gaugelist(xmin,ymin,xmax,ymax):
print('hi')
cur = conn.cursor()
cur.execute("""
SELECT *, ST_X(the_geom) as lng, ST_Y(the_geom) as lat
FROM gageloc
WHERE geom
@ -- contained by, gets fewer rows -- ONE YOU NEED!
ST_MakeEnvelope (
%(xmin)s, %(ymin)s, -- bounding
%(xmax)s, %(ymax)s, -- box limits
900913)
""", {"xmin":xmin,"ymin":ymin,"xmax":xmax,"ymax":ymax})
print(cur.fetchall())
return Response("hi", mimetype='text')
#return Response(outcss, mimetype='text/css')
if __name__ == '__main__':
app.run(debug=True)
|
Fix scan not emitting initial value | const combine = (combiner, ...observables) => next => {
let state = Array(observables.length)
observables.forEach((base, index) => base(value => {
state[index] = value
if(Object.keys(state).length === state.length)
next(combiner(...state))
}))
}
const constant = (base, value) => map(base, () => value)
const filter = (base, predicate) => next =>
base(value => predicate(value) && next(value))
const flatMap = (base, mapper) => next =>
base(value => mapper(value)(next))
const from = values => next => values.forEach(next)
const just = value => next => next(value)
const map = (base, mapper) => next =>
base(value => next(mapper(value)))
const merge = (...observables) => next =>
observables.forEach(base => base(next))
const periodic = interval => next => setInterval(next, interval)
const scan = (base, reducer, initial) => next => {
let state = initial
next(state)
base(value => {
state = reducer(state, value)
next(state)
})
}
export {
combine,
constant,
filter,
flatMap,
from,
just,
map,
merge,
periodic,
scan,
}
| const combine = (combiner, ...observables) => next => {
let state = Array(observables.length)
observables.forEach((base, index) => base(value => {
state[index] = value
if(Object.keys(state).length === state.length)
next(combiner(...state))
}))
}
const constant = (base, value) => map(base, () => value)
const filter = (base, predicate) => next =>
base(value => predicate(value) && next(value))
const flatMap = (base, mapper) => next =>
base(value => mapper(value)(next))
const from = values => next => values.forEach(next)
const just = value => next => next(value)
const map = (base, mapper) => next =>
base(value => next(mapper(value)))
const merge = (...observables) => next =>
observables.forEach(base => base(next))
const periodic = interval => next => setInterval(next, interval)
const scan = (base, reducer, initial) => next => {
let state = initial
base(value => {
state = reducer(state, value)
next(state)
})
}
export {
combine,
constant,
filter,
flatMap,
from,
just,
map,
merge,
periodic,
scan,
}
|
Fix 345. Reverse Vowels of a String to use two pointers | package leetcode
// 345. Reverse Vowels of a String
func reverseVowels(s string) string {
res := make([]byte, len(s))
copy(res, s)
vowels := map[byte]bool{'a': true, 'i': true, 'u': true, 'e': true, 'o': true, 'A': true, 'I': true, 'U': true, 'E': true, 'O': true}
for i, k := 0, len(s)-1; i < k; {
for i < k {
if _, ok := vowels[s[i]]; ok {
break
}
i++
}
for i < k {
if _, ok := vowels[s[k]]; ok {
break
}
k--
}
res[i], res[k] = res[k], res[i]
i++
k--
}
return string(res)
}
| package leetcode
// 345. Reverse Vowels of a String
func reverseVowels(s string) string {
res := make([]byte, 0)
vowels := make([]byte, 0)
for i := 0; i < len(s); i++ {
switch b := s[i]; b {
case 'a', 'i', 'u', 'e', 'o', 'A', 'I', 'U', 'E', 'O':
vowels = append(vowels, b)
}
}
for i, k := 0, len(vowels)-1; i < len(s); i++ {
switch b := s[i]; b {
case 'a', 'i', 'u', 'e', 'o', 'A', 'I', 'U', 'E', 'O':
res = append(res, vowels[k])
k--
default:
res = append(res, b)
}
}
return string(res)
}
|
Add timeout to email task
Email task needs a timeout, as there were some cases where celery caused the
task to hang. | """Basic tasks"""
import logging
from celery import task
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
log = logging.getLogger(__name__)
EMAIL_TIME_LIMIT = 30
@task(queue='web', time_limit=EMAIL_TIME_LIMIT)
def send_email_task(recipient, subject, template, template_html, context=None):
"""Send multipart email
recipient
Email recipient address
subject
Email subject header
template
Plain text template to send
template_html
HTML template to send as new message part
context
A dictionary to pass into the template calls
"""
msg = EmailMultiAlternatives(
subject,
get_template(template).render(context),
settings.DEFAULT_FROM_EMAIL,
[recipient]
)
msg.attach_alternative(get_template(template_html).render(context),
'text/html')
msg.send()
log.info('Sent email to recipient: %s', recipient)
| """Basic tasks"""
import logging
from celery import task
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
log = logging.getLogger(__name__)
@task(queue='web')
def send_email_task(recipient, subject, template, template_html, context=None):
"""Send multipart email
recipient
Email recipient address
subject
Email subject header
template
Plain text template to send
template_html
HTML template to send as new message part
context
A dictionary to pass into the template calls
"""
msg = EmailMultiAlternatives(
subject,
get_template(template).render(context),
settings.DEFAULT_FROM_EMAIL,
[recipient]
)
msg.attach_alternative(get_template(template_html).render(context),
'text/html')
msg.send()
log.info('Sent email to recipient: %s', recipient)
|
Fix Python packaging to use correct git log for package time/version stamps (2nd try) | from setuptools.command.egg_info import egg_info
import subprocess
import time
class EggInfoFromGit(egg_info):
"""Tag the build with git commit timestamp.
If a build tag has already been set (e.g., "egg_info -b", building
from source package), leave it alone.
"""
def git_timestamp_tag(self):
gitinfo = subprocess.check_output(
['git', 'log', '--first-parent', '--max-count=1',
'--format=format:%ct']).strip()
return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))
def tags(self):
if self.tag_build is None:
self.tag_build = self.git_timestamp_tag()
return egg_info.tags(self)
| from setuptools.command.egg_info import egg_info
import subprocess
import time
class EggInfoFromGit(egg_info):
"""Tag the build with git commit timestamp.
If a build tag has already been set (e.g., "egg_info -b", building
from source package), leave it alone.
"""
def git_timestamp_tag(self):
gitinfo = subprocess.check_output(
['git', 'log', '--first-parent', '--max-count=1',
'--format=format:%ct', '..']).strip()
return time.strftime('.%Y%m%d%H%M%S', time.gmtime(int(gitinfo)))
def tags(self):
if self.tag_build is None:
self.tag_build = self.git_timestamp_tag()
return egg_info.tags(self)
|
Remove import logging. This file is now identical to the branch point. | # Copyright 2009-2010 by Ka-Ping Yee
#
# 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.
"""Common exception classes."""
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
| # Copyright 2009-2010 by Ka-Ping Yee
#
# 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.
"""Common exception classes."""
import logging
class ErrorMessage(Exception):
"""Raise this exception to show an error message to the user."""
def __init__(self, status, message):
self.status = status
self.message = message
class Redirect(Exception):
"""Raise this exception to redirect to another page."""
def __init__(self, url):
self.url = url
|
Change doc setting for development. | """
Functions that return external URLs, for example for the Vesper documentation.
"""
import vesper.version as vesper_version
_USE_LATEST_DOCUMENTATION_VERSION = True
"""Set this `True` during development, `False` for release."""
def _create_documentation_url():
if _USE_LATEST_DOCUMENTATION_VERSION:
doc_version = 'latest'
else:
doc_version = vesper_version.full_version
return 'https://vesper.readthedocs.io/en/' + doc_version + '/'
def _create_tutorial_url():
return _create_documentation_url() + 'tutorial.html'
documentation_url = _create_documentation_url()
tutorial_url = _create_tutorial_url()
source_code_url = 'https://github.com/HaroldMills/Vesper'
| """
Functions that return external URLs, for example for the Vesper documentation.
"""
import vesper.version as vesper_version
_USE_LATEST_DOCUMENTATION_VERSION = False
"""Set this `True` during development, `False` for release."""
def _create_documentation_url():
if _USE_LATEST_DOCUMENTATION_VERSION:
doc_version = 'latest'
else:
doc_version = vesper_version.full_version
return 'https://vesper.readthedocs.io/en/' + doc_version + '/'
def _create_tutorial_url():
return _create_documentation_url() + 'tutorial.html'
documentation_url = _create_documentation_url()
tutorial_url = _create_tutorial_url()
source_code_url = 'https://github.com/HaroldMills/Vesper'
|
Optimize category titles through replacing | package de.hfu.studiportal.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ExamCategory implements Serializable {
private static final long serialVersionUID = -5178814560848378523L;
private List<Exam> examList;
private String categoryName;
public ExamCategory(String categoryName) {
this.setCategoryName(categoryName);
this.examList = new ArrayList<>();
}
public String getCategoryName() {
return this.categoryName;
}
public void setCategoryName(String newName) {
//Replace long terms with short ones to keep the titles short.
//Replacing only parts of the title will reserve the meaning (even with unknown titles)
this.categoryName = newName.replace(":", "").replace("*", "")
.replace("Module/Teilmodule", "Module").replace("(ECTS) ", "")
.replace("Bestandene Module", "Bestanden").trim();
}
public void addExam(Exam e) {
this.examList.add(e);
}
public void removeExam(Exam e) {
this.examList.remove(e);
}
public void removeExam(int index) {
this.examList.remove(index);
}
public int getExamCount() {
return this.examList.size();
}
public Exam getExam(int index) {
return this.examList.get(index);
}
public List<Exam> getAllExams() {
return new ArrayList<>(this.examList);
}
}
| package de.hfu.studiportal.data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ExamCategory implements Serializable {
private static final long serialVersionUID = -5178814560848378523L;
private List<Exam> examList;
private String categoryName;
public ExamCategory(String categoryName) {
this.setCategoryName(categoryName);
this.examList = new ArrayList<>();
}
public String getCategoryName() {
return this.categoryName;
}
public void setCategoryName(String newName) {
this.categoryName = newName.replace(":", "").replace("*", "");
}
public void addExam(Exam e) {
this.examList.add(e);
}
public void removeExam(Exam e) {
this.examList.remove(e);
}
public void removeExam(int index) {
this.examList.remove(index);
}
public int getExamCount() {
return this.examList.size();
}
public Exam getExam(int index) {
return this.examList.get(index);
}
public List<Exam> getAllExams() {
return new ArrayList<>(this.examList);
}
}
|
Use text index on Lookup.text | /* Catalog search - db schema
Copyright 2014 Commons Machinery http://commonsmachinery.se/
Distributed under an AGPL_v3 license, please see LICENSE in the top dir.
*/
'use strict';
var debug = require('debug')('catalog:search:db'); // jshint ignore:line
// Common libs
var mongo = require('../../../lib/mongo');
var config = require('../../../lib/config');
// Modules
var event = require('../../event/event');
var ObjectId = mongo.Schema.Types.ObjectId;
var Lookup = mongo.schema(
{
text: 'string',
uri: 'string',
object_type: 'string',
object_id: ObjectId,
property_type: 'string',
property_id: ObjectId,
score: Number,
}
);
Lookup.index({ text: 'text' });
Lookup.index('uri', { sparse: true });
Lookup.index({ 'object_id': 1, 'property_id': 1 }); // TODO: unique?
// Define the search model
var conn = mongo.connection();
exports.Lookup = conn.model('Lookup', Lookup);
exports.SearchEvent = conn.model('SearchEvent', event.EventStagingSchema);
// Connect, returning a promise that resolve when connected
exports.connect = function connect(options) {
return mongo.openConnection(conn, config.search.db, options).return(true);
};
| /* Catalog search - db schema
Copyright 2014 Commons Machinery http://commonsmachinery.se/
Distributed under an AGPL_v3 license, please see LICENSE in the top dir.
*/
'use strict';
var debug = require('debug')('catalog:search:db'); // jshint ignore:line
// Common libs
var mongo = require('../../../lib/mongo');
var config = require('../../../lib/config');
// Modules
var event = require('../../event/event');
var ObjectId = mongo.Schema.Types.ObjectId;
var Lookup = mongo.schema(
{
text: 'string',
uri: 'string',
object_type: 'string',
object_id: ObjectId,
property_type: 'string',
property_id: ObjectId,
score: Number,
}
);
Lookup.index('text', { sparse: true });
Lookup.index('uri', { sparse: true });
Lookup.index({ 'object_id': 1, 'property_id': 1 }); // TODO: unique?
// Define the search model
var conn = mongo.connection();
exports.Lookup = conn.model('Lookup', Lookup);
exports.SearchEvent = conn.model('SearchEvent', event.EventStagingSchema);
// Connect, returning a promise that resolve when connected
exports.connect = function connect(options) {
return mongo.openConnection(conn, config.search.db, options).return(true);
};
|
Use standard env var for DATABASE_URL | # -*- coding: utf-8 -*-
"""
Application configuration
"""
import os
from os.path import dirname, join
# get settings from environment, or credstash if running in AWS
env = os.environ
if env.get('SETTINGS') == 'AWS':
from lib.aws_env import env
ASSETS_DEBUG = False
DEBUG = bool(env.get('DEBUG', True))
HUMANIZE_USE_UTC = True
MARKDOWN_EXTENSIONS = [
'markdown.extensions.nl2br',
'markdown.extensions.sane_lists',
'markdown.extensions.smart_strong',
'markdown.extensions.smarty',
]
SECRET_KEY = env.get('SECRET_KEY', os.urandom(24))
SESSION_COOKIE_SECURE = False
SQLALCHEMY_DATABASE_PATH = join(dirname(__file__), '../development.db')
SQLALCHEMY_DATABASE_URI = env.get(
'DATABASE_URL',
'sqlite:///{}'.format(SQLALCHEMY_DATABASE_PATH))
SQLALCHEMY_TRACK_MODIFICATIONS = bool(env.get(
'SQLALCHEMY_TRACK_MODIFICATIONS',
False))
TESTING = bool(env.get('TESTING', False))
| # -*- coding: utf-8 -*-
"""
Application configuration
"""
import os
from os.path import dirname, join
# get settings from environment, or credstash if running in AWS
env = os.environ
if env.get('SETTINGS') == 'AWS':
from lib.aws_env import env
ASSETS_DEBUG = False
DEBUG = bool(env.get('DEBUG', True))
HUMANIZE_USE_UTC = True
MARKDOWN_EXTENSIONS = [
'markdown.extensions.nl2br',
'markdown.extensions.sane_lists',
'markdown.extensions.smart_strong',
'markdown.extensions.smarty',
]
SECRET_KEY = env.get('SECRET_KEY', os.urandom(24))
SESSION_COOKIE_SECURE = False
SQLALCHEMY_DATABASE_PATH = join(dirname(__file__), '../development.db')
SQLALCHEMY_DATABASE_URI = env.get(
'DATABASE_URI',
'sqlite:///{}'.format(SQLALCHEMY_DATABASE_PATH))
SQLALCHEMY_TRACK_MODIFICATIONS = bool(env.get(
'SQLALCHEMY_TRACK_MODIFICATIONS',
False))
TESTING = bool(env.get('TESTING', False))
|
Add wait for contact element to be visible before editing | module.exports = {
url: process.env.QA_HOST,
elements: {
editContactDetailsButton: 'a[href*="/edit"]',
auditHistoryTab: 'a[href*="/audit"]',
telephone: '#field-telephone_number',
telephoneCountryCode: '#field-telephone_countrycode',
archiveReason: 'label[for=field-archived_reason-1]',
unarchiveAnContactButton: 'a[href*="/unarchive"]',
userName: 'a[href*="/profile"]',
},
commands: [
{
editContactDetails (telephone, countryCode, number) {
this
.click('@editContactDetailsButton')
.waitForElementVisible('@telephoneCountryCode')
.waitForElementVisible('@telephone')
if (number > 1) {
this
.clearValue('@telephoneCountryCode')
.setValue('@telephoneCountryCode', countryCode)
}
this
.clearValue('@telephone')
.setValue('@telephone', telephone)
return this
},
},
],
}
| module.exports = {
url: process.env.QA_HOST,
elements: {
editContactDetailsButton: 'a[href*="/edit"]',
auditHistoryTab: 'a[href*="/audit"]',
telephone: '#field-telephone_number',
telephoneCountryCode: '#field-telephone_countrycode',
archiveReason: 'label[for=field-archived_reason-1]',
unarchiveAnContactButton: 'a[href*="/unarchive"]',
userName: 'a[href*="/profile"]',
},
commands: [
{
editContactDetails (telephone, countryCode, number) {
this.click('@editContactDetailsButton')
if (number > 1) {
this.clearValue('@telephoneCountryCode')
this.setValue('@telephoneCountryCode', countryCode)
}
this.clearValue('@telephone')
this.setValue('@telephone', telephone)
return this
},
},
],
}
|
Fix golint using type in variable declaration
This fixes:
main_test.go:25:9: should omit type discoAliasFlag from
declaration of var a; it will be inferred from the right-hand side
Closes #29 | package main
import (
"flag"
"testing"
)
func TestDefaultDisco(t *testing.T) {
v := discoAliases[defaultDisco]
if v == "" {
t.Fatalf("alias for %q is zero; all aliases: %v", defaultDisco, discoAliases)
}
}
func TestDiscoAliasFlag(t *testing.T) {
tests := []struct {
a discoAliasFlag
args []string
want string
}{
{defaultDisco, []string{"-d", "letsencrypt-staging"}, discoAliases["letsencrypt-staging"]},
{defaultDisco, []string{"-d", "https://disco"}, "https://disco"},
}
for i, test := range tests {
var a = test.a
fs := flag.NewFlagSet("test", flag.ContinueOnError)
fs.Var(&a, "d", "")
if err := fs.Parse(test.args); err != nil {
t.Errorf("%d: parse(%v): %v", i, test.args, err)
continue
}
if a.String() != test.want {
t.Errorf("%d: a = %q; want %q", i, a, test.want)
}
}
}
| package main
import (
"flag"
"testing"
)
func TestDefaultDisco(t *testing.T) {
v := discoAliases[defaultDisco]
if v == "" {
t.Fatalf("alias for %q is zero; all aliases: %v", defaultDisco, discoAliases)
}
}
func TestDiscoAliasFlag(t *testing.T) {
tests := []struct {
a discoAliasFlag
args []string
want string
}{
{defaultDisco, []string{"-d", "letsencrypt-staging"}, discoAliases["letsencrypt-staging"]},
{defaultDisco, []string{"-d", "https://disco"}, "https://disco"},
}
for i, test := range tests {
var a discoAliasFlag = test.a
fs := flag.NewFlagSet("test", flag.ContinueOnError)
fs.Var(&a, "d", "")
if err := fs.Parse(test.args); err != nil {
t.Errorf("%d: parse(%v): %v", i, test.args, err)
continue
}
if a.String() != test.want {
t.Errorf("%d: a = %q; want %q", i, a, test.want)
}
}
}
|
Fix minor issues in package class | package com.gitrekt.resort.model.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "resort.packages")
public class Package {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "price_per_person")
private double pricePerPerson;
public Package(String name, double pricePerPerson){
this.name = name;
this.pricePerPerson = pricePerPerson;
}
public String getName(){
return name;
}
//Returns the price rate per person for the package
public double getPricePerPerson(){
return pricePerPerson;
}
}
| package com.gitrekt.resort.model.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "resort.guest_packages")
//Class for a guest's package
public class Package {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "price_per_person")
private double pricePerPerson;
//The constructor for this class
public Package(String name, double pricePerPerson){
this.name = name;
this.pricePerPerson = pricePerPerson;
}
//Returns the name assocociated with the package
public String getName(){
return name;
}
//Returns the price rate per person for the package
public double getPricePerPerson(){
return pricePerPerson;
}
}
|
Add support for PHP 5.5 DateTimeInterface | <?php
namespace Phive\Queue;
use Phive\Queue\Exception\InvalidArgumentException;
class QueueUtils
{
private function __construct()
{
}
/**
* @param mixed $eta
*
* @return int The Unix timestamp.
*
* @throws InvalidArgumentException
*/
public static function normalizeEta($eta)
{
if (null === $eta) {
return time();
}
if (is_string($eta)) {
$eta = date_create($eta);
}
if ($eta instanceof \DateTime || $eta instanceof \DateTimeInterface) {
return $eta->getTimestamp();
}
if (is_int($eta)) {
return $eta;
}
throw new InvalidArgumentException('The eta parameter is not valid.');
}
}
| <?php
namespace Phive\Queue;
use Phive\Queue\Exception\InvalidArgumentException;
class QueueUtils
{
private function __construct()
{
}
/**
* @param mixed $eta
*
* @return int The Unix timestamp.
*
* @throws InvalidArgumentException
*/
public static function normalizeEta($eta)
{
if (null === $eta) {
return time();
}
if (is_string($eta)) {
$eta = date_create($eta);
}
if ($eta instanceof \DateTime) {
return $eta->getTimestamp();
}
if (is_int($eta)) {
return $eta;
}
throw new InvalidArgumentException('The eta parameter is not valid.');
}
}
|
Use forEach() in place of for-loop | import geojs from 'geojs/geo.js';
import VisComponent from '../../VisComponent';
export default class Geo extends VisComponent {
constructor (el, options) {
super(el);
this.plot = geojs.map({
node: el,
zoom: 6,
center: {x: 28.9550, y: 41.0136}
});
this.plot.createLayer('osm');
if (options.features) {
options.features.forEach(feature => {
this.plot.createLayer('feature')
.createFeature(feature.type)
.data(feature.data)
.position(d => ({
x: d[feature.position.x],
y: d[feature.position.y]
}));
});
this.plot.draw();
}
}
render () {
this.plot.draw();
}
}
| import geojs from 'geojs/geo.js';
import VisComponent from '../../VisComponent';
export default class Geo extends VisComponent {
constructor (el, options) {
super(el);
this.plot = geojs.map({
node: el,
zoom: 6,
center: {x: 28.9550, y: 41.0136}
});
this.plot.createLayer('osm');
if (options.features) {
for (let i = 0; i < options.features.length; ++i) {
this.plot.createLayer('feature')
.createFeature(options.features[i].type)
.data(options.features[i].data)
.position(d => ({
x: d[options.features[i].position.x],
y: d[options.features[i].position.y]
}));
}
this.plot.draw();
}
}
render () {
this.plot.draw();
}
}
|
Add DEFAULT_MAX_DELAY as 200 ms. | /*
* Kurento Android Media: Android Media Library based on FFmpeg.
* Copyright (C) 2011 Tikal Technologies
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kurento.kas.media.rx;
/**
*
* @author mparis
*
*/
public class MediaRx {
public static final int DEFAULT_MAX_DELAY = 200;
public static native int startVideoRx(String sdp_str, int maxDelay, VideoRx videoPlayer);
public static native int stopVideoRx();
public static native int startAudioRx(String sdp_str, int maxDelay, AudioRx audioPlayer);
public static native int stopAudioRx();
static {
System.loadLibrary("kas-media-native");
}
}
| /*
* Kurento Android Media: Android Media Library based on FFmpeg.
* Copyright (C) 2011 Tikal Technologies
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.kurento.kas.media.rx;
/**
*
* @author mparis
*
*/
public class MediaRx {
public static native int startVideoRx(String sdp_str, int maxDelay, VideoRx videoPlayer);
public static native int stopVideoRx();
public static native int startAudioRx(String sdp_str, int maxDelay, AudioRx audioPlayer);
public static native int stopAudioRx();
static {
System.loadLibrary("kas-media-native");
}
}
|
Add session info to extra data | #!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra_data={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
extra = {
'session': get_session_data(),
}
if extra_data: extra.update(extra_data)
return sentry.captureMessage(message, extra=extra)
| #!/usr/bin/env python
# encoding: utf-8
import logging
from raven.contrib.flask import Sentry
from framework.sessions import get_session
from website import settings
logger = logging.getLogger(__name__)
sentry = Sentry(dsn=settings.SENTRY_DSN)
# Nothing in this module should send to Sentry if debug mode is on
# or if Sentry isn't configured.
enabled = (not settings.DEBUG_MODE) and settings.SENTRY_DSN
def get_session_data():
try:
return get_session().data
except (RuntimeError, AttributeError):
return {}
def log_exception():
if not enabled:
logger.warning('Sentry called to log exception, but is not active')
return None
return sentry.captureException(extra={
'session': get_session_data(),
})
def log_message(message, extra={}):
if not enabled:
logger.warning(
'Sentry called to log message, but is not active: %s' % message
)
return None
return sentry.captureMessage(message, extra=extra)
|
Remove line that was previously removed | <?php
/*
PufferPanel - A Game Server Management Panel
Copyright (c) 2015 Dane Everitt
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
*/
namespace PufferPanel\Core;
$klein->respond('POST', '/node/ajax/console/power', function($request, $response) use ($core) {
if(!$core->permissions->has('console.power')) {
$response->code(403);
$response->body('You do not have permission to perform this action.')->send();
return;
}
if(!$core->daemon->powerOn()) {
$response->body("Unable to power on server due to a daemon error.")->send();
} else {
$response->body("ok")->send();
}
});
| <?php
/*
PufferPanel - A Game Server Management Panel
Copyright (c) 2015 Dane Everitt
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
*/
namespace PufferPanel\Core;
$klein->respond('POST', '/node/ajax/console/power', function($request, $response) use ($core) {
if(!$core->permissions->has('console.power')) {
$response->code(403);
$response->body('You do not have permission to perform this action.')->send();
return;
}
if(!$core->daemon->powerOn()) {
$response->body("Unable to power on server due to a daemon error.")->send();
} else {
$response->body("ok")->send();
}
});
include('files/routes.php'); |
Choose a more appropriate glyph for People.
Summary:
Test Plan:
Reviewers:
CC: | <?php
/*
* Copyright 2011 Facebook, 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.
*/
abstract class PhabricatorPeopleController extends PhabricatorController {
public function buildStandardPageResponse($view, array $data) {
$page = $this->buildStandardPageView();
$page->setApplicationName('People');
$page->setBaseURI('/people/');
$page->setTitle(idx($data, 'title'));
$page->setGlyph("\xE2\x99\x9F");
$page->appendChild($view);
$response = new AphrontWebpageResponse();
return $response->setContent($page->render());
}
}
| <?php
/*
* Copyright 2011 Facebook, 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.
*/
abstract class PhabricatorPeopleController extends PhabricatorController {
public function buildStandardPageResponse($view, array $data) {
$page = $this->buildStandardPageView();
$page->setApplicationName('People');
$page->setBaseURI('/people/');
$page->setTitle(idx($data, 'title'));
$page->setGlyph("\xE2\x99\xA5");
$page->appendChild($view);
$response = new AphrontWebpageResponse();
return $response->setContent($page->render());
}
}
|
Fix return in for loop instead of continue | 'use strict';
const createLifecyclesManager = db => {
let subscribers = [];
const lifecycleManager = {
subscribe(subscriber) {
// TODO: verify subscriber
subscribers.push(subscriber);
return () => {
subscribers.splice(subscribers.indexOf(subscriber), 1);
};
},
createEvent(action, uid, properties) {
const model = db.metadata.get(uid);
return {
action,
model,
...properties,
};
},
async run(action, uid, properties) {
for (const subscriber of subscribers) {
if (typeof subscriber === 'function') {
const event = this.createEvent(action, uid, properties);
await subscriber(event);
continue;
}
const hasAction = action in subscriber;
const hasModel = !subscriber.models || subscriber.models.includes(uid);
if (hasAction && hasModel) {
const event = this.createEvent(action, uid, properties);
await subscriber[action](event);
}
}
},
clear() {
subscribers = [];
},
};
return lifecycleManager;
};
module.exports = {
createLifecyclesManager,
};
| 'use strict';
const createLifecyclesManager = db => {
let subscribers = [];
const lifecycleManager = {
subscribe(subscriber) {
// TODO: verify subscriber
subscribers.push(subscriber);
return () => {
subscribers.splice(subscribers.indexOf(subscriber), 1);
};
},
createEvent(action, uid, properties) {
const model = db.metadata.get(uid);
return {
action,
model,
...properties,
};
},
async run(action, uid, properties) {
for (const subscriber of subscribers) {
if (typeof subscriber === 'function') {
const event = this.createEvent(action, uid, properties);
return await subscriber(event);
}
const hasAction = action in subscriber;
const hasModel = !subscriber.models || subscriber.models.includes(uid);
if (hasAction && hasModel) {
const event = this.createEvent(action, uid, properties);
await subscriber[action](event);
}
}
},
clear() {
subscribers = [];
},
};
return lifecycleManager;
};
module.exports = {
createLifecyclesManager,
};
|
Fix server error in tag search for non-existing tag. | # -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.loading import get_model
from django.http import Http404
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
try:
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
except ObjectDoesNotExist:
raise Http404
| # -*- coding: utf8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django import template
from django.db.models.loading import get_model
from ..models import CustomTag
register = template.Library()
@register.assignment_tag
def get_obj_list(app, model, obj):
'''
Return list of all objects of type app.model tagged with a tag pointing to
obj (an object in the db, e.g. Person, Family, ...).
'''
try:
return get_model(app, model).objects.filter(
tags__slug='%s.%s-%d' % (
obj._meta.app_label, obj._meta.model_name, obj.id))
except:
return []
@register.assignment_tag
def get_tag_list(app, model, tag):
'''
Return list of all objects of type app.model tagged with the tag "tag".
'''
try:
return get_model(app, model).objects.filter(tags__slug='%s' % tag)
except:
return []
@register.filter
def as_tag_text(slug):
tag = CustomTag.objects.get(slug=slug)
return tag.as_tag_text()
|
Remove AMP menu in non-AMP window | /**
* WordPress dependencies
*/
import domReady from '@wordpress/dom-ready';
const { parent } = window;
if ( parent.pairedBrowsingApp ) {
window.ampPairedBrowsingClient = true;
const app = parent.pairedBrowsingApp;
app.registerClientWindow( window );
domReady( () => {
if ( app.documentIsAmp( document ) ) {
// Hide the paired browsing menu item.
const pairedBrowsingMenuItem = document.getElementById( 'wp-admin-bar-amp-paired-browsing' );
if ( pairedBrowsingMenuItem ) {
pairedBrowsingMenuItem.remove();
}
// Hide menu item to view non-AMP version.
const ampViewBrowsingItem = document.getElementById( 'wp-admin-bar-amp-view' );
if ( ampViewBrowsingItem ) {
ampViewBrowsingItem.remove();
}
} else {
/**
* No need to show the AMP menu in the Non-AMP window.
*/
const ampMenuItem = document.getElementById( 'wp-admin-bar-amp' );
ampMenuItem.remove();
}
} );
}
| /**
* WordPress dependencies
*/
import domReady from '@wordpress/dom-ready';
const { parent } = window;
if ( parent.pairedBrowsingApp ) {
window.ampPairedBrowsingClient = true;
const app = parent.pairedBrowsingApp;
app.registerClientWindow( window );
domReady( () => {
if ( app.documentIsAmp( document ) ) {
// Hide the paired browsing menu item.
const pairedBrowsingMenuItem = document.getElementById( 'wp-admin-bar-amp-paired-browsing' );
if ( pairedBrowsingMenuItem ) {
pairedBrowsingMenuItem.remove();
}
// Hide menu item to view non-AMP version.
const ampViewBrowsingItem = document.getElementById( 'wp-admin-bar-amp-view' );
if ( ampViewBrowsingItem ) {
ampViewBrowsingItem.remove();
}
} else {
/**
* Override the entire AMP menu item with just "Non-AMP". There should be no link to
* the AMP version since it is already being shown.
*/
const ampMenuItem = document.getElementById( 'wp-admin-bar-amp' );
if ( ampMenuItem ) {
ampMenuItem.innerHTML = 'Non-AMP';
}
}
} );
}
|
Revert "Prepare branch for section 2.4 tutorial"
This reverts commit 169e11232511209548673dd769a9c6f71d9b8498. | var express = require('express');
var router = express.Router();
var JsonDB = require('node-json-db');
var _ = require('lodash');
// Recipes listing
router.get('/', function (req, res, next) {
var db = new JsonDB('db', false, false);
var recipes = db.getData('/recipes');
// Expand requested resources if they exist
// The resource to expand is singular, e.g.
// to expand 'users' we provide _expand=user
var expand = req.query._expand;
if (expand) {
try {
var relation = db.getData('/' + expand + 's');
_(recipes)
.forEach(function (recipe) {
recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
delete recipe[expand + 'Id'];
});
}
catch(err) {
console.log(err);
}
}
res.json(recipes);
});
module.exports = router;
| var express = require('express');
var router = express.Router();
var JsonDB = require('node-json-db');
var _ = require('lodash');
// Escape a string for regexp use
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// Recipes listing
router.get('/', function (req, res, next) {
var db = new JsonDB('db', false, false);
var recipes = db.getData('/recipes');
// Expand requested resources if they exist
// The resource to expand is singular, e.g.
// to expand 'users' we provide _expand=user
var expand = req.query._expand;
if (expand) {
try {
var relation = db.getData('/' + expand + 's');
_(recipes)
.forEach(function (recipe) {
recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
delete recipe[expand + 'Id'];
});
}
catch(err) {
console.log(err);
}
}
res.json(recipes);
});
module.exports = router;
|
Add spacing after demo description | package org.vaadin.elements.demo;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
public abstract class AbstractElementsDemo extends CustomComponent {
private final VerticalLayout layout = new VerticalLayout();
public AbstractElementsDemo() {
setSizeFull();
layout.setSizeFull();
layout.setSpacing(true);
setCompositionRoot(layout);
}
@Override
public void attach() {
super.attach();
if (layout.getComponentCount() == 0) {
Component demoView = getDemoView();
layout.addComponents(new Label(getDemoDescription()), demoView);
layout.setExpandRatio(demoView, 1);
}
}
protected abstract String getDemoDescription();
protected abstract Component getDemoView();
}
| package org.vaadin.elements.demo;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
public abstract class AbstractElementsDemo extends CustomComponent {
private final VerticalLayout layout = new VerticalLayout();
public AbstractElementsDemo() {
setSizeFull();
layout.setSizeFull();
setCompositionRoot(layout);
}
@Override
public void attach() {
super.attach();
if (layout.getComponentCount() == 0) {
Component demoView = getDemoView();
layout.addComponents(new Label(getDemoDescription()), demoView);
layout.setExpandRatio(demoView, 1);
}
}
protected abstract String getDemoDescription();
protected abstract Component getDemoView();
}
|
Remove Elemental2 usage from doc example | package arez.doc.examples.at_memoize2;
import akasha.EventListener;
import akasha.Global;
import arez.ComputableValue;
import arez.annotations.Action;
import arez.annotations.ArezComponent;
import arez.annotations.ComputableValueRef;
import arez.annotations.DepType;
import arez.annotations.Memoize;
import arez.annotations.OnActivate;
import arez.annotations.OnDeactivate;
@ArezComponent
public abstract class NetworkStatus
{
private final EventListener _listener = e -> updateOnlineStatus();
// Specify depType so can explicitly trigger a recalculation
// of method using reportPossiblyChanged()
@Memoize( depType = DepType.AREZ_OR_EXTERNAL )
public boolean isOnLine()
{
return Global.navigator().onLine();
}
@ComputableValueRef
abstract ComputableValue<Boolean> getOnLineComputableValue();
@OnActivate
void onOnLineActivate()
{
Global.addOnlineListener( _listener );
Global.addOfflineListener( _listener );
}
@OnDeactivate
void onOnLineDeactivate()
{
Global.removeOnlineListener( _listener );
Global.removeOfflineListener( _listener );
}
@Action
void updateOnlineStatus()
{
// Explicitly trigger a recalculation of the OnLine value
getOnLineComputableValue().reportPossiblyChanged();
}
}
| package arez.doc.examples.at_memoize2;
import arez.ComputableValue;
import arez.annotations.Action;
import arez.annotations.ArezComponent;
import arez.annotations.ComputableValueRef;
import arez.annotations.DepType;
import arez.annotations.Memoize;
import arez.annotations.OnActivate;
import arez.annotations.OnDeactivate;
import akasha.Global;
import akasha.EventListener;
@ArezComponent
public abstract class NetworkStatus
{
private final EventListener _listener = e -> updateOnlineStatus();
// Specify depType so can explicitly trigger a recalculation
// of method using reportPossiblyChanged()
@Memoize( depType = DepType.AREZ_OR_EXTERNAL )
public boolean isOnLine()
{
return Global.navigator().onLine();
}
@ComputableValueRef
abstract ComputableValue<Boolean> getOnLineComputableValue();
@OnActivate
void onOnLineActivate()
{
DomGlobal.window.addEventListener( "online", _listener );
DomGlobal.window.addEventListener( "offline", _listener );
}
@OnDeactivate
void onOnLineDeactivate()
{
DomGlobal.window.removeEventListener( "online", _listener );
DomGlobal.window.removeEventListener( "offline", _listener );
}
@Action
void updateOnlineStatus()
{
// Explicitly trigger a recalculation of the OnLine value
getOnLineComputableValue().reportPossiblyChanged();
}
}
|
Refactor PartyManager as per API. | /*
* Copyright 2014 Gabriel Harris-Rouquette
*
* 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.afterkraft.kraftrpg.entity.party;
import com.afterkraft.kraftrpg.api.RPGPlugin;
import com.afterkraft.kraftrpg.api.entity.PartyMember;
import com.afterkraft.kraftrpg.api.entity.party.Party;
import com.afterkraft.kraftrpg.api.entity.party.PartyManager;
public class RPGPartyManager implements PartyManager {
private final RPGPlugin plugin;
public RPGPartyManager(RPGPlugin plugin) {
this.plugin = plugin;
}
@Override
public void initialize() {
}
@Override
public void shutdown() {
}
@Override
public Party createParty(PartyMember partyLeader, PartyMember... members) {
return null;
}
}
| /*
* Copyright 2014 Gabriel Harris-Rouquette
*
* 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.afterkraft.kraftrpg.entity.party;
import com.afterkraft.kraftrpg.api.RPGPlugin;
import com.afterkraft.kraftrpg.api.entity.Champion;
import com.afterkraft.kraftrpg.api.entity.party.Party;
import com.afterkraft.kraftrpg.api.entity.party.PartyManager;
public class RPGPartyManager implements PartyManager {
private final RPGPlugin plugin;
public RPGPartyManager(RPGPlugin plugin) {
this.plugin = plugin;
}
@Override
public Party createParty(Champion partyLeader, Champion... members) {
return null;
}
@Override
public void initialize() {
}
@Override
public void shutdown() {
}
}
|
8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
for db in dbs:
db = db.split('(')
n = 0
for i in db:
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(i).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
t1 = ibmcnx.functions.getDSId( db )
print t1
# AdminConfig.show( t1 )
# print '\n\n'
# AdminConfig.showall( t1 )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' ) | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
for db in dbs:
db = db.split('(')
n = 0
for i in db:
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(i).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
print db
# for db in dbs:
# t1 = ibmcnx.functions.getDSId( db )
# AdminConfig.show( t1 )
# print '\n\n'
# AdminConfig.showall( t1 )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' ) |
Fix compatibility with null as routing key | <?php
namespace Swarrot\SwarrotBundle\Event;
use Swarrot\Broker\Message;
class MessagePublishedEvent extends SymfonyEvent
{
const NAME = 'swarrot.message_published';
private $messageType;
private $message;
private $connection;
private $exchange;
private $routingKey;
public function __construct(string $messageType, Message $message, string $connection, string $exchange, ?string $routingKey)
{
$this->messageType = $messageType;
$this->message = $message;
$this->connection = $connection;
$this->exchange = $exchange;
$this->routingKey = $routingKey;
}
public function getMessageType(): string
{
return $this->messageType;
}
public function getMessage(): Message
{
return $this->message;
}
public function getConnection(): string
{
return $this->connection;
}
public function getExchange(): string
{
return $this->exchange;
}
public function getRoutingKey(): ?string
{
return $this->routingKey;
}
}
| <?php
namespace Swarrot\SwarrotBundle\Event;
use Swarrot\Broker\Message;
class MessagePublishedEvent extends SymfonyEvent
{
const NAME = 'swarrot.message_published';
private $messageType;
private $message;
private $connection;
private $exchange;
private $routingKey;
public function __construct(string $messageType, Message $message, string $connection, string $exchange, string $routingKey)
{
$this->messageType = $messageType;
$this->message = $message;
$this->connection = $connection;
$this->exchange = $exchange;
$this->routingKey = $routingKey;
}
public function getMessageType(): string
{
return $this->messageType;
}
public function getMessage(): Message
{
return $this->message;
}
public function getConnection(): string
{
return $this->connection;
}
public function getExchange(): string
{
return $this->exchange;
}
public function getRoutingKey(): string
{
return $this->routingKey;
}
}
|
Add conditional get to the noditer example. | var Connect = require('./lib/connect');
var controlled = ["/console/", "/files/", "/messages/"];
new Connect.Server([
// We want to log all http traffic
{filter: "log"},
// Show pretty pages for exceptions
{filter: "error-handler"},
// Add cookie based sessions to the controlled routes
{filter: "session", route: controlled},
// Make sure the user is authenticated
{filter: "authentication", route: controlled, param: {}},
// Restrict access to controlled pages by user rules
{filter: "authorization", route: controlled, param: {}},
// Listen for publish subscribe messages in real-time
{provider: "pubsub", route: "/messages/", param: {}},
// This is a logic endpoint, it's ext-direct rpc protocol
{provider: "direct", route: "/console/", param: {}},
// Use conditional GET to save on bandwidth
{filter: "conditional-get"},
// Cache all rest and static responses
{filter: "cache"},
// Gzip all resources when it makes sense
{filter: "gzip"},
// This is another logic endpoint, it's a rest-style interface to files
{provider: "rest", route: "/files/", param: {}},
// Finally serve everything else as static files
{provider: "static", param: __dirname + "/public"}
]).listen(); | var Connect = require('./lib/connect');
var controlled = ["/console/", "/files/", "/messages/"];
new Connect.Server([
// We want to log all http traffic
{filter: "log"},
// Show pretty pages for exceptions
{filter: "error-handler"},
// Add cookie based sessions to the controlled routes
{filter: "session", route: controlled},
// Make sure the user is authenticated
{filter: "authentication", route: controlled, param: {}},
// Restrict access to controlled pages by user rules
{filter: "authorization", route: controlled, param: {}},
// Listen for publish subscribe messages in real-time
{provider: "pubsub", route: "/messages/", param: {}},
// This is a logic endpoint, it's ext-direct rpc protocol
{provider: "direct", route: "/console/", param: {}},
// Cache all rest and static responses
{filter: "cache"},
// Gzip all resources when it makes sense
{filter: "gzip"},
// This is another logic endpoint, it's a rest-style interface to files
{provider: "rest", route: "/files/", param: {}},
// Finally serve everything else as static files
{provider: "static", param: __dirname + "/public"}
]).listen(); |
Update method should use KConfig instead of ArrayObject as parameter. | <?php
/**
* @version $Id$
* @category Koowa
* @package Koowa_Event
* @copyright Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
* @license GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
* @link http://www.koowa.org
*/
/**
* Class to handle events.
*
* @author Johan Janssens <johan@koowa.org>
* @category Koowa
* @package Koowa_Event
*/
class KEventHandler extends KObject implements KPatternObserver, KObjectIdentifiable
{
/**
* Get the object identifier
*
* @return KIdentifier
* @see KObjectIdentifiable
*/
public function getIdentifier()
{
return $this->_identifier;
}
/**
* Method to trigger events
*
* @param object The event arguments
* @return mixed Routine return value
*/
public function update(KConfig $args)
{
if (in_array($args->event, $this->getMethods())) {
return $this->{$args->event}($args);
}
return null;
}
} | <?php
/**
* @version $Id$
* @category Koowa
* @package Koowa_Event
* @copyright Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
* @license GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
* @link http://www.koowa.org
*/
/**
* Class to handle events.
*
* @author Johan Janssens <johan@koowa.org>
* @category Koowa
* @package Koowa_Event
*/
class KEventHandler extends KObject implements KPatternObserver, KObjectIdentifiable
{
/**
* Get the object identifier
*
* @return KIdentifier
* @see KObjectIdentifiable
*/
public function getIdentifier()
{
return $this->_identifier;
}
/**
* Method to trigger events
*
* @param object The event arguments
* @return mixed Routine return value
*/
public function update(ArrayObject $args)
{
if (in_array($args['event'], $this->getMethods())) {
return $this->{$args['event']}($args);
}
return null;
}
} |
Build a query string with params in a dictionary and append it to the URL. Makes the code readale. Remove commented code | from machine import Pin
from ds18x20 import DS18X20
import onewire
import time
import ujson
import urequests
def posttocloud(temperature):
keystext = open("sparkfun_keys.json").read()
keys = ujson.loads(keystext)
params = {}
params['temp'] = temperature
params['private_key'] = keys['privateKey']
#data.sparkfun doesn't support putting data into the POST Body.
#We had to add the data to the query string
#Copied the Dirty hack from
#https://github.com/matze/python-phant/blob/24edb12a449b87700a4f736e43a5415b1d021823/phant/__init__.py
payload_str = "&".join("%s=%s" % (k, v) for k, v in params.items())
url = keys['inputUrl'] + "?" + payload_str
resp = urequests.request("POST", url)
print (resp.text)
while True:
p = Pin(2) # Data Line is on GPIO2 aka D4
ow = onewire.OneWire(p)
ds = DS18X20(ow)
lstrom = ds.scan()
#Assuming we have only 1 device connected
rom = lstrom[0]
ds.convert_temp()
time.sleep_ms(750)
temperature = round(float(ds.read_temp(rom)),1)
#print("Temperature: {:02.1f}".format(temperature))
posttocloud(temperature)
time.sleep(10) | from machine import Pin
from ds18x20 import DS18X20
import onewire
import time
import machine
import ujson
import urequests
def posttocloud(temperature):
keystext = open("sparkfun_keys.json").read()
keys = ujson.loads(keystext)
url = keys['inputUrl'] + "?private_key=" + keys['privateKey'] + "&temp=" + str(temperature)
#data = {'temp':temperature}
#data['private_key'] = keys['privateKey']
#print (keys['inputUrl'])
#print(keys['privateKey'])
#datajson = ujson.dumps(data)
#print (datajson)
resp = urequests.request("POST", url)
print (resp.text)
while True:
p = Pin(2) # Data Line is on GPIO2 aka D4
ow = onewire.OneWire(p)
ds = DS18X20(ow)
lstrom = ds.scan()
#Assuming we have only 1 device connected
rom = lstrom[0]
ds.convert_temp()
time.sleep_ms(750)
temperature = round(float(ds.read_temp(rom)),1)
#print("Temperature: {:02.1f}".format(temperature))
posttocloud(temperature)
time.sleep(10) |
Fix shell-on-build-end-webpack plugin run flag being set globally | const { exec } = require("child_process");
/**
* @typedef {Object} Options
* @property {string} command - The command to run
* @property {boolean=} once - Whether to run the script only once
* @param options {Options}
*/
module.exports = function ShellOnBuildEndPlugin(options) {
this.run = false;
this.apply = compiler => {
compiler.hooks.afterEmit.tap("AfterEmitPlugin", () => {
if (!this.ran) {
exec(options.command, (err, stdout, stderr) => {
if (stdout) process.stdout.write(stdout);
if (stderr) process.stderr.write(stderr);
});
if (options.once) {
this.ran = true;
}
}
});
};
};
| const { exec } = require("child_process");
let ran = false;
/**
* @typedef {Object} Options
* @property {string} command - The command to run
* @property {boolean=} once - Whether to run the script only once
* @param options {Options}
*/
module.exports = function ShellOnBuildEndPlugin(options) {
this.apply = compiler => {
compiler.hooks.afterEmit.tap("AfterEmitPlugin", () => {
if (!ran) {
exec(options.command, (err, stdout, stderr) => {
if (stdout) process.stdout.write(stdout);
if (stderr) process.stderr.write(stderr);
});
if (options.once) {
ran = true;
}
}
});
};
};
|
Check specifically for null before overriding the timestamp | <?php
require_once('MongoQueue.php');
require_once('MongoFunctor.php');
abstract class MongoJob
{
public static function later($delay = 0, $batch = false)
{
return self::at(time() + $delay, $batch);
}
public static function at($time = null, $batch = false)
{
if ($time === null) $time = time();
$className = get_called_class();
return new MongoFunctor($className, $time, $batch);
}
public static function batchLater($delay = 0)
{
return self::later($delay, true);
}
public static function batchAt($time = null)
{
return self::at($time, true);
}
public static function run()
{
return MongoQueue::run(get_called_class());
}
public static function count()
{
return MongoQueue::count(get_called_class());
}
}
| <?php
require_once('MongoQueue.php');
require_once('MongoFunctor.php');
abstract class MongoJob
{
public static function later($delay = 0, $batch = false)
{
return self::at(time() + $delay, $batch);
}
public static function at($time = null, $batch = false)
{
if (!$time) $time = time();
$className = get_called_class();
return new MongoFunctor($className, $time, $batch);
}
public static function batchLater($delay = 0)
{
return self::later($delay, true);
}
public static function batchAt($time = null)
{
return self::at($time, true);
}
public static function run()
{
return MongoQueue::run(get_called_class());
}
public static function count()
{
return MongoQueue::count(get_called_class());
}
}
|
Store widget_id on field element
This allows the captcha element to be targeted via the js api in situations where there is more than one nocaptcha widget on the page. See examples referencing `opt_widget_id` here https://developers.google.com/recaptcha/docs/display#js_api | var _noCaptchaFields=_noCaptchaFields || [];
function noCaptchaFieldRender() {
for(var i=0;i<_noCaptchaFields.length;i++) {
var field=document.getElementById('Nocaptcha-'+_noCaptchaFields[i]);
var options={
'sitekey': field.getAttribute('data-sitekey'),
'theme': field.getAttribute('data-theme'),
'type': field.getAttribute('data-type'),
'size': field.getAttribute('data-size'),
'callback': (field.getAttribute('data-callback') ? verifyCallback : undefined )
};
var widget_id = grecaptcha.render(field, options);
field.setAttribute("data-widgetid", widget_id);
}
}
| var _noCaptchaFields=_noCaptchaFields || [];
function noCaptchaFieldRender() {
for(var i=0;i<_noCaptchaFields.length;i++) {
var field=document.getElementById('Nocaptcha-'+_noCaptchaFields[i]);
var options={
'sitekey': field.getAttribute('data-sitekey'),
'theme': field.getAttribute('data-theme'),
'type': field.getAttribute('data-type'),
'size': field.getAttribute('data-size'),
'callback': (field.getAttribute('data-callback') ? verifyCallback : undefined )
};
grecaptcha.render(field, options);
}
}
|
Allow to use the middleware class name instead | <?php namespace Barryvdh\StackMiddleware;
use Closure;
use Illuminate\Contracts\Container\Container;
class Wrapper
{
/** @var Container $container */
protected $container;
/**
* @param Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* Wrap and register the middleware in the Container
*
* @param string $abstract
* @param Closure|string $callable
*/
public function bind($abstract, $callable)
{
$this->container->bind($abstract, function() use($callable) {
return $this->wrap($callable);
});
}
/**
* Wrap the StackPHP Middleware in a Laravel Middleware
*
* @param Closure|string $callable
* @return ClosureMiddleware
*/
public function wrap($callable)
{
$kernel = new ClosureHttpKernel();
if (is_callable($callable)) {
$middleware = $callable($kernel);
} else {
$middleware = new $callable($kernel)
}
return new ClosureMiddleware($kernel, $middleware);
}
}
| <?php namespace Barryvdh\StackMiddleware;
use Closure;
use Illuminate\Contracts\Container\Container;
class Wrapper
{
/** @var Container $container */
protected $container;
/**
* @param Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* Wrap and register the middleware in the Container
*
* @param $abstract
* @param Closure $callable
*/
public function bind($abstract, Closure $callable)
{
$this->container->bind($abstract, function() use($callable) {
return $this->wrap($callable);
});
}
/**
* Wrap the StackPHP Middleware in a Laravel Middleware
*
* @param Closure $callable
* @return ClosureMiddleware
*/
public function wrap(Closure $callable)
{
$kernel = new ClosureHttpKernel();
$middleware = $callable($kernel);
return new ClosureMiddleware($kernel, $middleware);
}
}
|
Change config of production server | require('dotenv').config();
module.exports = {
development: {
client: 'postgresql',
connection: {
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PASS,
database : process.env.DB_NAME,
port : process.env.DB_PORT,
ssl : process.env.DB_SSL
},
migrations: {
directory: './server/db/migrations',
tableName: 'migrations'
},
seeds: {
directory: './server/db/seeds'
}
},
production: {
client: 'postgresql',
connection: process.env.DATABASE_URL + '?ssl=true',
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'migrations'
}
}
}; | require('dotenv').config();
module.exports = {
development: {
client: 'postgresql',
connection: {
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PASS,
database : process.env.DB_NAME,
port : process.env.DB_PORT,
ssl : process.env.DB_SSL
},
migrations: {
directory: './server/db/migrations',
tableName: 'migrations'
},
seeds: {
directory: './server/db/seeds'
}
},
production: {
client: 'postgresql',
connection: process.env.DATABASE_PRODUCTION + '?ssl=true',
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'migrations'
}
}
}; |
Add new line at end of python script | import sounddevice as sd
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
# devList = sd.query_devices()
# print(devList)
fs = 48000 # Sample rate
duration = 100e-3 # Duration of recording
device = 'Microphone (MicNode) MME' # MME is needed since there are more than one MicNode device APIs (at least in Windows)
myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=1, dtype='int16', device=device)
print('Waiting...')
sd.wait() # Wait until recording is finished
print('Done!')
time = np.arange(0, duration, 1 / fs) # time vector
plt.plot(time, myrecording)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.title('MicNode')
plt.show()
| import sounddevice as sd
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
# devList = sd.query_devices()
# print(devList)
fs = 48000 # Sample rate
duration = 100e-3 # Duration of recording
device = 'Microphone (MicNode) MME' # MME is needed since there are more than one MicNode device APIs (at least in Windows)
myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=1, dtype='int16', device=device)
print('Waiting...')
sd.wait() # Wait until recording is finished
print('Done!')
time = np.arange(0, duration, 1 / fs) # time vector
plt.plot(time, myrecording)
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.title('MicNode')
plt.show() |
Revert "Unit Test Failure Trial"
This reverts commit 7e2b425fffcb54ab68e1a462c64305fd269f7d3f. | /*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry.client;
import org.junit.Test;
import static org.cloudfoundry.client.ValidationResult.Status.INVALID;
import static org.cloudfoundry.client.ValidationResult.Status.VALID;
import static org.junit.Assert.assertEquals;
public final class ValidationResultTest {
@Test
public void invalid() {
ValidationResult result = ValidationResult.builder()
.message("Test Message")
.build();
assertEquals(INVALID, result.getStatus());
}
@Test
public void valid() {
ValidationResult result = ValidationResult.builder()
.build();
assertEquals(VALID, result.getStatus());
}
}
| /*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry.client;
import org.junit.Test;
import static org.cloudfoundry.client.ValidationResult.Status.VALID;
import static org.junit.Assert.assertEquals;
public final class ValidationResultTest {
@Test
public void invalid() {
ValidationResult result = ValidationResult.builder()
.message("Test Message")
.build();
assertEquals(VALID, result.getStatus());
}
@Test
public void valid() {
ValidationResult result = ValidationResult.builder()
.build();
assertEquals(VALID, result.getStatus());
}
}
|
Use full airbnb config including React rules | module.exports = {
"parser": "babel-eslint",
"extends": "airbnb",
"rules": {
"keyword-spacing": 2,
"generator-star-spacing": 0, // Temporary, avoids a bug in eslint babel parser
"indent": ["error", 4, { "SwitchCase": 1 }],
"strict": ["error", "safe"],
"comma-dangle": ["error", "never"],
"no-use-before-define": ["error", { "functions": false, "classes": true }],
"no-param-reassign": ["error", { "props": false }],
"array-bracket-spacing": ["error", "always"],
"no-underscore-dangle": ["off"],
"radix": ["error", "as-needed"],
"import/no-extraneous-dependencies": ["error", {"devDependencies": true, "optionalDependencies": false}],
"no-continue": ["off"]
},
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "script"
}
}
| module.exports = {
"parser": "babel-eslint",
"extends": "airbnb-base",
"rules": {
"keyword-spacing": 2,
"generator-star-spacing": 0, // Temporary, avoids a bug in eslint babel parser
"indent": ["error", 4, { "SwitchCase": 1 }],
"strict": ["error", "safe"],
"comma-dangle": ["error", "never"],
"no-use-before-define": ["error", { "functions": false, "classes": true }],
"no-param-reassign": ["error", { "props": false }],
"array-bracket-spacing": ["error", "always"],
"no-underscore-dangle": ["off"],
"radix": ["error", "as-needed"],
"import/no-extraneous-dependencies": ["error", {"devDependencies": true, "optionalDependencies": false}],
"no-continue": ["off"]
},
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "script"
}
}
|
Fix compat with 2.7 by only requiring argparse on 2.6 | #!/usr/bin/env python
from setuptools import setup, find_packages
import os
import sys
here = os.path.abspath(os.path.dirname(__file__))
try:
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
except:
README = ''
requires = []
# add argparse to be installed for earlier versions of python
if sys.version_info[:2] <= (2, 6):
requires.append('argparse')
setup(name='ppagent',
version='0.2.3',
description='A statistics collection agent for powerpool mining server',
author='Isaac Cook',
long_description=README,
author_email='isaac@simpload.com',
url='http://www.python.org/sigs/distutils-sig/',
packages=find_packages(),
install_requires=requires,
package_data={'ppagent': ['install/*']},
entry_points={
'console_scripts': [
'ppagent = ppagent.main:entry'
]
}
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
import os
here = os.path.abspath(os.path.dirname(__file__))
try:
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
except:
README = ''
setup(name='ppagent',
version='0.2.2',
description='A statistics collection agent for powerpool mining server',
author='Isaac Cook',
long_description=README,
author_email='isaac@simpload.com',
url='http://www.python.org/sigs/distutils-sig/',
packages=find_packages(),
install_requires=['argparse'],
package_data={'ppagent': ['install/*']},
entry_points={
'console_scripts': [
'ppagent = ppagent.main:entry'
]
}
)
|
Add missing remove function for series | package de.meldanor.VaadinChart.charts;
import java.util.Collection;
import com.vaadin.annotations.JavaScript;
@JavaScript("circlechart_connector.min.js")
public abstract class CircleChart extends Chart {
private static final long serialVersionUID = 6506866186112698558L;
protected CircleChart() {
// For serialization
this("pie");
}
public CircleChart(final String type) {
getState(false).setType(type);
}
public String getType() {
return getState(false).getType();
}
@Override
protected CircleChartState getState() {
return (CircleChartState) super.getState();
}
@Override
protected CircleChartState getState(boolean markAsDirty) {
return (CircleChartState) super.getState(markAsDirty);
}
public void addDataSeries(CircleDataSeries series) {
getState().getSeries().add(series);
}
public void addDataSeries(Collection<CircleDataSeries> series) {
getState().getSeries().addAll(series);
}
public void removeDataSeries(String label) {
getState().getSeries().removeIf(s -> s.getLabel().equals(label));
}
}
| package de.meldanor.VaadinChart.charts;
import java.util.Collection;
import com.vaadin.annotations.JavaScript;
@JavaScript("circlechart_connector.min.js")
public abstract class CircleChart extends Chart {
private static final long serialVersionUID = 6506866186112698558L;
protected CircleChart() {
// For serialization
this("pie");
}
public CircleChart(final String type) {
getState(false).setType(type);
}
public String getType() {
return getState(false).getType();
}
@Override
protected CircleChartState getState() {
return (CircleChartState) super.getState();
}
@Override
protected CircleChartState getState(boolean markAsDirty) {
return (CircleChartState) super.getState(markAsDirty);
}
public void addDataSeries(CircleDataSeries series) {
getState().getSeries().add(series);
}
public void addDataSeries(Collection<CircleDataSeries> series) {
getState().getSeries().addAll(series);
// CircleChartState state = getState(false);
// series.forEach(s -> state.getSeries().put(s.getLabel(), s));
// markAsDirty();
}
}
|
Disable non file stream test for now
There's a weird race condition that causes
test-non-file-stream-duration.js to fail occasionally
when running the full test suite. | var path = require('path');
var fs = require('fs');
var through = require('through');
var mm = require('../lib/index');
var test = require('prova');
/* TODO: fix this test. There's a weird race condition when running the full
test suite that causes this test only to fail. If we remove the
nonFileStream stuff and just pass the FileStream everything works fine.
How to reproduce:
for run in {1..1000}
do
npm test
done
npm test will fail every 3rd to 5th time.
test('nonfilestream', function (t) {
t.plan(1);
// shim process for browser-based tests
if (!process.nextTick)
process.nextTick = function(cb) { setTimeout(cb, 0); };
var sample = path.join(__dirname, 'samples/id3v2-duration-allframes.mp3');
var nonFileStream = through(
function write(data) { this.queue(data); },
function end() { this.queue(null); });
var fileStream = fs.createReadStream(sample);
fileStream.pipe(nonFileStream);
new mm(nonFileStream, { duration: true, fileSize: 47889 })
.on('metadata', function (result) {
t.equal(result.duration, 1);
t.end();
});
});
*/
| var path = require('path');
var fs = require('fs');
var through = require('through');
var mm = require('../lib/index');
var test = require('prova');
test('nonfilestream', function (t) {
t.plan(1);
// shim process for browser-based tests
if (!process.nextTick)
process.nextTick = function(cb) { setTimeout(cb, 0); };
var sample = path.join(__dirname, 'samples/id3v2-duration-allframes.mp3');
var nonFileStream = through(
function write(data) { this.queue(data); },
function end() { this.queue(null); });
var fileStream = fs.createReadStream(sample);
fileStream.pipe(nonFileStream);
new mm(nonFileStream, { duration: true, fileSize: 47889 })
.on('metadata', function (result) {
t.equal(result.duration, 1);
t.end();
});
});
|
[FIX] jcapture: Add dependency on auth_token_access (service errors don't seem to appear though, sadly)
git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@42069 b456876b-0849-0410-b77d-98878d47e9d5 | // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
// JS glue for jCapture feature
function openJCaptureDialog() {
var $appletDiv = $("#jCaptureAppletDiv");
if ($appletDiv.length) {
$appletDiv.remove();
}
$appletDiv = $("<div id='jCaptureAppletDiv' style='width:1px;height:1px;visibility:hidden;'> </div>");
$(document.body).append($appletDiv);
$.get($.service('jcapture', 'capture'), {
area: "none",
page: "test"
}, function(data){
$appletDiv.html(data);
});
// } else { TODO later
// $appletDiv[0].showCaptureFrame();
// }
}
function insertAtCarret( areaId, dokuTag ) {
$("#jCaptureAppletDiv").hide();
var tag = dokuTag.substring(3, dokuTag.length - 3);
alert("file : " + tag);
if (areaId) {
insertAt( areaId, tag);
}
}
| // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
// JS glue for jCapture feature
function openJCaptureDialog() {
var $appletDiv = $("#jCaptureAppletDiv");
if ($appletDiv.length) {
$appletDiv.remove();
}
$appletDiv = $("<div id='jCaptureAppletDiv' style='width:1px;height:1px;visibility:hidden;'> </div>");
$(document.body).append($appletDiv);
$.get($.service('jcapture', 'capture'), {
area: "none",
page: "test"
}, function(data){
$appletDiv.html(data);
});
// } else { TODO later
// $appletDiv[0].showCaptureFrame();
// }
}
function insertAtCarret( areaId, dokuTag ) {
var tag = dokuTag.substring(3, dokuTag.length - 3);
alert("file : " + tag);
if (areaId) {
insertAt( areaId, tag);
}
}
|
Replace space with "T" in date strings, to allow parsing. | define(['jquery', 'underscore', 'backbone', 'model_want', 'utils'], function($, _, Backbone, Models, Utils) {
Models.Wants = Backbone.Collection.extend({
model: Models.Want,
initialize: function() {
this.fetch({
dataType: 'json',
success: function(model, response, options) {
},
error: function(model, response, options) {
if (response.status === 403) {
Utils.logIn();
}
}
});
},
parse: function(response) {
return response.listings;
},
comparator: function(first, second) {
var dateValue1 = first.get("dateStart").replace(/ /, 'T');
var dateValue2 = second.get("dateStart").replace(/ /, 'T');
var firstDate = Date.parse(dateValue1);
var secondDate = Date.parse(dateValue2);
var difference = secondDate - firstDate;
if (difference > 0) {
return 1;
} else if (difference === 0) {
return 0;
} else {
return -1;
}
}
});
return Models;
}); | define(['jquery', 'underscore', 'backbone', 'model_want', 'utils'], function($, _, Backbone, Models, Utils) {
Models.Wants = Backbone.Collection.extend({
model: Models.Want,
initialize: function() {
this.fetch({
dataType: 'json',
success: function(model, response, options) {
},
error: function(model, response, options) {
if (response.status === 403) {
Utils.logIn();
}
}
});
},
parse: function(response) {
return response.listings;
},
comparator: function(first, second) {
var dateValue1 = first.get("dateStart");
var dateValue2 = second.get("dateStart");
var firstDate = Date.parse(dateValue1);
var secondDate = Date.parse(dateValue2);
var difference = secondDate - firstDate;
if (difference > 0) {
return 1;
} else if (difference == 0) {
return 0;
} else {
return -1;
}
}
});
return Models;
}); |
Add check for ENV port variable. | var express = require('express'),
fs = require('fs');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.get('/:id/*?', function (req, res) {
var path = __dirname + "/dump" + req.originalUrl.split("?")[0];
//HACK: we need to handle files that are not html
var data = fs.readFileSync(path, 'utf8');
data += "<script src='/js/detect.js'></script>";
res.send(data);
});
var port = process.env.PORT || 3000;
app.listen(port, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
| var express = require('express'),
fs = require('fs');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.get('/:id/*?', function (req, res) {
var path = __dirname + "/dump" + req.originalUrl.split("?")[0];
//HACK: we need to handle files that are not html
var data = fs.readFileSync(path, 'utf8');
data += "<script src='/js/detect.js'></script>";
res.send(data);
});
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
|
Allow for tuple-based args in map also | from __future__ import absolute_import, division, print_function
import sys
PY3 = sys.version_info[0] == 3
PY2 = sys.version_info[0] == 2
if PY3:
import builtins
from queue import Queue, Empty
from itertools import zip_longest
from io import StringIO, BytesIO
from urllib.request import urlopen
from urllib.parse import urlparse
from urllib.parse import quote, unquote
unicode = str
long = int
def apply(func, args, kwargs=None):
if not isinstance(args, list) and not isinstance(args, tuple) and kwargs is None:
return func(args)
elif not isinstance(args, list) and not isinstance(args, tuple):
return func(args, **kwargs)
elif kwargs:
return func(*args, **kwargs)
else:
return func(*args)
range = range
else:
import __builtin__ as builtins
from Queue import Queue, Empty
import operator
from itertools import izip_longest as zip_longest
from StringIO import StringIO
from io import BytesIO
from urllib2 import urlopen
from urlparse import urlparse
from urllib import quote, unquote
unicode = unicode
long = long
apply = apply
range = xrange
def skip(func):
return
| from __future__ import absolute_import, division, print_function
import sys
PY3 = sys.version_info[0] == 3
PY2 = sys.version_info[0] == 2
if PY3:
import builtins
from queue import Queue, Empty
from itertools import zip_longest
from io import StringIO, BytesIO
from urllib.request import urlopen
from urllib.parse import urlparse
from urllib.parse import quote, unquote
unicode = str
long = int
def apply(func, args, kwargs=None):
if not isinstance(args, list) and kwargs is None:
return func(args)
elif not isinstance(args, list):
return func(args, **kwargs)
elif kwargs:
return func(*args, **kwargs)
else:
return func(*args)
range = range
else:
import __builtin__ as builtins
from Queue import Queue, Empty
import operator
from itertools import izip_longest as zip_longest
from StringIO import StringIO
from io import BytesIO
from urllib2 import urlopen
from urlparse import urlparse
from urllib import quote, unquote
unicode = unicode
long = long
apply = apply
range = xrange
def skip(func):
return
|
Check for new release in 10 minutes intervals | const url_for_static = require('../base/url').url_for_static;
const moment = require('moment');
const check_new_release = function() { // calling this method is handled by GTM tags
const last_reload = localStorage.getItem('new_release_reload_time');
// prevent reload in less than 10 minutes
if (last_reload && +last_reload + (10 * 60 * 1000) > moment().valueOf()) return;
localStorage.setItem('new_release_reload_time', moment().valueOf());
const currect_hash = $('script[src*="binary.min.js"],script[src*="binary.js"]').attr('src').split('?')[1];
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (+xhttp.readyState === 4 && +xhttp.status === 200) {
const latest_hash = xhttp.responseText;
if (latest_hash && latest_hash !== currect_hash) {
window.location.reload(true);
}
}
};
xhttp.open('GET', url_for_static() + 'version?' + Math.random().toString(36).slice(2), true);
xhttp.send();
};
module.exports = {
check_new_release: check_new_release,
};
| const url_for_static = require('../base/url').url_for_static;
const moment = require('moment');
const check_new_release = function() { // calling this method is handled by GTM tags
const last_reload = localStorage.getItem('new_release_reload_time');
// prevent reload in less than 10 minutes
if (last_reload && +last_reload + (10 * 60 * 1000) > moment().valueOf()) return;
const currect_hash = $('script[src*="binary.min.js"],script[src*="binary.js"]').attr('src').split('?')[1];
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (+xhttp.readyState === 4 && +xhttp.status === 200) {
const latest_hash = xhttp.responseText;
if (latest_hash && latest_hash !== currect_hash) {
localStorage.setItem('new_release_reload_time', moment().valueOf());
window.location.reload(true);
}
}
};
xhttp.open('GET', url_for_static() + 'version?' + Math.random().toString(36).slice(2), true);
xhttp.send();
};
module.exports = {
check_new_release: check_new_release,
};
|
Fix new links in top nacbar | <header class="banner navbar navbar-default navbar-static-top" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="brand" href="<?php echo home_url(); ?>/"><img class="logo" src="/wp-content/themes/owncloudorgnew/assets/img/common/logo_owncloud.svg" title="<?php bloginfo('name'); ?>" itemprop="logo"></a>
</div>
<nav class="collapse navbar-collapse" role="navigation">
<ul id="menu-header" class="nav navbar-nav">
<li class="menu-news"><a href="/news/">News</a></li>
<li class="menu-features"><a href="/features/">Features</a></li>
<li class="menu-demo"><a href="http://demo.owncloud.org">Demo</a></li>
<li class="menu-documentation"><a href="http://doc.owncloud.org">Documentation</a></li>
<li class="menu-install"><a href="/install/">Install</a></li>
</ul>
</nav>
</div>
</header>
| <header class="banner navbar navbar-default navbar-static-top" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="brand" href="<?php echo home_url(); ?>/"><img class="logo" src="/wp-content/themes/owncloudorgnew/assets/img/common/logo_owncloud.svg" title="<?php bloginfo('name'); ?>" itemprop="logo"></a>
</div>
<nav class="collapse navbar-collapse" role="navigation">
<ul id="menu-header" class="nav navbar-nav">
<li class="menu-news"><a href="news/">News</a></li>
<li class="menu-features"><a href="/features/">Features</a></li>
<li class="menu-demo"><a href="http://demo.owncloud.org">Demo</a></li>
<li class="menu-documentation"><a href="http://doc.owncloud.org">Documentation</a></li>
<li class="menu-install"><a href="/install/">Install</a></li>
</ul>
</nav>
</div>
</header>
|
Refactor source to use more ES6 syntax. | var TimeSegments = {
// Segment an array of events by scale
segment(events, scale, options) {
scale = scale || 'weeks';
options = options || {};
_.defaults(options, {
startAttribute: 'start',
endAttribute: 'end'
});
events = _.chain(events).clone().sortBy(options.startAttribute).value();
var segments = {};
// Clone our events so that we're not modifying the original
// objects. Loop through them, inserting the events into the
// corresponding segments
_.each(_.clone(events), e => {
// Calculate the duration of the event; this determines
// how many segments it will be in
var startMoment = moment.utc(e[options.startAttribute]).startOf(scale);
var endMoment = moment.utc(e[options.endAttribute]).endOf(scale).add(1, 'milliseconds');
// For each duration, add the event to the corresponding segment
var segmentStart;
for(var i = 0, duration = endMoment.diff(startMoment, scale); i < duration; i++) {
segmentStart = moment.utc(startMoment).add(i, scale).unix();
if (!segments[segmentStart]) { segments[segmentStart] = []; }
segments[segmentStart].push(_.clone(e));
}
});
return segments;
}
};
export default TimeSegments;
| var TimeSegments = {
// Segment an array of events by scale
segment(events, scale, options) {
scale = scale || 'weeks';
options = options || {};
_.defaults(options, {
startAttribute: 'start',
endAttribute: 'end'
});
events = _.chain(events).clone().sortBy(options.startAttribute).value();
var segments = {};
// Clone our events so that we're not modifying the original
// objects. Loop through them, inserting the events into the
// corresponding segments
_.each(_.clone(events), function(e) {
// Calculate the duration of the event; this determines
// how many segments it will be in
var startMoment = moment.utc(e[options.startAttribute]).startOf(scale);
var endMoment = moment.utc(e[options.endAttribute]).endOf(scale).add(1, 'milliseconds');
// For each duration, add the event to the corresponding segment
var segmentStart;
for(var i = 0, duration = endMoment.diff(startMoment, scale); i < duration; i++) {
segmentStart = moment.utc(startMoment).add(i, scale).unix();
if (!segments[segmentStart]) { segments[segmentStart] = []; }
segments[segmentStart].push(_.clone(e));
}
});
return segments;
}
};
export default TimeSegments;
|
FIx Rollup external not handling core-js module | import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import pkg from './package.json';
export default [
// browser-friendly UMD build
{
input: 'src/simplebar.js',
output: {
name: 'SimpleBar',
file: pkg.browser,
format: 'umd'
},
plugins: [
resolve(), // so Rollup can find dependencies
commonjs(), // so Rollup can convert dependencies to an ES module
babel({
exclude: ['node_modules/**']
})
]
},
// CommonJS (for Node) and ES module (for bundlers) build.
// (We could have three entries in the configuration array
// instead of two, but it's quicker to generate multiple
// builds from a single configuration where possible, using
// an array for the `output` option, where we can specify
// `file` and `format` for each target)
{
input: 'src/simplebar.js',
external: [...Object.keys(pkg.dependencies), 'core-js/fn/array/from'],
output: [
{ file: pkg.main, format: 'cjs' },
{ file: pkg.module, format: 'es' }
]
}
]; | import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import pkg from './package.json';
export default [
// browser-friendly UMD build
{
input: 'src/simplebar.js',
output: {
name: 'SimpleBar',
file: pkg.browser,
format: 'umd'
},
plugins: [
resolve(), // so Rollup can find `ms`
commonjs(), // so Rollup can convert `ms` to an ES module
babel({
exclude: ['node_modules/**']
})
]
},
// CommonJS (for Node) and ES module (for bundlers) build.
// (We could have three entries in the configuration array
// instead of two, but it's quicker to generate multiple
// builds from a single configuration where possible, using
// an array for the `output` option, where we can specify
// `file` and `format` for each target)
{
input: 'src/simplebar.js',
external: Object.keys(pkg.dependencies),
output: [
{ file: pkg.main, format: 'cjs' },
{ file: pkg.module, format: 'es' }
]
}
]; |
Enable linux 32 & win build | /* jshint node: true */
module.exports = function(grunt) {
var NW_VERSION = '0.8.3';
// linudev.so.0 workaround, see README.md
process.env.LD_LIBRARY_PATH = '.:' + process.env.LD_LIBRARY_PATH;
grunt.initConfig({
run: {
options: {
nwArgs: ['.'],
downloadDir: 'node-webkit',
runtimeVersion: NW_VERSION,
forceDownload: false,
forceExtract: false
}
},
build: {
options: {
downloadDir: 'node-webkit',
runtimeVersion: NW_VERSION,
forceDownload: false,
forceExtract: false,
linux_ia32: true,
linux_x64: true,
win: true,
osx: false
}
}
});
grunt.loadTasks('tasks');
}; | /* jshint node: true */
module.exports = function(grunt) {
var NW_VERSION = '0.8.3';
// linudev.so.0 workaround, see README.md
process.env.LD_LIBRARY_PATH = '.:' + process.env.LD_LIBRARY_PATH;
grunt.initConfig({
run: {
options: {
nwArgs: ['.'],
downloadDir: 'node-webkit',
runtimeVersion: NW_VERSION,
forceDownload: false,
forceExtract: false
}
},
build: {
options: {
downloadDir: 'node-webkit',
runtimeVersion: NW_VERSION,
forceDownload: false,
forceExtract: false,
linux_ia32: false,
linux_x64: true,
win: false,
osx: false
}
}
});
grunt.loadTasks('tasks');
}; |
Clean up Commit cha verify, add completed steps | var exec = require('child_process').exec
var fs = require('fs')
var helper = require('../verify/helpers.js')
var userData = require('../data.json')
var addtoList = helper.addtoList
var markChallengeCompleted = helper.markChallengeCompleted
var writeData = helper.writeData
var currentChallenge = 'commit_to_it'
// check that they've commited changes
module.exports = function commitVerify (path) {
if (!fs.lstatSync(path).isDirectory()) return addtoList('Path is not a directory', false)
exec('git status', {cwd: path}, function (err, stdout, stdrr) {
if (err) return addtoList(err.message, false)
var show = stdout.trim()
if (show.match('Initial commit')) {
addtoList("Hmm, can't find committed changes.", false)
} else if (show.match('nothing to commit')) {
addtoList('Changes have been committed!', true)
markChallengeCompleted()
writeData(userData, currentChallenge)
} else {
addtoList('Seems there are changes to commit still.', false)
}
})
}
| var exec = require('child_process').exec
var fs = require('fs')
var helper = require('../verify/helpers.js')
var userData = require('../data.json')
var addtoList = helper.addtoList
var markChallengeCompleted = helper.markChallengeCompleted
var writeData = helper.writeData
var currentChallenge = 'commit_to_it'
// check that they've commited changes
module.exports = function commitVerify (path) {
exec('git status', {cwd: path}, function (err, stdout, stdrr) {
if (err) return addtoList(err.message, false)
var show = stdout.trim()
if (show.match("Initial commit")) {
addtoList("Hmm, can't find\ncommitted changes.", false)
} else if (show.match("nothing to commit")) {
addtoList("Changes have been committed!", true)
} else {
addtoList("Seems there are changes\nto commit still.", false)
}
})
}
|
Make GENERIC_REASON consistent with web messages. | package uk.ac.ic.wlgitbridge.snapshot.base;
import com.google.gson.JsonElement;
import uk.ac.ic.wlgitbridge.git.exception.SnapshotAPIException;
import java.util.Arrays;
import java.util.List;
public class MissingRepositoryException extends SnapshotAPIException {
public static final String GENERIC_REASON =
"This Overleaf project currently has no git access.\n" +
"\n" +
"If this problem persists, please contact us.";
public static final String EXPORTED_TO_V2 =
"This Overleaf project has been moved to Overleaf v2, and git access is temporarily unsupported.\n" +
"\n" +
"See https://www.overleaf.com/help/342 for more information.";
private String message = "";
public MissingRepositoryException() {
}
public MissingRepositoryException(String message) {
this.message = message;
}
@Override
public void fromJSON(JsonElement json) {}
@Override
public String getMessage() {
return message;
}
@Override
public List<String> getDescriptionLines() {
return Arrays.asList(getMessage());
}
}
| package uk.ac.ic.wlgitbridge.snapshot.base;
import com.google.gson.JsonElement;
import uk.ac.ic.wlgitbridge.git.exception.SnapshotAPIException;
import java.util.Arrays;
import java.util.List;
public class MissingRepositoryException extends SnapshotAPIException {
public static final String GENERIC_REASON =
"This Overleaf project currently has no git access.\n" +
"\n" +
"If you think this is an error, contact support at support@overleaf.com.";
public static final String EXPORTED_TO_V2 =
"This Overleaf project has been moved to Overleaf v2, and git access is temporarily unsupported.\n" +
"\n" +
"See https://www.overleaf.com/help/342 for more information.";
private String message = "";
public MissingRepositoryException() {
}
public MissingRepositoryException(String message) {
this.message = message;
}
@Override
public void fromJSON(JsonElement json) {}
@Override
public String getMessage() {
return message;
}
@Override
public List<String> getDescriptionLines() {
return Arrays.asList(getMessage());
}
}
|
Adjust function isInViewport to be more fail-safe. | jQuery.ajaxSetup({
cache : false
});
jQuery.fn.isInViewport = function (offset) {
var elementTop, elementBottom, viewportTop, viewportBottom;
if (!jQuery(this).length) {
return;
}
// set undefined offset to 0
if (typeof offset === "undefined") {
offset = 0;
}
elementTop = jQuery(this).offset().top;
elementBottom = elementTop + jQuery(this).outerHeight();
viewportTop = jQuery(window).scrollTop();
viewportBottom = viewportTop + jQuery(window).height();
return (elementBottom - offset) > viewportTop && (elementTop + offset) < viewportBottom;
};
jQuery.debounce = function (delay, callback) {
var timeout = null;
return function () {
var _arguments = arguments;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function () {
callback.apply(null, _arguments);
timeout = null;
}, delay);
};
}
| jQuery.ajaxSetup({
cache : false
});
jQuery.fn.isInViewport = function (offset) {
var elementTop, elementBottom, viewportTop, viewportBottom;
if (typeof offset === "undefined") {
offset = 0;
}
elementTop = jQuery(this).offset().top;
elementBottom = elementTop + jQuery(this).outerHeight();
viewportTop = jQuery(window).scrollTop();
viewportBottom = viewportTop + jQuery(window).height();
return elementBottom - offset > viewportTop && elementTop + offset < viewportBottom;
};
jQuery.debounce = function (delay, callback) {
var timeout = null;
return function () {
var _arguments = arguments;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function () {
callback.apply(null, _arguments);
timeout = null;
}, delay);
};
}
|
Fix os-brick in virtual environments
When running os-brick in a virtual environment created by a non root
user, we get the following error:
ModuleNotFoundError: No module named 'os_brick.privileged.rootwrap'
This happens because the privsep daemon drops all the privileged except
those defined in the context, and our current context doesn't bypass
file read permission checks, so the Daemon cannot read the file with the
code it was asked to run, because it belongs to a different user.
This patch adds the CAP_DAC_READ_SEARCH capability to our privsep
context so we can load the libraries, but only when we are running on a
virtual environment to follow the principle of least privilege.
This bug doesn't affect system-wide installations because the files
installed under /sys/python*/site-packages belong to the Daemon user
(root), so no special capabilities are necessary.
Change-Id: Ib191c075ad1250822f6ac842f39214af8f3a02f0
Close-Bug: #1884059 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from oslo_privsep import capabilities as c
from oslo_privsep import priv_context
capabilities = [c.CAP_SYS_ADMIN]
# On virtual environments libraries are not owned by the Daemon user (root), so
# the Daemon needs the capability to bypass file read permission checks in
# order to dynamically load the code to run.
if os.environ.get('VIRTUAL_ENV'):
capabilities.append(c.CAP_DAC_READ_SEARCH)
# It is expected that most (if not all) os-brick operations can be
# executed with these privileges.
default = priv_context.PrivContext(
__name__,
cfg_section='privsep_osbrick',
pypath=__name__ + '.default',
capabilities=capabilities,
)
| # 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.
from oslo_privsep import capabilities as c
from oslo_privsep import priv_context
# It is expected that most (if not all) os-brick operations can be
# executed with these privileges.
default = priv_context.PrivContext(
__name__,
cfg_section='privsep_osbrick',
pypath=__name__ + '.default',
capabilities=[c.CAP_SYS_ADMIN],
)
|
Fix linting errors in fixture | module.exports = [
{
model: 'User',
data: {
email: 'test@abakus.no',
name: 'Test Bruker',
// Password: test
hash: '$2a$10$Gm09SZEHzdqx4eBV06nNheenfKpw3R1rXrMzmYfjX/.9UFPHnaAn6'
}
},
{
model: 'User',
data: {
email: 'backup@abakus.no',
name: 'Backup bruker',
// Password: test
hash: '$2a$10$Gm09SZEHzdqx4eBV06nNheenfKpw3R1rXrMzmYfjX/.9UFPHnaAn6'
}
}
];
| module.exports = [
{
"model": "User",
"data": {
"email": "test@abakus.no",
"name": "Test Bruker",
// Password: test
hash: '$2a$10$Gm09SZEHzdqx4eBV06nNheenfKpw3R1rXrMzmYfjX/.9UFPHnaAn6'
}
},
{
"model": "User",
"data": {
"email": "backup@abakus.no",
"name": "Backup bruker",
// Password: test
hash: '$2a$10$Gm09SZEHzdqx4eBV06nNheenfKpw3R1rXrMzmYfjX/.9UFPHnaAn6'
}
}
];
|
Add a method to convert a safe transformer to a function. | /*******************************************************************************
* Copyright (C) 2016 Push Technology Ltd.
*
* 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.pushtechnology.diffusion.transform.transformer;
import java.util.function.Function;
/**
* A transformer. Converts values of one type into values of a different
* type. It will not throw an exception.
*
* @param <S> the type of the source values
* @param <T> the type of the transformed values
* @author Push Technology Limited
* @deprecated since 2.0.0 in favour of {@link java.util.function.Function}
*/
@SuppressWarnings("deprecation")
@Deprecated
public interface SafeTransformer<S, T> extends Transformer<S, T> {
@Override
T transform(S value);
/**
* Convert the transformer to a function.
*
* @return the transformer as a function
*/
default Function<S, T> asFunction() {
return this::transform;
}
}
| /*******************************************************************************
* Copyright (C) 2016 Push Technology Ltd.
*
* 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.pushtechnology.diffusion.transform.transformer;
/**
* A transformer. Converts values of one type into values of a different
* type. It will not throw an exception.
*
* @param <S> the type of the source values
* @param <T> the type of the transformed values
* @author Push Technology Limited
* @deprecated since 2.0.0 in favour of {@link java.util.function.Function}
*/
@SuppressWarnings("deprecation")
@Deprecated
public interface SafeTransformer<S, T> extends Transformer<S, T> {
@Override
T transform(S value);
}
|
Add shim for python_2_unicode_compatible in tests | from __future__ import absolute_import
import sys
from django.conf import settings
from django.db import models
try:
from django.utils.encoding import python_2_unicode_compatible
except ImportError:
def python_2_unicode_compatible(c):
return c
import rules
@python_2_unicode_compatible
class Book(models.Model):
isbn = models.CharField(max_length=50, unique=True)
title = models.CharField(max_length=100)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.title
if sys.version_info.major >= 3:
from rules.contrib.models import RulesModel
class TestModel(RulesModel):
class Meta:
rules_permissions = {"add": rules.always_true, "view": rules.always_true}
@classmethod
def preprocess_rules_permissions(cls, perms):
perms["custom"] = rules.always_true
| from __future__ import absolute_import
import sys
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
import rules
@python_2_unicode_compatible
class Book(models.Model):
isbn = models.CharField(max_length=50, unique=True)
title = models.CharField(max_length=100)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.title
if sys.version_info.major >= 3:
from rules.contrib.models import RulesModel
class TestModel(RulesModel):
class Meta:
rules_permissions = {"add": rules.always_true, "view": rules.always_true}
@classmethod
def preprocess_rules_permissions(cls, perms):
perms["custom"] = rules.always_true
|
Adjust the error message styling | <?php require_once 'config.php';
if ($env == 'production') {
error_reporting(E_ERROR | E_PARSE);
}
function print_files($url, $dir)
{
$hide = ".";
$myDirectory = opendir($dir);
if ($myDirectory) {
while ($entryName = readdir($myDirectory))
{
$dirArray[] = $entryName;
}
closedir($myDirectory);
$indexCount = count($dirArray);
sort($dirArray);
for ($index = 0; $index < $indexCount; $index++)
{
if (substr("$dirArray[$index]", 0, 1) != $hide)
{
$name = $dirArray[$index];
$namehref = $dirArray[$index];
echo("
<li>
<a class='link' href='$url/$namehref'>$name</a>
</li>
");
}
}
} else {
echo("
<p class='mtm tac'>Couldn't open the directory specified.</p>
");
}
}
| <?php require_once 'config.php';
if ($env == 'production') {
error_reporting(E_ERROR | E_PARSE);
}
function print_files($url, $dir)
{
$hide = ".";
$myDirectory = opendir($dir);
if ($myDirectory) {
while ($entryName = readdir($myDirectory))
{
$dirArray[] = $entryName;
}
closedir($myDirectory);
$indexCount = count($dirArray);
sort($dirArray);
for ($index = 0; $index < $indexCount; $index++)
{
if (substr("$dirArray[$index]", 0, 1) != $hide)
{
$name = $dirArray[$index];
$namehref = $dirArray[$index];
echo("
<li>
<a class='link' href='$url/$namehref'>$name</a>
</li>
");
}
}
} else {
echo("
<p class='tac'>Couldn't open the directory specified.</p>
");
}
}
|
Insert importer at beginning of list | import re
import sys
class ProcessorImporter(object):
"""
The processors were moved to the PILKit project so they could be used
separtely from ImageKit (which has a bunch of Django dependencies). However,
there's no real need to expose this fact (and we want to maintain backwards
compatibility), so we proxy all "imagekit.processors" imports to
"pilkit.processors" using this object.
"""
pattern = re.compile(r'^imagekit\.processors((\..*)?)$')
def find_module(self, name, path=None):
if self.pattern.match(name):
return self
def load_module(self, name):
if name in sys.modules:
return sys.modules[name]
from django.utils.importlib import import_module
new_name = self.pattern.sub(r'pilkit.processors\1', name)
return import_module(new_name)
sys.meta_path.insert(0, ProcessorImporter())
| import re
import sys
class ProcessorImporter(object):
"""
The processors were moved to the PILKit project so they could be used
separtely from ImageKit (which has a bunch of Django dependencies). However,
there's no real need to expose this fact (and we want to maintain backwards
compatibility), so we proxy all "imagekit.processors" imports to
"pilkit.processors" using this object.
"""
pattern = re.compile(r'^imagekit\.processors((\..*)?)$')
def find_module(self, name, path=None):
if self.pattern.match(name):
return self
def load_module(self, name):
if name in sys.modules:
return sys.modules[name]
from django.utils.importlib import import_module
new_name = self.pattern.sub(r'pilkit.processors\1', name)
return import_module(new_name)
sys.meta_path.append(ProcessorImporter())
|
LILY-2495: Set Autolinker option stripTrailingSlash to false so that trailing slashes are shown in urls.
LILY-2495: Also prevent Autolinker from removing prefixes from an url. | var Autolinker = require('autolinker');
/**
* parseUrls is a template filter to call Autolinker.
* This is a library which automatically detects links, email addresses and
* Twitter handles and converts them to clickable links.
*
* @param text {string}: Text to be converted
*
* @returns: string: Text containing clickable links.
*/
angular.module('app.filters').filter('parseUrls', parseUrls);
parseUrls.$inject = [];
function parseUrls() {
return function(text) {
return Autolinker.link(text, {
stripPrefix: false,
stripTrailingSlash: false,
replaceFn: function(match) {
var email;
switch (match.getType()) {
case 'email':
email = match.getEmail();
return '<a href="#/email/compose/' + email + '/">' + email + '</a>';
default:
return true;
}
},
});
};
}
| var Autolinker = require('autolinker');
/**
* parseUrls is a template filter to call Autolinker.
* This is a library which automatically detects links, email addresses and
* Twitter handles and converts them to clickable links.
*
* @param text {string}: Text to be converted
*
* @returns: string: Text containing clickable links.
*/
angular.module('app.filters').filter('parseUrls', parseUrls);
parseUrls.$inject = [];
function parseUrls() {
return function(text) {
return Autolinker.link(text, {
replaceFn: function(match) {
var email;
switch (match.getType()) {
case 'email':
email = match.getEmail();
return '<a href="#/email/compose/' + email + '/">' + email + '</a>';
default:
return true;
}
},
});
};
}
|
Fix failing test case under logical operators. | if ( typeof window === 'undefined' ) {
require('../../app/logicalOperators');
var expect = require('chai').expect;
}
describe('logical operators', function(){
it('you should be able to work with logical or', function() {
expect(logicalOperatorsAnswers.or(false, true)).to.be.ok;
expect(logicalOperatorsAnswers.or(true, false)).to.be.ok;
expect(logicalOperatorsAnswers.or(true, true)).to.be.ok;
expect(logicalOperatorsAnswers.or(false, false)).not.to.be.ok;
expect(logicalOperatorsAnswers.or(3, 4)).to.not.eq(7);
});
it('you should be able to work with logical and', function() {
expect(logicalOperatorsAnswers.and(false, true)).not.to.be.ok;
expect(logicalOperatorsAnswers.and(false, false)).not.to.be.ok;
expect(logicalOperatorsAnswers.and(true, false)).not.to.be.ok;
expect(logicalOperatorsAnswers.and(true, true)).to.be.ok;
expect(logicalOperatorsAnswers.and(3, 4)).to.be.ok;
});
});
| if ( typeof window === 'undefined' ) {
require('../../app/logicalOperators');
var expect = require('chai').expect;
}
describe('logical operators', function(){
it('you should be able to work with logical or', function() {
expect(logicalOperatorsAnswers.or(false, true)).to.be.ok;
expect(logicalOperatorsAnswers.or(true, false)).to.be.ok;
expect(logicalOperatorsAnswers.or(true, true)).to.be.ok;
expect(logicalOperatorsAnswers.or(false, false)).not.to.be.ok;
expect(logicalOperatorsAnswers.or(3, 4)).to.not.eq(7);
});
it('you should be able to work with logical and', function() {
expect(logicalOperatorsAnswers.or(false, true)).not.to.be.ok;
expect(logicalOperatorsAnswers.and(false, false)).not.to.be.ok;
expect(logicalOperatorsAnswers.and(true, false)).not.to.be.ok;
expect(logicalOperatorsAnswers.and(true, true)).to.be.ok;
expect(logicalOperatorsAnswers.and(3, 4)).to.be.ok;
});
});
|
Use hifens instead of underscore for command names | import click, importlib
from shub.utils import missing_modules
def missingmod_cmd(modules):
modlist = ", ".join(modules)
@click.command(help="*DISABLED* - requires %s" % modlist)
@click.pass_context
def cmd(ctx):
click.echo("Error: '%s' command requires %s" % (ctx.info_name, modlist))
ctx.exit(1)
return cmd
@click.group(help="Scrapinghub command-line client")
def cli():
pass
module_deps = {
"deploy": ["scrapy", "setuptools"],
"login": [],
}
for command, modules in module_deps.iteritems():
m = missing_modules(*modules)
if m:
cli.add_command(missingmod_cmd(m), command)
else:
module_path = "shub." + command
command_module = importlib.import_module(module_path)
command_name = command.replace('_', '-') # easier to type
cli.add_command(command_module.cli, command)
| import click, importlib
from shub.utils import missing_modules
def missingmod_cmd(modules):
modlist = ", ".join(modules)
@click.command(help="*DISABLED* - requires %s" % modlist)
@click.pass_context
def cmd(ctx):
click.echo("Error: '%s' command requires %s" % (ctx.info_name, modlist))
ctx.exit(1)
return cmd
@click.group(help="Scrapinghub command-line client")
def cli():
pass
module_deps = {
"deploy": ["scrapy", "setuptools"],
"login": [],
}
for command, modules in module_deps.iteritems():
m = missing_modules(*modules)
if m:
cli.add_command(missingmod_cmd(m), command)
else:
module_path = "shub." + command
command_module = importlib.import_module(module_path)
cli.add_command(command_module.cli, command)
|
Add enum field for vSphere backend
Review-Url: https://codereview.chromium.org/1997903002 | # Copyright 2015 The LUCI Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Dimensions for the Machine Provider."""
from protorpc import messages
class Backend(messages.Enum):
"""Lists valid backends."""
DUMMY = 0
GCE = 1
VSPHERE = 2
class OSFamily(messages.Enum):
"""Lists valid OS families."""
LINUX = 1
OSX = 2
WINDOWS = 3
class Dimensions(messages.Message):
"""Represents the dimensions of a machine."""
# The operating system family of this machine.
os_family = messages.EnumField(OSFamily, 1)
# The backend which should be used to spin up this machine. This should
# generally be left unspecified so the Machine Provider selects the backend
# on its own.
backend = messages.EnumField(Backend, 2)
# The hostname of this machine.
hostname = messages.StringField(3)
# The number of CPUs available to this machine.
num_cpus = messages.IntegerField(4)
# The amount of memory available to this machine.
memory_gb = messages.FloatField(5)
# The disk space available to this machine.
disk_gb = messages.IntegerField(6)
| # Copyright 2015 The LUCI Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Dimensions for the Machine Provider."""
from protorpc import messages
class Backend(messages.Enum):
"""Lists valid backends."""
DUMMY = 0
GCE = 1
class OSFamily(messages.Enum):
"""Lists valid OS families."""
LINUX = 1
OSX = 2
WINDOWS = 3
class Dimensions(messages.Message):
"""Represents the dimensions of a machine."""
# The operating system family of this machine.
os_family = messages.EnumField(OSFamily, 1)
# The backend which should be used to spin up this machine. This should
# generally be left unspecified so the Machine Provider selects the backend
# on its own.
backend = messages.EnumField(Backend, 2)
# The hostname of this machine.
hostname = messages.StringField(3)
# The number of CPUs available to this machine.
num_cpus = messages.IntegerField(4)
# The amount of memory available to this machine.
memory_gb = messages.FloatField(5)
# The disk space available to this machine.
disk_gb = messages.IntegerField(6)
|
Move TODO items to GitHub issues | #!/usr/bin/env python3
import argparse
import yaml
import jinja2
import weasyprint
parser = argparse.ArgumentParser()
parser.add_argument('--data', help='path to data directory', required=True)
parser.add_argument('--number', help='Invoice number', type=int, required=True)
args = parser.parse_args()
data_directory = str(args.data)
invoice_number = str(args.number)
supplier_file = open(data_directory + 'data/supplier.yaml')
supplier_data = yaml.safe_load(supplier_file.read())
supplier_file.close()
invoice_file = open(data_directory + 'data/invoices/' + invoice_number + '.yaml')
invoice_data = yaml.safe_load(invoice_file.read())
invoice_file.close()
client_file = open(data_directory + 'data/clients/' + invoice_data['client'] + '.yaml')
client_data = yaml.safe_load(client_file.read())
client_file.close()
template_environment = jinja2.Environment(loader = jinja2.FileSystemLoader('../templates/'))
template = template_environment.get_template('invoice.html')
html_data = template.render(supplier = supplier_data, invoice = invoice_data, client = client_data)
weasyprint.HTML(string = html_data).write_pdf(data_directory + 'output/invoices/' + invoice_number + '.pdf')
| #!/usr/bin/env python3
import argparse
import yaml
import jinja2
import weasyprint
parser = argparse.ArgumentParser()
parser.add_argument('--data', help='path to data directory', required=True)
parser.add_argument('--number', help='Invoice number', type=int, required=True)
args = parser.parse_args()
data_directory = str(args.data)
invoice_number = str(args.number)
supplier_file = open(data_directory + 'data/supplier.yaml')
supplier_data = yaml.safe_load(supplier_file.read())
supplier_file.close()
invoice_file = open(data_directory + 'data/invoices/' + invoice_number + '.yaml')
invoice_data = yaml.safe_load(invoice_file.read())
invoice_file.close()
# TODO: Validation
# TODO: Sum of invoice items equals total
# TODO: Invoice number matches filename
client_file = open(data_directory + 'data/clients/' + invoice_data['client'] + '.yaml')
client_data = yaml.safe_load(client_file.read())
client_file.close()
template_environment = jinja2.Environment(loader = jinja2.FileSystemLoader('../templates/'))
template = template_environment.get_template('invoice.html')
html_data = template.render(supplier = supplier_data, invoice = invoice_data, client = client_data)
weasyprint.HTML(string = html_data).write_pdf(data_directory + 'output/invoices/' + invoice_number + '.pdf')
|
Add author and version number | #!/usr/bin/python
__author__ = 'Mahmoud Hossam'
__version__ = '0.1'
import requests
class RT:
def __init__(self, apikey):
self.apikey = apikey
@staticmethod
def make_request(url, params=None):
req = requests.get(url, params=params)
return req.content
def search(self, query, page_limit=30, page=1):
url = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json'
params = {
'q': query,
'page_limit': page_limit,
'page': page,
'apikey': self.apikey}
return make_request(url, params)
def box_office(self, limit=10, country='us'):
url = 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json'
params = {
'limit': limit,
'country': country,
'apikey': self.apikey}
return make_request(url, params=params) | #!/usr/bin/python
import requests
class RT:
def __init__(self, apikey):
self.apikey = apikey
@staticmethod
def make_request(url, params=None):
req = requests.get(url, params=params)
return req.content
def search(self, query, page_limit=30, page=1):
url = 'http://api.rottentomatoes.com/api/public/v1.0/movies.json'
params = {
'q': query,
'page_limit': page_limit,
'page': page,
'apikey': self.apikey}
return make_request(url, params)
def box_office(self, limit=10, country='us'):
url = 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json'
params = {
'limit': limit,
'country': country,
'apikey': self.apikey}
return make_request(url, params=params) |
Refactor (Dashbord): add prefix to dashbord route | <?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
/**
* Class DashboardController
* @package AppBundle\Controller
* @Route("/dashboard")
*/
class DashboardController extends Controller
{
/**
* @Route("/compte", name="dashboard.account")
* @Method({"GET","POST"})
*/
public function accountAction(Request $request)
{
return $this->render('dashboard/account.html.twig');
}
/**
* @Route("/profil", name="dashboard.profil")
* @Method({"GET"})
*/
public function profilAction()
{
return $this->render('dashboard/profil.html.twig');
}
/**
* @Route("/notification", name="dashboard.notification")
* @Method({"GET"})
*/
public function notificationAction()
{
return $this->render('dashboard/notification.html.twig');
}
}
| <?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class DashboardController extends Controller
{
/**
* @Route("/dashboard/compte", name="dashboard.account")
* @Method({"GET","POST"})
*/
public function accountAction(Request $request)
{
return $this->render('dashboard/account.html.twig');
}
/**
* @Route("/dashboard/profil", name="dashboard.profil")
* @Method({"GET"})
*/
public function profilAction()
{
return $this->render('dashboard/profil.html.twig');
}
/**
* @Route("/dashboard/notification", name="dashboard.notification")
* @Method({"GET"})
*/
public function notificationAction()
{
return $this->render('dashboard/notification.html.twig');
}
}
|
Exit replaced by Runtime Exception, disable log creation | <?php
namespace BlueRegister\Events;
use BlueEvent\Event\BaseEvent;
class RegisterException extends BaseEvent
{
/**
* @var bool
*/
protected static $allowKill = false;
/**
* Set var that allow to kill application if register exception is throwed away
*
* @param bool $allowKill
*/
public static function allowKill($allowKill)
{
self::$allowKill = (bool)$allowKill;
}
/**
* @return bool
*/
public static function isKillingAllowed()
{
return self::$allowKill;
}
/**
* Allow to kill application if register throw an exception
*
* @param string $eventName
* @param array $parameters
* @throws \Exception
*/
public function __construct($eventName, array $parameters)
{
parent::__construct($eventName, $parameters);
if (self::$allowKill) {
throw new \RuntimeException('System killed by Register Exception. Unknown class: ' . $parameters[0]);
}
}
}
| <?php
namespace BlueRegister\Events;
use BlueEvent\Event\BaseEvent;
class RegisterException extends BaseEvent
{
/**
* @var \SimpleLog\LogInterface
*/
protected $log;
/**
* @var bool
*/
protected static $allowKill = false;
/**
* Set var that allow to kill application if register exception is throwed away
*
* @param bool $allowKill
*/
public static function allowKill($allowKill)
{
self::$allowKill = (bool)$allowKill;
}
/**
* @return bool
*/
public static function isKillingAllowed()
{
return self::$allowKill;
}
/**
* Allow to kill application if register throw an exception
*
* @param string $eventName
* @param array $parameters
* @throws \Exception
*/
public function __construct($eventName, array $parameters)
{
parent::__construct($eventName, $parameters);
if (self::$allowKill) {
$this->log->makeLog('System killed by Register Exception.');
throw new \RuntimeException('System killed by Register Exception.');
}
}
}
|
Include README content as long description. | # -*- coding: utf-8 -*-
import codecs
from setuptools import setup
with codecs.open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(
name='syslog2IRC',
version='0.8',
description='A proxy to forward syslog messages to IRC',
long_description=long_description,
url='http://homework.nwsnet.de/releases/c474/#syslog2irc',
author='Jochen Kupperschmidt',
author_email='homework@nwsnet.de',
license='MIT',
classifiers=[
'Environment :: Console',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Communications :: Chat :: Internet Relay Chat',
'Topic :: Internet',
'Topic :: System :: Logging',
'Topic :: System :: Monitoring',
'Topic :: System :: Networking :: Monitoring',
'Topic :: System :: Systems Administration',
],
)
| from setuptools import setup
setup(
name='syslog2IRC',
version='0.8',
description='A proxy to forward syslog messages to IRC',
url='http://homework.nwsnet.de/releases/c474/#syslog2irc',
author='Jochen Kupperschmidt',
author_email='homework@nwsnet.de',
license='MIT',
classifiers=[
'Environment :: Console',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Communications :: Chat :: Internet Relay Chat',
'Topic :: Internet',
'Topic :: System :: Logging',
'Topic :: System :: Monitoring',
'Topic :: System :: Networking :: Monitoring',
'Topic :: System :: Systems Administration',
],
)
|
Fix sentence buttons on reloaded random sentence
Closes #1658. | /**
* Tatoeba Project, free collaborative creation of multilingual corpuses project
* Copyright (C) 2009 HO Ngoc Phuong Trang <tranglich@gmail.com>
*
* 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/>.
*/
$(document).ready(function(){
var lang = $("#randomLangChoice").val();
if (lang == null) {
lang = '';
}
$("#showRandom").click(function(){
lang = $("#randomLangChoice").val();
loadRandom(lang);
})
});
function loadRandom(lang){
$("#random-progress").show();
$("#random_sentence_display").hide();
$.ajax({
type: "GET",
url: "/sentences/random/" + lang,
success: function (data){
$("#random_sentence_display").watch("html", data);
$("#random-progress").hide();
$("#random_sentence_display").show();
}
});
}
| /**
* Tatoeba Project, free collaborative creation of multilingual corpuses project
* Copyright (C) 2009 HO Ngoc Phuong Trang <tranglich@gmail.com>
*
* 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/>.
*/
$(document).ready(function(){
var lang = $("#randomLangChoice").val();
if (lang == null) {
lang = '';
}
$("#showRandom").click(function(){
lang = $("#randomLangChoice").val();
loadRandom(lang);
})
});
function loadRandom(lang){
$("#random-progress").show();
$("#random_sentence_display").hide();
$.ajax({
type: "GET",
url: "/sentences/random/" + lang,
success: function (data){
$("#random_sentence_display").html(data);
$("#random-progress").hide();
$("#random_sentence_display").show();
}
});
}
|
Add support to bind to multiple events in one call. | "use strict";
// Bind event listeners to target.
export function on (el, events, cb, capture = false) {
events.split(' ').map(event => {
if (event) el.addEventListener(event, cb, capture);
});
}
// Unbind event listeners
export function off (el, events, cb, capture = false) {
events.split(' ').map(event => {
if (event) el.removeEventListener(event, cb, capture);
});
}
// "No operation" function.
export function noop () {}
export function fullscreenElement () {
return document.fullscreenElement ||
document.mozFullScreenElement ||
document.webkitFullscreenElement;
}
export function fullscreenEnabled () {
return document.fullscreenEnabled ||
document.mozFullScreenEnabled ||
document.webkitFullscreenEnabled;
}
// Request fullscreen for given element.
export function enterFullscreen (element)
{
if(element.requestFullscreen) {
element.requestFullscreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if(element.msRequestFullscreen) {
element.msRequestFullscreen();
}
}
// Exit fullscreen
export function exitFullscreen ()
{
if(document.exitFullscreen) {
document.exitFullscreen();
} else if(document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if(document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if(document.msExitFullscreen) {
document.msExitFullscreen();
}
}
| "use strict";
// Bind event listeners to target.
export function on (target, eventName, listener, capture = false) {
return target.addEventListener(eventName, listener, capture);
}
// Unbind event listeners
export function off (target, eventName, listener, capture = false) {
target.removeEventListener(eventName, listener, capture);
}
// "No operation" function.
export function noop () {}
export function fullscreenElement () {
return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;
}
export function fullscreenEnabled () {
return document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled;
}
// Request fullscreen for given element.
export function enterFullscreen (element)
{
if(element.requestFullscreen) {
element.requestFullscreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if(element.msRequestFullscreen) {
element.msRequestFullscreen();
}
}
// Exit fullscreen
export function exitFullscreen ()
{
if(document.exitFullscreen) {
document.exitFullscreen();
} else if(document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if(document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if(document.msExitFullscreen) {
document.msExitFullscreen();
}
}
|
Ch17: Revert to Tag Detail URL pattern. | from django.conf.urls import url
from ..views import (
TagCreate, TagDelete, TagDetail, TagList,
TagPageList, TagUpdate)
urlpatterns = [
url(r'^$',
TagList.as_view(),
name='organizer_tag_list'),
url(r'^create/$',
TagCreate.as_view(),
name='organizer_tag_create'),
url(r'^(?P<page_number>\d+)/$',
TagPageList.as_view(),
name='organizer_tag_page'),
url(r'^(?P<slug>[\w\-]+)/$',
TagDetail.as_view(),
name='organizer_tag_detail'),
url(r'^(?P<slug>[\w-]+)/delete/$',
TagDelete.as_view(),
name='organizer_tag_delete'),
url(r'^(?P<slug>[\w\-]+)/update/$',
TagUpdate.as_view(),
name='organizer_tag_update'),
]
| from django.conf.urls import url
from ..models import Tag
from ..utils import DetailView
from ..views import (
TagCreate, TagDelete, TagList, TagPageList,
TagUpdate)
urlpatterns = [
url(r'^$',
TagList.as_view(),
name='organizer_tag_list'),
url(r'^create/$',
TagCreate.as_view(),
name='organizer_tag_create'),
url(r'^(?P<page_number>\d+)/$',
TagPageList.as_view(),
name='organizer_tag_page'),
url(r'^(?P<slug>[\w\-]+)/$',
DetailView.as_view(
context_object_name='tag',
model=Tag,
template_name=(
'organizer/tag_detail.html')),
name='organizer_tag_detail'),
url(r'^(?P<slug>[\w-]+)/delete/$',
TagDelete.as_view(),
name='organizer_tag_delete'),
url(r'^(?P<slug>[\w\-]+)/update/$',
TagUpdate.as_view(),
name='organizer_tag_update'),
]
|
Use non-deprecated new instance method | package uk.co.ticklethepanda.carto.apps.web.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import uk.co.ticklethepanda.carto.core.projection.Projector;
import java.lang.reflect.InvocationTargetException;
@Configuration
public class ProjectionConfig {
@Bean(name = "projector")
public Projector projector(
@Value("${location.history.heatmap.projector}") String projectorName
) throws ClassNotFoundException,
IllegalAccessException,
InstantiationException,
NoSuchMethodException,
InvocationTargetException {
Class<?> projectorClass = Class.forName(projectorName);
Object projector = projectorClass.getDeclaredConstructor().newInstance();
if (!(projector instanceof Projector)) {
throw new IllegalArgumentException("\"location.history.heatmap.projector\" must be a type of Projector");
}
return (Projector) projector;
}
}
| package uk.co.ticklethepanda.carto.apps.web.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import uk.co.ticklethepanda.carto.core.projection.Projector;
@Configuration
public class ProjectionConfig {
@Bean(name = "projector")
public Projector projector(
@Value("${location.history.heatmap.projector}") String projectorName
) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class<?> projectorClass = Class.forName(projectorName);
Object projector = projectorClass.newInstance();
if (!(projector instanceof Projector)) {
throw new IllegalArgumentException("\"location.history.heatmap.projector\" must be a type of Projector");
}
return (Projector) projector;
}
}
|
Update the column type of the value field | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateTranslationTranslationTranslationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('translation__translation_translations', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->text('value');
$table->integer('translation_id')->unsigned();
$table->string('locale')->index();
$table->unique(['translation_id', 'locale'], 'translations_trans_id_locale_unique');
$table->foreign('translation_id' )->references('id')->on('translation__translations')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('translation__translation_translations');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateTranslationTranslationTranslationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('translation__translation_translations', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('value');
$table->integer('translation_id')->unsigned();
$table->string('locale')->index();
$table->unique(['translation_id', 'locale'], 'translations_trans_id_locale_unique');
$table->foreign('translation_id' )->references('id')->on('translation__translations')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('translation__translation_translations');
}
}
|
Add route to hit notification controller | <?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('jwt.auth')->get('v1/user', function (Request $request) {
return $request->user();
});
Route::group(['prefix' => 'v1/', 'middleware' => ['jwt.auth', 'cas.auth']], function () {
Route::post('faset', 'FasetVisitController@visit');
Route::get('faset', 'FasetVisitController@list')->middleware('can:administer');
Route::get('faset/{id}', 'FasetVisitController@show')->middleware('can:administer');
Route::put('faset/{id}', 'FasetVisitController@update')->middleware('can:administer');
Route::get('notification/send', 'NotificationController@sendNotification')->middleware('can:administer');
Route::middleware('can:administer')->resource('users', 'UserController', ['except' => ['create', 'edit']]);
Route::middleware('can:administer')->resource('events', 'EventController', ['except' => ['create', 'edit']]);
});
| <?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('jwt.auth')->get('v1/user', function (Request $request) {
return $request->user();
});
Route::group(['prefix' => 'v1/', 'middleware' => ['jwt.auth', 'cas.auth']], function () {
Route::post('faset', 'FasetVisitController@visit');
Route::get('faset', 'FasetVisitController@list')->middleware('can:administer');
Route::get('faset/{id}', 'FasetVisitController@show')->middleware('can:administer');
Route::put('faset/{id}', 'FasetVisitController@update')->middleware('can:administer');
Route::middleware('can:administer')->resource('users', 'UserController', ['except' => ['create', 'edit']]);
Route::middleware('can:administer')->resource('events', 'EventController', ['except' => ['create', 'edit']]);
});
|
CAPI-219: Allow creation of empty user groups | // Copyright 2013 Joyent, Inc. All rights reserved.
var util = require('util');
var ldap = require('ldapjs');
var Validator = require('../lib/schema/validator');
///--- Globals
var ConstraintViolationError = ldap.ConstraintViolationError;
///--- API
function GroupOfUniqueNames() {
Validator.call(this, {
name: 'groupofuniquenames',
optional: {
uniquemember: 1000000,
description: 1
},
strict: true
});
}
util.inherits(GroupOfUniqueNames, Validator);
GroupOfUniqueNames.prototype.validate = function validate(entry, callback) {
var members = entry.attributes.uniquemember || [];
members.sort();
for (var i = 0; i < members.length; i++) {
if (members.indexOf(members[i], i + 1) !== -1) {
return callback(new ConstraintViolationError(members[i] +
' is not unique'));
}
}
return callback();
};
///--- Exports
module.exports = {
createInstance: function createInstance() {
return new GroupOfUniqueNames();
}
};
| // Copyright 2012 Joyent, Inc. All rights reserved.
var util = require('util');
var ldap = require('ldapjs');
var Validator = require('../lib/schema/validator');
///--- Globals
var ConstraintViolationError = ldap.ConstraintViolationError;
///--- API
function GroupOfUniqueNames() {
Validator.call(this, {
name: 'groupofuniquenames',
required: {
uniquemember: 1000000
},
optional: {
description: 1
},
strict: true
});
}
util.inherits(GroupOfUniqueNames, Validator);
GroupOfUniqueNames.prototype.validate = function validate(entry, callback) {
var members = entry.attributes.uniquemember;
members.sort();
for (var i = 0; i < members.length; i++) {
if (members.indexOf(members[i], i + 1) !== -1) {
return callback(new ConstraintViolationError(members[i] +
' is not unique'));
}
}
return callback();
};
///--- Exports
module.exports = {
createInstance: function createInstance() {
return new GroupOfUniqueNames();
}
};
|
monkeysphere: Allow SHA256 hashes in URLs | #
# This file is part of Plinth.
#
# 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/>.
#
"""
URLs for the monkeysphere module.
"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^sys/monkeysphere/$', views.index, name='index'),
url(r'^sys/monkeysphere/(?P<ssh_fingerprint>[0-9A-Za-z:+/]+)/import/$',
views.import_key, name='import'),
url(r'^sys/monkeysphere/(?P<fingerprint>[0-9A-Fa-f]+)/details/$',
views.details, name='details'),
url(r'^sys/monkeysphere/(?P<fingerprint>[0-9A-Fa-f]+)/publish/$',
views.publish, name='publish'),
url(r'^sys/monkeysphere/cancel/$', views.cancel, name='cancel'),
]
| #
# This file is part of Plinth.
#
# 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/>.
#
"""
URLs for the monkeysphere module.
"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^sys/monkeysphere/$', views.index, name='index'),
url(r'^sys/monkeysphere/(?P<ssh_fingerprint>[0-9A-Fa-f:]+)/import/$',
views.import_key, name='import'),
url(r'^sys/monkeysphere/(?P<fingerprint>[0-9A-Fa-f]+)/details/$',
views.details, name='details'),
url(r'^sys/monkeysphere/(?P<fingerprint>[0-9A-Fa-f]+)/publish/$',
views.publish, name='publish'),
url(r'^sys/monkeysphere/cancel/$', views.cancel, name='cancel'),
]
|
Update service provider to use bindShared.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Facile;
use Illuminate\Support\ServiceProvider;
class FacileServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('orchestra.facile', function ($app) {
$env = new Environment($app);
$env->template('default', function () use ($app) {
return new Template\Base($app);
});
return $env;
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.facile');
}
}
| <?php namespace Orchestra\Facile;
use Illuminate\Support\ServiceProvider;
class FacileServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['orchestra.facile'] = $this->app->share(function ($app) {
$env = new Environment($app);
$env->template('default', function () use ($app) {
return new Template\Base($app);
});
return $env;
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.facile');
}
}
|
Set database session to UTC | package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"log"
"time"
)
func connectToDatabase() {
var err error
driver := "postgres"
connect := fmt.Sprintf("dbname='%s' user='%s' password='%s' host='%s' port='%s' sslmode='%s' connect_timeout='%s'",
SomaCfg.Database.Name,
SomaCfg.Database.User,
SomaCfg.Database.Pass,
SomaCfg.Database.Host,
SomaCfg.Database.Port,
SomaCfg.TlsMode,
SomaCfg.Timeout,
)
conn, err = sql.Open(driver, connect)
if err != nil {
log.Fatal(err)
}
log.Print("Connected to database")
conn.Exec(`SET TIME ZONE 'UTC';`)
}
func pingDatabase() {
ticker := time.NewTicker(time.Second).C
for {
<-ticker
err := conn.Ping()
if err != nil {
log.Print(err)
}
}
}
// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
| package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"log"
"time"
)
func connectToDatabase() {
var err error
driver := "postgres"
connect := fmt.Sprintf("dbname='%s' user='%s' password='%s' host='%s' port='%s' sslmode='%s' connect_timeout='%s'",
SomaCfg.Database.Name,
SomaCfg.Database.User,
SomaCfg.Database.Pass,
SomaCfg.Database.Host,
SomaCfg.Database.Port,
SomaCfg.TlsMode,
SomaCfg.Timeout,
)
conn, err = sql.Open(driver, connect)
if err != nil {
log.Fatal(err)
}
log.Print("Connected to database")
}
func pingDatabase() {
ticker := time.NewTicker(time.Second).C
for {
<-ticker
err := conn.Ping()
if err != nil {
log.Print(err)
}
}
}
// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
|
Add date_created and date_updated to editos.Edito model | from django.db import models
from geelweb.django.editos import settings
class Edito(models.Model):
title = models.CharField(max_length=100)
link = models.URLField()
button_label = models.CharField(max_length=20, default="Go !",
Required=False)
image = models.FileField(upload_to="editos")
text_content = models.CharField(max_length=400)
display_from = models.DateField()
display_until = models.DateField()
active = models.BooleanField(default=True)
text_theme = models.CharField(max_length=10, choices=settings.EDITOS_THEMES,
default=settings.EDITOS_DEFAULT_THEME)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.title
| from django.db import models
from geelweb.django.editos import settings
class Edito(models.Model):
title = models.CharField(max_length=100)
link = models.URLField()
button_label = models.CharField(max_length=20, default="Go !",
Required=False)
image = models.FileField(upload_to="editos")
text_content = models.CharField(max_length=400)
display_from = models.DateField()
display_until = models.DateField()
active = models.BooleanField(default=True)
text_theme = models.CharField(max_length=10, choices=settings.EDITOS_THEMES,
default=settings.EDITOS_DEFAULT_THEME)
def __unicode__(self):
return self.title
|
Split out a helper function. | // Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// 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 auth
import (
"errors"
"github.com/jacobsa/aws"
"github.com/jacobsa/aws/s3/http"
)
// A Signer knows how to create signatures suitable for inclusion in an HTTP
// request to S3.
type Signer interface {
// Add an appropriate signature header to the supplied HTTP request.
Sign(r *http.Request) error
}
// NewSigner creates a Signer using the supplied access key.
func NewSigner(key aws.AccessKey) (Signer, error) {
return newSigner(stringToSign, key)
}
// newSigner is a helper used by NewSigner, split out for testability. It
// allows you to inject the function that is used to determine the string to
// sign for any given request.
func newSigner(
sts func(*http.Request) (string, error),
key aws.AccessKey) (Signer, error) {
return nil, errors.New("TODO: Implement newSigner.")
}
| // Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// 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 auth
import (
"errors"
"github.com/jacobsa/aws"
"github.com/jacobsa/aws/s3/http"
)
// A Signer knows how to create signatures suitable for inclusion in an HTTP
// request to S3.
type Signer interface {
// Add an appropriate signature header to the supplied HTTP request.
Sign(r *http.Request) error
}
// NewSigner creates a Signer using the supplied access key.
func NewSigner(key aws.AccessKey) (Signer, error) {
return nil, errors.New("TODO: Implement NewSigner.")
}
|
Use write to avoid newline problems | #!/usr/bin/python
import re
import sys
def main(argv):
examples = {}
requires = set()
for filename in argv[1:]:
lines = open(filename, 'rU').readlines()
if len(lines) > 0 and lines[0].startswith('// NOCOMPILE'):
continue
requires.update(line for line in lines if line.startswith('goog.require'))
examples[filename] = [line for line in lines if not line.startswith('goog.require')]
for require in sorted(requires):
sys.stdout.write(require)
for filename in sorted(examples.keys()):
sys.stdout.write('// ' + filename + '\n')
sys.stdout.write('(function(){\n')
for line in examples[filename]:
sys.stdout.write(line)
sys.stdout.write('})();\n')
if __name__ == '__main__':
sys.exit(main(sys.argv))
| #!/usr/bin/python
import re
import sys
def main(argv):
examples = {}
requires = set()
for filename in argv[1:]:
lines = open(filename, 'rU').readlines()
if len(lines) > 0 and lines[0].startswith('// NOCOMPILE'):
continue
requires.update(line for line in lines if line.startswith('goog.require'))
examples[filename] = [line for line in lines if not line.startswith('goog.require')]
for require in sorted(requires):
print require,
for filename in sorted(examples.keys()):
print '// ', filename
print '(function(){'
for line in examples[filename]:
print line,
print '})();'
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
Handle form decoding error & refactor | package actions
import (
"bones/web/forms"
"bones/web/templating"
"net/http"
)
type SaveFormAndRedirect struct {
ResponseWriter http.ResponseWriter
Request *http.Request
Form forms.Form
SuccessUrl string
ErrorContext templating.TemplateContext
}
func (wf SaveFormAndRedirect) Run() {
if err := forms.DecodeForm(wf.Form, wf.Request); wf.renderError(err) {
return
}
if err := wf.Form.Validate(); wf.renderError(err) {
return
}
if err := wf.Form.Save(); wf.renderError(err) {
return
}
http.Redirect(wf.ResponseWriter, wf.Request, wf.SuccessUrl, 302)
}
func (wf SaveFormAndRedirect) renderError(err error) bool {
if err != nil {
wf.ErrorContext.AddError(err)
renderErr := templating.RenderTemplate(wf.ResponseWriter, wf.ErrorContext)
if renderErr != nil {
logTemplateRenderingErrorAndRespond500(wf.ResponseWriter, renderErr, wf.ErrorContext)
}
return true
}
return false
}
| package actions
import (
"bones/web/forms"
"bones/web/templating"
"net/http"
)
type SaveFormAndRedirect struct {
ResponseWriter http.ResponseWriter
Request *http.Request
Form forms.Form
SuccessUrl string
ErrorContext templating.TemplateContext
}
func (wf SaveFormAndRedirect) Run() {
forms.DecodeForm(wf.Form, wf.Request)
err := wf.Form.Validate()
if err != nil {
wf.renderError(err)
} else {
err = wf.Form.Save()
if err != nil {
wf.renderError(err)
return
}
http.Redirect(wf.ResponseWriter, wf.Request, wf.SuccessUrl, 302)
}
}
func (wf SaveFormAndRedirect) renderError(err error) {
wf.ErrorContext.AddError(err)
renderErr := templating.RenderTemplate(wf.ResponseWriter, wf.ErrorContext)
if renderErr != nil {
logTemplateRenderingErrorAndRespond500(wf.ResponseWriter, renderErr, wf.ErrorContext)
}
}
|
Fix typo: export -> expose | /*
Copyright 2016 The Kubernetes Authors.
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 main
import (
"fmt"
"github.com/spf13/cobra"
)
func init() {
cmd := &cobra.Command{
Use: "expose",
Short: "Expose secrets",
Long: `Expose secrets.`,
Run: func(cmd *cobra.Command, args []string) {
exitWithError(fmt.Errorf("The 'secrets expose' command has been replaced by 'get secrets -oplaintext'"))
},
}
secretsCmd.AddCommand(cmd)
}
| /*
Copyright 2016 The Kubernetes Authors.
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 main
import (
"fmt"
"github.com/spf13/cobra"
)
func init() {
cmd := &cobra.Command{
Use: "expose",
Short: "Expose secrets",
Long: `Expose secrets.`,
Run: func(cmd *cobra.Command, args []string) {
exitWithError(fmt.Errorf("The 'secrets export' command has been replaced by 'get secrets -oplaintext'"))
},
}
secretsCmd.AddCommand(cmd)
}
|
Remove redundant app.Name, internally codegangsta uses os.Args[0] | /*
* Mini Object Storage, (C) 2014,2015 Minio, 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.
*/
package main
import (
"log"
"os"
"os/user"
"github.com/codegangsta/cli"
)
func init() {
// Check for the environment early on and gracefuly report.
_, err := user.Current()
if err != nil {
log.Fatalf("mc: Unable to obtain user's home directory. \nERROR[%v]\n", err)
}
}
func main() {
app := cli.NewApp()
app.Usage = "Minio Client for S3 Compatible Object Storage"
app.Version = "0.1.0"
app.Commands = options
app.Flags = flags
app.Author = "Minio.io"
app.EnableBashCompletion = true
app.Action = parseGlobalOptions
app.Run(os.Args)
}
| /*
* Mini Object Storage, (C) 2014,2015 Minio, 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.
*/
package main
import (
"log"
"os"
"os/user"
"github.com/codegangsta/cli"
)
func init() {
// Check for the environment early on and gracefuly report.
_, err := user.Current()
if err != nil {
log.Fatalf("mc: Unable to obtain user's home directory. \nERROR[%v]\n", err)
}
}
func main() {
app := cli.NewApp()
app.Name = "mc"
app.Usage = "Minio Client for S3 Compatible Object Storage"
app.Version = "0.1.0"
app.Commands = options
app.Flags = flags
app.Author = "Minio.io"
app.EnableBashCompletion = true
app.Action = parseGlobalOptions
app.Run(os.Args)
}
|
Update push() to addd() in test app. | <?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.3.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace TestApp;
use Cake\Http\BaseApplication;
use Cake\Routing\Middleware\RoutingMiddleware;
class Application extends BaseApplication
{
/**
* Bootstrap hook.
*
* Nerfed as this is for IntegrationTestCase testing.
*
* @return void
*/
public function bootstrap()
{
// Do nothing.
}
public function middleware($middleware)
{
$middleware->add(new RoutingMiddleware());
$middleware->add(function ($req, $res, $next) {
$res = $next($req, $res);
return $res->withHeader('X-Middleware', 'true');
});
return $middleware;
}
}
| <?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.3.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace TestApp;
use Cake\Http\BaseApplication;
use Cake\Routing\Middleware\RoutingMiddleware;
class Application extends BaseApplication
{
/**
* Bootstrap hook.
*
* Nerfed as this is for IntegrationTestCase testing.
*
* @return void
*/
public function bootstrap()
{
// Do nothing.
}
public function middleware($middleware)
{
$middleware->push(new RoutingMiddleware());
$middleware->push(function ($req, $res, $next) {
$res = $next($req, $res);
return $res->withHeader('X-Middleware', 'true');
});
return $middleware;
}
}
|
Make JsonField actually do it's work
This code will be used when objects are registered.
Change-Id: I2f1b3e2dd5584335e318b936984c227050bbe699
Partial-Bug: 1491258 | # Copyright 2014 Intel Corp.
#
# 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.
from oslo_serialization import jsonutils as json
from oslo_versionedobjects import fields
import six
class Json(fields.FieldType):
def coerce(self, obj, attr, value):
if isinstance(value, six.string_types):
loaded = json.loads(value)
return loaded
return value
def from_primitive(self, obj, attr, value):
return self.coerce(obj, attr, value)
def to_primitive(self, obj, attr, value):
return json.dumps(value)
class JsonField(fields.AutoTypedField):
AUTO_TYPE = Json()
class ListField(fields.AutoTypedField):
AUTO_TYPE = fields.List(fields.FieldType())
| # Copyright 2014 Intel Corp.
#
# 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.
from oslo_serialization import jsonutils as json
from oslo_versionedobjects import fields
import six
class Json(fields.FieldType):
def coerce(self, obj, attr, value):
if isinstance(value, six.string_types):
loaded = json.loads(value)
return loaded
return value
def from_primitive(self, obj, attr, value):
return self.coerce(obj, attr, value)
def to_primitive(self, obj, attr, value):
return json.dumps(value)
class JsonField(fields.AutoTypedField):
pass
class ListField(fields.AutoTypedField):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.