text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Clarify ambiguous reference to Empty class | package org.workcraft.plugins.circuit.tools;
import java.awt.Color;
import org.workcraft.gui.graph.tools.Decoration;
public interface StateDecoration extends Decoration {
boolean showForcedInit();
class Empty implements StateDecoration {
@Override
public Color getColorisation() {
return Decoration.Empty.INSTANCE.getColorisation();
}
@Override
public Color getBackground() {
return Decoration.Empty.INSTANCE.getBackground();
}
@Override
public boolean showForcedInit() {
return true;
}
public static final StateDecoration.Empty INSTANCE = new StateDecoration.Empty();
}
}
| package org.workcraft.plugins.circuit.tools;
import java.awt.Color;
import org.workcraft.gui.graph.tools.Decoration;
public interface StateDecoration extends Decoration {
boolean showForcedInit();
class Empty implements StateDecoration {
@Override
public Color getColorisation() {
return Decoration.Empty.INSTANCE.getColorisation();
}
@Override
public Color getBackground() {
return Decoration.Empty.INSTANCE.getBackground();
}
@Override
public boolean showForcedInit() {
return true;
}
public static final Empty INSTANCE = new Empty();
}
}
|
Add stacktrace to error event | "use strict";
angular.module('arethusa').factory('GlobalErrorHandler', [
'$window',
'$analytics',
function($window, $analytics) {
var oldErrorHandler = $window.onerror;
$window.onerror = function errorHandler(errorMessage, url, lineNumber) {
$analytics.eventTrack(errorMessage + " @" + url + " : " + lineNumber, {
category: 'error', label: errorMessage
});
if (oldErrorHandler)
return oldErrorHandler(errorMessage, url, lineNumber);
return false;
};
}
]);
angular.module('arethusa').factory('$exceptionHandler', [
'$analytics',
'$log',
function($analytics, $log) {
return function errorHandler(exception, cause) {
$log.error.apply($log, arguments);
var trace = printStackTrace();
$analytics.eventTrack(exception + ': ' + cause, {
category: 'error', label: trace.join(', ')
});
};
}
]);
| "use strict";
angular.module('arethusa').factory('GlobalErrorHandler', [
'$window',
'$analytics',
function($window, $analytics) {
var oldErrorHandler = $window.onerror;
$window.onerror = function errorHandler(errorMessage, url, lineNumber) {
$analytics.eventTrack(errorMessage + " @" + url + " : " + lineNumber, {
category: 'error', label: errorMessage
});
if (oldErrorHandler)
return oldErrorHandler(errorMessage, url, lineNumber);
return false;
};
}
]);
angular.module('arethusa').factory('$exceptionHandler', [
'$analytics',
'$log',
function($analytics, $log) {
return function(exception, cause) {
$log.error.apply($log, arguments);
$analytics.eventTrack(exception + ": " + cause, {
category: 'error', label: exception
});
};
}
]);
|
Use res.locals.namespace instead of config.app.namespace
config.app.namespace may not be defined, but res.locals.namespace will. | var passport = require('passport');
exports.setRoutes = function(app, config) {
app.get('/login', function(req, res) {
res.render('login.html', { errors: req.flash('error') });
});
app.post('/login',
passport.authenticate('local', {
failureRedirect : res.locals.namespace + '/login',
failureFlash : true
}),
function(req, res) {
res.redirect(req.session.returnTo || res.locals.namespace);
}
);
app.get('/logout', function(req, res) {
req.logout();
res.redirect(req.header('Referrer') || res.locals.namespace);
});
};
| var passport = require('passport');
exports.setRoutes = function(app, config) {
app.get('/login', function(req, res) {
res.render('login.html', { errors: req.flash('error') });
});
app.post('/login',
passport.authenticate('local', {
failureRedirect : config.app.namespace + '/login',
failureFlash : true
}),
function(req, res) {
res.redirect(req.session.returnTo || config.app.namespace);
}
);
app.get('/logout', function(req, res) {
req.logout();
res.redirect(req.header('Referrer') || config.app.namespace);
});
};
|
Use UserSerializer to serialize current user in the root response | from rest_framework.decorators import api_view
from rest_framework.response import Response
from .utils import absolute_reverse
from api.users.serializers import UserSerializer
@api_view(('GET',))
def root(request, format=None):
if request.user and not request.user.is_anonymous():
user = request.user
# TODO: Use user serializer
current_user = UserSerializer(user).data
else:
current_user = None
return Response({
'meta': {
'message': 'Welcome to the OSF API v2',
'current_user': current_user,
},
'links': {
'nodes': absolute_reverse('nodes:node-list'),
'users': absolute_reverse('users:user-list'),
}
})
| from rest_framework.decorators import api_view
from rest_framework.response import Response
from .utils import absolute_reverse
@api_view(('GET',))
def root(request, format=None):
if request.user and not request.user.is_anonymous():
user = request.user
# TODO: Use user serializer
current_user = {
'id': user.pk,
'fullname': user.fullname,
}
else:
current_user = None
return Response({
'message': 'Welcome to the OSF API v2',
'current_user': current_user,
'links': {
'nodes': absolute_reverse('nodes:node-list'),
'users': absolute_reverse('users:user-list'),
}
})
|
Remove action from required params | class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.data_type
self._handler = handler_class(self, **handler_options)
self._connected = False
def _assert_not_connected(self):
assert not self._connected, 'transport connection already created'
def _assert_connected(self):
assert self._connected, 'transport connection has not created'
def _encode_obj(self, obj):
return self._data_format.encode(obj)
def _decode_data(self, data):
return self._data_format.decode(data)
def _call_handler_method(self, name, *args):
getattr(self._handler, name)(*args)
def is_connected(self):
return self._connected
def connect(self, url, **options):
raise NotImplementedError
def send_request(self, obj, **params):
raise NotImplementedError
def request(self, obj, **params):
raise NotImplementedError
def close(self):
raise NotImplementedError
def join(self, timeout=None):
raise NotImplementedError
| class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.data_type
self._handler = handler_class(self, **handler_options)
self._connected = False
def _assert_not_connected(self):
assert not self._connected, 'transport connection already created'
def _assert_connected(self):
assert self._connected, 'transport connection has not created'
def _encode_obj(self, obj):
return self._data_format.encode(obj)
def _decode_data(self, data):
return self._data_format.decode(data)
def _call_handler_method(self, name, *args):
getattr(self._handler, name)(*args)
def is_connected(self):
return self._connected
def connect(self, url, **options):
raise NotImplementedError
def send_request(self, action, obj, **params):
raise NotImplementedError
def request(self, action, obj, **params):
raise NotImplementedError
def close(self):
raise NotImplementedError
def join(self, timeout=None):
raise NotImplementedError
|
Support for PSR-15 RequestHandlerInterface for queue items
Problem/details/solution noted here:
https://github.com/relayphp/Relay.Relay/issues/47 | <?php
/**
*
* This file is part of Relay for PHP.
*
* @license http://opensource.org/licenses/MIT MIT
*
* @copyright 2015-2018, Paul M. Jones
*
*/
namespace Relay;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
*
* A PSR-15 request handler.
*
* @package relay/relay
*
*/
class Runner extends RequestHandler
{
/**
* @inheritdoc
*/
public function handle(ServerRequestInterface $request) : ResponseInterface
{
$entry = current($this->queue);
$middleware = call_user_func($this->resolver, $entry);
next($this->queue);
if ($middleware instanceof MiddlewareInterface) {
return $middleware->process($request, $this);
}
if ($middleware instanceof RequestHandlerInterface) {
return $middleware->handle($request);
}
return $middleware($request, $this);
}
}
| <?php
/**
*
* This file is part of Relay for PHP.
*
* @license http://opensource.org/licenses/MIT MIT
*
* @copyright 2015-2018, Paul M. Jones
*
*/
namespace Relay;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
/**
*
* A PSR-15 request handler.
*
* @package relay/relay
*
*/
class Runner extends RequestHandler
{
/**
* @inheritdoc
*/
public function handle(ServerRequestInterface $request) : ResponseInterface
{
$entry = current($this->queue);
$middleware = call_user_func($this->resolver, $entry);
next($this->queue);
if ($middleware instanceof MiddlewareInterface) {
return $middleware->process($request, $this);
}
return $middleware($request, $this);
}
}
|
Check for creating only Saga instances. | <?php
declare(strict_types = 1);
namespace Apha\Saga;
use Apha\Domain\Identity;
class GenericSagaFactory implements SagaFactory
{
/**
* @param string $sagaType
* @param Identity $identity
* @param AssociationValues $associationValues
* @return Saga
* @throws \InvalidArgumentException
*/
public function createSaga(string $sagaType, Identity $identity, AssociationValues $associationValues): Saga
{
if (!$this->supports($sagaType)) {
throw new \InvalidArgumentException("This factory does not support Sagas of type '{$sagaType}'.");
}
return new $sagaType($identity, $associationValues);
}
/**
* @param string $sagaType
* @return bool
*/
public function supports(string $sagaType): bool
{
return is_subclass_of($sagaType, Saga::class, true);
}
} | <?php
declare(strict_types = 1);
namespace Apha\Saga;
use Apha\Domain\Identity;
class GenericSagaFactory implements SagaFactory
{
/**
* @param string $sagaType
* @param Identity $identity
* @param AssociationValues $associationValues
* @return Saga
* @throws \InvalidArgumentException
*/
public function createSaga(string $sagaType, Identity $identity, AssociationValues $associationValues): Saga
{
return new $sagaType($identity, $associationValues);
}
/**
* @param string $sagaType
* @return bool
*/
public function supports(string $sagaType): bool
{
// the naive way
return true;
}
} |
Update isFeatureEnabled to require a Set and add guard. | /**
* Feature flags.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const enabledFeatures = new Set( global?._googlesitekitBaseData?.enabledFeatures || [] );
/**
* Returns true if a feature is enabled; false otherwise.
*
* @since 1.25.0
* @since n.e.x.t Changed _enabledFeatures argument to be a `Set` instead of `Array`.
*
* @param {string} feature The name of the feature to check.
* @param {Set} [_enabledFeatures] Optional. The set of enabled features. Uses `enabledFeatures` set by the server in a global JS variable, by default.
* @return {boolean} `true` if a feature is enabled; `false` otherwise.
*/
export const isFeatureEnabled = ( feature, _enabledFeatures = enabledFeatures ) => {
if ( ! ( _enabledFeatures instanceof Set ) ) {
return false;
}
return _enabledFeatures.has( feature );
};
| /**
* Feature flags.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const enabledFeatures = new Set( global?._googlesitekitBaseData?.enabledFeatures || [] );
/**
* Returns true if a feature is enabled; false otherwise.
*
* @since 1.25.0
*
* @param {string} feature The name of the feature to check.
* @param {Set} [_enabledFeatures] Optional. The set of enabled features. Uses `enabledFeatures` set by the server in a global JS variable, by default.
* @return {boolean} `true` if a feature is enabled; `false` otherwise.
*/
export const isFeatureEnabled = ( feature, _enabledFeatures = enabledFeatures ) => {
return _enabledFeatures.has( feature );
};
|
Make it so HTML and EJS are both rendering via EJS. | var routeList = require('../config/routeList');
var router = require('koa-router');
var controllers = require('./controllers')
var views = require('./views');
module.exports = function(app){
app.use(views('./views', {
map: {
html: 'ejs',
ejs: 'ejs'
},
locals: {
title: 'with underscore'
},
cache: false
}));
app.use(router(app));
for(var k in routeList){
var functionsToCall = []
var routeData = k.split(' ');
var method = routeData[0].toLowerCase();
var route = routeData[1];
functionsToCall.push(route);
var actionList = routeList[k].split(' ');
for(var i=0; i<actionList.length; i+=1){
var actionData = actionList[i].split('.');
var cont = actionData[0];
var action = actionData[1];
functionsToCall.push(controllers[cont][action]);
}
// var actionData = routeList[k].split('.');
// var cont = actionData[0];
// var action = actionData[1];
app[method].apply(null, functionsToCall);
}
}
| var routeList = require('../config/routeList');
var router = require('koa-router');
var controllers = require('./controllers')
var views = require('./views');
module.exports = function(app){
app.use(views('./views', {
map: {
html: 'underscore'
},
locals: {
title: 'with underscore'
},
cache: false
}));
app.use(router(app));
for(var k in routeList){
var functionsToCall = []
var routeData = k.split(' ');
var method = routeData[0].toLowerCase();
var route = routeData[1];
functionsToCall.push(route);
var actionList = routeList[k].split(' ');
for(var i=0; i<actionList.length; i+=1){
var actionData = actionList[i].split('.');
var cont = actionData[0];
var action = actionData[1];
functionsToCall.push(controllers[cont][action]);
}
// var actionData = routeList[k].split('.');
// var cont = actionData[0];
// var action = actionData[1];
app[method].apply(null, functionsToCall);
}
}
|
Add scalar typehints/return types on final/internal/private code | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Entry point for the Validator component.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
final class Validation
{
/**
* Creates a new validator.
*
* If you want to configure the validator, use
* {@link createValidatorBuilder()} instead.
*
* @return ValidatorInterface The new validator
*/
public static function createValidator(): ValidatorInterface
{
return self::createValidatorBuilder()->getValidator();
}
/**
* Creates a configurable builder for validator objects.
*
* @return ValidatorBuilderInterface The new builder
*/
public static function createValidatorBuilder(): ValidatorBuilder
{
return new ValidatorBuilder();
}
/**
* This class cannot be instantiated.
*/
private function __construct()
{
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator;
use Symfony\Component\Validator\Validator\ValidatorInterface;
/**
* Entry point for the Validator component.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
final class Validation
{
/**
* Creates a new validator.
*
* If you want to configure the validator, use
* {@link createValidatorBuilder()} instead.
*
* @return ValidatorInterface The new validator
*/
public static function createValidator()
{
return self::createValidatorBuilder()->getValidator();
}
/**
* Creates a configurable builder for validator objects.
*
* @return ValidatorBuilderInterface The new builder
*/
public static function createValidatorBuilder()
{
return new ValidatorBuilder();
}
/**
* This class cannot be instantiated.
*/
private function __construct()
{
}
}
|
Add autoreload on settings default true | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import tornado.ioloop
import tornado.web
import tornado.autoreload
from tornado.options import parse_command_line, define, options
define('port', default=8888)
define('template_path', default='templates')
define('PROJECT_PATH', default=os.path.join(
os.path.abspath(os.path.dirname(__file__))))
settings = dict(
debug=True,
gzip=True,
autoreload=True,
template_path="{}/{}".format(options.PROJECT_PATH, options.template_path))
def main():
from urls import URLS
application = tornado.web.Application(URLS, **settings)
print "openmining.io server starting..."
def fn():
print "openmining.io before reloading..."
parse_command_line()
application.listen(options.port)
tornado.autoreload.add_reload_hook(fn)
tornado.autoreload.start()
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import tornado.ioloop
import tornado.web
import tornado.autoreload
from tornado.options import parse_command_line, define, options
define('port', default=8888)
define('template_path', default='templates')
define('PROJECT_PATH', default=os.path.join(
os.path.abspath(os.path.dirname(__file__))))
settings = dict(
debug=True,
gzip=True,
template_path="{}/{}".format(options.PROJECT_PATH, options.template_path))
def main():
from urls import URLS
application = tornado.web.Application(URLS, **settings)
print "openmining.io server starting..."
def fn():
print "openmining.io before reloading..."
parse_command_line()
application.listen(options.port)
tornado.autoreload.add_reload_hook(fn)
tornado.autoreload.start()
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
|
Format everything nicely + cleanup | /*
MessageRepeat plugin - Desigened to forward incomming messages to another server
*/
var request = require('request')
var logger = require('../log')
function run (trigger, scope, data, config, callback) {
if (config.repeatURI) {
var uri = config.repeatURI
var apikey = config.repeatAPIKEY
var messageData = {
address: data.capcode,
message: data.message,
source: data.source
}
request.post({
url: uri,
headers: {
'X-Requested-With': 'XMLHttpRequest',
"content-type": 'application/json',
'User-Agent': 'PagerMon Plugin - Message Repeat',
apikey: apikey,
json: true
},
form: messageData
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
logger.main.info('MessageRepeat: Message Sent')
} else {
logger.main.error('MessageRepeat: ' + error + response.statusCode + response.statusText)
}
})
callback()
} else {
callback()
}
}
module.exports = {
run: run
}
| /*
MessageRepeat plugin - Desigened to forward incomming messages to another server
*/
var request = require('request')
var logger = require('../log')
function run (trigger, scope, data, config, callback) {
if (config.repeatURI) {
var uri = config.repeatURI
var apikey = config.repeatAPIKEY
var messageData = {
address: data.capcode,
message: data.message,
source: data.source
}
request.post({
url: uri,
headers: {
'X-Requested-With': 'XMLHttpRequest',
"content-type": "application/json",
'User-Agent': 'PagerMon Plugin - Message Repeat',
apikey: apikey,
json: true
},
form: messageData
}, function (error, response, body) {
//if (!error && response.statusCode === 200) {
//logger.main.info('MessageRepeat: Message Sent')
//} else {
// logger.main.error('MessageRepeat: ' + error + response.statusCode + response.statusText)
//}
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
})
callback()
} else {
callback()
}
}
module.exports = {
run: run
}
|
refactor: Add service to retrieve list of team for a user | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.repository.api;
import io.gravitee.repository.model.Member;
import io.gravitee.repository.model.Team;
import io.gravitee.repository.model.TeamRole;
import java.util.Set;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface TeamMembershipRepository {
void addMember(String teamName, String username, TeamRole role);
void updateMember(String teamName, String username, TeamRole role);
void deleteMember(String teamName, String username);
Set<Member> listMembers(String teamName);
/**
* List {@link Team} where the user is a member.
*
* @param username The name used to identify a user.
* @return List of {@link Team}
*/
Set<Team> findByUser(String username);
}
| /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.repository.api;
import io.gravitee.repository.model.Member;
import io.gravitee.repository.model.Team;
import io.gravitee.repository.model.TeamRole;
import java.util.Set;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface TeamMembershipRepository {
void addMember(String teamName, String username, TeamRole role);
void updateMember(String teamName, String username, TeamRole role);
void deleteMember(String teamName, String username);
Set<Member> listMembers(String teamName);
/**
* List {@link Team} where the user is a member.
*
* @param username The name used to identify a user.
* @return List of {@link Team}
*/
Set<Team> findByUser(String username);
}
|
Use protected method getCurrentDate() instead of time() to allow override | <?php
namespace CFDIReader\PostValidations\Validators;
use CFDIReader\CFDIReader;
use CFDIReader\PostValidations\Issues;
class Fechas extends AbstractValidator
{
public function validate(CFDIReader $cfdi, Issues $issues)
{
// setup the AbstractValidator Helper class
$this->setup($cfdi, $issues);
// do the validation process
$document = strtotime($this->comprobante["fecha"]);
$timbrado = strtotime($this->comprobante->complemento->timbreFiscalDigital["fechaTimbrado"]);
if ($document > $this->getCurrentDate()) {
$this->errors->add('La fecha del documento es mayor a la fecha actual');
}
if ($document > $timbrado) {
$this->errors->add('La fecha del documento es mayor a la fecha del timbrado');
}
if ($timbrado - $document > 259200) {
$this->errors->add('La fecha fecha del timbrado excedió las 72 horas de la fecha del documento');
}
}
/**
* @return int
*/
protected function getCurrentDate()
{
return time();
}
}
| <?php
namespace CFDIReader\PostValidations\Validators;
use CFDIReader\CFDIReader;
use CFDIReader\PostValidations\Issues;
class Fechas extends AbstractValidator
{
public function validate(CFDIReader $cfdi, Issues $issues)
{
// setup the AbstractValidator Helper class
$this->setup($cfdi, $issues);
// do the validation process
$maxdate = time();
$document = strtotime($this->comprobante["fecha"]);
$comprobante = strtotime($this->comprobante->complemento->timbreFiscalDigital["fechaTimbrado"]);
if ($document > $maxdate) {
$this->errors->add('La fecha del documento es mayor a la fecha actual');
}
if ($document > $comprobante) {
$this->errors->add('La fecha del documento es mayor a la fecha del timbrado');
}
if ($comprobante - $document > 259200) {
$this->errors->add('La fecha fecha del timbrado excedió las 72 horas de la fecha del documento');
}
}
}
|
Handle when /etc/passwd is missing because the image is built using scratch or another base layer that does not provide that file. | package main
import (
"encoding/json"
"fmt"
"os"
"strings"
"syscall"
"github.com/concourse/docker-image-resource/cmd/print-metadata/passwd"
)
type imageMetadata struct {
User string `json:"user,omitempty"`
Env []string `json:"env"`
}
var blacklistedEnv = map[string]bool{
"HOSTNAME": true,
}
func main() {
username, err := username()
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to determine username, will not be included in metadata")
}
err = json.NewEncoder(os.Stdout).Encode(imageMetadata{
User: username,
Env: env(),
})
if err != nil {
panic(err)
}
}
func username() (string, error) {
users, err := passwd.ReadUsers("/etc/passwd")
if err != nil {
return "", err
}
name, found := users.NameForID(syscall.Getuid())
if !found {
return "", fmt.Errorf("could not find user in /etc/passwd")
}
return name, nil
}
func env() []string {
var envVars []string
for _, e := range os.Environ() {
parts := strings.SplitN(e, "=", 2)
name := parts[0]
if !blacklistedEnv[name] {
envVars = append(envVars, e)
}
}
return envVars
}
| package main
import (
"encoding/json"
"os"
"strings"
"syscall"
"github.com/concourse/docker-image-resource/cmd/print-metadata/passwd"
)
type imageMetadata struct {
User string `json:"user"`
Env []string `json:"env"`
}
var blacklistedEnv = map[string]bool{
"HOSTNAME": true,
}
func main() {
err := json.NewEncoder(os.Stdout).Encode(imageMetadata{
User: username(),
Env: env(),
})
if err != nil {
panic(err)
}
}
func username() string {
users, err := passwd.ReadUsers("/etc/passwd")
if err != nil {
panic(err)
}
name, found := users.NameForID(syscall.Getuid())
if !found {
panic("could not find user in /etc/passwd")
}
return name
}
func env() []string {
var envVars []string
for _, e := range os.Environ() {
parts := strings.SplitN(e, "=", 2)
name := parts[0]
if !blacklistedEnv[name] {
envVars = append(envVars, e)
}
}
return envVars
}
|
Make the web port configurable | // This is the main server file.
//
// It parses the command line and instantiates the two servers for this app:
const async = require('async')
const {cyan, dim, green, red} = require('chalk')
const ExoRelay = require('exorelay');
const N = require('nitroglycerin');
const {name, version} = require('../package.json')
const WebServer = require('./web-server')
const port = process.env.PORT || 3000
function startExorelay (done) {
global.exorelay = new ExoRelay({serviceName: process.env.SERVICE_NAME,
exocomPort: process.env.EXOCOM_PORT})
global.exorelay.on('error', (err) => { console.log(red(err)) })
global.exorelay.on('online', (port) => {
console.log(`${green('ExoRelay')} online at port ${cyan(port)}`)
done()
})
global.exorelay.listen(process.env.EXORELAY_PORT)
}
function startWebServer (done) {
const webServer = new WebServer;
webServer.on('error', (err) => { console.log(red(err)) })
webServer.on('listening', () => {
console.log(`${green('HTML server')} online at port ${cyan(webServer.port())}`)
done()
})
webServer.listen(port)
}
startExorelay( N( () => {
startWebServer( N( () => {
console.log(green('all systems go'))
}))
}))
| // This is the main server file.
//
// It parses the command line and instantiates the two servers for this app:
const async = require('async')
const {cyan, dim, green, red} = require('chalk')
const ExoRelay = require('exorelay');
const N = require('nitroglycerin');
const {name, version} = require('../package.json')
const WebServer = require('./web-server');
function startExorelay (done) {
global.exorelay = new ExoRelay({serviceName: process.env.SERVICE_NAME,
exocomPort: process.env.EXOCOM_PORT})
global.exorelay.on('error', (err) => { console.log(red(err)) })
global.exorelay.on('online', (port) => {
console.log(`${green('ExoRelay')} online at port ${cyan(port)}`)
done()
})
global.exorelay.listen(process.env.EXORELAY_PORT)
}
function startWebServer (done) {
const webServer = new WebServer;
webServer.on('error', (err) => { console.log(red(err)) })
webServer.on('listening', () => {
console.log(`${green('HTML server')} online at port ${cyan(webServer.port())}`)
done()
})
webServer.listen(3000)
}
startExorelay( N( () => {
startWebServer( N( () => {
console.log(green('all systems go'))
}))
}))
|
Use default user/password for testing | # -*- coding: utf-8 -*-
import os, sys
sys.path.insert(0, '..')
PROJECT_ROOT = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '',
}
}
MIDDLEWARE_CLASSES = [
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'en'
ADMIN_MEDIA_PREFIX = '/static/admin/'
STATICFILES_DIRS = ()
SECRET_KEY = 'di!n($kqa3)nd%ikad#kcjpkd^uw*h%*kj=*pm7$vbo6ir7h=l'
INSTALLED_APPS = (
'pg_json_fields',
)
#TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
| # -*- coding: utf-8 -*-
import os, sys
sys.path.insert(0, '..')
PROJECT_ROOT = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test',
'USER': 'test',
'PASSWORD': 'test',
'HOST': 'localhost',
'PORT': '',
}
}
MIDDLEWARE_CLASSES = [
"django.middleware.common.CommonMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'en'
ADMIN_MEDIA_PREFIX = '/static/admin/'
STATICFILES_DIRS = ()
SECRET_KEY = 'di!n($kqa3)nd%ikad#kcjpkd^uw*h%*kj=*pm7$vbo6ir7h=l'
INSTALLED_APPS = (
'pg_json_fields',
)
#TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
|
Fix isFunction failure message differences
The toString representation of functions has changed slightly between
Node 8 and Node 10. Node 10 retains the original whitespace between
the function keyword and the opening braces while Node 8 always inserts
a blank. | "use strict";
module.exports = function(referee) {
referee.add("isFunction", {
assert: function(actual) {
return typeof actual === "function";
},
assertMessage:
"${customMessage}${actual} (${actualType}) expected to be function",
refuteMessage: "${customMessage}${actual} expected not to be function",
expectation: "toBeFunction",
values: function(actual, message) {
return {
actual: String(actual)
.replace("function(", "function (")
.replace("\n", ""),
actualType: typeof actual,
customMessage: message
};
}
});
};
| "use strict";
module.exports = function(referee) {
referee.add("isFunction", {
assert: function(actual) {
return typeof actual === "function";
},
assertMessage:
"${customMessage}${actual} (${actualType}) expected to be function",
refuteMessage: "${customMessage}${actual} expected not to be function",
expectation: "toBeFunction",
values: function(actual, message) {
return {
actual: String(actual).replace("\n", ""),
actualType: typeof actual,
customMessage: message
};
}
});
};
|
Fix wrong text splitting to words | const striptags = require('striptags');
const { convertFormatToSeconds, convertSecondsToFormat, normalizeString } = require('../utils');
class SubtitlePiece {
static fromSubtitlesParserItem(item) {
return new SubtitlePiece(item);
}
constructor({ id, startTime, endTime, text, data }) {
if (!id) throw new Error();
if (!startTime) throw new Error();
if (!endTime) throw new Error();
if (!text) throw new Error();
this.id = id;
this.startTime = typeof startTime === 'number' ? convertSecondsToFormat(startTime) : startTime;
this.endTime = typeof endTime === 'number' ? convertSecondsToFormat(endTime) : endTime;
this.text = text;
this.data = data;
}
get words() {
return striptags(this.text).split(/\s+/);
}
get normalizedWords() {
return this.words.map(normalizeString).filter(word => word.length > 0);
}
get startTimeS() {
return convertFormatToSeconds(this._startTime);
}
get startTimeF() {
return this._startTime;
}
get textLevenshtein() {
return this.normalizedWords.join("");
}
}
module.exports = SubtitlePiece;
| const striptags = require('striptags');
const { convertFormatToSeconds, convertSecondsToFormat, normalizeString } = require('../utils');
class SubtitlePiece {
static fromSubtitlesParserItem(item) {
return new SubtitlePiece(item);
}
constructor({ id, startTime, endTime, text, data }) {
if (!id) throw new Error();
if (!startTime) throw new Error();
if (!endTime) throw new Error();
if (!text) throw new Error();
this.id = id;
this.startTime = typeof startTime === 'number' ? convertSecondsToFormat(startTime) : startTime;
this.endTime = typeof endTime === 'number' ? convertSecondsToFormat(endTime) : endTime;
this.text = text;
this.data = data;
}
get words() {
return striptags(this.text).split(' ');
}
get normalizedWords() {
return this.words.map(normalizeString).filter(word => word.length > 0);
}
get startTimeS() {
return convertFormatToSeconds(this._startTime);
}
get startTimeF() {
return this._startTime;
}
get textLevenshtein() {
return this.normalizedWords.join("");
}
}
module.exports = SubtitlePiece;
|
Remove space between function keyword and params | 'use strict';
// TODO: get sounds and lightprograms available from the RaspberryPi
const sounds = [
'Extreme wake up',
'Releaxed wake up',
'Crazy wake up',
'Beautiful morning',
'Cold morning'
];
const lightprograms = [
'Morning lights',
'Colorful',
'Orange morning',
'Purple morning'
];
export class AlarmCtrl {
constructor($scope) {
const self = this;
$scope.sounds = sounds;
$scope.lightprograms = lightprograms;
$scope.lightprogram = $scope.lightprograms[1];
$scope.sound = $scope.sounds[2];
$scope.tpslots = {epochTime: 30600, format: 12, step: 5};
$scope.time = self.epochToTime(30600)
$scope.timePickerCallback = function(val) {
if (typeof(val) != 'undefined') {
$scope.time = self.epochToTime(val);
}
};
}
epochToTime(epochs) {
const hours = parseInt(epochs / 3600, 10);
const minutes = (epochs / 60) % 60;
return (this.prependZero(hours) + ":" + this.prependZero(minutes));
}
prependZero(value) {
if (String(value).length < 2) {
return '0' + String(value);
}
return String(value);
}
}
AlarmCtrl.$inject = ['$scope'];
| 'use strict';
// TODO: get sounds and lightprograms available from the RaspberryPi
const sounds = [
'Extreme wake up',
'Releaxed wake up',
'Crazy wake up',
'Beautiful morning',
'Cold morning'
];
const lightprograms = [
'Morning lights',
'Colorful',
'Orange morning',
'Purple morning'
];
export class AlarmCtrl {
constructor($scope) {
const self = this;
$scope.sounds = sounds;
$scope.lightprograms = lightprograms;
$scope.lightprogram = $scope.lightprograms[1];
$scope.sound = $scope.sounds[2];
$scope.tpslots = {epochTime: 30600, format: 12, step: 5};
$scope.time = self.epochToTime(30600)
$scope.timePickerCallback = function (val) {
if (typeof(val) != 'undefined') {
$scope.time = self.epochToTime(val);
}
};
}
epochToTime(epochs) {
const hours = parseInt(epochs / 3600, 10);
const minutes = (epochs / 60) % 60;
return (this.prependZero(hours) + ":" + this.prependZero(minutes));
}
prependZero(value) {
if (String(value).length < 2) {
return '0' + String(value);
}
return String(value);
}
}
AlarmCtrl.$inject = ['$scope'];
|
Add respacing test with varying group sizes | package com.mssngvwls;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class PhaseRespacerTests {
@Mock
private RandomNumberGenerator randomNumberGenerator;
@InjectMocks
private PhraseRespacer phraseRespacer;
@Test
public void phrase_is_respaced_with_equal_spacings() {
final String input = "Manchester United";
when(randomNumberGenerator.between(1, 4)).thenReturn(1);
final String expectedOutput = "M a n c h e s t e r U n i t e d";
final String actualOutput = phraseRespacer.respace(input);
assertThat(actualOutput).isEqualTo(expectedOutput);
}
@Test
public void phrase_is_respaced_with_different_spacings() {
final String input = "Manchester United";
when(randomNumberGenerator.between(1, 4)).thenReturn(3, 2, 4, 3, 1, 3);
final String expectedOutput = "Man ch este rUn i ted";
final String actualOutput = phraseRespacer.respace(input);
assertThat(actualOutput).isEqualTo(expectedOutput);
}
}
| package com.mssngvwls;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class PhaseRespacerTests {
@Mock
private RandomNumberGenerator randomNumberGenerator;
@InjectMocks
private PhraseRespacer phraseRespacer;
@Test
public void phrase_is_respaced() {
final String input = "Manchester United";
when(randomNumberGenerator.between(1, 4)).thenReturn(1);
final String expectedOutput = "M a n c h e s t e r U n i t e d";
final String actualOutput = phraseRespacer.respace(input);
assertThat(actualOutput).isEqualTo(expectedOutput);
}
}
|
Disable CJS→ES interop in CommonJS build. | import buble from 'rollup-plugin-buble'
import inject from 'rollup-plugin-inject'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import builtins from 'builtin-modules'
const pkg = require('./package.json')
export default {
input: 'src/index.js',
output: [
{ format: 'cjs', file: pkg.main, sourcemap: true, exports: 'default', interop: false },
{ format: 'es', file: pkg.module, sourcemap: true }
],
external: builtins.concat(Object.keys(pkg.dependencies)),
plugins: [
buble({
include: 'src/**',
target: {
node: 4
}
}),
resolve({
module: true,
jsnext: true,
main: true,
browser: false,
preferBuiltins: true
}),
commonjs(),
inject({
include: 'src/**',
Promise: 'bluebirdish'
})
]
}
| import buble from 'rollup-plugin-buble'
import inject from 'rollup-plugin-inject'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import builtins from 'builtin-modules'
const pkg = require('./package.json')
export default {
input: 'src/index.js',
output: [
{ format: 'cjs', file: pkg.main, sourcemap: true, exports: 'default' },
{ format: 'es', file: pkg.module, sourcemap: true }
],
external: builtins.concat(Object.keys(pkg.dependencies)),
plugins: [
buble({
include: 'src/**',
target: {
node: 4
}
}),
resolve({
module: true,
jsnext: true,
main: true,
browser: false,
preferBuiltins: true
}),
commonjs(),
inject({
include: 'src/**',
Promise: 'bluebirdish'
})
]
}
|
Load the config as late as possible to avoid crashing when the configuration is not ready yet. Also this code is more reentrant | # Copyright (C) 2011 Yaco Sistemas (http://www.yaco.es)
#
# 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 django import template
from djangosaml2.conf import config_settings_loader
register = template.Library()
class IdPListNode(template.Node):
def __init__(self, variable_name):
self.variable_name = variable_name
def render(self, context):
conf = config_settings_loader()
context[self.variable_name] = conf.get_available_idps()
return ''
@register.tag
def idplist(parser, token):
try:
tag_name, as_part, variable = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
'%r tag requires two arguments' % token.contents.split()[0])
if not as_part == 'as':
raise template.TemplateSyntaxError(
'%r tag first argument must be the literal "as"' % tag_name)
return IdPListNode(variable)
| # Copyright (C) 2011 Yaco Sistemas (http://www.yaco.es)
#
# 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 django import template
from djangosaml2.conf import config_settings_loader
register = template.Library()
class IdPListNode(template.Node):
def __init__(self, variable_name):
self.variable_name = variable_name
self.conf = config_settings_loader()
def render(self, context):
context[self.variable_name] = self.conf.get_available_idps()
return ''
@register.tag
def idplist(parser, token):
try:
tag_name, as_part, variable = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
'%r tag requires two arguments' % token.contents.split()[0])
if not as_part == 'as':
raise template.TemplateSyntaxError(
'%r tag first argument must be the literal "as"' % tag_name)
return IdPListNode(variable)
|
Fix middleware if cookie does not exist. | <?php namespace Flarum\Forum\Middleware;
use Flarum\Support\Actor;
use Flarum\Core\Models\AccessToken;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Stratigility\MiddlewareInterface;
class LoginWithCookie implements MiddlewareInterface
{
/**
* @var Actor
*/
protected $actor;
public function __construct(Actor $actor)
{
$this->actor = $actor;
}
/**
* {@inheritdoc}
*/
public function __invoke(Request $request, Response $response, callable $out = null)
{
if (($token = array_get($request->getCookieParams(), 'flarum_remember')) &&
($accessToken = AccessToken::where('id', $token)->first())
) {
$this->actor->setUser($user = $accessToken->user);
$user->updateLastSeen()->save();
}
return $out ? $out($request, $response) : $response;
}
}
| <?php namespace Flarum\Forum\Middleware;
use Flarum\Support\Actor;
use Flarum\Core\Models\AccessToken;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Stratigility\MiddlewareInterface;
class LoginWithCookie implements MiddlewareInterface
{
/**
* @var Actor
*/
protected $actor;
public function __construct(Actor $actor)
{
$this->actor = $actor;
}
/**
* {@inheritdoc}
*/
public function __invoke(Request $request, Response $response, callable $out = null)
{
$cookies = $request->getCookieParams();
if (($token = $cookies['flarum_remember']) &&
($accessToken = AccessToken::where('id', $token)->first())
) {
$this->actor->setUser($user = $accessToken->user);
$user->updateLastSeen()->save();
}
return $out ? $out($request, $response) : $response;
}
}
|
Fix ensures DatasetResource.sanitizeDataset method won't remove HTML line break added during metadata parsing | package org.gbif.registry.metadata.parse;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
/**
* Class to temporarily keep paragraph strings before they are used as a single,
* concatenated string argument in other rules.
* Digester needs public access to this otherwise package scoped class.
* </br>
* Note HTML is used to concatenate paragraphs using break tag <br> instead of newline character ("\n"), see POR-3138.
* @see <a href="http://dev.gbif.org/issues/browse/POR-3138">POR-3138</a>
*/
public class ParagraphContainer {
private static Joiner PARA_JOIN = Joiner.on("<br />");
private List<String> paragraphs = Lists.newArrayList();
public void appendParagraph(String para) {
if (!Strings.isNullOrEmpty(para)) {
paragraphs.add(para.trim());
}
}
public String toString() {
if (paragraphs.isEmpty()) {
return null;
}
return PARA_JOIN.join(paragraphs);
}
} | package org.gbif.registry.metadata.parse;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
/**
* Class to temporarily keep paragraph strings before they are used as a single,
* concatenated string argument in other rules.
* Digester needs public access to this otherwise package scoped class.
* </br>
* Note HTML is used to concatenate paragraphs using break tag </br> instead of newline character ("\n"), see POR-3138.
* @see <a href="http://dev.gbif.org/issues/browse/POR-3138">POR-3138</a>
*/
public class ParagraphContainer {
private static Joiner PARA_JOIN = Joiner.on("</br>");
private List<String> paragraphs = Lists.newArrayList();
public void appendParagraph(String para) {
if (!Strings.isNullOrEmpty(para)) {
paragraphs.add(para.trim());
}
}
public String toString() {
if (paragraphs.isEmpty()) {
return null;
}
return PARA_JOIN.join(paragraphs);
}
} |
Fix missing numpy import in ucr test | """
Script for performing queries on large time series by using UCR ED and DTW algs.
"""
from time import time
import blaze
from blaze.ts.ucr_dtw import ucr
import numpy as np
# Convert txt file into Blaze native format
def convert(filetxt, storage):
import os.path
if not os.path.exists(storage):
blaze.Array(np.loadtxt(filetxt),
params=blaze.params(storage=storage))
# Make sure that data is converted into a persistent Blaze array
convert("Data.txt", "Data")
convert("Query.txt", "Query")
convert("Query2.txt", "Query2")
t0 = time()
# Open Blaze arrays on-disk (will not be loaded in memory)
data = blaze.open("Data")
query = blaze.open("Query")
query2 = blaze.open("Query2")
print "Total Blaze arrays open time :", round(time()-t0, 4)
t0 = time()
# Do different searches using ED/DTW with native Blaze arrays
#loc, dist = ucr.ed(data, query, 128)
loc, dist = ucr.dtw(data, query, 0.1, 128, verbose=False)
#loc, dist = ucr.dtw(data, query2, 0.1, 128)
print "Location : ", loc
print "Distance : ", dist
print "Data Scanned : ", data.size
print "Total Execution Time :", round(time()-t0, 4)
| """
Script for performing queries on large time series by using UCR ED and DTW algs.
"""
from time import time
import blaze
from blaze.ts.ucr_dtw import ucr
# Convert txt file into Blaze native format
def convert(filetxt, storage):
import os.path
if not os.path.exists(storage):
blaze.Array(np.loadtxt(filetxt),
params=blaze.params(storage=storage))
# Make sure that data is converted into a persistent Blaze array
convert("Data.txt", "Data")
convert("Query.txt", "Query")
convert("Query2.txt", "Query2")
t0 = time()
# Open Blaze arrays on-disk (will not be loaded in memory)
data = blaze.open("Data")
query = blaze.open("Query")
query2 = blaze.open("Query2")
print "Total Blaze arrays open time :", round(time()-t0, 4)
t0 = time()
# Do different searches using ED/DTW with native Blaze arrays
#loc, dist = ucr.ed(data, query, 128)
loc, dist = ucr.dtw(data, query, 0.1, 128, verbose=False)
#loc, dist = ucr.dtw(data, query2, 0.1, 128)
print "Location : ", loc
print "Distance : ", dist
print "Data Scanned : ", data.size
print "Total Execution Time :", round(time()-t0, 4)
|
Use helmet on graphql server | import express from 'express'
import graphQLHTTP from 'express-graphql'
import { maskErrors } from 'graphql-errors'
import cors from 'cors'
import helmet from 'helmet'
import cookieParser from 'cookie-parser'
import dotenv from 'dotenv'
import debug from 'debug'
import sessionMiddleware from './sessionMiddleware'
import Schema from './schema'
import intlMiddleware from './intlMiddleware'
import Database from './data/Database'
dotenv.config()
const log = debug('graphql')
const PORT = process.env.PORT_GRAPHQL
const app = express()
const corsOptions = {
origin: process.env.APP_ENDPOINT,
methods: ['POST'],
allowedHeaders: ['X-Requested-With', 'content-type'],
credentials: true,
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(helmet())
app.use(cors(corsOptions))
app.use(cookieParser())
app.use(intlMiddleware)
app.use(sessionMiddleware)
maskErrors(Schema)
app.use('/', graphQLHTTP(({ session, tokenData }, res) => ({
graphiql: true,
pretty: true,
schema: Schema,
context: { db: new Database() },
rootValue: { session, tokenData, res },
})))
app.listen(PORT, () =>
log(`GraphQL Server is now running on http://localhost:${PORT}`),
)
| import express from 'express'
import graphQLHTTP from 'express-graphql'
import { maskErrors } from 'graphql-errors'
import cors from 'cors'
import cookieParser from 'cookie-parser'
import dotenv from 'dotenv'
import debug from 'debug'
import sessionMiddleware from './sessionMiddleware'
import Schema from './schema'
import intlMiddleware from './intlMiddleware'
import Database from './data/Database'
dotenv.config()
const log = debug('graphql')
const PORT = process.env.PORT_GRAPHQL
const app = express()
const corsOptions = {
origin: process.env.APP_ENDPOINT,
methods: ['POST'],
allowedHeaders: ['X-Requested-With', 'content-type'],
credentials: true,
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(cors(corsOptions))
app.use(cookieParser())
app.use(intlMiddleware)
app.use(sessionMiddleware)
maskErrors(Schema)
app.use('/', graphQLHTTP(({ session, tokenData }, res) => ({
graphiql: true,
pretty: true,
schema: Schema,
context: { db: new Database() },
rootValue: { session, tokenData, res },
})))
app.listen(PORT, () =>
log(`GraphQL Server is now running on http://localhost:${PORT}`),
)
|
Allow both string and number for the radio button value | import React from 'react';
import PropTypes from 'prop-types';
import Control from './Control';
import controlActions from '../actions/controls';
import {connect} from '../store';
import {getValue, hasError} from '../store/reducers';
class RadioButton extends Control {
static propTypes = {
className: PropTypes.string,
id: PropTypes.string,
model: PropTypes.string.isRequired,
style: PropTypes.string,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]).isRequired,
checked: PropTypes.string,
};
componentDidMount() {}
componentDidUpdate() {}
render() {
const {id, value, style, checked} = this.props;
return (
<input
type="radio"
id={id}
className={this.getClassName()}
style={style}
value={value}
checked={checked === value}
onChange={e => this.onChange(e.target.value)}
/>
);
}
}
const mapStateToProps = (state, props) => ({
checked: getValue(state, props.model),
hasError: hasError(state, props.model),
});
const mapDispatchToProps = {
setErrors: controlActions.setErrors,
setValue: controlActions.setValue,
};
export default connect(mapStateToProps, mapDispatchToProps)(RadioButton);
| import React from 'react';
import PropTypes from 'prop-types';
import Control from './Control';
import controlActions from '../actions/controls';
import {connect} from '../store';
import {getValue, hasError} from '../store/reducers';
class RadioButton extends Control {
static propTypes = {
className: PropTypes.string,
id: PropTypes.string,
model: PropTypes.string.isRequired,
style: PropTypes.string,
value: PropTypes.string.isRequired,
checked: PropTypes.string,
};
componentDidMount() {}
componentDidUpdate() {}
render() {
const {id, value, style, checked} = this.props;
return (
<input
type="radio"
id={id}
className={this.getClassName()}
style={style}
value={value}
checked={checked === value}
onChange={e => this.onChange(e.target.value)}
/>
);
}
}
const mapStateToProps = (state, props) => ({
checked: getValue(state, props.model),
hasError: hasError(state, props.model),
});
const mapDispatchToProps = {
setErrors: controlActions.setErrors,
setValue: controlActions.setValue,
};
export default connect(mapStateToProps, mapDispatchToProps)(RadioButton);
|
Change imports in dataone test and add test for resource map parsing | """test_dataone.py
Test the DataOne utility library.
"""
from d1lod import dataone
def test_parsing_resource_map():
pid = 'resourceMap_df35d.3.2'
aggd_pids = dataone.getAggregatedIdentifiers(pid)
assert len(aggd_pids) == 7
def test_extracting_identifiers_from_urls():
# Returns None when it should
assert dataone.extractIdentifierFromFullURL('asdf') is None
assert dataone.extractIdentifierFromFullURL(1) is None
assert dataone.extractIdentifierFromFullURL('1') is None
assert dataone.extractIdentifierFromFullURL('http://google.com') is None
# Extracts the right thing
assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/meta/some_pid') == 'some_pid'
assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/meta/kgordon.23.30') == 'kgordon.23.30'
assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/resolve/kgordon.23.30') == 'kgordon.23.30'
assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v1/object/kgordon.23.30') == 'kgordon.23.30'
assert dataone.extractIdentifierFromFullURL('https://cn.dataone.org/cn/v2/object/kgordon.23.30') == 'kgordon.23.30'
| """test_dataone.py
Test the DataOne utility library.
"""
from d1lod.dataone import extractIdentifierFromFullURL as extract
def test_extracting_identifiers_from_urls():
# Returns None when it should
assert extract('asdf') is None
assert extract(1) is None
assert extract('1') is None
assert extract('http://google.com') is None
# Extracts the right thing
assert extract('https://cn.dataone.org/cn/v1/meta/some_pid') == 'some_pid'
assert extract('https://cn.dataone.org/cn/v1/meta/kgordon.23.30') == 'kgordon.23.30'
assert extract('https://cn.dataone.org/cn/v1/resolve/kgordon.23.30') == 'kgordon.23.30'
assert extract('https://cn.dataone.org/cn/v1/object/kgordon.23.30') == 'kgordon.23.30'
assert extract('https://cn.dataone.org/cn/v2/object/kgordon.23.30') == 'kgordon.23.30'
|
Add configuration for victoire menu item | <?php
namespace Victoire\Widget\PollBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('victoire_widget_poll');
$rootNode
->children()
->booleanNode('victoire_menu_item')
->defaultFalse()
->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace Victoire\Widget\PollBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('victoire_widget_poll');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
|
Fix course mode settings import
Without this, we were pulling edx's default (audit) from common,
instead of pulling "ours" from aws/json (honor). | from cms.envs.aws import *
from lms.envs.aws import COURSE_MODE_DEFAULTS
CMS_BASE = ENV_TOKENS.get(
'CMS_BASE',
)
COPYRIGHT_EMAIL = ENV_TOKENS.get(
'COPYRIGHT_EMAIL',
COPYRIGHT_EMAIL
)
DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get(
'DEFAULT_COURSE_ABOUT_IMAGE_URL',
DEFAULT_COURSE_ABOUT_IMAGE_URL
)
EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES)
SHIB_ONLY_SITE = ENV_TOKENS.get(
'SHIB_ONLY_SITE',
SHIB_ONLY_SITE
)
SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get(
'SHIB_REDIRECT_DOMAIN_WHITELIST',
SHIB_REDIRECT_DOMAIN_WHITELIST
)
XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get(
'XBLOCKS_ALWAYS_IN_STUDIO',
XBLOCKS_ALWAYS_IN_STUDIO
)
INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get(
'INSTRUCTOR_QUERY_PROBLEM_TYPES',
INSTRUCTOR_QUERY_PROBLEM_TYPES
)
| from cms.envs.aws import *
from lms.envs.common import COURSE_MODE_DEFAULTS
CMS_BASE = ENV_TOKENS.get(
'CMS_BASE',
)
COPYRIGHT_EMAIL = ENV_TOKENS.get(
'COPYRIGHT_EMAIL',
COPYRIGHT_EMAIL
)
DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get(
'DEFAULT_COURSE_ABOUT_IMAGE_URL',
DEFAULT_COURSE_ABOUT_IMAGE_URL
)
EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES)
SHIB_ONLY_SITE = ENV_TOKENS.get(
'SHIB_ONLY_SITE',
SHIB_ONLY_SITE
)
SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get(
'SHIB_REDIRECT_DOMAIN_WHITELIST',
SHIB_REDIRECT_DOMAIN_WHITELIST
)
XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get(
'XBLOCKS_ALWAYS_IN_STUDIO',
XBLOCKS_ALWAYS_IN_STUDIO
)
INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get(
'INSTRUCTOR_QUERY_PROBLEM_TYPES',
INSTRUCTOR_QUERY_PROBLEM_TYPES
)
|
Fix MIT classification for pypi | #!/usr/bin/env python
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
setup(name='djeasyroute',
version='0.0.1',
description='A simple class based route system for django similar to flask',
author='Ryan Goggin',
author_email='info@ryangoggin.net',
url='https://github.com/Goggin/djeasyroute',
download_url='',
classifiers=[
"Development Status :: 3 - Alpha",
"Framework :: Django",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Intended Audience :: Developers",
"Topic :: Software Development",
],
install_requires=[
'django',
],
packages=[
'djeasyroute',
],
)
| #!/usr/bin/env python
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
setup(name='djeasyroute',
version='0.0.1',
description='A simple class based route system for django similar to flask',
author='Ryan Goggin',
author_email='info@ryangoggin.net',
url='https://github.com/Goggin/djeasyroute',
download_url='',
classifiers=[
"Development Status :: 3 - Alpha",
"Framework :: Django",
"License :: OSI Approved :: MIT",
"Operating System :: OS Independent",
"Intended Audience :: Developers",
"Topic :: Software Development",
],
install_requires=[
'django',
],
packages=[
'djeasyroute',
],
)
|
Fix spelling of parameter name. | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.clustering.group;
/**
* Listener for {@link Group} membership changes.
* @author Paul Ferraro
*/
public interface GroupListener {
/**
* Indicates that the membership of the group has changed.
*
* @param previousMembership previous group membership
* @param membership new group membership
* @param merged indicates whether the membership change is the result of a merge view
*/
void membershipChanged(Membership previousMembership, Membership membership, boolean merged);
}
| /*
* JBoss, Home of Professional Open Source.
* Copyright 2017, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.clustering.group;
/**
* Listener for {@link Group} membership changes.
* @author Paul Ferraro
*/
public interface GroupListener {
/**
* Indicates that the membership of the group has changed.
*
* @param previousMembership previous group membership
* @param membership new group membership
* @param merged indicates whether the membership change is the result of a merge view
*/
void membershipChanged(Membership previousMembership, Membership membersip, boolean merged);
}
|
Send a read-reciept to the API
ACK, ACK! | import Ember from 'ember';
import ENV from '../config/environment';
import { Bindings } from 'ember-pusher/bindings';
// used by the Application controller
export default Ember.Mixin.create(Bindings, {
logPusherEvents: (ENV.environment === "development"),
PUSHER_SUBSCRIPTIONS: {
activities: ["push"]
},
userChannel: function() {
console.log(this.get("session.username"));
}.property("session.username"),
subscribeToMyChannel: function() {
var channelName = this.get("username") + '_channel';
this.pusher.wire(this, channelName, ['notify']);
}.observes("userChannel"),
init: function() {
this._super();
this.subscribeToMyChannel();
},
actions: {
push: function(data) {
this.store.pushPayload('activity', data);
},
notify: function(data) {
this.store.pushPayload('notification', data);
var activity = data.activities[0];
Ember.$.post(ENV.api + "/notifications/" + data.notification.id + "/ack")
switch (activity.type) {
case "ProposalComment":
this.flash.notice("Someone just commented on your proposal for " + activity.wordId);
break;
case "ProposalClosed":
this.flash.notice("Your proposal for " + activity.wordId + " was " + activity.finalState);
break;
}
}
},
});
| import Ember from 'ember';
import ENV from '../config/environment';
import { Bindings } from 'ember-pusher/bindings';
// used by the Application controller
export default Ember.Mixin.create(Bindings, {
logPusherEvents: (ENV.environment === "development"),
PUSHER_SUBSCRIPTIONS: {
activities: ["push"]
},
userChannel: function() {
console.log(this.get("session.username"));
}.property("session.username"),
subscribeToMyChannel: function() {
var channelName = this.get("username") + '_channel';
this.pusher.wire(this, channelName, ['notify']);
}.observes("userChannel"),
init: function() {
this._super();
this.subscribeToMyChannel();
},
actions: {
push: function(data) {
this.store.pushPayload('activity', data);
},
notify: function(data) {
this.store.pushPayload('notification', data);
var activity = data.activities[0];
switch (activity.type) {
case "ProposalComment":
this.flash.notice("Someone just commented on your proposal for " + activity.wordId);
break;
case "ProposalClosed":
this.flash.notice("Your proposal for " + activity.wordId + " was " + activity.finalState);
break;
}
}
},
});
|
Update cello to use Orchestra\Model\Role::admin()
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
class Cello_Seed_Acl {
/**
* Start Orchestra during construct
*
* @return void
*/
public function __construct()
{
Bundle::start('orchestra');
if (false === Orchestra\Installer::installed())
{
throw new RuntimeException("Orchestra need to be install first.");
}
}
/**
* Make changes to the database.
*
* @return void
*/
public function up()
{
$role = Orchestra\Model\Role::admin();
$cello = Orchestra\Acl::register('cello', function($acl) use ($role)
{
$acl->add_action('manage pages');
$acl->add_role($role->name);
$acl->allow($role->name, 'manage pages');
});
$cello->attach(Orchestra::memory());
return true;
}
/**
* Revert the changes to the database.
*
* @return void
*/
public function down()
{
}
}
| <?php
class Cello_Seed_Acl {
/**
* Start Orchestra during construct
*
* @return void
*/
public function __construct()
{
Bundle::start('orchestra');
if (false === Orchestra\Installer::installed())
{
throw new RuntimeException("Orchestra need to be install first.");
}
}
/**
* Make changes to the database.
*
* @return void
*/
public function up()
{
$role = Orchestra\Model\Role::find(
Config::get('orchestra::orchestra.default_role', 1)
);
$cello = Orchestra\Acl::register('cello', function($acl) use ($role)
{
$acl->add_action('manage pages');
$acl->add_role($role->name);
$acl->allow($role->name, 'manage pages');
});
$cello->attach(Orchestra::memory());
return true;
}
/**
* Revert the changes to the database.
*
* @return void
*/
public function down()
{
}
}
|
Remove unused dependencies and updates used dependencies | Package.describe({
name: 'sanjo:karma',
summary: 'Integrates Karma into Meteor',
version: '1.6.1',
git: 'https://github.com/Sanjo/meteor-karma.git'
})
Npm.depends({
'karma': '0.13.3',
'karma-chrome-launcher': '0.2.0',
'karma-firefox-launcher': '0.1.6',
'karma-jasmine': '0.3.6',
'karma-babel-preprocessor': '5.2.1',
'karma-coffee-preprocessor': '0.3.0',
'karma-phantomjs-launcher': '0.2.0',
'karma-sauce-launcher': '0.2.14',
'fs-extra': '0.22.1'
})
Package.onUse(function (api) {
api.versionsFrom('1.1.0.2')
api.use('practicalmeteor:loglevel@1.1.0_3', 'server')
api.use('sanjo:meteor-files-helpers@1.1.0_6', 'server')
api.use('sanjo:long-running-child-process@1.1.1', 'server')
api.addFiles('main.js', 'server')
api.export('Karma')
api.export('KarmaInternals')
})
| Package.describe({
name: 'sanjo:karma',
summary: 'Integrates Karma into Meteor',
version: '1.6.1',
git: 'https://github.com/Sanjo/meteor-karma.git'
})
Npm.depends({
'karma': '0.13.3',
'karma-chrome-launcher': '0.2.0',
'karma-firefox-launcher': '0.1.6',
'karma-jasmine': '0.3.6',
'karma-babel-preprocessor': '5.2.1',
'karma-coffee-preprocessor': '0.3.0',
'karma-phantomjs-launcher': '0.2.0',
'karma-sauce-launcher': '0.2.14',
'fs-extra': '0.22.1'
})
Package.onUse(function (api) {
api.versionsFrom('1.0.3.2')
api.use('coffeescript', 'server')
api.use('underscore', 'server')
api.use('check', 'server')
api.use('practicalmeteor:loglevel@1.1.0_2', 'server')
api.use('sanjo:meteor-files-helpers@1.1.0_2', 'server')
api.use('sanjo:long-running-child-process@1.0.2', 'server')
api.addFiles('main.js', 'server')
api.export('Karma')
api.export('KarmaInternals')
})
|
Remove shortcut for about dialog | define([
"text!src/welcome.md"
], function(welcomeMessage) {
var commands = codebox.require("core/commands");
var dialogs = codebox.require("utils/dialogs");
var File = codebox.require("models/file");
// About dialog
commands.register({
id: "about.show",
title: "Application: About",
run: function() {
return dialogs.alert("About Codebox");
}
});
// Welcome message
commands.register({
id: "about.welcome",
title: "Application: Welcome",
run: function() {
return commands.run("file.open", {
file: File.buffer("welcome.md", welcomeMessage)
})
}
});
});a | define([
"text!src/welcome.md"
], function(welcomeMessage) {
var commands = codebox.require("core/commands");
var dialogs = codebox.require("utils/dialogs");
var File = codebox.require("models/file");
// About dialog
commands.register({
id: "about.show",
title: "Application: About",
shortcuts: [
"mod+shift+a"
],
run: function() {
return dialogs.alert("About Codebox");
}
});
// Welcome message
commands.register({
id: "about.welcome",
title: "Application: Welcome",
run: function() {
return commands.run("file.open", {
file: File.buffer("welcome.md", welcomeMessage)
})
}
});
});a |
Define a path to the image folder for fake beps generator
Path is defined in beps_gen_utils
Users can still provide their own images if they want. |
import numpy as np
import os
beps_image_folder = os.path.abspath(os.path.join(os.path.realpath(__file__), '../beps_data_gen_images'))
def combine_in_out_field_loops(in_vec, out_vec):
"""
Parameters
----------
in_vec
out_vec
Returns
-------
"""
return np.vstack((in_vec, out_vec))
def build_loop_from_mat(loop_mat, num_steps):
"""
Parameters
----------
loop_mat
num_steps
Returns
-------
"""
return np.vstack((loop_mat[0, :int(num_steps / 4) + 1],
loop_mat[1],
loop_mat[0, int(num_steps / 4) + 1: int(num_steps / 2)]))
def get_noise_vec(num_pts, noise_coeff):
"""
Parameters
----------
num_pts
noise_coeff
Returns
-------
"""
return np.ones(num_pts) * (1 + 0.5 * noise_coeff) - np.random.random(num_pts) * noise_coeff
|
import numpy as np
def combine_in_out_field_loops(in_vec, out_vec):
"""
Parameters
----------
in_vec
out_vec
Returns
-------
"""
return np.vstack((in_vec, out_vec))
def build_loop_from_mat(loop_mat, num_steps):
"""
Parameters
----------
loop_mat
num_steps
Returns
-------
"""
return np.vstack((loop_mat[0, :int(num_steps / 4) + 1],
loop_mat[1],
loop_mat[0, int(num_steps / 4) + 1: int(num_steps / 2)]))
def get_noise_vec(num_pts, noise_coeff):
"""
Parameters
----------
num_pts
noise_coeff
Returns
-------
"""
return np.ones(num_pts) * (1 + 0.5 * noise_coeff) - np.random.random(num_pts) * noise_coeff
|
Fix canvas chart test missing colors | import expect from 'expect';
import I from 'immutable';
import {Note} from '../../../../../reducers/chart';
import {NOTE_HEIGHT} from '../../constants';
import {playerColors} from '../../../../../config/constants';
import {
WIDTH,
HEIGHT,
renderNotes,
} from '../';
class MockContext {
constructor() {
this.canvas = {
width: WIDTH,
height: HEIGHT,
};
this.fillRect = expect.createSpy();
this.strokeRect = expect.createSpy();
}
}
describe('<CanvasChart>', () => {
it('renders notes on the judgement line when the scroll offset matches the note offset', () => {
const offsetPositionYPercent = 0.9;
const offset = 20 * 24 + 12;
const note = new Note({
col: 0,
totalOffset: offset,
});
const ctx = new MockContext();
const offsetBarY = (1 - offsetPositionYPercent) * HEIGHT;
renderNotes(ctx, {
colors: playerColors,
notes: I.Set([note]),
beatSpacing: 160,
offset,
offsetBarY,
});
expect(ctx.fillRect.calls.length).toEqual(1);
expect(ctx.fillRect.calls[0].arguments[1]).toEqual(offsetBarY - (NOTE_HEIGHT / 2));
});
});
| import expect from 'expect';
import I from 'immutable';
import {Note} from '../../../../../reducers/chart';
import {NOTE_HEIGHT} from '../..//constants';
import {
WIDTH,
HEIGHT,
renderNotes,
} from '../';
class MockContext {
constructor() {
this.canvas = {
width: WIDTH,
height: HEIGHT,
};
this.fillRect = expect.createSpy();
this.strokeRect = expect.createSpy();
}
}
describe('<CanvasChart>', () => {
it('renders notes on the judgement line when the scroll offset matches the note offset', () => {
const offsetPositionYPercent = 0.9;
const offset = 20 * 24 + 12;
const note = new Note({
col: 0,
totalOffset: offset,
});
const ctx = new MockContext();
const offsetBarY = (1 - offsetPositionYPercent) * HEIGHT;
renderNotes(ctx, {
notes: I.Set([note]),
beatSpacing: 160,
offset,
offsetBarY,
});
expect(ctx.fillRect.calls.length).toEqual(1);
expect(ctx.fillRect.calls[0].arguments[1]).toEqual(offsetBarY - (NOTE_HEIGHT / 2));
});
});
|
Add new failed status for items that can't be fetched. | <?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Items extends Model {
const STATUS_NEW = 'new';
const STATUS_BEING_FETCHED = 'being_fetched';
const STATUS_FETCHED = 'fetched';
const STATUS_BEING_CONVERTED = 'being_converted';
const STATUS_CONVERTED = 'converted';
const STATUS_BEING_UPLOADED = 'being_uploaded';
const STATUS_UPLOADED = 'uploaded';
const STATUS_FETCH_FAILED = 'fetch_failed';
const STATUS_CONVERSION_FAILED = 'conversion_failed';
public $incrementing = false;
public $timestamps = false;
public static $validation = [
'url' => 'required|url|unique:items|unique:user_items'
];
//
}
| <?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Items extends Model {
const STATUS_NEW = 'new';
const STATUS_BEING_FETCHED = 'being_fetched';
const STATUS_FETCHED = 'fetched';
const STATUS_BEING_CONVERTED = 'being_converted';
const STATUS_CONVERTED = 'converted';
const STATUS_CONVERSION_FAILED = 'conversion_failed';
const STATUS_BEING_UPLOADED = 'being_uploaded';
const STATUS_UPLOADED = 'uploaded';
public $incrementing = false;
public $timestamps = false;
public static $validation = [
'url' => 'required|url|unique:items|unique:user_items'
];
//
}
|
Replace isFunction check with more open isCallable | 'use strict';
var slice = Array.prototype.slice
, isCallable = require('es5-ext/lib/Object/is-callable')
, silent = require('es5-ext/lib/Function/prototype/silent');
require('../../extend')('invoke', null, function (args, resolve) {
var fn;
if (this.failed) {
resolve(this.promise);
return;
}
fn = args[0];
args = slice.call(args, 1);
if (!isCallable(fn)) {
if (!isCallable(this.value[fn])) {
resolve(new Error("Cannot invoke '" + fn +
"' on given result. It's not a function."));
return;
}
fn = this.value[fn];
}
resolve(silent.apply(fn.bind(this.value), args));
});
module.exports = require('../../deferred');
| 'use strict';
var slice = Array.prototype.slice
, isFunction = require('es5-ext/lib/Function/is-function')
, silent = require('es5-ext/lib/Function/prototype/silent');
require('../../extend')('invoke', null, function (args, resolve) {
var fn;
if (this.failed) {
resolve(this.promise);
return;
}
fn = args[0];
args = slice.call(args, 1);
if (!isFunction(fn)) {
if (!isFunction(this.value[fn])) {
resolve(new Error("Cannot invoke '" + fn +
"' on given result. It's not a function."));
return;
}
fn = this.value[fn];
}
resolve(silent.apply(fn.bind(this.value), args));
});
module.exports = require('../../deferred');
|
Revert afterInstall -> beforeInstall change. afterInstall is fine. | var path = require('path');
module.exports = {
description: 'Initialize files needed for typescript compilation',
files: function() {
return [
path.join(this.path, 'files', 'tsconfig.json'),
path.join(this.path, 'files', 'app', 'config', 'environment.d.ts')
];
},
mapFile: function() {
var result = this._super.mapFile.apply(this, arguments);
if (result.indexOf('/tsconfig.json')>-1) {
return 'tsconfig.json';
} else if (result.indexOf('/app/')>-1) {
var pos = result.indexOf('/app/');
return result.substring(pos+1);
}
},
normalizeEntityName: function() {
// Entity name is optional right now, creating this hook avoids an error.
},
afterInstall: function() {
return this.addPackagesToProject([
{ name: 'typescript', target: '^2.1' },
{ name: '@types/ember', target: '^2.7.34' }
]);
}
}
| var path = require('path');
module.exports = {
description: 'Initialize files needed for typescript compilation',
files: function() {
return [
path.join(this.path, 'files', 'tsconfig.json'),
path.join(this.path, 'files', 'app', 'config', 'environment.d.ts')
];
},
mapFile: function() {
var result = this._super.mapFile.apply(this, arguments);
if (result.indexOf('/tsconfig.json')>-1) {
return 'tsconfig.json';
} else if (result.indexOf('/app/')>-1) {
var pos = result.indexOf('/app/');
return result.substring(pos+1);
}
},
normalizeEntityName: function() {
// Entity name is optional right now, creating this hook avoids an error.
},
beforeInstall: function() {
return this.addPackagesToProject([
{ name: 'typescript', target: '^2.1' },
{ name: '@types/ember', target: '^2.7.34' }
]);
}
}
|
Add the ability to use wildcard in white/black lists | /**
* Creates an array from list using \n as delimiter
* and checks if any element in list is contained in the url.
*
* @param url
* @param list
* @returns {boolean}
*/
function contains(url, list) {
var lines = list.split('\n');
for (var i = 0; i < lines.length; i ++) {
// Trim all lines from the list one by one
var cleanLine = lines[i].trim();
// If by any chance one line in the list is empty, ignore it
if(cleanLine === '') continue;
var lineRe = new RegExp(cleanLine.replace('.', '\.').replace('*', '.*'));
// If url matches the current line return true
if (lineRe.test(url)) {
return true;
}
}
return false;
}
module.exports = contains;
| /**
* Creates an array from list using \n as delimiter
* and checks if any element in list is contained in the url.
*
* @param url
* @param list
* @returns {boolean}
*/
function contains(url, list) {
var lines = list.split('\n');
for (var i = 0; i < lines.length; i ++) {
// Trim all lines from the list one by one
var cleanLine = lines[i].trim();
// If by any chance one line in the list is empty, ignore it
if(cleanLine === '') continue;
// If url contains the current line return true
if (url.indexOf(cleanLine) > -1) {
return true;
}
}
return false;
}
module.exports = contains;
|
Add support for notifications on gallery.gallerypicture | // @flow
import React from 'react';
import { Link } from 'react-router';
import type { AggregatedActivity } from './types';
export function lookupContext(
aggregatedActivity: AggregatedActivity,
key: string
) {
return aggregatedActivity.context[key];
}
export const contextRender = {
'users.user': (context: Object) => (
<Link to={`/users/${context.username}/`}>
{`${context.firstName} ${context.lastName}`}
</Link>
),
'events.event': (context: Object) => (
<Link to={`/events/${context.id}/`}>{`${context.title}`}</Link>
),
'meetings.meetinginvitation': (context: Object) => (
<Link to={`/meetings/${context.meeting.id}/`}>{context.meeting.title}</Link>
),
'articles.article': (context: Object) => (
<Link to={`/articles/${context.id}/`}>{context.title}</Link>
),
'notifications.announcement': (context: Object) => <p>{context.message}</p>,
'gallery.gallerypicture': (context: Object) => (
<Link to={`/photos/${context.gallery.id}/picture/${context.id}`}>
{context.gallery.title}-#{context.id}
</Link>
)
};
| // @flow
import React from 'react';
import { Link } from 'react-router';
import type { AggregatedActivity } from './types';
export function lookupContext(
aggregatedActivity: AggregatedActivity,
key: string
) {
return aggregatedActivity.context[key];
}
export const contextRender = {
'users.user': (context: Object) => (
<Link to={`/users/${context.username}/`}>
{`${context.firstName} ${context.lastName}`}
</Link>
),
'events.event': (context: Object) => (
<Link to={`/events/${context.id}/`}>{`${context.title}`}</Link>
),
'meetings.meetinginvitation': (context: Object) => (
<Link to={`/meetings/${context.meeting.id}/`}>{context.meeting.title}</Link>
),
'articles.article': (context: Object) => (
<Link to={`/articles/${context.id}/`}>{context.title}</Link>
),
'notifications.announcement': (context: Object) => <p>{context.message}</p>
};
|
Rename cookie message cookie name
It currently clashes with GOV.UK cookie name so if the user has previously
visited GOV.UK they won't see our cookie message. | function setCookie(name, value, options = {}) {
let cookieString = `${name}=${value}; path=/`;
if (options.days) {
const date = new Date();
date.setTime(date.getTime() + (options.days * 24 * 60 * 60 * 1000));
cookieString = `${cookieString}; expires=${date.toGMTString()}`;
}
if (document.location.protocol === 'https:') {
cookieString = `${cookieString}; Secure`;
}
document.cookie = cookieString;
}
function getCookie(name) {
const nameEQ = `${name}=`;
const cookies = document.cookie.split(';');
for (let i = 0, len = cookies.length; i < len; i++) {
let cookie = cookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return decodeURIComponent(cookie.substring(nameEQ.length));
}
}
return null;
}
module.exports = (id) => {
const banner = document.getElementById(id);
if (banner && getCookie('nhsuk_seen_cookie_message') === null) {
banner.style.display = 'block';
setCookie('seen_cookie_message', 'yes', { days: 28 });
}
};
| function setCookie(name, value, options = {}) {
let cookieString = `${name}=${value}; path=/`;
if (options.days) {
const date = new Date();
date.setTime(date.getTime() + (options.days * 24 * 60 * 60 * 1000));
cookieString = `${cookieString}; expires=${date.toGMTString()}`;
}
if (document.location.protocol === 'https:') {
cookieString = `${cookieString}; Secure`;
}
document.cookie = cookieString;
}
function getCookie(name) {
const nameEQ = `${name}=`;
const cookies = document.cookie.split(';');
for (let i = 0, len = cookies.length; i < len; i++) {
let cookie = cookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return decodeURIComponent(cookie.substring(nameEQ.length));
}
}
return null;
}
module.exports = (id) => {
const banner = document.getElementById(id);
if (banner && getCookie('seen_cookie_message') === null) {
banner.style.display = 'block';
setCookie('seen_cookie_message', 'yes', { days: 28 });
}
};
|
Test that lib/action is an invoker | describe('action', function() {
beforeEach(function() {
this.subject = require(libDir + 'action');
});
it('is an invoker', function() {
assert.isFunction(this.subject.invoke);
});
it('has a list of available methods', function() {
var methodNames = Object.keys(this.subject.methods);
assert(methodNames.length > 0, 'expected more than 0 method names');
});
it('has actions in the form {topic}.{event}', function() {
var allowedTopics = ['database', 'player', 'playlist'],
actionFormat = new RegExp(
'^(' + allowedTopics.join('|') + '){1}\.\\w+$'
),
subject = this.subject,
methodNames = Object.keys(subject.methods);
methodNames.forEach(function(m) {
assert.match(m, actionFormat);
});
});
it('has a function for every available method', function() {
var subject = this.subject,
methodNames = Object.keys(subject.methods);
methodNames.forEach(function(m) {
assert.isFunction(
subject.methods[m],
'expected '+m+' to have a function'
);
});
});
});
| describe('action', function() {
beforeEach(function() {
this.subject = require(libDir + 'action');
});
it('has a list of available methods', function() {
var methodNames = Object.keys(this.subject.methods);
assert(methodNames.length > 0, 'expected more than 0 method names');
});
it('has actions in the form {topic}.{event}', function() {
var allowedTopics = ['database', 'player', 'playlist'],
actionFormat = new RegExp(
'^(' + allowedTopics.join('|') + '){1}\.\\w+$'
),
subject = this.subject,
methodNames = Object.keys(subject.methods);
methodNames.forEach(function(m) {
assert.match(m, actionFormat);
});
});
it('has a function for every available method', function() {
var subject = this.subject,
methodNames = Object.keys(subject.methods);
methodNames.forEach(function(m) {
assert.isFunction(
subject.methods[m],
'expected '+m+' to have a function'
);
});
});
});
|
Rename cash flow getter to getHistory | /*
* LapisCommons
* Copyright (c) 2014, LapisDev <https://github.com/LapisDev>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package blue.lapis.common.economy;
public interface EconomyAccount {
String getAccountName();
double getBalance();
void setBalance();
boolean hasHistory();
TransactionHistory getHistory();
String getCurrencyNameSingular();
String getCurrencyNamePlural();
}
| /*
* LapisCommons
* Copyright (c) 2014, LapisDev <https://github.com/LapisDev>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package blue.lapis.common.economy;
public interface EconomyAccount {
String getAccountName();
double getBalance();
void setBalance();
boolean hasCashFlow();
TransactionHistory getCashFlow();
String getCurrencyNameSingular();
String getCurrencyNamePlural();
}
|
Change how mode strings are constructed | from txircd.utils import CaseInsensitiveDictionary, now()
class IRCChannel(object):
def __init__(self, ircd, name):
self.ircd = ircd
self.name = name
self.created = now()
self.topic = ""
self.topicSetter = ""
self.topicTime = now()
self.mode = {}
self.users = CaseInsensitiveDictionary()
self.metadata = {}
self.cache = {}
def modeString(self, user):
modes = [] # Since we're appending characters to this string, it's more efficient to store the array of characters and join it rather than keep making new strings
params = []
for mode, param in self.mode.iteritems():
modetype = self.ircd.channel_mode_type[mode]
if modetype > 0:
modes.append(mode)
if param:
params.append(self.ircd.channel_modes[modetype][mode].showParam(user, param))
return ("+{} {}".format("".join(modes), " ".join(params)) if params else "".join(modes))
def setTopic(self, topic, setter):
self.topic = topic
self.topicSetter = setter
self.topicTime = now()
def getMetadata(self, key):
if key in self.metadata:
return self.metadata[key]
return "" | from txircd.utils import CaseInsensitiveDictionary, now()
class IRCChannel(object):
def __init__(self, ircd, name):
self.ircd = ircd
self.name = name
self.created = now()
self.topic = ""
self.topicSetter = ""
self.topicTime = now()
self.mode = {}
self.users = CaseInsensitiveDictionary()
self.metadata = {}
self.cache = {}
def modeString(self, user):
modes = "+"
params = []
for mode, param in self.mode.iteritems():
modetype = self.ircd.channel_mode_type[mode]
if modetype > 0:
modes += mode
if param:
params.append(self.ircd.channel_modes[modetype][mode].showParam(user, param))
return ("{} {}".format(modes, " ".join(params)) if params else modes)
def setTopic(self, topic, setter):
self.topic = topic
self.topicSetter = setter
self.topicTime = now()
def getMetadata(self, key):
if key in self.metadata:
return self.metadata[key]
return "" |
Remove test Zarr files after completion. | #!/usr/bin/env python
import os
import shutil
import sys
if not os.environ.get("TEST_NOTEBOOKS"):
sys.exit(0)
for each in list(sys.argv[1:]) + [
"reg.h5",
"reg_sub.h5",
"reg_f_f0.h5",
"reg_wt.h5",
"reg_norm.h5",
"reg_dict.h5",
"reg_post.h5",
"reg_traces.h5",
"reg_rois.h5",
"reg_proj.h5",
"reg.zarr",
"reg_sub.zarr",
"reg_f_f0.zarr",
"reg_wt.zarr",
"reg_norm.zarr",
"reg_dict.zarr",
"reg_post.zarr",
"reg_traces.zarr",
"reg_rois.zarr",
"reg_proj.zarr",
"reg_proj.html"]:
if os.path.isfile(each):
os.remove(each)
elif os.path.isdir(each):
shutil.rmtree(each)
| #!/usr/bin/env python
import os
import shutil
import sys
if not os.environ.get("TEST_NOTEBOOKS"):
sys.exit(0)
for each in list(sys.argv[1:]) + [
"reg.h5",
"reg_sub.h5",
"reg_f_f0.h5",
"reg_wt.h5",
"reg_norm.h5",
"reg_dict.h5",
"reg_post.h5",
"reg_traces.h5",
"reg_rois.h5",
"reg_proj.h5",
"reg_proj.html"]:
if os.path.isfile(each):
os.remove(each)
elif os.path.isdir(each):
shutil.rmtree(each)
|
Update ES client to support ES 5.x | Package.describe({
name: 'easysearch:elasticsearch',
summary: "Elasticsearch Engine for EasySearch",
version: "2.1.1",
git: "https://github.com/matteodem/meteor-easy-search.git",
documentation: 'README.md'
});
Npm.depends({
'elasticsearch': '13.0.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.2');
// Dependencies
api.use(['check', 'ecmascript']);
api.use(['easysearch:core@2.1.0', 'erasaur:meteor-lodash@4.0.0']);
api.addFiles([
'lib/data-syncer.js',
'lib/engine.js',
]);
api.export('EasySearch');
api.mainModule('./lib/main.js');
});
Package.onTest(function(api) {
api.use(['tinytest', 'ecmascript']);
api.use('easysearch:elasticsearch');
api.addFiles(['tests/engine-tests.js']);
});
| Package.describe({
name: 'easysearch:elasticsearch',
summary: "Elasticsearch Engine for EasySearch",
version: "2.1.1",
git: "https://github.com/matteodem/meteor-easy-search.git",
documentation: 'README.md'
});
Npm.depends({
'elasticsearch': '8.2.0'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.2');
// Dependencies
api.use(['check', 'ecmascript']);
api.use(['easysearch:core@2.1.0', 'erasaur:meteor-lodash@4.0.0']);
api.addFiles([
'lib/data-syncer.js',
'lib/engine.js',
]);
api.export('EasySearch');
api.mainModule('./lib/main.js');
});
Package.onTest(function(api) {
api.use(['tinytest', 'ecmascript']);
api.use('easysearch:elasticsearch');
api.addFiles(['tests/engine-tests.js']);
});
|
Revert test servlet to /test location | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/test")
public class TestServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;");
response.getWriter().println("<h1>Hello world!</h1>");
}
}
| // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/test2")
public class TestServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html;");
response.getWriter().println("<h1>Hello world!</h1>");
}
}
|
Fix tests depending on native services | /*
* Copyright 2014 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.gradle.testfixtures.internal;
import org.gradle.internal.nativeintegration.services.NativeServices;
import java.io.File;
public class NativeServicesTestFixture {
static NativeServices nativeServices;
static boolean initialized;
public static synchronized void initialize() {
if (!initialized) {
System.setProperty("org.gradle.native", "true");
File nativeDir = getNativeServicesDir();
NativeServices.initialize(nativeDir);
initialized = true;
}
}
public static synchronized NativeServices getInstance() {
if (nativeServices == null) {
initialize();
nativeServices = NativeServices.getInstance();
}
return nativeServices;
}
public static File getNativeServicesDir() {
return new File("build/native-libs");
}
}
| /*
* Copyright 2014 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.gradle.testfixtures.internal;
import org.gradle.internal.nativeintegration.services.NativeServices;
import java.io.File;
public class NativeServicesTestFixture {
static NativeServices nativeServices;
static boolean initialized;
public static synchronized void initialize() {
if (!initialized) {
File nativeDir = getNativeServicesDir();
NativeServices.initialize(nativeDir);
initialized = true;
}
}
public static synchronized NativeServices getInstance() {
if (nativeServices == null) {
initialize();
nativeServices = NativeServices.getInstance();
}
return nativeServices;
}
public static File getNativeServicesDir() {
return new File("build/native-libs");
}
}
|
Clean up test a bit. | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import io
from hypothesis import given
from hypothesis.strategies import builds, lists, integers, just
from sensibility import Program, vocabulary
tokens = integers(min_value=vocabulary.start_token_index + 1,
max_value=vocabulary.end_token_index - 1)
vectors = lists(tokens, min_size=1)
programs = builds(Program, just('<test>'), vectors)
@given(programs)
def test_program_random(program):
assert 0 <= program.random_token_index() < len(program)
assert 0 <= program.random_insertion_point() <= len(program)
@given(programs)
def test_program_print(program):
with io.StringIO() as output:
program.print(output)
output_text = output.getvalue()
assert len(program) == len(output_text.split())
| #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import io
from hypothesis import given
from hypothesis.strategies import lists, integers
from sensibility import Program, vocabulary
#semicolon = vocabulary.to_index(';')
@given(lists(integers(min_value=vocabulary.start_token_index + 1,
max_value=vocabulary.end_token_index - 1),
min_size=1))
def test_program_random(tokens):
p = Program('<none>', tokens)
assert 0 <= p.random_token_index() < len(p)
assert 0 <= p.random_insertion_point() <= len(p)
@given(lists(integers(min_value=vocabulary.start_token_index + 1,
max_value=vocabulary.end_token_index - 1),
min_size=1))
def test_program_print(tokens):
program = Program('<none>', tokens)
with io.StringIO() as output:
program.print(output)
output_text = output.getvalue()
assert len(program) >= 1
assert len(program) == len(output_text.split())
|
Change the option name to better reflect the contents | <?php
/**
* Represents the WordPress option for saving the dismissed messages.
*/
class Whip_WPDismissOption implements Whip_DismissStorage {
/** @var string */
protected $optionName = 'whip_dismiss_timestamp';
/**
* Saves the value to the options.
*
* @param int $dismissedValue The value to save.
*
* @return bool True when successful.
*/
public function set( $dismissedValue ) {
return update_option( $this->optionName, $dismissedValue );
}
/**
* Returns the value of the whip_dismissed option.
*
* @return int Returns the value of the option or an empty string when not set.
*/
public function get() {
$dismissedOption = get_option( $this->optionName );
if ( ! $dismissedOption ) {
return 0;
}
return (int) $dismissedOption;
}
}
| <?php
/**
* Represents the WordPress option for saving the dismissed messages.
*/
class Whip_WPDismissOption implements Whip_DismissStorage {
/** @var string */
protected $optionName = 'whip_dismissed_for_wp_version';
/**
* Saves the value to the options.
*
* @param int $dismissedValue The value to save.
*
* @return bool True when successful.
*/
public function set( $dismissedValue ) {
return update_option( $this->optionName, $dismissedValue );
}
/**
* Returns the value of the whip_dismissed option.
*
* @return int Returns the value of the option or an empty string when not set.
*/
public function get() {
$dismissedOption = get_option( $this->optionName );
if ( ! $dismissedOption ) {
return 0;
}
return (int) $dismissedOption;
}
}
|
Update usage string with "path" subcommand. | package main
import (
"fmt"
"log"
"os"
)
func main() {
mode := ""
if len(os.Args) > 1 {
mode = os.Args[1]
if len(os.Args) > 2 {
os.Args = append(os.Args[:1], os.Args[2:]...)
} else {
os.Args = os.Args[0:1]
}
} else {
usage()
}
// Subcommands may override this.
log.SetOutput(os.Stderr)
switch mode {
case "build":
DoBuildCommand()
case "list":
DoListCommand()
case "print":
DoPrintCommand()
default:
usage()
}
}
func usage() {
fmt.Printf("Usage: kerouac {build, list, print}\n")
fmt.Printf("\n")
fmt.Printf("Use kerouac <subcommand> -h for help.\n")
os.Exit(1)
}
| package main
import (
"fmt"
"log"
"os"
)
func main() {
mode := ""
if len(os.Args) > 1 {
mode = os.Args[1]
if len(os.Args) > 2 {
os.Args = append(os.Args[:1], os.Args[2:]...)
} else {
os.Args = os.Args[0:1]
}
} else {
usage()
}
// Subcommands may override this.
log.SetOutput(os.Stderr)
switch mode {
case "build":
DoBuildCommand()
case "list":
DoListCommand()
case "print":
DoPrintCommand()
default:
usage()
}
}
func usage() {
fmt.Printf("Usage: kerouac {build, list}\n")
fmt.Printf("\n")
fmt.Printf("Use kerouac <subcommand> -h for help.\n")
os.Exit(1)
}
|
Add 'jump consistent hash' keyword. | from __future__ import print_function
import sys
from setuptools import setup
if sys.version_info < (3, 2):
print('ERROR: jump-consistent-hash requires Python version 3.2 or newer.',
file=sys.stderr)
sys.exit(1)
setup(name='jump_consistent_hash',
version='1.0.3',
description='Implementation of the Jump Consistent Hash algorithm',
author='Peter Renström',
license='MIT',
url='https://github.com/renstrom/python-jump-consistent-hash',
packages=['jump'],
test_suite='tests',
keywords=[
'jump hash',
'jumphash',
'jump consistent hash',
'consistent hash',
'hash algorithm',
'hash'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
])
| from __future__ import print_function
import sys
from setuptools import setup
if sys.version_info < (3, 2):
print('ERROR: jump-consistent-hash requires Python version 3.2 or newer.',
file=sys.stderr)
sys.exit(1)
setup(name='jump_consistent_hash',
version='1.0.3',
description='Implementation of the Jump Consistent Hash algorithm',
author='Peter Renström',
license='MIT',
url='https://github.com/renstrom/python-jump-consistent-hash',
packages=['jump'],
test_suite='tests',
keywords=[
'jump hash',
'jumphash',
'consistent hash',
'hash algorithm',
'hash'
],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4'
])
|
Add Word model to shell context | import os
import coverage
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand
from config import basedir
from app import create_app, db
from app.models import User, Dictionary, Word
app = create_app(os.getenv("MYDICTIONARY_CONFIG") or "default")
migrate = Migrate(app, db)
manager = Manager(app)
def make_shell_context():
return dict(app=app, db=db, User=User, Dictionary=Dictionary, Word=Word)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command("db", MigrateCommand)
cov = coverage.coverage(branch=True, include="app/*")
@manager.command
def test(coverage=False):
""" Run the unit tests. """
if coverage:
cov.start()
import unittest
tests = unittest.TestLoader().discover("tests")
unittest.TextTestRunner(verbosity=2).run(tests)
if coverage:
cov.stop()
cov.save()
print("Coverage Summary:")
cov.report()
cov_dir = os.path.join(basedir, "tmp/coverage")
cov.html_report(directory=cov_dir)
print("HTML version: %s/index.html" % cov_dir)
cov.erase()
if __name__ == "__main__":
manager.run() | import os
import coverage
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand
from config import basedir
from app import create_app, db
from app.models import User, Dictionary
app = create_app(os.getenv("MYDICTIONARY_CONFIG") or "default")
migrate = Migrate(app, db)
manager = Manager(app)
def make_shell_context():
return dict(app=app, db=db, User=User, Dictionary=Dictionary)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command("db", MigrateCommand)
cov = coverage.coverage(branch=True, include="app/*")
@manager.command
def test(coverage=False):
""" Run the unit tests. """
if coverage:
cov.start()
import unittest
tests = unittest.TestLoader().discover("tests")
unittest.TextTestRunner(verbosity=2).run(tests)
if coverage:
cov.stop()
cov.save()
print("Coverage Summary:")
cov.report()
cov_dir = os.path.join(basedir, "tmp/coverage")
cov.html_report(directory=cov_dir)
print("HTML version: %s/index.html" % cov_dir)
cov.erase()
if __name__ == "__main__":
manager.run() |
Add timeInfo() for conditional scales
Fix quotes and remove whitespace | import fmt from "./fmt"
import { log } from "fly-util"
export default function () {
this.on("fly_run", ({ path }) =>
log(`Flying with ${fmt.path}...`, path))
.on("flyfile_not_found", ({ error }) =>
log(`No Flyfile Error: ${fmt.error}`, error))
.on("fly_watch", () =>
log(`${fmt.warn}`, "Watching files..."))
.on("plugin_load", ({ plugin }) =>
log(`Loading plugin ${fmt.name}`, plugin))
.on("plugin_error", ({ plugin, error }) =>
log(`${fmt.error} failed due to ${fmt.error}`, plugin, error))
.on("task_error", ({ task, error }) =>
log(`${fmt.error} failed due to ${fmt.error}`, task, error))
.on("task_start", ({ task }) =>
log(`Starting ${fmt.start}`, task))
.on("task_complete", ({ task, duration }) => {
const time = timeInfo(duration)
log(`Finished ${fmt.complete} in ${fmt.secs}`, task, time.duration, time.scale)
})
.on("task_not_found", ({ task }) =>
log(`${fmt.error} not found in Flyfile.`, task))
return this
}
/**
* conditionally format task duration
* @param {Number} duration task duration in ms
* @param {String} scale default scale for output
* @return {Object} time information
*/
function timeInfo (duration, scale = "ms") {
const time = duration >= 1000
? { duration: Math.round((duration / 1000) * 10) / 10, scale: "s" }
: { duration, scale }
return time
}
| import fmt from "./fmt"
import { log } from "fly-util"
export default function () {
this.on("fly_run", ({ path }) =>
log(`Flying with ${fmt.path}...`, path))
.on("flyfile_not_found", ({ error }) =>
log(`No Flyfile Error: ${fmt.error}`, error))
.on("fly_watch", () =>
log(`${fmt.warn}`, "Watching files..."))
.on("plugin_load", ({ plugin }) =>
log(`Loading plugin ${fmt.name}`, plugin))
.on("plugin_error", ({ plugin, error }) =>
log(`${fmt.error} failed due to ${fmt.error}`, plugin, error))
.on("task_error", ({ task, error }) =>
log(`${fmt.error} failed due to ${fmt.error}`, task, error))
.on("task_start", ({ task }) =>
log(`Starting ${fmt.start}`, task))
.on("task_complete", ({ task, duration }) =>
log(`Finished ${fmt.complete} in ${fmt.secs}`, task, duration, "ms"))
.on("task_not_found", ({ task }) =>
log(`${fmt.error} not found in Flyfile.`, task))
return this
}
|
Fix an assertion in test | package water;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.*;
public class TypeMapTest extends TestUtil {
@BeforeClass()
public static void setup() { stall_till_cloudsize(1); }
@Test
public void testPrintTypeMap() {
TypeMap.printTypeMap(System.out);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try (PrintStream ps = new PrintStream(os)) {
TypeMap.printTypeMap(ps);
}
String output = os.toString();
String[] lines = output.split("\n");
String[] bootstrapClasses = TypeMap.bootstrapClasses();
assertTrue(bootstrapClasses.length <= lines.length);
for (int i = 0; i < bootstrapClasses.length; i++) {
assertEquals(i + " -> " + bootstrapClasses[i] + " (map: " + i + ")", lines[i]);
}
}
}
| package water;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.*;
public class TypeMapTest extends TestUtil {
@BeforeClass()
public static void setup() { stall_till_cloudsize(1); }
@Test
public void testPrintTypeMap() {
TypeMap.printTypeMap(System.out);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try (PrintStream ps = new PrintStream(os)) {
TypeMap.printTypeMap(ps);
}
String output = os.toString();
String[] lines = output.split("\n");
String[] bootstrapClasses = TypeMap.bootstrapClasses();
assertTrue(bootstrapClasses.length >= lines.length);
for (int i = 0; i < bootstrapClasses.length; i++) {
assertEquals(i + " -> " + bootstrapClasses[i] + " (map: " + i + ")", lines[i]);
}
}
}
|
Add force slug functions back. | <?php
/**
* Custom login logo.
*
* @return void
*/
add_action('login_head', function()
{
$path = ADMIN_URL.'/images/admin-login-logo.png';
echo "<style> h1 a { background-image:url($path) !important; background-size: auto auto !important; } </style>";
});
/**
* Custom login logo url.
*
* @return string
*/
add_filter('login_headerurl', function()
{
return LOGIN_HEADER_URL;
});
/**
* Custom footer text.
*
* @return void
*/
add_filter('admin_footer_text', function()
{
return 'Thank you for creating with <a href="'.AUTHOR_URL.'">'.AUTHOR.'</a>.';
});
/**
* Force Perfect JPG Images.
*
* @return integer
*/
add_filter('jpeg_quality', function()
{
return 100;
});
/**
* Filters that allow shortcodes in Text Widgets
*/
add_filter('widget_text', 'shortcode_unautop');
add_filter('widget_text', 'do_shortcode');
/**
* Force slug to update on save.
*
* @return array
*/
add_filter('wp_insert_post_data', function($data, $postarr) {
if (!in_array( $data['post_status'], ['draft', 'pending', 'auto-draft'])) {
$title = $data['post_title'];
$title = iconv('UTF8', 'ASCII//TRANSLIT', $title);
$title = preg_replace('/[^a-zA-Z0-9]/', '_', $title);
$data['post_name'] = sanitize_title_with_dashes( $title );
}
return $data;
}, 99, 2 );
| <?php
/**
* Custom login logo.
*
* @return void
*/
add_action('login_head', function()
{
$path = ADMIN_URL.'/images/admin-login-logo.png';
echo "<style> h1 a { background-image:url($path) !important; background-size: auto auto !important; } </style>";
});
/**
* Custom login logo url.
*
* @return string
*/
add_filter('login_headerurl', function()
{
return LOGIN_HEADER_URL;
});
/**
* Custom footer text.
*
* @return void
*/
add_filter('admin_footer_text', function()
{
return 'Thank you for creating with <a href="'.AUTHOR_URL.'">'.AUTHOR.'</a>.';
});
/**
* Force Perfect JPG Images.
*
* @return integer
*/
add_filter('jpeg_quality', function()
{
return 100;
});
/**
* Filters that allow shortcodes in Text Widgets
*/
add_filter('widget_text', 'shortcode_unautop');
add_filter('widget_text', 'do_shortcode');
|
Use let instead of var for max compatibility | 'use strict'
/**
* Mixes reducers in order. The resulting reducer function will try all
* available reducers until a new state is obtained, thus it is recommended
* to keep the state object immutable.
* @param {Array.<Function>} reducers functions that accept `state, action`
* arguments and return new state.
* @return {Function} a new reducer function
*/
function mixn (_reducers) {
const reducers = Array.isArray(_reducers) ? _reducers : Array.from(arguments)
if (reducers.length === 0) {
throw new Error('The reducers array needs at least one function')
}
reducers.forEach(function (reducer) {
if (typeof reducer !== 'function') {
throw new TypeError('All reducers must be a function')
}
})
function reduce (state, action) {
var newState
reducers.some(function (fn) {
newState = fn(state, action)
return newState !== state
})
return newState
}
return reduce
}
module.exports = mixn
| 'use strict'
/**
* Mixes reducers in order. The resulting reducer function will try all
* available reducers until a new state is obtained, thus it is recommended
* to keep the state object immutable.
* @param {Array.<Function>} reducers functions that accept `state, action`
* arguments and return new state.
* @return {Function} a new reducer function
*/
function mixn (_reducers) {
const reducers = Array.isArray(_reducers) ? _reducers : Array.from(arguments)
if (reducers.length === 0) {
throw new Error('The reducers array needs at least one function')
}
reducers.forEach(function (reducer) {
if (typeof reducer !== 'function') {
throw new TypeError('All reducers must be a function')
}
})
function reduce (state, action) {
let newState
reducers.some(function (fn) {
newState = fn(state, action)
return newState !== state
})
return newState
}
return reduce
}
module.exports = mixn
|
Test edit - to check svn email hook | import os, glob, string, shutil
from distutils.core import setup
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']
def main():
setup (name = 'neuroimaging',
version = '0.01a',
description = 'This is a neuroimaging python package',
author = 'Various, one of whom is Jonathan Taylor',
author_email = 'jonathan.taylor@stanford.edu',
ext_package = 'neuroimaging',
packages=packages,
package_dir = {'neuroimaging': 'lib'},
url = 'http://neuroimaging.scipy.org',
long_description =
'''
''')
if __name__ == "__main__":
main()
| from distutils.core import setup
import os, glob, string, shutil
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']
def main():
setup (name = 'neuroimaging',
version = '0.01a',
description = 'This is a neuroimaging python package',
author = 'Various, one of whom is Jonathan Taylor',
author_email = 'jonathan.taylor@stanford.edu',
ext_package = 'neuroimaging',
packages=packages,
package_dir = {'neuroimaging': 'lib'},
url = 'http://neuroimaging.scipy.org',
long_description =
'''
''')
if __name__ == "__main__":
main()
|
Add copyright and license information. | #!/usr/bin/python3
"""
Copyright (c) 2017 Finn Ellis.
Free to use and modify under the terms of the MIT license.
See included LICENSE file for details.
"""
import tweepy
import random
import os
from secrets import *
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
twitter = tweepy.API(auth)
photo_file = os.path.join("polaroids", os.listdir("polaroids")[0])
comment = random.choice([
"Hmm ...",
"Remember this party?",
"Oh dear.",
"Huh.",
"Uh ...",
"I totally forgot about this.",
"Oh geeze.",
"This one's going in my scrapbook.",
"...",
"Oh wow, remember this?",
"Whose house even was this?",
"I don't remember this at all.",
"Er ...",
"Those were the days.",
"I miss that crew."
])
tweet = twitter.update_with_media(photo_file, comment)
os.remove(photo_file)
| #!/usr/bin/python3
import tweepy
import random
import os
from secrets import *
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
twitter = tweepy.API(auth)
photo_file = os.path.join("polaroids", os.listdir("polaroids")[0])
comment = random.choice([
"Hmm ...",
"Remember this party?",
"Oh dear.",
"Huh.",
"Uh ...",
"I totally forgot about this.",
"Oh geeze.",
"This one's going in my scrapbook.",
"...",
"Oh wow, remember this?",
"Whose house even was this?",
"I don't remember this at all.",
"Er ...",
"Those were the days.",
"I miss that crew."
])
tweet = twitter.update_with_media(photo_file, comment)
os.remove(photo_file)
|
Fix wrong array typehint for errors | <?php
namespace MangoPay\Libraries;
/**
* Class represents error object
*/
class Error
{
/**
* Error message
* @var string
* @access public
*/
public $Message;
/**
* Array with errors information
* @var object
* @access public
*/
public $Errors;
/**
* An identifer for this API response
* @var string
* @access public
*/
public $Id;
/**
* The timestamp of this API response
* @var int
* @access public
*/
public $Date;
/**
* The type of error
* @var string
* @access public
*/
public $Type;
/**
* Return the stdClass error serialized as string
* @access public
*/
public function __toString()
{
return serialize($this->Errors);
}
}
| <?php
namespace MangoPay\Libraries;
/**
* Class represents error object
*/
class Error
{
/**
* Error message
* @var string
* @access public
*/
public $Message;
/**
* Array with errors information
* @var array
* @access public
*/
public $Errors;
/**
* An identifer for this API response
* @var string
* @access public
*/
public $Id;
/**
* The timestamp of this API response
* @var timestamp
* @access public
*/
public $Date;
/**
* The type of error
* @var string
* @access public
*/
public $Type;
/**
* Return the stdClass error serialized as string
* @access public
*/
public function __toString()
{
return serialize($this->Errors);
}
}
|
Add switch hostname to node entity | // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.entity;
import java.util.Objects;
import java.util.Optional;
/**
* Information about a node from a {@link EntityService}.
*
* @author mpolden
*/
public class NodeEntity {
private final String hostname;
private final Optional<String> model;
private final Optional<String> manufacturer;
private final Optional<String> switchHostname;
public NodeEntity(String hostname, String model, String manufacturer, String switchHostname) {
this.hostname = Objects.requireNonNull(hostname);
this.model = nonBlank(model);
this.manufacturer = nonBlank(manufacturer);
this.switchHostname = nonBlank(switchHostname);
}
public String hostname() {
return hostname;
}
/** The model name of this node */
public Optional<String> model() {
return model;
}
/** The manufacturer of this node */
public Optional<String> manufacturer() {
return manufacturer;
}
/** The hostname of network switch this node is connected to */
public Optional<String> switchHostname() {
return switchHostname;
}
private static Optional<String> nonBlank(String s) {
return Optional.ofNullable(s).filter(v -> !v.isBlank());
}
}
| // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.entity;
import java.util.Objects;
import java.util.Optional;
/**
* Information about a node from a {@link EntityService}.
*
* @author mpolden
*/
public class NodeEntity {
private final String hostname;
private final Optional<String> model;
private final Optional<String> manufacturer;
public NodeEntity(String hostname, String model, String manufacturer) {
this.hostname = Objects.requireNonNull(hostname);
this.model = nonBlank(model);
this.manufacturer = nonBlank(manufacturer);
}
public String hostname() {
return hostname;
}
/** The model name of this node */
public Optional<String> model() {
return model;
}
/** The manufacturer of this node */
public Optional<String> manufacturer() {
return manufacturer;
}
private static Optional<String> nonBlank(String s) {
return Optional.ofNullable(s).filter(v -> !v.isBlank());
}
}
|
Fix overzealous transactions on dashboard panels
Summary: Fixes T10474. This had the same root cause as T10024 -- a missing call to `didSetValueFromStorage()` because of the way the fields work.
Test Plan:
- Edited a text panel before change, without changing text: got silly transaction.
- Made change, edited text panel without changing text, no transaction.
- Made a real edit, got a good transaction.
Reviewers: chad
Reviewed By: chad
Maniphest Tasks: T10474
Differential Revision: https://secure.phabricator.com/D15391 | <?php
final class PhabricatorDashboardPanelCoreCustomField
extends PhabricatorDashboardPanelCustomField
implements PhabricatorStandardCustomFieldInterface {
public function getStandardCustomFieldNamespace() {
return 'dashboard:core';
}
public function createFields($object) {
$impl = $object->requireImplementation();
$specs = $impl->getFieldSpecifications();
return PhabricatorStandardCustomField::buildStandardFields($this, $specs);
}
public function shouldUseStorage() {
return false;
}
public function readValueFromObject(PhabricatorCustomFieldInterface $object) {
$key = $this->getProxy()->getRawStandardFieldKey();
$this->setValueFromStorage($object->getProperty($key));
$this->didSetValueFromStorage();
}
public function applyApplicationTransactionInternalEffects(
PhabricatorApplicationTransaction $xaction) {
$object = $this->getObject();
$key = $this->getProxy()->getRawStandardFieldKey();
$this->setValueFromApplicationTransactions($xaction->getNewValue());
$value = $this->getValueForStorage();
$object->setProperty($key, $value);
}
public function applyApplicationTransactionExternalEffects(
PhabricatorApplicationTransaction $xaction) {
return;
}
}
| <?php
final class PhabricatorDashboardPanelCoreCustomField
extends PhabricatorDashboardPanelCustomField
implements PhabricatorStandardCustomFieldInterface {
public function getStandardCustomFieldNamespace() {
return 'dashboard:core';
}
public function createFields($object) {
$impl = $object->requireImplementation();
$specs = $impl->getFieldSpecifications();
return PhabricatorStandardCustomField::buildStandardFields($this, $specs);
}
public function shouldUseStorage() {
return false;
}
public function readValueFromObject(PhabricatorCustomFieldInterface $object) {
$key = $this->getProxy()->getRawStandardFieldKey();
$this->setValueFromStorage($object->getProperty($key));
}
public function applyApplicationTransactionInternalEffects(
PhabricatorApplicationTransaction $xaction) {
$object = $this->getObject();
$key = $this->getProxy()->getRawStandardFieldKey();
$this->setValueFromApplicationTransactions($xaction->getNewValue());
$value = $this->getValueForStorage();
$object->setProperty($key, $value);
}
public function applyApplicationTransactionExternalEffects(
PhabricatorApplicationTransaction $xaction) {
return;
}
}
|
Add if statement to gruntifle for conditionally watching LESS | 'use strict';
module.exports = function(grunt)
{
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-watch');
// load all grunt tasks
grunt.initConfig({
watch: {
<% if(themeUsesLESS) { %>
styles: {
files: ['**/*.less'],
tasks: ['less'],
options: {
spawn: false,
},
},
<%}%>
<% if(themeUsesCoffee) { %>
scripts: {
files: ['**/*.coffee'],
tasks: ['coffee'],
options: {
spawn: false,
},
},
<%}%>
},
less: {
development: {
options: {
strictImports: true
},
files: {
"css/style.css": "less/*.less"
}
}
},
coffee: {
compile: {
files: {
'js/script.js' : 'coffee/*.coffee'
}
}
}
});
} | 'use strict';
module.exports = function(grunt)
{
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-watch');
// load all grunt tasks
grunt.initConfig({
watch: {
styles: {
files: ['**/*.less'],
tasks: ['less'],
options: {
spawn: false,
},
},
<% if(themeUsesCoffee) { %>
scripts: {
files: ['**/*.coffee'],
tasks: ['coffee'],
options: {
spawn: false,
},
},
<%}%>
},
less: {
development: {
options: {
strictImports: true
},
files: {
"css/style.css": "less/*.less"
}
}
},
coffee: {
compile: {
files: {
'js/script.js' : 'coffee/*.coffee'
}
}
}
});
} |
Fix error message when patch is missing. | from __future__ import absolute_import, division, print_function
import os
import sys
from os.path import isfile, join, expanduser
import conda.config as cc
from conda_build.config import config
def find_executable(executable):
# dir_paths is referenced as a module-level variable
# in other code
global dir_paths
if sys.platform == 'win32':
dir_paths = [join(config.build_prefix, 'Scripts'),
join(cc.root_dir, 'Scripts'),
'C:\\cygwin\\bin']
else:
dir_paths = [join(config.build_prefix, 'bin'),
join(cc.root_dir, 'bin'),]
dir_paths.extend(os.environ['PATH'].split(os.pathsep))
for dir_path in dir_paths:
if sys.platform == 'win32':
for ext in '.exe', '.bat', '':
path = join(dir_path, executable + ext)
if isfile(path):
return path
else:
path = join(dir_path, executable)
if isfile(expanduser(path)):
return expanduser(path)
return None
| from __future__ import absolute_import, division, print_function
import os
import sys
from os.path import isfile, join, expanduser
import conda.config as cc
from conda_build.config import config
def find_executable(executable):
if sys.platform == 'win32':
dir_paths = [join(config.build_prefix, 'Scripts'),
join(cc.root_dir, 'Scripts'),
'C:\\cygwin\\bin']
else:
dir_paths = [join(config.build_prefix, 'bin'),
join(cc.root_dir, 'bin'),]
dir_paths.extend(os.environ['PATH'].split(os.pathsep))
for dir_path in dir_paths:
if sys.platform == 'win32':
for ext in '.exe', '.bat', '':
path = join(dir_path, executable + ext)
if isfile(path):
return path
else:
path = join(dir_path, executable)
if isfile(expanduser(path)):
return expanduser(path)
return None
|
Increment version number to 0.0.2 | #!/usr/bin/env python
from setuptools import setup
setup(
name='django-simple-url',
version='0.0.2',
description='Simpler URL specification for Django.',
author="Sjoerd Job Postmus",
author_email='sjoerdjob@sjec.nl',
url='https://github.com/sjoerdjob/django-simple-url',
packages=['django_simple_url'],
package_dir={'': 'src'},
include_package_data=True,
license='MIT license',
keywords=['django', 'url'],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='django-simple-url',
version='0.0.1',
description='Simpler URL specification for Django.',
author="Sjoerd Job Postmus",
author_email='sjoerdjob@sjec.nl',
url='https://github.com/sjoerdjob/django-simple-url',
packages=['django_simple_url'],
package_dir={'': 'src'},
include_package_data=True,
license='MIT license',
keywords=['django', 'url'],
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
)
|
Update the twitter sample example | // Twitter Sample
//
// Using the Twitter Streaming API. In this example, we retrieve the
// sample of the statuses in real time.
// Import node modules
var Twit = require('twit'), // Twitter API Client
config = require('./config.json'); // Twitter Credentials
// Configure the Twit object with the application credentials
var T = new Twit(config);
// Subscribe to the sample stream and begin listening
var stream = T.stream('statuses/sample');
// The callback will be invoked on each tweet. Here, we print the username
// and the text of the tweet in the screen.
stream.on('tweet', function(tweet) {
console.log('[@' + tweet.user.screen_name + ']: ' + tweet.text);
});
// The 'connect' callback is invoked when the Twitter API Client
// tries to connect to Twitter.
stream.on('connect', function(msg) {
console.log('connect');
});
// The 'connected' event is triggered when the connection is successful.
stream.on('connected', function(msg) {
console.log('connected');
});
// The 'reconnect' event is triggered when a reconnection is scheduled.
stream.on('reconnect', function(req, res, interval) {
console.log('Reconnecting in ' + (interval / 3) + ' seconds.');
});
// The 'warning' event is triggered if the client is not processing the
// tweets fast enough.
stream.on('warning', function(msg) {
console.warning('warning')
});
// The 'disconnect' event is triggered when a disconnect message comes from
// Twitter.
stream.on('disconnect', function(msg) {
console.log('disconnect');
}); | // Twitter Sample
//
// Using the Twitter Streaming API. In this example, we retrieve the
// sample of the statuses in real time.
// Import node modules
var Twit = require('twit'), // Twitter API Client
config = require('./config.json'); // Twitter Credentials
// Configure the Twit object with the application credentials
var T = new Twit(config);
// Subscribe to the stream sample, for tweets in english
var stream = T.stream('statuses/sample');
// The callback will be invoked on each tweet. Here, we print the username
// and the text of the tweet in the screen.
stream.on('tweet', function(tweet) {
console.log('[@' + tweet.user.screen_name + ']: ' + tweet.text);
});
// The 'connect' callback is invoked when the Twitter API Client
// tries to connect to Twitter.
stream.on('connect', function(msg) {
console.log('connect');
});
// The 'connected' event is triggered when the connection is successful.
stream.on('connected', function(msg) {
console.log('connected');
});
// The 'warning' event is triggered if the client is not processing the
// tweets fast enough.
stream.on('warning', function(msg) {
console.warning('warning')
});
// The 'disconnect' event is triggered when a disconnect message comes from
// Twitter.
stream.on('disconnect', function(msg) {
console.log('disconnect');
}); |
Use facade because config() helper may cause some issue on teardown
process during testing.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
class OrchestraAuthCreatePasswordRemindersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create($this->tableNameForPasswordReset(), static function (Blueprint $table) {
$table->string('email')->index();
$table->string('token')->index();
$table->timestamp('created_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists($this->tableNameForPasswordReset());
}
/**
* Resolve table name.
*/
protected function tableNameForPasswordReset(): string
{
return Config::get(
'auth.passwords.'.Config::get('auth.defaults.passwords').'.table', 'password_resets'
);
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class OrchestraAuthCreatePasswordRemindersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create($this->tableNameForPasswordReset(), static function (Blueprint $table) {
$table->string('email')->index();
$table->string('token')->index();
$table->timestamp('created_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists($this->tableNameForPasswordReset());
}
/**
* Resolve table name.
*/
protected function tableNameForPasswordReset(): string
{
return config(
'auth.passwords.'.config('auth.defaults.passwords').'.table', 'password_resets'
);
}
}
|
Clear error after no response | package medtronic
import (
"log"
"time"
)
const (
Wakeup CommandCode = 0x5D
)
func (pump *Pump) Wakeup() {
pump.Model()
if pump.Error() == nil {
return
}
pump.SetError(nil)
log.Printf("waking pump")
const (
// Older pumps should have RF enabled to increase the
// frequency with which they listen for wakeups.
numWakeups = 100
xmitDelay = 10 * time.Millisecond
)
packet := commandPacket(Wakeup, nil)
for i := 0; i < numWakeups; i++ {
pump.Radio.Send(packet)
time.Sleep(xmitDelay)
}
n := pump.Retries()
pump.SetRetries(1)
defer pump.SetRetries(n)
t := pump.Timeout()
pump.SetTimeout(10 * time.Second)
defer pump.SetTimeout(t)
pump.Execute(Wakeup, nil)
}
| package medtronic
import (
"log"
"time"
)
const (
Wakeup CommandCode = 0x5D
)
func (pump *Pump) Wakeup() {
pump.Model()
if pump.Error() == nil {
return
}
log.Printf("waking pump")
const (
// Older pumps should have RF enabled to increase the
// frequency with which they listen for wakeups.
numWakeups = 75
xmitDelay = 35 * time.Millisecond
)
packet := commandPacket(Wakeup, nil)
for i := 0; i < numWakeups; i++ {
pump.Radio.Send(packet)
time.Sleep(xmitDelay)
}
n := pump.Retries()
pump.SetRetries(1)
defer pump.SetRetries(n)
t := pump.Timeout()
pump.SetTimeout(10 * time.Second)
defer pump.SetTimeout(t)
pump.Execute(Wakeup, nil)
}
|
Make a part of webpack config consistent with gh-pages branch variant for simpler future conflict resolutions. | import Bootstrap from 'bootstrap-webpack-plugin'
import Path from 'path'
const path = Path.join.bind(null, __dirname)
const outputDirName = `build`
const outputDir = path(outputDirName)
export default {
entry: {
playground: `./examples/playground/main.js`,
multipleTriggers: `./examples/multiple-triggers/main.js`,
},
output: {
path: outputDir,
filename: `[name].js`
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loaders: [`babel`]},
{ test: /\.css$/, exclude: /node_modules/, loaders: [ `style`, `css`, `cssnext` ]},
],
},
devtool: `source-map`,
devServer: {
contentBase: outputDir,
},
plugins: [Bootstrap({})],
}
| import Bootstrap from 'bootstrap-webpack-plugin'
import Path from 'path'
const path = Path.join.bind(null, __dirname)
const outputDir = path(`build`)
export default {
entry: {
playground: `./examples/playground/main.js`,
multipleTriggers: `./examples/multiple-triggers/main.js`,
},
output: {
path: outputDir,
filename: `[name].js`
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loaders: [`babel`]},
{ test: /\.css$/, exclude: /node_modules/, loaders: [ `style`, `css`, `cssnext` ]},
],
},
devtool: `source-map`,
devServer: {
contentBase: outputDir,
},
plugins: [Bootstrap({})],
}
|
Set discord status on ready instead. | const MessageHandler = require("./MessageHandler.js");
var appConfig = require("./config.json");
var Discord = require('discord.io');
// Create Discord Bot (based on token in config)
var bot = new Discord.Client({
token: appConfig.api.discord.token,
autorun: true
});
// Handler that will take messages and pass them through to Frotz
var messageHandler = new MessageHandler(bot);
process.on('exit', function(){
// gracefully clean up connection to Discord
bot.disconnect();
// we need to close the game so there is not a lingering child process
// running in the background
messageHandler.closeGame();
});
bot.on('ready', function() {
console.log(bot.username + " - (" + bot.id + ")");
// Set discord status
if (messageHandler.mode == 1 && messageHandler.game){
messageHandler.setBotOnline(messageHandler.game.config.prettyName);
}
else{
messageHandler.setBotIdle();
}
});
bot.on('message', function(user, userID, channelID, message, event) {
messageHandler.onMessage(user, userID, channelID, message, event);
});
bot.on('disconnect', function(errMsg, code) {
bot.connect();
});
| const MessageHandler = require("./MessageHandler.js");
var appConfig = require("./config.json");
var Discord = require('discord.io');
// Create Discord Bot (based on token in config)
var bot = new Discord.Client({
token: appConfig.api.discord.token,
autorun: true
});
// Handler that will take messages and pass them through to Frotz
var messageHandler = new MessageHandler(bot);
process.on('exit', function(){
// gracefully clean up connection to Discord
bot.disconnect();
// we need to close the game so there is not a lingering child process
// running in the background
messageHandler.closeGame();
});
bot.on('ready', function() {
console.log(bot.username + " - (" + bot.id + ")");
});
bot.on('message', function(user, userID, channelID, message, event) {
messageHandler.onMessage(user, userID, channelID, message, event);
});
bot.on('disconnect', function(errMsg, code) {
bot.connect();
if (messageHandler.mode == 1 && messageHandler.game){
messageHandler.setBotOnline(messageHandler.game.config.prettyName);
}
else{
messageHandler.setBotIdle();
}
});
|
Add Webrecorder to short description | #!/usr/bin/env python
from setuptools import setup
with open('README.md', 'r') as readme_f:
long_description = readme_f.read()
setup(
name='py-wasapi-client',
version='1.1.0',
url='https://github.com/unt-libraries/py-wasapi-client',
author='University of North Texas Libraries',
author_email='lauren.ko@unt.edu',
license='BSD',
py_modules=['wasapi_client'],
scripts=['wasapi_client.py'],
description='A client for the Archive-It and Webrecorder WASAPI Data Transer API',
long_description=long_description,
long_description_content_type='text/markdown',
install_requires=['requests>=2.18.1'],
entry_points={
'console_scripts': [
'wasapi-client=wasapi_client:main'
]
},
setup_requires=['pytest-runner'],
tests_require=['pytest'],
classifiers=[
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Communications :: File Sharing',
],
)
| #!/usr/bin/env python
from setuptools import setup
with open('README.md', 'r') as readme_f:
long_description = readme_f.read()
setup(
name='py-wasapi-client',
version='1.1.0',
url='https://github.com/unt-libraries/py-wasapi-client',
author='University of North Texas Libraries',
author_email='lauren.ko@unt.edu',
license='BSD',
py_modules=['wasapi_client'],
scripts=['wasapi_client.py'],
description='A client for the [Archive-It] WASAPI Data Transer API',
long_description=long_description,
long_description_content_type='text/markdown',
install_requires=['requests>=2.18.1'],
entry_points={
'console_scripts': [
'wasapi-client=wasapi_client:main'
]
},
setup_requires=['pytest-runner'],
tests_require=['pytest'],
classifiers=[
'Intended Audience :: System Administrators',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Communications :: File Sharing',
],
)
|
Make sure version is initialized | import libsinan
from libsinan import handler, output, jsax
class VersionCheckTaskHandler(output.SimpleTaskHandler):
def __init__(self):
output.SimpleTaskHandler.__init__(self)
self.version = None
def object_end(self):
""" We only get one object per right now so
lets print it out when we get it """
if self.task == "version":
if self.event_type == 'info':
self.version = self.desc
return True
else:
return output.SimpleTaskHandler.object_end(self)
class VersionCheckHandler(handler.Handler):
def handles(self, task):
return task == "version"
def handle(self, largs):
self.do_request(largs, handle)
version = None
def handle(task, conn):
global version
if conn.status == 200:
try:
task_handler = VersionCheckTaskHandler()
jsax.parse(conn, task_handler)
version = task_handler.version
return 0
except ValueError, msg:
print "Got an error back from sinan. Check the logs at ~/.sinan/logs/kernel.log"
else:
return 1
| import libsinan
from libsinan import handler, output, jsax
class VersionCheckTaskHandler(output.SimpleTaskHandler):
def object_end(self):
""" We only get one object per right now so
lets print it out when we get it """
if self.task == "version":
if self.event_type == 'info':
self.version = self.desc
return True
else:
return output.SimpleTaskHandler.object_end(self)
class VersionCheckHandler(handler.Handler):
def handles(self, task):
return task == "version"
def handle(self, largs):
self.do_request(largs, handle)
version = None
def handle(task, conn):
global version
if conn.status == 200:
try:
task_handler = VersionCheckTaskHandler()
jsax.parse(conn, task_handler)
version = task_handler.version
return 0
except ValueError, msg:
print "Got an error back from sinan. Check the logs at ~/.sinan/logs/kernel.log"
else:
return 1
|
Fix test by allowing empty index | import _ from 'underscore'
import search from 'api/lib/elasticsearch.coffee'
import { matchAll } from 'api/apps/search/queries'
const { NODE_ENV } = process.env
// GET /api/search
export const index = (req, res, next) => {
const env = NODE_ENV === 'production' ? 'production' : 'staging'
let index = ''
if (req.query.type) {
index = _.map(req.query.type.split(','), term => {
return `${term}_${env}`
}).join(',')
}
search.client.search({
index,
body: {
query: matchAll(req.query.term)
}},
(error, response) => {
if (error) {
return console.log(`nothing matched for: ${req.query.term}`)
}
return res.send(response.hits)
}
)
}
| import _ from 'underscore'
import search from 'api/lib/elasticsearch.coffee'
import { matchAll } from 'api/apps/search/queries'
const { NODE_ENV } = process.env
// GET /api/search
export const index = (req, res, next) => {
const env = NODE_ENV === 'production' ? 'production' : 'staging'
const index = _.map(req.query.type.split(','), term => {
return `${term}_${env}`
}).join(',')
search.client.search({
index,
body: {
query: matchAll(req.query.term)
}},
(error, response) => {
if (error) {
return console.log(`nothing matched for: ${req.query.term}`)
}
return res.send(response.hits)
}
)
}
|
Add support for the [img] tag. | from django.http import HttpResponse
from django.shortcuts import render
from django.db import connections
import bbcode
def bbcode_img(tag_name, value, options, parent, context):
if tag_name in options and 'x' in options[tag_name]:
options['width'], options['height'] = options[tag_name].split('x', 1)
del options[tag_name]
attrs = ' '.join([name+'="{}"' for name in options.keys()])
return ('<img src="{}" '+attrs+' />').format(value, *options.values())
bbcode_parser = bbcode.Parser()
bbcode_parser.add_formatter("img", bbcode_img, replace_links=False)
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
def all_news(request):
cursor = connections['mybb'].cursor()
cursor.execute("SELECT * FROM mybb_threads JOIN mybb_posts WHERE firstpost=mybb_posts.pid AND mybb_threads.fid=%s AND mybb_threads.visible=1", [3])
articles = dictfetchall(cursor)
for article in articles:
article['html'] = bbcode_parser.format(article['message'])
return render(request, 'news_listing.html', dict(articles=articles))
| from django.http import HttpResponse
from django.shortcuts import render
from django.db import connections
import bbcode
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
def all_news(request):
cursor = connections['mybb'].cursor()
cursor.execute("SELECT * FROM mybb_threads JOIN mybb_posts WHERE firstpost=mybb_posts.pid AND mybb_threads.fid=%s AND mybb_threads.visible=1", [3])
articles = dictfetchall(cursor)
for article in articles:
article['html'] = bbcode.render_html(article['message'])
return render(request, 'news_listing.html', dict(articles=articles))
|
Fix navigition links a bit again | import datetime
from sqlalchemy import desc
from application import db
class Page(db.Model):
__tablename__ = 'page'
id = db.Column(db.Integer, primary_key=True)
path = db.Column(db.String(256), unique=True)
revisions = db.relationship('PageRevision', backref='page', lazy='dynamic')
def __init__(self, path):
self.path = path
def get_most_recent(self):
revision = PageRevision.query.filter(PageRevision.page_id == self.id)
revision = revision.order_by(PageRevision.timestamp.desc()).first()
if revision is not None:
revision.path = self.path
return revision
class PageRevision(db.Model):
__tablename__ = 'page_revision'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(128))
content = db.Column(db.Text)
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
page_id = db.Column(db.Integer, db.ForeignKey('page.id'))
def __init__(self, page, author, title, content,
timestamp=datetime.datetime.utcnow()):
self.title = title
self.path = ''
self.content = content
self.user_id = author.id
self.page_id = page.id
self.timestamp = timestamp
| import datetime
from sqlalchemy import desc
from application import db
class Page(db.Model):
__tablename__ = 'page'
id = db.Column(db.Integer, primary_key=True)
path = db.Column(db.String(256), unique=True)
revisions = db.relationship('PageRevision', backref='page', lazy='dynamic')
def __init__(self, path):
self.path = path
def get_most_recent(self):
revision = PageRevision.query.filter(PageRevision.page_id == self.id)
revision = revision.order_by(PageRevision.timestamp.desc()).first()
revision.path = self.path
return revision
class PageRevision(db.Model):
__tablename__ = 'page_revision'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(128))
content = db.Column(db.Text)
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
page_id = db.Column(db.Integer, db.ForeignKey('page.id'))
def __init__(self, page, author, title, content,
timestamp=datetime.datetime.utcnow()):
self.title = title
self.path = ''
self.content = content
self.user_id = author.id
self.page_id = page.id
self.timestamp = timestamp
|
Add test for Ops is associative | <?php
require_once(__DIR__ . '/../../opensrs/openSRS_loader.php');
class openSRS_OpsTest extends PHPUnit_Framework_TestCase
{
/**
* Should convert specials chars, & encode in utf8
*
* @return void
*/
public function testQuoteXMLChars()
{
$ops = new openSRS_ops;
$data = 'This is my & < > \' " string';
$result = $ops->_quoteXMLChars($data);
/// chars should be converted
$this->assertEquals($result, 'This is my & < > ' " string');
// should be utf8
$this->assertTrue(mb_check_encoding($result, 'UTF-8'));
}
/**
* Should return true for associative, and false for plain
*
* @return void
*/
public function testIsAssoc()
{
$ops = new openSRS_ops;
$no = array(1, 2, 3, 4);
$yes = array('this' => 'is', 'associative');
$this->assertfalse($ops->_is_assoc($no));
$this->assertTrue($ops->_is_assoc($yes));
}
}
| <?php
require_once(__DIR__ . '/../../opensrs/openSRS_loader.php');
class openSRS_OpsTest extends PHPUnit_Framework_TestCase
{
/**
* Should convert specials chars, & encode in utf8
*
* @return void
*/
public function testQuoteXMLChars()
{
$ops = new openSRS_ops;
$data = 'This is my & < > \' " string';
$result = $ops->_quoteXMLChars($data);
/// chars should be converted
$this->assertEquals($result, 'This is my & < > ' " string');
// should be utf8
$this->assertTrue(mb_check_encoding($result, 'UTF-8'));
}
}
|
Add next page response test | import Ember from 'ember';
import {
module,
test
} from 'qunit';
import startApp from 'superhero/tests/helpers/start-app';
import data from '../fixtures/characters';
var application, server;
module('Acceptance: Characters', {
beforeEach: function() {
application = startApp();
var characters = data();
server = new Pretender(function() {
this.get('/v1/public/characters', function(request) {
var responseData = JSON.stringify(characters);
return [
200,
{"Content-Type": "application/json"},
responseData
];
});
});
},
afterEach: function() {
Ember.run(application, 'destroy');
}
});
test('visiting /characters should show a list of characters', function(assert) {
visit('/characters');
andThen(function() {
assert.equal(currentURL(), '/characters');
assert.equal(find('div.character-card').length, 20, 'The page should have 20 characters');
});
});
test('Clicking the next page button should load a new page of characters', function(assert) {
visit('/characters');
andThen(function() {
click('button.button-next-page');
});
andThen(function() {
assert.equal(currentURL(), '/characters?offset=20');
assert.equal(find('div.character-card').length, 20, 'The page should have 20 characters');
});
});
| import Ember from 'ember';
import {
module,
test
} from 'qunit';
import startApp from 'superhero/tests/helpers/start-app';
import data from '../fixtures/characters';
var application, server;
module('Acceptance: Characters', {
beforeEach: function() {
application = startApp();
var characters = data();
server = new Pretender(function() {
this.get('/v1/public/characters', function(request) {
return [
200,
{"Content-Type": "application/json"},
JSON.stringify(characters)
];
});
});
},
afterEach: function() {
Ember.run(application, 'destroy');
}
});
test('visiting /characters should show a list of characters', function(assert) {
visit('/characters');
andThen(function() {
assert.equal(currentURL(), '/characters');
assert.equal(find('div.character-card').length, 20, 'The page should have 20 characters');
});
});
test('Clicking the next page button should load a new page of characters', function(assert) {
visit('/characters');
andThen(function() {
click('button.button-next-page');
});
andThen(function() {
assert.equal(currentURL(), '/characters?offset=20');
});
});
|
Modify production url for github hosting | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'eapp',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
sassOptions: {
includePaths: ['bower_components/materialize/sass']
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.baseURL = 'http://vysakh0.github.io/hooli/';
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'eapp',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
sassOptions: {
includePaths: ['bower_components/materialize/sass']
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
Fix incorrect name of start command callback | /**
* NotificationService.java
*
* @author Johan
*/
package se.chalmers.watchme.notifications;
import java.util.Calendar;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class NotificationService extends Service {
private final IBinder binder = new ServiceBinder();
public class ServiceBinder extends Binder {
NotificationService getService() {
return NotificationService.this;
}
}
@Override
public IBinder onBind(Intent arg0) {
return this.binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startID) {
Log.i("Custom", "Received start id " + startID + ": " + intent);
// This service is sticky - it runs until it's stopped.
return START_STICKY;
}
public void setAlarm(Calendar c) {
Log.i("Custom", "Set alarm");
// Start a new task for the alarm on another thread (separated from the UI thread)
new AlarmTask(this, c).run();
}
}
| /**
* NotificationService.java
*
* @author Johan
*/
package se.chalmers.watchme.notifications;
import java.util.Calendar;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class NotificationService extends Service {
private final IBinder binder = new ServiceBinder();
public class ServiceBinder extends Binder {
NotificationService getService() {
return NotificationService.this;
}
}
@Override
public IBinder onBind(Intent arg0) {
return this.binder;
}
public int startCommand(Intent intent, int flags, int startID) {
// This service is sticky - it runs until it's stopped.
return START_STICKY;
}
public void setAlarm(Calendar c) {
// Start a new task for the alarm on another thread (separated from the UI thread)
new AlarmTask(this, c).run();
}
}
|
Use a instead of as input to inspect | var num = 0;
module.exports.inspect = (a) => {
console.log('INSPECTOR #', ++num);
console.log(a);
return a;
};
const pluckUser = module.exports.pluckUser = (user) =>
({
id: user.id,
fbId: user.facebook_id,
firstName: user.first_name,
lastName: user.last_name,
description: user.description,
photoUrl: user.photo_url,
});
module.exports.pluckUsers = (users) =>
users.map((user) => pluckUser(user));
module.exports.pluckLanguages = (offerOrLearnResults) =>
({
canTeach: offerOrLearnResults[0],
willLearn: offerOrLearnResults[1],
});
module.exports.pluckMatches = (matchesResults) => (
matchesResults.map(matchResult => (
{
id: matchResult.teach_id,
firstName: matchResult.teach_first,
lastName: matchResult.teach_last,
description: matchResult.teach_description,
photoUrl: matchResult.teach_url,
fbId: matchResult.teach_facebook_id,
}
))
);
| var num = 0;
module.exports.inspect = (i) => {
console.log('INSPECTOR #', ++num);
console.log(i);
return i;
};
const pluckUser = module.exports.pluckUser = (user) =>
({
id: user.id,
fbId: user.facebook_id,
firstName: user.first_name,
lastName: user.last_name,
description: user.description,
photoUrl: user.photo_url,
});
module.exports.pluckUsers = (users) =>
users.map((user) => pluckUser(user));
module.exports.pluckLanguages = (offerOrLearnResults) =>
({
canTeach: offerOrLearnResults[0],
willLearn: offerOrLearnResults[1],
});
module.exports.pluckMatches = (matchesResults) => (
matchesResults.map(matchResult => (
{
id: matchResult.teach_id,
firstName: matchResult.teach_first,
lastName: matchResult.teach_last,
description: matchResult.teach_description,
photoUrl: matchResult.teach_url,
fbId: matchResult.teach_facebook_id,
}
))
);
|
Remove debug of ui router state changes. | (function (module) {
module.controller('projectListProcess', projectListProcess);
projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"];
function projectListProcess(processes, project, $state, mcmodal, $filter) {
var ctrl = this;
ctrl.viewProcess = viewProcess;
ctrl.chooseTemplate = chooseTemplate;
ctrl.processes = processes;
ctrl.project = project;
if (ctrl.processes.length !== 0) {
ctrl.processes = $filter('orderBy')(ctrl.processes, 'name');
ctrl.current = ctrl.processes[0];
$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
}
///////////////////////////////////
function viewProcess(process) {
ctrl.current = process;
$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
}
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project);
}
}
}(angular.module('materialscommons')));
| (function (module) {
module.controller('projectListProcess', projectListProcess);
projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"];
function projectListProcess(processes, project, $state, mcmodal, $filter) {
console.log('projectListProcess');
var ctrl = this;
ctrl.viewProcess = viewProcess;
ctrl.chooseTemplate = chooseTemplate;
ctrl.processes = processes;
ctrl.project = project;
if (ctrl.processes.length !== 0) {
console.log(' ctrl.processes.length !== 0');
ctrl.processes = $filter('orderBy')(ctrl.processes, 'name');
ctrl.current = ctrl.processes[0];
//$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
}
///////////////////////////////////
function viewProcess(process) {
ctrl.current = process;
$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id});
}
function chooseTemplate() {
mcmodal.chooseTemplate(ctrl.project);
}
}
}(angular.module('materialscommons')));
|
ADD MISSING FILE TO PREV COMMIT "modify BMC plugin: overwrite URL for CC-BY license. We have a MORE specific URL (from the license statement on the BMC pages) than the Open Definition one" | import requests
from copy import deepcopy
from datetime import datetime
from isitopenaccess.plugins import string_matcher
def page_license(record):
"""
To respond to the provider identifier: http://www.biomedcentral.com
This should determine the licence conditions of the BMC article and populate
the record['bibjson']['license'] (note the US spelling) field.
"""
# licensing statements to look for on this publisher's pages
# take the form of {statement: meaning}
# where meaning['type'] identifies the license (see licenses.py)
# and meaning['version'] identifies the license version (if available)
lic_statements = [
{"This is an Open Access article distributed under the terms of the Creative Commons Attribution License (<a href='http://creativecommons.org/licenses/by/2.0'>http://creativecommons.org/licenses/by/2.0</a>), which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited.":
{'type': 'cc-by', 'version':'2.0', 'open_access': True, 'BY': True, 'NC': False, 'SA': False, 'ND': False,
# also declare some properties which override info about this license in the licenses list (see licenses module)
'url': 'http://creativecommons.org/licenses/by/2.0'}
}
]
string_matcher.simple_extract(lic_statements, record)
| import requests
from copy import deepcopy
from datetime import datetime
from isitopenaccess.plugins import string_matcher
def page_license(record):
"""
To respond to the provider identifier: http://www.biomedcentral.com
This should determine the licence conditions of the BMC article and populate
the record['bibjson']['license'] (note the US spelling) field.
"""
# licensing statements to look for on this publisher's pages
# take the form of {statement: meaning}
# where meaning['type'] identifies the license (see licenses.py)
# and meaning['version'] identifies the license version (if available)
lic_statements = [
{"This is an Open Access article distributed under the terms of the Creative Commons Attribution License (<a href='http://creativecommons.org/licenses/by/2.0'>http://creativecommons.org/licenses/by/2.0</a>), which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited.":
{'type': 'cc-by', 'version':'2.0', 'open_access': True, 'BY': True, 'NC': False, 'SA': False, 'ND': False}
}
]
string_matcher.simple_extract(lic_statements, record)
|
Correct shuffle not to be in place. | /* exported catane */
/* Manual define exports since JS Hint does not handle well generators */
const DICE_DISTRIBUTION = [ 11, 3, 6, 5, 4, 9, 10, 8, 4, 11, 12, 9, 10, 8, 3, 6, 2, 5 ];
/**
* Creates a new array with given values in randome order
* @param {[Array]} values values to randomize
* @return {[Array]} array of values in random order
*/
function shuffle(values) {
var currentIndex = values.length, randomIndex ;
var array = [];
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
array[currentIndex] = values[randomIndex];
array[randomIndex] = values[currentIndex];
}
return array;
}
export function *catane() {
var values = DICE_DISTRIBUTION;
var index = 0;
for (;;) {
if (index >= values.length) {
values = shuffle(DICE_DISTRIBUTION);
index = 0;
}
yield values[index];
index += 1;
}
} | /* exported catane */
/* Manual define exports since JS Hint does not handle well generators */
const DICE_DISTRIBUTION = [ 11, 3, 6, 5, 4, 9, 10, 8, 4, 11, 12, 9, 10, 8, 3, 6, 2, 5 ];
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex ;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
export function *catane() {
var values = DICE_DISTRIBUTION;
var index = 0;
for (;;) {
if (index >= values.length) {
values = shuffle(DICE_DISTRIBUTION);
index = 0;
}
yield values[index];
index += 1;
}
} |
Check that the directory exists before creating log file. | "use strict";
var fs = require('fs');
var util = require('util');
var path = require('path');
var config = require('./config');
var log_path = config.logDir;
var log_name = new Date().toISOString();
var log_stdout = process.stdout;
var log_file;
try {
var log_file_name = util.format("%s/%s.log", log_path, log_name);
ensureDirectoryExistence(log_file_name);
log_file = fs.createWriteStream(log_file_name, {flags: 'w'}); //__dirname + '/debug.log'
} catch (e){
process.stderr.write("Exception creating log file write stream: " + util.inspect(e));
}
var date = new Date();
console.log = function(d) {
if(log_file){
log_file.write(date.now().toISOString() + ": " + util.format(d) + '\n');
}
log_stdout.write(util.format(d) + '\n');
};
function ensureDirectoryExistence(filePath) {
var dirname = path.dirname(filePath);
if (directoryExists(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
function directoryExists(path) {
try {
return fs.statSync(path).isDirectory();
}
catch (err) {
return false;
}
} | "use strict";
var fs = require('fs');
var util = require('util');
var config = require('./config');
var log_path = config.logDir;
var log_name = new Date().toISOString();
var log_stdout = process.stdout;
var log_file;
try {
log_file = fs.createWriteStream(util.format("%s/%s.log", log_path, log_name), {flags: 'w'}); //__dirname + '/debug.log'
} catch (e){
process.stderr.write("Exception creating log file write stream: " + util.inspect(e));
}
var date = new Date();
console.log = function(d) {
if(log_file){
log_file.write(date.now().toISOString() + ": " + util.format(d) + '\n');
}
log_stdout.write(util.format(d) + '\n');
}; |
Fix how we find conversion to use file formats | from . import conversions
from .file_formats import FileFormats
class FileConverter(object):
def get_conversion(self, source_format, target_format):
return {
FileFormats.PDF: conversions.NoOp,
FileFormats.JPEG: conversions.JpegToPdf,
FileFormats.PNG: conversions.PngToPdf,
FileFormats.GIF: conversions.GifToPdf,
FileFormats.TIFF: conversions.TiffToPdf,
FileFormats.TXT: conversions.TextToPdf,
FileFormats.DOCX: conversions.DocxToPdf,
FileFormats.DOC: conversions.DocToPdf,
FileFormats.PPTX: conversions.PptxToPdf,
FileFormats.PPT: conversions.PptToPdf,
FileFormats.ODT: conversions.OdtToPdf,
FileFormats.RTF: conversions.RtfToPdf,
}[source_format]()
| from . import conversions
from .file_formats import FileFormats
class FileConverter(object):
def get_conversion(self, source_format, target_format):
return {
'application/pdf': conversions.NoOp,
'image/jpeg': conversions.JpegToPdf,
'image/png': conversions.PngToPdf,
'image/gif': conversions.GifToPdf,
'image/tiff': conversions.TiffToPdf,
'text/plain': conversions.TextToPdf,
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': conversions.DocxToPdf,
'application/msword': conversions.DocToPdf,
'application/vnd.openxmlformats-officedocument.presentationml.presentation': conversions.PptxToPdf,
'application/vnd.ms-powerpoint': conversions.PptToPdf,
'application/vnd.oasis.opendocument.text': conversions.OdtToPdf,
'application/rtf': conversions.RtfToPdf,
}[source_format]()
|
Drop Sort alias for Collect. | // setup transform definition aliases
import {definition} from 'vega-dataflow';
definition('Formula', definition('Apply'));
export {default as parse} from './src/parse';
export {default as selector} from './src/parsers/event-selector';
export {default as signal} from './src/parsers/signal';
export {default as signalUpdates} from './src/parsers/signal-updates';
export {default as stream} from './src/parsers/stream';
export {
MarkRole,
FrameRole,
ScopeRole,
AxisRole,
AxisDomainRole,
AxisGridRole,
AxisLabelRole,
AxisTickRole,
AxisTitleRole,
LegendRole,
LegendEntryRole,
LegendLabelRole,
LegendSymbolRole,
LegendTitleRole
} from './src/parsers/marks/roles';
export {marktypes, isMarkType} from './src/parsers/marks/marktypes';
export {default as Scope} from './src/Scope';
export {default as DataScope} from './src/DataScope';
| // setup transform definition aliases
import {definition} from 'vega-dataflow';
definition('Sort', definition('Collect'));
definition('Formula', definition('Apply'));
export {default as parse} from './src/parse';
export {default as selector} from './src/parsers/event-selector';
export {default as signal} from './src/parsers/signal';
export {default as signalUpdates} from './src/parsers/signal-updates';
export {default as stream} from './src/parsers/stream';
export {
MarkRole,
FrameRole,
ScopeRole,
AxisRole,
AxisDomainRole,
AxisGridRole,
AxisLabelRole,
AxisTickRole,
AxisTitleRole,
LegendRole,
LegendEntryRole,
LegendLabelRole,
LegendSymbolRole,
LegendTitleRole
} from './src/parsers/marks/roles';
export {marktypes, isMarkType} from './src/parsers/marks/marktypes';
export {default as Scope} from './src/Scope';
export {default as DataScope} from './src/DataScope';
|
Send regular ping on SSE channel
Otherwise dead clients stay around for a very long time (they are
only detected and removed when sending data fails, and that used to
depend on new emails arriving). | from flask import current_app
from gevent.queue import Empty, Queue
clients = set()
def broadcast(event, data=None):
for q in clients:
q.put((event, data))
def handle_sse_request():
return current_app.response_class(_gen(), mimetype='text/event-stream')
def _gen():
yield _sse('connected')
q = Queue()
clients.add(q)
while True:
try:
msg = q.get(timeout=60)
except Empty:
yield _sse('ping')
continue
try:
yield _sse(*msg)
except GeneratorExit:
clients.remove(q)
raise
def _sse(event, data=None):
parts = [f'event: {event}', f'data: {data or ""}']
return ('\r\n'.join(parts) + '\r\n\r\n').encode()
| from flask import current_app
from gevent.queue import Queue
clients = set()
def broadcast(event, data=None):
for q in clients:
q.put((event, data))
def handle_sse_request():
return current_app.response_class(_gen(), mimetype='text/event-stream')
def _gen():
yield _sse('connected')
q = Queue()
clients.add(q)
while True:
msg = q.get()
try:
yield _sse(*msg)
except GeneratorExit:
clients.remove(q)
raise
def _sse(event, data=None):
parts = [f'event: {event}', f'data: {data or ""}']
return ('\r\n'.join(parts) + '\r\n\r\n').encode()
|
Mark abstract since it isn't separately runnable | package edu.northwestern.bioinformatics.studycalendar.web;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.springframework.mock.web.MockServletContext;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* @author Rhett Sutphin
*/
public abstract class WebTestCase extends StudyCalendarTestCase {
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
protected MockServletContext servletContext;
protected MockHttpSession session;
protected void setUp() throws Exception {
super.setUp();
servletContext = new MockServletContext();
session = new MockHttpSession(servletContext);
request = new MockHttpServletRequest(servletContext);
request.setMethod("POST");
request.setSession(session);
response = new MockHttpServletResponse();
}
}
| package edu.northwestern.bioinformatics.studycalendar.web;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.springframework.mock.web.MockServletContext;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* @author Rhett Sutphin
*/
public class WebTestCase extends StudyCalendarTestCase {
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
protected MockServletContext servletContext;
protected MockHttpSession session;
protected void setUp() throws Exception {
super.setUp();
servletContext = new MockServletContext();
session = new MockHttpSession(servletContext);
request = new MockHttpServletRequest(servletContext);
request.setMethod("POST");
request.setSession(session);
response = new MockHttpServletResponse();
}
}
|
Check file listing loads in E2E test. | var assert = require('assert');
describe("Basic Test", function(){
it("Loads the basic demo page and sends values to server", function(){
browser.url('http://localhost:7888/src/e2e-tests/basic-demo-page?auto-activate-glasswing')
browser.waitUntil(function () {
var a = browser.execute(function(){
return window.a
}).value
return a == 25;
}, 20000, 'expected a to be set to 25 by the page')
browser.waitUntil(function () {
var a = browser.execute(function(){
return window.__jscb.recordedValueBuffer.length
}).value
console.log("length", a)
return a == 0;
}, 20000, 'expected values to be sent to server and value buffer to be reset');
})
it("Shows simple.js in the Glasswing file listing", function(){
browser.url('http://localhost:9500')
var fileLinksTable = $(".file-links")
fileLinksTable.waitForExist(5000)
var jsFilePath = "http://localhost:7888/src/e2e-tests/basic-demo-page/basic-demo.js"
assert(fileLinksTable.getText().indexOf(jsFilePath) !== -1)
})
})
}) | var assert = require('assert');
describe("Basic Test", function(){
it("Loads the basic demo page and sends values to server", function(){
browser.url('http://localhost:7888/src/e2e-tests/basic-demo-page?auto-activate-glasswing')
browser.waitUntil(function () {
var a = browser.execute(function(){
return window.a
}).value
return a == 25;
}, 30000, 'expected a to be set to 25 by the page')
browser.waitUntil(function () {
var a = browser.execute(function(){
return window.__jscb.recordedValueBuffer.length
}).value
console.log("length", a)
return a == 0;
}, 30000, 'expected values to be sent to server and value buffer to be reset');
})
}) |
Add a todo for interfaces | package net.kencochrane.raven.event.interfaces;
import java.util.Map;
//TODO: Change interfaces so they do not behave like pre-made JSON objects
//Instead the encoder should take care of interpreting each interface in a specific way (more code, but more sensible).
public interface SentryInterface {
/**
* Gets the unique name of the interface.
*
* @return name of the interface.
*/
String getInterfaceName();
/**
* Gets the content of the interface as a Map.
* <p>
* The values contained in the Map can only be:
* <ul>
* <li>A {@code String}</li>
* <li>A wrapped primitive</li>
* <li>A {@code Collection<String>}</li>
* <li>A {@code Map<String, V>} where {@code V} is one of the types currently listed</li>
* </ul>
* </p>
*
* @return the content of the interface.
*/
Map<String, Object> getInterfaceContent();
}
| package net.kencochrane.raven.event.interfaces;
import java.util.Map;
public interface SentryInterface {
/**
* Gets the unique name of the interface.
*
* @return name of the interface.
*/
String getInterfaceName();
/**
* Gets the content of the interface as a Map.
* <p>
* The values contained in the Map can only be:
* <ul>
* <li>A {@code String}</li>
* <li>A wrapped primitive</li>
* <li>A {@code Collection<String>}</li>
* <li>A {@code Map<String, V>} where {@code V} is one of the types currently listed</li>
* </ul>
* </p>
*
* @return the content of the interface.
*/
Map<String, Object> getInterfaceContent();
}
|
Disable eslint for this for now. | // eslint-disable
export default function skipSpace() {
// https://github.com/ternjs/acorn/blob/master/src/tokenize.js#L100-L116
return function ha(endSign) {
const endS = endSign ? endSign : '*/';
let startLoc = this.options.onComment && this.curPosition();
let start = this.pos,
end = this.input.indexOf(endS, this.pos += endS.length);
if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
this.pos = end + endS.length;
if (this.options.locations) {
lineBreakG.lastIndex = start
let match
while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
++this.curLine
this.lineStart = match.index + match[0].length
}
}
if (this.options.onComment)
this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
startLoc, this.curPosition())
};
}
| export default function skipSpace() {
// https://github.com/ternjs/acorn/blob/master/src/tokenize.js#L100-L116
return function ha(endSign) {
const endS = endSign ? endSign : '*/';
let startLoc = this.options.onComment && this.curPosition();
let start = this.pos, end = this.input.indexOf(endS, this.pos += endS.length);
if (end === -1) this.raise(this.pos - 2, "Unterminated comment")
this.pos = end + endS.length
if (this.options.locations) {
lineBreakG.lastIndex = start
let match
while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
++this.curLine
this.lineStart = match.index + match[0].length
}
}
if (this.options.onComment)
this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
startLoc, this.curPosition())
};
}
|
Include dynamic file name link | <?php
date_default_timezone_set('America/Chicago');
$dir = $_SERVER['DOCUMENT_ROOT'];
$file = $_FILES['uploadedfile']['tmp_name'];
$names = $_FILES['uploadedfile']['name'];
$target = $dir.'/In/'.$names;
move_uploaded_file( $_FILES['uploadedfile']['tmp_name'], $target);
$command = escapeshellcmd("python2.7 read.py $target");
exec($command, $output);
echo "<pre>";
echo "something";
echo $output[0];
echo '<a href="'.$output[0].'">Download Report</a>';
echo "</pre>";
// Re-route to directory to download the file.
// $domain = $_SERVER['HTTP_HOST'];
// $path = implode("/",$fullPath);
// $toLogin = 'http://'.$domain.$path."/out";
// header('Location:'.$toLogin);
?> | <?php
date_default_timezone_set('America/Chicago');
$dir = $_SERVER['DOCUMENT_ROOT'];
$file = $_FILES['uploadedfile']['tmp_name'];
$names = $_FILES['uploadedfile']['name'];
$target = $dir.'/In/'.$names;
move_uploaded_file( $_FILES['uploadedfile']['tmp_name'], $target);
$command = escapeshellcmd("python2.7 read.py $target");
exec($command, $output);
echo "<pre>";
echo "something";
echo $output;
echo '<a href="yup'.$output['file'].'">Download Report</a>';
echo "</pre>";
// Re-route to directory to download the file.
// $domain = $_SERVER['HTTP_HOST'];
// $path = implode("/",$fullPath);
// $toLogin = 'http://'.$domain.$path."/out";
// header('Location:'.$toLogin);
?> |
Fix double-click login button issue | import React from 'react';
import { ScrollView } from 'react-native';
import UserAccount from './UserAccount';
import CardPreferences from './CardPreferences';
import css from '../../styles/css';
// View for user to manage preferences, including which cards are visible
class PreferencesView extends React.Component {
constructor(props) {
super(props);
this.state = {
scrollEnabled: true
};
}
toggleScroll = () => {
this.setState({ scrollEnabled: !this.state.scrollEnabled });
}
render() {
return (
<ScrollView
keyboardShouldPersistTaps={'handled'}
style={css.main_container}
scrollEnabled={this.state.scrollEnabled}
>
<UserAccount />
<CardPreferences
toggleScroll={this.toggleScroll}
/>
</ScrollView>
);
}
}
export default PreferencesView;
| import React from 'react';
import { ScrollView } from 'react-native';
import UserAccount from './UserAccount';
import CardPreferences from './CardPreferences';
import css from '../../styles/css';
// View for user to manage preferences, including which cards are visible
class PreferencesView extends React.Component {
constructor(props) {
super(props);
this.state = {
scrollEnabled: true
};
}
toggleScroll = () => {
this.setState({ scrollEnabled: !this.state.scrollEnabled });
}
render() {
return (
<ScrollView
style={css.main_container}
scrollEnabled={this.state.scrollEnabled}
>
<UserAccount />
<CardPreferences
toggleScroll={this.toggleScroll}
/>
</ScrollView>
);
}
}
export default PreferencesView;
|
Use Illuminate\Events\Dispatcher instead of contract
Laravel dispatcher should be either Illuminate\Contracts\Events\Dispatcher
or Illuminate\Events\Dispatcher, however only the latter has fire()
method, which in turn just a wrapper for dispatch()
Using fire() inplace with contract tests are failing with exceptions:
1. Tmdb\Laravel\Adapters\Tests\EventDispatcherTestLaravel5::it_dispatches_events_through_both_laravel_and_symfony
Prophecy\Exception\Doubler\MethodNotFoundException: Method `Double\Dispatcher\P25::fire()` is not defined.
2. Tmdb\Laravel\Adapters\Tests\EventDispatcherTestLaravel5::it_returns_the_event_returned_by_the_symfony_dispatcher
Prophecy\Exception\Doubler\MethodNotFoundException: Method `Double\Dispatcher\P27::fire()` not found. | <?php
/**
* @package php-tmdb\laravel
* @author Mark Redeman <markredeman@gmail.com>
* @copyright (c) 2014, Mark Redeman
*/
namespace Tmdb\Laravel\Adapters\Tests;
use Tmdb\Laravel\Adapters\EventDispatcherLaravel5 as AdapterDispatcher;
class EventDispatcherTestLaravel5 extends AbstractEventDispatcherTest
{
protected function createEventDispatcher()
{
$this->laravel = $this->prophesize('Illuminate\Events\Dispatcher');
$this->symfony = $this->prophesize('Symfony\Component\EventDispatcher\EventDispatcher');
return new AdapterDispatcher(
$this->laravel->reveal(),
$this->symfony->reveal()
);
}
} | <?php
/**
* @package php-tmdb\laravel
* @author Mark Redeman <markredeman@gmail.com>
* @copyright (c) 2014, Mark Redeman
*/
namespace Tmdb\Laravel\Adapters\Tests;
use Tmdb\Laravel\Adapters\EventDispatcherLaravel5 as AdapterDispatcher;
class EventDispatcherTestLaravel5 extends AbstractEventDispatcherTest
{
protected function createEventDispatcher()
{
$this->laravel = $this->prophesize('Illuminate\Contracts\Events\Dispatcher');
$this->symfony = $this->prophesize('Symfony\Component\EventDispatcher\EventDispatcher');
return new AdapterDispatcher(
$this->laravel->reveal(),
$this->symfony->reveal()
);
}
} |
Update service provider to use bindShared.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Optimize;
use Illuminate\Support\ServiceProvider;
class OptimizeServiceProvider 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.commands.optimize', function () {
$components = require __DIR__."/compile.php";
return new OptimizeCommand($components);
});
$this->commands('orchestra.commands.optimize');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.commands.optimize');
}
}
| <?php namespace Orchestra\Optimize;
use Illuminate\Support\ServiceProvider;
class OptimizeServiceProvider 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.commands.optimize'] = $this->app->share(function () {
$components = require __DIR__."/compile.php";
return new OptimizeCommand($components);
});
$this->commands('orchestra.commands.optimize');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.commands.optimize');
}
}
|
Fix for loading SiteMap entry on Spring 2.x | /*
* Created on 11-Jan-2006
*/
package uk.org.ponder.rsf.test.sitemap;
import java.util.HashMap;
import uk.org.ponder.rsf.bare.junit.PlainRSFTests;
import uk.org.ponder.rsf.viewstate.EntityCentredViewParameters;
import uk.org.ponder.rsf.viewstate.support.BasicViewParametersParser;
public class TestSiteMap extends PlainRSFTests {
public TestSiteMap() {
contributeConfigLocation("classpath:uk/org/ponder/rsf/test/sitemap/sitemap-context.xml");
}
public void testParseECVP() {
BasicViewParametersParser bvpp = (BasicViewParametersParser) applicationContext.getBean("viewParametersParser");
HashMap attrmap = new HashMap();
attrmap.put("flowtoken", "ec38f0");
EntityCentredViewParameters ecvp = (EntityCentredViewParameters) bvpp.parse("/recipe/3652/", attrmap);
System.out.println("ECVP for entity " + ecvp.entity.ID + " of type " + ecvp.entity.entityname);
}
}
| /*
* Created on 11-Jan-2006
*/
package uk.org.ponder.rsf.test.sitemap;
import java.util.HashMap;
import uk.org.ponder.rsf.bare.junit.PlainRSFTests;
import uk.org.ponder.rsf.viewstate.EntityCentredViewParameters;
import uk.org.ponder.rsf.viewstate.support.BasicViewParametersParser;
public class TestSiteMap extends PlainRSFTests {
public void testParseECVP() {
BasicViewParametersParser bvpp = (BasicViewParametersParser) applicationContext.getBean("viewParametersParser");
HashMap attrmap = new HashMap();
attrmap.put("flowtoken", "ec38f0");
EntityCentredViewParameters ecvp = (EntityCentredViewParameters) bvpp.parse("/recipe/3652/", attrmap);
System.out.println("ECVP for entity " + ecvp.entity.ID + " of type " + ecvp.entity.entityname);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.