text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
III-1783: Remove unnecessary dependency on Monolog | <?php
namespace CultuurNet\UDB3\Log;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
class ContextEnrichingLoggerTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function it_passes_additional_context_to_the_decorated_logger()
{
/** @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject $decoratedLogger */
$decoratedLogger = $this->createMock(LoggerInterface::class);
$additionalContext = array(
'job_id' => 1,
);
$logger = new ContextEnrichingLogger(
$decoratedLogger,
$additionalContext
);
$decoratedLogger->expects($this->once())
->method('log')
->with(
LogLevel::DEBUG,
'test',
[
'foo' => 'bar',
'job_id' => 1
]
);
$logger->log(
LogLevel::DEBUG,
'test',
[
'foo' => 'bar'
]
);
}
}
| <?php
/**
* @file
*/
namespace CultuurNet\UDB3\Log;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
class ContextEnrichingLoggerTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function it_passes_additional_context_to_the_decorated_logger()
{
/** @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject $decoratedLogger */
$decoratedLogger = $this->createMock(LoggerInterface::class);
$additionalContext = array(
'job_id' => 1,
);
$logger = new ContextEnrichingLogger(
$decoratedLogger,
$additionalContext
);
$decoratedLogger->expects($this->once())
->method('log')
->with(
Logger::DEBUG,
'test',
[
'foo' => 'bar',
'job_id' => 1
]
);
$logger->log(
Logger::DEBUG,
'test',
[
'foo' => 'bar'
]
);
}
}
|
Increase taskList performance by reducing queries | <?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* TaskListsRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class TaskListsRepository extends EntityRepository
{
public function findAll()
{
$today = new \DateTime();
return $this
->createQueryBuilder('tl')
->select('tl, t, a, c, w')
->leftJoin('tl.tasks', 't')
->leftJoin('tl.account', 'a')
->leftJoin('a.client', 'c')
->leftJoin('t.workLog', 'w')
->orderBy("tl.createdAt", "ASC")
->getQuery()
->getResult();
}
public function findAllWithActiveTasks()
{
$today = new \DateTime();
return $this
->createQueryBuilder('tl')
->select('tl, t')
->leftJoin('tl.tasks', 't')
->where('t.completedAt > :today')
->orWhere('t.completed <> true')
->addOrderBy("t.completed", "ASC")
->addOrderBy("t.order", "ASC")
->setParameter(':today', $today->format('Y-m-d'))
->getQuery()
->getResult();
}
public function search($searchTerm)
{
return $this
->createQueryBuilder('tl')
->select()
->where('tl.name LIKE :searchTerm')
->setParameter(":searchTerm", '%' . $searchTerm . '%')
->getQuery()
->getResult();
}
}
| <?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* TaskListsRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class TaskListsRepository extends EntityRepository
{
public function findAll()
{
$today = new \DateTime();
return $this
->createQueryBuilder('tl')
->select('tl, t')
->leftJoin('tl.tasks', 't')
->orderBy("tl.createdAt", "ASC")
->getQuery()
->getResult();
}
public function findAllWithActiveTasks()
{
$today = new \DateTime();
return $this
->createQueryBuilder('tl')
->select('tl, t')
->leftJoin('tl.tasks', 't')
->where('t.completedAt > :today')
->orWhere('t.completed <> true')
->addOrderBy("t.completed", "ASC")
->addOrderBy("t.order", "ASC")
->setParameter(':today', $today->format('Y-m-d'))
->getQuery()
->getResult();
}
public function search($searchTerm)
{
return $this
->createQueryBuilder('tl')
->select()
->where('tl.name LIKE :searchTerm')
->setParameter(":searchTerm", '%' . $searchTerm . '%')
->getQuery()
->getResult();
}
}
|
Add a NONE order option to sort order. | /*
* Copyright 2013 Franklin Bristow <[email protected]>.
*
* 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 ca.corefacility.bioinformatics.irida.model.enums;
/**
* When sorting a collection of generic objects you should be able to specify
* the order of the sort.
*
* @author Franklin Bristow <[email protected]>
*/
public enum Order {
ASCENDING("ASCENDING"),
DESCENDING("DESCENDING"),
NONE("NONE");
private String code;
private Order(String code) {
this.code = code;
}
@Override
public String toString() {
return code;
}
public static Order fromString(String code) {
switch (code.toUpperCase()) {
case "ASCENDING":
return ASCENDING;
case "DESCENDING":
return DESCENDING;
default:
return NONE;
}
}
}
| /*
* Copyright 2013 Franklin Bristow <[email protected]>.
*
* 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 ca.corefacility.bioinformatics.irida.model.enums;
/**
* When sorting a collection of generic objects you should be able to specify
* the order of the sort.
*
* @author Franklin Bristow <[email protected]>
*/
public enum Order {
ASCENDING("ASCENDING"),
DESCENDING("DESCENDING");
private String code;
private Order(String code) {
this.code = code;
}
@Override
public String toString() {
return code;
}
public static Order fromString(String code) {
switch (code.toUpperCase()) {
case "ASCENDING":
return ASCENDING;
case "DESCENDING":
return DESCENDING;
default:
throw new IllegalArgumentException("[" + code + "] is not a valid type of Order.");
}
}
}
|
Add some tests for stringport | """
Unittests for opal.utils
"""
from django.test import TestCase
from django.db.models import ForeignKey, CharField
from opal import utils
class StringportTestCase(TestCase):
def test_import(self):
import collections
self.assertEqual(collections, utils.stringport('collections'))
def test_import_no_period(self):
with self.assertRaises(ImportError):
utils.stringport('wotcha')
def test_import_perioded_thing(self):
self.assertEqual(TestCase, utils.stringport('django.test.TestCase'))
def test_empty_name_is_valueerror(self):
with self.assertRaises(ValueError):
utils.stringport('')
class ItersubclassesTestCase(TestCase):
def test_tree_structure(self):
class A(object):
pass
class B(A):
pass
class C(B, utils.AbstractBase):
pass
class D(C):
pass
results = {i for i in utils._itersubclasses(A)}
self.assertEqual(results, set([B, D]))
class FindTemplateTestCase(TestCase):
def test_find_template_first_exists(self):
self.assertEqual('base.html',
utils.find_template(['base.html', 'baser.html', 'basest.html']))
def test_find_template_one_exists(self):
self.assertEqual('base.html',
utils.find_template(['baser.html', 'base.html', 'basest.html']))
def test_find_template_none_exists(self):
self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
| """
Unittests for opal.utils
"""
from django.test import TestCase
from django.db.models import ForeignKey, CharField
from opal import utils
class StringportTestCase(TestCase):
def test_import(self):
import collections
self.assertEqual(collections, utils.stringport('collections'))
class ItersubclassesTestCase(TestCase):
def test_tree_structure(self):
class A(object):
pass
class B(A):
pass
class C(B, utils.AbstractBase):
pass
class D(C):
pass
results = {i for i in utils._itersubclasses(A)}
self.assertEqual(results, set([B, D]))
class FindTemplateTestCase(TestCase):
def test_find_template_first_exists(self):
self.assertEqual('base.html',
utils.find_template(['base.html', 'baser.html', 'basest.html']))
def test_find_template_one_exists(self):
self.assertEqual('base.html',
utils.find_template(['baser.html', 'base.html', 'basest.html']))
def test_find_template_none_exists(self):
self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
|
Add function name for debugging | "use strict";
module.exports = function(opts) {
opts.dbname = opts.dbname || 'yamb';
if (!opts.storage) {
// TODO: fix error message
throw new Error('error with storage');
}
const Yamb = require('./yamb')(opts);
return {
create: function create(data) {
let post = new Yamb();
return post.update(data);
},
fetch: function *fetch(params, options) {
options = options || {};
options.limit = 1;
let results = yield opts.storage.find(opts.dbname, params, options);
if (!results || results.length === 0) {
return false;
}
let post = new Yamb(results[0]);
return post;
},
fetchAll: function *fetchAll(params, options) {
let results = yield opts.storage.find(opts.dbname, params, options);
if (!results || results.length === 0) {
return false;
}
// TODO: replace Array to Map
let posts = [], post, i, length = results.length;
for (i=0; i<length; i++) {
post = new Yamb(results[i]);
posts.push(post);
}
return posts;
},
remove: function *remove(params) {
let results = yield opts.storage.remove(opts.dbname, params);
// TODO: remove all related posts
return results;
}
};
}; | "use strict";
module.exports = function(opts) {
opts.dbname = opts.dbname || 'yamb';
if (!opts.storage) {
// TODO: fix error message
throw new Error('error with storage');
}
const Yamb = require('./yamb')(opts);
return {
create: function(data) {
let post = new Yamb();
return post.update(data);
},
fetch: function *fetch(params, options) {
options = options || {};
options.limit = 1;
let results = yield opts.storage.find(opts.dbname, params, options);
if (!results || results.length === 0) {
return false;
}
let post = new Yamb(results[0]);
return post;
},
fetchAll: function *fetchAll(params, options) {
let results = yield opts.storage.find(opts.dbname, params, options);
if (!results || results.length === 0) {
return false;
}
// TODO: replace Array to Map
let posts = [], post, i, length = results.length;
for (i=0; i<length; i++) {
post = new Yamb(results[i]);
posts.push(post);
}
return posts;
},
remove: function *remove(params) {
let results = yield opts.storage.remove(opts.dbname, params);
// TODO: remove all related posts
return results;
}
};
}; |
Fix bug in handling arguments
Signed-off-by: Stefan Marr <[email protected]> | package som;
import java.util.Arrays;
public class VMOptions {
public static final String STANDARD_PLATFORM_FILE = "core-lib/Platform.som";
public static final String STANDARD_KERNEL_FILE = "core-lib/Kernel.som";
public String platformFile = STANDARD_PLATFORM_FILE;
public String kernelFile = STANDARD_KERNEL_FILE;
public final String[] args;
public final boolean showUsage;
public VMOptions(final String[] args) {
this.args = processVmArguments(args);
showUsage = args.length == 0;
}
private String[] processVmArguments(final String[] arguments) {
int currentArg = 0;
// parse optional --platform and --kernel, need to be the first arguments
boolean parsedArgument = true;
while (parsedArgument) {
if (currentArg >= arguments.length) {
return null;
} else {
if (arguments[currentArg].equals("--platform")) {
platformFile = arguments[currentArg + 1];
currentArg += 2;
} else if (arguments[currentArg].equals("--kernel")) {
kernelFile = arguments[currentArg + 1];
currentArg += 2;
} else {
parsedArgument = false;
}
}
}
// store remaining arguments
if (currentArg < arguments.length) {
return Arrays.copyOfRange(arguments, currentArg, arguments.length);
} else {
return null;
}
}
}
| package som;
import java.util.Arrays;
public class VMOptions {
public static final String STANDARD_PLATFORM_FILE = "core-lib/Platform.som";
public static final String STANDARD_KERNEL_FILE = "core-lib/Kernel.som";
public String platformFile = STANDARD_PLATFORM_FILE;
public String kernelFile = STANDARD_KERNEL_FILE;
public final String[] args;
public final boolean showUsage;
public VMOptions(final String[] args) {
this.args = processVmArguments(args);
showUsage = args.length == 0;
}
private String[] processVmArguments(final String[] arguments) {
int currentArg = 0;
// parse optional --platform and --kernel, need to be the first arguments
boolean parsedArgument = true;
while (parsedArgument) {
if (currentArg >= arguments.length) {
return arguments;
} else {
if (arguments[currentArg].equals("--platform")) {
platformFile = arguments[currentArg + 1];
currentArg += 2;
} else if (arguments[currentArg].equals("--kernel")) {
kernelFile = arguments[currentArg + 1];
currentArg += 2;
} else {
parsedArgument = false;
}
}
}
// store remaining arguments
if (currentArg < arguments.length) {
return Arrays.copyOfRange(arguments, currentArg, arguments.length);
} else {
return arguments;
}
}
}
|
Change marathon endpoint to groups | import ActionTypes from '../constants/ActionTypes';
var AppDispatcher = require('./AppDispatcher');
var Config = require('../config/Config');
var RequestUtil = require('../utils/RequestUtil');
module.exports = {
fetchApps: RequestUtil.debounceOnError(
Config.getRefreshRate(),
function (resolve, reject) {
return function () {
const embed = 'embed=group.groups&embed=group.apps&' +
'embed=group.apps.deployments&embed=group.apps.counts';
let url = `${Config.rootUrl}/marathon/v2/groups?${embed}`;
RequestUtil.json({
url: url,
success: function (response) {
AppDispatcher.handleServerAction({
type: ActionTypes.REQUEST_MARATHON_APPS_SUCCESS,
data: response
});
resolve();
},
error: function (e) {
AppDispatcher.handleServerAction({
type: ActionTypes.REQUEST_MARATHON_APPS_ERROR,
data: e.message
});
reject();
},
hangingRequestCallback: function () {
AppDispatcher.handleServerAction({
type: ActionTypes.REQUEST_MARATHON_APPS_ONGOING
});
}
});
};
},
{delayAfterCount: Config.delayAfterErrorCount}
)
};
| import ActionTypes from '../constants/ActionTypes';
var AppDispatcher = require('./AppDispatcher');
var Config = require('../config/Config');
var RequestUtil = require('../utils/RequestUtil');
module.exports = {
fetchApps: RequestUtil.debounceOnError(
Config.getRefreshRate(),
function (resolve, reject) {
return function () {
var url = Config.rootUrl + '/marathon/v2/apps';
RequestUtil.json({
url: url,
success: function (response) {
AppDispatcher.handleServerAction({
type: ActionTypes.REQUEST_MARATHON_APPS_SUCCESS,
data: response
});
resolve();
},
error: function (e) {
AppDispatcher.handleServerAction({
type: ActionTypes.REQUEST_MARATHON_APPS_ERROR,
data: e.message
});
reject();
},
hangingRequestCallback: function () {
AppDispatcher.handleServerAction({
type: ActionTypes.REQUEST_MARATHON_APPS_ONGOING
});
}
});
};
},
{delayAfterCount: Config.delayAfterErrorCount}
)
};
|
Add setting about server port | /**
* Created by dell on 2015/7/20.
* This is gulp init
*/
(function(){
"use strict";
var gulp = require('gulp');
var loadPlugins = require('gulp-load-plugins');
var plugins = loadPlugins();
var Browsersync = require('browser-sync').create();
var del = require('del');
var paths = {
src: 'app',
dist: 'dist'
};
// 默认任务
gulp.task('default', ["server","less","watch"]);
// 搭建静态服务器
gulp.task('server', function() {
Browsersync.init({
port: 3005,
ui: {
port: 3006
},
server: {
baseDir: "./" +paths.src
}
});
});
// 编译Less文件
gulp.task('less',function(){
gulp.src([paths.src + '/less/style.less'])
.pipe(plugins.less())
.pipe(gulp.dest(paths.src + '/css'));
});
// 监控文件
gulp.task('watch',function(){
gulp.watch(paths.src + '/less/**/*.less', ['less']);
gulp.watch([
paths.src +"/**/*.html",
paths.src + "/js/**/*.js",
paths.src + "/lib/**/*.js",
paths.src + "/css/**/*.css",
paths.src + "/lib/**/*.css"
]).on("change", Browsersync.reload);
});
}).call(this); | /**
* Created by dell on 2015/7/20.
* This is gulp init
*/
(function(){
"use strict";
var gulp = require('gulp');
var loadPlugins = require('gulp-load-plugins');
var plugins = loadPlugins();
var Browsersync = require('browser-sync').create();
var del = require('del');
var paths = {
src: 'app',
dist: 'dist'
};
// 默认任务
gulp.task('default', ["server","less","watch"]);
// 搭建静态服务器
gulp.task('server', function() {
Browsersync.init({
server: {
baseDir: "./" +paths.src
}
});
});
// 编译Less文件
gulp.task('less',function(){
gulp.src([paths.src + '/less/style.less'])
.pipe(plugins.less())
.pipe(gulp.dest(paths.src + '/css'));
});
// 监控文件
gulp.task('watch',function(){
gulp.watch(paths.src + '/less/**/*.less', ['less']);
gulp.watch([
paths.src +"/**/*.html",
paths.src + "/js/**/*.js",
paths.src + "/lib/**/*.js",
paths.src + "/css/**/*.css",
paths.src + "/lib/**/*.css"
]).on("change", Browsersync.reload);
});
}).call(this); |
Use double quotes to quote command arguments. The Windows command
parser doesn't recognize single quotes. | import sys
import os
import time
try:
import subprocess
except ImportError:
# use private copy for old Python versions
import MonetDBtesting.subprocess26 as subprocess
def server():
s = subprocess.Popen('%s "--dbinit=include sql;" --set gdk_readonly=yes' % os.getenv('MSERVER'),
shell = True,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
s.stdin.write('\nio.printf("\\nReady.\\n");\n')
s.stdin.flush()
while True:
ln = s.stdout.readline()
if not ln:
print 'Unexpected EOF from server'
sys.exit(1)
sys.stdout.write(ln)
if 'Ready' in ln:
break
return s
def client():
c = subprocess.Popen("%s" % os.getenv('SQL_CLIENT'),
shell = True,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
return c
script1 = '''\
create table t2 (a int);
'''
def main():
s = server()
c = client()
o, e = c.communicate(script1)
sys.stdout.write(o)
sys.stderr.write(e)
o, e = s.communicate()
sys.stdout.write(o)
sys.stderr.write(e)
if __name__ == '__main__':
main()
| import sys
import os
import time
try:
import subprocess
except ImportError:
# use private copy for old Python versions
import MonetDBtesting.subprocess26 as subprocess
def server():
s = subprocess.Popen("%s --dbinit='include sql;' --set gdk_readonly=yes" % os.getenv('MSERVER'),
shell = True,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
s.stdin.write('\nio.printf("\\nReady.\\n");\n')
s.stdin.flush()
while True:
ln = s.stdout.readline()
if not ln:
print 'Unexpected EOF from server'
sys.exit(1)
sys.stdout.write(ln)
if 'Ready' in ln:
break
return s
def client():
c = subprocess.Popen("%s" % os.getenv('SQL_CLIENT'),
shell = True,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
return c
script1 = '''\
create table t2 (a int);
'''
def main():
s = server()
c = client()
o, e = c.communicate(script1)
sys.stdout.write(o)
sys.stderr.write(e)
o, e = s.communicate()
sys.stdout.write(o)
sys.stderr.write(e)
if __name__ == '__main__':
main()
|
oss: Fix overquoting of thrift paths
Summary: This overquotes the paths in travis builds. This will fix the opensource broken builds
Reviewed By: snarkmaster
Differential Revision: D5923131
fbshipit-source-id: 1ff3e864107b0074fc85e8a45a37455430cf4ba3 | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'fbcode_builder steps to build & test Bistro'
import specs.fbthrift as fbthrift
import specs.folly as folly
import specs.proxygen as proxygen
from shell_quoting import ShellQuoted
# Since Bistro doesn't presently have an "install" target, there is no
# point in having its spec in the shared spec directory.
def fbcode_builder_spec(builder):
return {
'depends_on': [folly, proxygen, fbthrift],
'steps': [
builder.fb_github_project_workdir('bistro/bistro'),
builder.step('Build bistro', [
# Future: should this share some code with `cmake_install()`?
builder.run(ShellQuoted(
'PATH="$PATH:"{p}/bin '
'TEMPLATES_PATH={p}/include/thrift/templates '
'./cmake/run-cmake.sh Debug -DCMAKE_INSTALL_PREFIX={p}'
).format(p=builder.option('prefix'))),
builder.workdir('cmake/Debug'),
builder.parallel_make(),
]),
builder.step('Run bistro tests', [
builder.run(ShellQuoted('ctest')),
]),
]
}
config = {
'github_project': 'facebook/bistro',
'fbcode_builder_spec': fbcode_builder_spec,
}
| #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'fbcode_builder steps to build & test Bistro'
import specs.fbthrift as fbthrift
import specs.folly as folly
import specs.proxygen as proxygen
from shell_quoting import ShellQuoted
# Since Bistro doesn't presently have an "install" target, there is no
# point in having its spec in the shared spec directory.
def fbcode_builder_spec(builder):
return {
'depends_on': [folly, proxygen, fbthrift],
'steps': [
builder.fb_github_project_workdir('bistro/bistro'),
builder.step('Build bistro', [
# Future: should this share some code with `cmake_install()`?
builder.run(ShellQuoted(
'PATH="$PATH:{p}/bin" '
'TEMPLATES_PATH="{p}/include/thrift/templates" '
'./cmake/run-cmake.sh Debug -DCMAKE_INSTALL_PREFIX={p}'
).format(p=builder.option('prefix'))),
builder.workdir('cmake/Debug'),
builder.parallel_make(),
]),
builder.step('Run bistro tests', [
builder.run(ShellQuoted('ctest')),
]),
]
}
config = {
'github_project': 'facebook/bistro',
'fbcode_builder_spec': fbcode_builder_spec,
}
|
Update js to bust compressor cache. |
'use strict';
(function() {
angular.module('fireStation.homeController', [])
.controller('home', function($scope, map, $filter) {
var homeMap = map.initMap('map', {scrollWheelZoom: false});
homeMap.setView([40, -90], 4);
var headquartersIcon = L.FireCARESMarkers.headquartersmarker();
if (featured_departments != null) {
L.geoJson(featured_departments, {
pointToLayer: function(feature, latlng) {
return L.marker(latlng, {icon: headquartersIcon});
},
onEachFeature: function(feature, layer) {
if (feature.properties && feature.properties.name) {
var popUp = '<b><a href="' + feature.properties.url +'">' + feature.properties.name + '</a></b>';
if (feature.properties.dist_model_score != null) {
popUp += '<br><b>Performance score: </b> ' + feature.properties.dist_model_score + ' seconds';
}
if (feature.properties.predicted_fires != null) {
popUp += '<br><b>Predicted annual residential fires: </b> ' + $filter('number')(feature.properties.predicted_fires, 0);
}
layer.bindPopup(popUp);
}
}
}).addTo(homeMap);
}
});
})();
|
'use strict';
(function() {
angular.module('fireStation.homeController', [])
.controller('home', function($scope, map, $filter) {
var homeMap = map.initMap('map', {scrollWheelZoom: false});
homeMap.setView([40, -90], 4);
var headquartersIcon = L.FireCARESMarkers.headquartersmarker();
if (featured_departments != null) {
L.geoJson(featured_departments, {
pointToLayer: function(feature, latlng) {
return L.marker(latlng, {icon: headquartersIcon});
},
onEachFeature: function(feature, layer) {
if (feature.properties && feature.properties.name) {
var popUp = '<b><a href="' + feature.properties.url +'">' + feature.properties.name + '</a></b>';
if (feature.properties.dist_model_score != null) {
popUp += '<br><b>Performance score: </b> ' + feature.properties.dist_model_score + ' seconds';
}
if (feature.properties.predicted_fires != null) {
popUp += '<br><b>Predicted annual residential fires: </b> ' + $filter('number')(feature.properties.predicted_fires, 0);
}
layer.bindPopup(popUp);
}
}
}).addTo(homeMap);
}
});
})();
|
Update gui on receiving CLIENTLIST message | package lanchat.client;
import java.io.IOException;
import java.util.ArrayList;
import javafx.application.Platform;
import lanchat.common.ServerMessage;
import lanchat.common.ServerMessageType;
import lanchat.gui.ClientGUI;
public class MessageListener extends Thread{
private Client client;
private boolean running;
private ClientGUI gui;
public MessageListener(Client client, ClientGUI gui) {
this.client = client;
this.gui = gui;
}
public void run() {
running = true;
while(running ){
try {
ServerMessage serverMessage = (ServerMessage) client.getInputStream().readObject();
ServerMessageType type = serverMessage.getType();
String message = serverMessage.getMessage();
String username = serverMessage.getUsername();
ArrayList<String> usernames = serverMessage.getUsernames();
switch (type) {
case MESSAGE:
//TODO update gui (display message)
break;
case CLIENTLIST:
Platform.runLater(new Runnable() {
@Override
public void run() {
gui.setClientList(usernames);
}
});
break;
}
} catch (ClassNotFoundException e) {
//can't do anything if class is not found
} catch (IOException e) {
//server has closed the connection
startGuiLoginView("Connection to server lost");
break;
}
}
}
public void shutdown() {
running = false;
}
private void startGuiLoginView(String reason) {
Platform.runLater(new Runnable() {
@Override
public void run() {
gui.startLoginView();
gui.setLoginErrorText(reason);
}
});
}
}
| package lanchat.client;
import java.io.IOException;
import java.util.ArrayList;
import javafx.application.Platform;
import lanchat.common.ServerMessage;
import lanchat.common.ServerMessageType;
import lanchat.gui.ClientGUI;
public class MessageListener extends Thread{
private Client client;
private boolean running;
private ClientGUI gui;
public MessageListener(Client client, ClientGUI gui) {
this.client = client;
this.gui = gui;
}
public void run() {
running = true;
while(running ){
try {
ServerMessage serverMessage = (ServerMessage) client.getInputStream().readObject();
ServerMessageType type = serverMessage.getType();
String message = serverMessage.getMessage();
String username = serverMessage.getUsername();
ArrayList<String> usernames = serverMessage.getUsernames();
switch (type) {
case MESSAGE:
//TODO update gui (display message)
break;
case CLIENTLIST:
//TODO update gui (update clientlist)
break;
}
} catch (ClassNotFoundException e) {
//can't do anything if class is not found
} catch (IOException e) {
//server has closed the connection
startGuiLoginView("Connection to server lost");
break;
}
}
}
public void shutdown() {
running = false;
}
private void startGuiLoginView(String reason) {
Platform.runLater(new Runnable() {
@Override
public void run() {
gui.startLoginView();
gui.setLoginErrorText(reason);
}
});
}
}
|
Fix emoticon-related parsing issues for chat messages | package pro.beam.api.resource.chat.events.data;
import java.util.List;
import pro.beam.api.resource.BeamUser;
import pro.beam.api.resource.chat.AbstractChatEvent;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterators;
import com.google.gson.annotations.SerializedName;
public class IncomingMessageData extends AbstractChatEvent.EventData {
public int channel;
public String id;
public String user_name;
public String user_id;
public List<BeamUser.Role> user_roles;
public List<MessagePart> message;
public String getMessage() {
return Joiner.on(' ').join(Iterators.transform(this.message.iterator(), new Function<MessagePart, String>() {
@Override public String apply(MessagePart part) {
switch(part.type) {
case ME:
case EMOTICON:
return part.text;
case LINK:
return part.url;
case TEXT:
default:
return part.data;
}
}
}));
}
public static class MessagePart {
public Type type;
public String url;
public String data;
public String path;
public String text;
// Emoticon-related
public String source;
public String pack;
public Coords coords;
public static class Coords {
public int x;
public int y;
}
public static enum Type {
@SerializedName("me") ME,
@SerializedName("text") TEXT,
@SerializedName("emoticon") EMOTICON,
@SerializedName("link") LINK,
}
}
}
| package pro.beam.api.resource.chat.events.data;
import java.util.List;
import pro.beam.api.resource.BeamUser;
import pro.beam.api.resource.chat.AbstractChatEvent;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterators;
import com.google.gson.annotations.SerializedName;
public class IncomingMessageData extends AbstractChatEvent.EventData {
public int channel;
public String id;
public String user_name;
public String user_id;
public List<BeamUser.Role> user_roles;
public List<MessagePart> message;
public String getMessage() {
return Joiner.on(' ').join(Iterators.transform(this.message.iterator(), new Function<MessagePart, String>() {
@Override public String apply(MessagePart part) {
switch(part.type) {
case ME:
return part.text;
case EMOTICON:
return part.path;
case LINK:
return part.url;
case TEXT:
default:
return part.data;
}
}
}));
}
public static class MessagePart {
public Type type;
public String url;
public String data;
public String path;
public String text;
public static enum Type {
@SerializedName("me") ME,
@SerializedName("text") TEXT,
@SerializedName("emoticon") EMOTICON,
@SerializedName("link") LINK,
}
}
}
|
Use const for requirements, constants and variables that are initialized once | const BaseDataview = require('./base');
const TYPE = 'list';
const listSqlTpl = ctx => `select ${ctx._columns} from (${ctx._query}) as _cdb_list`;
/**
{
type: 'list',
options: {
columns: ['name', 'description']
}
}
*/
module.exports = class List extends BaseDataview{
constructor (query, options = {}) {
super();
this._checkOptions(options);
this.query = query;
this.columns = options.columns;
}
_checkOptions (options) {
if (!Array.isArray(options.columns)) {
throw new Error('List expects `columns` array in widget options');
}
}
sql (psql, override, callback) {
if (!callback) {
callback = override;
}
const listSql = listSqlTpl({
_query: this.query,
_columns: this.columns.join(', ')
});
return callback(null, listSql);
}
format (result) {
return {
rows: result.rows
};
}
getType () {
return TYPE;
}
toString () {
return JSON.stringify({
_type: TYPE,
_query: this.query,
_columns: this.columns.join(', ')
});
};
}
| var BaseDataview = require('./base');
var TYPE = 'list';
var listSqlTpl = ctx => `select ${ctx._columns} from (${ctx._query}) as _cdb_list`;
/**
{
type: 'list',
options: {
columns: ['name', 'description']
}
}
*/
module.exports = class List extends BaseDataview{
constructor (query, options = {}) {
super();
this._checkOptions(options);
this.query = query;
this.columns = options.columns;
}
_checkOptions (options) {
if (!Array.isArray(options.columns)) {
throw new Error('List expects `columns` array in widget options');
}
}
sql (psql, override, callback) {
if (!callback) {
callback = override;
}
var listSql = listSqlTpl({
_query: this.query,
_columns: this.columns.join(', ')
});
return callback(null, listSql);
}
format (result) {
return {
rows: result.rows
};
}
getType () {
return TYPE;
}
toString () {
return JSON.stringify({
_type: TYPE,
_query: this.query,
_columns: this.columns.join(', ')
});
};
}
|
Fix значение файла из php.ini конвертируем в килобайты | <?php
namespace SleepingOwl\Admin\Traits;
trait MaxFileSizeTrait
{
/**
* @var number
*/
protected $maxFileSize;
/**
* Возвращает максимальный размер загружаемого файла из конфигурации php.ini
*
* @return number Максимальный размер загружаемого файла в килобайтах
*/
public function getMaxFileSize()
{
if (! $this->maxFileSize) {
try {
$this->maxFileSize = $this->convertKB(ini_get('upload_max_filesize'));
} catch (\Exception $e) {
$this->maxFileSize = 5;
}
}
return $this->maxFileSize;
}
/**
* Конвертация значения размера загружаемого файла.
*
* @param string $value
*
* @return number Размер файла в килобайтах
*/
public function convertKB($value)
{
if (is_numeric($value)) {
return $value;
} else {
$value_length = strlen($value);
$qty = substr($value, 0, $value_length - 1);
$unit = strtolower(substr($value, $value_length - 1));
switch ($unit) {
case 'k':
$qty = $qty;
break;
case 'm':
$qty *= 1024;
break;
case 'g':
$qty *= 1048576;
break;
}
return $qty;
}
}
}
| <?php
namespace SleepingOwl\Admin\Traits;
trait MaxFileSizeTrait
{
/**
* @var number
*/
protected $maxFileSize;
/**
* @return number
*/
public function getMaxFileSize()
{
if (! $this->maxFileSize) {
try {
$this->maxFileSize = $this->convertMB(ini_get('upload_max_filesize'));
} catch (\Exception $e) {
$this->maxFileSize = 5;
}
}
return $this->maxFileSize;
}
/**
* Конвертирование значения
* максимального размера загружаемого файла.
*/
public function convertMB($value)
{
if (is_numeric($value)) {
return $value;
} else {
$value_length = strlen($value);
$qty = substr($value, 0, $value_length - 1);
$unit = strtolower(substr($value, $value_length - 1));
switch ($unit) {
case 'k':
$qty /= 1024;
break;
case 'm':
$qty = $qty;
break;
case 'g':
$qty *= 1024;
break;
}
return $qty;
}
}
}
|
Fix typo in `scarlarToString` method name.
This is a protected function and is not called anywhere else but this class, so this is safe to rename. | <?php
namespace Flint\Config\Normalizer;
use Pimple;
/**
* @package Flint
*/
class PimpleAwareNormalizer extends \Flint\PimpleAware implements NormalizerInterface
{
const PLACEHOLDER = '{%%|%([a-z0-9_.]+)%}';
/**
* @param Pimple $pimple
*/
public function __construct(Pimple $pimple = null)
{
$this->setPimple($pimple);
}
/**
* @param string $contents
* @return string
*/
public function normalize($contents)
{
return preg_replace_callback(static::PLACEHOLDER, array($this, 'callback'), $contents);
}
/**
* @param array $matches
* @return mixed
*/
protected function callback($matches)
{
if (!isset($matches[1])) {
return '%%';
}
return $this->scalarToString($this->pimple[$matches[1]]);
}
/**
* @param mixed $value
* @return mixed
*/
protected function scalarToString($value)
{
switch (gettype($value)) {
case 'resource':
case 'object':
throw new \RuntimeException('Unable to replace placeholder if its replacement is an object or resource.');
case 'boolean':
return $value ? 'true' : 'false';
case 'NULL':
return 'null';
default:
return (string) $value;
}
}
}
| <?php
namespace Flint\Config\Normalizer;
use Pimple;
/**
* @package Flint
*/
class PimpleAwareNormalizer extends \Flint\PimpleAware implements NormalizerInterface
{
const PLACEHOLDER = '{%%|%([a-z0-9_.]+)%}';
/**
* @param Pimple $pimple
*/
public function __construct(Pimple $pimple = null)
{
$this->setPimple($pimple);
}
/**
* @param string $contents
* @return string
*/
public function normalize($contents)
{
return preg_replace_callback(static::PLACEHOLDER, array($this, 'callback'), $contents);
}
/**
* @param array $matches
* @return mixed
*/
protected function callback($matches)
{
if (!isset($matches[1])) {
return '%%';
}
return $this->scarlarToString($this->pimple[$matches[1]]);
}
/**
* @param mixed $value
* @return mixed
*/
protected function scarlarToString($value)
{
switch (gettype($value)) {
case 'resource':
case 'object':
throw new \RuntimeException('Unable to replace placeholder if its replacement is an object or resource.');
case 'boolean':
return $value ? 'true' : 'false';
case 'NULL':
return 'null';
default:
return (string) $value;
}
}
}
|
Add stopwatch to log output and a finished message | package com.axiomalaska.sos.injector.db;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.axiomalaska.sos.SosInjector;
import com.google.common.base.Stopwatch;
public class DatabaseSosInjector {
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseSosInjector.class);
private static final String MOCK = "mock";
public static void main(String[] args){
if (args.length > 0) {
String configFile = args[0];
DatabaseSosInjectorConfig.initialize(configFile);
}
Stopwatch stopwatch = Stopwatch.createStarted();
try {
SosInjector sosInjector = null;
if (System.getProperty(MOCK) != null) {
//mock
sosInjector = SosInjector.mock("mock-database-sos-injector",
new DatabaseStationRetriever(),
new DatabaseObservationRetriever(),
true);
LOGGER.info("Mock SosInjector initialized");
} else {
sosInjector = new SosInjector("database-sos-injector",
DatabaseSosInjectorConfig.instance().getSosUrl(),
DatabaseSosInjectorConfig.instance().getSosAuthenticationToken(),
DatabaseSosInjectorConfig.instance().getPublisherInfo(),
new DatabaseStationRetriever(),
new DatabaseObservationRetriever(),
null);
}
if (sosInjector == null) {
throw new NullPointerException("sosInjector is null");
}
sosInjector.update();
LOGGER.info("SOS injection finished in {} seconds", stopwatch.elapsed(TimeUnit.SECONDS));
} catch (Exception e) {
LOGGER.error("Sos injection failed after {} seconds", stopwatch.elapsed(TimeUnit.SECONDS), e);
}
}
} | package com.axiomalaska.sos.injector.db;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.axiomalaska.sos.SosInjector;
public class DatabaseSosInjector {
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseSosInjector.class);
private static final String MOCK = "mock";
public static void main(String[] args){
if (args.length > 0) {
String configFile = args[0];
DatabaseSosInjectorConfig.initialize(configFile);
}
try {
SosInjector sosInjector = null;
if (System.getProperty(MOCK) != null) {
//mock
sosInjector = SosInjector.mock("mock-database-sos-injector",
new DatabaseStationRetriever(),
new DatabaseObservationRetriever(),
true);
LOGGER.info("Mock SosInjector initialized");
} else {
sosInjector = new SosInjector("database-sos-injector",
DatabaseSosInjectorConfig.instance().getSosUrl(),
DatabaseSosInjectorConfig.instance().getSosAuthenticationToken(),
DatabaseSosInjectorConfig.instance().getPublisherInfo(),
new DatabaseStationRetriever(),
new DatabaseObservationRetriever(),
null);
}
if (sosInjector == null) {
throw new NullPointerException("sosInjector is null");
}
sosInjector.update();
} catch (Exception e) {
LOGGER.error("Sos injection failed", e);
}
}
} |
Remove enabled filter on clusterTemplates that caused js error
rancher/rancher#20268 | import Controller from '@ember/controller';
import { computed, get } from '@ember/object';
import { inject as service } from '@ember/service';
export default Controller.extend({
router: service(),
clusterTemplateRevisionId: null,
actions: {
save() {
if (this.clusterTemplateRevisionId) {
this.router.transitionTo('global-admin.clusters.new.launch', this.model.provider, { queryParams: { clusterTemplateRevision: this.clusterTemplateRevisionId } });
} else {
this.router.transitionTo('global-admin.clusters.new.launch', this.model.provider, { queryParams: { clusterTemplateRevision: null } });
}
},
cancel() {
this.router.transitionTo('global-admin.clusters.new')
}
},
allTemplates: computed('model.clusterTemplates.[]', 'model.clusterTemplateRevisions.[]', function() {
const remapped = [];
let { clusterTemplates, clusterTemplateRevisions } = this.model;
clusterTemplateRevisions = clusterTemplateRevisions.filterBy('enabled');
clusterTemplateRevisions.forEach((rev) => {
let match = clusterTemplates.findBy('id', get(rev, 'clusterTemplateId'));
if (match) {
remapped.pushObject({
clusterTemplateId: get(match, 'id'),
clusterTemplateName: get(match, 'displayName'),
clusterTemplateRevisionId: get(rev, 'id'),
clusterTemplateRevisionName: get(rev, 'name'),
});
}
});
return remapped;
}),
});
| import Controller from '@ember/controller';
import { computed, get } from '@ember/object';
import { inject as service } from '@ember/service';
export default Controller.extend({
router: service(),
clusterTemplateRevisionId: null,
actions: {
save() {
if (this.clusterTemplateRevisionId) {
this.router.transitionTo('global-admin.clusters.new.launch', this.model.provider, { queryParams: { clusterTemplateRevision: this.clusterTemplateRevisionId } });
} else {
this.router.transitionTo('global-admin.clusters.new.launch', this.model.provider, { queryParams: { clusterTemplateRevision: null } });
}
},
cancel() {
this.router.transitionTo('global-admin.clusters.new')
}
},
allTemplates: computed('model.clusterTemplates.[]', 'model.clusterTemplateRevisions.[]', function() {
const remapped = [];
let { clusterTemplates, clusterTemplateRevisions } = this.model;
clusterTemplates = clusterTemplates.filterBy('enabled');
clusterTemplateRevisions = clusterTemplateRevisions.filterBy('enabled');
clusterTemplateRevisions.forEach((rev) => {
let match = clusterTemplates.findBy('id', get(rev, 'clusterTemplateId'));
remapped.pushObject({
clusterTemplateId: get(match, 'id'),
clusterTemplateName: get(match, 'displayName'),
clusterTemplateRevisionId: get(rev, 'id'),
clusterTemplateRevisionName: get(rev, 'name'),
});
});
return remapped;
}),
});
|
Refactor FefPopup to work with dynamic links | const DEFAULT_HEIGHT = 600,
DEFAULT_WIDTH= 944,
DEFAULT_MEDIA_QUERY = 'screen';
export function init() {
$(document).on('click', '.js-popup', (event) => {
let popup = new FefPopup($(event.currentTarget));
popup.openPopup(event);
});
}
class FefPopup {
/**
* @param $element jQuery.element
*/
constructor ($element) {
this.$element = $element;
this.target = this.$element.attr('href');
this.width = this.$element.data('popup-width') || DEFAULT_WIDTH;
this.height = this.$element.data('popup-height') || DEFAULT_HEIGHT;
this.mediaQuery = this.$element.data('popup-media-query') || DEFAULT_MEDIA_QUERY;
this.triggerEvent = this.$element.data('popup-trigger-event') || null;
}
openPopup(event) {
if (matchMedia(this.mediaQuery).matches) {
event.preventDefault();
let parameters = [
'width='+this.width,
'height='+this.height,
'toolbar=1',
'scrollbars=1',
'location=1',
'status=0',
'menubar=1',
'resizable=1'
];
if (this.triggerEvent) {
$(window).trigger(this.triggerEvent);
}
window.open(this.target, '_blank', parameters.join(','));
}
}
}
| const DEFAULT_HEIGHT = 600,
DEFAULT_WIDTH= 944,
DEFAULT_MEDIA_QUERY = 'screen';
export function init() {
$('.js-popup').each((index, elem) => {
new FefPopup($(elem));
});
}
export class FefPopup {
/**
* @param $element jQuery.element
*/
constructor ($element) {
this.$element = $element;
this.target = this.$element.attr('href');
this.width = this.$element.data('popup-width') || DEFAULT_WIDTH;
this.height = this.$element.data('popup-height') || DEFAULT_HEIGHT;
this.mediaQuery = this.$element.data('popup-media-query') || DEFAULT_MEDIA_QUERY;
this.triggerEvent = this.$element.data('popup-trigger-event') || null;
this.bindEvents();
}
/**
* Bind click
*/
bindEvents () {
this.$element.on('click', (event) => {
this.openPopup(event);
});
}
openPopup(event) {
if (matchMedia(this.mediaQuery).matches) {
event.preventDefault();
let parameters = [
'width='+this.width,
'height='+this.height,
'toolbar=1',
'scrollbars=1',
'location=1',
'status=0',
'menubar=1',
'resizable=1'
];
if (this.triggerEvent) {
$(window).trigger(this.triggerEvent);
}
window.open(this.target, '_blank', parameters.join(','));
}
}
}
|
Remove unused field from game form | from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Submit, Button, Fieldset
from django.forms import ModelForm, Textarea
from core.models import Game
class GameForm(ModelForm):
class Meta:
model = Game
exclude = ['owner', 'date_published']
widgets = {
'description': Textarea(attrs={'cols': 100, 'rows': 15})
}
def __init__(self, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'{{ heading }}',
'name',
'description',
HTML("""{% if form.image.value %}<img class="img-responsive" src="{{ MEDIA_URL }}{{ form.image.value }}">
{% endif %}"""),
'image',
'tags',
'group',
'event_name',
'game_file'
),
FormActions(
Submit('save', 'Save'),
Button('cancel', 'Cancel', onclick='history.go(-1);', css_class="btn-default")
)
)
| from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Submit, Button, Fieldset
from django.forms import ModelForm, Textarea
from core.models import Game
class GameForm(ModelForm):
class Meta:
model = Game
exclude = ['owner', 'date_published']
widgets = {
'description': Textarea(attrs={'cols': 100, 'rows': 15})
}
def __init__(self, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'{{ heading }}',
'name',
'description',
'link',
HTML("""{% if form.image.value %}<img class="img-responsive" src="{{ MEDIA_URL }}{{ form.image.value }}">
{% endif %}"""),
'image',
'tags',
'group',
'event_name',
'game_file'
),
FormActions(
Submit('save', 'Save'),
Button('cancel', 'Cancel', onclick='history.go(-1);', css_class="btn-default")
)
)
|
Switch left/right mouse buttons, remove zoom on middle | 'use strict';
define(
['three', 'OrbitControls'],
function(THREE) {
return class Camera {
// ##############################################
// # Constructor ################################
// ##############################################
constructor(scene, renderer, fov, aspectRatio, near, far, cameraPosition) {
this.scene = scene;
this.near = near;
this.far = far;
this.cameraPosition = cameraPosition;
this.camera = new THREE.PerspectiveCamera(fov, aspectRatio, near, far);
this.camera.position.set(cameraPosition.x, cameraPosition.y, cameraPosition.z);
this.camera.zoom = 0.5;
this.camera.updateProjectionMatrix();
scene.camera = this;
this.controls = new THREE.OrbitControls(this.camera, renderer.domElement);
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.125;
this.controls.enableZoom = true;
this.controls.rotateSpeed = 0.15;
this.controls.enableKeys = false;
this.controls.mouseButtons = { ORBIT: THREE.MOUSE.RIGHT, PAN: THREE.MOUSE.LEFT };
}
}
}
); | 'use strict';
define(
['three', 'OrbitControls'],
function(THREE) {
return class Camera {
// ##############################################
// # Constructor ################################
// ##############################################
constructor(scene, renderer, fov, aspectRatio, near, far, cameraPosition) {
this.scene = scene;
this.near = near;
this.far = far;
this.cameraPosition = cameraPosition;
this.camera = new THREE.PerspectiveCamera(fov, aspectRatio, near, far);
this.camera.position.set(cameraPosition.x, cameraPosition.y, cameraPosition.z);
this.camera.zoom = 0.5;
this.camera.updateProjectionMatrix();
scene.camera = this;
this.controls = new THREE.OrbitControls(this.camera, renderer.domElement);
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.125;
this.controls.enableZoom = true;
this.controls.rotateSpeed = 0.15;
this.controls.enableKeys = false;
}
}
}
); |
Make plugin loader more robust | class PluginLoader:
def load(self, directory):
ret = []
for plugin in directory.children:
plugin_file = plugin.find(name=plugin.name, type='py')
if not plugin_file:
continue
plugin_class = plugin_file.classes.get(plugin.name)
if not plugin_class:
print 'Plugin file is missing proper class!', plugin.name, plugin_file.classes
continue
self._check_attributes(plugin_class)
plugin_instance = plugin_class()
ret.append(plugin_instance)
return ret
def _check_attributes(self, klass):
self._check_aliases(klass)
self._check_matches(klass)
self._check_priority(klass)
def _check_aliases(self, klass):
self._check_attribute(klass, 'aliases', '')
def _check_matches(self, klass):
def matches(self, expression):
if isinstance(self.aliases, str):
return expression == self.aliases
return expression in self.aliases
self._check_attribute(klass, 'matches', matches)
def _check_priority(self, klass):
self._check_attribute(klass, 'priority', 'normal')
if klass.priority not in ('low', 'normal', 'high'):
klass.priority = 'normal'
def _check_attribute(self, klass, attribute, value):
if not hasattr(klass, attribute):
setattr(klass, attribute, value)
| class PluginLoader:
def load(self, directory):
ret = []
for plugin in directory.children:
plugin_file = plugin.find(name=plugin.name, type='py')
if not plugin_file:
continue
plugin_class = plugin_file.classes[plugin.name]
self._check_attributes(plugin_class)
plugin_instance = plugin_class()
ret.append(plugin_instance)
return ret
def _check_attributes(self, klass):
self._check_aliases(klass)
self._check_matches(klass)
self._check_priority(klass)
def _check_aliases(self, klass):
self._check_attribute(klass, 'aliases', '')
def _check_matches(self, klass):
def matches(self, expression):
if isinstance(self.aliases, str):
return expression == self.aliases
return expression in self.aliases
self._check_attribute(klass, 'matches', matches)
def _check_priority(self, klass):
self._check_attribute(klass, 'priority', 'normal')
if klass.priority not in ('low', 'normal', 'high'):
klass.priority = 'normal'
def _check_attribute(self, klass, attribute, value):
if not hasattr(klass, attribute):
setattr(klass, attribute, value)
|
fix: Add style to required radio button group | import styles from './input.css'
export default ({ className, onCommit, property, value }) => {
function getValue(checked, newValue) {
if (!property.isArray) {
return newValue
}
const values = [...value]
if (checked) {
values.push(newValue)
}
else {
values.splice(values.indexOf(newValue), 1)
}
return values
}
function isChecked(newValue) {
if (!property.isArray) {
return value === newValue
}
for (const selection of value) {
if (selection === newValue) {
return true
}
}
}
return (
<div className={`${className} ${styles.input} ct-${property.display}-list`}>
{property.options.map(option => {
return (
<div key={option.value}>
<input
checked={isChecked(option.value)}
disabled={property.disabled}
onChange={e => onCommit(getValue(e.target.checked, option.value))}
name={property.id}
title={property.title}
type={property.isArray ? 'checkbox' : 'radio'}
value={option.value} />
{option.title}
</div>
)
})}
</div>
)
}
| export default ({ className, onCommit, property, value }) => {
function getValue(checked, newValue) {
if (!property.isArray) {
return newValue
}
const values = [...value]
if (checked) {
values.push(newValue)
}
else {
values.splice(values.indexOf(newValue), 1)
}
return values
}
function isChecked(newValue) {
if (!property.isArray) {
return value === newValue
}
for (const selection of value) {
if (selection === newValue) {
return true
}
}
}
return (
<div className={`${className} ct-${property.display}-list`}>
{property.options.map(option => {
return (
<div key={option.value}>
<input
checked={isChecked(option.value)}
disabled={property.disabled}
onChange={e => onCommit(getValue(e.target.checked, option.value))}
name={property.id}
title={property.title}
type={property.isArray ? 'checkbox' : 'radio'}
value={option.value} />
{option.title}
</div>
)
})}
</div>
)
}
|
Add development version and correct url to github | """
Flask-MongoKit
--------------
Flask-MongoKit simplifies to use MongoKit, a powerful MongoDB ORM in Flask
applications.
Links
`````
* `documentation <http://packages.python.org/Flask-MongoKit>`_
* `development version <http://github.com/jarus/flask-mongokit/zipball/master#egg=Flask-MongoKit-dev>`_
* `MongoKit <http://namlook.github.com/mongokit/>`_
* `Flask <http://flask.pocoo.org>`_
"""
from setuptools import setup
setup(
name='Flask-MongoKit',
version='0.2',
url='http://github.com/jarus/flask-mongokit',
license='BSD',
author='Christoph Heer',
author_email='[email protected]',
description='A Flask extension simplifies to use MongoKit',
long_description=__doc__,
packages=['flaskext'],
namespace_packages=['flaskext'],
zip_safe=False,
platforms='any',
install_requires=[
'Flask',
'MongoKit'
],
test_suite='tests.suite',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
) | """
Flask-MongoKit
--------------
Flask-MongoKit simplifies to use MongoKit, a powerful MongoDB ORM in Flask
applications.
Links
`````
* `documentation <http://packages.python.org/Flask-MongoKit>`_
* `sourcecode <http://bitbucket.org/Jarus/flask-mongokit/>`_
* `MongoKit <http://namlook.github.com/mongokit/>`_
* `Flask <http://flask.pocoo.org>`_
"""
from setuptools import setup
setup(
name='Flask-MongoKit',
version='0.2',
url='http://bitbucket.org/Jarus/flask-mongokit',
license='BSD',
author='Christoph Heer',
author_email='[email protected]',
description='A Flask extension simplifies to use MongoKit',
long_description=__doc__,
packages=['flaskext'],
namespace_packages=['flaskext'],
zip_safe=False,
platforms='any',
install_requires=[
'Flask',
'MongoKit'
],
test_suite='tests.suite',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
) |
Add test reporting debug logging | var request = require('superagent');
module.exports = {
"Load front page": function(browser) {
browser
.url("http://localhost:44199")
.waitForElementVisible('body', 1000)
.assert.containsText('.login', 'Sign in')
.end();
},
tearDown: function(done) {
var userName = this.client.options.username;
var accessKey = this.client.options.access_key;
console.log('tearDown started');
if (userName && accessKey) {
request
.put('https://saucelabs.com/rest/v1/' + userName + '/jobs/' + this.client.sessionId)
.send({ passed: true })
.auth(userName, accessKey)
.end(function(error, res){
if (error) {
console.log('ERROR sending verdict');
console.log(error);
} else {
console.log('Verdict sent to Sauce Labs, response:' + res.res.statusMessage);
}
done();
});
} else {
console.log('User name or access key missing, name: ' + userName + ', key: ' + accessKey);
console.log(this.client);
done();
}
}
};
| var request = require('superagent');
module.exports = {
"Load front page": function(browser) {
browser
.url("http://localhost:44199")
.waitForElementVisible('body', 1000)
.assert.containsText('.login', 'Sign in')
.end();
},
tearDown: function(done) {
var userName = this.client.options.username;
var accessKey = this.client.options.access_key;
console.log('tearDown started');
if (userName && accessKey) {
request
.put('https://saucelabs.com/rest/v1/' + userName + '/jobs/' + this.client.sessionId)
.send({ passed: true })
.auth(userName, accessKey)
.end(function(error, res){
if (error) {
console.log('ERROR sending verdict');
console.log(error);
} else {
console.log('Verdict sent to Sauce Labs, response:' + res.res.statusMessage);
}
done();
});
}
}
};
|
Put root URL the way it was. | <?php
namespace Trotch\Renderer;
use Trotch\Container;
use Trotch\Renderer;
class GeoLike extends Renderer
{
/**
* @var string
*/
protected $template = 'like.php';
/**
*
*/
protected function pre()
{
if (isset($_GET['token']) && isset($_SESSION['token']) && $_GET['token'] == $_SESSION['token']) {
try {
$fb = Container::get('Facebook');
$fb->setUserStatus();
$_SESSION['geoLikingSuccess'] = true;
}
catch (\Exception $e) {
$_SESSION['geoLikingWarning'] = $e->getMessage();
}
}
else {
$_SESSION['geoLikingWarning'] = 'Invalid token';
}
}
/**
* @return array
*/
protected function data()
{
return array();
}
/**
*
*/
protected function post()
{
unset($_SESSION['token']);
$app = Container::get('App');
$app->redirect('/');
}
}
| <?php
namespace Trotch\Renderer;
use Trotch\Container;
use Trotch\Renderer;
class GeoLike extends Renderer
{
/**
* @var string
*/
protected $template = 'like.php';
/**
*
*/
protected function pre()
{
if (isset($_GET['token']) && isset($_SESSION['token']) && $_GET['token'] == $_SESSION['token']) {
try {
$fb = Container::get('Facebook');
$fb->setUserStatus();
$_SESSION['geoLikingSuccess'] = true;
}
catch (\Exception $e) {
$_SESSION['geoLikingWarning'] = $e->getMessage();
}
}
else {
$_SESSION['geoLikingWarning'] = 'Invalid token';
}
}
/**
* @return array
*/
protected function data()
{
return array();
}
/**
*
*/
protected function post()
{
unset($_SESSION['token']);
$app = Container::get('App');
$app->redirect($app->request()->getRootUri());
}
}
|
Make fallback XML root element be in correct namespace | <?php
namespace PharIo\Phive {
abstract class XmlRepository {
/**
* @var string
*/
private $filename = '';
/**
* @var \DOMDocument
*/
private $dom;
/**
* @var \DOMXPath
*/
private $xPath;
/**
* @param File $filename
*/
public function __construct(Filename $filename) {
$this->filename = $filename;
$this->init();
}
/**
* @return \DOMDocument
*/
protected function getDom() {
return $this->dom;
}
/**
* @return string
*/
protected function getFilename() {
return $this->filename;
}
/**
* @return \DOMXPath
*/
protected function getXPath() {
return $this->xPath;
}
/**
* @return string
*/
abstract protected function getRootElementName();
/**
* @return string
*/
abstract protected function getNamespace();
/**
*
*/
private function init() {
$this->dom = new \DOMDocument('1.0', 'UTF-8');
$this->dom->preserveWhiteSpace = false;
$this->dom->formatOutput = true;
if ($this->filename->exists()) {
$this->dom->load($this->filename->asString());
} else {
$this->dom->appendChild($this->dom->createElementNS($this->getNamespace(), $this->getRootElementName()));
}
$this->xPath = new \DOMXPath($this->dom);
$this->xPath->registerNamespace('phive', $this->getNamespace());
}
}
}
| <?php
namespace PharIo\Phive {
abstract class XmlRepository {
/**
* @var string
*/
private $filename = '';
/**
* @var \DOMDocument
*/
private $dom;
/**
* @var \DOMXPath
*/
private $xPath;
/**
* @param File $filename
*/
public function __construct(Filename $filename) {
$this->filename = $filename;
$this->init();
}
/**
* @return \DOMDocument
*/
protected function getDom() {
return $this->dom;
}
/**
* @return string
*/
protected function getFilename() {
return $this->filename;
}
/**
* @return \DOMXPath
*/
protected function getXPath() {
return $this->xPath;
}
/**
* @return string
*/
abstract protected function getRootElementName();
/**
* @return string
*/
abstract protected function getNamespace();
/**
*
*/
private function init() {
$this->dom = new \DOMDocument('1.0', 'UTF-8');
$this->dom->preserveWhiteSpace = false;
$this->dom->formatOutput = true;
if ($this->filename->exists()) {
$this->dom->load($this->filename->asString());
} else {
$this->dom->appendChild($this->dom->createElement($this->getRootElementName()));
}
$this->xPath = new \DOMXPath($this->dom);
$this->xPath->registerNamespace('phive', $this->getNamespace());
}
}
}
|
Add hack to allow specifying newlines in scripts | class InstructionBase(object):
BEFORE=None
AFTER=None
def __init__(self, search_string):
self.search_string = search_string
@property
def search_string(self):
return self._search_string
@search_string.setter
def search_string(self, value):
if value.startswith(self.INSTRUCTION):
temp = value[(len(self.INSTRUCTION) + 1):]
else:
temp = value
self._search_string = temp.replace("\\n", "\n")
def __str__(self):
return self.INSTRUCTION + " " + self.search_string
def run(self, inputcontainer):
return (None, False)
def _search(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text == inputcontainer.EOF:
return inputcontainer.EOF
offset = text.find(self.search_string)
if offset == -1:
return inputcontainer.EOF
else:
return offset
def _copy(self, inputcontainer):
text = inputcontainer.get_at_pointer()
offset = self._search(inputcontainer)
if offset == inputcontainer.EOF:
inputcontainer.move_to_eof()
else:
inputcontainer.move_pointer(offset)
text = text[:offset]
return text
def _if(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text.startswith(self.search_string):
return True
else:
return False
| class InstructionBase(object):
BEFORE=None
AFTER=None
def __init__(self, search_string):
self.search_string = search_string
@property
def search_string(self):
return self._search_string
@search_string.setter
def search_string(self, value):
if value.startswith(self.INSTRUCTION):
self._search_string = value[(len(self.INSTRUCTION) + 1):]
else:
self._search_string = value
def __str__(self):
return self.INSTRUCTION + " " + self.search_string
def run(self, inputcontainer):
return (None, False)
def _search(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text == inputcontainer.EOF:
return inputcontainer.EOF
offset = text.find(self.search_string)
if offset == -1:
return inputcontainer.EOF
else:
return offset
def _copy(self, inputcontainer):
text = inputcontainer.get_at_pointer()
offset = self._search(inputcontainer)
if offset == inputcontainer.EOF:
inputcontainer.move_to_eof()
else:
inputcontainer.move_pointer(offset)
text = text[:offset]
return text
def _if(self, inputcontainer):
text = inputcontainer.get_at_pointer()
if text.startswith(self.search_string):
return True
else:
return False
|
Allow keyword arguments in GeneralStoreManager.create_item method | from graphene.storage.id_store import *
class GeneralStoreManager:
"""
Handles the creation/deletion of nodes to the NodeStore with ID recycling
"""
def __init__(self, store):
"""
Creates an instance of the GeneralStoreManager
:param store: Store to manage
:return: General store manager to handle index recycling
:rtype: GeneralStoreManager
"""
self.store = store
self.idStore = IdStore(store.FILE_NAME + ".id")
def create_item(self, **kwargs):
"""
Creates an item with the type of the store being managed
:return: New item with type STORE_TYPE
"""
# Check for an available ID from the IdStore
available_id = self.idStore.get_id()
# If no ID is available, get the last index of the file
if available_id == IdStore.NO_ID:
available_id = self.store.get_last_file_index()
# Create a type based on the type our store stores
return self.store.STORAGE_TYPE(available_id, **kwargs)
def delete_item(self, item):
"""
Deletes the given item from the store and adds the index to its IdStore
to be recycled
:return: Nothing
:rtype: None
"""
# Get index of item to be deleted
deleted_index = item.index
# Delete the item from the store
self.store.delete_item(item)
# Add the index to the IdStore, so it can be recycled
self.idStore.store_id(deleted_index)
| from graphene.storage.id_store import *
class GeneralStoreManager:
"""
Handles the creation/deletion of nodes to the NodeStore with ID recycling
"""
def __init__(self, store):
"""
Creates an instance of the GeneralStoreManager
:param store: Store to manage
:return: General store manager to handle index recycling
:rtype: GeneralStoreManager
"""
self.store = store
self.idStore = IdStore(store.FILE_NAME + ".id")
def create_item(self):
"""
Creates an item with the type of the store being managed
:return: New item with type STORE_TYPE
"""
# Check for an available ID from the IdStore
available_id = self.idStore.get_id()
# If no ID is available, get the last index of the file
if available_id == IdStore.NO_ID:
available_id = self.store.get_last_file_index()
# Create a type based on the type our store stores
return self.store.STORAGE_TYPE(available_id)
def delete_item(self, item):
"""
Deletes the given item from the store and adds the index to its IdStore
to be recycled
:return: Nothing
:rtype: None
"""
# Get index of item to be deleted
deleted_index = item.index
# Delete the item from the store
self.store.delete_item(item)
# Add the index to the IdStore, so it can be recycled
self.idStore.store_id(deleted_index)
|
Add my name to user list. | module.exports = {
users: [ // ADD YOUR USERNAME AT THE TOP
'julbaxter'
'mattclaw',
'crankeye',
'cgroner',
'tejohnso',
'sp1d3rx',
'evsie001',
'msied',
'd7p',
'kasperlewau',
'kennethrapp',
'briansoule',
'qguv',
'ianwalter',
'williamle8300',
'jeffawang',
'sorpaas',
'dylnclrk',
'dcancel',
'theprofessor117',
'roryokane',
'shedd',
'LeandroLovisolo',
'euank',
'humd',
'bwlang',
'barretts',
'pksjce',
'tito0224',
'hemanth',
'treygriffith',
'megamattron',
'pents90',
'michaelnovakjr',
'markbao',
'kalmi',
'lablayers',
'dfjones'
]
};
| module.exports = {
users: [ // ADD YOUR USERNAME AT THE TOP
'mattclaw',
'crankeye',
'cgroner',
'tejohnso',
'sp1d3rx',
'evsie001',
'msied',
'd7p',
'kasperlewau',
'kennethrapp',
'briansoule',
'qguv',
'ianwalter',
'williamle8300',
'jeffawang',
'sorpaas',
'dylnclrk',
'dcancel',
'theprofessor117',
'roryokane',
'shedd',
'LeandroLovisolo',
'euank',
'humd',
'bwlang',
'barretts',
'pksjce',
'tito0224',
'hemanth',
'treygriffith',
'megamattron',
'pents90',
'michaelnovakjr',
'markbao',
'kalmi',
'lablayers',
'dfjones'
]
}; |
Remove LICENCE inclusion from package | #!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.6-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='[email protected]',
packages=find_packages(exclude=['examples', 'tests']),
# data_files=[('', ['LICENSE', 'README.rst'])],
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
| #!/usr/bin/env python
import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 3):
sys.exit('Sorry, Python < 3.3 is not supported')
setup(
name='pyecore',
version='0.5.6-dev',
description=('A Python(ic) Implementation of the Eclipse Modeling '
'Framework (EMF/Ecore)'),
long_description=open('README.rst').read(),
keywords='model metamodel EMF Ecore MDE',
url='https://github.com/pyecore/pyecore',
author='Vincent Aranega',
author_email='[email protected]',
packages=find_packages(exclude=['examples', 'tests']),
data_files=[('', ['LICENSE', 'README.rst'])],
install_requires=['enum34;python_version<"3.4"',
'ordered-set',
'lxml'],
tests_require={'pytest'},
license='BSD 3-Clause',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'License :: OSI Approved :: BSD License',
]
)
|
Allow to conceal expert section from create form
- Workaround for cases when fields are duplicated in a details view | import template from './expert-contract-form.html';
const expertContract = {
template,
bindings: {
model: '=',
form: '<',
contractTemplate: '<',
expert: '<',
errors: '<',
},
controller: class ExpertContractController {
$onInit() {
this.loading = true;
let sortedOptions = {};
angular.forEach(this.expert.order, name => {
sortedOptions[name] = this.expert.options[name];
});
this.expert.options = sortedOptions;
this.tabs = [this.createTab(gettext('Details'), this.expert.options)];
angular.forEach(this.contractTemplate.order, tabName => {
let tab = this.contractTemplate.options[tabName];
if (!tab.hiddenInCreateForm) {
this.tabs.push(this.createTab(tab.label, tab.options));
}
angular.forEach(tab.options, (option, name) => {
option.name = name;
this.model[name] = this.getDefaultValue(option);
});
});
this.loading = false;
}
getDefaultValue(option) {
const overrides = this.expert.options_overrides || {};
const extra = overrides[option.name] || {};
return extra.default_value || option.default_value;
}
createTab(name, options) {
return {
label: name,
options: options,
required: Object.keys(options).some(name => options[name].required),
};
}
}
};
export default expertContract;
| import template from './expert-contract-form.html';
const expertContract = {
template,
bindings: {
model: '=',
form: '<',
contractTemplate: '<',
expert: '<',
errors: '<',
},
controller: class ExpertContractController {
$onInit() {
this.loading = true;
let sortedOptions = {};
angular.forEach(this.expert.order, name => {
sortedOptions[name] = this.expert.options[name];
});
this.expert.options = sortedOptions;
this.tabs = [this.createTab(gettext('Details'), this.expert.options)];
angular.forEach(this.contractTemplate.order, tabName => {
let tab = this.contractTemplate.options[tabName];
this.tabs.push(this.createTab(tab.label, tab.options));
angular.forEach(tab.options, (option, name) => {
option.name = name;
this.model[name] = this.getDefaultValue(option);
});
});
this.loading = false;
}
getDefaultValue(option) {
const overrides = this.expert.options_overrides || {};
const extra = overrides[option.name] || {};
return extra.default_value || option.default_value;
}
createTab(name, options) {
return {
label: name,
options: options,
required: Object.keys(options).some(name => options[name].required),
};
}
}
};
export default expertContract;
|
Make test names lower case prefix | import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def testReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def testReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def testLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def testDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def testDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
| import unittest
import src
import sys
from io import StringIO
class TestConfigFileLoading(unittest.TestCase):
filepath_prefix = ''
@classmethod
def setUpClass(cls):
if sys.argv[0].endswith('nosetests'):
cls.filepath_prefix = "./resources/config/"
else:
cls.filepath_prefix = "../resources/config/"
def TestReadJsonCorrectly(self):
config_file = self.filepath_prefix + "default-config.json"
exp_res = 17
config_json = src.read_json(config_file)
result = len(config_json)
self.assertEqual(result, exp_res)
def TestReadJsonBadFileName(self):
config_file = self.filepath_prefix + "fig.json"
with self.assertRaises(FileNotFoundError):
src.read_json(config_file)
def TestLoadConfigFileCheckRead(self):
exp_res = "Read styling config JSON correctly."
out = StringIO()
src.load_config_file(out=out)
result = out.getvalue().strip()
self.assertEqual(result, exp_res)
def TestDefaultConfigOverwritten(self):
exp_res = 666
config = src.load_config_file()
result = config["max_line_length"]
self.assertEqual(result, exp_res)
def TestDefaultConfigPersists(self):
exp_res = True
config = src.load_config_file()
result = config["spellcheck"]
self.assertEqual(result, exp_res)
|
Add __completion and updatedAt to 'Vie scolaire' | 'use strict';
angular.module('impactApp')
.config(function($stateProvider) {
var index = 'espace_perso.mes_profils.profil.vie_scolaire';
$stateProvider
.state(index, {
url: '/vie_scolaire',
templateUrl: 'app/espace_perso/mes_profils/profil/section.html',
controller: 'SectionCtrl',
redirectTo: index + '.situation',
resolve: {
sections: function($http) {
return $http.get('/api/sections').then(function(result) {
return result.data;
});
},
sectionId: function() {
return 'vie_scolaire';
},
section: function(sections, sectionId) {
return _.find(sections, {id: sectionId});
},
sectionModel: function(profile, sectionId) {
if (!profile[sectionId]) {
profile[sectionId] = {};
}
return profile[sectionId];
},
saveSection: function($state, currentUser, profile, sectionId, sectionModel) {
return function() {
profile[sectionId] = sectionModel;
profile.saveSection(sectionId, sectionModel, currentUser, function() {
$state.go('espace_perso.mes_profils.profil', {}, {reload: true});
});
};
}
}
});
});
| 'use strict';
angular.module('impactApp')
.config(function($stateProvider) {
var index = 'espace_perso.mes_profils.profil.vie_scolaire';
$stateProvider
.state(index, {
url: '/vie_scolaire',
templateUrl: 'app/espace_perso/mes_profils/profil/section.html',
controller: 'SectionCtrl',
redirectTo: index + '.situation',
resolve: {
sections: function($http) {
return $http.get('/api/sections').then(function(result) {
return result.data;
});
},
sectionId: function() {
return 'vie_scolaire';
},
section: function(sections, sectionId) {
return _.find(sections, {id: sectionId});
},
sectionModel: function(profile, sectionId) {
if (!profile[sectionId]) {
profile[sectionId] = {};
}
return profile[sectionId];
},
saveSection: function($state, currentUser, profile, sectionId, sectionModel) {
return function() {
profile[sectionId] = sectionModel;
profile.$save({userId: currentUser._id}, function() {
$state.go('espace_perso.mes_profils.profil', {}, {reload: true});
});
};
}
}
});
});
|
Fix checkAuth to make it work with componentWillReceiveProps | import React from 'react';
import {connect} from 'react-redux';
import {pushState} from 'redux-router';
export function requireAuthentication(Component) {
class AuthenticatedComponent extends React.Component {
componentWillMount () {
this.checkAuth(this.props.isAuthenticated);
}
componentWillReceiveProps (nextProps) {
this.checkAuth(nextProps.isAuthenticated);
}
checkAuth (isAuthenticated) {
if (!isAuthenticated) {
let redirectAfterLogin = this.props.location.pathname;
this.props
.dispatch(pushState(null, `/login?next=${redirectAfterLogin}`));
}
}
render () {
return (
<div>
{this.props.isAuthenticated === true
? <Component {...this.props}/>
: null
}
</div>
)
}
}
const mapStateToProps = (state) => ({
token: state.auth.token,
userName: state.auth.userName,
isAuthenticated: state.auth.isAuthenticated
});
return connect(mapStateToProps)(AuthenticatedComponent);
}
| import React from 'react';
import {connect} from 'react-redux';
import {pushState} from 'redux-router';
export function requireAuthentication(Component) {
class AuthenticatedComponent extends React.Component {
componentWillMount () {
this.checkAuth();
}
componentWillReceiveProps (nextProps) {
this.checkAuth();
}
checkAuth () {
if (!this.props.isAuthenticated) {
let redirectAfterLogin = this.props.location.pathname;
this.props
.dispatch(pushState(null, `/login?next=${redirectAfterLogin}`));
}
}
render () {
return (
<div>
{this.props.isAuthenticated === true
? <Component {...this.props}/>
: null
}
</div>
)
}
}
const mapStateToProps = (state) => ({
token: state.auth.token,
userName: state.auth.userName,
isAuthenticated: state.auth.isAuthenticated
});
return connect(mapStateToProps)(AuthenticatedComponent);
}
|
Delete recursive root path input | <?php
namespace CalendarReminder;
use PHPUnit\Framework\TestCase;
class ReminderFileRepositoryTest extends TestCase
{
const REMINDERS_ROOT_PATH = 'tests/reminders';
/** @var ReminderFileRepository */
public $reminderRepository;
protected function setUp()
{
$this->reminderRepository = new ReminderFileRepository(self::REMINDERS_ROOT_PATH);
}
protected function tearDown()
{
$this->deleteRecursive(self::REMINDERS_ROOT_PATH);
}
/**
* @test
*/
public function itShouldHaveRepositoryRootPath()
{
$this->assertEquals(self::REMINDERS_ROOT_PATH, $this->reminderRepository->remindersPath());
}
/**
* @test
*/
public function itShouldCreateReminderAndSave()
{
$date = date('d.m.Y');
$content = 'some content';
$this->reminderRepository->createReminder($date, $content);
$reminderFileName = sprintf('%s/%s/%s'
, self::REMINDERS_ROOT_PATH
, $date
, $content
);
$foundReminder = unserialize(file_get_contents($reminderFileName));
$this->assertEquals($foundReminder->date(), $date);
$this->assertEquals($foundReminder->content(), $content);
}
private function deleteRecursive($input)
{
if (is_file($input)) {
unlink($input);
return;
}
if (is_dir($input)) {
foreach (scandir($input) as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$file = join('/', [$input, $file]);
if (is_file($file)) {
unlink($file);
continue;
}
$this->deleteRecursive($file);
rmdir($file);
}
}
}
} | <?php
namespace CalendarReminder;
use PHPUnit\Framework\TestCase;
class ReminderFileRepositoryTest extends TestCase
{
const REMINDERS_ROOT_PATH = 'tests/reminders';
/** @var ReminderFileRepository */
public $reminderRepository;
protected function setUp()
{
$this->reminderRepository = new ReminderFileRepository(self::REMINDERS_ROOT_PATH);
}
protected function tearDown()
{
$this->deleteRecursive(self::REMINDERS_ROOT_PATH);
}
/**
* @test
*/
public function itShouldHaveRepositoryRootPath()
{
$this->assertEquals(self::REMINDERS_ROOT_PATH, $this->reminderRepository->remindersPath());
}
/**
* @test
*/
public function itShouldCreateReminderAndSave()
{
$date = date('d.m.Y');
$content = 'some content';
$this->reminderRepository->createReminder($date, $content);
$reminderFileName = sprintf('%s/%s/%s'
, self::REMINDERS_ROOT_PATH
, $date
, $content
);
$foundReminder = unserialize(file_get_contents($reminderFileName));
$this->assertEquals($foundReminder->date(), $date);
$this->assertEquals($foundReminder->content(), $content);
}
}
} |
Fix classname in scoreboard parser | from HTMLParser import HTMLParser
class ScoreboardParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.scores = []
self.cur_game = None
self.get_data = False
self.get_name = False
def handle_starttag(self, tag, attrs):
if tag == 'table':
self.cur_game = []
elif tag == 'td':
if ('class', 'name') in attrs:
self.get_name = True
elif ('class', 'finalScore') in attrs:
self.get_data = True
elif ('class', 'label') in attrs and ('align', 'left') in attrs:
self.get_data = True
elif tag == 'a' and self.get_name:
for name, value in attrs:
if name == 'href':
self.cur_game.append(value.split("/")[4])
self.get_name = False
def handle_endtag(self, tag):
if tag == 'table':
self.scores.append(self.cur_game)
def handle_data(self, data):
if not self.get_data:
return
self.cur_game.append(data.strip())
self.get_data = False
| from HTMLParser import HTMLParser
class ScoreboardParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.scores = []
self.cur_game = None
self.get_data = False
self.get_name = False
def handle_starttag(self, tag, attrs):
if tag == 'table':
self.cur_game = []
elif tag == 'td':
if ('class', 'name') in attrs:
self.get_name = True
elif ('class', 'finalscore') in attrs:
self.get_data = True
elif ('class', 'label') in attrs and ('align', 'left') in attrs:
self.get_data = True
elif tag == 'a' and self.get_name:
for name, value in attrs:
if name == 'href':
self.cur_game.append(value.split("/")[4])
self.get_name = False
def handle_endtag(self, tag):
if tag == 'table':
self.scores.append(self.cur_game)
def handle_data(self, data):
if not self.get_data:
return
self.cur_game.append(data.strip())
self.get_data = False
|
Allow consumers to provide options that are forwarded to tape | 'use strict';
var tape = require('tape');
var through = require('through2');
var PluginError = require('gulp-util').PluginError;
var requireUncached = require('require-uncached');
var PLUGIN_NAME = 'gulp-tape';
var gulpTape = function(opts) {
opts = opts || {};
var outputStream = opts.outputStream || process.stdout;
var reporter = opts.reporter || through.obj();
var tapeOpts = opts.tapeOpts || {};
var files = [];
var transform = function(file, encoding, cb) {
if (file.isNull()) {
return cb(null, file);
}
if (file.isStream()) {
return cb(new PluginError(PLUGIN_NAME, 'Streaming is not supported'));
}
files.push(file.path);
cb(null, file);
};
var flush = function(cb) {
try {
tape.createStream(tapeOpts).pipe(reporter).pipe(outputStream);
files.forEach(function(file) {
requireUncached(file);
});
var tests = tape.getHarness()._tests;
var pending = tests.length;
if (pending === 0) {
return cb();
}
tests.forEach(function(test) {
test.once('end', function() {
if (--pending === 0) {
cb();
}
});
});
} catch (err) {
cb(new PluginError(PLUGIN_NAME, err));
}
};
return through.obj(transform, flush);
};
module.exports = gulpTape;
| 'use strict';
var tape = require('tape');
var through = require('through2');
var PluginError = require('gulp-util').PluginError;
var requireUncached = require('require-uncached');
var PLUGIN_NAME = 'gulp-tape';
var gulpTape = function(opts) {
opts = opts || {};
var outputStream = opts.outputStream || process.stdout;
var reporter = opts.reporter || through.obj();
var files = [];
var transform = function(file, encoding, cb) {
if (file.isNull()) {
return cb(null, file);
}
if (file.isStream()) {
return cb(new PluginError(PLUGIN_NAME, 'Streaming is not supported'));
}
files.push(file.path);
cb(null, file);
};
var flush = function(cb) {
try {
tape.createStream().pipe(reporter).pipe(outputStream);
files.forEach(function(file) {
requireUncached(file);
});
var tests = tape.getHarness()._tests;
var pending = tests.length;
if (pending === 0) {
return cb();
}
tests.forEach(function(test) {
test.once('end', function() {
if (--pending === 0) {
cb();
}
});
});
} catch (err) {
cb(new PluginError(PLUGIN_NAME, err));
}
};
return through.obj(transform, flush);
};
module.exports = gulpTape;
|
Make KQMLString subclass of KQMLObject. | from io import BytesIO
from kqml import KQMLObject
from .util import safe_decode
class KQMLString(KQMLObject):
def __init__(self, data=None):
if data is None:
self.data = ''
else:
self.data = safe_decode(data)
def __len__(self):
return len(self.data)
def char_at(self, n):
return self.data[n]
def equals(self, obj):
if not isinstance(obj, KQMLString):
return False
else:
return obj.data == self.data
def write(self, out):
out.write(b'"')
for ch in self.data:
if ch == '"':
out.write(b'\\')
out.write(ch.encode())
out.write(b'"')
def to_string(self):
out = BytesIO()
self.write(out)
return safe_decode(out.getvalue())
def string_value(self):
return self.data
def __str__(self):
return safe_decode(self.to_string())
def __repr__(self):
s = self.__str__()
s = s.replace('\n', '\\n')
return s
def __getitem__(self, *args):
return self.data.__getitem__(*args)
| from io import BytesIO
from kqml import KQMLObject
from .util import safe_decode
class KQMLString(object):
def __init__(self, data=None):
if data is None:
self.data = ''
else:
self.data = safe_decode(data)
def __len__(self):
return len(self.data)
def char_at(self, n):
return self.data[n]
def equals(self, obj):
if not isinstance(obj, KQMLString):
return False
else:
return obj.data == self.data
def write(self, out):
out.write(b'"')
for ch in self.data:
if ch == '"':
out.write(b'\\')
out.write(ch.encode())
out.write(b'"')
def to_string(self):
out = BytesIO()
self.write(out)
return safe_decode(out.getvalue())
def string_value(self):
return self.data
def __str__(self):
return safe_decode(self.to_string())
def __repr__(self):
s = self.__str__()
s = s.replace('\n', '\\n')
return s
def __getitem__(self, *args):
return self.data.__getitem__(*args)
|
Reset error bag on file upload hydration
This helps get rid of error messages between file uploads so you don't see an error message if the file was uploaded successfully. | <?php
namespace App\Http\Livewire\Files;
use App\Models\File;
use Livewire\Component;
use Livewire\WithFileUploads;
class UploadFileModalForm extends Component
{
use WithFileUploads;
/**
* Determines if the modal should be shown to the user.
*
* @var boolean
*/
public $showModal = false;
/**
* The file that should be uploaded.
*
* @var mixed
*/
public $file = null;
/**
* Hydrates the component.
*
* @return void
*/
public function hydrate()
{
$this->resetErrorBag();
}
/**
* Handle state changes when the model is toggled.
*
* @param bool $state
* @return void
*/
public function updatedShowModal($state)
{
if (!$state) {
$this->resetErrorBag();
}
}
/**
* Handles uploading and saving the file.
*
* @return
*/
public function save()
{
$this->resetErrorBag();
if ($this->file) {
$file = File::createAndSave($this->file);
session()->flash('upload-url', $file->resource_url);
}
$this->reset('file');
}
/**
* Render the component.
*
* @return \Illuminate\View\View
*/
public function render()
{
return view('files.upload-file-modal-form');
}
}
| <?php
namespace App\Http\Livewire\Files;
use App\Models\File;
use Livewire\Component;
use Livewire\WithFileUploads;
class UploadFileModalForm extends Component
{
use WithFileUploads;
/**
* Determines if the modal should be shown to the user.
*
* @var boolean
*/
public $showModal = false;
/**
* The file that should be uploaded.
*
* @var mixed
*/
public $file = null;
/**
* Handle state changes when the model is toggled.
*
* @param bool $state
* @return void
*/
public function updatedShowModal($state)
{
if (!$state) {
$this->resetErrorBag();
}
}
/**
* Handles uploading and saving the file.
*
* @return
*/
public function save()
{
if ($this->file) {
$file = File::createAndSave($this->file);
session()->flash('upload-url', $file->resource_url);
}
$this->reset('file');
}
/**
* Render the component.
*
* @return \Illuminate\View\View
*/
public function render()
{
return view('files.upload-file-modal-form');
}
}
|
Fix test for Python 3 | import unittest
from jip.repository import MavenFileSystemRepos
from jip.maven import Artifact
from contextlib import contextmanager
import shutil
import tempfile
import errno
import os
@contextmanager
def tmpdir():
dirname = tempfile.mkdtemp()
try:
yield dirname
finally:
shutil.rmtree(dirname)
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
class RespositoryTests(unittest.TestCase):
def testLocalDownloadOfPomWithUtfChars(self):
with tmpdir() as temp_repo_dir:
artifact_dir = "%s/dummygroup/dummyartifact/1.0.0/" % temp_repo_dir
mkdir_p(artifact_dir)
with open("%sdummyartifact-1.0.0.pom" % artifact_dir, "w") as f:
f.write("\xe2")
testee = MavenFileSystemRepos('dummy_name', temp_repo_dir)
artifact = Artifact('dummygroup', 'dummyartifact', '1.0.0')
pom = testee.download_pom(artifact)
# should not raise an UnicodeDecodeError
pom.encode("utf-8")
if __name__ == '__main__':
unittest.main()
| import unittest
from jip.repository import MavenFileSystemRepos
from jip.maven import Artifact
from contextlib import contextmanager
import shutil
import tempfile
import errno
import os
@contextmanager
def tmpdir():
dirname = tempfile.mkdtemp()
try:
yield dirname
finally:
shutil.rmtree(dirname)
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
class RespositoryTests(unittest.TestCase):
def testLocalDownloadOfPomWithUtfChars(self):
with tmpdir() as temp_repo_dir:
artifact_dir = "%s/dummygroup/dummyartifact/1.0.0/" % temp_repo_dir
mkdir_p(artifact_dir)
with open("%sdummyartifact-1.0.0.pom" % artifact_dir, "wb") as f:
f.write("\xe2")
testee = MavenFileSystemRepos('dummy_name', temp_repo_dir)
artifact = Artifact('dummygroup', 'dummyartifact', '1.0.0')
pom = testee.download_pom(artifact)
# should not raise an UnicodeDecodeError
pom.encode("utf-8")
if __name__ == '__main__':
unittest.main()
|
Clean imports and remove unnecessary toString() | package uk.ac.ebi.atlas.commons.writers;
import org.springframework.context.annotation.Scope;
import uk.ac.ebi.atlas.commons.writers.impl.TsvWriterImpl;
import javax.inject.Named;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.MessageFormat;
@Named
@Scope("prototype")
public class FileTsvWriterBuilder {
private String experimentAccession;
private String tsvFilePathTemplate;
private boolean append = true;
public FileTsvWriterBuilder() {
}
public FileTsvWriterBuilder withExperimentAccession(String experimentAccession) {
this.experimentAccession = experimentAccession;
return this;
}
public FileTsvWriterBuilder forTsvFilePathTemplate(String tsvFilePathTemplate) {
this.tsvFilePathTemplate = tsvFilePathTemplate;
return this;
}
public FileTsvWriterBuilder withAppend(boolean append) {
this.append = append;
return this;
}
public TsvWriter build() {
String tsvFilePath = MessageFormat.format(tsvFilePathTemplate, experimentAccession);
try {
return new TsvWriterImpl(new OutputStreamWriter(new FileOutputStream(new File(tsvFilePath), append)));
} catch (IOException e) {
throw new IllegalStateException("Cannot write TSV file to path " + tsvFilePath, e);
}
}
}
| package uk.ac.ebi.atlas.commons.writers;
import org.springframework.context.annotation.Scope;
import uk.ac.ebi.atlas.commons.readers.TsvReader;
import uk.ac.ebi.atlas.commons.readers.impl.TsvReaderImpl;
import uk.ac.ebi.atlas.commons.writers.impl.TsvWriterImpl;
import javax.inject.Named;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.MessageFormat;
@Named
@Scope("prototype")
public class FileTsvWriterBuilder {
private String experimentAccession;
private String tsvFilePathTemplate;
private boolean append = true;
public FileTsvWriterBuilder() {
}
public FileTsvWriterBuilder withExperimentAccession(String experimentAccession) {
this.experimentAccession = experimentAccession;
return this;
}
public FileTsvWriterBuilder forTsvFilePathTemplate(String tsvFilePathTemplate) {
this.tsvFilePathTemplate = tsvFilePathTemplate;
return this;
}
public FileTsvWriterBuilder withAppend(boolean append) {
this.append = append;
return this;
}
public TsvWriter build() {
String tsvFilePath = MessageFormat.format(tsvFilePathTemplate, experimentAccession);
try {
return new TsvWriterImpl(new OutputStreamWriter(new FileOutputStream(new File(tsvFilePath), append)));
} catch (IOException e) {
throw new IllegalStateException("Cannot write TSV file to path " + tsvFilePath.toString(), e);
}
}
} |
Use gtk ui by default | # Copyright (c) 2012 John Reese
# Licensed under the MIT License
from __future__ import absolute_import, division
engine = None
ui = None
def async_engine_command(command, network=None, params=None):
"""Send a command to the current backend engine."""
return engine.async_command(command, network, params)
def async_ui_message(message_type, network=None, content=None):
"""Send a message to the current frontend user interface."""
return ui.async_message(message_type, network, content)
def start(frontend='gtk'):
"""Initialize both the backend and frontend, and wait for them to mutually exit."""
global engine
global ui
import signal
def sigint(signum, frame):
print 'stopping'
if engine:
engine.stop()
if ui:
ui.stop()
signal.signal(signal.SIGINT, sigint)
frontend = frontend.lower()
if frontend == 'stdout':
from pyranha.ui.stdout import StdoutUI
ui = StdoutUI()
elif frontend == 'gtk':
from pyranha.ui.gtk import GtkUI
ui = GtkUI()
else:
raise Exception('unsupported frontend type "{0}"'.format(frontend))
from pyranha.engine.engine import Engine
engine = Engine()
engine.start()
ui.start()
while engine.is_alive():
engine.join()
while ui.is_alive():
ui.join()
| # Copyright (c) 2012 John Reese
# Licensed under the MIT License
from __future__ import absolute_import, division
engine = None
ui = None
def async_engine_command(command, network=None, params=None):
"""Send a command to the current backend engine."""
return engine.async_command(command, network, params)
def async_ui_message(message_type, network=None, content=None):
"""Send a message to the current frontend user interface."""
return ui.async_message(message_type, network, content)
def start(frontend='stdout'):
"""Initialize both the backend and frontend, and wait for them to mutually exit."""
global engine
global ui
import signal
def sigint(signum, frame):
print 'stopping'
if engine:
engine.stop()
if ui:
ui.stop()
signal.signal(signal.SIGINT, sigint)
frontend = frontend.lower()
if frontend == 'stdout':
from pyranha.ui.stdout import StdoutUI
ui = StdoutUI()
elif frontend == 'gtk':
from pyranha.ui.gtk import GtkUI
ui = GtkUI()
else:
raise Exception('unsupported frontend type "{0}"'.format(frontend))
from pyranha.engine.engine import Engine
engine = Engine()
engine.start()
ui.start()
while engine.is_alive():
engine.join()
while ui.is_alive():
ui.join()
|
Add get request method function | <?php
namespace Acd;
/**
* Request Class
* @author Acidvertigo MIT Licence
*/
class Request
{
private $headers = [];
/**
* Check HTTP request headers
* @return array list of response headers
* @throws InvalidArgumentException if header is null
*/
public function getRequestHeaders()
{
if (function_exists('getallheaders()'))
{
$this->headers = getallheaders();
} else
{
$this->headers = $this->getServerHeaders();
}
if ($this->headers !== null)
{
return $this->headers;
} else
{
throw new \InvalidArgumentException('Unable to get Request Headers');
}
}
/**
* @return string the actual request method
*/
public function getReqestMethod()
{
return $_SERVER['REQUEST_METHOD'];
}
/**
* Helper function if getallheaders() not available
* @return array list of response headers
*/
private function getServerHeaders()
{
foreach (array_keys($_SERVER) as $skey) {
if (strpos($skey, 'HTTP_') !== FALSE)
{
$this->headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($skey, 5)))))] = $_SERVER[$skey];
}
}
return $this->headers;
}
}
| <?php
namespace Acd;
/**
* Request Class
* @author Acidvertigo MIT Licence
*/
class Request
{
private $headers = [];
/**
* Check HTTP request headers
* @return array list of response headers
* @throws InvalidArgumentException if header is null
*/
public function getRequestHeaders()
{
if (function_exists('getallheaders()'))
{
$this->headers = getallheaders();
} else
{
$this->headers = $this->getServerHeaders();
}
if ($this->headers !== null)
{
return $this->headers;
} else
{
throw new \InvalidArgumentException('Unable to get Request Headers');
}
}
/**
* Helper function if getallheaders() not available
* @return array list of response headers
*/
private function getServerHeaders()
{
foreach (array_keys($_SERVER) as $skey) {
if (strpos($skey, 'HTTP_') !== FALSE)
{
$this->headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($skey, 5)))))] = $_SERVER[$skey];
}
}
return $this->headers;
}
}
|
Set attributes via prototype & remove custom toJSON | "use strict";
var util = require("util");
var AbstractError = require("./AbstractError.js"),
defaultRenderer = require("./defaultRenderer.js");
/**
* generate Error-classes based on AbstractError
*
* @param error
* @returns {Function}
*/
function erroz(error) {
var errorFn = function (data) {
for (var errKey in errorFn.prototype) {
if (errorFn.prototype.hasOwnProperty(errKey)) {
this[errKey] = errorFn.prototype[errKey];
}
}
//add per instance properties
this.data = data || {};
this.message = this.message || erroz.options.renderMessage(error.template, data);
errorFn.super_.call(this, this.constructor);
};
util.inherits(errorFn, AbstractError);
//add static error properties (name, status, etc)
for (var errKey in error) {
if (error.hasOwnProperty(errKey)) {
errorFn[errKey] = error[errKey];
errorFn.prototype[errKey] = error[errKey];
}
}
errorFn.prototype.toJSend = function () {
var data = this.data;
if(erroz.options.includeStack && this.stack) {
data.stack = this.stack;
}
return {
status: this.status,
code: this.code,
message: this.message,
data: data
};
};
return errorFn;
}
erroz.options = {
/**
* overwrite this function for custom rendered messages
*
* @param {Object} data
* @param {String=} template
* @returns {String}
*/
renderMessage: defaultRenderer,
includeStack: true
};
module.exports = erroz; | "use strict";
var util = require("util");
var AbstractError = require("./AbstractError.js"),
defaultRenderer = require("./defaultRenderer.js");
/**
* generate Error-classes based on AbstractError
*
* @param error
* @returns {Function}
*/
function erroz(error) {
var errorFn = function (data) {
//add per instance properties
this.data = data;
this.message = this.message || erroz.options.renderMessage(error.template, data);
errorFn.super_.call(this, this.constructor);
};
util.inherits(errorFn, AbstractError);
//add static error properties (name, status, etc.)
for (var errKey in error) {
if (error.hasOwnProperty(errKey)) {
errorFn.prototype[errKey] = error[errKey];
}
}
errorFn.prototype.toJSON = function() {
var data = this.data || {};
if(erroz.options.includeStack) {
data.stack = this.stack;
}
return {
status: this.status,
code: this.code,
message: this.message,
data: data
};
};
return errorFn;
}
erroz.options = {
/**
* overwrite this function for custom rendered messages
*
* @param {Object} data
* @param {String=} template
* @returns {String}
*/
renderMessage: defaultRenderer,
includeStack: true
};
module.exports = erroz; |
Fix redirect after deleting of faq feedback | <?php
namespace Backend\Modules\Faq\Actions;
/*
* This file is part of Fork CMS.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
use Backend\Core\Engine\Base\ActionDelete as BackendBaseActionDelete;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Modules\Faq\Engine\Model as BackendFaqModel;
use Backend\Modules\Faq\Form\FaqFeedbackDeleteType;
/**
* This is the DeleteFeedback action, it will display a form to create a new item
*/
class DeleteFeedback extends BackendBaseActionDelete
{
public function execute(): void
{
$deleteForm = $this->createForm(FaqFeedbackDeleteType::class);
$deleteForm->handleRequest($this->getRequest());
if (!$deleteForm->isSubmitted() || !$deleteForm->isValid()) {
$this->redirect(BackendModel::createURLForAction('Index') . '&error=something-went-wrong');
}
$deleteFormData = $deleteForm->getData();
$feedbackId = $deleteFormData['id'];
$feedback = BackendFaqModel::getFeedback($feedbackId);
// there is no feedback data, so redirect
if (empty($feedback)) {
$this->redirect(BackendModel::createURLForAction('Index') . '&error=non-existing');
}
BackendFaqModel::deleteFeedback($feedbackId);
$this->redirect(
BackendModel::createURLForAction('Edit') . '&id=' .
$feedback['question_id'] . '&report=deleted#tabFeedback'
);
}
}
| <?php
namespace Backend\Modules\Faq\Actions;
/*
* This file is part of Fork CMS.
*
* For the full copyright and license information, please view the license
* file that was distributed with this source code.
*/
use Backend\Core\Engine\Base\ActionDelete as BackendBaseActionDelete;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Modules\Faq\Engine\Model as BackendFaqModel;
use Backend\Modules\Faq\Form\FaqFeedbackDeleteType;
/**
* This is the DeleteFeedback action, it will display a form to create a new item
*/
class DeleteFeedback extends BackendBaseActionDelete
{
public function execute(): void
{
$deleteForm = $this->createForm(FaqFeedbackDeleteType::class);
$deleteForm->handleRequest($this->getRequest());
if (!$deleteForm->isSubmitted() || !$deleteForm->isValid()) {
$this->redirect(BackendModel::createURLForAction('Index') . '&error=something-went-wrong');
}
$deleteFormData = $deleteForm->getData();
$feedbackId = $deleteFormData['id'];
$feedback = BackendFaqModel::getFeedback($feedbackId);
// there is no feedback data, so redirect
if (empty($feedback)) {
$this->redirect(BackendModel::createURLForAction('Index') . '&error=non-existing');
}
BackendFaqModel::deleteFeedback($feedbackId);
$this->redirect(
BackendModel::createURLForAction('Edit') . '&id=' .
$feedback['question_id'] . '&report=deleted#tabFeedback'
);
}
}
|
Make cryptography an optional install dependency | """
Flask-JWT-Extended
-------------------
Flask-Login provides jwt endpoint protection for Flask.
"""
from setuptools import setup
setup(name='Flask-JWT-Extended',
version='1.5.0',
url='https://github.com/vimalloc/flask-jwt-extended',
license='MIT',
author='Landon Gilbert-Bland',
author_email='[email protected]',
description='Extended JWT integration with Flask',
long_description='Extended JWT integration with Flask',
keywords = ['flask', 'jwt', 'json web token'],
packages=['flask_jwt_extended'],
zip_safe=False,
platforms='any',
install_requires=['Flask', 'PyJWT', 'simplekv'],
extras_require={
'asymmetric_crypto': ["cryptography"]
}
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
])
| """
Flask-JWT-Extended
-------------------
Flask-Login provides jwt endpoint protection for Flask.
"""
from setuptools import setup
setup(name='Flask-JWT-Extended',
version='1.5.0',
url='https://github.com/vimalloc/flask-jwt-extended',
license='MIT',
author='Landon Gilbert-Bland',
author_email='[email protected]',
description='Extended JWT integration with Flask',
long_description='Extended JWT integration with Flask',
keywords = ['flask', 'jwt', 'json web token'],
packages=['flask_jwt_extended'],
zip_safe=False,
platforms='any',
install_requires=['Flask', 'PyJWT', 'simplekv', 'cryptography'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
])
|
Fix use of a deprecated API | package io.zucchiniui.backend.support.websocket;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
public class WebSocketEnablerBundle implements ConfiguredBundle<Configuration> {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketEnablerBundle.class);
@Override
public void initialize(final Bootstrap<?> bootstrap) {
}
@Override
public void run(final Configuration config, final Environment environment) {
environment.servlets().addServletListeners(new ServletContextListener() {
@Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
LOGGER.info("Configuring WebSocket container");
try {
WebSocketServerContainerInitializer.initialize(environment.getApplicationContext());
} catch (final ServletException e) {
throw new RuntimeException("Can't enable WebSocket feature for Jetty", e);
}
}
@Override
public void contextDestroyed(final ServletContextEvent servletContextEvent) {
// Nothing to do
}
});
}
}
| package io.zucchiniui.backend.support.websocket;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
public class WebSocketEnablerBundle implements ConfiguredBundle<Configuration> {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketEnablerBundle.class);
@Override
public void initialize(final Bootstrap<?> bootstrap) {
}
@Override
public void run(final Configuration config, final Environment environment) {
environment.servlets().addServletListeners(new ServletContextListener() {
@Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
LOGGER.info("Configuring WebSocket container");
try {
WebSocketServerContainerInitializer.configureContext(environment.getApplicationContext());
} catch (final ServletException e) {
throw new RuntimeException("Can't enable WebSocket feature for Jetty", e);
}
}
@Override
public void contextDestroyed(final ServletContextEvent servletContextEvent) {
// Nothing to do
}
});
}
}
|
Add environmental settings for basic authentication. | import sys
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
# Core environmental settings
INSTALLED_APPS=(
# Put contenttypes before auth to work around test issue.
# See: https://code.djangoproject.com/ticket/10827#comment:12
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'incuna_auth',
),
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',),
AUTH_USER_MODEL='tests.User',
ROOT_URLCONF='incuna_auth.urls',
REST_FRAMEWORK={
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',),
},
# LoginRequiredMiddleware data
LOGIN_REQUIRED_SEND_MESSAGE=False,
LOGIN_EXEMPT_URLS = (
'^exempt-url/$',
'^exempt-and-protected-url/$',
),
LOGIN_PROTECTED_URLS = (
'^exempt-and-protected-url/$',
'^protected-url/$',
),
# BasicAuthenticationMiddleware data
BASIC_WWW_AUTHENTICATION_USERNAME = 'user',
BASIC_WWW_AUTHENTICATION_PASSWORD = 'pass',
BASIC_WWW_AUTHENTICATION = True,
)
from django.test.runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
| import sys
from colour_runner.django_runner import ColourRunnerMixin
from django.conf import settings
settings.configure(
INSTALLED_APPS=(
# Put contenttypes before auth to work around test issue.
# See: https://code.djangoproject.com/ticket/10827#comment:12
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.admin',
'incuna_auth',
),
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',),
AUTH_USER_MODEL='tests.User',
ROOT_URLCONF='incuna_auth.urls',
REST_FRAMEWORK={
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',),
},
LOGIN_REQUIRED_SEND_MESSAGE=False,
LOGIN_EXEMPT_URLS = (
'^exempt-url/$',
'^exempt-and-protected-url/$',
),
LOGIN_PROTECTED_URLS = (
'^exempt-and-protected-url/$',
'^protected-url/$',
),
)
from django.test.runner import DiscoverRunner
class Runner(ColourRunnerMixin, DiscoverRunner):
pass
test_runner = Runner(verbosity=1)
failures = test_runner.run_tests(['tests'])
if failures:
sys.exit(1)
|
Fix when using multiple entity managers.
As per doctrine 2.4 default entity manager is referenced by doctrine.orm.entity_manager. | <?php
namespace Tbbc\MoneyBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
class StorageCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
$storage = $container->getParameter('tbbc_money.pair.storage');
//Determine if DoctrineBundle is defined
if ('doctrine' === $storage) {
if(!isset($bundles['DoctrineBundle'])) {
throw new \RuntimeException('TbbcMoneyBundle - DoctrineBundle is needed to use Doctrine as a storage');
}
$storageDoctrineDefinition = new Definition('Tbbc\MoneyBundle\Pair\Storage\DoctrineStorage', array(
new Reference('doctrine.orm.entity_manager'),
$container->getParameter('tbbc_money.reference_currency')
));
$container->setDefinition('tbbc_money.pair.doctrine_storage', $storageDoctrineDefinition);
$container->getDefinition('tbbc_money.pair_manager')->replaceArgument(0, new Reference('tbbc_money.pair.doctrine_storage'));
}
}
}
| <?php
namespace Tbbc\MoneyBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
class StorageCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
$storage = $container->getParameter('tbbc_money.pair.storage');
//Determine if DoctrineBundle is defined
if ('doctrine' === $storage) {
if(!isset($bundles['DoctrineBundle'])) {
throw new \RuntimeException('TbbcMoneyBundle - DoctrineBundle is needed to use Doctrine as a storage');
}
$storageDoctrineDefinition = new Definition('Tbbc\MoneyBundle\Pair\Storage\DoctrineStorage', array(
new Reference('doctrine.orm.default_entity_manager'),
$container->getParameter('tbbc_money.reference_currency')
));
$container->setDefinition('tbbc_money.pair.doctrine_storage', $storageDoctrineDefinition);
$container->getDefinition('tbbc_money.pair_manager')->replaceArgument(0, new Reference('tbbc_money.pair.doctrine_storage'));
}
}
}
|
Make all lines shorter than 80 characters | import os
import re
class OratioIgnoreParser():
def __init__(self):
self.ignored_paths = ["oratiomodule.tar.gz"]
def load(self, oratio_ignore_path):
with open(oratio_ignore_path, "r") as f:
self.ignored_paths.extend([line.strip() for line in f])
def should_be_ignored(self, filepath):
for ig in self.ignored_paths:
compiled_regex = re.compile(
'^' + re.escape(ig).replace('\\*', '.*') + '$'
)
if compiled_regex.search(filepath) or \
compiled_regex.search(filepath.split('/')[-1]):
return True
return False
def list_files(self, directory):
filepaths = []
ignored_files = []
for root, dirs, files in os.walk("."):
for name in files:
relative_path = os.path.join(root, name)
if relative_path.startswith("./"):
relative_path = relative_path[2:]
if not self.should_be_ignored(relative_path):
filepaths.append(relative_path)
else:
ignored_files.append(relative_path)
return filepaths, ignored_files
| import os
import re
class OratioIgnoreParser():
def __init__(self):
self.ignored_paths = ["oratiomodule.tar.gz"]
def load(self, oratio_ignore_path):
with open(oratio_ignore_path, "r") as f:
self.ignored_paths.extend([line.strip() for line in f])
def should_be_ignored(self, filepath):
for ig in self.ignored_paths:
compiled_regex = re.compile('^' + re.escape(ig).replace('\\*', '.*') + '$')
if compiled_regex.search(filepath) or compiled_regex.search(filepath.split('/')[-1]):
return True
return False
def list_files(self, directory):
filepaths = []
ignored_files = []
for root, dirs, files in os.walk("."):
for name in files:
relative_path = os.path.join(root, name)
if relative_path.startswith("./"):
relative_path = relative_path[2:]
if not self.should_be_ignored(relative_path):
filepaths.append(relative_path)
else:
ignored_files.append(relative_path)
return filepaths, ignored_files
|
Use string "null" if default driver is set to NULL | <?php
namespace Laravel\Scout;
use Illuminate\Support\Manager;
use AlgoliaSearch\Client as Algolia;
use Laravel\Scout\Engines\NullEngine;
use Laravel\Scout\Engines\AlgoliaEngine;
use AlgoliaSearch\Version as AlgoliaUserAgent;
class EngineManager extends Manager
{
/**
* Get a driver instance.
*
* @param string|null $name
* @return mixed
*/
public function engine($name = null)
{
return $this->driver($name);
}
/**
* Create an Algolia engine instance.
*
* @return \Laravel\Scout\Engines\AlgoliaEngine
*/
public function createAlgoliaDriver()
{
AlgoliaUserAgent::addSuffixUserAgentSegment('Laravel Scout', '3.0.7');
return new AlgoliaEngine(new Algolia(
config('scout.algolia.id'), config('scout.algolia.secret')
));
}
/**
* Create a Null engine instance.
*
* @return \Laravel\Scout\Engines\NullEngine
*/
public function createNullDriver()
{
return new NullEngine;
}
/**
* Get the default session driver name.
*
* @return string
*/
public function getDefaultDriver()
{
return $this->app['config']['scout.driver'] ?? 'null';
}
}
| <?php
namespace Laravel\Scout;
use Illuminate\Support\Manager;
use AlgoliaSearch\Client as Algolia;
use Laravel\Scout\Engines\NullEngine;
use Laravel\Scout\Engines\AlgoliaEngine;
use AlgoliaSearch\Version as AlgoliaUserAgent;
class EngineManager extends Manager
{
/**
* Get a driver instance.
*
* @param string|null $name
* @return mixed
*/
public function engine($name = null)
{
return $this->driver($name);
}
/**
* Create an Algolia engine instance.
*
* @return \Laravel\Scout\Engines\AlgoliaEngine
*/
public function createAlgoliaDriver()
{
AlgoliaUserAgent::addSuffixUserAgentSegment('Laravel Scout', '3.0.7');
return new AlgoliaEngine(new Algolia(
config('scout.algolia.id'), config('scout.algolia.secret')
));
}
/**
* Create a Null engine instance.
*
* @return \Laravel\Scout\Engines\NullEngine
*/
public function createNullDriver()
{
return new NullEngine;
}
/**
* Get the default session driver name.
*
* @return string
*/
public function getDefaultDriver()
{
return $this->app['config']['scout.driver'];
}
}
|
Improve Route model binding query for Paste | <?php
namespace Wdi\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Route;
use Wdi\Entities\Language;
use Wdi\Entities\Paste;
/**
* Class RouteServiceProvider
*
* @package Wdi\Providers
*/
final class RouteServiceProvider extends ServiceProvider
{
/** {@inheritdoc} */
public function boot()
{
parent::boot();
Route::model("language", Language::class);
Route::bind("paste", function ($slug) {
return Paste::select(["id", "language_id", "paste_id", "user_id", "slug", "name", "extension", "code", "description", "created_at", "updated_at"])
->where("slug", $slug)->firstOrFail();
});
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapHandlerRoutes();
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
private function mapApiRoutes()
{
Route::prefix("api")->namespace("Wdi\Http\Api")->middleware("api")->group(base_path("routes/api.php"));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
private function mapHandlerRoutes()
{
Route::middleware("web")->group(base_path("routes/handler.php"));
}
}
| <?php
namespace Wdi\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Route;
use Wdi\Entities\Language;
use Wdi\Entities\Paste;
/**
* Class RouteServiceProvider
*
* @package Wdi\Providers
*/
final class RouteServiceProvider extends ServiceProvider
{
/** {@inheritdoc} */
public function boot()
{
parent::boot();
Route::model("paste", Paste::class);
Route::model("language", Language::class);
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapHandlerRoutes();
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
private function mapApiRoutes()
{
Route::prefix("api")->namespace("Wdi\Http\Api")->middleware("api")->group(base_path("routes/api.php"));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
private function mapHandlerRoutes()
{
Route::middleware("web")->group(base_path("routes/handler.php"));
}
}
|
Remove broken authorization header code
The authorization header generation code in receipt.py was setting
the authorization header to a byte stream rather than a string
(b'...'). As requests provides a way to generate basic auth headers
using the auth param it makes more sense to use that. | from app import settings
import logging
from structlog import wrap_logger
import base64
import os
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('%s/templates/' % os.path.dirname(__file__)))
logger = wrap_logger(logging.getLogger(__name__))
def get_receipt_endpoint(decrypted_json):
try:
statistical_unit_id = decrypted_json['metadata']['ru_ref']
exercise_sid = decrypted_json['collection']['exercise_sid']
except KeyError as e:
logger.error("Unable to get required data from json", exception=repr(e))
return None
host = settings.RECEIPT_HOST
path = settings.RECEIPT_PATH
logger.debug("RECEIPT|HOST/PATH: %s/%s" % (host, path))
uri = path + "/" + statistical_unit_id + "/collectionexercises/" + exercise_sid + "/receipts"
endpoint = host + "/" + uri
logger.debug("RECEIPT|ENDPOINT: %s" % endpoint)
return endpoint
def get_receipt_xml(decrypted_json):
try:
template = env.get_template('receipt.xml.tmpl')
output = template.render(survey=decrypted_json)
return output
except Exception as e:
logger.error("Unable to render xml receipt", exception=repr(e))
return None
def get_receipt_headers():
headers = {}
headers['Content-Type'] = "application/vnd.collections+xml"
return headers
| from app import settings
import logging
from structlog import wrap_logger
import base64
import os
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('%s/templates/' % os.path.dirname(__file__)))
logger = wrap_logger(logging.getLogger(__name__))
def get_receipt_endpoint(decrypted_json):
try:
statistical_unit_id = decrypted_json['metadata']['ru_ref']
exercise_sid = decrypted_json['collection']['exercise_sid']
except KeyError as e:
logger.error("Unable to get required data from json", exception=repr(e))
return None
host = settings.RECEIPT_HOST
path = settings.RECEIPT_PATH
logger.debug("RECEIPT|HOST/PATH: %s/%s" % (host, path))
uri = path + "/" + statistical_unit_id + "/collectionexercises/" + exercise_sid + "/receipts"
endpoint = host + "/" + uri
logger.debug("RECEIPT|ENDPOINT: %s" % endpoint)
return endpoint
def get_receipt_xml(decrypted_json):
try:
template = env.get_template('receipt.xml.tmpl')
output = template.render(survey=decrypted_json)
return output
except Exception as e:
logger.error("Unable to render xml receipt", exception=repr(e))
return None
def get_receipt_headers():
headers = {}
auth = settings.RECEIPT_USER + ":" + settings.RECEIPT_PASS
encoded = base64.b64encode(bytes(auth, 'utf-8'))
headers['Authorization'] = "Basic " + str(encoded)
headers['Content-Type'] = "application/vnd.collections+xml"
return headers
|
Return empty array if value is empty | import React, { Component } from 'react';
import { Creatable } from 'react-select';
import R from 'ramda';
import './TagSelect.css';
class TagSelect extends Component {
state = {
multi: true,
multiValue: [],
options: this.props.options,
}
componentWillReceiveProps = nextProps => {
if (nextProps.edit) {
// because it could be user custom tag, we need to put in
// into list of options:
const computedOptions = (values, options) => {
const allOptions = values.reduce((acc, value) => {
const transformedValue = {
value,
label: value,
};
acc.push(transformedValue);
return acc;
}, options);
return R.uniq(allOptions);
};
this.setState({
multiValue: nextProps.input.value,
options: computedOptions(nextProps.input.value, nextProps.options),
});
}
}
handleOnChange = value => {
this.setState((prevState, props) => ({ multiValue: value }));
this.props.input.onChange((value) ? value.split(',') : []);
}
render() {
const { multi, multiValue } = this.state;
return (
<Creatable
{...this.props}
className="j-tags-select"
placeholder={this.props.placeholder}
multi={multi}
simpleValue
options={this.state.options}
onChange={this.handleOnChange}
value={multiValue}
/>
);
}
}
export default TagSelect;
| import React, { Component } from 'react';
import { Creatable } from 'react-select';
import R from 'ramda';
import './TagSelect.css';
class TagSelect extends Component {
state = {
multi: true,
multiValue: [],
options: this.props.options,
}
componentWillReceiveProps = nextProps => {
if (nextProps.edit) {
// because it could be user custom tag, we need to put in
// into list of options:
const computedOptions = (values, options) => {
const allOptions = values.reduce((acc, value) => {
const transformedValue = {
value,
label: value,
};
acc.push(transformedValue);
return acc;
}, options);
return R.uniq(allOptions);
};
this.setState({
multiValue: nextProps.input.value,
options: computedOptions(nextProps.input.value, nextProps.options),
});
}
}
handleOnChange = value => {
this.setState((prevState, props) => ({ multiValue: value }));
this.props.input.onChange(value.split(','));
}
render() {
const { multi, multiValue } = this.state;
return (
<Creatable
{...this.props}
className="j-tags-select"
placeholder={this.props.placeholder}
multi={multi}
simpleValue
options={this.state.options}
onChange={this.handleOnChange}
value={multiValue}
/>
);
}
}
export default TagSelect;
|
Add conf to coverage source setting. | const gulp = require('gulp');
const spawn = require('child_process').spawn;
gulp.task('test', (cb) => {
const command = [ 'run', 'python', 'manage.py', 'test' ];
const args = process.argv;
if (args[3] == '--test' && args[4]) {
command.push(args[4]);
}
spawn(
'pipenv',
command,
{
stdio: 'inherit'
}
).on('exit', (code) => {
process.exit(code);
});
});
gulp.task('coverage', (cb) => {
spawn(
'pipenv',
[
'run',
'coverage',
'run',
'--source=conf,core,api',
'manage.py',
'test'
],
{
stdio: 'inherit'
}
).on('exit', (code) => {
if (code != 0) process.exit(code);
spawn(
'pipenv',
[
'run',
'coverage',
'report',
'-m'
],
{
stdio: 'inherit'
}
).on('exit', (code) => {
if (code != 0) process.exit(code);
return cb;
});
});
});
| const gulp = require('gulp');
const spawn = require('child_process').spawn;
gulp.task('test', (cb) => {
const command = [ 'run', 'python', 'manage.py', 'test' ];
const args = process.argv;
if (args[3] == '--test' && args[4]) {
command.push(args[4]);
}
spawn(
'pipenv',
command,
{
stdio: 'inherit'
}
).on('exit', (code) => {
process.exit(code);
});
});
gulp.task('coverage', (cb) => {
spawn(
'pipenv',
[
'run',
'coverage',
'run',
'--source=core,api',
'manage.py',
'test'
],
{
stdio: 'inherit'
}
).on('exit', (code) => {
if (code != 0) process.exit(code);
spawn(
'pipenv',
[
'run',
'coverage',
'report',
'-m'
],
{
stdio: 'inherit'
}
).on('exit', (code) => {
if (code != 0) process.exit(code);
return cb;
});
});
});
|
Improve doc related to “isMultiTenantSupportInstalled” | import knex from 'knex';
import PromiseAsyncCache from 'promise-async-cache';
import * as knexTenantSupport from './knex-tenant-support';
const debug = require('./debug')('tenant');
/**
* Defines whenever the tenant monkey patch on knex has been installed
*/
let isMultiTenantSupportInstalled = false;
/**
* Keep knex tenants in memory and handle race conditions
*/
const cache = new PromiseAsyncCache({
/**
* Build knex tenant and load it to the cache
* @param tenantId
*/
async load (tenantId, baseKnex) {
if (!isMultiTenantSupportInstalled) {
try {
debug('installing knextancy');
knexTenantSupport.install();
isMultiTenantSupportInstalled = true;
} catch (err) {
debug('Error installing knex multi tenant support', err.stack || err);
throw err;
}
}
debug('building knex for new tenant %d', tenantId);
const proxyKnex = knex(knexTenantSupport.buildConfig(baseKnex.client.config, tenantId));
Object.defineProperty(proxyKnex, 'tenantId', {
get: function() {
return this.client.tenantId;
},
});
debug('initializing multi tenant database');
debug('running migration tasks');
await proxyKnex.migrate.latest();
debug('running seed tasks');
await proxyKnex.seed.run();
return proxyKnex;
},
});
export default async function (baseKnex, tenantId) {
try {
return cache.get(tenantId, baseKnex);
} catch (err) {
debug('Error on initializing the multi tenant database', err.stack || err);
throw err;
}
}
| import knex from 'knex';
import PromiseAsyncCache from 'promise-async-cache';
import * as knexTenantSupport from './knex-tenant-support';
const debug = require('./debug')('tenant');
let isMultiTenantSupportInstalled = false;
/**
* Keep knex tenants in memory and handle race conditions
*/
const cache = new PromiseAsyncCache({
/**
* Build knex tenant and load it to the cache
* @param tenantId
*/
async load (tenantId, baseKnex) {
if (!isMultiTenantSupportInstalled) {
try {
debug('installing knextancy');
knexTenantSupport.install();
isMultiTenantSupportInstalled = true;
} catch (err) {
debug('Error installing knex multi tenant support', err.stack || err);
throw err;
}
}
debug('building knex for new tenant %d', tenantId);
const proxyKnex = knex(knexTenantSupport.buildConfig(baseKnex.client.config, tenantId));
Object.defineProperty(proxyKnex, 'tenantId', {
get: function() {
return this.client.tenantId;
},
});
debug('initializing multi tenant database');
debug('running migration tasks');
await proxyKnex.migrate.latest();
debug('running seed tasks');
await proxyKnex.seed.run();
return proxyKnex;
},
});
export default async function (baseKnex, tenantId) {
try {
return cache.get(tenantId, baseKnex);
} catch (err) {
debug('Error on initializing the multi tenant database', err.stack || err);
throw err;
}
}
|
Add comment about work to be completed | /*
* Copyright 2016 Timothy Brooks
*
* 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 net.uncontended.precipice.circuit;
public class CircuitBreakerConfig<Rejected extends Enum<Rejected>> {
public final Rejected reason;
public final Rejected forcedReason;
public final int failurePercentageThreshold;
public final long failureThreshold;
// TODO: Change these all to nanos to avoid computing millis time
public final long trailingPeriodMillis;
public final long healthRefreshMillis;
public final long backOffTimeMillis;
public final long sampleSizeThreshold;
public CircuitBreakerConfig(Rejected reason, Rejected forcedReason, long failureThreshold, int failurePercentageThreshold,
long trailingPeriodMillis, long healthRefreshMillis, long backOffTimeMillis,
long sampleSizeThreshold) {
this.reason = reason;
this.forcedReason = forcedReason;
this.failureThreshold = failureThreshold;
this.failurePercentageThreshold = failurePercentageThreshold;
this.trailingPeriodMillis = trailingPeriodMillis;
this.healthRefreshMillis = healthRefreshMillis;
this.backOffTimeMillis = backOffTimeMillis;
this.sampleSizeThreshold = sampleSizeThreshold;
}
}
| /*
* Copyright 2016 Timothy Brooks
*
* 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 net.uncontended.precipice.circuit;
public class CircuitBreakerConfig<Rejected extends Enum<Rejected>> {
public final Rejected reason;
public final Rejected forcedReason;
public final int failurePercentageThreshold;
public final long failureThreshold;
public final long trailingPeriodMillis;
public final long healthRefreshMillis;
public final long backOffTimeMillis;
public final long sampleSizeThreshold;
public CircuitBreakerConfig(Rejected reason, Rejected forcedReason, long failureThreshold, int failurePercentageThreshold,
long trailingPeriodMillis, long healthRefreshMillis, long backOffTimeMillis,
long sampleSizeThreshold) {
this.reason = reason;
this.forcedReason = forcedReason;
this.failureThreshold = failureThreshold;
this.failurePercentageThreshold = failurePercentageThreshold;
this.trailingPeriodMillis = trailingPeriodMillis;
this.healthRefreshMillis = healthRefreshMillis;
this.backOffTimeMillis = backOffTimeMillis;
this.sampleSizeThreshold = sampleSizeThreshold;
}
}
|
Fix script to save output to script’s directory. | #!/usr/bin/env python3
from os import scandir
from sys import argv
from platform import uname
from pathlib import Path
filename_template = """
# -------------------------------------------------------------------------------
# filename: {filename}
# -------------------------------------------------------------------------------
{data}
# -------------------------------------------------------------------------------
# END
# -------------------------------------------------------------------------------
"""
def read_and_format_data(filename, outbuf):
"""
Read file and format
Args:
filename:
Returns:
str
"""
with open(filename, 'r') as inbuf:
data = inbuf.read()
data = filename_template.format(filename=filename,
data=data)
outbuf.write(data)
def main(args):
parent_dir = Path(args[0]).parent
lib_dir = parent_dir.joinpath('lib')
hostname = uname()[1]
local_dir = parent_dir.joinpath('local')
outfilename = parent_dir.joinpath("zsh_plugins.zsh")
with open(str(outfilename), 'w') as outbuf:
for filename in scandir(str(lib_dir)):
read_and_format_data(filename.path, outbuf)
for filename in scandir(str(local_dir)):
filename = Path(filename.path)
if filename.stem == hostname:
read_and_format_data(str(filename), outbuf)
if __name__ == "__main__":
main(argv)
| #!/usr/bin/env python3
from os import scandir
from sys import argv
from platform import uname
from pathlib import Path
filename_template = """
# -------------------------------------------------------------------------------
# filename: {filename}
# -------------------------------------------------------------------------------
{data}
# -------------------------------------------------------------------------------
# END
# -------------------------------------------------------------------------------
"""
def read_and_format_data(filename, outbuf):
"""
Read file and format
Args:
filename
Returns:
str
:param outbuf:
"""
with open(filename, 'r') as inbuf:
data = inbuf.read()
data = filename_template.format(filename=filename,
data=data)
outbuf.write(data)
def main(args):
parent_dir = Path(args[0]).parent
lib_dir = parent_dir.joinpath('lib')
hostname = uname()[1]
local_dir = parent_dir.joinpath('local')
with open('zsh_plugins.zsh', 'w') as outbuf:
for filename in scandir(str(lib_dir)):
read_and_format_data(filename.path, outbuf)
for filename in scandir(str(local_dir)):
filename = Path(filename.path)
if filename.stem == hostname:
read_and_format_data(str(filename), outbuf)
if __name__ == "__main__":
main(argv)
|
Improve logs and change delete pos | # -*- coding: utf-8 -*-
import logging
from base import BaseStep
from logical.models import Database
import datetime
LOG = logging.getLogger(__name__)
class BuildDatabase(BaseStep):
def __unicode__(self):
return "Creating logical database..."
def do(self, workflow_dict):
try:
if not workflow_dict['team'] or not workflow_dict['description'] or not workflow_dict['databaseinfra']:
return False
LOG.info("Creating Database...")
database = Database.provision(name= workflow_dict['name'], databaseinfra= workflow_dict['databaseinfra'])
LOG.info("Database %s created!" % database)
workflow_dict['database'] = database
LOG.info("Updating database team")
database.team = workflow_dict['team']
if 'project' in workflow_dict:
LOG.info("Updating database project")
database.project = workflow_dict['project']
LOG.info("Updating database description")
database.description = workflow_dict['description']
database.save()
return True
except Exception, e:
print e
return False
def undo(self, workflow_dict):
try:
if not 'database' in workflow_dict:
return False
LOG.info("Destroying the database....")
if not workflow_dict['database'].is_in_quarantine:
LOG.info("Putting Database in quarentine...")
database = workflow_dict['database']
database.is_in_quarantine= True
database.quarantine_dt = datetime.datetime.now().date()
database.save()
database.delete()
return True
except Exception, e:
print e
return False
| # -*- coding: utf-8 -*-
import logging
from base import BaseStep
from logical.models import Database
LOG = logging.getLogger(__name__)
class BuildDatabase(BaseStep):
def __unicode__(self):
return "Creating logical database..."
def do(self, workflow_dict):
try:
if not workflow_dict['team'] or not workflow_dict['description'] or not workflow_dict['databaseinfra']:
return False
LOG.info("Creating Database...")
database = Database.provision(name= workflow_dict['name'], databaseinfra= workflow_dict['databaseinfra'])
workflow_dict['database'] = database
database.team = workflow_dict['team']
if 'project' in workflow_dict:
database.project = workflow_dict['project']
database.description = workflow_dict['description']
database.save()
return True
except Exception, e:
print e
return False
def undo(self, workflow_dict):
try:
LOG.info("Destroying the database....")
workflow_dict['database'].delete()
return True
except Exception, e:
print e
return False
|
Call to config helper function instead of an instance of the container | <?php
namespace GearHub\LaravelEnhancementSuite\Repositories;
use GearHub\LaravelEnhancementSuite\Contracts\Repositories\RepositoryFactory as RepositoryFactoryContract;
class RepositoryFactory implements RepositoryFactoryContract
{
/**
* Mapping keys to repositories. Takes precidence over the dynamic resolution.
*
* @var array
*/
protected $overrides = [];
/**
* Create new instance of RepositoryFactory.
*
* @param array $overrides
*
* @return void
*/
public function __construct(array $overrides = [])
{
$this->overrides = $overrides;
}
/**
* Get repository for the corresponding model.
* If $key is null return instance of the factory.
*
* @param string|null $key
*
* @return mixed
*/
public function get($key = null)
{
if (!empty($key)) {
$class = null;
if (array_has($this->overrides, $key)) {
$class = array_get($this->overrides, $key);
} else {
$class = $this->build($key);
}
return resolve($class);
}
return $this;
}
/**
* Build the path of the Repository class.
*
* @param string $key
*
* @return string
*/
protected function build($key)
{
return app()->getNamespace() . config('les.repository_namespace') . '\\' . studly_case(str_singular($key)) . 'Repository';
}
}
| <?php
namespace GearHub\LaravelEnhancementSuite\Repositories;
use GearHub\LaravelEnhancementSuite\Contracts\Repositories\RepositoryFactory as RepositoryFactoryContract;
class RepositoryFactory implements RepositoryFactoryContract
{
/**
* Mapping keys to repositories. Takes precidence over the dynamic resolution.
*
* @var array
*/
protected $overrides = [];
/**
* Create new instance of RepositoryFactory.
*
* @param array $overrides
*
* @return void
*/
public function __construct(array $overrides = [])
{
$this->overrides = $overrides;
}
/**
* Get repository for the corresponding model.
* If $key is null return instance of the factory.
*
* @param string|null $key
*
* @return mixed
*/
public function get($key = null)
{
if (!empty($key)) {
$class = null;
if (array_has($this->overrides, $key)) {
$class = array_get($this->overrides, $key);
} else {
$class = $this->build($key);
}
return resolve($class);
}
return $this;
}
/**
* Build the path of the Repository class.
*
* @param string $key
*
* @return string
*/
protected function build($key)
{
return app()->getNamespace() . $this->laravel['config']['les.repository_namespace'] . '\\' . studly_case(str_singular($key)) . 'Repository';
}
}
|
Move requirements to separate file | #!/usr/bin/env python
import sys
from os.path import join, dirname
from setuptools import setup
CURDIR = dirname(__file__)
with open(join(CURDIR, 'requirements.txt')) as f:
REQUIREMENTS = f.read().splitlines()
sys.path.append(join(CURDIR, 'src'))
filename = join(CURDIR, 'src', 'BrowserMobProxyLibrary', 'version.py')
if sys.version_info.major >= 3:
exec(compile(open(filename).read(), filename, 'exec'))
else:
execfile(filename)
setup(name = 'robotframework-browsermobproxylibrary',
version = VERSION,
description = 'BrowserMob Proxy library for Robot Framework',
long_description = DESCRIPTION,
author = 'Marcin Mierzejewski',
author_email = '<[email protected]>',
url = 'https://github.com/s4int/robotframework-BrowserMobProxyLibrary',
license = 'Apache License 2.0',
keywords = 'robotframework testing selenium selenium2 webdriver web browsermob proxy',
platforms = 'any',
classifiers = [
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Software Development :: Testing"
],
install_requires = REQUIREMENTS,
package_dir = {'': 'src'},
packages = ['BrowserMobProxyLibrary'],
)
| #!/usr/bin/env python
import sys
from os.path import join, dirname
from setuptools import setup
sys.path.append(join(dirname(__file__), 'src'))
execfile(join(dirname(__file__), 'src', 'BrowserMobProxyLibrary', 'version.py'))
DESCRIPTION = """
BrowserMobProxyLibrary is a Robot Framework library ro interface with BrowserMob Proxy.
BrowserMob Proxy is a simple utility to capture performance data for web apps (via the HAR format),
as well as manipulate browser behavior and traffic, such as whitelisting and blacklisting content,
simulating network traffic and latency, and rewriting HTTP requests and responses.
"""
setup(name = 'robotframework-browsermobproxylibrary',
version = VERSION,
description = 'BrowserMob Proxy library for Robot Framework',
long_description = DESCRIPTION,
author = 'Marcin Mierzejewski',
author_email = '<[email protected]>',
url = 'https://github.com/s4int/robotframework-BrowserMobProxyLibrary',
license = 'Apache License 2.0',
keywords = 'robotframework testing selenium selenium2 webdriver web browsermob proxy',
platforms = 'any',
classifiers = [
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Software Development :: Testing"
],
install_requires = [
'robotframework >= 2.6.0',
'browsermob-proxy >= 0.7.1',
],
package_dir = {'': 'src'},
packages = ['BrowserMobProxyLibrary'],
)
|
Remove border from dialpad-button to hide the button style on ubuntu | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main;
import java.awt.*;
import java.awt.event.*;
import javax.swing.BorderFactory;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.swing.*;
/**
* The dial pad button in the contact list.
*
* @author Yana Stamcheva
*/
public class DialPadButton
extends SIPCommTextButton
{
/**
* The dial pad dialog that this button opens.
*/
GeneralDialPadDialog dialPad;
/**
* Creates an instance of <tt>DialPadButton</tt>.
*/
public DialPadButton()
{
super("");
loadSkin();
setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (dialPad == null)
dialPad = new GeneralDialPadDialog();
dialPad.clear();
dialPad.setVisible(true);
}
});
}
/**
* Loads images and sets history view.
*/
public void loadSkin()
{
Image image = ImageLoader.getImage(ImageLoader.CONTACT_LIST_DIAL_BUTTON);
setBgImage(image);
this.setPreferredSize(new Dimension(image.getWidth(this),
image.getHeight(this)));
}
}
| /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.gui.main;
import java.awt.*;
import java.awt.event.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.util.swing.*;
/**
* The dial pad button in the contact list.
*
* @author Yana Stamcheva
*/
public class DialPadButton
extends SIPCommTextButton
{
/**
* The dial pad dialog that this button opens.
*/
GeneralDialPadDialog dialPad;
/**
* Creates an instance of <tt>DialPadButton</tt>.
*/
public DialPadButton()
{
super("");
loadSkin();
addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (dialPad == null)
dialPad = new GeneralDialPadDialog();
dialPad.clear();
dialPad.setVisible(true);
}
});
}
/**
* Loads images and sets history view.
*/
public void loadSkin()
{
Image image = ImageLoader.getImage(ImageLoader.CONTACT_LIST_DIAL_BUTTON);
setBgImage(image);
this.setPreferredSize(new Dimension(image.getWidth(this),
image.getHeight(this)));
}
}
|
Convert read data to unicode.
The NamedTemporaryFile is in binary mode by default, so the read returns raw
bytes. | import os
import sys
import tempfile
from twisted.trial import unittest
from twisted.python import util
from comet.icomet import IHandler
from comet.handler import SpawnCommand
SHELL = '/bin/sh'
class DummyEvent(object):
def __init__(self, text=None):
self.text = text or u""
class SpawnCommandProtocolTestCase(unittest.TestCase):
def test_interface(self):
self.assertTrue(IHandler.implementedBy(SpawnCommand))
def test_good_process(self):
spawn = SpawnCommand(sys.executable)
d = spawn(DummyEvent())
d.addCallback(self.assertEqual, True)
return d
def test_bad_process(self):
spawn = SpawnCommand("/not/a/real/executable")
return self.assertFailure(spawn(DummyEvent()), Exception)
def test_write_data(self):
if not os.access(SHELL, os.X_OK):
raise unittest.SkipTest("Shell not available")
TEXT = u"Test spawn process"
output_file = tempfile.NamedTemporaryFile()
def read_data(result):
try:
# NamedTemporaryFile is opened in binary mode, so we need to
# encode the read for comparison.
self.assertEqual(output_file.read().decode('utf-8'), TEXT)
finally:
output_file.close()
spawn = SpawnCommand('/bin/sh', util.sibpath(__file__, "test_spawn.sh"), output_file.name)
d = spawn(DummyEvent(TEXT))
d.addCallback(read_data)
return d
| import os
import sys
import tempfile
from twisted.trial import unittest
from twisted.python import util
from comet.icomet import IHandler
from comet.handler import SpawnCommand
SHELL = '/bin/sh'
class DummyEvent(object):
def __init__(self, text=None):
self.text = text or u""
class SpawnCommandProtocolTestCase(unittest.TestCase):
def test_interface(self):
self.assertTrue(IHandler.implementedBy(SpawnCommand))
def test_good_process(self):
spawn = SpawnCommand(sys.executable)
d = spawn(DummyEvent())
d.addCallback(self.assertEqual, True)
return d
def test_bad_process(self):
spawn = SpawnCommand("/not/a/real/executable")
return self.assertFailure(spawn(DummyEvent()), Exception)
def test_write_data(self):
if not os.access(SHELL, os.X_OK):
raise unittest.SkipTest("Shell not available")
TEXT = "Test spawn process"
output_file = tempfile.NamedTemporaryFile()
def read_data(result):
try:
self.assertEqual(output_file.read(), TEXT)
finally:
output_file.close()
spawn = SpawnCommand('/bin/sh', util.sibpath(__file__, "test_spawn.sh"), output_file.name)
d = spawn(DummyEvent(TEXT))
d.addCallback(read_data)
return d
|
Change Karma port to 8081
This change makes Karma compatible with Cloud9,
because the latter supports only ports 808x. | // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
files: [
{ pattern: './src/test.ts', watched: false }
],
preprocessors: {
'./src/test.ts': ['@angular/cli']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: config.angularCli && config.angularCli.codeCoverage
? ['progress', 'coverage-istanbul']
: ['progress', 'kjhtml'],
port: 8081,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
| // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
files: [
{ pattern: './src/test.ts', watched: false }
],
preprocessors: {
'./src/test.ts': ['@angular/cli']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: config.angularCli && config.angularCli.codeCoverage
? ['progress', 'coverage-istanbul']
: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
|
Fix res returned on delegate | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: David Coninckx <[email protected]>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp.osv import orm
from ..model.sync_typo3 import Sync_typo3
class delegate_child_wizard(orm.TransientModel):
_inherit = 'delegate.child.wizard'
def delegate(self, cr, uid, ids, context=None):
child_ids = self._default_child_ids(cr, uid, context)
child_obj = self.pool.get('compassion.child')
typo3_to_remove_ids = list()
for child in child_obj.browse(cr, uid, child_ids, context):
if (child.state == 'I'):
typo3_to_remove_ids.append(child.id)
if typo3_to_remove_ids:
res = child_obj.child_remove_from_typo3(
cr, uid, typo3_to_remove_ids, context)
res = super(delegate_child_wizard, self).delegate(
cr, uid, ids, context) and res
return res or Sync_typo3.typo3_index_error(cr, uid, self, context)
| # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: David Coninckx <[email protected]>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp.osv import orm
from ..model.sync_typo3 import Sync_typo3
class delegate_child_wizard(orm.TransientModel):
_inherit = 'delegate.child.wizard'
def delegate(self, cr, uid, ids, context=None):
child_ids = self._default_child_ids(cr, uid, context)
child_obj = self.pool.get('compassion.child')
typo3_to_remove_ids = list()
for child in child_obj.browse(cr, uid, child_ids, context):
if (child.state == 'I'):
typo3_to_remove_ids.append(child.id)
if typo3_to_remove_ids:
res = child_obj.child_remove_from_typo3(
cr, uid, typo3_to_remove_ids, context)
res = super(delegate_child_wizard, self).delegate(
cr, uid, ids, context)
return res or Sync_typo3.typo3_index_error(cr, uid, self, context)
|
Set title style and disabled color | package com.quemb.qmbform.view;
import com.quemb.qmbform.R;
import com.quemb.qmbform.descriptor.RowDescriptor;
import android.content.Context;
import android.widget.TextView;
/**
* Created by tonimoeckel on 15.07.14.
*/
public class FormTitleFieldCell extends FormBaseCell {
private TextView mTextView;
public FormTitleFieldCell(Context context,
RowDescriptor rowDescriptor) {
super(context, rowDescriptor);
}
@Override
protected void init() {
super.init();
mTextView = (TextView) findViewById(R.id.textView);
setStyleId(mTextView, CellDescriptor.APPEARANCE_TEXT_LABEL, CellDescriptor.COLOR_LABEL);
}
@Override
protected int getResource() {
return R.layout.text_field_cell;
}
@Override
protected void update() {
String title = getFormItemDescriptor().getTitle();
mTextView.setText(title);
mTextView.setVisibility(title == null ? GONE : VISIBLE);
if (getRowDescriptor().getDisabled()) {
getRowDescriptor().setOnFormRowClickListener(null);
setTextColor(mTextView, CellDescriptor.COLOR_LABEL_DISABLED);
}
}
public TextView getTextView() {
return mTextView;
}
}
| package com.quemb.qmbform.view;
import com.quemb.qmbform.R;
import com.quemb.qmbform.descriptor.RowDescriptor;
import android.content.Context;
import android.widget.TextView;
/**
* Created by tonimoeckel on 15.07.14.
*/
public class FormTitleFieldCell extends FormBaseCell {
private TextView mTextView;
public FormTitleFieldCell(Context context,
RowDescriptor rowDescriptor) {
super(context, rowDescriptor);
}
@Override
protected void init() {
super.init();
mTextView = (TextView) findViewById(R.id.textView);
mTextView.setTextColor(R.attr.editTextColor);
mTextView.setTextAppearance(getContext(), R.style.Base_TextAppearance_AppCompat_Body2);
}
@Override
protected int getResource() {
return R.layout.text_field_cell;
}
@Override
protected void update() {
String title = getFormItemDescriptor().getTitle();
mTextView.setText(title);
mTextView.setVisibility(title == null ? GONE : VISIBLE);
if (getRowDescriptor().getDisabled()) {
getRowDescriptor().setOnFormRowClickListener(null);
mTextView.setTextColor(getResources().getColor(R.color.form_cell_disabled));
}
}
public TextView getTextView() {
return mTextView;
}
}
|
Use a scroll pane for the scroll bar test. | package com.seaglasslookandfeel.demo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TestScrollBars {
public static void main(String[] args) {
if (true) {
try {
UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 500));
panel.setBackground(Color.WHITE);
JScrollPane scrollPane = new JScrollPane(panel);
JFrame frame = new JFrame();
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(275, 125);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
| package com.seaglasslookandfeel.demo;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TestScrollBars {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JScrollBar scrollBar = new JScrollBar(JScrollBar.VERTICAL);
scrollBar.setPreferredSize(new Dimension(15, 300));
JPanel panel = new JPanel();
panel.add(scrollBar, BorderLayout.CENTER);
JFrame frame = new JFrame();
frame.add(panel, BorderLayout.CENTER);
frame.setSize(275, 125);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
|
Add FA icons to buttons | @extends('crudapi::layouts.master')
@section('content')
<h1>{{ $model }}<button class="btn btn-sm btn-success pull-right"><i class="fa fa-plus"></i> Insert {{ $model }}</button></h1>
<table class="table">
<tr>
@foreach($fields as $f)
<th>{{ ucfirst($f) }}</th>
@endforeach
<th>Created At</th>
<th>Updated At</th>
<th>Actions</th>
</tr>
<tbody>
@if(isset($items))
@foreach($items as $item)
<tr>
@foreach($fields as $f)
<td>{{ $item->$f }}</td>
@endforeach
<td>{{ $item->created_at }}</td>
<td>{{ $item->updated_at }}</td>
<td><button class="btn btn-xs btn-info"><i class="fa fa-pencil"></i> Edit</button> <button class="btn btn-xs btn-danger"><i class="fa fa-times"></i> Delete</button></td>
</tr>
@endforeach
@endif
</tbody>
</table>
@stop
| @extends('crudapi::layouts.master')
@section('content')
<h1>{{ $model }}<button class="btn btn-sm btn-success pull-right">Insert {{ $model }}</button></h1>
<table class="table">
<tr>
@foreach($fields as $f)
<th>{{ ucfirst($f) }}</th>
@endforeach
<th>Created At</th>
<th>Updated At</th>
<th>Actions</th>
</tr>
<tbody>
@if(isset($items))
@foreach($items as $item)
<tr>
@foreach($fields as $f)
<td>{{ $item->$f }}</td>
@endforeach
<td>{{ $item->created_at }}</td>
<td>{{ $item->updated_at }}</td>
<td><button class="btn btn-xs btn-info">Edit</button> <button class="btn btn-xs btn-danger">Delete</button></td>
</tr>
@endforeach
@endif
</tbody>
</table>
@stop
|
Fix bug if no voting | @extends('main')
@section('head')
<style>
.row
{
margin-top: 5%;
}
#meme
{
display: block;
margin-left: auto;
margin-right: auto;
}
#progress
{
margin-top: 1%;
}
</style>
@endsection
@section('content')
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="jumbotron">
<div class="page-header">
<h1>
{{{ $meme->name }}} <small><small>{{{ $meme->description }}}</small></small>
</h1>
</div>
<div class="">
<img id="meme" class="img-responsive img-thumbnail" title="{{ $meme->name }}" src="{{{ $image }}}">
@if(isset($code))
<div class="panel-footer text-center">
<a href="{{ URL::to('vote/'.$code.'/1') }}" class="btn btn-success btn-lg" >Spoko</a>
<a href="{{ URL::to('vote/'.$code.'/0') }}" class="btn btn-danger btn-lg" >Suchar</a>
</div>
@endif
</div>
</div>
</div>
</div>
@endsection | @extends('main')
@section('head')
<style>
.row
{
margin-top: 5%;
}
#meme
{
display: block;
margin-left: auto;
margin-right: auto;
}
#progress
{
margin-top: 1%;
}
</style>
@endsection
@section('content')
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="jumbotron">
<div class="page-header">
<h1>
{{{ $meme->name }}} <small><small>{{{ $meme->description }}}</small></small>
</h1>
</div>
<div class="">
<img id="meme" class="img-responsive img-thumbnail" title="{{ $meme->name }}" src="{{{ $image }}}">
<div class="panel-footer text-center">
<a href="{{ URL::to('vote/'.$code.'/1') }}" class="btn btn-success btn-lg" >Spoko</a>
<a href="{{ URL::to('vote/'.$code.'/0') }}" class="btn btn-danger btn-lg" >Suchar</a>
</div>
</div>
</div>
</div>
</div>
@endsection |
Add a generic load method for routes
Signed-off-by: Kaustav Das Modak <[email protected]> | 'use strict';
/**
* Finder Model - Main model that uses FinderJS
*
* @constructor
*/
var FinderModel = function (arg) {
// Assign `this` through `riot.observable()`
var self = riot.observable(this);
// Store args
self.args = arg;
// Create an instance of `Applait.Finder`
self.finder = new Applait.Finder({
type: "sdcard",
minSearchLength: 2,
debugMode: arg.debug
});
// Current search results
self.searchResults = [];
/**
* Reset all internals
*/
self.reset = function () {
self.searchResults = [];
self.finder.reset();
};
/**
* Initiate search
*
* @param {string} key - The search string
*/
self.search = function (key) {
self.reset();
self.finder.search(key);
};
/**
* Subscribe to Finder's fileFound event
*/
self.finder.on("fileFound", function (file) {
self.searchResults.push(file);
});
/**
* Subscribe to Finder's searchComplete event
*
* The `resultsFound` is triggered if any file is matched.
* Else, `noResults` is triggered
*/
self.finder.on("searchComplete", function () {
if (self.searchResults.length && self.finder.filematchcount) {
self.trigger("resultsFound");
} else {
self.trigger("noResults");
}
});
/**
* Provide a generic "load" method for routing
*/
self.load = function (path) {
self.trigger("load:" + path);
};
};
| 'use strict';
/**
* Finder Model - Main model that uses FinderJS
*
* @constructor
*/
var FinderModel = function (arg) {
// Assign `this` through `riot.observable()`
var self = riot.observable(this);
// Store args
self.args = arg;
// Create an instance of `Applait.Finder`
self.finder = new Applait.Finder({
type: "sdcard",
minSearchLength: 2,
debugMode: arg.debug
});
// Current search results
self.searchResults = [];
/**
* Reset all internals
*/
self.reset = function () {
self.searchResults = [];
self.finder.reset();
};
/**
* Initiate search
*
* @param {string} key - The search string
*/
self.search = function (key) {
self.reset();
self.finder.search(key);
};
/**
* Subscribe to Finder's fileFound event
*/
self.finder.on("fileFound", function (file) {
self.searchResults.push(file);
});
/**
* Subscribe to Finder's searchComplete event
*
* The `resultsFound` is triggered if any file is matched.
* Else, `noResults` is triggered
*/
self.finder.on("searchComplete", function () {
if (self.searchResults.length && self.finder.filematchcount) {
self.trigger("resultsFound");
} else {
self.trigger("noResults");
}
});
};
|
Put in a max for how many entities will be generated | var chance = require('./fake-extension.js'),
glimpse = require('glimpse'),
maxEvents = chance.integerRange(25, 35),
currentEvent = 0;
function publishEntry() {
var mvc = chance.mvc(),
serverLowerTime = chance.integerRange(5, 10),
serverUpperTime = chance.integerRange(60, 100),
networkTime = chance.integerRange(0, 15),
clientTime = chance.integerRange(20, 120),
serverTime = chance.integerRange(serverLowerTime, serverUpperTime),
actionTime = chance.integerRange(serverLowerTime, serverUpperTime),
viewTime = serverTime - actionTime,
queryTime = chance.integerRange(2, actionTime / 3),
item = {
id: chance.guid(),
url: mvc.url,
method: chance.method(),
status: chance.status(),
duration: clientTime + serverTime + networkTime,
networkTime: networkTime,
serverTime: serverTime,
clientTime: clientTime,
controller: mvc.controller,
action: mvc.action,
actionTime: actionTime,
viewTime: viewTime,
queryTime: queryTime,
queryCount: chance.integerRange(1, 4),
last: (chance.integerRange(1, 45) + ' sec ago ')
};
glimpse.emit('data.request.entry.updated', item);
if (currentEvent++ < maxEvents) {
setTimeout(publishEntry, chance.integerRange(3000, 5000));
}
}
publishEntry();
| var chance = require('./fake-extension.js'),
glimpse = require('glimpse');
function publishEntry() {
var mvc = chance.mvc(),
serverLowerTime = chance.integerRange(5, 10),
serverUpperTime = chance.integerRange(60, 100),
networkTime = chance.integerRange(0, 15),
clientTime = chance.integerRange(20, 120),
serverTime = chance.integerRange(serverLowerTime, serverUpperTime),
actionTime = chance.integerRange(serverLowerTime, serverUpperTime),
viewTime = serverTime - actionTime,
queryTime = chance.integerRange(2, actionTime / 3),
item = {
id: chance.guid(),
url: mvc.url,
method: chance.method(),
status: chance.status(),
duration: clientTime + serverTime + networkTime,
networkTime: networkTime,
serverTime: serverTime,
clientTime: clientTime,
controller: mvc.controller,
action: mvc.action,
actionTime: actionTime,
viewTime: viewTime,
queryTime: queryTime,
queryCount: chance.integerRange(1, 4),
last: (chance.integerRange(1, 45) + ' sec ago ')
};
glimpse.emit('data.request.entry.updated', item);
setTimeout(publishEntry, chance.integerRange(3000, 5000));
}
publishEntry();
|
Move created from construct to create | <?php
class Game extends ActiveRecordBase {
public $id;
public $created;
public $width;
public $height;
public $rounds;
public function __construct( $id = false ) {
if ( $id ) {
$this->exists = true;
$game_info = dbSelectOne( 'games', array( 'created', 'width', 'height' ), compact( 'id' ) );
$this->id = $gameid = $id;
$this->created = $game_info[ 'created' ];
$this->width = $game_info[ 'width' ];
$this->height = $game_info[ 'height' ];
$rounds = dbSelect( 'roundcreatures', array( 'roundid' ), compact( 'gameid' ) );
for ( $i = 0; $i <= count( $rounds ); ++$i ) {
$this->rounds[ $i ] = new Round( $this, $i );
}
}
}
protected function validate() {
if ( !is_int( $this->width ) ) {
throw new ModelValidationException( 'width_not_valid' );
}
if ( !is_int( $this->height ) ) {
throw new ModelValidationException( 'height_not_valid' );
}
}
protected function create() {
$width = $this->width;
$height = $this->height;
$created = $this->created = date('Y-m-d H:i:s');
$this->id = dbInsert(
'games',
compact( 'width', 'height', 'created' )
);
}
}
?>
| <?php
class Game extends ActiveRecordBase {
public $id;
public $created;
public $width;
public $height;
public $rounds;
public function __construct( $id = false ) {
if ( $id ) {
$this->exists = true;
$game_info = dbSelectOne( 'games', array( 'created', 'width', 'height' ), compact( 'id' ) );
$this->id = $gameid = $id;
$this->created = $game_info[ 'created' ];
$this->width = $game_info[ 'width' ];
$this->height = $game_info[ 'height' ];
$rounds = dbSelect( 'roundcreatures', array( 'roundid' ), compact( 'gameid' ) );
for ( $i = 0; $i <= count( $rounds ); ++$i ) {
$this->rounds[ $i ] = new Round( $this, $i );
}
$this->created = date('Y-m-d H:i:s');
}
}
protected function validate() {
if ( !is_int( $this->width ) ) {
throw new ModelValidationException( 'width_not_valid' );
}
if ( !is_int( $this->height ) ) {
throw new ModelValidationException( 'height_not_valid' );
}
}
protected function create() {
$width = $this->width;
$height = $this->height;
$created = $this->created;
$this->id = dbInsert(
'games',
compact( 'width', 'height', 'created' )
);
}
}
?>
|
Add button full component to shopping list | import React, {Component} from 'react';
import { View, Text, ScrollView } from 'react-native';
import { Button } from 'native-base';
import axios from 'axios';
import colors from '../config/colors';
import { UserItem } from '../components/UserItem';
class ShoppingList extends Component {
constructor(props) {
super(props);
this.state = {
userItems: []
};
this.getUserItems = this.getUserItems.bind(this);
this.handleButtonPress = this.handleButtonPress.bind(this);
}
componentDidMount() {
this.getUserItems();
}
getUserItems() {
axios.get('http://localhost:3000/user_items')
.then(response => {
this.setState({userItems: response.data})
})
.catch(error => {
console.log(error);
});
}
handleButtonPress() {
this.props.navigation.navigate('PickStop');
};
render() {
return (
<View style={{ backgroundColor: colors.background }}>
<ScrollView style={{ backgroundColor: colors.background}}>
{this.state.userItems.map((userItem, idx) => (
<UserItem user_item={userItem} getUserItems={this.getUserItems} key={idx} />
))}
</ScrollView>
<Button full onPress={() => this.handleButtonPress()}>
<Text>Find Yo' Stop!</Text>
</Button>
</View>
);
}
}
export default ShoppingList;
| import React, {Component} from 'react';
import { View, Text, ScrollView, Button } from 'react-native';
import axios from 'axios';
import colors from '../config/colors';
import { UserItem } from '../components/UserItem';
class ShoppingList extends Component {
constructor(props) {
super(props);
this.state = {
userItems: []
};
this.getUserItems = this.getUserItems.bind(this);
this.handleButtonPress = this.handleButtonPress.bind(this);
}
componentDidMount() {
this.getUserItems();
}
getUserItems() {
axios.get('http://localhost:3000/user_items')
.then(response => {
this.setState({userItems: response.data})
})
.catch(error => {
console.log(error);
});
}
handleButtonPress() {
this.props.navigation.navigate('PickStop');
};
render() {
return (
<View style={{ backgroundColor: colors.background }}>
<ScrollView style={{ backgroundColor: colors.background}}>
{this.state.userItems.map((userItem, idx) => (
<UserItem user_item={userItem} getUserItems={this.getUserItems} key={idx} />
))}
</ScrollView>
<Button
onPress={() => this.handleButtonPress()}
title="Find Yo' Stop!"
color={colors.buttonText}
backgroundColor={colors.buttonBackground}
accessibilityLabel="Find Your Stop for One Stop Shopping"
style={{height: 600}}
/>
</View>
);
}
}
export default ShoppingList;
|
Change Avatar Title and Sub-Title strings | import React, { PropTypes, Component } from 'react'
import classes from './PostItem.scss'
import { ListItem } from 'material-ui/List'
import Delete from 'material-ui/svg-icons/action/delete'
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import profilePic from 'static/image/2frere.jpg'
import { isObject } from 'lodash'
export default class PostItem extends Component {
static propTypes = {
post: PropTypes.object.isRequired,
id: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
])
}
render () {
const { post, id, onDeleteClick } = this.props
const date = new Date(parseInt(post.date)).toLocaleString('FR-ca')
return (
<div className={classes.container}>
<Card>
<CardHeader
title="Les 6 jours de Garonne"
subtitle="De Toulouse à Bordeaux en Kayak sur la Garonne"
avatar={profilePic}
/>
<CardMedia
overlay={<CardTitle title={post.title} subtitle={post.subTitle} />}
>
<img src={post.imageUrl} />
</CardMedia>
<CardTitle title={post.titre} subtitle={post.subTitle} />
<CardText>
{post.text}
</CardText>
<CardText>
{date}
</CardText>
</Card>
</div>
)
}
}
| import React, { PropTypes, Component } from 'react'
import classes from './PostItem.scss'
import { ListItem } from 'material-ui/List'
import Delete from 'material-ui/svg-icons/action/delete'
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import profilePic from 'static/image/2frere.jpg'
import { isObject } from 'lodash'
export default class PostItem extends Component {
static propTypes = {
post: PropTypes.object.isRequired,
id: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
])
}
render () {
const { post, id, onDeleteClick } = this.props
const date = new Date(parseInt(post.date)).toLocaleString('FR-ca')
return (
<div className={classes.container}>
<Card>
<CardHeader
title="Jérôme et Jean-François"
subtitle="Les deux frères"
avatar={profilePic}
/>
<CardMedia
overlay={<CardTitle title={post.title} subtitle={post.subTitle} />}
>
<img src={post.imageUrl} />
</CardMedia>
<CardTitle title={post.titre} subtitle={post.subTitle} />
<CardText>
{post.text}
</CardText>
<CardText>
{date}
</CardText>
</Card>
</div>
)
}
}
|
Remove enum to gain flexibility | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBusinessesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('businesses', function(Blueprint $table)
{
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->string('slug')->unique();
$table->string('name');
$table->string('description');
$table->string('postal_address')->nullable();
$table->string('phone')->nullable();
$table->string('social_facebook')->nullable();
$table->string('timezone');
$table->string('strategy', 15)->default('timeslot'); /* Appointment Booking Strategy */
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('businesses');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBusinessesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('businesses', function(Blueprint $table)
{
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->string('slug')->unique();
$table->string('name');
$table->string('description');
$table->string('postal_address')->nullable();
$table->string('phone')->nullable();
$table->string('social_facebook')->nullable();
$table->string('timezone');
$table->enum('strategy', ['dateslot', 'timeslot'])->default('timeslot'); /* Appointment Booking Strategy */
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('businesses');
}
}
|
Enable CORS ignore orgin header | const Hapi = require('@hapi/hapi');
const routes = require('./routes');
const auth = require('./auth');
module.exports = async (elastic, config, cb) => {
const server = new Hapi.Server({ port: config.port, routes: { cors: { origin: "ignore" }, log: { collect: true } } });
server.route(routes(elastic, config));
if (config.auth) {
server.route(auth());
await server.register(require('hapi-auth-jwt2'));
await server.register(require('./auth/authentication'));
}
try {
await server.register([
{
plugin: require('good'),
options: {
reporters: {
console: [{ module: 'good-console' }, 'stdout']
}
}
},
require('inert'),
require('vision'),
require('h2o2'),
{
plugin: require('./routes/plugins/error'),
options: {
config: config
}
}
]);
} catch (err) {
return cb(err);
}
server.views({
engines: { html: { module: require('handlebars'), compileMode: 'sync' } },
relativeTo: __dirname,
path: './templates/pages',
layout: 'default',
layoutPath: './templates/layouts',
partialsPath: './templates/partials',
helpersPath: './templates/helpers'
});
cb(null, { server, elastic });
};
| const Hapi = require('@hapi/hapi');
const routes = require('./routes');
const auth = require('./auth');
module.exports = async (elastic, config, cb) => {
const server = new Hapi.Server({ port: config.port, routes: { cors: true, log: { collect: true } } });
server.route(routes(elastic, config));
if (config.auth) {
server.route(auth());
await server.register(require('hapi-auth-jwt2'));
await server.register(require('./auth/authentication'));
}
try {
await server.register([
{
plugin: require('good'),
options: {
reporters: {
console: [{ module: 'good-console' }, 'stdout']
}
}
},
require('inert'),
require('vision'),
require('h2o2'),
{
plugin: require('./routes/plugins/error'),
options: {
config: config
}
}
]);
} catch (err) {
return cb(err);
}
server.views({
engines: { html: { module: require('handlebars'), compileMode: 'sync' } },
relativeTo: __dirname,
path: './templates/pages',
layout: 'default',
layoutPath: './templates/layouts',
partialsPath: './templates/partials',
helpersPath: './templates/helpers'
});
cb(null, { server, elastic });
};
|
Refactor parser again to remove use of exceptions | define(function() {
'use strict';
/**
* @class
*/
function CurrencyParser() { }
/**
* Array of recognised currency formats, each with a regex pattern
* and a parser function which receives the first matched group.
*/
var formats = [
{
// Just pence, with optional 'p'
pattern: /^(\d+)p?$/,
parser: function (str) { return parseInt(str); }
},
{
// Just pounds, with '£' and optional 'p'
pattern: /^£(\d+)p?$/,
parser: function (str) { return parseInt(str) * 100; }
},
{
// Pounds and pence, with decimal point, and optional '£' and/or 'p'
pattern: /^£?(\d+(\.\d*))p?$/,
parser: function (str) { return Math.round(parseFloat(str) * 100); }
},
];
/**
* Parse the specified string and return a number of pence Sterling
* @param {String} input - The string to be parsed
* @returns {Number} Value in pence, or undefined if parsing failed
*/
CurrencyParser.prototype.parseString = function(input) {
for (var i = 0; i < formats.length; i++) {
var format = formats[i];
var matches = input.match(format.pattern);
if (matches)
return format.parser(matches[1]);
}
// Return undefined if no format was matched
};
// Return constructor
return CurrencyParser;
});
| define(function() {
'use strict';
/**
* @class
*/
function CurrencyParser() { }
function ParseError() { }
var penceOnlyParser = function (str) {
var found = str.match(/^(\d+)p?$/);
if (found === null)
throw new ParseError();
else
return parseInt(found[1]);
};
var poundsOnlyParser = function (str) {
var found = str.match(/^£(\d+)p?$/);
if (found === null)
throw new ParseError();
else
return parseInt(found[1] * 100);
};
var poundsAndPenceParser = function (str) {
var found = str.match(/^£?(\d+(\.\d*))p?$/);
if (found === null)
throw new ParseError();
else
return Math.round(parseFloat(found[1]) * 100);
};
var parsers = [
penceOnlyParser,
poundsOnlyParser,
poundsAndPenceParser
];
/**
* Parse the supplied string as a number of British pence
* @param {String} subject - The string to be parsed
* @returns {Number} The value of the string in pence
*/
CurrencyParser.prototype.parseString = function(str) {
for (var i = 0; i < parsers.length; i++) {
try {
var parser = parsers[i];
return parser(str)
} catch (e) {
continue;
}
}
// Return undefined if no parser succeeded
};
// Return constructor
return CurrencyParser;
});
|
Add 'use strict' for javascript's spec | /**
* Created by Victor Avendano on 1/10/15.
* [email protected]
*/
'use strict';
(function(){
var mod = angular.module('routeScripts', ['ngRoute']);
mod.directive('routeScripts', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'A',
link: function (scope, element) {
var html = '<script ng-src="{{jsUrl}}" ng-repeat="(routeCtrl, jsUrl) in routeScripts"></script>';
element.append($compile(html)(scope));
scope.routeScripts = {};
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if(current && current.$$route && current.$$route.js){
if(!Array.isArray(current.$$route.js)){
current.$$route.js = [current.$$route.js];
}
angular.forEach(current.$$route.js, function(script){
delete scope.routeScripts[script];
});
}
if(next && next.$$route && next.$$route.js){
if(!Array.isArray(next.$$route.js)){
next.$$route.js = [next.$$route.js];
}
angular.forEach(next.$$route.js, function(script){
scope.routeScripts[script] = script;
});
}
});
}
};
}
]);
})(); | /**
* Created by Victor Avendano on 1/10/15.
* [email protected]
*/
(function(){
var mod = angular.module('routeScripts', ['ngRoute']);
mod.directive('routeScripts', ['$rootScope','$compile',
function($rootScope, $compile){
return {
restrict: 'A',
link: function (scope, element) {
var html = '<script ng-src="{{jsUrl}}" ng-repeat="(routeCtrl, jsUrl) in routeScripts"></script>';
element.append($compile(html)(scope));
scope.routeScripts = {};
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if(current && current.$$route && current.$$route.js){
if(!Array.isArray(current.$$route.js)){
current.$$route.js = [current.$$route.js];
}
angular.forEach(current.$$route.js, function(script){
delete scope.routeScripts[script];
});
}
if(next && next.$$route && next.$$route.js){
if(!Array.isArray(next.$$route.js)){
next.$$route.js = [next.$$route.js];
}
angular.forEach(next.$$route.js, function(script){
scope.routeScripts[script] = script;
});
}
});
}
};
}
]);
})(); |
Add TEMPLATES configuration for Django v1.10 purposes. | import sys
import django
from django.conf import settings
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'shopify_auth',
),
AUTHENTICATION_BACKENDS=(
'shopify_auth.backends.ShopUserBackend',
),
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
),
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True
}
],
ROOT_URLCONF = 'shopify_auth.urls',
SHOPIFY_APP_NAME='Test App',
SHOPIFY_APP_API_KEY='test-api-key',
SHOPIFY_APP_API_SECRET='test-api-secret',
SHOPIFY_APP_API_SCOPE='read_products',
SHOPIFY_APP_IS_EMBEDDED=True,
SHOPIFY_APP_DEV_MODE=False,
)
django.setup()
from django.test.runner import DiscoverRunner
test_runner = DiscoverRunner()
failures = test_runner.run_tests(['shopify_auth'])
if failures:
sys.exit(failures)
| import sys
import django
from django.conf import settings
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
INSTALLED_APPS=(
'django.contrib.auth',
'django.contrib.contenttypes',
'shopify_auth',
),
AUTHENTICATION_BACKENDS=(
'shopify_auth.backends.ShopUserBackend',
),
MIDDLEWARE_CLASSES=(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
),
ROOT_URLCONF = 'shopify_auth.urls',
SHOPIFY_APP_NAME='Test App',
SHOPIFY_APP_API_KEY='test-api-key',
SHOPIFY_APP_API_SECRET='test-api-secret',
SHOPIFY_APP_API_SCOPE='read_products',
SHOPIFY_APP_IS_EMBEDDED=True,
SHOPIFY_APP_DEV_MODE=False,
)
django.setup()
from django.test.runner import DiscoverRunner
test_runner = DiscoverRunner()
failures = test_runner.run_tests(['shopify_auth'])
if failures:
sys.exit(failures)
|
refactor: Move the issue details over to using $modal. | var mod = angular.module('Trestle.issue', []);
mod.controller('IssueCtrl', function($scope, $modal, $rootScope) {
// init
$scope.$id = "IssueCtrl_" + $scope.$id;
_.extend(this, {
init: function(issue) {
this.issue = issue;
},
isPullRequest: function() {
return this.issue.pull_request && this.issue.pull_request.html_url;
},
getAssignedUser: function() {
return this.issue.assignee;
},
showIssueDetails: function() {
// Create a local scope for the template and add the issue into it
var modal_scope = $rootScope.$new();
modal_scope.issue = this.issue;
var opts = {
scope : modal_scope,
windowClass : 'issue_details_modal',
backdrop : true,
keyboard : true,
templateUrl : "board/issue_details/issue_details.tpl.html"
};
$modal.open(opts);
}
});
this.init($scope.$parent.issue);
});
mod.directive('trIssueCard', function() {
return {
restrict: 'EA',
replace: true,
templateUrl: "issue/issue.tpl.html",
scope: {
// XXX: This should allow access in the template but is not for some reason
// need to figure this out and make better.
issue: '=issue'
}
};
});
| var mod = angular.module('Trestle.issue', []);
mod.controller('IssueCtrl', function($scope, $dialog) {
// init
$scope.$id = "IssueCtrl_" + $scope.$id;
_.extend(this, {
init: function(issue) {
this.issue = issue;
},
isPullRequest: function() {
return this.issue.pull_request && this.issue.pull_request.html_url;
},
getAssignedUser: function() {
return this.issue.assignee;
},
showIssueDetails: function() {
var me = this;
var opts = {
backdrop : true,
keyboard : true,
backdropClick : true,
templateUrl : "board/issue_details/issue_details.tpl.html",
resolve: {
issue: function() { return me.issue; } // angular.copy ??
}
};
var d = $dialog.dialog(opts);
d.open();
}
});
this.init($scope.$parent.issue);
});
mod.directive('trIssueCard', function() {
return {
restrict: 'EA',
replace: true,
templateUrl: "issue/issue.tpl.html",
scope: {
// XXX: This should allow access in the template but is not for some reason
// need to figure this out and make better.
issue: '=issue'
}
};
});
|
Remove border from search input | import React from 'react';
import styled, { css } from 'styled-components';
import PropTypes from 'prop-types';
import { transitionOpacity } from 'mixins';
import HeaderButton from 'components/HeaderButton';
import theme from 'theme';
const StyledContainer = styled.div`
display: flex;
position: absolute;
width: 100%;
height: 100%;
${transitionOpacity}
`;
const closeBar = css`
background: ${theme.black};
content: '';
height: 3px;
width: 20px;
position: absolute;
top: 7px;
left: -1px;
`;
const CloseSearch = styled.div`
height: 18px;
width: 18px;
position: relative;
&::after {
${closeBar}
transform: rotate(45deg);
}
&::before {
${closeBar}
transform: rotate(-45deg);
}
`;
const StyledInput = styled.input`
border: 0;
flex: 1 0 calc(100% - 65px);
padding-left: 25px;
`;
const Search = (props) => {
return (
<StyledContainer show={props.show}>
<StyledInput type="text" placeholder="Find a movie" />
<HeaderButton>
<CloseSearch onClick={props.close} />
</HeaderButton>
</StyledContainer>
);
}
Search.propTypes = {
close: PropTypes.func.isRequired,
show: PropTypes.bool.isRequired,
};
export default Search;
| import React from 'react';
import styled, { css } from 'styled-components';
import PropTypes from 'prop-types';
import { transitionOpacity } from 'mixins';
import HeaderButton from 'components/HeaderButton';
import theme from 'theme';
const StyledContainer = styled.div`
display: flex;
position: absolute;
width: 100%;
height: 100%;
${transitionOpacity}
`;
const closeBar = css`
background: ${theme.black};
content: '';
height: 3px;
width: 20px;
position: absolute;
top: 7px;
left: -1px;
`;
const CloseSearch = styled.div`
height: 18px;
width: 18px;
position: relative;
&::after {
${closeBar}
transform: rotate(45deg);
}
&::before {
${closeBar}
transform: rotate(-45deg);
}
`;
const StyledInput = styled.input`
flex: 1 0 calc(100% - 65px);
padding-left: 25px;
`;
const Search = (props) => {
return (
<StyledContainer show={props.show}>
<StyledInput type="text" placeholder="Find a movie" />
<HeaderButton>
<CloseSearch onClick={props.close} />
</HeaderButton>
</StyledContainer>
);
}
Search.propTypes = {
close: PropTypes.func.isRequired,
show: PropTypes.bool.isRequired,
};
export default Search;
|
Update to match changes in ob-airtable | import os
from luigi import Parameter
from ob_airtable import AirtableClient
AIRTABLE_EXPT_TABLE = 'Genomics%20Expt'
AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample'
S3_BUCKET = os.environ.get('S3_BUCKET')
client = AirtableClient()
def get_samples(expt_id):
expt = client.get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE)
sample_keys = expt['fields']['Genomics samples']
for sample_key in sample_keys:
sample = client.get_record(sample_key, AIRTABLE_SAMPLE_TABLE)
yield sample['fields']['Name']
class Sample(object):
sample_id = Parameter()
@property
def sample(self):
if not hasattr(self, '_sample'):
self._sample = client.get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields']
return self._sample
@property
def sample_folder(self):
return '{expt}/{sample}'.format(
bucket=S3_BUCKET,
expt = self.experiment['Name'],
sample=self.sample_id)
@property
def experiment(self):
if not hasattr(self, '_experiment'):
expt_key = self.sample['Experiment'][0]
self._experiment = client.get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields']
return self._experiment
| import os
from luigi import Parameter
from ob_airtable import get_record_by_name, get_record
AIRTABLE_EXPT_TABLE = 'Genomics%20Expt'
AIRTABLE_SAMPLE_TABLE = 'Genomics%20Sample'
S3_BUCKET = os.environ.get('S3_BUCKET')
def get_samples(expt_id):
expt = get_record_by_name(expt_id, AIRTABLE_EXPT_TABLE)
sample_keys = expt['fields']['Genomics samples']
for sample_key in sample_keys:
sample = get_record(sample_key, AIRTABLE_SAMPLE_TABLE)
yield sample['fields']['Name']
class Sample(object):
sample_id = Parameter()
@property
def sample(self):
if not hasattr(self, '_sample'):
self._sample = get_record_by_name(self.sample_id, AIRTABLE_SAMPLE_TABLE)['fields']
return self._sample
@property
def sample_folder(self):
return '{expt}/{sample}'.format(
bucket=S3_BUCKET,
expt = self.experiment['Name'],
sample=self.sample_id)
@property
def experiment(self):
if not hasattr(self, '_experiment'):
expt_key = self.sample['Experiment'][0]
self._experiment = get_record(expt_key, AIRTABLE_EXPT_TABLE)['fields']
return self._experiment
|
Add visit counter for rooms. | Meteor.methods({
userAddVisitedRoom: function(roomId) {
var rooms = Rooms.find({
_id: roomId
}, {
_id: 1
});
if (rooms.count() === 0) {
throw new Meteor.Error(422, 'Room does not exist');
}
var users = Meteor.users.find({
$and: [{
_id: Meteor.userId()
}, {
visitedRooms: {
$elemMatch: {
room_id: roomId
}
}
}]
}, {
_id: 1
});
if (users.count() === 0) {
Meteor.users.update({
_id: Meteor.userId()
}, {
$push: {
visitedRooms: {
when: new Date(),
room_id: roomId
}
}
});
Rooms.update({
_id: roomId
}, {
$inc: {
visits: 1
}
});
}
},
userUpdate: function(user) {
validateUser(user);
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: user
});
}
});
var validateUser = function(user) {
check(user, {
'profile.fullname': String,
'profile.company': String,
'profile.location': String,
'profile.about': String,
'profile.skills': Array,
'profile.interests': Array,
'profile.availability': {
morning: Boolean,
afternoon: Boolean,
night: Boolean
},
'profile.timezone': String
});
}; | Meteor.methods({
userAddVisitedRoom: function(roomId) {
var rooms = Rooms.find({
_id: roomId
}, {
_id: 1
});
if (rooms.count() === 0) {
throw new Meteor.Error(422, 'Room does not exist');
}
var users = Meteor.users.find({
$and: [{
_id: Meteor.userId()
}, {
visitedRooms: {
$elemMatch: {
room_id: roomId
}
}
}]
}, {
_id: 1
});
if (users.count() === 0) {
Meteor.users.update({
_id: Meteor.userId()
}, {
$push: {
visitedRooms: {
when: new Date(),
room_id: roomId
}
}
});
}
},
userUpdate: function(user) {
validateUser(user);
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: user
});
}
});
var validateUser = function(user) {
check(user, {
'profile.fullname': String,
'profile.company': String,
'profile.location': String,
'profile.about': String,
'profile.skills': Array,
'profile.interests': Array,
'profile.availability': {
morning: Boolean,
afternoon: Boolean,
night: Boolean
},
'profile.timezone': String
});
}; |
Update path fonts gulp task | // imports
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
// build src
gulp.task('browserify', function(cb){
return browserify('./src/app.js', {
debug: true
})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./www/'));
cb();
});
// build in release mode
gulp.task('browserify:release', function(cb){
return browserify('./src/app.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./www/'));
cb();
});
// copy fonts
gulp.task('fonts', function(cb){
return gulp.src('node_modules/ionic-npm/fonts/**')
.pipe(gulp.dest('./www/fonts/'));
cb();
});
// copy assets
gulp.task('assets', function(cb){
return gulp.src('./assets/**')
.pipe(gulp.dest('./www/'));
cb();
});
// copy templates
gulp.task('templates', function(cb){
return gulp.src('./src/**/*.html')
.pipe(gulp.dest('./www/'));
cb();
});
| // imports
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var buffer = require('vinyl-buffer');
// build src
gulp.task('browserify', function(cb){
return browserify('./src/app.js', {
debug: true
})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./www/'));
cb();
});
// build in release mode
gulp.task('browserify:release', function(cb){
return browserify('./src/app.js')
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./www/'));
cb();
});
// copy fonts
gulp.task('fonts', function(cb){
return gulp.src('node_modules/ionic-framework/release/fonts/**')
.pipe(gulp.dest('./www/fonts/'));
cb();
});
// copy assets
gulp.task('assets', function(cb){
return gulp.src('./assets/**')
.pipe(gulp.dest('./www/'));
cb();
});
// copy templates
gulp.task('templates', function(cb){
return gulp.src('./src/**/*.html')
.pipe(gulp.dest('./www/'));
cb();
}); |
Normalize in the other direction. | <?php
namespace mcordingley\Regression\Algorithm\GradientDescent\Gradient;
final class Linear implements Gradient
{
/** @var int */
private $power;
/**
* @param int $power
*/
public function __construct($power = 2)
{
$this->power = $power;
}
/**
* @param array $coefficients
* @param array $features
* @param float $outcome
* @return float
*/
public function cost(array $coefficients, array $features, $outcome)
{
return pow(abs($this->predicted($coefficients, $features) - $outcome), $this->power);
}
/**
* @param array $coefficients
* @param array $features
* @return float
*/
private function predicted(array $coefficients, array $features)
{
return array_sum(array_map(function ($coefficient, $feature) {
return $coefficient * $feature;
}, $coefficients, $features));
}
/**
* @param array $coefficients
* @param array $features
* @param float $outcome
* @return array
*/
public function gradient(array $coefficients, array $features, $outcome)
{
$gradient = [];
$predicted = $this->predicted($coefficients, $features);
for ($i = 0; $i < count($features); $i++) {
$gradient[] = $this->power * pow(abs($predicted - $outcome), $this->power - 1) * $features[$i];
}
return $gradient;
}
}
| <?php
namespace mcordingley\Regression\Algorithm\GradientDescent\Gradient;
final class Linear implements Gradient
{
/** @var int */
private $power;
/**
* @param int $power
*/
public function __construct($power = 2)
{
$this->power = $power;
}
/**
* @param array $coefficients
* @param array $features
* @param float $outcome
* @return float
*/
public function cost(array $coefficients, array $features, $outcome)
{
return abs(pow($this->predicted($coefficients, $features) - $outcome, $this->power));
}
/**
* @param array $coefficients
* @param array $features
* @return float
*/
private function predicted(array $coefficients, array $features)
{
return array_sum(array_map(function ($coefficient, $feature) {
return $coefficient * $feature;
}, $coefficients, $features));
}
/**
* @param array $coefficients
* @param array $features
* @param float $outcome
* @return array
*/
public function gradient(array $coefficients, array $features, $outcome)
{
$gradient = [];
$predicted = $this->predicted($coefficients, $features);
for ($i = 0; $i < count($features); $i++) {
$gradient[] = $this->power * abs(pow($predicted - $outcome, $this->power - 1)) * $features[$i];
}
return $gradient;
}
}
|
Update Tabs to use S selectors | /*jslint unparam: true, browser: true, indent: 2 */
;(function ($, window, document, undefined) {
'use strict';
Foundation.libs.tab = {
name : 'tab',
version : '5.1.0',
settings : {
active_class: 'active',
callback : function () {}
},
init : function (scope, method, options) {
this.bindings(method, options);
},
events : function () {
var S = this.S;
S(this.scope).off('.tab').on('click.fndtn.tab', '[data-tab] > dd > a', function (e) {
e.preventDefault();
var tab = S(this).parent(),
tabs = tab.closest('[data-tab]'),
target = S('#' + this.href.split('#')[1]),
siblings = tab.siblings(),
settings = tabs.data('tab-init');
// allow usage of data-tab-content attribute instead of href
if (S(this).data('tab-content')) {
target = S('#' + S(this).data('tab-content').split('#')[1]);
}
tab.addClass(settings.active_class).trigger('opened');
siblings.removeClass(settings.active_class);
target.siblings().removeClass(settings.active_class).end().addClass(settings.active_class);
settings.callback(tab);
tabs.trigger('toggled', [tab]);
});
},
off : function () {},
reflow : function () {}
};
}(jQuery, this, this.document));
| /*jslint unparam: true, browser: true, indent: 2 */
;(function ($, window, document, undefined) {
'use strict';
Foundation.libs.tab = {
name : 'tab',
version : '5.0.3',
settings : {
active_class: 'active',
callback : function () {}
},
init : function (scope, method, options) {
this.bindings(method, options);
},
events : function () {
$(this.scope).off('.tab').on('click.fndtn.tab', '[data-tab] > dd > a', function (e) {
e.preventDefault();
var tab = $(this).parent(),
tabs = tab.closest('[data-tab]'),
target = $('#' + this.href.split('#')[1]),
siblings = tab.siblings(),
settings = tabs.data('tab-init');
// allow usage of data-tab-content attribute instead of href
if ($(this).data('tab-content')) {
target = $('#' + $(this).data('tab-content').split('#')[1]);
}
tab.addClass(settings.active_class).trigger('opened');
siblings.removeClass(settings.active_class);
target.siblings().removeClass(settings.active_class).end().addClass(settings.active_class);
settings.callback(tab);
tabs.trigger('toggled', [tab]);
});
},
off : function () {},
reflow : function () {}
};
}(jQuery, this, this.document));
|
Update how filter query is applied | import Ember from 'ember';
import config from '../config/environment';
export default Ember.Service.extend({
host: config.HOST,
namespace: 'solr',
core: 'dina',
parseResponse (data) {
return data.response.docs.mapBy('primary_id');
},
select (query, {entityType, fq, rows}) {
const service = this;
let url = `${this.host}/${this.namespace}/${this.core}/select?q=${query}&fl=primary_id&wt=json&indent=true`;
if (entityType) {
fq['entity_type'] = entityType;
}
let fqString = '';
for(let key in fq) {
fqString += `&fq=${key}%3A${fq[key]}`;
}
url += fqString;
if (rows) {
url += `&rows=${rows}`;
}
return new Ember.RSVP.Promise(function (resolve, reject) {
Ember.$.getJSON(url).success((data)=>{
resolve(service.parseResponse(data));
}).fail((error)=>{
reject(error);
});
});
},
updateIndex () {
const url = `${this.host}/${this.namespace}/${this.core}/dataimport?command=delta-import&commit=1&wt=json`;
Ember.$.getJSON(url);
}
});
| import Ember from 'ember';
import config from '../config/environment';
export default Ember.Service.extend({
host: config.HOST,
namespace: 'solr',
core: 'dina',
parseResponse (data) {
return data.response.docs.mapBy('primary_id');
},
select (query, {entityType, fq, rows}) {
const service = this;
let url = `${this.host}/${this.namespace}/${this.core}/select?q=${query}&fl=primary_id&wt=json&indent=true`;
if (entityType) {
fq['entity_type'] = entityType;
}
let fqString = '';
for(let key in fq) {
fqString += `&fq=${key}%3D${fq[key]}`;
}
url += fqString;
if (rows) {
url += `&rows=${rows}`;
}
return new Ember.RSVP.Promise(function (resolve, reject) {
Ember.$.getJSON(url).success((data)=>{
resolve(service.parseResponse(data));
}).fail((error)=>{
reject(error);
});
});
},
updateIndex () {
const url = `${this.host}/${this.namespace}/${this.core}/dataimport?command=delta-import&commit=1&wt=json`;
Ember.$.getJSON(url);
}
});
|
Remove test covering module creation from alpha version | 'use strict';
var _ = require('lodash');
function testProperties(BBY) {
expect(BBY.options).not.toBe(undefined);
expect(BBY.options.key).toBe(process.env.BBY_API_KEY);
expect(BBY.availability instanceof Function).toBe(true);
expect(BBY.openBox instanceof Function).toBe(true);
expect(BBY.categories instanceof Function).toBe(true);
expect(BBY.products instanceof Function).toBe(true);
expect(BBY.recommendations instanceof Function).toBe(true);
expect(BBY.reviews instanceof Function).toBe(true);
expect(BBY.stores instanceof Function).toBe(true);
}
describe('The BBY API module is correctly initialized', function() {
describe('When using type one initilization', function() {
var BBY = require('../bestbuy')(process.env.BBY_API_KEY);
it('Has all properties', function(done) {
testProperties(BBY);
done();
});
});
describe('When using type two initilization', function() {
var BBY = require('../bestbuy')({
'key': process.env.BBY_API_KEY
});
it('Has all properties', function(done) {
testProperties(BBY);
done();
});
});
describe('When using type three initilization', function() {
var BBY = require('../bestbuy')();
it('Has all properties', function(done) {
testProperties(BBY);
done();
});
});
}); | 'use strict';
var _ = require('lodash');
function testProperties(BBY) {
expect(BBY.options).not.toBe(undefined);
expect(BBY.options.key).toBe(process.env.BBY_API_KEY);
expect(BBY.availability instanceof Function).toBe(true);
expect(BBY.openBox instanceof Function).toBe(true);
expect(BBY.categories instanceof Function).toBe(true);
expect(BBY.products instanceof Function).toBe(true);
expect(BBY.recommendations instanceof Function).toBe(true);
expect(BBY.reviews instanceof Function).toBe(true);
expect(BBY.stores instanceof Function).toBe(true);
}
describe('The BBY API module is correctly initialized', function() {
describe('When using type one initilization', function() {
var BBY = require('../bestbuy')(process.env.BBY_API_KEY);
it('Has all properties', function(done) {
testProperties(BBY);
done();
});
});
describe('When using type two initilization', function() {
var BBY = require('../bestbuy')({
'key': process.env.BBY_API_KEY
});
it('Has all properties', function(done) {
testProperties(BBY);
done();
});
});
describe('When using type three initilization', function() {
var BBY = require('../bestbuy');
it('Has all properties', function(done) {
testProperties(BBY);
done();
});
});
describe('When using type three initilization', function() {
var BBY = require('../bestbuy')();
it('Has all properties', function(done) {
testProperties(BBY);
done();
});
});
}); |
Validate user is in conversation on create message | from rest_framework import serializers
from foodsaving.conversations.models import Conversation, ConversationMessage
class ConversationSerializer(serializers.ModelSerializer):
class Meta:
model = Conversation
fields = [
'id',
'participants',
'created_at'
]
def retrieve(self, validated_data):
user = self.context['request'].user
return ConversationMessage.objects.create(author=user, **validated_data)
class ConversationMessageSerializer(serializers.ModelSerializer):
class Meta:
model = ConversationMessage
fields = [
'id',
'author',
'content',
'conversation',
'created_at'
]
class CreateConversationMessageSerializer(serializers.ModelSerializer):
class Meta:
model = ConversationMessage
fields = [
'id',
'author',
'content',
'conversation'
]
extra_kwargs = {
'author': {
'read_only': True
}
}
def validate_conversation(self, conversation):
if self.context['request'].user not in conversation.participants.all():
raise serializers.ValidationError("You are not in this conversation")
return conversation
def create(self, validated_data):
user = self.context['request'].user
return ConversationMessage.objects.create(author=user, **validated_data)
| from rest_framework import serializers
from foodsaving.conversations.models import Conversation, ConversationMessage
class ConversationSerializer(serializers.ModelSerializer):
class Meta:
model = Conversation
fields = [
'id',
'participants',
'created_at'
]
def retrieve(self, validated_data):
user = self.context['request'].user
return ConversationMessage.objects.create(author=user, **validated_data)
class ConversationMessageSerializer(serializers.ModelSerializer):
class Meta:
model = ConversationMessage
fields = [
'id',
'author',
'content',
'conversation',
'created_at'
]
class CreateConversationMessageSerializer(serializers.ModelSerializer):
class Meta:
model = ConversationMessage
fields = [
'id',
'author',
'content',
'conversation'
]
extra_kwargs = {
'author': {
'read_only': True
}
}
def create(self, validated_data):
user = self.context['request'].user
return ConversationMessage.objects.create(author=user, **validated_data)
|
Use a broad-brush filter for the signal handlers | # -*- coding: utf-8 -*-
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from django.core.exceptions import ImproperlyConfigured
from cms.exceptions import PluginAlreadyRegistered, PluginNotRegistered
from .segment_pool import segment_pool
from ..models import SegmentBasePluginModel
@receiver(post_save)
def register_segment(sender, instance, created, **kwargs):
'''
Ensure that saving changes in the model results in the de-registering (if
necessary) and registering of this segment plugin.
'''
if isinstance(instance, SegmentBasePluginModel):
if not created:
try:
segment_pool.unregister_segment_plugin(instance)
except (PluginAlreadyRegistered, ImproperlyConfigured):
pass
# Either way, we register it.
try:
segment_pool.register_segment_plugin(instance)
except (PluginAlreadyRegistered, ImproperlyConfigured):
pass
@receiver(pre_delete)
def unregister_segment(sender, instance, **kwargs):
'''
Listens for signals that a SegmentPlugin instance is to be deleted, and
un-registers it from the segment_pool.
'''
if isinstance(instance, SegmentBasePluginModel):
try:
segment_pool.unregister_segment_plugin(instance)
except (PluginNotRegistered, ImproperlyConfigured):
pass
| # -*- coding: utf-8 -*-
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from django.core.exceptions import ImproperlyConfigured
from cms.exceptions import PluginAlreadyRegistered, PluginNotRegistered
from .segment_pool import segment_pool
@receiver(post_save)
def register_segment(sender, instance, created, **kwargs):
'''
Ensure that saving changes in the model results in the de-registering (if
necessary) and registering of this segment plugin.
'''
#
# NOTE: Removed the test if instance is the right type from here, as it is
# already the first thing that happens in the (un)register_plugin()
# methods. Its not these signal handlers' job to decide who gets to be
# registered and who doesn't.
#
if not created:
try:
segment_pool.unregister_segment_plugin(instance)
except (PluginAlreadyRegistered, ImproperlyConfigured):
pass
# Either way, we register it.
try:
segment_pool.register_segment_plugin(instance)
except (PluginAlreadyRegistered, ImproperlyConfigured):
pass
@receiver(pre_delete)
def unregister_segment(sender, instance, **kwargs):
'''
Listens for signals that a SegmentPlugin instance is to be deleted, and
un-registers it from the segment_pool.
'''
# NOTE: See note in register_segment()
try:
segment_pool.unregister_segment_plugin(instance)
except (PluginNotRegistered, ImproperlyConfigured):
pass
|
Fix Python version detection for Python 2.6 | import sys
from setuptools import setup, find_packages
py26_dependency = []
if sys.version_info <= (2, 6):
py26_dependency = ["argparse >= 1.2.1"]
setup(
name='dataset',
version='0.3.14',
description="Toolkit for Python-based data processing.",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3'
],
keywords='sql sqlalchemy etl loading utility',
author='Friedrich Lindenberg, Gregor Aisch',
author_email='[email protected]',
url='http://github.com/pudo/dataset',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=[],
include_package_data=False,
zip_safe=False,
install_requires=[
'sqlalchemy >= 0.8.1',
'alembic >= 0.6.1',
'python-slugify >= 0.0.6',
"PyYAML >= 3.10"
] + py26_dependency,
tests_require=[],
entry_points={
'console_scripts': [
'datafreeze = dataset.freeze.app:main',
]
}
)
| import sys
from setuptools import setup, find_packages
py26_dependency = []
if sys.version_info.major == 2 and sys.version_info.minor < 7:
py26_dependency = ["argparse >= 1.2.1"]
setup(
name='dataset',
version='0.3.14',
description="Toolkit for Python-based data processing.",
long_description="",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3'
],
keywords='sql sqlalchemy etl loading utility',
author='Friedrich Lindenberg, Gregor Aisch',
author_email='[email protected]',
url='http://github.com/pudo/dataset',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=[],
include_package_data=False,
zip_safe=False,
install_requires=[
'sqlalchemy >= 0.8.1',
'alembic >= 0.6.1',
'python-slugify >= 0.0.6',
"PyYAML >= 3.10"
] + py26_dependency,
tests_require=[],
entry_points={
'console_scripts': [
'datafreeze = dataset.freeze.app:main',
]
}
)
|
Move BAE secret into try catch block | ##################################
# Added for BAE
##################################
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
import bae_secrets
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
| ##################################
# Added for BAE
##################################
try:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': const.CACHE_ADDR,
'TIMEOUT': 60,
}
}
except:
pass
try:
from bae.core import const
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': bae_secrets.database_name,
'USER': const.MYSQL_USER,
'PASSWORD': const.MYSQL_PASS,
'HOST': const.MYSQL_HOST,
'PORT': const.MYSQL_PORT,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
###Or
#SESSION_ENGINE = 'django.contrib.sessions.backends.db'
##################################
except:
pass
EMAIL_BACKEND = 'django.core.mail.backends.bcms.EmailBackend'
try:
from objsys.baidu_mail import EmailBackend
EMAIL_BACKEND = 'objsys.baidu_mail.EmailBackend'
except:
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
|
Update Android registration code snippet | package com.push.pushapplication;
import android.util.Log;
import android.app.Application;
import org.jboss.aerogear.android.core.Callback;
import org.jboss.aerogear.android.unifiedpush.PushRegistrar;
import org.jboss.aerogear.android.unifiedpush.RegistrarManager;
import org.jboss.aerogear.android.unifiedpush.gcm.AeroGearGCMPushConfiguration;
public class PushApplication extends Application {
private final String VARIANT_ID = "{{ variant.variantID }}";
private final String SECRET = "{{ variant.secret }}";
private final String GCM_SENDER_ID = "{{ variant.projectNumber }}";
private final String UNIFIED_PUSH_URL = "{{ contextPath }}";
@Override
public void onCreate() {
super.onCreate();
RegistrarManager.config("register", AeroGearGCMPushConfiguration.class)
.setPushServerURI(URI.create(UNIFIED_PUSH_URL))
.setSenderIds(GCM_SENDER_ID)
.setVariantID(VARIANT_ID)
.setSecret(SECRET)
.asRegistrar();
PushRegistrar registrar = RegistrarManager.getRegistrar("register");
registrar.register(getApplicationContext(), new Callback<Void>() {
@Override
public void onSuccess(Void data) {
Log.i(TAG, "Registration Succeeded!");
}
@Override
public void onFailure(Exception e) {
Log.e(TAG, exception.getMessage(), exception);
}
});
}
}
| package com.push.pushapplication;
import java.net.URI;
import java.net.URISyntaxException;
import org.jboss.aerogear.android.unifiedpush.PushConfig;
import org.jboss.aerogear.android.unifiedpush.PushRegistrar;
import org.jboss.aerogear.android.unifiedpush.Registrations;
import android.app.Application;
public class PushApplication extends Application {
private final String VARIANT_ID = "{{ variant.variantID }}";
private final String SECRET = "{{ variant.secret }}";
private final String GCM_SENDER_ID = "{{ variant.projectNumber }}";
private final String UNIFIED_PUSH_URL = "{{ contextPath }}";
private PushRegistrar registration;
@Override
public void onCreate() {
super.onCreate();
Registrations registrations = new Registrations();
try {
PushConfig config = new PushConfig(new URI(UNIFIED_PUSH_URL), GCM_SENDER_ID);
config.setVariantID(VARIANT_ID);
config.setSecret(SECRET);
config.setAlias(MY_ALIAS);
registration = registrations.push("unifiedpush", config);
registration.register(getApplicationContext(), new Callback() {
private static final long serialVersionUID = 1L;
@Override
public void onSuccess(Void ignore) {
Toast.makeText(MainActivity.this, "Registration Succeeded!",
Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Exception exception) {
Log.e("MainActivity", exception.getMessage(), exception);
}
});
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
|
Remove updating the schema when it already exists
In some cases (I can't really pinpoint it) it removed all the tables except for those we tried to install | <?php
namespace Common\Doctrine\Entity;
use Doctrine\DBAL\Exception\TableExistsException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\ORM\Tools\ToolsException;
class CreateSchema
{
/** @var EntityManager */
private $entityManager;
/**
* @param EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* Adds a new doctrine entity in the database
*
* @param string $entityClass
*/
public function forEntityClass($entityClass)
{
$this->forEntityClasses([$entityClass]);
}
/**
* Adds new doctrine entities in the database
*
* @param array $entityClasses
*
* @throws ToolsException
*/
public function forEntityClasses(array $entityClasses)
{
// create the database table for the given class using the doctrine SchemaTool
$schemaTool = new SchemaTool($this->entityManager);
try {
$schemaTool->createSchema(
array_map(
[$this->entityManager, 'getClassMetadata'],
$entityClasses
)
);
} catch (TableExistsException $tableExists) {
// do nothing
} catch (ToolsException $toolsException) {
if (!$toolsException->getPrevious() instanceof TableExistsException) {
throw $toolsException;
}
// do nothing
}
}
}
| <?php
namespace Common\Doctrine\Entity;
use Doctrine\DBAL\Exception\TableExistsException;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\ORM\Tools\ToolsException;
class CreateSchema
{
/** @var EntityManager */
private $entityManager;
/**
* @param EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* Adds a new doctrine entity in the database
*
* @param string $entityClass
*/
public function forEntityClass($entityClass)
{
$this->forEntityClasses([$entityClass]);
}
/**
* Adds new doctrine entities in the database
*
* @param array $entityClasses
*
* @throws ToolsException
*/
public function forEntityClasses(array $entityClasses)
{
// create the database table for the given class using the doctrine SchemaTool
$schemaTool = new SchemaTool($this->entityManager);
try {
$schemaTool->createSchema(
array_map(
[$this->entityManager, 'getClassMetadata'],
$entityClasses
)
);
} catch (TableExistsException $tableExists) {
$schemaTool->updateSchema(
array_map(
[$this->entityManager, 'getClassMetadata'],
$entityClasses
)
);
} catch (ToolsException $toolsException) {
if (!$toolsException->getPrevious() instanceof TableExistsException) {
throw $toolsException;
}
$schemaTool->updateSchema(
array_map(
[$this->entityManager, 'getClassMetadata'],
$entityClasses
)
);
}
}
}
|
Use Python file objects directly as input
- fix wrong separator between path and filename
Signed-off-by: Stefan Marr <[email protected]> | import os
from StringIO import StringIO
def compile_class_from_file(path, filename, system_class, universe):
return _SourcecodeCompiler().compile(path, filename, system_class, universe)
def compile_class_from_string(stmt, system_class, universe):
return _SourcecodeCompiler().compile_class_string(stmt, system_class, universe)
class _SourcecodeCompiler(object):
def __init__(self):
self._parser = None
def compile(self, path, filename, system_class, universe):
fname = path + os.sep + filename + ".som"
with open(fname, "r") as input_file:
self._parser = Parser(input_file, universe)
result = self._compile(system_class, universe)
cname = result.get_name()
cnameC = cname.get_string()
if filename != cnameC:
raise ValueError("File name " + filename + " does not match class name " + cnameC)
return result
def compile_class_string(self, stream, system_class, universe):
self._parser = Parser(StringIO(stream), universe)
result = self._compile(system_class, universe)
return result
def _compile(self, system_class, universe):
cgc = ClassGenerationContext(universe)
result = system_class
self._parser.classdef(cgc)
if not system_class:
result = cgc.assemble()
else:
cgc.assemble_system_class(result)
return result
| import os
def compile_class_from_file(path, filename, system_class, universe):
return _SourcecodeCompiler().compile(path, filename, system_class, universe)
def compile_class_from_string(stmt, system_class, universe):
return _SourcecodeCompiler().compile_class_string(stmt, system_class, universe)
class _SourcecodeCompiler(object):
def __init__(self):
self._parser = None
def compile(self, path, filename, system_class, universe):
result = system_class
fname = path + os.pathsep + filename + ".som"
self._parser = Parser(FileReader(fname), universe)
result = self._compile(system_class, universe)
cname = result.get_name()
cnameC = cname.get_string()
if filename != cnameC:
raise ValueError("File name " + filename + " does not match class name " + cnameC)
return result
def compile_class_string(self, stream, system_class, universe):
self._parser = Parser(StringReader(stream), universe)
result = self._compile(system_class, universe)
return result
def _compile(self, system_class, universe):
cgc = ClassGenerationContext(universe)
result = system_class
self._parser.classdef(cgc)
if not system_class:
result = cgc.assemble()
else:
cgc.assemble_system_class(result)
return result
|
[cleanup] Fix bad default case statement | import GeometryResourceDescriptor from './GeometryResourceDescriptor';
import PropTypes from 'react/lib/ReactPropTypes';
import THREE from 'three.js';
class ShapeGeometryResourceDescriptor extends GeometryResourceDescriptor {
constructor(react3RendererInstance) {
super(react3RendererInstance);
this.hasProp('type', {
type: PropTypes.oneOf([
'points',
'spacedPoints',
'shape',
]).isRequired,
update: this.triggerRemount,
'default': '',
});
this.hasProp('divisions', {
type: PropTypes.number,
update: this.triggerRemount,
'default': 5,
});
}
applyInitialProps(threeObject, props) {
super.applyInitialProps(threeObject, props);
threeObject.userData._divisions = props.divisions;
threeObject.userData._type = props.type;
}
applyToSlot(threeObject, parentObject, shape:THREE.Shape) {
if (!shape) {
return super.applyToSlot(threeObject, parentObject, null);
}
let geometry;
switch (threeObject.userData._type) {
case 'points':
geometry = shape.createPointsGeometry();
break;
case 'spacedPoints':
geometry = shape.createSpacedPointsGeometry(threeObject.userData._divisions);
break;
case 'shape':
// TODO shapeGeometryDescriptor
geometry = new THREE.ShapeGeometry(shape);
break;
default:
debugger;
break;
}
return super.applyToSlot(threeObject, parentObject, geometry);
}
}
module.exports = ShapeGeometryResourceDescriptor;
| import GeometryResourceDescriptor from './GeometryResourceDescriptor';
import PropTypes from 'react/lib/ReactPropTypes';
import THREE from 'three.js';
class ShapeGeometryResourceDescriptor extends GeometryResourceDescriptor {
constructor(react3RendererInstance) {
super(react3RendererInstance);
this.hasProp('type', {
type: PropTypes.oneOf([
'points',
'spacedPoints',
'shape',
]).isRequired,
update: this.triggerRemount,
'default': '',
});
this.hasProp('divisions', {
type: PropTypes.number,
update: this.triggerRemount,
'default': 5,
});
}
applyInitialProps(threeObject, props) {
super.applyInitialProps(threeObject, props);
threeObject.userData._divisions = props.divisions;
threeObject.userData._type = props.type;
}
applyToSlot(threeObject, parentObject, shape:THREE.Shape) {
if (!shape) {
return super.applyToSlot(threeObject, parentObject, null);
}
let geometry;
switch (threeObject.userData._type) {
case 'points':
geometry = shape.createPointsGeometry();
break;
case 'spacedPoints':
geometry = shape.createSpacedPointsGeometry(threeObject.userData._divisions);
break;
case 'shape':
// TODO shapeGeometryDescriptor
geometry = new THREE.ShapeGeometry(shape);
break;
'default':
debugger;
break;
}
return super.applyToSlot(threeObject, parentObject, geometry);
}
}
module.exports = ShapeGeometryResourceDescriptor;
|
Fix one last linting error | <?php
/**
* abstract compiler pass for extref things
*/
namespace Graviton\DocumentBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @link http://swisscom.ch
*/
abstract class AbstractExtRefCompilerPass implements CompilerPassInterface
{
/**
* load services
*
* @param ContainerBuilder $container container builder
*
* @return void
*/
final public function process(ContainerBuilder $container)
{
$gravitonServices = array_filter(
$container->getServiceIds(),
function ($id) {
return substr($id, 0, 8) == 'graviton' &&
strpos($id, 'controller') !== false &&
$id !== 'graviton.rest.controller';
}
);
$this->processServices($container, $gravitonServices);
}
/**
* null implementation of method
*
* @param ContainerBuilder $container container
* @param array $services services
*
* @return void
*/
public function processServices(ContainerBuilder $container, $services)
{
}
}
| <?php
/**
* abstract compiler pass for extref things
*/
namespace Graviton\DocumentBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @link http://swisscom.ch
*/
abstract class AbstractExtRefCompilerPass implements CompilerPassInterface
{
/**
* load services
*
* @param ContainerBuilder $container container builder
*
* @return void
*/
public final function process(ContainerBuilder $container)
{
$gravitonServices = array_filter(
$container->getServiceIds(),
function ($id) {
return substr($id, 0, 8) == 'graviton' &&
strpos($id, 'controller') !== false &&
$id !== 'graviton.rest.controller';
}
);
$this->processServices($container, $gravitonServices);
}
/**
* null implementation of method
*
* @param ContainerBuilder $container container
* @param array $services services
*
* @return void
*/
public function processServices(ContainerBuilder $container, $services)
{
}
}
|
Add warning icons to some alerts | @if (App::environment() !== 'production')
<div class="alert alert-warning">
<p><i class="icon fa fa-warning"></i> This installation of OpenDominion is running on <b>{{ App::environment() }}</b> environment and is not meant for production purposes. Any data you register and actions you take on this instance might be wiped without notice.</p>
</div>
@endif
@if (isset($selectedDominion) && $selectedDominion->isLocked())
<div class="alert alert-warning">
<p><i class="icon fa fa-warning"></i> This dominion is <strong>locked</strong> due to the round having ended. No actions can be performed and no ticks will be processed.</p>
</div>
@endif
@if (!$errors->isEmpty())
<div class="alert alert-danger alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<h4>One or more errors occurred:</h4>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@foreach (['danger', 'warning', 'success', 'info'] as $alert_type)
@if (Session::has('alert-' . $alert_type))
<div class="alert alert-{{ $alert_type }} alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p>{{ Session::get('alert-' . $alert_type) }}</p>
</div>
@endif
@endforeach
| @if (App::environment() !== 'production')
<div class="alert alert-warning">
<p>This installation of OpenDominion is running on <b>{{ App::environment() }}</b> environment and is not meant for production purposes. Any data you register and actions you take on this instance might be wiped without notice.</p>
</div>
@endif
@if (isset($selectedDominion) && $selectedDominion->isLocked())
<div class="alert alert-warning">
<p>This dominion is <strong>locked</strong> due to the round having ended. No actions can be performed and no ticks will be processed.</p>
</div>
@endif
@if (!$errors->isEmpty())
<div class="alert alert-danger alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<h4>One or more errors occurred:</h4>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@foreach (['danger', 'warning', 'success', 'info'] as $alert_type)
@if (Session::has('alert-' . $alert_type))
<div class="alert alert-{{ $alert_type }} alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<p>{{ Session::get('alert-' . $alert_type) }}</p>
</div>
@endif
@endforeach
|
Fix issue with listing users due to removed 'subuserOf' method | <?php
namespace Pterodactyl\Repositories\Eloquent;
use Pterodactyl\Models\User;
use Illuminate\Support\Collection;
use Pterodactyl\Repositories\Concerns\Searchable;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
class UserRepository extends EloquentRepository implements UserRepositoryInterface
{
use Searchable;
/**
* Return the model backing this repository.
*
* @return string
*/
public function model()
{
return User::class;
}
/**
* Return all users with counts of servers and subusers of servers.
*
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
*/
public function getAllUsersWithCounts(): LengthAwarePaginator
{
return $this->getBuilder()->withCount('servers')
->search($this->getSearchTerm())
->paginate(50, $this->getColumns());
}
/**
* Return all matching models for a user in a format that can be used for dropdowns.
*
* @param string|null $query
* @return \Illuminate\Support\Collection
*/
public function filterUsersByQuery(?string $query): Collection
{
$this->setColumns([
'id', 'email', 'username', 'name_first', 'name_last',
]);
$instance = $this->getBuilder()->search($query)->get($this->getColumns());
return $instance->transform(function ($item) {
$item->md5 = md5(strtolower($item->email));
return $item;
});
}
}
| <?php
namespace Pterodactyl\Repositories\Eloquent;
use Pterodactyl\Models\User;
use Illuminate\Support\Collection;
use Pterodactyl\Repositories\Concerns\Searchable;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
class UserRepository extends EloquentRepository implements UserRepositoryInterface
{
use Searchable;
/**
* Return the model backing this repository.
*
* @return string
*/
public function model()
{
return User::class;
}
/**
* Return all users with counts of servers and subusers of servers.
*
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
*/
public function getAllUsersWithCounts(): LengthAwarePaginator
{
return $this->getBuilder()->withCount('servers', 'subuserOf')
->search($this->getSearchTerm())
->paginate(50, $this->getColumns());
}
/**
* Return all matching models for a user in a format that can be used for dropdowns.
*
* @param string|null $query
* @return \Illuminate\Support\Collection
*/
public function filterUsersByQuery(?string $query): Collection
{
$this->setColumns([
'id', 'email', 'username', 'name_first', 'name_last',
]);
$instance = $this->getBuilder()->search($query)->get($this->getColumns());
return $instance->transform(function ($item) {
$item->md5 = md5(strtolower($item->email));
return $item;
});
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.