text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Remove method that was vestigial from pre-1.0.0 release | var
fs = require('fs'),
_ = require('underscore'),
createTemplates = require('./poet/templates'),
createHelpers = require('./poet/helpers'),
routes = require('./poet/routes'),
methods = require('./poet/methods'),
utils = require('./poet/utils'),
method = utils.method;
function Poet (app, options) {
this.app = app;
// Set up a hash of posts and a cache for storing sorted array
// versions of posts, tags, and categories for the helper
this.posts = {};
this.cache = {};
// Merge options with defaults
this.options = utils.createOptions(options);
// Set up default templates (markdown, jade)
this.templates = createTemplates();
// Construct helper methods
this.helpers = createHelpers(this);
// Bind locals for view access
utils.createLocals(this.app, this.helpers);
// Bind routes to express app based off of options
routes.bindRoutes(this);
}
module.exports = function (app, options) {
return new Poet(app, options);
};
Poet.prototype.addTemplate = method(methods.addTemplate);
Poet.prototype.init = method(methods.init);
Poet.prototype.clearCache = method(methods.clearCache);
Poet.prototype.addRoute = method(routes.addRoute);
Poet.prototype.watch = method(methods.watch);
| var
fs = require('fs'),
_ = require('underscore'),
createTemplates = require('./poet/templates'),
createHelpers = require('./poet/helpers'),
routes = require('./poet/routes'),
methods = require('./poet/methods'),
utils = require('./poet/utils'),
method = utils.method;
function Poet (app, options) {
this.app = app;
// Set up a hash of posts and a cache for storing sorted array
// versions of posts, tags, and categories for the helper
this.posts = {};
this.cache = {};
// Merge options with defaults
this.options = utils.createOptions(options);
// Set up default templates (markdown, jade)
this.templates = createTemplates();
// Construct helper methods
this.helpers = createHelpers(this);
// Bind locals for view access
utils.createLocals(this.app, this.helpers);
// Bind routes to express app based off of options
routes.bindRoutes(this);
}
module.exports = function (app, options) {
return new Poet(app, options);
};
Poet.prototype.addTemplate = method(methods.addTemplate);
Poet.prototype.init = method(methods.init);
Poet.prototype.middleware = method(methods.middleware);
Poet.prototype.clearCache = method(methods.clearCache);
Poet.prototype.addRoute = method(routes.addRoute);
Poet.prototype.watch = method(methods.watch);
|
Add "idir" as default value. | from rest_framework.response import Response
from rest_framework.views import APIView
from gwells.settings.base import get_env_variable
class KeycloakConfig(APIView):
""" serves keycloak config """
def get(self, request):
config = {
"realm": get_env_variable("SSO_REALM"),
"auth-server-url": get_env_variable("SSO_AUTH_HOST"),
"ssl-required": "external",
"resource": get_env_variable("SSO_CLIENT"),
"public-client": True,
"confidential-port": int(get_env_variable("SSO_PORT", "0"))
}
return Response(config)
class GeneralConfig(APIView):
""" serves general configuration """
def get(self, request):
config = {
"enable_data_entry": get_env_variable("ENABLE_DATA_ENTRY") == "True",
"enable_google_analytics": get_env_variable("ENABLE_GOOGLE_ANALYTICS") == "True",
"sso_idp_hint": get_env_variable("SSO_IDP_HINT") or "idir"
}
return Response(config)
| from rest_framework.response import Response
from rest_framework.views import APIView
from gwells.settings.base import get_env_variable
class KeycloakConfig(APIView):
""" serves keycloak config """
def get(self, request):
config = {
"realm": get_env_variable("SSO_REALM"),
"auth-server-url": get_env_variable("SSO_AUTH_HOST"),
"ssl-required": "external",
"resource": get_env_variable("SSO_CLIENT"),
"public-client": True,
"confidential-port": int(get_env_variable("SSO_PORT", "0"))
}
return Response(config)
class GeneralConfig(APIView):
""" serves general configuration """
def get(self, request):
config = {
"enable_data_entry": get_env_variable("ENABLE_DATA_ENTRY") == "True",
"enable_google_analytics": get_env_variable("ENABLE_GOOGLE_ANALYTICS") == "True",
"sso_idp_hint": get_env_variable("SSO_IDP_HINT")
}
return Response(config)
|
Fix for JodaTime not being initialized correctly in dev builds | package mn.devfest;
import android.app.Application;
import android.content.Context;
import net.danlew.android.joda.JodaTimeAndroid;
import timber.log.Timber;
/**
* DevFest application class
*
* Performs application-wide configuration
*
* @author bherbst
*/
public class DevFestApplication extends Application {
private DevFestGraph mGraph;
@Override
public void onCreate() {
super.onCreate();
JodaTimeAndroid.init(this);
init();
buildComponent();
}
/**
* Build the Dagger component
*/
private void buildComponent() {
mGraph = DevFestComponent.Initializer.init(this);
}
/**
* Get the Dagger component
*/
public DevFestGraph component() {
return mGraph;
}
/**
* Initialize app-wide configuration
*
* The default implementation sets up the app for release. Do not call through to super()
* if you do not want the release configuration.
*/
protected void init() {
Timber.plant(new ReleaseTree());
}
/**
* Get a WvwApplication from a Context
* @param context The Context in which to get the WvwApplication
* @return The WvwApplication associated with the given Context
*/
public static DevFestApplication get(Context context) {
return (DevFestApplication) context.getApplicationContext();
}
}
| package mn.devfest;
import android.app.Application;
import android.content.Context;
import net.danlew.android.joda.JodaTimeAndroid;
import timber.log.Timber;
/**
* DevFest application class
*
* Performs application-wide configuration
*
* @author bherbst
*/
public class DevFestApplication extends Application {
private DevFestGraph mGraph;
@Override
public void onCreate() {
super.onCreate();
init();
buildComponent();
}
/**
* Build the Dagger component
*/
private void buildComponent() {
mGraph = DevFestComponent.Initializer.init(this);
}
/**
* Get the Dagger component
*/
public DevFestGraph component() {
return mGraph;
}
/**
* Initialize app-wide configuration
*
* The default implementation sets up the app for release. Do not call through to super()
* if you do not want the release configuration.
*/
protected void init() {
JodaTimeAndroid.init(this);
Timber.plant(new ReleaseTree());
}
/**
* Get a WvwApplication from a Context
* @param context The Context in which to get the WvwApplication
* @return The WvwApplication associated with the given Context
*/
public static DevFestApplication get(Context context) {
return (DevFestApplication) context.getApplicationContext();
}
}
|
Make safe_makedirs resilient to race conditions. | # -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
try:
os.makedirs(path)
except FileExistsError:
# Maybe someone else created the directory for us; if so, ignore error
if os.path.exists(path):
return
raise
| # -*- coding: utf-8 -*-
import os
import os.path
import shutil
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, folder) = os.path.split(path)
if folder != "":
splitted_path.insert(0, folder)
else:
if path != "":
splitted_path.insert(0, path)
break
return splitted_path
#-------------------------------------------------------------------------------
# This function is necessary because Python’s makedirs cannot create a
# directory such as "d:\data\foo/bar" because it’ll split it as "d:\data"
# and "foo/bar" then try to create a directory named "foo/bar".
def safe_makedirs(path):
if os.sep is '\\':
path = path.replace('/', '\\')
elif os.sep is '/':
path = path.replace('\\', '/')
if not os.path.exists(path):
os.makedirs(path)
|
Add problem 2 and 3 to main class. | package com.rmd.personal.projecteuler;
import java.util.ArrayList;
import java.util.List;
public final class Main {
private List<Problem> problemList;
private Main() {
this.problemList = new ArrayList<Problem>();
this.getProblemList().add(new Problem1());
this.getProblemList().add(new Problem2());
this.getProblemList().add(new Problem3());
}
private List<Problem> getProblemList() {
return this.problemList;
}
public static void main(String[] args) {
(new Main()).run();
}
private void run() {
for (Problem problem : this.getProblemList()) {
System.out.println("Problem: " + this.getProblemList().indexOf(problem));
System.out.println(problem.getDescription());
System.out.println(problem.run());
}
}
}
| package com.rmd.personal.projecteuler;
import java.util.ArrayList;
import java.util.List;
public final class Main {
private List<Problem> problemList;
private Main() {
this.problemList = new ArrayList<Problem>();
this.getProblemList().add(new Problem1());
}
private List<Problem> getProblemList() {
return this.problemList;
}
public static void main(String[] args) {
(new Main()).run();
}
private void run() {
for (Problem problem : this.getProblemList()) {
System.out.println("Problem: " + this.getProblemList().indexOf(problem));
System.out.println(problem.getDescription());
System.out.println(problem.run());
}
}
}
|
Update service provider to use bindShared.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Orchestra\Asset;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class AssetServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('orchestra.asset', function ($app) {
return new Environment($app);
});
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Orchestra\Asset', 'Orchestra\Support\Facades\Asset');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.asset');
}
}
| <?php namespace Orchestra\Asset;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class AssetServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var boolean
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['orchestra.asset'] = $this->app->share(function ($app) {
return new Environment($app);
});
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Orchestra\Asset', 'Orchestra\Support\Facades\Asset');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('orchestra.asset');
}
}
|
Rename test user to avoid clash | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from unittest.mock import patch
import pytest
from byceps.services.user_message import service as user_message_service
def test_recipient_formatting(make_user, site, params):
screen_name, email_address, expected = params
user = make_user(screen_name, email_address=email_address)
message = user_message_service.create_message(
user.id, user.id, '', '', site.id
)
assert message.recipients == [expected]
@pytest.fixture(params=[
('Alicia', 'alicia@users.test', 'Alicia <alicia@users.test>'),
('<AngleInvestor>', 'angleinvestor@users.test', '"<AngleInvestor>" <angleinvestor@users.test>'),
('-=]YOLO[=-', 'yolo@users.test', '"-=]YOLO[=-" <yolo@users.test>'),
])
def params(request):
yield request.param
| """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from unittest.mock import patch
import pytest
from byceps.services.user_message import service as user_message_service
def test_recipient_formatting(make_user, site, params):
screen_name, email_address, expected = params
user = make_user(screen_name, email_address=email_address)
message = user_message_service.create_message(
user.id, user.id, '', '', site.id
)
assert message.recipients == [expected]
@pytest.fixture(params=[
('Alice', 'alice@users.test', 'Alice <alice@users.test>'),
('<AngleInvestor>', 'angleinvestor@users.test', '"<AngleInvestor>" <angleinvestor@users.test>'),
('-=]YOLO[=-', 'yolo@users.test', '"-=]YOLO[=-" <yolo@users.test>'),
])
def params(request):
yield request.param
|
Use custom interpolation for client templates. | /**
* Precompiles Underscore templates to a `.jst` file.
*
* ---------------------------------------------------------------
*
* (i.e. basically it takes HTML files and turns them into tiny little
* javascript functions that you pass data to and return HTML. This can
* speed up template rendering on the client, and reduce bandwidth usage.)
*
* For usage docs see:
* https://github.com/gruntjs/grunt-contrib-jst
*
*/
module.exports = function(grunt) {
var templateFilesToInject = [
'templates/**/*.html'
];
grunt.config.set('jst', {
dev: {
// To use other sorts of templates, specify a regexp like the example below:
options: {
templateSettings: {
interpolate: /\{\{(.+?)\}\}/g
}
},
// Note that the interpolate setting above is simply an example of overwriting lodash's
// default interpolation. If you want to parse templates with the default _.template behavior
// (i.e. using <div></div>), there's no need to overwrite `templateSettings.interpolate`.
files: {
// e.g.
// 'relative/path/from/gruntfile/to/compiled/template/destination' : ['relative/path/to/sourcefiles/**/*.html']
'.tmp/public/jst.js': require('../pipeline').templateFilesToInject
}
}
});
grunt.loadNpmTasks('grunt-contrib-jst');
};
| /**
* Precompiles Underscore templates to a `.jst` file.
*
* ---------------------------------------------------------------
*
* (i.e. basically it takes HTML files and turns them into tiny little
* javascript functions that you pass data to and return HTML. This can
* speed up template rendering on the client, and reduce bandwidth usage.)
*
* For usage docs see:
* https://github.com/gruntjs/grunt-contrib-jst
*
*/
module.exports = function(grunt) {
var templateFilesToInject = [
'templates/**/*.html'
];
grunt.config.set('jst', {
dev: {
// To use other sorts of templates, specify a regexp like the example below:
// options: {
// templateSettings: {
// interpolate: /\{\{(.+?)\}\}/g
// }
// },
// Note that the interpolate setting above is simply an example of overwriting lodash's
// default interpolation. If you want to parse templates with the default _.template behavior
// (i.e. using <div></div>), there's no need to overwrite `templateSettings.interpolate`.
files: {
// e.g.
// 'relative/path/from/gruntfile/to/compiled/template/destination' : ['relative/path/to/sourcefiles/**/*.html']
'.tmp/public/jst.js': require('../pipeline').templateFilesToInject
}
}
});
grunt.loadNpmTasks('grunt-contrib-jst');
};
|
Add debug information to IRC handler | /* eslint no-console: 0 */
'use strict';
const irc = require('irc');
const server = process.env.IRC_SERVER;
const user = process.env.IRC_USER;
const channel = process.env.IRC_CHANNEL;
const client = module.exports.client = new irc.Client(server, user, {
debug: true,
autoConnect: false,
autoRejoin: true,
channels: [channel],
showErrors: true,
});
client.connect(5, function() {
console.log(arguments);
});
if (process.env.NODE_ENV !== 'testing') {
client.on('registered', function clientOnRegisterd(message) {
console.log(new Date(), '[IRC]', message.args[1]);
});
}
client.on('error', function clientOnError(error) {
console.error(error);
console.error('Shutting Down...');
process.exit(1);
});
module.exports.notify = function ircPost(nodes, callback) {
nodes.forEach(function nodesForEach(node) {
// let name = `[${node.name}](${jenkins}/computer/${node.name})`;
if (node.offline) {
client.say(channel, `Jenkins slave ${node.name} is offline`);
} else {
client.say(channel, `Jenkins slave ${node.name} is online`);
}
});
callback(null);
};
| /* eslint no-console: 0 */
'use strict';
const irc = require('irc');
const server = process.env.IRC_SERVER;
const user = process.env.IRC_USER;
const channel = process.env.IRC_CHANNEL;
const client = module.exports.client = new irc.Client(server, user, {
channels: [channel],
});
if (process.env.NODE_ENV !== 'testing') {
client.on('registered', function clientOnRegisterd(message) {
console.log(new Date(), '[IRC]', message.args[1]);
});
}
client.on('error', function clientOnError(error) {
console.error(error);
console.error('Shutting Down...');
process.exit(1);
});
module.exports.notify = function ircPost(nodes, callback) {
nodes.forEach(function nodesForEach(node) {
// let name = `[${node.name}](${jenkins}/computer/${node.name})`;
if (node.offline) {
client.say(channel, `Jenkins slave ${node.name} is offline`);
} else {
client.say(channel, `Jenkins slave ${node.name} is online`);
}
});
callback(null);
};
|
Test APL code should give credit to Wikipedia | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import readability
import unittest
good_code = """
def this_is_some_good_code(var):
for i in range(10):
print(i)
"""
bad_code = """
tisgc = lambda var: [print(i) for i in range(10)]
"""
# taken from http://en.wikipedia.org/wiki/APL_%28programming_language%29#Examples
apl_code = u"""
life←{↑1 ⍵∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵}
"""
class TestReadability(unittest.TestCase):
def setUp(self):
pass
def test_good_better_than_bad(self):
good_score = readability.score(good_code)
bad_score = readability.score(bad_code)
apl_score = readability.score(apl_code)
self.assertTrue(good_score < bad_score < apl_score)
def test_ignore_pattern(self):
self.assertFalse(readability.EXT_RE.match("abc.py"))
self.assertTrue(readability.EXT_RE.match("abc.pyc"))
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import readability
import unittest
good_code = """
def this_is_some_good_code(var):
for i in range(10):
print(i)
"""
bad_code = """
tisgc = lambda var: [print(i) for i in range(10)]
"""
apl_code = u"""
life←{↑1 ⍵∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵}
"""
class TestReadability(unittest.TestCase):
def setUp(self):
pass
def test_good_better_than_bad(self):
good_score = readability.score(good_code)
bad_score = readability.score(bad_code)
apl_score = readability.score(apl_code)
self.assertTrue(good_score < bad_score < apl_score)
def test_ignore_pattern(self):
self.assertFalse(readability.EXT_RE.match("abc.py"))
self.assertTrue(readability.EXT_RE.match("abc.pyc"))
if __name__ == '__main__':
unittest.main()
|
Use absolute locations for plugins and presets in packager babel config
Reviewed By: davidaurelio
Differential Revision: D5044244
fbshipit-source-id: ab1af28d0158c22d0426a7a3b3f1bb0a63abac4e | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
require('./setupNodePolyfills');
var _only = [];
function registerOnly(onlyList) {
require('babel-register')(config(onlyList));
}
function config(onlyList) {
_only = _only.concat(onlyList);
return {
presets: [require('babel-preset-es2015-node')],
plugins: [
'transform-flow-strip-types',
'syntax-trailing-function-commas',
'transform-object-rest-spread',
'transform-async-to-generator',
].map(pluginName => require(`babel-plugin-${pluginName}`)),
only: _only,
retainLines: true,
sourceMaps: 'inline',
babelrc: false,
};
}
module.exports = exports = registerOnly;
exports.config = config;
| /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
require('./setupNodePolyfills');
var _only = [];
function registerOnly(onlyList) {
require('babel-register')(config(onlyList));
}
function config(onlyList) {
_only = _only.concat(onlyList);
return {
presets: ['es2015-node'],
plugins: [
'transform-flow-strip-types',
'syntax-trailing-function-commas',
'transform-object-rest-spread',
'transform-async-to-generator',
],
only: _only,
retainLines: true,
sourceMaps: 'inline',
babelrc: false,
};
}
module.exports = exports = registerOnly;
exports.config = config;
|
Adjust GET / and GET /certificates | <?php
// Auto load composer components
require '../vendor/autoload.php';
// Require config
include('../config.php');
// Initalize Slim instance
$app = new \Slim\Slim();
$app->view(new \JsonApiView());
$app->add(new \JsonApiMiddleware());
// Check for necessarry credential/configuration constants
if (!defined('DB_HOSTNAME') || !defined('DB_NAME') | !defined('DB_USERNAME') | !defined('DB_PASSWORD')) {
die('{"msg":"Invalid database connection","error":true,"status":500}');
}
// Initalize database connection
$database = new medoo([
'database_type' => 'mysql',
'database_name' => constant('DB_NAME'),
'server' => constant('DB_HOSTNAME'),
'username' => constant('DB_USERNAME'),
'password' => constant('DB_PASSWORD'),
'charset' => 'utf8',
// 'prefix' => 'crt_',
]);
// GET "/" route
$app->get('/', function() use ($app, $database) {
// Create array with available routes
$routes = array(
'GET /' => 'This API overview, right here',
'GET /certificates' => 'Get all available certificates'
);
// Render as JSON resulta
$app->render(200,array(
'msg' => array('routes'=>$routes)
));
});
// GET "/certificates" route
$app->get('/certificates', function() use ($app, $database) {
// Run SQL select
$data = $database->select("certificates", "*");
// Render result
$app->render(200,array(
'msg' => $data
));
});
$app->run();
| <?php
// Auto load composer components
require '../vendor/autoload.php';
// Require config
include('../config.php');
// Initalize Slim instance
$app = new \Slim\Slim();
$app->view(new \JsonApiView());
$app->add(new \JsonApiMiddleware());
// Check for necessarry credential/configuration constants
if (!defined('DB_HOSTNAME') || !defined('DB_NAME') | !defined('DB_USERNAME') | !defined('DB_PASSWORD')) {
die('{"msg":"Invalid database connection","error":true,"status":500}');
}
// Initalize database connection
$database = new medoo([
'database_type' => 'mysql',
'database_name' => constant('DB_NAME'),
'server' => constant('DB_HOSTNAME'),
'username' => constant('DB_USERNAME'),
'password' => constant('DB_PASSWORD'),
'charset' => 'utf8',
// 'prefix' => 'crt_',
]);
// GET "/" route
$app->get('/', function() use ($app) {
$app->render(200,array(
'msg' => 'Welcome to my json API!',
));
});
$app->run();
|
Clean up: removed unused field | package com.jaiwo99.cards.service;
import com.jaiwo99.cards.deal.JiangDealStrategy;
import com.jaiwo99.cards.domain.Jiang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author liang - jaiwo99@gmail.com
*/
@Service
public class JiangDealServiceImpl implements JiangDealService {
@Autowired
private JiangDealStrategy jiangDealStrategy;
@Override
public List<Jiang> choose() {
return jiangDealStrategy.choose();
}
@Override
public Jiang pick(String id) {
return jiangDealStrategy.pick(id);
}
@Override
public List<Jiang> listNew() {
return jiangDealStrategy.listNew();
}
@Override
public List<Jiang> listChosen() {
return jiangDealStrategy.listChosen();
}
@Override
public List<Jiang> listPicked() {
return jiangDealStrategy.listPicked();
}
@Override
public void reset() {
jiangDealStrategy.reset();
}
}
| package com.jaiwo99.cards.service;
import com.jaiwo99.cards.deal.JiangDealStrategy;
import com.jaiwo99.cards.domain.Jiang;
import com.jaiwo99.cards.repository.CardDealRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author liang - jaiwo99@gmail.com
*/
@Service
public class JiangDealServiceImpl implements JiangDealService {
@Autowired
private JiangDealStrategy jiangDealStrategy;
@Autowired
private CardDealRepository cardDealRepository;
@Override
public List<Jiang> choose() {
return jiangDealStrategy.choose();
}
@Override
public Jiang pick(String id) {
return jiangDealStrategy.pick(id);
}
@Override
public List<Jiang> listNew() {
return jiangDealStrategy.listNew();
}
@Override
public List<Jiang> listChosen() {
return jiangDealStrategy.listChosen();
}
@Override
public List<Jiang> listPicked() {
return jiangDealStrategy.listPicked();
}
@Override
public void reset() {
jiangDealStrategy.reset();
}
}
|
GUACAMOLE-197: Remove remaining JavaScript debug code. | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Controller for the "GUAC_RADIUS_CHALLENGE_RESPONSE" field which uses the DuoWeb
* API to prompt the user for additional credentials, ultimately receiving a
* signed response from the Duo service.
*/
angular.module('guacRadius').controller('radiusResponseController', ['$scope', '$element',
function radiusResponseController($scope, $element) {
// Find the area to display the challenge message
var radiusChallenge = $element.find(document.querySelector('#radius-challenge-text'));
// Populate the reply message field
radiusChallenge.html($scope.field.replyMsg);
}]);
| /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Controller for the "GUAC_RADIUS_CHALLENGE_RESPONSE" field which uses the DuoWeb
* API to prompt the user for additional credentials, ultimately receiving a
* signed response from the Duo service.
*/
angular.module('guacRadius').controller('radiusResponseController', ['$scope', '$element',
function radiusResponseController($scope, $element) {
// Find the area to display the challenge message
var radiusChallenge = $element.find(document.querySelector('#radius-challenge-text'));
// Populate the reply message field
console.log("RADIUS Reply Message: " + $scope.field.replyMsg);
radiusChallenge.html($scope.field.replyMsg);
}]);
|
Add log statement in readJson |
module.exports = readJson;
var fs = require("fs"),
semver = require("./semver"),
log = require("../utils").log;
function readJson (jsonFile, cb) {
log(jsonFile, "readJson");
fs.readFile(jsonFile, function (er, jsonString) {
if (er) return cb(er, jsonString);
var json;
try {
json = JSON.parse(jsonString);
} catch (ex) {
return cb(new Error(
"Failed to parse json file: "+jsonFile+"\n"+ex.message+"\n"+jsonString));
}
json.name = json.name.replace(/([^\w-]|_)+/g, '-');
// allow semvers, but also stuff like
// 0.1.2beta-L24561-2010-02-25-13-41-32-903 for test/link packages.
if (!(semver.valid(json.version))) {
return cb(new Error("Invalid version: "+json.version));
}
var key = json.name+"-"+json.version;
json._npmKey = key;
cb(null, json);
});
};
|
module.exports = readJson;
var fs = require("fs"),
semver = require("./semver");
function readJson (jsonFile, cb) {
fs.readFile(jsonFile, function (er, jsonString) {
if (er) return cb(er, jsonString);
var json;
try {
json = JSON.parse(jsonString);
} catch (ex) {
return cb(new Error(
"Failed to parse json file: "+jsonFile+"\n"+ex.message+"\n"+jsonString));
}
json.name = json.name.replace(/([^\w-]|_)+/g, '-');
// allow semvers, but also stuff like
// 0.1.2beta-L24561-2010-02-25-13-41-32-903 for test/link packages.
if (!(semver.valid(json.version))) {
return cb(new Error("Invalid version: "+json.version));
}
var key = json.name+"-"+json.version;
json._npmKey = key;
cb(null, json);
});
};
|
Include TinyMCE icons after update | import tinymce from 'tinymce/tinymce';
window.tinymce = tinymce;
import 'tinymce/themes/silver';
import 'tinymce/icons/default';
import 'tinymce/plugins/link';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/image';
import 'tinymce/plugins/table';
import 'tinymce/plugins/code';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/media';
import 'tinymce/plugins/noneditable';
import {getInitConfig} from '../libs/tinymce_extensions';
const ENHANCED = window.VERIFIED || window.SUP;
function initRichTextEditor(element, code=false) {
// Vue rebuilds the whole dom in between the call to init and tinymce actually doing the init
// so we use a selector here until we use vue to init tinymce
const selector=`${element.type}#${element.id}`;
let config = getInitConfig(selector, ENHANCED, code);
return tinymce.init(config);
}
for (const textArea of document.querySelectorAll('.richtext-editor'))
initRichTextEditor(textArea);
for (const textArea of document.querySelectorAll('.richtext-editor-src'))
initRichTextEditor(textArea, true);
global.initRichTextEditor = initRichTextEditor;
| import tinymce from 'tinymce/tinymce';
window.tinymce = tinymce;
import 'tinymce/themes/silver';
import 'tinymce/plugins/link';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/image';
import 'tinymce/plugins/table';
import 'tinymce/plugins/code';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/media';
import 'tinymce/plugins/noneditable';
import {getInitConfig} from '../libs/tinymce_extensions';
const ENHANCED = window.VERIFIED || window.SUP;
function initRichTextEditor(element, code=false) {
// Vue rebuilds the whole dom in between the call to init and tinymce actually doing the init
// so we use a selector here until we use vue to init tinymce
const selector=`${element.type}#${element.id}`;
let config = getInitConfig(selector, ENHANCED, code);
return tinymce.init(config);
}
for (const textArea of document.querySelectorAll('.richtext-editor'))
initRichTextEditor(textArea);
for (const textArea of document.querySelectorAll('.richtext-editor-src'))
initRichTextEditor(textArea, true);
global.initRichTextEditor = initRichTextEditor;
|
Make dynamic host in /API | /*
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Smart Developer Hub Project:
http://www.smartdeveloperhub.org/
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
'use strict';
var fs = require('fs');
exports.apiInfo = function() {
var aux = JSON.parse(fs.readFileSync('./api/swagger.json', 'utf8'));
return {
"swaggerjson" : aux,
"host" : aux.host
};
};
| /*
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Smart Developer Hub Project:
http://www.smartdeveloperhub.org/
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
'use strict';
var fs = require('fs');
exports.apiInfo = function() {
return {
"swaggerjson" : JSON.parse(fs.readFileSync('./api/swagger.json', 'utf8')),
"host" : "http://localhost:8080"
};
};
|
Return str(self) instead of self. | #
# Copyright 2008 Andi Albrecht <albrecht.andi@gmail.com>
#
# 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.
class CallableString(str):
def __call__(self):
return str(self)
def id(self):
try:
return int(self.split('_')[-1])
except:
return None
| #
# Copyright 2008 Andi Albrecht <albrecht.andi@gmail.com>
#
# 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.
class CallableString(str):
def __call__(self):
return self
def id(self):
try:
return int(self.split('_')[-1])
except:
return None
|
Fix typo in objectified name | from lxml.objectify import fromstring
class BaseMessage(object):
"""
Base XML message.
"""
def __init__(self, xml):
"""
Create an object of BaseMessage.
:param xml: a file object or a string with the XML
:return: an instance of BaseMessage
"""
self.objectified = xml
@property
def objectified(self):
"""
The XML objectified
:return: the XML objectified
"""
return self._objectified
@objectified.setter
def objectified(self, value):
"""
Objectify an XML
:param value: a file object or string with the XML
"""
if isinstance(value, file):
value = value.read()
self._xml = value
self._objectified = fromstring(self._xml)
class MessageS(BaseMessage):
"""
Message class for reports.
"""
pass
| from lxml.objectify import fromstring
class BaseMessage(object):
"""
Base XML message.
"""
def __init__(self, xml):
"""
Create an object of BaseMessage.
:param xml: a file object or a string with the XML
:return: an instance of BaseMessage
"""
self.objectified = xml
@property
def objectified(self):
"""
The XML objectified
:return: the XML objectified
"""
return self._objectifyed
@objectified.setter
def objectified(self, value):
"""
Objectify an XML
:param value: a file object or string with the XML
"""
if isinstance(value, file):
value = value.read()
self._xml = value
self._objectifyed = fromstring(self._xml)
class MessageS(BaseMessage):
"""
Message class for reports.
"""
pass
|
Add missing paren to if statement. | 'use strict';
var assign = Object.assign || require('object.assign');
function hasOwnKey(key, object) {
return object != null && object.hasOwnProperty(key);
}
function objectsHaveOwnKey() {
var key = arguments[0],
objects = [].slice.call(arguments, 1);
return objects.every(hasOwnKey.bind(null, key));
}
function strictAssign() {
var target = arguments[0],
sources = [].slice.call(arguments, 1),
assignArgs = [].concat({}, sources),
i,
key,
strippedTarget;
sources.forEach(function stripTarget(source) {
for (key in source) {
if (objectsHaveOwnKey(key, source, target)
&& !hasOwnKey(key, strippedTarget)) {
strippedTarget[key] = target[key];
}
}
});
assignArgs.push(strippedTarget);
return assign.apply(null, assignArgs);
}
module.exports = strictAssign;
| 'use strict';
var assign = Object.assign || require('object.assign');
function hasOwnKey(key, object) {
return object != null && object.hasOwnProperty(key);
}
function objectsHaveOwnKey() {
var key = arguments[0],
objects = [].slice.call(arguments, 1);
return objects.every(hasOwnKey.bind(null, key));
}
function strictAssign() {
var target = arguments[0],
sources = [].slice.call(arguments, 1),
assignArgs = [].concat({}, sources),
i,
key,
strippedTarget;
sources.forEach(function stripTarget(source) {
for (key in source) {
if (objectsHaveOwnKey(key, source, target)
&& !hasOwnKey(key, strippedTarget) {
strippedTarget[key] = target[key];
}
}
});
assignArgs.push(strippedTarget);
return assign.apply(null, assignArgs);
}
module.exports = strictAssign;
|
Add -d / --directory option | #!/usr/bin/env python3
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
import argparse
import os
import zipfile
parser = argparse.ArgumentParser(description = "Extract zip file includes cp932 encoding file name")
parser.add_argument("file")
parser.add_argument("-d", "--directory", nargs="?", type=str, default="")
args = parser.parse_args()
with zipfile.ZipFile(args.file, 'r') as archive:
for item in archive.namelist():
filename = os.path.join(args.directory, item.encode("cp437").decode("cp932"))
directory = os.path.dirname(filename)
if not os.path.exists(directory):
os.makedirs(directory)
if os.path.basename(filename):
with open(filename, "wb") as data:
data.write(archive.read(item))
# Local variables:
# tab-width: 4
# c-basic-offset: 4
# c-hanging-comment-ender-p: nil
# End:
| #!/usr/bin/env python3
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
import argparse
import os
import zipfile
parser = argparse.ArgumentParser(description = "Extract zip file includes cp932 encoding file name")
parser.add_argument("file")
args = parser.parse_args()
with zipfile.ZipFile(args.file, 'r') as archive:
for item in archive.namelist():
filename = item.encode("cp437").decode("cp932")
directory = os.path.dirname(filename)
if not os.path.exists(directory):
os.makedirs(directory)
if os.path.basename(filename):
with open(filename, "wb") as data:
data.write(archive.read(item))
# Local variables:
# tab-width: 4
# c-basic-offset: 4
# c-hanging-comment-ender-p: nil
# End:
|
Change default day format to 3-letter day. | 'use strict';
angular
.module('mwl.calendar')
.provider('calendarConfig', function() {
var defaultDateFormats = {
hour: 'ha',
day: 'D MMM',
month: 'MMMM',
// CUSTOMIZATION: change to dd for Sa Su Mo Tu We Th Fr
// weekDay: 'ddd'
weekDay: 'ddd'
};
var defaultTitleFormats = {
day: 'dddd D MMMM, YYYY',
week: 'Week {week} of {year}',
month: 'MMMM YYYY',
year: 'YYYY'
};
var i18nStrings = {
eventsLabel: 'Events',
timeLabel: 'Time'
};
var configProvider = this;
configProvider.setDateFormats = function(formats) {
angular.extend(defaultDateFormats, formats);
return configProvider;
};
configProvider.setTitleFormats = function(formats) {
angular.extend(defaultTitleFormats, formats);
return configProvider;
};
configProvider.setI18nStrings = function(strings) {
angular.extend(i18nStrings, strings);
return configProvider;
};
configProvider.$get = function() {
return {
dateFormats: defaultDateFormats,
titleFormats: defaultTitleFormats,
i18nStrings: i18nStrings
};
};
});
| 'use strict';
angular
.module('mwl.calendar')
.provider('calendarConfig', function() {
var defaultDateFormats = {
hour: 'ha',
day: 'D MMM',
month: 'MMMM',
// CUSTOMIZATION: change to dd for Sa Su Mo Tu We Th Fr
// weekDay: 'ddd'
weekDay: 'dddd'
};
var defaultTitleFormats = {
day: 'dddd D MMMM, YYYY',
week: 'Week {week} of {year}',
month: 'MMMM YYYY',
year: 'YYYY'
};
var i18nStrings = {
eventsLabel: 'Events',
timeLabel: 'Time'
};
var configProvider = this;
configProvider.setDateFormats = function(formats) {
angular.extend(defaultDateFormats, formats);
return configProvider;
};
configProvider.setTitleFormats = function(formats) {
angular.extend(defaultTitleFormats, formats);
return configProvider;
};
configProvider.setI18nStrings = function(strings) {
angular.extend(i18nStrings, strings);
return configProvider;
};
configProvider.$get = function() {
return {
dateFormats: defaultDateFormats,
titleFormats: defaultTitleFormats,
i18nStrings: i18nStrings
};
};
});
|
Add workaround that makes completion actually work. | #!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var tab = require('tabalot');
var noop = function() {}
var homedir = path.resolve(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], '.grunt-init');
if (process.argv.indexOf('completion') !== -1 && process.argv.indexOf('--') === -1) {
process.argv.push('--bin');
process.argv.push('grunt-init');
process.argv.push('--completion');
process.argv.push('grunt-init-completion');
}
fs.readdir(path.join(homedir), function(err, files) {
if (err) process.exit(2);
files = files.filter(function(file) {
return fs.statSync(path.join(homedir, file)).isDirectory();
});
files.forEach(function(file) {
tab(file)(noop);
});
tab.parse();
});
| #!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var tab = require('tabalot');
var noop = function() {}
var homedir = path.resolve(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], '.grunt-init');
if (process.argv.indexOf('completion') !== -1 && process.argv.indexOf('--') === -1) {
process.argv.push('--bin');
process.argv.push('grunt-init');
process.argv.push('--completion');
process.argv.push('grunt-init-completion');
}
tab()
('-i', function(callback) {
fs.readdir(path.join(homedir), function(err, files) {
if (err) callback(err);
files = files.filter(function(file) {
return fs.statSync(path.join(homedir, file)).isDirectory();
});
if (files.length) return callback(null, files, {
exitCode:15,
});
callback();
});
})
tab.parse();
|
Fix bug that didn't return the right leaderboard | from nameko.rpc import rpc, RpcProxy
from nameko.events import event_handler
class ScoreService(object):
name = 'score_service'
player_rpc = RpcProxy('players_service')
@rpc
def leaderboard(self):
players = self.player_rpc.get_players()
sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
return [(p.name, p.score) for p in sorted_players]
@event_handler('battle_service', 'battle_finished')
def update_players_score(self, data):
# NOTE: for now the winner gets 2 points and the loser 1
_, winner, loser = data
self.player_rpc.get_player(winner).add_score(2)
self.player_rpc.get_player(loser).add_score(1)
| from nameko.rpc import rpc, RpcProxy
from nameko.events import event_handler
class ScoreService(object):
name = 'score_service'
player_rpc = RpcProxy('players_service')
@rpc
def leaderboard(self):
players = self.player_rpc.get_players()
sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
return [(p.name, p.score) for p in players]
@event_handler('battle_service', 'battle_finished')
def update_players_score(self, data):
# NOTE: for now the winner gets 2 points and the loser 1
_, winner, loser = data
self.player_rpc.get_player(winner).add_score(2)
self.player_rpc.get_player(loser).add_score(1)
|
Add dateutils to the requirements | import sys
from setuptools import setup, find_packages
import populous
requirements = [
"click",
"cached-property",
"fake-factory",
"dateutils"
]
if sys.version_info < (3, 2):
requirements.append('functools32')
setup(
name="populous",
version=populous.__version__,
url=populous.__url__,
description=populous.__doc__,
author=populous.__author__,
license=populous.__license__,
long_description="TODO",
packages=find_packages(),
install_requires=requirements,
entry_points={
'console_scripts': [
'populous = populous.__main__:cli'
]
},
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Utilities",
],
keywords='populous populate database',
)
| import sys
from setuptools import setup, find_packages
import populous
requirements = [
"click",
"cached-property",
"fake-factory",
]
if sys.version_info < (3, 2):
requirements.append('functools32')
setup(
name="populous",
version=populous.__version__,
url=populous.__url__,
description=populous.__doc__,
author=populous.__author__,
license=populous.__license__,
long_description="TODO",
packages=find_packages(),
install_requires=requirements,
entry_points={
'console_scripts': [
'populous = populous.__main__:cli'
]
},
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Utilities",
],
keywords='populous populate database',
)
|
Add IP access for custom dev envs. | <?php
use Symfony\Component\HttpFoundation\Request;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array(
'127.0.0.1',
'::1',
'83.156.34.69', // RW dev server
'51.255.174.234', // MC dev server
))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check ' . basename(__FILE__) . ' for more information.');
}
$loader = require_once __DIR__ . '/../app/bootstrap.php.cache';
require_once __DIR__ . '/../app/AppKernel.php';
$kernel = new AppKernel('dev', TRUE);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(@$_SERVER['REMOTE_ADDR'], array(
'127.0.0.1',
'::1',
))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Fix petty error in dashboard. | package org.robockets.stronghold.robot.highgoalshooter;
import org.robockets.stronghold.robot.EncoderPIDSource;
import org.robockets.stronghold.robot.Robot;
import org.robockets.stronghold.robot.RobotMap;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
*
*/
public class UpdateHighGoalShooterDashboard extends Command {
public UpdateHighGoalShooterDashboard() {
}
protected void initialize() {
}
protected void execute() {
SmartDashboard.putNumber("Turn table encoder", new EncoderPIDSource(RobotMap.turnTableEncoder, 0.16096579).pidGet());
}
protected boolean isFinished() {
return false;
}
protected void end() {
}
protected void interrupted() {
}
}
| package org.robockets.stronghold.robot.highgoalshooter;
import org.robockets.stronghold.robot.Robot;
import org.robockets.stronghold.robot.RobotMap;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
*
*/
public class UpdateHighGoalShooterDashboard extends Command {
public UpdateHighGoalShooterDashboard() {
}
protected void initialize() {
}
protected void execute() {
SmartDashboard.putNumber("Turn table encoder", new EncoderPIDSource(RobotMap.turnTableEncoder, 0.16096579).pidGet());
}
protected boolean isFinished() {
return false;
}
protected void end() {
}
protected void interrupted() {
}
}
|
Add Config.get() to skip KeyErrors
Adds common `dict.get()` pattern to our own Config class, to enable
use of fallbacks or `None`, as appropriate. | #! /usr/bin/env python
import os
import warnings
import yaml
class Config(object):
config_fname = "configuration.yaml"
def __init__(self, config_fname=None):
config_fname = config_fname or self.config_fname
fo = open(config_fname, "r")
blob = fo.read()
fo.close()
self.config = yaml.load(blob)
def __getattr__(self, attrname):
if attrname == "slack_name":
warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" %
self.config_fname, DeprecationWarning)
return self.config[attrname]
def get(self, attrname, fallback=None):
try:
return self.config[attrname]
except KeyError:
return fallback
# This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME
SLACK_NAME = os.getenv("SLACK_NAME")
if SLACK_NAME is None:
SLACK_NAME = Config().slack_name
| #! /usr/bin/env python
import os
import warnings
import yaml
class Config(object):
config_fname = "configuration.yaml"
def __init__(self, config_fname=None):
config_fname = config_fname or self.config_fname
fo = open(config_fname, "r")
blob = fo.read()
fo.close()
self.config = yaml.load(blob)
def __getattr__(self, attrname):
if attrname == "slack_name":
warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" %
self.config_fname, DeprecationWarning)
return self.config[attrname]
# This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME
SLACK_NAME = os.getenv("SLACK_NAME")
if SLACK_NAME is None:
SLACK_NAME = Config().slack_name
|
Add helper function to create a DualPlot | import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r', linestyle=':', fmt='.2f', xtransf=lambda x: x, **kargs):
ax.axvline(left,color=color, linestyle=linestyle)
ax.axvline(right,color=color, linestyle=linestyle)
s = "{:"+fmt+"}"+kargs.get('unit','')
ax.annotate(s.format(xtransf(right-left)),(.5*(left+right),y),(0,2),textcoords='offset pixels',va='bottom',ha='center')
ax.annotate("",(left,y),(right,y),arrowprops=dict(arrowstyle=kargs.get('arrowstyle','<->')))
def DualPlot(ax, col1='C0',col2='C1'):
axb = ax.twinx()
axb.spines['left'].set_color(col1)
axb.spines['right'].set_color(col2)
ax.yaxis.label.set_color(col1)
axb.yaxis.label.set_color(col2)
ax.tick_params(axis='y', colors=col1)
axb.tick_params(axis='y', colors=col2)
return axb | import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r', linestyle=':', fmt='.2f', xtransf=lambda x: x, **kargs):
ax.axvline(left,color=color, linestyle=linestyle)
ax.axvline(right,color=color, linestyle=linestyle)
s = "{:"+fmt+"}"+kargs.get('unit','')
ax.annotate(s.format(xtransf(right-left)),(.5*(left+right),y),(0,2),textcoords='offset pixels',va='bottom',ha='center')
ax.annotate("",(left,y),(right,y),arrowprops=dict(arrowstyle=kargs.get('arrowstyle','<->'))) |
Add Pagination Button to navigate between the result | <?php get_header();?>
<?php $catid = get_cat_id( single_cat_title("",false) );?>
<head><title><?php single_cat_title('',true); echo ' - '; bloginfo('name'); ?></title></head>
<div class="container">
<div class="shadow-box shadow-box-colour row" style = "padding-top : 5px;">
<h5>Category : <?php single_cat_title('',true); ?></h5>
<p> <?php echo category_description($catid); ?> </p>
</div>
<?php if (have_posts()) : while(have_posts()) : the_post();?>
<div class="shadow-box-page shadow-box-colour row">
<a class = 'header-link' href="<?php the_permalink();?>" title = "<?php the_title();?>"><h3 class = "header-text text-center"><?php the_title();?></h3></a>
<center><?php if (has_post_thumbnail()) {the_post_thumbnail('large',array('class' => 'img-responsive img-thumb'));} ?></center>
<p class = "content"><?php the_excerpt(); ?></p>
</div>
<?php endwhile; else : ?>
<p><?php _e('No post right now.'); ?></p>
<?php endif; ?>
<div class = "content-nav container">
<?php next_posts_link('Older Entries') ?>
<?php previous_posts_link('Newer Entries') ?>
</div>
</div>
<?php get_footer();?>
| <?php get_header();?>
<?php $catid = get_cat_id( single_cat_title("",false) );?>
<head><title><?php single_cat_title('',true); echo ' - '; bloginfo('name'); ?></title></head>
<div class="container" style="margin-bottom:75px;">
<div class="shadow-box shadow-box-colour row" style = "padding-top : 5px;">
<h5>Category : <?php single_cat_title('',true); ?></h5>
<p> <?php echo category_description($catid); ?> </p>
</div>
<?php if (have_posts()) : while(have_posts()) : the_post();?>
<div class="shadow-box-page shadow-box-colour row">
<a class = 'header-link' href="<?php the_permalink();?>" title = "<?php the_title();?>"><h3 class = "header-text text-center"><?php the_title();?></h3></a>
<center><?php if (has_post_thumbnail()) {the_post_thumbnail('large',array('class' => 'img-responsive img-thumb'));} ?></center>
<p class = "content"><?php the_excerpt(); ?></p>
</div>
<?php endwhile; else : ?>
<p><?php _e('No post right now.'); ?></p>
<?php endif; ?>
</div>
<?php get_footer();?>
|
Fix a failure in test | package seedu.address.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Scheduler App\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/scheduler.xml\n" +
"Scheduler name : MyScheduler";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
| package seedu.address.commons.core;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ConfigTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toString_defaultObject_stringReturned() {
String defaultConfigAsString = "App title : Date App\n" +
"Current log level : INFO\n" +
"Preference file Location : preferences.json\n" +
"Local data file location : data/scheduler.xml\n" +
"Scheduler name : MyScheduler";
assertEquals(defaultConfigAsString, new Config().toString());
}
@Test
public void equalsMethod(){
Config defaultConfig = new Config();
assertFalse(defaultConfig.equals(null));
assertTrue(defaultConfig.equals(defaultConfig));
}
}
|
Fix dashboard chart update after customer switch.
Temporary disable chart pulling. | // @flow
import { delay, takeEvery } from 'redux-saga';
import { call, take, put, cancel, fork } from 'redux-saga/effects';
import api from './api';
import actions from './actions';
const CHART_PULLING_INTERVAL = 60 * 1000;
function* fetchDashboardChart(chartId, scope) {
try {
const charts = yield call(api.fetchChart, chartId, scope);
yield put(actions.dashboardChartSuccess(chartId, charts));
} catch(error) {
yield put(actions.dashboardChartError(chartId, error));
}
}
function* pullDashboardChart(chartId, scope) {
// eslint-disable-next-line no-constant-condition
while (true) {
fetchDashboardChart(chartId, scope);
yield call(delay, CHART_PULLING_INTERVAL);
}
}
function* startDashboardChart({ chartId, scope }) {
const task = yield fork(pullDashboardChart, chartId, scope);
yield take(action => action.type === actions.DASHBOARD_CHARTS_STOP && action.chartId === chartId);
yield cancel(task);
}
function* watchEmit() {
yield takeEvery(actions.EMIT_SIGNAL, action => api.emitSignal(action.signal));
}
function* rootSaga():any {
yield takeEvery(actions.DASHBOARD_CHARTS_START, ({chartId, scope}) => fetchDashboardChart(chartId, scope));
yield fork(watchEmit);
}
export default rootSaga;
| // @flow
import { delay, takeEvery } from 'redux-saga';
import { call, take, put, cancel, fork } from 'redux-saga/effects';
import api from './api';
import actions from './actions';
const CHART_PULLING_INTERVAL = 60 * 1000;
function* pullDashboardChart(chartId, scope) {
// eslint-disable-next-line no-constant-condition
while (true) {
try {
const charts = yield call(api.fetchChart, chartId, scope);
yield put(actions.dashboardChartSuccess(chartId, charts));
} catch(error) {
yield put(actions.dashboardChartError(chartId, error));
}
yield call(delay, CHART_PULLING_INTERVAL);
}
}
function* startDashboardChart({ chartId, scope }) {
const task = yield fork(pullDashboardChart, chartId, scope);
yield take(action => action.type === actions.DASHBOARD_CHARTS_STOP && action.chartId === chartId);
yield cancel(task);
}
function* watchEmit() {
yield takeEvery(actions.EMIT_SIGNAL, action => api.emitSignal(action.signal));
}
function* rootSaga():any {
yield takeEvery(actions.DASHBOARD_CHARTS_START, startDashboardChart);
yield fork(watchEmit);
}
export default rootSaga;
|
Use relative path to typestring for tests | /**
* typestring - In-memory TypeScript compiler
* https://github.com/gavinhungry/typestring
*/
(function() {
'use strict';
var fs = require('fs');
var tap = require('tap');
var ts = require('../typestring');
tap.test('no/undefined input results in an empty string', function(t) {
var js = ts.compile();
t.equal(js, '', 'undefined input outputs empty string');
js = ts.compile('');
t.equal(js, '', 'empty string input outputs empty string');
js = ts.compile(' ');
t.equal(js, '', 'whitespace input outputs empty string');
t.end();
});
tap.test('simple module input results in correct output', function(t) {
var simpleClassJS = 'var Foo = (function () {\n function Foo() {\n this.bar = 2;\n }\n return Foo;\n})();\n';
var js = ts.compile('class Foo { public bar = 2; }');
t.equal(js, simpleClassJS, 'inline class outputs expected result');
js = ts.compile('/// <reference path="foo.ts" />', {
'foo.ts': 'class Foo { public bar = 2; }'
});
t.equal(js, simpleClassJS, 'reference path class outputs expected result');
t.end();
});
})();
| /**
* typestring - In-memory TypeScript compiler
* https://github.com/gavinhungry/typestring
*/
(function() {
'use strict';
var fs = require('fs');
var tap = require('tap');
var ts = require('typestring');
tap.test('no/undefined input results in an empty string', function(t) {
var js = ts.compile();
t.equal(js, '', 'undefined input outputs empty string');
js = ts.compile('');
t.equal(js, '', 'empty string input outputs empty string');
js = ts.compile(' ');
t.equal(js, '', 'whitespace input outputs empty string');
t.end();
});
tap.test('simple module input results in correct output', function(t) {
var simpleClassJS = 'var Foo = (function () {\n function Foo() {\n this.bar = 2;\n }\n return Foo;\n})();\n';
var js = ts.compile('class Foo { public bar = 2; }');
t.equal(js, simpleClassJS, 'inline class outputs expected result');
js = ts.compile('/// <reference path="foo.ts" />', {
'foo.ts': 'class Foo { public bar = 2; }'
});
t.equal(js, simpleClassJS, 'reference path class outputs expected result');
t.end();
});
})();
|
Add filter by status route for projects | <?php
/*
|--------------------------------------------------------------------------
| Application Routers
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::group(['before' => 'Sentinel\auth'], function()
{
Route::resource('projects', 'ProjectsController');
Route::resource('tickets', 'TicketsController');
Route::resource('invoices', 'InvoicesController');
Route::get('/tickets/status/{status}', ['as' => 'tickets.by.status', 'uses' => 'TicketsController@filterByStatus']);
Route::get('/projects/status/{status}', ['as' => 'projects.by.status', 'uses' => 'ProjectsController@filterByStatus']);
Route::post('tickets/{id}/reply', 'TicketsController@reply');
Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
# Override Sentinel's Default user routes with our own filter requirement
Route::get('/users/{id}', ['as' => 'sl_user.show', 'uses' => 'SimpleLance\UserController@show'])->where('id', '[0-9]+');
Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@index']);
});
Route::group(['before' => 'Sentinel\inGroup:Admins'], function()
{
Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]);
Route::resource('statuses', 'StatusesController', ['except' => ['show']]);
});
| <?php
/*
|--------------------------------------------------------------------------
| Application Routers
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::group(['before' => 'Sentinel\auth'], function()
{
Route::resource('projects', 'ProjectsController');
Route::resource('tickets', 'TicketsController');
Route::resource('invoices', 'InvoicesController');
Route::get('/tickets/status/{status}', ['as' => 'ticket.by.status', 'uses' => 'TicketsController@filterByStatus']);
Route::post('tickets/{id}/reply', 'TicketsController@reply');
Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
# Override Sentinel's Default user routes with our own filter requirement
Route::get('/users/{id}', ['as' => 'sl_user.show', 'uses' => 'SimpleLance\UserController@show'])->where('id', '[0-9]+');
Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@index']);
});
Route::group(['before' => 'Sentinel\inGroup:Admins'], function()
{
Route::resource('priorities', 'PrioritiesController', ['except' => ['show']]);
Route::resource('statuses', 'StatusesController', ['except' => ['show']]);
});
|
Fix entity type post deletion | from .base import BaseModelResource, BaseModelsResource
from zou.app.models.entity_type import EntityType
from zou.app.utils import events
from zou.app.services import entities_service
class EntityTypesResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, EntityType)
def check_read_permissions(self):
return True
def emit_create_event(self, instance_dict):
events.emit("asset-type:new", {"asset_type_id": instance_dict["id"]})
class EntityTypeResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, EntityType)
def check_read_permissions(self, instance):
return True
def emit_update_event(self, instance_dict):
events.emit("asset-type:update", {"asset_type_id": instance_dict["id"]})
def emit_delete_event(self, instance_dict):
events.emit("asset-type:delete", {"asset_type_id": instance_dict["id"]})
def post_update(self, instance_dict):
entities_service.clear_entity_type_cache(instance_dict["id"])
def post_delete(self, instance_dict):
entities_service.clear_entity_type_cache(instance_dict["id"])
| from .base import BaseModelResource, BaseModelsResource
from zou.app.models.entity_type import EntityType
from zou.app.utils import events
from zou.app.services import entities_service
class EntityTypesResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, EntityType)
def check_read_permissions(self):
return True
def emit_create_event(self, instance_dict):
events.emit("asset-type:new", {"asset_type_id": instance_dict["id"]})
class EntityTypeResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, EntityType)
def check_read_permissions(self, instance):
return True
def emit_update_event(self, instance_dict):
events.emit("asset-type:update", {"asset_type_id": instance_dict["id"]})
def emit_delete_event(self, instance_dict):
events.emit("asset-type:delete", {"asset_type_id": instance_dict["id"]})
def post_update(self, instance_dict):
entities_service.clear_entity_type_cache(instance_dict["id"])
def post_delete(self, instance_dict):
tasks_service.clear_entity_type_cache(instance_dict["id"])
|
Replace all occurrences of special chars in RFC3986 | var crypto = require('crypto')
, qs = require('querystring')
;
function sha1 (key, body) {
return crypto.createHmac('sha1', key).update(body).digest('base64')
}
function rfc3986 (str) {
return encodeURIComponent(str)
.replace(/!/g,'%21')
.replace(/\*/g,'%2A')
.replace(/\(/g,'%28')
.replace(/\)/g,'%29')
.replace(/'/g,'%27')
;
}
function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret, body) {
// adapted from https://dev.twitter.com/docs/auth/oauth
var base =
(httpMethod || 'GET') + "&" +
encodeURIComponent( base_uri ) + "&" +
Object.keys(params).sort().map(function (i) {
// big WTF here with the escape + encoding but it's what twitter wants
return escape(rfc3986(i)) + "%3D" + escape(rfc3986(params[i]))
}).join("%26")
var key = consumer_secret + '&'
if (token_secret) key += token_secret
return sha1(key, base)
}
exports.hmacsign = hmacsign
exports.rfc3986 = rfc3986 | var crypto = require('crypto')
, qs = require('querystring')
;
function sha1 (key, body) {
return crypto.createHmac('sha1', key).update(body).digest('base64')
}
function rfc3986 (str) {
return encodeURIComponent(str)
.replace('!','%21')
.replace('*','%2A')
.replace('(','%28')
.replace(')','%29')
.replace("'",'%27')
;
}
function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret, body) {
// adapted from https://dev.twitter.com/docs/auth/oauth
var base =
(httpMethod || 'GET') + "&" +
encodeURIComponent( base_uri ) + "&" +
Object.keys(params).sort().map(function (i) {
// big WTF here with the escape + encoding but it's what twitter wants
return escape(rfc3986(i)) + "%3D" + escape(rfc3986(params[i]))
}).join("%26")
var key = consumer_secret + '&'
if (token_secret) key += token_secret
return sha1(key, base)
}
exports.hmacsign = hmacsign
exports.rfc3986 = rfc3986 |
Fix changelog versioning to include date only after final release
(cherry picked from commit d3a4e31fe254ba0c8f3d066a8de32502c0fcafcc) | #!/usr/bin/env node
// Sets the release date of the current release in the changelog.
// This is run automatically when npm version is run.
const fs = require('fs');
const cp = require('child_process');
const suffix = process.env.PRERELEASE_SUFFIX || 'rc';
const changelog = fs.readFileSync('CHANGELOG.md', 'utf8');
// The changelog entry to be updated looks like this:
// ## Unreleased
// We need to add the version and release date in a YYYY-MM-DD format, so that it looks like this:
// ## 2.5.3 (2019-04-25)
const pkg = require('../../package.json');
const version = pkg.version.replace(new RegExp('-' + suffix + '\\..*'), '');
const header = new RegExp(`^## (Unreleased|${version})$`, 'm');
if (!header.test(changelog)) {
console.error('Missing changelog entry');
process.exit(1);
}
const newHeader = pkg.version.indexOf(suffix) === -1
? `## ${version} (${new Date().toISOString().split('T')[0]})`
: `## ${version}`;
fs.writeFileSync('CHANGELOG.md',
changelog.replace(header, newHeader)
);
cp.execSync('git add CHANGELOG.md', { stdio: 'inherit' });
| #!/usr/bin/env node
// Sets the release date of the current release in the changelog.
// This is run automatically when npm version is run.
const fs = require('fs');
const cp = require('child_process');
const suffix = process.env.PRERELEASE_SUFFIX || 'rc';
const changelog = fs.readFileSync('CHANGELOG.md', 'utf8');
// The changelog entry to be updated looks like this:
// ## Unreleased
// We need to add the version and release date in a YYYY-MM-DD format, so that it looks like this:
// ## 2.5.3 (2019-04-25)
const pkg = require('../../package.json');
const version = pkg.version.replace(new RegExp('-' + suffix + '\\..*'), '');
const unreleased = /^## Unreleased$/im;
const released = new RegExp(`^## ${version} \\([-\\d]*\\)$`, 'm');
if (released.test(changelog)) {
process.exit(0);
}
if (!unreleased.test(changelog)) {
console.error('Missing changelog entry');
process.exit(1);
}
fs.writeFileSync('CHANGELOG.md', changelog.replace(
unreleased,
`## ${version} (${new Date().toISOString().split('T')[0]})`),
);
cp.execSync('git add CHANGELOG.md', { stdio: 'inherit' });
|
Set the default IPP URI | <?php
namespace QuickBooksOnline\API\Core\Configuration;
/**
* Base Urls for QBO, QBD and IPP
* -----------------
* Remove QBD part from this and the sdk.config File
* Feb.7th.2017 @Hao
* -----------------
*/
class BaseUrl
{
/**
* Gets or sets the url for QuickBooks Online Rest Service.
* @var string
*/
public $Qbo;
/**
* Gets or sets the url for Platform Rest Service.
* @var string
*/
public $Ipp;
/**
* Initializes a new instance of the BaseUrl class.
*
* @param string $Qbo url for QuickBooks Online Rest Service
* @param string $Ipp url for Platform Rest Service
*/
public function __construct($Qbo=null, $Ipp=null)
{
$this->Qbo=$Qbo;
if(isset($Ipp))
{
$this->Ipp = $Ipp;
}else {
$this->Ipp = "https://appcenter.intuit.com/api/";
}
}
}
| <?php
namespace QuickBooksOnline\API\Core\Configuration;
/**
* Base Urls for QBO, QBD and IPP
* -----------------
* Remove QBD part from this and the sdk.config File
* Feb.7th.2017 @Hao
* -----------------
*/
class BaseUrl
{
/**
* Gets or sets the url for QuickBooks Online Rest Service.
* @var string
*/
public $Qbo;
/**
* Gets or sets the url for Platform Rest Service.
* @var string
*/
public $Ipp;
/**
* Initializes a new instance of the BaseUrl class.
*
* @param string $Qbo url for QuickBooks Online Rest Service
* @param string $Ipp url for Platform Rest Service
*/
public function __construct($Qbo=null, $Ipp=null)
{
$this->Qbo=$Qbo;
$this->Ipp=$Ipp;
}
}
|
Fix attempt QuorumTest for clients
Make sure a client uses a single connection to the cluster. So it is aligned
with blocked connections. | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.quorum;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.nio.Address;
import static com.hazelcast.test.HazelcastTestSupport.getNode;
public class QuorumTestUtil {
private QuorumTestUtil() {
}
public static ClientConfig getClientConfig(HazelcastInstance instance) {
ClientConfig clientConfig = new ClientConfig();
Address address = getNode(instance).address;
clientConfig.getNetworkConfig().addAddress(address.getHost() + ":" + address.getPort());
clientConfig.getNetworkConfig().setSmartRouting(false);
clientConfig.getGroupConfig().setName(instance.getConfig().getGroupConfig().getName());
return clientConfig;
}
}
| /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.quorum;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.nio.Address;
import static com.hazelcast.test.HazelcastTestSupport.getNode;
public class QuorumTestUtil {
private QuorumTestUtil() {
}
public static ClientConfig getClientConfig(HazelcastInstance instance) {
ClientConfig clientConfig = new ClientConfig();
Address address = getNode(instance).address;
clientConfig.getNetworkConfig().addAddress(address.getHost() + ":" + address.getPort());
clientConfig.getGroupConfig().setName(instance.getConfig().getGroupConfig().getName());
return clientConfig;
}
}
|
Handle situation when kwargs is None | from django.conf import settings
from django.core import urlresolvers
from django.utils import translation
from localeurl import utils
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs', {})
if reverse_kwargs!=None:
locale = utils.supported_language(reverse_kwargs.pop('locale',
translation.get_language()))
else:
locale = translation.get_language()
url = django_reverse(*args, **kwargs)
_, path = utils.strip_script_prefix(url)
return utils.locale_url(path, locale)
django_reverse = None
def patch_reverse():
"""
Monkey-patches the urlresolvers.reverse function. Will not patch twice.
"""
global django_reverse
if urlresolvers.reverse is not reverse:
django_reverse = urlresolvers.reverse
urlresolvers.reverse = reverse
if settings.USE_I18N:
patch_reverse()
| from django.conf import settings
from django.core import urlresolvers
from django.utils import translation
from localeurl import utils
def reverse(*args, **kwargs):
reverse_kwargs = kwargs.get('kwargs', {})
locale = utils.supported_language(reverse_kwargs.pop('locale',
translation.get_language()))
url = django_reverse(*args, **kwargs)
_, path = utils.strip_script_prefix(url)
return utils.locale_url(path, locale)
django_reverse = None
def patch_reverse():
"""
Monkey-patches the urlresolvers.reverse function. Will not patch twice.
"""
global django_reverse
if urlresolvers.reverse is not reverse:
django_reverse = urlresolvers.reverse
urlresolvers.reverse = reverse
if settings.USE_I18N:
patch_reverse()
|
Add damageType, activationDuration and healthCost | package main
type targetType uint8
const (
_ targetType = iota
targetTypeOneself
targetTypeFriend
targetTypeAllFriends
targetTypeEnemy
targetTypeAllEnemies
)
type damageType uint8
const (
_ damageType = iota
damageTypePhysical
damageTypeMagic
damageTypeTrue
)
type ability struct {
name string
targetType targetType
damageType damageType
healthCost statistic
manaCost statistic
activationDuration gameDuration
cooldownDuration gameDuration
disableTypes []disableType
perform func(performer, receiver *unit)
}
// satisfiedRequirements returns true iff the ability satisfy activation requirements
func (a *ability) satisfiedRequirements(performer *unit) bool {
if performer.health() < a.healthCost {
return false
}
if performer.mana() < a.manaCost {
return false
}
for o := range performer.operators {
switch o := o.(type) {
case *cooldown:
if a == o.ability {
return false
}
case *disable:
for d := range a.disableTypes {
if disableType(d) == o.disableType {
return false
}
}
}
}
return true
}
| package main
type targetType uint8
const (
_ targetType = iota
targetTypeOneself
targetTypeFriend
targetTypeAllFriends
targetTypeEnemy
targetTypeAllEnemies
)
type ability struct {
targetType
manaCost statistic
cooldown gameDuration
disableTypes []disableType
perform func(performer, receiver *unit)
}
// satisfiedRequirements returns true iff the ability satisfy activation requirements
func (a *ability) satisfiedRequirements(performer *unit) bool {
if performer.mana() < a.manaCost {
return false
}
for o := range performer.operators {
switch o := o.(type) {
case *cooldown:
if a == o.ability {
return false
}
case *disable:
for d := range a.disableTypes {
if disableType(d) == o.disableType {
return false
}
}
}
}
return true
}
|
Build tweak to launch chrome for tests | module.exports = function (config) {
const cfg = {
basePath: '',
frameworks: ['jasmine'],
files: [
{ pattern: './main.js', watched: false }
],
exclude: [
],
preprocessors: {
'./main.js': ['webpack', 'sourcemap']
},
webpack: require('./webpack-spec.config')({ env: 'test' }),
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
singleRun: true,
concurrency: Infinity
};
if (process.env.TRAVIS) {
cfg.browsers = ['Chrome_travis_ci'];
}
config.set(cfg);
}
| module.exports = function (config) {
const cfg = {
basePath: '',
frameworks: ['jasmine'],
files: [
{ pattern: './main.js', watched: false }
],
exclude: [
],
preprocessors: {
'./main.js': ['webpack', 'sourcemap']
},
webpack: require('./webpack-spec.config')({ env: 'test' }),
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
customLaunchers: {
ChromeTravisCi: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
singleRun: true,
concurrency: Infinity
};
if (process.env.TRAVIS) {
cfg.browsers = ['Chrome_travis_ci'];
}
config.set(cfg);
}
|
Fix issue with empty object
throwing error | <?php namespace PHRETS\Parsers\GetMetadata;
use GuzzleHttp\Message\ResponseInterface;
use Illuminate\Support\Collection;
use PHRETS\Session;
class Object extends Base
{
public function parse(Session $rets, ResponseInterface $response)
{
$xml = $response->xml();
$collection = new Collection;
if ($xml->METADATA and $xml->METADATA->{'METADATA-OBJECT'}->Object) {
foreach ($xml->METADATA->{'METADATA-OBJECT'}->Object as $key => $value) {
$metadata = new \PHRETS\Models\Metadata\Object;
$metadata->setSession($rets);
$obj = $this->loadFromXml($metadata, $value, $xml->METADATA->{'METADATA-OBJECT'});
$collection->put($obj->getObjectType(), $obj);
}
}
return $collection;
}
}
| <?php namespace PHRETS\Parsers\GetMetadata;
use GuzzleHttp\Message\ResponseInterface;
use Illuminate\Support\Collection;
use PHRETS\Session;
class Object extends Base
{
public function parse(Session $rets, ResponseInterface $response)
{
$xml = $response->xml();
$collection = new Collection;
if ($xml->METADATA) {
foreach ($xml->METADATA->{'METADATA-OBJECT'}->Object as $key => $value) {
$metadata = new \PHRETS\Models\Metadata\Object;
$metadata->setSession($rets);
$obj = $this->loadFromXml($metadata, $value, $xml->METADATA->{'METADATA-OBJECT'});
$collection->put($obj->getObjectType(), $obj);
}
}
return $collection;
}
}
|
Check if student can choose a project before allowing them to join it | from aiohttp import web
from db_helper import get_project_id, get_user_id, can_choose_project
from permissions import view_only, value_set
@view_only("join_projects")
@value_set("student_choosable")
async def on_submit(request):
session = request.app["session"]
cookies = request.cookies
post = await request.post()
option = int(post["order"]) - 1
attrs = ["first_option_id", "second_option_id", "third_option_id"]
project = get_project_id(session, int(post["choice"]))
if not can_choose_project(session, cookies, project):
return web.Response(status=403, text="You cannot choose this project")
user = get_user_id(session, cookies)
setattr(user, attrs[option], project.id)
for attr in set(attrs) - {attrs[option]}:
if getattr(user, attr) == project.id:
setattr(user, attr, None)
session.commit()
return web.Response(status=200, text="set")
| from aiohttp import web
from db_helper import get_project_id, get_most_recent_group, get_user_id
from permissions import view_only, value_set
@view_only("join_projects")
@value_set("student_choosable")
async def on_submit(request):
session = request.app["session"]
cookies = request.cookies
post = await request.post()
option = int(post["order"]) - 1
attrs = ["first_option_id", "second_option_id", "third_option_id"]
project = get_project_id(session, int(post["choice"]))
if project.group is not get_most_recent_group(session):
return web.Response(status=403, text="Cannot join legacy projects")
user = get_user_id(session, cookies)
setattr(user, attrs[option], project.id)
for attr in set(attrs) - {attrs[option]}:
if getattr(user, attr) == project.id:
setattr(user, attr, None)
session.commit()
return web.Response(status=200, text="set")
|
Sort the final table by keplerid | """Creates an SQLite database detailing all the K2 target pixel files.
TODO
----
* Add an index to the sqlite table?
"""
import glob
import logging
import sqlite3
import pandas as pd
log = logging.getLogger(__name__)
log.setLevel("INFO")
CSV_FILENAME = "../k2-target-pixel-files.csv"
SQLITE_FILENAME = "../k2-target-pixel-files.db"
if __name__ == "__main__":
log.info("Reading the data")
df = pd.concat([pd.read_csv(fn)
for fn
in glob.glob("intermediate-data/*metadata.csv")])
df = df.sort_values("keplerid")
# Write to the CSV file
log.info("Writing {}".format(CSV_FILENAME))
df.to_csv(CSV_FILENAME, index=False)
# Write the SQLite table
log.info("Writing {}".format(SQLITE_FILENAME))
con = sqlite3.connect(SQLITE_FILENAME)
df.to_sql(name='tpf', con=con, if_exists='replace', index=False)
| """Creates an SQLite database detailing all the K2 target pixel files.
TODO
----
* Sort the final table by EPIC ID.
* Add an index to the sqlite table?
"""
import glob
import logging
import sqlite3
import pandas as pd
log = logging.getLogger(__name__)
log.setLevel("INFO")
CSV_FILENAME = "../k2-target-pixel-files.csv"
SQLITE_FILENAME = "../k2-target-pixel-files.db"
if __name__ == "__main__":
log.info("Reading the data")
df = pd.concat([pd.read_csv(fn)
for fn
in glob.glob("intermediate-data/*metadata.csv")])
# Write to the CSV file
log.info("Writing {}".format(CSV_FILENAME))
df.to_csv(CSV_FILENAME, index=False)
# Write the SQLite table
log.info("Writing {}".format(SQLITE_FILENAME))
con = sqlite3.connect(SQLITE_FILENAME)
df.to_sql(name='tpf', con=con, if_exists='replace', index=False)
|
Use propTypes from external package in anchor-plugin | import React from 'react';
import PropTypes from 'prop-types';
const propTypes = {
className: PropTypes.string,
children: PropTypes.node.isRequired,
entityKey: PropTypes.string,
getEditorState: PropTypes.func.isRequired
};
const Link = ({
children,
className,
entityKey,
getEditorState,
target
}) => {
const entity = getEditorState().getCurrentContent().getEntity(entityKey);
const entityData = entity ? entity.get('data') : undefined;
const href = (entityData && entityData.url) || undefined;
return (
<a
className={className}
title={href}
href={href}
target={target}
rel="noopener noreferrer"
>
{children}
</a>
);
};
Link.propTypes = propTypes;
export default Link;
| import React, { PropTypes } from 'react';
const propTypes = {
className: PropTypes.string,
children: PropTypes.node.isRequired,
entityKey: PropTypes.string,
getEditorState: PropTypes.func.isRequired
};
const Link = ({
children,
className,
entityKey,
getEditorState,
target
}) => {
const entity = getEditorState().getCurrentContent().getEntity(entityKey);
const entityData = entity ? entity.get('data') : undefined;
const href = (entityData && entityData.url) || undefined;
return (
<a
className={className}
title={href}
href={href}
target={target}
rel="noopener noreferrer"
>
{children}
</a>
);
};
Link.propTypes = propTypes;
export default Link;
|
Change env variable for PORT. | const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const yamlConfig = require('node-yaml-config');
/*
* Create the app, database and tables if required
*/
const app = express();
const db = new sqlite3.Database('canaritus.db');
db.run('CREATE TABLE IF NOT EXISTS ids (id TEXT, UNIQUE(id))');
db.run('CREATE TABLE IF NOT EXISTS events (title TEXT, body TEXT, time DATETIME)');
/*
* Application constants
*/
const PORT = process.env.PORT || 3000;
const SERVER_KEY = process.env.SERVER_KEY;
const GCM_ENDPOINT = 'https://android.googleapis.com/gcm/send';
const HOST_YAML = process.env.HOST_YAML || 'hosts.yaml';
/*
* Configure express app
*/
app.use(bodyParser.json());
app.use(express.static(__dirname + '/../../dist'));
/*
* Set up the utils
*/
const utils = require('./utils')(db, GCM_ENDPOINT, SERVER_KEY);
/*
* Set up the routes
*/
require('./routes/main')(app, db, utils.addEvent, utils.log);
/*
* Set up the periodic tasks
*/
const config = yamlConfig.load(__dirname + '/../../' + HOST_YAML);
require('./tasks')(config, utils, db);
/*
* Start server
*/
app.listen(PORT);
utils.log('SERVER', `Listening on port ${PORT}`);
| const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const yamlConfig = require('node-yaml-config');
/*
* Create the app, database and tables if required
*/
const app = express();
const db = new sqlite3.Database('canaritus.db');
db.run('CREATE TABLE IF NOT EXISTS ids (id TEXT, UNIQUE(id))');
db.run('CREATE TABLE IF NOT EXISTS events (title TEXT, body TEXT, time DATETIME)');
/*
* Application constants
*/
const PORT = process.env.SERVER_KEY || 3000;
const SERVER_KEY = process.env.SERVER_KEY;
const GCM_ENDPOINT = 'https://android.googleapis.com/gcm/send';
const HOST_YAML = process.env.HOST_YAML || 'hosts.yaml';
/*
* Configure express app
*/
app.use(bodyParser.json());
app.use(express.static(__dirname + '/../../dist'));
/*
* Set up the utils
*/
const utils = require('./utils')(db, GCM_ENDPOINT, SERVER_KEY);
/*
* Set up the routes
*/
require('./routes/main')(app, db, utils.addEvent, utils.log);
/*
* Set up the periodic tasks
*/
const config = yamlConfig.load(__dirname + '/../../' + HOST_YAML);
require('./tasks')(config, utils, db);
/*
* Start server
*/
app.listen(PORT);
utils.log('SERVER', `Listening on port ${PORT}`);
|
Create variables for HTML start and end. | import sublime, sublime_plugin
import os
import re
from .mistune import markdown
HTML_START = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>'
HTML_END = '</body></html>'
class CreateMinuteCommand(sublime_plugin.TextCommand):
def run(self, edit):
region = sublime.Region(0, self.view.size())
md_source = self.view.substr(region)
md_source.encode(encoding='UTF-8',errors='strict')
html_source = HTML_START + markdown(md_source) + HTML_END
file_name = self.view.file_name()
html_file = self.change_extension(file_name, ".html")
with open(html_file, 'w+') as file_:
file_.write(html_source)
print(file_name)
print(html_file)
def change_extension(self,file_name, new_ext):
f, ext = os.path.splitext(file_name)
f += new_ext
return f
| import sublime, sublime_plugin
import os
import re
from .mistune import markdown
class CreateMinuteCommand(sublime_plugin.TextCommand):
def run(self, edit):
region = sublime.Region(0, self.view.size())
md_source = self.view.substr(region)
md_source.encode(encoding='UTF-8',errors='strict')
html_source = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>' + markdown(md_source) + '</body></html>'
file_name = self.view.file_name()
html_file = self.change_extension(file_name, ".html")
with open(html_file, 'w+') as file_:
file_.write(html_source)
print(file_name)
print(html_file)
def change_extension(self,file_name, new_ext):
f, ext = os.path.splitext(file_name)
f += new_ext
return f
|
Fix `render is undefined` in EmailParliament | import React, { useState } from 'react';
import { render } from 'react-dom';
import classnames from 'classnames';
import { search } from './api';
import SearchByPostcode from './SearchByPostcode';
import EmailComposer from './EmailComposer';
import ComponentWrapper from '../../components/ComponentWrapper';
import { redirect } from '../../util/redirector';
export const init = options => {
if (!options.config || !options.config.active) return;
if (options.el) {
render(
<EmailParliament config={options.config} onSend={options.onSend} />,
options.el
);
}
};
const EmailParliament = props => {
const [target, setTarget] = useState(null);
const searchClassname = classnames({
'hidden-irrelevant': target !== null,
});
return (
<div className="EmailParliament">
<ComponentWrapper locale={props.config.locale}>
<SearchByPostcode className={searchClassname} onChange={setTarget} />
<EmailComposer
title={props.config.title}
postcode={''}
target={target}
subject={props.config.subject}
template={props.config.template}
onSend={props.onSend || redirect}
/>
</ComponentWrapper>
</div>
);
};
export default EmailParliament;
| import React, { useState } from 'react';
import classnames from 'classnames';
import { search } from './api';
import SearchByPostcode from './SearchByPostcode';
import EmailComposer from './EmailComposer';
import ComponentWrapper from '../../components/ComponentWrapper';
import { redirect } from '../../util/redirector';
export const init = options => {
if (!options.config || !options.config.active) return;
if (options.el) {
render(
<EmailParliament config={options.config} onSend={options.onSend} />,
options.el
);
}
};
const EmailParliament = props => {
const [target, setTarget] = useState(null);
const searchClassname = classnames({
'hidden-irrelevant': target !== null,
});
return (
<div className="EmailParliament">
<ComponentWrapper locale={props.config.locale}>
<SearchByPostcode className={searchClassname} onChange={setTarget} />
<EmailComposer
title={props.config.title}
postcode={''}
target={target}
subject={props.config.subject}
template={props.config.template}
onSend={props.onSend || redirect}
/>
</ComponentWrapper>
</div>
);
};
export default EmailParliament;
|
Make sourcemaps from grunt build | module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.initConfig({
concat: {
'build/pointerevents.css': 'src/*.css',
},
uglify: {
pointerevents: {
options: {
sourceMap: 'build/pointerevents.js.map',
sourceMappingURL: 'pointerevents.js.map',
sourceMapRoot: '..'
},
dest: 'build/pointerevents.js',
src: [
'src/PointerEvent.js',
'src/pointermap.js',
'src/sidetable.js',
'src/dispatcher.js',
'src/installer.js',
'src/findTarget.js',
'src/platform-events.js',
'src/capture.js',
]
}
},
});
grunt.registerTask('default', ['concat', 'uglify']);
};
| module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.initConfig({
concat: {
'build/pointerevents.css': 'src/*.css',
},
uglify: {
pointerevents: {
dest: 'build/pointerevents.js',
src: [
'src/PointerEvent.js',
'src/pointermap.js',
'src/sidetable.js',
'src/dispatcher.js',
'src/installer.js',
'src/findTarget.js',
'src/platform-events.js',
'src/capture.js',
]
}
},
});
grunt.registerTask('default', ['concat', 'uglify']);
};
|
Add Imported field to GKE upstream spec builder
Without this patch, if a GKE cluster is imported to Rancher, and then a
change from GKE is synced back to the cluster in Rancher, "imported"
will flip back to false, and the guard in gke-operator that prevents
sending a DELETE request to imported clusters that are removed from
Rancher gets thwarted. This change fixes the upstream spec builder
function in the cluster refresher to always use the config spec value
for the Imported attribute.
(cherry picked from commit 9373c67723ab66ab43f9f3874044c33806e5a944) | package clusterupstreamrefresher
import (
"context"
gkecontroller "github.com/rancher/gke-operator/controller"
gkev1 "github.com/rancher/gke-operator/pkg/apis/gke.cattle.io/v1"
mgmtv3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
wranglerv1 "github.com/rancher/wrangler/pkg/generated/controllers/core/v1"
)
func BuildGKEUpstreamSpec(secretsCache wranglerv1.SecretCache, cluster *mgmtv3.Cluster) (*gkev1.GKEClusterConfigSpec, error) {
ctx := context.Background()
upstreamCluster, err := gkecontroller.GetCluster(ctx, secretsCache, cluster.Spec.GKEConfig)
if err != nil {
return nil, err
}
upstreamSpec, err := gkecontroller.BuildUpstreamClusterState(upstreamCluster)
if err != nil {
return nil, err
}
upstreamSpec.ClusterName = cluster.Spec.GKEConfig.ClusterName
upstreamSpec.Region = cluster.Spec.GKEConfig.Region
upstreamSpec.Zone = cluster.Spec.GKEConfig.Zone
upstreamSpec.GoogleCredentialSecret = cluster.Spec.GKEConfig.GoogleCredentialSecret
upstreamSpec.ProjectID = cluster.Spec.GKEConfig.ProjectID
upstreamSpec.Imported = cluster.Spec.GKEConfig.Imported
return upstreamSpec, nil
}
| package clusterupstreamrefresher
import (
"context"
gkecontroller "github.com/rancher/gke-operator/controller"
gkev1 "github.com/rancher/gke-operator/pkg/apis/gke.cattle.io/v1"
mgmtv3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
wranglerv1 "github.com/rancher/wrangler/pkg/generated/controllers/core/v1"
)
func BuildGKEUpstreamSpec(secretsCache wranglerv1.SecretCache, cluster *mgmtv3.Cluster) (*gkev1.GKEClusterConfigSpec, error) {
ctx := context.Background()
upstreamCluster, err := gkecontroller.GetCluster(ctx, secretsCache, cluster.Spec.GKEConfig)
if err != nil {
return nil, err
}
upstreamSpec, err := gkecontroller.BuildUpstreamClusterState(upstreamCluster)
if err != nil {
return nil, err
}
upstreamSpec.ClusterName = cluster.Spec.GKEConfig.ClusterName
upstreamSpec.Region = cluster.Spec.GKEConfig.Region
upstreamSpec.Zone = cluster.Spec.GKEConfig.Zone
upstreamSpec.GoogleCredentialSecret = cluster.Spec.GKEConfig.GoogleCredentialSecret
upstreamSpec.ProjectID = cluster.Spec.GKEConfig.ProjectID
return upstreamSpec, nil
}
|
Add a test for listMembers | <?php
require_once('tests/php/base.php');
class CashSeedTests extends UnitTestCase {
function testS3Seed(){
$settings = new S3Seed(1,1);
$this->assertIsa($settings, 'S3Seed');
}
function testTwitterSeed(){
$user_id = 1;
$settings_id = 1;
$twitter = new TwitterSeed($user_id,$settings_id);
$this->assertIsa($twitter, 'TwitterSeed');
}
function testMailchimpSeed(){
if(array_key_exists('MAILCHIMP_API_KEY', $_ENV)) {
$key = $_ENV['MAILCHIMP_API_KEY'];
$mc = new MailchimpSeed($key);
$this->assertIsa($mc, 'MailchimpSeed');
$this->assertTrue($mc->url);
$this->assertTrue($mc->lists());
$this->assertTrue($mc->listWebhooks(42));
$this->assertTrue($mc->listWebhooks(42));
$this->assertTrue($mc->listMembers(1));
} else {
fwrite(STDERR,"Mailchimp api key not found, skipping mailchimp tests\n");
return;
}
}
}
?>
| <?php
require_once('tests/php/base.php');
class CashSeedTests extends UnitTestCase {
function testS3Seed(){
$settings = new S3Seed(1,1);
$this->assertIsa($settings, 'S3Seed');
}
function testTwitterSeed(){
$user_id = 1;
$settings_id = 1;
$twitter = new TwitterSeed($user_id,$settings_id);
$this->assertIsa($twitter, 'TwitterSeed');
}
function testMailchimpSeed(){
if(array_key_exists('MAILCHIMP_API_KEY', $_ENV)) {
$key = $_ENV['MAILCHIMP_API_KEY'];
$settings = new MailchimpSeed($key);
$this->assertIsa($settings, 'MailchimpSeed');
$this->assertTrue($settings->url);
$this->assertTrue($settings->lists());
$this->assertTrue($settings->listWebhooks(42));
} else {
fwrite(STDERR,"Mailchimp api key not found, skipping mailchimp tests\n");
return;
}
}
}
?>
|
Simplify py 2/3 unicode string helper | import datetime
import os
import sys
import time
from dear_astrid.constants import *
from dear_astrid.constants import __all__ as _constants_all
from dear_astrid.tzinfo import *
from dear_astrid.tzinfo import __all__ as _tzinfo_all
__all__ = [
'dtu',
'u',
'timezone',
] + _constants_all + _tzinfo_all
def dtu(*args):
args = list(args)
while len(args) < 7:
args.append(0)
return datetime.datetime(*(args + [UTC()]))
class timezone(object):
def __init__(self, tz=None):
self.tz = tz
self.orig = None
def set_env(self, tz):
if tz is None:
if 'TZ' in os.environ:
del os.environ['TZ']
else:
os.environ['TZ'] = tz
time.tzset()
def __enter__(self):
self.orig = os.environ.get('TZ', None)
self.set_env(self.tz)
def __exit__(self, *args):
self.set_env(self.orig)
PY3 = sys.version_info >= (3,)
def u(string):
if not PY3:
string = string.decode('utf-8')
return string
| import datetime
import os
import sys
import time
from dear_astrid.constants import *
from dear_astrid.constants import __all__ as _constants_all
from dear_astrid.tzinfo import *
from dear_astrid.tzinfo import __all__ as _tzinfo_all
__all__ = [
'dtu',
'u',
'timezone',
] + _constants_all + _tzinfo_all
def dtu(*args):
args = list(args)
while len(args) < 7:
args.append(0)
return datetime.datetime(*(args + [UTC()]))
class timezone(object):
def __init__(self, tz=None):
self.tz = tz
self.orig = None
def set_env(self, tz):
if tz is None:
if 'TZ' in os.environ:
del os.environ['TZ']
else:
os.environ['TZ'] = tz
time.tzset()
def __enter__(self):
self.orig = os.environ.get('TZ', None)
self.set_env(self.tz)
def __exit__(self, *args):
self.set_env(self.orig)
PY3 = False
try:
PY3 = (sys.version_info.major == 3)
except:
pass
if PY3:
def u(string):
return string
else:
exec("def u(string):\n return string + u''\n")
|
Remove tearDown not used method | from mockito import *
import unittest
from source.server import *
from source.exception import *
from source.commands.system import *
class ServerTestCase(unittest.TestCase):
def createCommandResponse(self, command, parameters = {}, timeout = None):
response = mock()
response.status_code = 200
json = { 'command': command, 'parameters': parameters }
if timeout is not None:
json['timeout'] = timeout
when(response).json().thenReturn({ 'command': command, 'timeout': timeout, 'parameters': parameters })
return response
def setResponse(self, response):
when(self.server._requests).get('').thenReturn(response)
def setUp(self):
self.server = Server('')
self.server._requests = mock()
def testGet(self):
self.setResponse(self.createCommandResponse('copy', parameters = {'src': 'source', 'dst': 'destination' }, timeout = 10))
response = self.server.get()
self.assertIsInstance(response, Copy)
self.assertEqual(response.parameters, {'src': 'source', 'dst': 'destination', })
self.assertIs(response.timeout, 10)
def testGetCommandNotFound(self):
self.setResponse(self.createCommandResponse('Not found command'))
self.assertRaises(CommandNotFoundException, self.server.get) | from mockito import *
import unittest
from source.server import *
from source.exception import *
from source.commands.system import *
class ServerTestCase(unittest.TestCase):
def createCommandResponse(self, command, parameters = {}, timeout = None):
response = mock()
response.status_code = 200
json = { 'command': command, 'parameters': parameters }
if timeout is not None:
json['timeout'] = timeout
when(response).json().thenReturn({ 'command': command, 'timeout': timeout, 'parameters': parameters })
return response
def setResponse(self, response):
when(self.server._requests).get('').thenReturn(response)
def setUp(self):
self.server = Server('')
self.server._requests = mock()
def tearDown(self):
pass
def testGet(self):
self.setResponse(self.createCommandResponse('copy', parameters = {'src': 'source', 'dst': 'destination' }, timeout = 10))
response = self.server.get()
self.assertIsInstance(response, Copy)
self.assertEqual(response.parameters, {'src': 'source', 'dst': 'destination', })
self.assertIs(response.timeout, 10)
def testGetCommandNotFound(self):
self.setResponse(self.createCommandResponse('Not found command'))
self.assertRaises(CommandNotFoundException, self.server.get) |
Fix for new entity repository implementation | <?php
namespace Plinth\Entity;
use Plinth\Connector;
use Plinth\Exception\PlinthException;
class EntityRepository extends Connector
{
/**
* @var EntityRepository[]
*/
private $repositories;
/**
* @param $fqcn
* @return EntityRepository
* @throws PlinthException
*/
public function getRepository($fqcn)
{
$fqcnLegacy = $fqcn . 'Repository';
if (class_exists($fqcnLegacy)) {
$fqcn = $fqcnLegacy;
} elseif (!class_exists($fqcn)) {
throw new PlinthException("Your repository, $fqcn, cannot be found.");
}
if (!in_array(self::class, class_parents($fqcn))) {
throw new PlinthException("Your repository, $fqcn, must extend " . self::class . ".");
}
if (!isset($this->repositories[$fqcn])) {
$this->repositories[$fqcn] = new $fqcn($this->main);
}
return $this->repositories[$fqcn];
}
} | <?php
namespace Plinth\Entity;
use Plinth\Connector;
use Plinth\Exception\PlinthException;
class EntityRepository extends Connector
{
/**
* @var EntityRepository[]
*/
private $repositories;
/**
* @param $fqcn
* @return EntityRepository
* @throws PlinthException
*/
public function getRepository($fqcn)
{
if (!in_array(self::class, class_parents($fqcn))) {
$fqcn .= 'Repository'; // Legacy check
if (!in_array(self::class, class_parents($fqcn))) {
throw new PlinthException("Your repository, $fqcn, must extend " . self::class);
}
}
if (!isset($this->repositories[$fqcn])) {
$this->repositories[$fqcn] = new $fqcn($this->main);
}
return $this->repositories[$fqcn];
}
} |
Add support for environmental services configuration and support only yml | <?php
namespace Knp\RadBundle\AppBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
class ContainerExtension extends Extension
{
private $path;
public function __construct($path)
{
$this->path = $path;
}
public function getAlias()
{
return 'app';
}
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$environment = $container->getParameter('kernel.environment');
$loader = new Loader\YamlFileLoader(
$container, new FileLocator($this->path.'/Resources/config')
);
if (file_exists($this->path.'/Resources/config/services.yml')) {
$loader->load('services.yml');
}
if (file_exists($this->path.'/Resources/config/services_'.$environment.'.yml')) {
$loader->load('services_'.$environment.'.yml');
}
}
}
| <?php
namespace Knp\RadBundle\AppBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
class ContainerExtension extends Extension
{
private $path;
public function __construct($path)
{
$this->path = $path;
}
public function getAlias()
{
return 'app';
}
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
if (file_exists($this->path.'/Resources/config/services.yml')) {
$loader = new Loader\YamlFileLoader(
$container, new FileLocator($this->path.'/Resources/config')
);
$loader->load('services.yml');
}
if (file_exists($this->path.'/Resources/config/services.xml')) {
$loader = new Loader\XmlFileLoader(
$container, new FileLocator($this->path.'/Resources/config')
);
$loader->load('services.xml');
}
}
}
|
Set default roles only if user has no roles | /**
* Sets the default permissions to new users
*/
Meteor.users.after.insert(function (userId, doc) {
var userId = doc._id;
if (orion.adminExists) {
// if there is a admin created we will set the default roles.
if (Roles._collection.find({ userId: userId }).count() == 0) {
var defaultRoles = Options.get('defaultRoles');
Roles.addUserToRoles(userId, defaultRoles);
}
} else {
// If there is no admin, we will add the admin role to this new user.
Roles.addUserToRoles(userId, 'admin');
// Pass to the client if the admin exists
orion.adminExists = true;
Inject.obj('adminExists', { exists: true });
}
});
/**
* Pass to the client if there is a admin account
*/
orion.adminExists = Roles._collection.find({ roles: 'admin' }).count() != 0;
Inject.obj('adminExists', { exists: orion.adminExists });
| /**
* Sets the default permissions to new users
*/
Meteor.users.after.insert(function (userId, doc) {
var userId = doc._id;
if (orion.adminExists) {
// if there is a admin created we will set the default roles.
var defaultRoles = Options.get('defaultRoles');
Roles.addUserToRoles(userId, defaultRoles);
} else {
// If there is no admin, we will add the admin role to this new user.
Roles.addUserToRoles(userId, 'admin');
// Pass to the client if the admin exists
orion.adminExists = true;
Inject.obj('adminExists', { exists: true });
}
});
/**
* Pass to the client if there is a admin account
*/
orion.adminExists = Roles._collection.find({ roles: 'admin' }).count() != 0;
Inject.obj('adminExists', { exists: orion.adminExists });
|
Format support time like `hh:mm`, HP-575 | <?php
/**
* Finance module for HiPanel
*
* @link https://github.com/hiqdev/hipanel-module-finance
* @package hipanel-module-finance
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
*/
namespace hipanel\modules\finance\logic\bill;
use Yii;
/**
* Class SupportTimeQuantity.
*
* @author Dmytro Naumenko <d.naumenko.a@gmail.com>
*/
class SupportTimeQuantity extends DefaultQuantityFormatter
{
public function format(): string
{
$qty = $this->getQuantity()->getQuantity();
return Yii::t('hipanel:finance', '{qty}', [
'qty' => sprintf('%02d:%02d', (int)$qty, fmod($qty, 1) * 60),
]);
}
}
| <?php
/**
* Finance module for HiPanel
*
* @link https://github.com/hiqdev/hipanel-module-finance
* @package hipanel-module-finance
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
*/
namespace hipanel\modules\finance\logic\bill;
use Yii;
/**
* Class SupportTimeQuantity.
*
* @author Dmytro Naumenko <d.naumenko.a@gmail.com>
*/
class SupportTimeQuantity extends DefaultQuantityFormatter
{
public function format(): string
{
return Yii::t('hipanel:finance', '{quantity}', [
'quantity' => Yii::$app->formatter->asDuration(ceil($this->getQuantity()->getQuantity() * 3600))
]);
}
}
|
Add more test on retrieving CompilationUnit from relative path
test real src directory | import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import java.io.File;
/**
* Some hack before a proper unit test harness is put in place
*
* @author Emmanuel Bernard <emmanuel@hibernate.org>
*/
public class MainForTest {
/**
* Files that are not under a proper module structure are placed under a <nomodule> module.
*/
public static void main(String[] args) throws Exception {
final TypeChecker typeChecker = new TypeCheckerBuilder()
.verbose(false)
.addSrcDirectory( new File("test") )
.getTypeChecker();
Tree.CompilationUnit compilationUnit = typeChecker.getCompilationUnitFromRelativePath("ceylon/language/BaseObject.ceylon");
if ( compilationUnit == null ) {
throw new RuntimeException("Failed to pass getCompilationUnitFromRelativePath for files in .src");
}
compilationUnit = typeChecker.getCompilationUnitFromRelativePath("capture/Capture.ceylon");
if ( compilationUnit == null ) {
throw new RuntimeException("Failed to pass getCompilationUnitFromRelativePath for files in real src dir");
}
}
}
| import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import java.io.File;
/**
* Some hack before a proper unit test harness is put in place
*
* @author Emmanuel Bernard <emmanuel@hibernate.org>
*/
public class MainForTest {
/**
* Files that are not under a proper module structure are placed under a <nomodule> module.
*/
public static void main(String[] args) throws Exception {
final TypeChecker typeChecker = new TypeCheckerBuilder()
.verbose(false)
.addSrcDirectory( new File("test") )
.getTypeChecker();
final Tree.CompilationUnit compilationUnit = typeChecker.getCompilationUnitFromRelativePath("ceylon/language/BaseObject.ceylon");
if ( compilationUnit == null ) {
throw new RuntimeException("Failed to pass getCompilationUnitFromRelativePath");
}
}
}
|
Read the correct amount of bytes to also support MKV
Fixes #1 | #!/usr/bin/env node
'use strict';
const readChunk = require('read-chunk');
const meow = require('meow');
const fileType = require('file-type');
const cli = meow(`
Usage
$ file-type <filename>
$ file-type < <filename>
Example
$ file-type unicorn.png
png
image/png
`);
function init(data) {
const type = fileType(data);
if (!type) {
console.error('Unrecognized file type');
process.exit(65);
}
console.log(`${type.ext}\n${type.mime}`);
}
const input = cli.input[0];
if (!input && process.stdin.isTTY) {
console.error('Specify a filename');
process.exit(1);
}
if (input) {
init(readChunk.sync(cli.input[0], 0, 4100));
} else {
process.stdin.once('data', init);
}
| #!/usr/bin/env node
'use strict';
const readChunk = require('read-chunk');
const meow = require('meow');
const fileType = require('file-type');
const cli = meow(`
Usage
$ file-type <filename>
$ file-type < <filename>
Example
$ file-type unicorn.png
png
image/png
`);
function init(data) {
const type = fileType(data);
if (!type) {
console.error('Unrecognized file type');
process.exit(65);
}
console.log(`${type.ext}\n${type.mime}`);
}
const input = cli.input[0];
if (!input && process.stdin.isTTY) {
console.error('Specify a filename');
process.exit(1);
}
if (input) {
init(readChunk.sync(cli.input[0], 0, 262));
} else {
process.stdin.once('data', init);
}
|
Join user table to select speaker name | var mysql = require('./mysql');
exports.getSessions = function(dbPool, callback) {
dbPool.query("SELECT session.*, CONCAT(user.firstname, ' ', user.name) AS speaker_name FROM session LEFT JOIN user ON user.id = session.speaker_id", function(err, result) {
callback(err, result);
});
}
exports.createSession = function (sessionModel, dbPool, callback) {
dbPool.query(
"INSERT INTO session (title, description, date, speaker_id, start_time, session_type_id, session_state_id, created_at, modified_at) VALUES (:title, :description, :date, :speaker_id, :start_time, :session_type_id, :session_state_id, :created_at, :modified_at)",
sessionModel
, function(err, result) {
callback(err, result.insertId);
});
}
exports.createSessionFile = function (sessionFileModel, dbPool, callback) {
dbPool.query(
"INSERT INTO session_file (session_id, file_id, type) VALUES (:session_id, :file_id, :type)",
sessionFileModel,
function(err, result){
callback(err);
});
}
exports.searchSessionId = function (name, dbPool, callback) {
var gotId = name;
if (isNaN(gotId) == true) {
callback(gotId);
return;
}
dbPool.query(
"SELECT * FROM session WHERE id= :name;",
{ name: gotId }
, function(err, rows) {
callback(err, rows);
});
} | var mysql = require('./mysql');
exports.getSessions = function(dbPool, callback) {
dbPool.query("SELECT * FROM session", function(err, result) {
callback(err, result);
});
}
exports.createSession = function (sessionModel, dbPool, callback) {
dbPool.query(
"INSERT INTO session (title, description, date, speaker_id, start_time, session_type_id, session_state_id, created_at, modified_at) VALUES (:title, :description, :date, :speaker_id, :start_time, :session_type_id, :session_state_id, :created_at, :modified_at)",
sessionModel
, function(err, result) {
callback(err, result.insertId);
});
}
exports.createSessionFile = function (sessionFileModel, dbPool, callback) {
dbPool.query(
"INSERT INTO session_file (session_id, file_id, type) VALUES (:session_id, :file_id, :type)",
sessionFileModel,
function(err, result){
callback(err);
});
}
exports.searchSessionId = function (name, dbPool, callback) {
var gotId = name;
if (isNaN(gotId) == true) {
callback(gotId);
return;
}
dbPool.query(
"SELECT * FROM session WHERE id= :name;",
{ name: gotId }
, function(err, rows) {
callback(err, rows);
});
} |
Upgrade Lookup model to Expando and DNS result properties from integer to string. | from google.appengine.ext import db
TOP_LEVEL_DOMAINS = """
com net org biz info
ag am at
be by
ch ck
de
es eu
fm
in io is it
la li ly
me mobi ms
name
ru
se sh sy
tel th to travel tv
us
""".split()
# Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN.
class UpgradeStringProperty(db.IntegerProperty):
def validate(self, value):
return unicode(value) if value else u''
class Lookup(db.Expando):
"""
The datastore key name is the domain name, without top level.
IP address fields use 0 (zero) for NXDOMAIN because None is
returned for missing properties.
Some updates on 2010-01-01 use negative numbers for 60 bit hashes of
the SOA server name.
Since 2010-01-02, this model inherits from Expando to flexibly add
more top level domains. Each property stores the authority name
server as string backwards, e.g. com.1and1.ns1 for better sorting.
"""
backwards = db.StringProperty(required=True) # For suffix matching.
timestamp = db.DateTimeProperty(required=True) # Created or updated.
com = UpgradeStringProperty()
net = UpgradeStringProperty()
org = UpgradeStringProperty()
biz = UpgradeStringProperty()
info = UpgradeStringProperty()
| from google.appengine.ext import db
TOP_LEVEL_DOMAINS = 'com net org biz info'.split()
class Lookup(db.Model):
"""
The datastore key name is the domain name, without top level.
IP address fields use 0 (zero) for NXDOMAIN because None is
returned for missing properties.
Updates since 2010-01-01 use negative numbers for 60 bit hashes of
the SOA server name, see tools/update_dns.py.
"""
backwards = db.StringProperty(required=True) # For suffix matching.
timestamp = db.DateTimeProperty(required=True) # Created or updated.
com = db.IntegerProperty(indexed=False)
net = db.IntegerProperty(indexed=False)
org = db.IntegerProperty(indexed=False)
biz = db.IntegerProperty(indexed=False)
info = db.IntegerProperty(indexed=False)
|
Restructure the valid_paths list into a dict. | """ fedmsg-notifications internal API """
import fmn.lib.models
import logging
log = logging.getLogger(__name__)
def recipients(session, config, message):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients.
"""
res = {}
for context in session.query(fmn.lib.models.Context).all():
res[context.name] = recipients_for_context(
session, config, context, message)
return res
def recipients_for_context(session, config, context, message):
""" Returns the recipients for a given fedmsg message and stated context.
Context may be either the name of a context or an instance of
fmn.lib.models.Context.
"""
if isinstance(context, basestring):
context = session.query(fmn.lib.models.Context)\
.filter_by(name=context).one()
return context.recipients(session, config, message)
def load_filters(root='fmn.filters'):
""" Load the big list of allowed callable filters. """
module = __import__(root, fromlist=[root.split('.')[0]])
filters = {}
for name in dir(module):
obj = getattr(module, name)
if not callable(obj):
continue
log.info("Found filter %r %r" % (name, obj))
filters[name] = obj
return {root: filters}
| """ fedmsg-notifications internal API """
import fmn.lib.models
import logging
log = logging.getLogger(__name__)
def recipients(session, config, message):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients.
"""
res = {}
for context in session.query(fmn.lib.models.Context).all():
res[context.name] = recipients_for_context(
session, config, context, message)
return res
def recipients_for_context(session, config, context, message):
""" Returns the recipients for a given fedmsg message and stated context.
Context may be either the name of a context or an instance of
fmn.lib.models.Context.
"""
if isinstance(context, basestring):
context = session.query(fmn.lib.models.Context)\
.filter_by(name=context).one()
return context.recipients(session, config, message)
def load_filters(root='fmn.filters'):
""" Load the big list of allowed callable filters. """
module = __import__(root, fromlist=[root.split('.')[0]])
filters = []
for name in dir(module):
obj = getattr(module, name)
if not callable(obj):
continue
log.info("Found filter %r %r" % (name, obj))
filters.append(obj)
return filters
|
Add other tournaments in navigation | 'use strict';
import React from 'react';
import {Link, IndexLink} from 'react-router';
import SearchInput from './SearchInput.react.js';
const Page = props => (
<div>
<div className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<IndexLink className="navbar-brand" to="/">
MTG Pro Tour Results
</IndexLink>
</div>
<ul className="nav navbar-nav">
<li>
<Link to="/rankings/t8" activeClassName="activeLink">
Player Rankings
</Link>
</li>
<li>
<Link to="/other-tournaments" activeClassName="activeLink">
Other Tournaments
</Link>
</li>
</ul>
<div className="navbar-form navbar-right">
<SearchInput />
</div>
</div>
</div>
{props.children}
</div>
);
export default Page;
| 'use strict';
import React from 'react';
import {Link, IndexLink} from 'react-router';
import SearchInput from './SearchInput.react.js';
const Page = props => (
<div>
<div className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<IndexLink className="navbar-brand" to="/">
MTG Pro Tour Results
</IndexLink>
</div>
<ul className="nav navbar-nav">
<li>
<Link to="/rankings/t8" activeClassName="activeLink">
Player Rankings
</Link>
</li>
</ul>
<div className="navbar-form navbar-right">
<SearchInput />
</div>
</div>
</div>
{props.children}
</div>
);
export default Page;
|
Tweak the call with parameters of the tests | import { setUpBrowserWindow } from '../../../src/set-up/browser-window';
import chai from 'chai';
import debug from 'debug';
import sinon from 'sinon';
import sinonAsPromised from 'sinon-as-promised';
chai.use(require('sinon-chai'));
const expect = chai.expect;
describe('Set up browser window', () => {
let sandbox;
let BrowserWindow;
beforeEach(() => {
sandbox = sinon.sandbox.create();
BrowserWindow = sandbox.stub().returns({
loadURL: sandbox.stub(),
openDevTools: sandbox.stub()
});
});
afterEach(() => {
sandbox.restore();
});
it('resolves the promise with a mainWindow object', (done) => {
setUpBrowserWindow(BrowserWindow).then((mainWindow) => {
expect(BrowserWindow).to.have.been.calledWith({
height: 600,
width: 800,
icon:'./assets/16x16.png'
});
expect(mainWindow.loadURL).to.have.been.calledWithMatch('/app/index.html');
expect(mainWindow.openDevTools).to.have.been.called;
done();
}).catch((error) => {
expect(error).to.be.undefined;
done();
});
});
});
| import { setUpBrowserWindow } from '../../../src/set-up/browser-window';
import chai from 'chai';
import debug from 'debug';
import sinon from 'sinon';
import sinonAsPromised from 'sinon-as-promised';
chai.use(require('sinon-chai'));
const expect = chai.expect;
describe('set up browser window', () => {
let sandbox;
let BrowserWindow;
beforeEach(() => {
sandbox = sinon.sandbox.create();
BrowserWindow = sandbox.stub().returns({
loadURL: sandbox.stub(),
openDevTools: sandbox.stub()
});
});
afterEach(() => {
sandbox.restore();
});
it('resolves the promise with a mainWindow object', (done) => {
setUpBrowserWindow(BrowserWindow).then((mainWindow) => {
expect(mainWindow.loadURL).to.have.been.called;
expect(mainWindow.openDevTools).to.have.been.called;
done();
}).catch((error) => {
expect(error).to.be.undefined;
done();
});
});
});
|
Update regex to match sentences starting with ÅÄÖ | import textract
import sys
import os
import re
import random
###################################
# Extracts text from a pdf file and
# selects one sentence, which it
# then prints.
#
# Created by Fredrik Omstedt.
###################################
# Extracts texts from pdf files. If given a directory, the
# program will return texts from all pdf files in that directory.
def extractTexts():
file = sys.argv[1]
texts = []
if os.path.isdir(file):
for f in os.listdir(file):
if re.match(r'^.*\.pdf$', f):
texts.append(textract.process(file + "/" + f))
else:
texts.append(textract.process(file))
return texts
# Chooses one sentence randomly from each of the given texts.
def selectSentences(texts):
chosen_sentences = []
for text in texts:
sentence_structure = re.compile(r'([A-Z\xc4\xc5\xd6][^\.!?]*[\.!?])', re.M)
sentences = sentence_structure.findall(text)
chosen_sentences.append(
sentences[random.randint(0, len(sentences)-1)].replace("\n", " ")
)
return chosen_sentences
def main():
texts = extractTexts()
sentences = selectSentences(texts)
for sentence in sentences:
print(sentence)
print("\n")
if __name__ == '__main__':
main()
| import textract
import sys
import os
import re
import random
###################################
# Extracts text from a pdf file and
# selects one sentence, which it
# then prints.
#
# Created by Fredrik Omstedt.
###################################
# Extracts texts from pdf files. If given a directory, the
# program will return texts from all pdf files in that directory.
def extractTexts():
file = sys.argv[1]
texts = []
if os.path.isdir(file):
for f in os.listdir(file):
if re.match(r'^.*\.pdf$', f):
texts.append(textract.process(file + "/" + f))
else:
texts.append(textract.process(file))
return texts
# Chooses one sentence randomly from each of the given texts.
def selectSentences(texts):
chosen_sentences = []
for text in texts:
sentence_structure = re.compile(r'([A-Z][^\.!?]*[\.!?])', re.M)
sentences = sentence_structure.findall(text)
chosen_sentences.append(
sentences[random.randint(0, len(sentences)-1)].replace("\n", " ")
)
return chosen_sentences
def main():
texts = extractTexts()
sentences = selectSentences(texts)
for sentence in sentences:
print(sentence)
print("\n")
if __name__ == '__main__':
main()
|
Revert "Updated middleware contract to force use of Request and Response contracts."
This reverts commit 47d2083f48b676d359c2b2eb3836b2ce2f85909d. | <?php
namespace Phapi\Contract\Middleware;
use Psr\Http\Message\ServerRequestInterface as RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Interface Middleware
*
* Middleware accepts a request and a response and optionally a callback
* ($next) that is called if the middleware allows further middleware to
* process the request.
*
* If a middleware doesn't need or desire to allow further processing it
* should not call the callback ($next) and should instead return a response.
*
* @category Phapi
* @package Phapi\Contract
* @author Peter Ahinko <peter@ahinko.se>
* @license MIT (http://opensource.org/licenses/MIT)
* @link https://github.com/phapi/contract
*/
interface Middleware {
/**
* Process an incoming request and/or response.
*
* Accepts a request and a response (PSR-7 compatible) instance and
* does something with them.
*
* The middleware must pass a request and a response to the ($next)
* callback and finally either return the response from the ($next)
* callback or by modifying the response before returning it.
*
* Examples:
* return $next();
*
* OR
*
* $response = $next();
* // Modify response
* ...
* return $response;
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param callable $next
* @return ResponseInterface
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next = null);
} | <?php
namespace Phapi\Contract\Middleware;
use Phapi\Contract\Http\Request;
use Phapi\Contract\Http\Response;
/**
* Interface Middleware
*
* Middleware accepts a request and a response and optionally a callback
* ($next) that is called if the middleware allows further middleware to
* process the request.
*
* If a middleware doesn't need or desire to allow further processing it
* should not call the callback ($next) and should instead return a response.
*
* @category Phapi
* @package Phapi\Contract
* @author Peter Ahinko <peter@ahinko.se>
* @license MIT (http://opensource.org/licenses/MIT)
* @link https://github.com/phapi/contract
*/
interface Middleware {
/**
* Process an incoming request and/or response.
*
* Accepts a request and a response (PSR-7 compatible) instance and
* does something with them.
*
* The middleware must pass a request and a response to the ($next)
* callback and finally either return the response from the ($next)
* callback or by modifying the response before returning it.
*
* Examples:
* return $next();
*
* OR
*
* $response = $next();
* // Modify response
* ...
* return $response;
*
* @param Request $request
* @param Response $response
* @param callable $next
* @return Request
*/
public function __invoke(Request $request, Response $response, callable $next = null);
} |
Handle empty or null authorization header prefix | <?php
namespace Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor;
use Symfony\Component\HttpFoundation\Request;
/**
* AuthorizationHeaderTokenExtractor.
*
* @author Nicolas Cabot <n.cabot@lexik.fr>
*/
class AuthorizationHeaderTokenExtractor implements TokenExtractorInterface
{
/**
* @var string
*/
protected $prefix;
/**
* @var string
*/
protected $name;
/**
* @param string|null $prefix
* @param string $name
*/
public function __construct($prefix, $name)
{
$this->prefix = $prefix;
$this->name = $name;
}
/**
* {@inheritdoc}
*/
public function extract(Request $request)
{
if (!$request->headers->has($this->name)) {
return false;
}
$authorizationHeader = $request->headers->get($this->name);
if (empty($this->prefix)) {
return $authorizationHeader;
}
$headerParts = explode(' ', $authorizationHeader);
if (!(count($headerParts) === 2 && $headerParts[0] === $this->prefix)) {
return false;
}
return $headerParts[1];
}
}
| <?php
namespace Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor;
use Symfony\Component\HttpFoundation\Request;
/**
* AuthorizationHeaderTokenExtractor.
*
* @author Nicolas Cabot <n.cabot@lexik.fr>
*/
class AuthorizationHeaderTokenExtractor implements TokenExtractorInterface
{
/**
* @var string
*/
protected $prefix;
/**
* @var string
*/
protected $name;
/**
* @param string $prefix
* @param string $name
*/
public function __construct($prefix, $name)
{
$this->prefix = $prefix;
$this->name = $name;
}
/**
* {@inheritdoc}
*/
public function extract(Request $request)
{
if (!$request->headers->has($this->name)) {
return false;
}
$headerParts = explode(' ', $request->headers->get($this->name));
if (!(count($headerParts) === 2 && $headerParts[0] === $this->prefix)) {
return false;
}
return $headerParts[1];
}
}
|
Test for getting container service ip. | "use strict";
const Environment = require('../environment/environment');
const Loader = require("../terminal-utils/async_loader");
module.exports = {
description : "Create new environment and install drupal in it.",
run : () => {
let loader;
Environment.create({projectName: "test"}, ['php', 'web', 'database']).then((env) => {
loader = new Loader("saving environment config");
return env.save("/home/zoltan.fodor/Documents/Drupal/test");
}).then((env) => {
loader.setMessage("generating docker env");
return env.write("docker", "/home/zoltan.fodor/Documents/Drupal/test");
}).then((docker) => {
loader.setMessage("starting docker");
return docker.getIp("nginx");
}).then((ip) => {
console.log(ip);
loader.finish("asd");
}).catch((err) => {
console.log(err);
console.error("Chain failed:\n" + err);
});
}
}; | "use strict";
const Environment = require('../environment/environment');
const Loader = require("../terminal-utils/async_loader");
module.exports = {
description : "Create new environment and install drupal in it.",
run : () => {
let loader;
Environment.create(['php', 'web', 'database']).then((env) => {
loader = new Loader("saving environment config");
return env.save("/home/zoltan.fodor/Documents/Drupal/test");
}).then((env) => {
loader.setMessage("generating docker env");
return env.write("docker", "/home/zoltan.fodor/Documents/Drupal/test");
}).then((docker) => {
loader.setMessage("starting docker");
return docker.start();
}).then(() => {
loader.finish("container started");
}).catch((err) => {
console.log(err);
console.error("Chain failed:\n" + err);
});
}
}; |
chore(Karma): Use Phantom.js for FEND tets | // 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-phantomjs-launcher'),
require('karma-remap-istanbul'),
require('angular-cli/plugins/karma')
],
files: [
{ pattern: './demo/test.ts', watched: false }
],
preprocessors: {
'./demo/test.ts': ['angular-cli']
},
remapIstanbulReporter: {
reports: {
html: 'coverage',
lcovonly: './coverage/coverage.lcov'
}
},
angularCli: {
config: './angular-cli.json',
environment: 'dev'
},
reporters: ['progress', 'karma-remap-istanbul'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: true
});
};
| // 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-remap-istanbul'),
require('angular-cli/plugins/karma')
],
files: [
{ pattern: './demo/test.ts', watched: false }
],
preprocessors: {
'./demo/test.ts': ['angular-cli']
},
remapIstanbulReporter: {
reports: {
html: 'coverage',
lcovonly: './coverage/coverage.lcov'
}
},
angularCli: {
config: './angular-cli.json',
environment: 'dev'
},
reporters: ['progress', 'karma-remap-istanbul'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: true
});
};
|
[webpack] Disable uglifier and enable debugging in non-production mode | var webpack = require('webpack');
var isProduction = process.env['NODE_ENV'] === 'production';
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/lib',
filename: 'index.browser.js',
library: 'hacktablParser'
},
module: {
loaders: [
{test: /\.js$/, loader: 'babel?optional[]=runtime', exclude: /node_modules/}
]
},
plugins: [
new webpack.DefinePlugin({
'typeof window': JSON.stringify('object')
}),
// Ignore jsdom in src/parseTable,
// http, https and url in src/fetchDoc
//
new webpack.IgnorePlugin(/^(?:jsdom|http|https|url)$/)
],
debug: !isProduction
};
if(isProduction) {
module.exports.plugins.push(new webpack.optimize.UglifyJsPlugin({
sourceMap: false
}))
} | var webpack = require('webpack');
module.exports = {
entry: './src/index.js',
output: {
path: __dirname + '/lib',
filename: 'index.browser.js'
},
module: {
loaders: [
{test: /\.js$/, loader: 'babel', exclude: /node_modules/}
]
},
plugins: [
new webpack.DefinePlugin({
'typeof window': JSON.stringify('object')
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: false
}),
// Ignore jsdom in src/parseTable,
// http, https and url in src/fetchDoc
//
new webpack.IgnorePlugin(/^(?:jsdom|http|https|url)$/)
],
debug: false
};
|
Make only the status symbol colored | #!/usr/bin/env node
'use strict';
var chalk = require('chalk');
var envcheck = require('./index');
if (process.argv.indexOf('-h') !== -1 || process.argv.indexOf('--help') !== -1) {
return console.log('Usage\n ' + chalk.blue('envcheck') + '\n\nRuns checks against the environment');
}
if (process.argv.indexOf('-v') !== -1 || process.argv.indexOf('--version') !== -1) {
return console.log(require('./package').version);
}
envcheck(function (err, results) {
if (err) {
throw err;
}
var fail = false;
console.log(chalk.underline('\nEnvironment check\n') + results.map(function (el) {
if (el.fail) {
fail = true;
return chalk.red('✘ ') + el.title + (el.message ? ' - ' + el.message : '');
}
return chalk.green('✔ ') + el.title + (el.message ? ' - ' + el.message : '');
}).join('\n'));
process.exit(fail ? 1 : 0);
});
| #!/usr/bin/env node
'use strict';
var chalk = require('chalk');
var envcheck = require('./index');
if (process.argv.indexOf('-h') !== -1 || process.argv.indexOf('--help') !== -1) {
return console.log('Usage\n ' + chalk.blue('envcheck') + '\n\nRuns checks against the environment');
}
if (process.argv.indexOf('-v') !== -1 || process.argv.indexOf('--version') !== -1) {
return console.log(require('./package').version);
}
envcheck(function (err, results) {
if (err) {
throw err;
}
var fail = false;
console.log(chalk.underline('\nEnvironment check\n') + results.map(function (el) {
if (el.fail) {
fail = true;
return chalk.red('✘ ' + el.title) + (el.message ? ' - ' + el.message : '');
}
return chalk.green('✔ ' + el.title) + (el.message ? ' - ' + el.message : '');
}).join('\n'));
process.exit(fail ? 1 : 0);
});
|
Send all scraped data in one big json dump. | #!/usr/bin/python
import sys
import api
import getpass
# Banks
banks = {}
import bankofamerica
banks["bankofamerica"] = bankofamerica
print "Login"
print "Username: ",
username = sys.stdin.readline().strip()
password = getpass.getpass()
if not api.callapi("login",{"username": username, "password": password}):
print "Login failed"
sys.exit(1)
todo = api.callapi("accountstodo")
print todo
for account in todo:
if account["bankname"] not in banks:
print "No scraper for %s!" % (account["bankname"])
continue
print "Scraping %s..." % (account["bankname"])
data = json.dumps(banks[account["bankname"]].downloadaccount(account),default=str)
api.callapi("newtransactions", {"data": data})
api.callapi("logout")
| #!/usr/bin/python
import sys
import api
import getpass
# Banks
banks = {}
import bankofamerica
banks["bankofamerica"] = bankofamerica
print "Login"
print "Username: ",
username = sys.stdin.readline().strip()
password = getpass.getpass()
if not api.callapi("login",{"username": username, "password": password}):
print "Login failed"
sys.exit(1)
todo = api.callapi("accountstodo")
print todo
for account in todo:
if account["bankname"] not in banks:
print "No scraper for %s!" % (account["bankname"])
continue
print "Scraping %s..." % (account["bankname"])
data = banks[account["bankname"].downloadaccount(account)
for key in data:
if data[key]:
api.callapi("new"+key, data[key])
api.callapi("logout")
|
Fix json bug for python35 in tests | # -*- coding: utf-8 -*-
import json as _json
from collections import OrderedDict as _OrderedDict
import os as _os
_thisdir = _os.path.dirname(__file__)
class MenuData(object):
_data_files = [
'data.json',
]
def __init__(self, *args, **kwargs):
dfiles = [_os.path.join(_thisdir, x) for x in self._data_files]
for fpath in dfiles:
with open(fpath, 'rt') as fdata:
dat = _json.load(fdata)
for k,v in dat.items():
setattr(self, k, v)
self.people = _OrderedDict(self.people)
| # -*- coding: utf-8 -*-
import json as _json
from collections import OrderedDict as _OrderedDict
import os as _os
_thisdir = _os.path.dirname(__file__)
class MenuData(object):
_data_files = [
'data.json',
]
def __init__(self, *args, **kwargs):
dfiles = [_os.path.join(_thisdir, x) for x in self._data_files]
for fpath in dfiles:
with open(fpath, 'rb') as fdata:
dat = _json.load(fdata)
for k,v in dat.items():
setattr(self, k, v)
self.people = _OrderedDict(self.people)
|
Build js file for v1.0.0-rc | // Generated by CoffeeScript 1.3.3
/*
jquery.turbolinks.js ~ v1.0.0-rc ~ https://github.com/kossnocorp/jquery.turbolinks
jQuery plugin for drop-in fix binded events problem caused by Turbolinks
The MIT License
Copyright (c) 2012 Sasha Koss
*/
(function() {
var $, callbacks, ready;
$ = (typeof require === "function" ? require('jquery') : void 0) || window.jQuery;
callbacks = [];
ready = function() {
var callback, _i, _len, _results;
_results = [];
for (_i = 0, _len = callbacks.length; _i < _len; _i++) {
callback = callbacks[_i];
_results.push(callback($));
}
return _results;
};
$(ready);
$.fn.ready = function(callback) {
callbacks.push(callback);
if ($.isReady) {
return callback($);
}
};
$.setReadyEvent = function(event) {
return $(document).off('.turbolinks').on(event + '.turbolinks', ready);
};
$.setReadyEvent('page:load');
}).call(this);
| // Generated by CoffeeScript 1.3.3
/*
jquery.turbolinks.js ~ v0.2.1 ~ https://github.com/kossnocorp/jquery.turbolinks
jQuery plugin for drop-in fix binded events problem caused by Turbolinks
The MIT License
Copyright (c) 2012 Sasha Koss
*/
(function() {
var $, callbacks, ready;
$ = (typeof require === "function" ? require('jquery') : void 0) || window.jQuery;
callbacks = [];
ready = function() {
var callback, _i, _len, _results;
_results = [];
for (_i = 0, _len = callbacks.length; _i < _len; _i++) {
callback = callbacks[_i];
_results.push(callback($));
}
return _results;
};
$(ready);
$.fn.ready = function(callback) {
return callbacks.push(callback);
};
$.setReadyEvent = function(event) {
return $(document).off('.turbolinks').on(event + '.turbolinks', ready);
};
$.setReadyEvent('page:load');
}).call(this);
|
Add forgotten program file for deployment | """
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015 Dirk Beyer
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import benchexec.util as util
yogar_cbmc = __import__("benchexec.tools.yogar-cbmc", fromlist=["Tool"])
class Tool(yogar_cbmc.Tool):
REQUIRED_PATHS = [
"yogar-cbmc"
]
def executable(self):
return util.find_executable('yogar-cbmc-parallel')
def name(self):
return 'Yogar-CBMC-Parallel'
def cmdline(self, executable, options, tasks, propertyfile, rlimits):
return [executable] + options + tasks
| """
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015 Dirk Beyer
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import benchexec.util as util
yogar_cbmc = __import__("benchexec.tools.yogar-cbmc", fromlist=["Tool"])
class Tool(yogar_cbmc.Tool):
def executable(self):
return util.find_executable('yogar-cbmc-parallel')
def name(self):
return 'Yogar-CBMC-Parallel'
def cmdline(self, executable, options, tasks, propertyfile, rlimits):
return [executable] + options + tasks
|
Install some more packages for trac. | from __future__ import absolute_import
from fabric.api import sudo, task, put
from twisted.python.filepath import FilePath
from braid import pypy, service, authbind, git, package, bazaar, postgres
@task
def bootstrap():
"""
Prepare the machine to be able to correctly install, configure and execute
twisted services.
"""
# Each service specific system user shall be added to the 'service' group
sudo('groupadd -f --system service')
package.install(['python2.7', 'python2.7-dev'])
# gcc is needed for 'pip install'
package.install(['gcc', 'python-pip'])
# For trac
package.install(['python-subversion', 'enscript'])
pypy.install()
authbind.install()
git.install()
bazaar.install()
postgres.install()
sshConfig()
def sshConfig():
"""
Install ssh config that allows anyone who can login as root
to login as any service.
"""
configFile = FilePath(__file__).sibling('sshd_config')
put(configFile.path, '/etc/ssh/sshd_config', use_sudo=True)
sudo('chgrp service /root/.ssh/authorized_keys')
sudo('chmod go+X /root /root/.ssh')
sudo('chmod g+r /root/.ssh/authorized_keys')
service.restart('ssh')
| from __future__ import absolute_import
from fabric.api import sudo, task, put
from twisted.python.filepath import FilePath
from braid import pypy, service, authbind, git, package, bazaar, postgres
@task
def bootstrap():
"""
Prepare the machine to be able to correctly install, configure and execute
twisted services.
"""
# Each service specific system user shall be added to the 'service' group
sudo('groupadd -f --system service')
# gcc is needed for 'pip install'
package.install(['gcc', 'python-pip'])
# For trac
package.install(['python-subversion'])
pypy.install()
authbind.install()
git.install()
bazaar.install()
postgres.install()
sshConfig()
def sshConfig():
"""
Install ssh config that allows anyone who can login as root
to login as any service.
"""
configFile = FilePath(__file__).sibling('sshd_config')
put(configFile.path, '/etc/ssh/sshd_config', use_sudo=True)
sudo('chgrp service /root/.ssh/authorized_keys')
sudo('chmod go+X /root /root/.ssh')
sudo('chmod g+r /root/.ssh/authorized_keys')
service.restart('ssh')
|
Revert "id removed from the form"
This reverts commit deacaaa17285ee642a8888c4a0dad824ade72017. | @push('js')
<script src="{{ asset('components/ckeditor4/ckeditor.js') }}"></script>
<script src="{{ asset('components/ckeditor4/config-full.js') }}"></script>
@endpush
@component('core::admin._buttons-form', ['model' => $model])
@endcomponent
{!! BootForm::hidden('id') !!}
<file-manager related-table="{{ $model->getTable() }}" :related-id="{{ $model->id ?? 0 }}"></file-manager>
<file-field type="image" field="image_id" data="{{ $model->image }}"></file-field>
<div class="row">
<div class="col-sm-6">
{!! BootForm::text(__('Url'), 'url')->type('url')->placeholder('https://') !!}
</div>
</div>
{!! BootForm::select(__('Page'), 'page_id', Pages::allForSelect()) !!}
<div class="form-group">
{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
</div>
{!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor-full') !!}
| @push('js')
<script src="{{ asset('components/ckeditor4/ckeditor.js') }}"></script>
<script src="{{ asset('components/ckeditor4/config-full.js') }}"></script>
@endpush
@component('core::admin._buttons-form', ['model' => $model])
@endcomponent
<file-manager related-table="{{ $model->getTable() }}" :related-id="{{ $model->id ?? 0 }}"></file-manager>
<file-field type="image" field="image_id" data="{{ $model->image }}"></file-field>
<div class="row">
<div class="col-sm-6">
{!! BootForm::text(__('Url'), 'url')->type('url')->placeholder('https://') !!}
</div>
</div>
{!! BootForm::select(__('Page'), 'page_id', Pages::allForSelect()) !!}
<div class="form-group">
{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
</div>
{!! TranslatableBootForm::textarea(__('Body'), 'body')->addClass('ckeditor-full') !!}
|
Check for the class of the member as opposed to the toplevel name of the member | <?php
namespace Refinery29\ApiOutput;
use Refinery29\ApiOutput\Resource\TopLevelResource;
use Refinery29\ApiOutput\Serializer\Serializer;
use Refinery29\ApiOutput\Serializer\CustomResult;
class ResponseBody
{
/**
* @var TopLevelResource[]
*/
protected $members = [];
/**
* @param TopLevelResource $member
*
* @throws \Exception
*/
public function addMember(TopLevelResource $member)
{
$this->members[] = $member;
}
/**
* @return Serializer[]
*/
public function getMembers()
{
return $this->members;
}
/**mae
* @return string JSON representation of the response.
*/
public function getOutput()
{
$response = [];
reset($this->members);
$member = current($this->getMembers());
if ($member instanceof CustomResult) {
return json_encode((object) $member->getOutput(), JSON_UNESCAPED_SLASHES);
}
foreach ($this->members as $member) {
$response[$member->getTopLevelName()] = $member->getOutput();
}
return json_encode((object) $response, JSON_UNESCAPED_SLASHES);
}
}
| <?php
namespace Refinery29\ApiOutput;
use Refinery29\ApiOutput\Resource\TopLevelResource;
use Refinery29\ApiOutput\Serializer\Serializer;
class ResponseBody
{
/**
* @var TopLevelResource[]
*/
protected $members = [];
/**
* @param TopLevelResource $member
*
* @throws \Exception
*/
public function addMember(TopLevelResource $member)
{
$this->members[] = $member;
}
/**
* @return Serializer[]
*/
public function getMembers()
{
return $this->members;
}
/**mae
* @return string JSON representation of the response.
*/
public function getOutput()
{
$response = [];
reset($this->members);
$member = current($this->getMembers());
if ($member->getTopLevelName() === '') {
return json_encode((object) $member->getOutput(), JSON_UNESCAPED_SLASHES);
}
foreach ($this->members as $member) {
$response[$member->getTopLevelName()] = $member->getOutput();
}
return json_encode((object) $response, JSON_UNESCAPED_SLASHES);
}
}
|
Switch rst2html to HTML5 builder
This gives a prettier output and every browser in widespread usage has
supported it for years. The license, which was previously missing, is
added.
Signed-off-by: Stephen Finucane <06fa905d7f2aaced6dc72e9511c71a2a51e8aead@that.guru> | #!/usr/bin/env python3
# -*- coding: utf8 -*-
# :Copyright: © 2015 Günter Milde.
# :License: Released under the terms of the `2-Clause BSD license`_, in short:
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.
# This file is offered as-is, without any warranty.
#
# .. _2-Clause BSD license: http://www.spdx.org/licenses/BSD-2-Clause
"""
A version of rst2html5 with support for rst2pdf's custom roles/directives.
"""
import locale
from docutils.core import default_description
from docutils.core import publish_cmdline
from docutils.parsers.rst import directives
from docutils.parsers.rst import roles
from rst2pdf.directives import code_block
from rst2pdf.directives import noop
from rst2pdf.roles import counter_off
locale.setlocale(locale.LC_ALL, '')
directives.register_directive('code-block', code_block.code_block_directive)
directives.register_directive('oddeven', noop.noop_directive)
roles.register_canonical_role('counter', counter_off.counter_fn)
description = (
'Generates HTML5 documents from standalone reStructuredText '
'sources.\n' + default_description
)
publish_cmdline(writer_name='html5', description=description)
| #!/usr/bin/env python3
"""
A minimal front end to the Docutils Publisher, producing HTML.
"""
import locale
from docutils.core import publish_cmdline, default_description
from docutils.parsers.rst import directives
from docutils.parsers.rst import roles
from rst2pdf.directives import code_block
from rst2pdf.directives import noop
from rst2pdf.roles import counter_off
locale.setlocale(locale.LC_ALL, '')
directives.register_directive('code-block', code_block.code_block_directive)
directives.register_directive('oddeven', noop.noop_directive)
roles.register_canonical_role('counter', counter_off.counter_fn)
description = (
'Generates (X)HTML documents from standalone reStructuredText '
'sources. ' + default_description
)
publish_cmdline(writer_name='html', description=description)
|
Use willMount/willReceiveProps in history actions | import React, { PropTypes } from 'react'
import {
historyContext as historyContextType
} from './PropTypes'
class HistoryAction extends React.Component {
static contextTypes = {
history: historyContextType.isRequired
}
static propTypes = {
perform: PropTypes.func.isRequired
}
componentWillMount() {
this.props.perform(this.context.history)
}
componentWillReceiveProps(nextProps) {
nextProps.perform(this.context.history)
}
render() {
return null
}
}
export const Push = ({ path, state }) =>
<HistoryAction perform={history => history.push(path, state)}/>
Push.propTypes = {
path: PropTypes.string.isRequired,
state: PropTypes.any
}
export const Replace = ({ path, state }) =>
<HistoryAction perform={history => history.replace(path, state)}/>
Replace.propTypes = Push.propTypes
export const Pop = ({ go }) =>
<HistoryAction perform={history => history.pop(go)}/>
Pop.propTypes = {
go: PropTypes.number.isRequired
}
| import React, { PropTypes } from 'react'
import {
historyContext as historyContextType
} from './PropTypes'
class HistoryAction extends React.Component {
static contextTypes = {
history: historyContextType.isRequired
}
static propTypes = {
perform: PropTypes.func.isRequired
}
performAction() {
this.props.perform(this.context.history)
}
componentDidMount() {
this.performAction()
}
componentDidUpdate() {
this.performAction()
}
render() {
return null
}
}
export const Push = ({ path, state }) =>
<HistoryAction perform={history => history.push(path, state)}/>
Push.propTypes = {
path: PropTypes.string.isRequired,
state: PropTypes.any
}
export const Replace = ({ path, state }) =>
<HistoryAction perform={history => history.replace(path, state)}/>
Replace.propTypes = Push.propTypes
export const Pop = ({ go }) =>
<HistoryAction perform={history => history.pop(go)}/>
Pop.propTypes = {
go: PropTypes.number.isRequired
}
|
Support event handlers on proxy, reduce iterations | /* @flow */
import React, { Component, PropTypes } from "react"
import { Element as ReactElement } from "react"
import ReactHigherEventProxyContextTypes from "./ReactHigherEventProxyContextTypes"
type EventProps = {
[key: string]: Function,
}
class ReactHigherEventProxy extends Component<void, Props, void> {
componentDidMount() {
const { higherEventProxy } = this.context
this.unsubscribe = higherEventProxy.subscribe(this.forceUpdate.bind(this))
}
componentWillUnmount() {
this.unsubscribe()
}
getEventProps(): EventProps {
const { higherEventProxy } = this.context
const eventProps = {}
higherEventProxy.events.forEach((key) => {
eventProps[key] = (event) => {
if(this.props[key]) {
this.props[key](event)
}
higherEventProxy.handleEvent(key, event)
}
})
return eventProps
}
render(): ReactElement {
const { children, ...props } = this.props
return (
<div {...props} {...this.getEventProps()}>
{children}
</div>
)
}
}
ReactHigherEventProxy.contextTypes = ReactHigherEventProxyContextTypes
type Props = {
children?: any,
}
export default ReactHigherEventProxy
| /* @flow */
import React, { Component, PropTypes } from "react"
import { Element as ReactElement } from "react"
import ReactHigherEventProxyContextTypes from "./ReactHigherEventProxyContextTypes"
type EventProps = {
[key: string]: Function,
}
class ReactHigherEventProxy extends Component<void, Props, void> {
componentDidMount() {
const { higherEventProxy } = this.context
this.unsubscribe = higherEventProxy.subscribe(this.forceUpdate.bind(this))
}
componentWillUnmount() {
this.unsubscribe()
}
getEventProps(): EventProps {
const { higherEventProxy } = this.context
return Array.from(higherEventProxy.events.keys()).reduce((acc, key) => {
return {
...acc,
[key]: higherEventProxy.handleEvent.bind(null, key),
}
}, {})
}
render(): ReactElement {
const { children, ...props } = this.props
return (
<div {...props} {...this.getEventProps()}>
{children}
</div>
)
}
}
ReactHigherEventProxy.contextTypes = ReactHigherEventProxyContextTypes
type Props = {
children?: any,
}
export default ReactHigherEventProxy
|
Increase timeout values to max that were used in last API class | package net.buycraft.plugin.shared;
import net.buycraft.plugin.shared.util.FakeProxySelector;
import net.buycraft.plugin.shared.util.Ipv4PreferDns;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import java.io.File;
import java.net.ProxySelector;
import java.util.concurrent.TimeUnit;
public final class Setup {
private Setup() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
public static OkHttpClient okhttp(File base) {
return okhttpBuilder().cache(new Cache(new File(base, "cache"), 1024 * 1024 * 10)).build();
}
public static OkHttpClient.Builder okhttpBuilder() {
return new OkHttpClient.Builder()
.connectTimeout(6, TimeUnit.SECONDS)
.writeTimeout(7, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.dns(new Ipv4PreferDns())
.proxySelector(ProxySelector.getDefault() == null ? FakeProxySelector.INSTANCE : ProxySelector.getDefault());
}
}
| package net.buycraft.plugin.shared;
import net.buycraft.plugin.shared.util.FakeProxySelector;
import net.buycraft.plugin.shared.util.Ipv4PreferDns;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import java.io.File;
import java.net.ProxySelector;
import java.util.concurrent.TimeUnit;
public final class Setup {
private Setup() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
public static OkHttpClient okhttp(File base) {
return okhttpBuilder().cache(new Cache(new File(base, "cache"), 1024 * 1024 * 10)).build();
}
public static OkHttpClient.Builder okhttpBuilder() {
return new OkHttpClient.Builder()
.connectTimeout(3, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.dns(new Ipv4PreferDns())
.proxySelector(ProxySelector.getDefault() == null ? FakeProxySelector.INSTANCE : ProxySelector.getDefault());
}
}
|
Fix warning when no listener is registered | <?php
// Copyright (c) 2018 Fernando Bevilacqua <dovyski@gmail.com>
// Licensed under the MIT license, see LICENSE file.
namespace Codebot;
class Signal {
private $listeners;
private function getKey($theListener) {
if(is_string($theListener)) {
return $theListener;
} else if(is_array($theListener)) {
return (is_string($theListener[0]) ? $theListener[0] : spl_object_hash($theListener[0])) . $theListener[1];
} else {
throw new \Exception('Invalid listener: it should be string or array(class, method).');
}
}
public function add($theListener) {
$aKey = $this->getKey($theListener);
if(!isset($this->listeners[$aKey])) {
$this->listeners[$aKey] = $theListener;
return true;
}
return false;
}
public function remove($theListener) {
$aKey = $this->getKey($theListener);
if(isset($this->listeners[$aKey])) {
unset($this->listeners[$aKey]);
return true;
}
return false;
}
public function dispatch(array $theParams = array()) {
if(count($this->listeners) == 0) {
return;
}
foreach($this->listeners as $aKey => $aListener) {
call_user_func_array($aListener, $theParams);
}
}
}
?>
| <?php
// Copyright (c) 2018 Fernando Bevilacqua <dovyski@gmail.com>
// Licensed under the MIT license, see LICENSE file.
namespace Codebot;
class Signal {
private $listeners;
private function getKey($theListener) {
if(is_string($theListener)) {
return $theListener;
} else if(is_array($theListener)) {
return (is_string($theListener[0]) ? $theListener[0] : spl_object_hash($theListener[0])) . $theListener[1];
} else {
throw new \Exception('Invalid listener: it should be string or array(class, method).');
}
}
public function add($theListener) {
$aKey = $this->getKey($theListener);
if(!isset($this->listeners[$aKey])) {
$this->listeners[$aKey] = $theListener;
return true;
}
return false;
}
public function remove($theListener) {
$aKey = $this->getKey($theListener);
if(isset($this->listeners[$aKey])) {
unset($this->listeners[$aKey]);
return true;
}
return false;
}
public function dispatch(array $theParams = array()) {
foreach($this->listeners as $aKey => $aListener) {
call_user_func_array($aListener, $theParams);
}
}
}
?>
|
Fix foreach to be architectical correct | <?php
include_once '../../config/config-local.php';
include_once '../../models/database.php';
include_once '../../models/db.php';
include_once 'countries_array.php';
$countries = getCountries();
$array = array();
$count = 0;
foreach ( $countries as $key => $value ) {
$res = db_insert( 'countries', array( 'id' => NULL, 'country' => $value, 'shortname' => $key ) );
if ( $res === false ) {
die( "sql query died with the following error\n\"" . mysql_error() );
}
++$count;
}
echo "You imported $count raws out of the 239 countries in the table 'countries'.";
?>
| <?php
include_once '../../config/config-local.php';
include_once '../../models/database.php';
include_once '../../models/db.php';
include_once 'countries_array.php';
$countries = getCountries();
$array = array();
$count = 0;
$keys = array_keys( $countries );
foreach ( $keys as $key ) {
$value = $countries[ $key ];
$res = db_insert( 'countries', array( 'id' => NULL, 'country' => $value, 'shortname' => $key ) );
if ( $res === false ) {
die( "sql query died with the following error\n\"" . mysql_error() );
}
++$count;
}
echo "You imported $count raws out of the 239 countries in the table 'countries'.";
?>
|
Use Django 1.2 for the cron/tasks instance too. | import logging
import os
import sys
from google.appengine.dist import use_library
use_library('django', '1.2')
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_settings'
# Tweak import path so that httplib2 (which lives in datasources) can be
# imported as httplib2 while the app is running.
# TODO(mihaip): move httplib2 (and oauth2 and python-twitter) into a third_party
# directory.
APP_DIR = os.path.abspath(os.path.dirname(__file__))
DATASOURCES_DIR = os.path.join(APP_DIR, 'datasources')
sys.path.insert(0, DATASOURCES_DIR)
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import feedplayback.handlers
def main():
application = webapp.WSGIApplication([
('/cron/feed-playback/advance', feedplayback.handlers.AdvanceCronHandler),
('/tasks/feed-playback/advance', feedplayback.handlers.AdvanceTaskHandler),
],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| import logging
import os
import sys
# Tweak import path so that httplib2 (which lives in datasources) can be
# imported as httplib2 while the app is running.
# TODO(mihaip): move httplib2 (and oauth2 and python-twitter) into a third_party
# directory.
APP_DIR = os.path.abspath(os.path.dirname(__file__))
DATASOURCES_DIR = os.path.join(APP_DIR, 'datasources')
sys.path.insert(0, DATASOURCES_DIR)
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import feedplayback.handlers
def main():
application = webapp.WSGIApplication([
('/cron/feed-playback/advance', feedplayback.handlers.AdvanceCronHandler),
('/tasks/feed-playback/advance', feedplayback.handlers.AdvanceTaskHandler),
],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
|
BAP-4676: Fix Major issues mentioned in Scrutinizer builds
- Edit | <?php
namespace Oro\Bundle\EmailBundle\Model;
/**
* Represents an email message template
*/
interface EmailTemplateInterface
{
/**
* Gets email template type
*
* @return string
*/
public function getType();
/**
* Gets email subject
*
* @return string
*/
public function getSubject();
/**
* Gets email template content
*
* @return string
*/
public function getContent();
/**
* Sets email template content
*
* @param string $content
*
* @return EmailTemplateInterface
*/
public function setContent($content);
/**
* Sets email subject
*
* @param string $subject
*
* @return EmailTemplateInterface
*/
public function setSubject($subject);
}
| <?php
namespace Oro\Bundle\EmailBundle\Model;
/**
* Represents an email message template
*/
interface EmailTemplateInterface
{
/**
* Gets email template type
*
* @return string
*/
public function getType();
/**
* Gets email subject
*
* @return string
*/
public function getSubject();
/**
* Gets email template content
*
* @return string
*/
public function getContent();
/**
* Sets email template content
*
* @param string $content
* @return EmailTemplateInterface
*/
public function setContent($content);
/**
* Sets email subject
*
* @param string $subject
* @return EmailTemplateInterface
*/
public function setSubject($subject);
}
|
main: Print nicer error messages on invalid arguments
Signed-off-by: Kai Blin <ad3597797f6179d503c382b2627cc19939309418@biosustain.dtu.dk> | """Command line handling for ncbi-genome-download."""
import logging
from ncbi_genome_download import args_download
from ncbi_genome_download import argument_parser
from ncbi_genome_download import __version__
def main():
"""Build and parse command line."""
parser = argument_parser(version=__version__)
args = parser.parse_args()
if args.debug:
log_level = logging.DEBUG
elif args.verbose:
log_level = logging.INFO
else:
log_level = logging.WARNING
logger = logging.getLogger("ncbi-genome-download")
logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)
max_retries = args.retries
attempts = 0
try:
ret = args_download(args)
except ValueError as err:
print(err)
return -2
while ret == 75 and attempts < max_retries:
attempts += 1
logger.error(
'Downloading from NCBI failed due to a connection error, retrying. Retries so far: %s',
attempts)
ret = args_download(args)
return ret
if __name__ == '__main__':
main()
| """Command line handling for ncbi-genome-download."""
import logging
from ncbi_genome_download import args_download
from ncbi_genome_download import argument_parser
from ncbi_genome_download import __version__
def main():
"""Build and parse command line."""
parser = argument_parser(version=__version__)
args = parser.parse_args()
if args.debug:
log_level = logging.DEBUG
elif args.verbose:
log_level = logging.INFO
else:
log_level = logging.WARNING
logger = logging.getLogger("ncbi-genome-download")
logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)
max_retries = args.retries
attempts = 0
ret = args_download(args)
while ret == 75 and attempts < max_retries:
attempts += 1
logger.error(
'Downloading from NCBI failed due to a connection error, retrying. Retries so far: %s',
attempts)
ret = args_download(args)
return ret
if __name__ == '__main__':
main()
|
Add in API testing version
Signed-off-by: Chris Wisecarver <5fccdd17c1f7bcc7e393d2cb5e2fad37705ca69f@cos.io> | # Use API defaults. This allows these settings to work with API tests
from api.base.settings.defaults import * # noqa
DEBUG_PROPAGATE_EXCEPTIONS = True
#DATABASES = {
# 'default': {
# 'CONN_MAX_AGE': 0,
# 'ENGINE': 'osf.db.backends.postgresql',
# 'HOST': '',
# 'NAME': 'osf-models-test',
# 'PASSWORD': '',
# 'PORT': '',
# 'USER': '',
# 'ATOMIC_REQUESTS': True,
# }
#}
SITE_ID = 1
# SECRET_KEY = 'not very secret in tests'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
)
REST_FRAMEWORK['ALLOWED_VERSIONS'] = (
'2.0',
'2.0.1',
'2.1',
'2.2',
'2.3',
'3.0',
'3.0.1',
)
| # Use API defaults. This allows these settings to work with API tests
from api.base.settings.defaults import * # noqa
DEBUG_PROPAGATE_EXCEPTIONS = True
#DATABASES = {
# 'default': {
# 'CONN_MAX_AGE': 0,
# 'ENGINE': 'osf.db.backends.postgresql',
# 'HOST': '',
# 'NAME': 'osf-models-test',
# 'PASSWORD': '',
# 'PORT': '',
# 'USER': '',
# 'ATOMIC_REQUESTS': True,
# }
#}
SITE_ID = 1
# SECRET_KEY = 'not very secret in tests'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
)
REST_FRAMEWORK['ALLOWED_VERSIONS'] = (
'2.0',
'2.1',
'2.2',
'2.3',
'3.0',
'3.0.1',
)
|
Remove initial state test key | // ------------------------------------
// Constants
// ------------------------------------
const MAKE_SCREENSHOT = 'MAKE_SCREENSHOT'
const MAKE_SCREENSHOT_RESULT = 'MAKE_SCREENSHOT_RESULT'
// ------------------------------------
// Actions
// ------------------------------------
export function makeScreenshot() {
return {
type: MAKE_SCREENSHOT
}
}
// // ------------------------------------
// // Specialized Action Creator
// // ------------------------------------
// export const updateLocation = ({ dispatch }) => {
// return (nextLocation) => dispatch(locationChange(nextLocation))
//}
export const actions = {
MAKE_SCREENSHOT,
MAKE_SCREENSHOT_RESULT,
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {};
export default function mainReducer(state = initialState, action) {
switch (action.type) {
case actions.MAKE_SCREENSHOT_RESULT:
return {...state, screenshotData: action.data};
break;
//
// case MAKE_SCREENSHOT:
// return Object.assign({}, state, {
// screenshotData: null,
// });
default:
return state;
}
}
| // ------------------------------------
// Constants
// ------------------------------------
const MAKE_SCREENSHOT = 'MAKE_SCREENSHOT'
const MAKE_SCREENSHOT_RESULT = 'MAKE_SCREENSHOT_RESULT'
// ------------------------------------
// Actions
// ------------------------------------
export function makeScreenshot() {
return {
type: MAKE_SCREENSHOT
}
}
// // ------------------------------------
// // Specialized Action Creator
// // ------------------------------------
// export const updateLocation = ({ dispatch }) => {
// return (nextLocation) => dispatch(locationChange(nextLocation))
//}
export const actions = {
MAKE_SCREENSHOT,
MAKE_SCREENSHOT_RESULT,
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {test: 123};
export default function mainReducer(state = initialState, action) {
switch (action.type) {
case actions.MAKE_SCREENSHOT_RESULT:
return {...state, screenshotData: action.data};
break;
//
// case MAKE_SCREENSHOT:
// return Object.assign({}, state, {
// screenshotData: null,
// });
default:
return state;
}
}
|
Fix uploading for files with troubles another root domain | <?php
return array(
/*
|--------------------------------------------------------------------------
| Application Path
|--------------------------------------------------------------------------
|
| Here we just defined the path to the application directory. Most likely
| you will never need to change this value as the default setup should
| work perfectly fine for the vast majority of all our applications.
|
*/
'app' => __DIR__.'/../app',
/*
|--------------------------------------------------------------------------
| Public Path
|--------------------------------------------------------------------------
|
| The public path contains the assets for your web application, such as
| your JavaScript and CSS files, and also contains the primary entry
| point for web requests into these applications from the outside.
|
*/
'public' => __DIR__.'/../www',
/*
|--------------------------------------------------------------------------
| Base Path
|--------------------------------------------------------------------------
|
| The base path is the root of the Laravel installation. Most likely you
| will not need to change this value. But, if for some wild reason it
| is necessary you will do so here, just proceed with some caution.
|
*/
'base' => __DIR__.'/..',
/*
|--------------------------------------------------------------------------
| Storage Path
|--------------------------------------------------------------------------
|
| The storage path is used by Laravel to store cached Blade views, logs
| and other pieces of information. You may modify the path here when
| you want to change the location of this directory for your apps.
|
*/
'storage' => __DIR__.'/../storage',
);
| <?php
return array(
/*
|--------------------------------------------------------------------------
| Application Path
|--------------------------------------------------------------------------
|
| Here we just defined the path to the application directory. Most likely
| you will never need to change this value as the default setup should
| work perfectly fine for the vast majority of all our applications.
|
*/
'app' => __DIR__.'/../app',
/*
|--------------------------------------------------------------------------
| Public Path
|--------------------------------------------------------------------------
|
| The public path contains the assets for your web application, such as
| your JavaScript and CSS files, and also contains the primary entry
| point for web requests into these applications from the outside.
|
*/
'public' => __DIR__.'/../public',
/*
|--------------------------------------------------------------------------
| Base Path
|--------------------------------------------------------------------------
|
| The base path is the root of the Laravel installation. Most likely you
| will not need to change this value. But, if for some wild reason it
| is necessary you will do so here, just proceed with some caution.
|
*/
'base' => __DIR__.'/..',
/*
|--------------------------------------------------------------------------
| Storage Path
|--------------------------------------------------------------------------
|
| The storage path is used by Laravel to store cached Blade views, logs
| and other pieces of information. You may modify the path here when
| you want to change the location of this directory for your apps.
|
*/
'storage' => __DIR__.'/../storage',
);
|
Support providing SECRET_KEY as environment variable. | """Settings file for the Django project used for tests."""
import os
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
PROJECT_NAME = 'project'
# Base paths.
ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT = os.path.join(ROOT, PROJECT_NAME)
# Django configuration.
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
DEBUG = TEMPLATE_DEBUG = True
INSTALLED_APPS = (
'django.contrib.staticfiles',
'endless_pagination',
PROJECT_NAME,
)
ROOT_URLCONF = PROJECT_NAME + '.urls'
SECRET_KEY = os.getenv('ENDLESS_PAGINATION_SECRET_KEY', 'secret')
SITE_ID = 1
STATIC_ROOT = os.path.join(PROJECT, 'static')
STATIC_URL = '/static/'
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
PROJECT_NAME + '.context_processors.navbar',
PROJECT_NAME + '.context_processors.versions',
)
TEMPLATE_DIRS = os.path.join(PROJECT, 'templates')
# Testing.
NOSE_ARGS = (
'--verbosity=2',
'--with-coverage',
'--cover-package=endless_pagination',
)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
| """Settings file for the Django project used for tests."""
import os
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
PROJECT_NAME = 'project'
# Base paths.
ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT = os.path.join(ROOT, PROJECT_NAME)
# Django configuration.
DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
DEBUG = TEMPLATE_DEBUG = True
INSTALLED_APPS = (
'django.contrib.staticfiles',
'endless_pagination',
PROJECT_NAME,
)
ROOT_URLCONF = PROJECT_NAME + '.urls'
SECRET_KEY = 'secret'
SITE_ID = 1
STATIC_ROOT = os.path.join(PROJECT, 'static')
STATIC_URL = '/static/'
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
PROJECT_NAME + '.context_processors.navbar',
PROJECT_NAME + '.context_processors.versions',
)
TEMPLATE_DIRS = os.path.join(PROJECT, 'templates')
# Testing.
NOSE_ARGS = (
'--verbosity=2',
'--with-coverage',
'--cover-package=endless_pagination',
)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
|
Remove unnecessary $location parameter in qr-device-interaction. | /*global angular*/
(function () {
'use strict';
angular.module('core').directive('qrDeviceInteraction', function () {
var template = '';
template += '<a href="{{qrConfig.slideUrl}}" target="_blank">';
template += ' <qr text="qrConfig.slideUrl" type-number="qrConfig.typeNumber" correction-level="qrConfig.correctionLevel"';
template += ' size="qrConfig.size" input-mode="qrConfig.inputMode" image="qrConfig.image">';
template += ' </qr>';
template += '</a>';
return {
restrict: 'E',
template: template,
};
});
}());
| /*global angular*/
(function () {
'use strict';
angular.module('core').directive('qrDeviceInteraction', ["$location", function ($location) {
var template = '';
template += '<a href="{{qrConfig.slideUrl}}" target="_blank">';
template += ' <qr text="qrConfig.slideUrl" type-number="qrConfig.typeNumber" correction-level="qrConfig.correctionLevel"';
template += ' size="qrConfig.size" input-mode="qrConfig.inputMode" image="qrConfig.image">';
template += ' </qr>';
template += '</a>';
return {
restrict: 'E',
template: template,
};
}]);
}());
|
Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation | # -*- coding: utf-8 -*-
# Import chosenforms for pretty search forms
from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags for searching
from taggit.models import Tag
from taggit.models import TagBase
from taggit.managers import TaggableManager
from django.utils.translation import ugettext_lazy as _
# Create seperate classes for each tag type that will be a foreign key reference from User
class TeachSkills(models.Model):
skills = TaggableManager()
class LearnSkills(models.Model):
skills = TaggableManager()
class UserManager(models.Manager):
def create(self, name):
new_user = Food()
new_user.name = name
new_user.teach = TeachSkills()
new_user.teach.save()
new_user.learn = LearnSkills()
new_user.learn.save()
new_user.save()
return new_user
# Subclass AbstractUser
class User(AbstractUser):
def __unicode__(self):
return self.username
objects = UserManager()
teach = models.ForeignKey(TeachSkills, null=True)
learn = models.ForeignKey(LearnSkills, null=True)
short_bio = models.TextField()
location = models.CharField(max_length=50) | # -*- coding: utf-8 -*-
# Import chosenforms for pretty search forms
from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags for searching
from taggit.models import Tag
from taggit.models import TagBase
from taggit.managers import TaggableManager
from django.utils.translation import ugettext_lazy as _
# Create seperate classes for each tag type that will be a foreign key reference from User
class TeachSkills(models.Model):
skills = TaggableManager()
class LearnSkills(models.Model):
skills = TaggableManager()
# Subclass AbstractUser
class User(AbstractUser):
def __unicode__(self):
return self.username
teach = models.ForeignKey(TeachSkills, null=True)
learn = models.ForeignKey(LearnSkills, null=True)
short_bio = models.TextField()
location = models.CharField(max_length=50) |
Reduce complexity of oBoolean function | 'use babel';
'use strict';
const process = require('process');
var Common = function () {
const isWin = (/^win/.test(process.platform));
const pathSeparator = (isWin) ? ';' : ':';
const fileSeparator = (isWin) ? '\\' : '/';
const homeDir = (isWin) ? process.env.HOMEPATH : process.env.HOME;
return {
isWin: isWin,
pathSeparator: pathSeparator,
fileSeparator: fileSeparator,
homeDir: homeDir,
resolveEnvironmentVariable: function (env) {
return process.env[env];
},
toBoolean: function (value) {
if (typeof (value) === 'string') {
value = value.toLowerCase().trim();
}
if (value === 'true' || value === true) {
return true;
} else {
return false;
}
}
};
};
module.exports = Common();
| 'use babel';
'use strict';
const process = require('process');
var Common = function () {
const isWin = (/^win/.test(process.platform));
const pathSeparator = (isWin) ? ';' : ':';
const fileSeparator = (isWin) ? '\\' : '/';
const homeDir = (isWin) ? process.env.HOMEPATH : process.env.HOME;
return {
isWin: isWin,
pathSeparator: pathSeparator,
fileSeparator: fileSeparator,
homeDir: homeDir,
resolveEnvironmentVariable: function (env) {
return process.env[env];
},
toBoolean: function (value) {
if (typeof (value) === 'string') {
value = value.toLowerCase().trim();
}
switch (value) {
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
};
};
module.exports = Common();
|
Ref: Change attribute name weightSize to weightStyle | package sizebay.catalog.client.model;
import java.io.Serializable;
import java.util.Map;
import lombok.*;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class ProductBasicInformation implements Serializable {
long id;
@NonNull String name;
@NonNull String permalink;
String genderTheWearWasDesignedFor;
String coverImage;
int isShoe;
@Deprecated int szbMainCategoryId; // FIXME Remove this field after legacy virtual dead
@Deprecated int szbSubCategoryId; // FIXME Remove this field after legacy virtual dead
@Deprecated String szbMainCategoryName = null; // FIXME Remove this field after legacy virtual dead
@Deprecated String szbSubCategoryName = null; // FIXME Remove this field after legacy virtual dead
String categoryName;
String modelingName;
@Deprecated boolean bottomOnly;
ClothesType clothesType;
String sizeType;
Boolean status;
Product.AgeGroupEnum ageGroup = null;
Map<String, ModelingSizeMeasures> measures;
Boolean accessory;
int strongBrandId;
String strongBrandName;
int strongCategoryTypeId;
String strongCategoryTypeName;
int strongCategoryId;
String strongCategoryName;
int strongSubcategoryId;
String strongSubcategoryName;
int strongModelId;
String strongModelName;
double weightStyle;
} | package sizebay.catalog.client.model;
import java.io.Serializable;
import java.util.Map;
import lombok.*;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class ProductBasicInformation implements Serializable {
long id;
@NonNull String name;
@NonNull String permalink;
String genderTheWearWasDesignedFor;
String coverImage;
int isShoe;
@Deprecated int szbMainCategoryId; // FIXME Remove this field after legacy virtual dead
@Deprecated int szbSubCategoryId; // FIXME Remove this field after legacy virtual dead
@Deprecated String szbMainCategoryName = null; // FIXME Remove this field after legacy virtual dead
@Deprecated String szbSubCategoryName = null; // FIXME Remove this field after legacy virtual dead
String categoryName;
String modelingName;
@Deprecated boolean bottomOnly;
ClothesType clothesType;
String sizeType;
Boolean status;
Product.AgeGroupEnum ageGroup = null;
Map<String, ModelingSizeMeasures> measures;
Boolean accessory;
int strongBrandId;
String strongBrandName;
int strongCategoryTypeId;
String strongCategoryTypeName;
int strongCategoryId;
String strongCategoryName;
int strongSubcategoryId;
String strongSubcategoryName;
int strongModelId;
String strongModelName;
double weightSize;
} |
Use cache backend for sessions in deployed settings. |
DATABASES = {
"default": {
# Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle".
"ENGINE": "django.db.backends.postgresql_psycopg2",
# DB name or path to database file if using sqlite3.
"NAME": "%(proj_name)s",
# Not used with sqlite3.
"USER": "%(proj_name)s",
# Not used with sqlite3.
"PASSWORD": "%(db_pass)s",
# Set to empty string for localhost. Not used with sqlite3.
"HOST": "127.0.0.1",
# Set to empty string for default. Not used with sqlite3.
"PORT": "",
}
}
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https")
CACHE_MIDDLEWARE_SECONDS = 60
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.memcached.MemcachedCache",
"LOCATION": "127.0.0.1:11211",
}
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
|
DATABASES = {
"default": {
# Ends with "postgresql_psycopg2", "mysql", "sqlite3" or "oracle".
"ENGINE": "django.db.backends.postgresql_psycopg2",
# DB name or path to database file if using sqlite3.
"NAME": "%(proj_name)s",
# Not used with sqlite3.
"USER": "%(proj_name)s",
# Not used with sqlite3.
"PASSWORD": "%(db_pass)s",
# Set to empty string for localhost. Not used with sqlite3.
"HOST": "127.0.0.1",
# Set to empty string for default. Not used with sqlite3.
"PORT": "",
}
}
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https")
CACHE_MIDDLEWARE_SECONDS = 60
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.memcached.MemcachedCache",
"LOCATION": "127.0.0.1:11211",
}
}
|
Use not equal filter instead. | 'use strict';
const _ = require('lodash');
module.exports = function (Model, bootOptions = {}) {
Model.defineProperty('deleted', {
type: Boolean,
required: true,
default: false
});
/**
* @return {Promise<Model>}
*/
Model.prototype.softDelete = function () {
return this.updateAttribute('deleted', true);
}
/**
* @return {Promise<Model>}
*/
Model.prototype.restore = function () {
return this.updateAttribute('deleted', false);
}
Model.beforeRemote('find', (ctx, instance, next) => {
const scope = _.get(ctx.args, 'filter.scope', 'active');
_.unset(ctx.args, 'filter.scope');
switch (scope) {
case 'active':
_.set(ctx.args, 'filter.where.deleted.neq', true);
break;
case 'inactive':
_.set(ctx.args, 'filter.where.deleted', true);
break;
default:
_.unset(ctx.args, 'filter.where.deleted');
break;
}
process.nextTick(next);
});
}
| 'use strict';
const _ = require('lodash');
module.exports = function (Model, bootOptions = {}) {
Model.defineProperty('deleted', {
type: Boolean,
required: true,
default: false
});
/**
* @return {Promise<Model>}
*/
Model.prototype.softDelete = function () {
return this.updateAttribute('deleted', true);
}
/**
* @return {Promise<Model>}
*/
Model.prototype.restore = function () {
return this.updateAttribute('deleted', false);
}
Model.beforeRemote('find', (ctx, instance, next) => {
const scope = _.get(ctx.args, 'filter.scope', 'active');
_.unset(ctx.args, 'filter.scope');
switch (scope) {
case 'active':
_.set(ctx.args, 'filter.where.deleted', false);
break;
case 'inactive':
_.set(ctx.args, 'filter.where.deleted', true);
break;
default:
_.unset(ctx.args, 'filter.where.deleted');
break;
}
process.nextTick(next);
});
}
|
Add setitem and contains to DataStore
Adding new things to the DataStore now actually works >_> | import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = {}
self.load()
def load(self):
if not os.path.exists(self.storagePath):
self.save()
return
with open(self.storagePath) as storageFile:
self.data = json.load(storageFile)
def save(self):
tmpFile = "{}.tmp".format(self.storagePath)
with open(tmpFile, "w") as storageFile:
storageFile.write(json.dumps(self.data, indent=4))
os.rename(tmpFile, self.storagePath)
def __len__(self):
return len(self.data)
def __iter__(self):
return iter(self.data)
def __getitem__(self, item):
return self.data[item]
def __setitem__(self, key, value):
self.data[key] = value
def __contains__(self, key):
return key in self.data
| import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = {}
self.load()
def load(self):
if not os.path.exists(self.storagePath):
self.save()
return
with open(self.storagePath) as storageFile:
self.data = json.load(storageFile)
def save(self):
tmpFile = "{}.tmp".format(self.storagePath)
with open(tmpFile, "w") as storageFile:
storageFile.write(json.dumps(self.data, indent=4))
os.rename(tmpFile, self.storagePath)
def __len__(self):
return len(self.data)
def __iter__(self):
return iter(self.data)
def __getitem__(self, item):
return self.data[item]
|
Fix indentation for break keyword. | '''
Given the names and grades for each student in a Physics class of N students,
store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the same grade, order their names alphabetically and print
each name on a new line.
By HackerRank
'''
students = []
for _ in range(int(input())):
name = input()
score = float(input())
students.append([name,score])
students.sort(key=lambda x: x[1])
second_lowest_grade = students[0][1]
for name,grade in students:
if grade > second_lowest_grade:
second_lowest_grade = grade
break
names = []
for name, grade in sorted(students):
if grade == second_lowest_grade:
names.append(name)
print('\n'.join(names))
| '''
Given the names and grades for each student in a Physics class of N students,
store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the same grade, order their names alphabetically and print
each name on a new line.
By HackerRank
'''
students = []
for _ in range(int(input())):
name = input()
score = float(input())
students.append([name,score])
students.sort(key=lambda x: x[1])
second_lowest_grade = students[0][1]
for name,grade in students:
if grade > second_lowest_grade:
second_lowest_grade = grade
break
names = []
for name, grade in sorted(students):
if grade == second_lowest_grade:
names.append(name)
print('\n'.join(names))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.