text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Update footer version with env | <?php
namespace OpenDominion\Providers;
use Illuminate\Contracts\View\View;
use Illuminate\Support\ServiceProvider;
use OpenDominion\Calculators\NetworthCalculator;
use OpenDominion\Services\DominionSelectorService;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* @return void
*/
public function boot()
{
view()->composer('partials.main-footer', function (View $view) {
$env = getenv('APP_ENV');
$shortHash = shell_exec('git log --pretty="%h" -n1 HEAD');
$longHash = shell_exec('git log --pretty="%H" -n1 HEAD');
$branch = shell_exec('git branch | grep \' * \'');
$branch = str_replace('* ', '', trim($branch));
$url = "https://github.com/WaveHack/OpenDominion/commit/{$longHash}";
$view->with('version', "<strong>{$env}</strong> @ <a href=\"{$url}\" target=\"_blank\"><strong>#{$shortHash}</strong></a> ({$branch})");
});
view()->composer('partials.resources-overview', function (View $view) {
$dominionSelectorService = app()->make(DominionSelectorService::class);
$dominion = $dominionSelectorService->getUserSelectedDominion();
$networthCalculator = app()->make(NetworthCalculator::class, [$dominion]);
$view->with('networthCalculator', $networthCalculator);
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
| <?php
namespace OpenDominion\Providers;
use Illuminate\Contracts\View\View;
use Illuminate\Support\ServiceProvider;
use OpenDominion\Calculators\NetworthCalculator;
use OpenDominion\Services\DominionSelectorService;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* @return void
*/
public function boot()
{
view()->composer('partials.main-footer', function (View $view) {
$branch = shell_exec('git branch | grep \' * \'');
$branch = str_replace('* ', '', trim($branch));
$shortHash = shell_exec('git log --pretty="%h" -n1 HEAD');
$longHash = shell_exec('git log --pretty="%H" -n1 HEAD');
$url = "https://github.com/WaveHack/OpenDominion/commit/{$longHash}";
$view->with('version', "revision <a href=\"{$url}\" target=\"_blank\"><strong>#{$shortHash}</strong></a> on branch <strong>{$branch}</strong>");
});
view()->composer('partials.resources-overview', function (View $view) {
$dominionSelectorService = app()->make(DominionSelectorService::class);
$dominion = $dominionSelectorService->getUserSelectedDominion();
$networthCalculator = app()->make(NetworthCalculator::class, [$dominion]);
$view->with('networthCalculator', $networthCalculator);
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
|
Print the discovered queues in alphabetical order for convenience | from django.core.management.base import BaseCommand
from ... import app_settings
from ...utils import get_backend, load_extra_config
from ...cron_scheduler import get_cron_config
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--config', action='store', default=None,
help="The path to an additional django-style config file to load")
def handle(self, **options):
# Configuration overrides
extra_config = options['config']
if extra_config is not None:
load_extra_config(extra_config)
print("django-lightweight-queue")
print("========================")
print("")
print("{0:<55} {1:<5} {2}".format("Queue name", "Concurrency", "Backend"))
print("-" * 27)
for k, v in sorted(app_settings.WORKERS.items()):
print(" {0:<54} {1:<5} {2}".format(
k,
v,
get_backend(k).__class__.__name__,
))
print("")
print("Middleware:")
for x in app_settings.MIDDLEWARE:
print(" * %s" % x)
print("")
print("Cron configuration")
for x in get_cron_config():
print("")
for k in (
'command',
'command_args',
'hours',
'minutes',
'queue',
'timeout',
'sigkill_on_stop',
):
print("% 20s: %s" % (k, x.get(k, '-')))
| from django.core.management.base import BaseCommand
from ... import app_settings
from ...utils import get_backend, load_extra_config
from ...cron_scheduler import get_cron_config
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--config', action='store', default=None,
help="The path to an additional django-style config file to load")
def handle(self, **options):
# Configuration overrides
extra_config = options['config']
if extra_config is not None:
load_extra_config(extra_config)
print("django-lightweight-queue")
print("========================")
print("")
print("{0:<55} {1:<5} {2}".format("Queue name", "Concurrency", "Backend"))
print("-" * 27)
for k, v in app_settings.WORKERS.items():
print(" {0:<54} {1:<5} {2}".format(
k,
v,
get_backend(k).__class__.__name__,
))
print("")
print("Middleware:")
for x in app_settings.MIDDLEWARE:
print(" * %s" % x)
print("")
print("Cron configuration")
for x in get_cron_config():
print("")
for k in (
'command',
'command_args',
'hours',
'minutes',
'queue',
'timeout',
'sigkill_on_stop',
):
print("% 20s: %s" % (k, x.get(k, '-')))
|
Fix syntax error, rename manifest | const webpack = require('webpack')
const path = require('path')
const Dotenv = require('dotenv-webpack')
const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin')
const WebpackChunkHash = require('webpack-chunk-hash')
module.exports = {
entry: {
client: './src/client'
},
target: 'web',
module: {
rules: [{
test: /\.jsx?$/,
use: 'babel-loader',
include: [
path.join(__dirname, 'src')
]
}]
},
resolve: {
extensions: ['.json', '.js', '.jsx'],
alias: {
api: path.resolve(__dirname, 'src/api/')
}
},
plugins: [
new webpack.HashedModuleIdsPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.ProvidePlugin({
fetch: 'isomorphic-fetch'
}),
new Dotenv({
path: './.env',
safe: false
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function include(module) {
return module.context && module.context.indexOf('node_modules') !== -1
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
}),
new WebpackChunkHash(),
new ChunkManifestPlugin({
filename: 'chunk-manifest.json',
manifestVariable: 'webpackManifest'
})
],
output: {
path: path.join(__dirname, 'dist'),
publicPath: 'dist/',
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js'
}
}
| const webpack = require('webpack')
const path = require('path')
const Dotenv = require('dotenv-webpack')
const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin')
const WebpackChunkHash = require('webpack-chunk-hash')
module.exports = {
entry: {
client: './src/client'
},
target: 'web',
module: {
rules: [{
test: /\.jsx?$/,
use: 'babel-loader',
include: [
path.join(__dirname, 'src')
]
}]
},
resolve: {
extensions: ['.json', '.js', '.jsx'],
alias: {
api: path.resolve(__dirname, 'src/api/')
}
},
plugins: [
new webpack.HashedModuleIdsPlugin(),
new webpack.NoEmitOnErrorsPlugin()
new webpack.ProvidePlugin({
fetch: 'isomorphic-fetch'
}),
new Dotenv({
path: './.env',
safe: false
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function include(module) {
return module.context && module.context.indexOf('node_modules') !== -1
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'client.manifest',
}),
new WebpackChunkHash(),
new ChunkManifestPlugin({
filename: 'client.chunk-manifest.json',
manifestVariable: 'webpackManifest'
})
],
output: {
path: path.join(__dirname, 'dist'),
publicPath: 'dist/',
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js'
}
}
|
Reorder down() for migrate:refresh and migrate:rollback consistency | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class Scaffoldinterfaces extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('scaffoldinterfaces', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->String('package');
$table->String('migration');
$table->String('model');
$table->String('controller');
$table->String('views');
$table->String('tablename');
$table->timestamps();
});
Schema::create('relations', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('scaffoldinterface_id')->unsigned();
$table->String('to');
$table->String('having');
$table->foreign('scaffoldinterface_id')->references('id')->on('scaffoldinterfaces')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('relations');
Schema::drop('scaffoldinterfaces');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class Scaffoldinterfaces extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('scaffoldinterfaces', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->String('package');
$table->String('migration');
$table->String('model');
$table->String('controller');
$table->String('views');
$table->String('tablename');
$table->timestamps();
});
Schema::create('relations', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('scaffoldinterface_id')->unsigned();
$table->String('to');
$table->String('having');
$table->foreign('scaffoldinterface_id')->references('id')->on('scaffoldinterfaces')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('scaffoldinterfaces');
Schema::drop('relations');
}
}
|
Fix issue in SdlService constructor in hello_sdl_java_ee sample | package com.smartdevicelink;
/**
* This is a sample of how to get Java EE Bean to work with an SDL application
* The code can be uncommented out with the proper gradle dependencies added
*/
// @ServerEndpoint("/")
// @Stateful(name = "SDLSessionEJB")
public class Main {
/* Session session;
static Thread thread = null, mainThread;
static Object LOCK;
static com.smartdevicelink.SdlService sdlService;
CustomTransport websocket;
@OnOpen
public void onOpen (Session session, EndpointConfig config) {
websocket = new CustomTransport("http://localhost") {
@Override
public void onWrite(byte[] bytes, int offset, int length) {
try {
session.getBasicRemote().sendBinary(ByteBuffer.wrap(bytes));
}
catch (IOException e) {
}
}
};
this.session = session;
sdlService = new com.smartdevicelink.SdlService(new CustomTransportConfig(websocket), sdlServiceCallback);
sdlService.start();
}
@OnMessage
public void onMessage (ByteBuffer message, Session session) {
websocket.onByteBufferReceived(message);
}
static final com.smartdevicelink.SdlService.SdlServiceCallback sdlServiceCallback = new com.smartdevicelink.SdlService.SdlServiceCallback() {
@Override
public void onEnd() {
}
};
*/
}
| package com.smartdevicelink;
/**
* This is a sample of how to get Java EE Bean to work with an SDL application
* The code can be uncommented out with the proper gradle dependencies added
*/
// @ServerEndpoint("/")
// @Stateful(name = "SDLSessionEJB")
public class Main {
/* Session session;
static Thread thread = null, mainThread;
static Object LOCK;
static com.smartdevicelink.SdlService sdlService;
CustomTransport websocket;
@OnOpen
public void onOpen (Session session, EndpointConfig config) {
websocket = new CustomTransport("http://localhost") {
@Override
public void onWrite(byte[] bytes, int offset, int length) {
try {
session.getBasicRemote().sendBinary(ByteBuffer.wrap(bytes));
}
catch (IOException e) {
}
}
};
this.session = session;
sdlService = new com.smartdevicelink.SdlService(websocket, sdlServiceCallback);
sdlService.start();
}
@OnMessage
public void onMessage (ByteBuffer message, Session session) {
websocket.onByteBufferReceived(message);
}
static final com.smartdevicelink.SdlService.SdlServiceCallback sdlServiceCallback = new com.smartdevicelink.SdlService.SdlServiceCallback() {
@Override
public void onEnd() {
}
};
*/
}
|
Update admin middleware to fix permissions for adding users etc
Changed the wrong variable in the last fix. | <?php namespace JamylBot\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use JamylBot\Group;
class MustBeAdmin {
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect('/home')->with('auth_message', 'Must be logged in.');
}
}
/** @var \JamylBot\User $user */
$user = $this->auth->user();
if ($user->admin) {
return $next($request);
}
$groupId = $request->groupId ? $request->groupId : $request->group;
if ($groupId) {
/** @var Group $group */
$group = Group::find($groupId);
if ($group->isOwner($user->id)) {
return $next($request);
}
}
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect('/home')->with('auth_message', 'Access Denied');
}
}
}
| <?php namespace JamylBot\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use JamylBot\Group;
class MustBeAdmin {
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect('/home')->with('auth_message', 'Must be logged in.');
}
}
/** @var \JamylBot\User $user */
$user = $this->auth->user();
if ($user->admin) {
return $next($request);
}
$groupId = $request->group ? $request->group : $request->groups;
if ($groupId) {
/** @var Group $group */
$group = Group::find($groupId);
if ($group->isOwner($user->id)) {
return $next($request);
}
}
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect('/home')->with('auth_message', 'Access Denied');
}
}
}
|
Remove unused field from request. | import json
from ._base import get_base_rdio_client
class _RdioExportClient(object):
def __init__(self, base_client):
self.base_client = base_client
def get_current_user_key(self):
return self.base_client.call('currentUser')['key']
def get_collection_by_album(self, batch_size=100):
current_user_key = self.get_current_user_key()
start = 0
result = []
while True:
batch = self.base_client.call(
'getAlbumsInCollection',
user=current_user_key,
sort='dateAdded',
start=start,
count=batch_size,
extras=json.dumps([
{'field': '*', 'exclude': True},
{'field': 'key'},
{'field': 'trackKeys'},
]),
)
for album in batch:
yield album
if (len(batch) < batch_size):
break
else:
start += batch_size
def get_album_data(self, album_key):
return self.base_client.call(
'get',
keys=album_key,
extras=json.dumps([
{'field': '*'},
{
'field': 'track',
'extras': [
{'field': '*'},
],
},
]),
)
def get_rdio_client():
base_client = get_base_rdio_client()
return _RdioExportClient(base_client)
| import json
from ._base import get_base_rdio_client
class _RdioExportClient(object):
def __init__(self, base_client):
self.base_client = base_client
def get_current_user_key(self):
return self.base_client.call('currentUser')['key']
def get_collection_by_album(self, batch_size=100):
current_user_key = self.get_current_user_key()
start = 0
result = []
while True:
batch = self.base_client.call(
'getAlbumsInCollection',
user=current_user_key,
sort='dateAdded',
start=start,
count=batch_size,
extras=json.dumps([
{'field': '*', 'exclude': True},
{'field': 'key'},
{'field': 'artist'},
{'field': 'trackKeys'},
]),
)
for album in batch:
yield album
if (len(batch) < batch_size):
break
else:
start += batch_size
def get_album_data(self, album_key):
return self.base_client.call(
'get',
keys=album_key,
extras=json.dumps([
{'field': '*'},
{
'field': 'track',
'extras': [
{'field': '*'},
],
},
]),
)
def get_rdio_client():
base_client = get_base_rdio_client()
return _RdioExportClient(base_client)
|
Add loader functionality for jpeg, jpg and gif to webpack |
'use strict';
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: {
'vendor': ['angular','angular-animate','angular-aria','angular-messages','angular-material','angular-material-icons','@uirouter/angularjs'],
'app': path.resolve(__dirname,'src/app.js')
},
output: {
path: path.resolve(__dirname,'dist'),
filename: 'scripts/[name].js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules,libs)/,
loader: 'babel-loader', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015']
}
},
{
test: /\.html$/,
loader: 'html-loader'
},
// Extract css files
{
test: /\.(jpe?g|gif|png|svg)$/i,
loader: "file-loader?name=./images/[name].[ext]"
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor']
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname,'src/index.html')
}),
new ExtractTextPlugin("styles/[name].css"),
]
}; |
'use strict';
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: {
'vendor': ['angular','angular-animate','angular-aria','angular-messages','angular-material','angular-material-icons','@uirouter/angularjs'],
'app': path.resolve(__dirname,'src/app.js')
},
output: {
path: path.resolve(__dirname,'dist'),
filename: 'scripts/[name].js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules,libs)/,
loader: 'babel-loader', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015']
}
},
{
test: /\.html$/,
loader: 'html-loader'
},
// Extract css files
{
test: /\.(png|svg)$/,
loader: "file-loader?name=./images/[name].[ext]"
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor']
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname,'src/index.html')
}),
new ExtractTextPlugin("styles/[name].css"),
]
}; |
test: Split IAM template tests with paramtrize
See also: #208 | """Test IAM Policy templates are valid JSON."""
import json
import jinja2
import pytest
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def iam_templates():
"""Generate list of IAM templates."""
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES]))
iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([
x.startswith('infrastructure/iam/'),
'trust' not in x,
'wrapper' not in x, ]))
for iam_template_name in iam_template_names:
yield iam_template_name
@pytest.mark.parametrize(argnames='template_name', argvalues=iam_templates())
def test_all_iam_templates(template_name):
"""Verify all IAM templates render as proper JSON."""
*_, service_json = template_name.split('/')
service, *_ = service_json.split('.')
items = ['resource1', 'resource2']
if service == 'rds-db':
items = {
'resource1': 'user1',
'resource2': 'user2',
}
try:
rendered = render_policy_template(
account_number='',
app='coreforrest',
env='dev',
group='forrest',
items=items,
pipeline_settings={
'lambda': {
'vpc_enabled': False,
},
},
region='us-east-1',
service=service)
except json.decoder.JSONDecodeError:
pytest.fail('Bad template: {0}'.format(template_name), pytrace=False)
assert isinstance(rendered, list)
| """Test IAM Policy templates are valid JSON."""
import jinja2
from foremast.iam.construct_policy import render_policy_template
from foremast.utils.templates import LOCAL_TEMPLATES
def iam_templates():
"""Generate list of IAM templates."""
jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES]))
iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([
x.startswith('infrastructure/iam/'),
'trust' not in x,
'wrapper' not in x, ]))
for iam_template_name in iam_template_names:
yield iam_template_name
items = ['resource1', 'resource2']
if service == 'rds-db':
items = {
'resource1': 'user1',
'resource2': 'user2',
}
rendered = render_policy_template(
account_number='',
app='coreforrest',
env='dev',
group='forrest',
items=items,
pipeline_settings={
'lambda': {
'vpc_enabled': False,
},
},
region='us-east-1',
service=service)
assert isinstance(rendered, list)
|
Add JSHint in test target. | /*
* grunt-stamp
* https://github.com/brainkim/grunt-stamp
*
* Copyright (c) 2013 Brian Kim
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
clean: {
tests: ['tmp'],
},
copy: {
tests: {
expand: true,
src: 'test/fixtures/*',
dest: 'tmp/',
flatten: true
}
},
stamp: {
testdir: {
options: {
banner: 'banner',
footer: 'footer'
},
files: {
src: 'tmp/*'
}
},
},
nodeunit: {
tests: ['test/*_test.js'],
},
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Run stamp twice to make sure it's idempotent
grunt.registerTask('test', ['jshint', 'clean', 'copy', 'stamp', 'nodeunit']);
grunt.registerTask('default', ['test']);
};
| /*
* grunt-stamp
* https://github.com/brainkim/grunt-stamp
*
* Copyright (c) 2013 Brian Kim
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
clean: {
tests: ['tmp'],
},
copy: {
tests: {
expand: true,
src: 'test/fixtures/*',
dest: 'tmp/',
flatten: true
}
},
stamp: {
testdir: {
options: {
banner: 'banner',
footer: 'footer'
},
files: {
src: 'tmp/*'
}
},
},
nodeunit: {
tests: ['test/*_test.js'],
},
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Run stamp twice to make sure it's idempotent
grunt.registerTask('test', ['clean', 'copy', 'stamp', 'stamp', 'nodeunit']);
grunt.registerTask('default', ['jshint', 'test']);
};
|
Revert "Change careeropportunity migration dep"
This reverts commit 60fdfab7e3b557e46276c225ff159f5773930525. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('companyprofile', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CareerOpportunity',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(max_length=100, verbose_name='tittel')),
('ingress', models.CharField(max_length=250, verbose_name='ingress')),
('description', models.TextField(verbose_name='beskrivelse')),
('start', models.DateTimeField(verbose_name='aktiv fra')),
('end', models.DateTimeField(verbose_name='aktiv til')),
('featured', models.BooleanField(default=False, verbose_name='fremhevet')),
('company', models.ForeignKey(related_name='company', to='companyprofile.Company')),
],
options={
'verbose_name': 'karrieremulighet',
'verbose_name_plural': 'karrieremuligheter',
'permissions': (('view_careeropportunity', 'View CareerOpportunity'),),
},
bases=(models.Model,),
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('companyprofile', '0001_squashed_0003_company_image'),
]
operations = [
migrations.CreateModel(
name='CareerOpportunity',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(max_length=100, verbose_name='tittel')),
('ingress', models.CharField(max_length=250, verbose_name='ingress')),
('description', models.TextField(verbose_name='beskrivelse')),
('start', models.DateTimeField(verbose_name='aktiv fra')),
('end', models.DateTimeField(verbose_name='aktiv til')),
('featured', models.BooleanField(default=False, verbose_name='fremhevet')),
('company', models.ForeignKey(related_name='company', to='companyprofile.Company')),
],
options={
'verbose_name': 'karrieremulighet',
'verbose_name_plural': 'karrieremuligheter',
'permissions': (('view_careeropportunity', 'View CareerOpportunity'),),
},
bases=(models.Model,),
),
]
|
Disable mouse handling in vterm example. | #!/usr/bin/python
import urwid
def main():
event_loop = urwid.SelectEventLoop()
mainframe = urwid.Frame(
urwid.Columns([
('fixed', 3, urwid.SolidFill('|')),
urwid.Pile([
('weight', 70, urwid.TerminalWidget(None, event_loop)),
('fixed', 1, urwid.Filler(urwid.Edit('focus test edit: '))),
]),
('fixed', 3, urwid.SolidFill('|')),
], box_columns=[1]),
header=urwid.Columns([
('fixed', 3, urwid.Text('.,:')),
urwid.Divider('-'),
('fixed', 3, urwid.Text(':,.')),
]),
footer=urwid.Columns([
('fixed', 3, urwid.Text('`"*')),
urwid.Divider('-'),
('fixed', 3, urwid.Text('*"\'')),
]),
)
def quit(key):
if key in ('q', 'Q'):
raise urwid.ExitMainLoop()
loop = urwid.MainLoop(
mainframe,
handle_mouse=False,
unhandled_input=quit,
event_loop=event_loop
).run()
if __name__ == '__main__':
main()
| #!/usr/bin/python
import urwid
def main():
event_loop = urwid.SelectEventLoop()
mainframe = urwid.Frame(
urwid.Columns([
('fixed', 3, urwid.SolidFill('|')),
urwid.Pile([
('weight', 70, urwid.TerminalWidget(None, event_loop)),
('fixed', 1, urwid.Filler(urwid.Edit('focus test edit: '))),
]),
('fixed', 3, urwid.SolidFill('|')),
], box_columns=[1]),
header=urwid.Columns([
('fixed', 3, urwid.Text('.,:')),
urwid.Divider('-'),
('fixed', 3, urwid.Text(':,.')),
]),
footer=urwid.Columns([
('fixed', 3, urwid.Text('`"*')),
urwid.Divider('-'),
('fixed', 3, urwid.Text('*"\'')),
]),
)
def quit(key):
if key in ('q', 'Q'):
raise urwid.ExitMainLoop()
loop = urwid.MainLoop(
mainframe,
unhandled_input=quit,
event_loop=event_loop
).run()
if __name__ == '__main__':
main()
|
Remove extra line in line 33 | package seedu.ezdo.model.task;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import seedu.ezdo.model.todo.StartDate;
public class StartDateTest {
@Test
public void isValidStartDate() {
// invalid dates
assertFalse(StartDate.isValidTaskDate(" ")); // spaces only
assertFalse(StartDate.isValidTaskDate("next")); // non-numeric
assertFalse(StartDate.isValidTaskDate("13 12 1999")); // spaces within
// digits
assertFalse(StartDate.isValidTaskDate("05.10.1977")); // fullstops
// within digits
assertFalse(StartDate.isValidTaskDate("22/11/q2r1")); // alphabets
// within digits
// valid dates
assertTrue(StartDate.isValidTaskDate("15/12/1992 10:12")); // month with
// 31 days
assertTrue(StartDate.isValidTaskDate("11/02/2014 07:21")); // month with
// 30 days
assertTrue(StartDate.isValidTaskDate("29/02/2003 20:21")); // leap year
}
}
| package seedu.ezdo.model.task;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import seedu.ezdo.model.todo.StartDate;
public class StartDateTest {
@Test
public void isValidStartDate() {
// invalid dates
assertFalse(StartDate.isValidTaskDate(" ")); // spaces only
assertFalse(StartDate.isValidTaskDate("next")); // non-numeric
assertFalse(StartDate.isValidTaskDate("13 12 1999")); // spaces within
// digits
assertFalse(StartDate.isValidTaskDate("05.10.1977")); // fullstops
// within digits
assertFalse(StartDate.isValidTaskDate("22/11/q2r1")); // alphabets
// within digits
// valid dates
assertTrue(StartDate.isValidTaskDate("15/12/1992 10:12")); // month with
// 31 days
assertTrue(StartDate.isValidTaskDate("11/02/2014 07:21")); // month with
// 30 days
assertTrue(StartDate.isValidTaskDate("29/02/2003 20:21")); // leap year
}
}
|
Add config option for WebSockets port | var Reflux = require('reflux');
var ApiActions = require('./../actions/ApiActions');
var ConfigStore = require('./ConfigStore');
var buffer = [];
var ws = null;
var ApiStore = Reflux.createStore({
init() {
this.listenTo(ConfigStore, this.initWs);
},
initWs(config) {
var proto = 'ws';
if (config.useWssConnection === true) {
proto = 'wss';
}
var port = 80;
if (config.wsPort > 0) {
port = config.wsPort;
}
ws = new WebSocket(`${ proto }://${ window.document.location.host }:${ port }`);
ws.onmessage = event => {
ApiStore.trigger(JSON.parse(event.data));
};
ws.onopen = () => {
buffer.forEach(request => {
ws.send(JSON.stringify(request));
});
};
this.listenTo(ApiActions.get, this.get);
},
get(id, params) {
if (ws === null || ws.readyState !== WebSocket.OPEN) {
buffer.push({
id: id,
params: params || {}
});
return;
}
ws.send(JSON.stringify({
id: id,
params: params || {}
}));
}
});
module.exports = ApiStore;
| var Reflux = require('reflux');
var ApiActions = require('./../actions/ApiActions');
var ConfigStore = require('./ConfigStore');
var buffer = [];
var ws = null;
var ApiStore = Reflux.createStore({
init() {
this.listenTo(ConfigStore, this.initWs);
},
initWs(config) {
var proto = 'ws';
if (config.useWssConnection === true) {
proto = 'wss';
}
ws = new WebSocket(`${ proto }://${ window.document.location.host }`);
ws.onmessage = event => {
ApiStore.trigger(JSON.parse(event.data));
};
ws.onopen = () => {
buffer.forEach(request => {
ws.send(JSON.stringify(request));
});
};
this.listenTo(ApiActions.get, this.get);
},
get(id, params) {
if (ws === null || ws.readyState !== WebSocket.OPEN) {
buffer.push({
id: id,
params: params || {}
});
return;
}
ws.send(JSON.stringify({
id: id,
params: params || {}
}));
}
});
module.exports = ApiStore; |
Add build index modal extra changes message | import React from "react";
import { map, sortBy } from "lodash-es";
import { Row, Col, ListGroup, ListGroupItem, Panel } from "react-bootstrap";
import { LoadingPlaceholder } from "../../base";
export default function RebuildHistory ({ unbuilt, error }) {
const extraChanges = unbuilt.page_count > 1
? (
<ListGroupItem key="last-item">
<div style={{textAlign: "right"}}>
+ {unbuilt.total_count - unbuilt.per_page} more changes
</div>
</ListGroupItem>
) : null;
let content;
if (unbuilt === null) {
content = <LoadingPlaceholder margin="22px" />;
} else {
const historyComponents = map(sortBy(unbuilt.documents, "otu.name"), change =>
<ListGroupItem key={change.id}>
<Row>
<Col md={5}>
<strong>{change.otu.name}</strong>
</Col>
<Col md={7}>
{change.description || "No Description"}
</Col>
</Row>
</ListGroupItem>
);
content = (
<ListGroup style={{overflowY: "auto", maxHeight: "700px"}}>
{historyComponents}
{extraChanges}
</ListGroup>
);
}
const panelStyle = error ? "panel-danger" : "panel-default";
return (
<Panel className={panelStyle}>
<Panel.Heading>Changes</Panel.Heading>
<Panel.Body>
{content}
</Panel.Body>
</Panel>
);
}
| import React from "react";
import { map, sortBy } from "lodash-es";
import { Row, Col, ListGroup, ListGroupItem, Panel } from "react-bootstrap";
import { LoadingPlaceholder } from "../../base";
export default function RebuildHistory ({ unbuilt, error }) {
let content;
if (unbuilt === null) {
content = <LoadingPlaceholder margin="22px" />;
} else {
const historyComponents = map(sortBy(unbuilt.documents, "otu.name"), change =>
<ListGroupItem key={change.id}>
<Row>
<Col md={5}>
<strong>{change.otu.name}</strong>
</Col>
<Col md={7}>
{change.description || "No Description"}
</Col>
</Row>
</ListGroupItem>
);
content = (
<ListGroup style={{overflowY: "auto", maxHeight: "700px"}}>
{historyComponents}
</ListGroup>
);
}
const panelStyle = error ? "panel-danger" : "panel-default";
return (
<Panel className={panelStyle}>
<Panel.Heading>Changes</Panel.Heading>
<Panel.Body>
{content}
</Panel.Body>
</Panel>
);
}
|
Fix import and indent issue | import hashlib
import models
import os
import os.path
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.read(8192)
return h.hexdigest()
def traverse(path):
path = os.path.abspath(path)
for (dir_path, dirs, files) in os.walk(path):
buf = []
for file_name in sorted(files):
file_path = os.path.join(dir_path, file_name)
entry = {
'path': file_path,
'size': os.path.getsize(file_path),
'last_modified': os.path.getmtime(file_path),
'hash_str': digest(file_path)
}
buf.append(entry)
if len(buf) >= 256:
print('Writing chunks until', file_name)
models.Entry.insert_many(buf).execute()
buf.clear()
def reduce():
from models import Entry
from peewee import fn, SQL
duplicates = (Entry
.select(Entry.hash_str, fn.COUNT(Entry.hash_str).alias('occurrence'))
.group_by(Entry.hash_str)
.having(SQL('occurrence') > 1))
return duplicates
| import hashlib
import models
import os
import os.path
import peewee
def init():
models.db.connect()
models.db.create_tables([models.Entry])
def digest(file_path):
h = hashlib.sha1()
file = open(file_path, 'rb')
buf = file.read(8192)
while len(buf) > 0:
h.update(buf)
buf = file.read(8192)
return h.hexdigest()
def traverse(path):
path = os.path.abspath(path)
for (dir_path, dirs, files) in os.walk(path):
buf = []
for file_name in sorted(files):
file_path = os.path.join(dir_path, file_name)
entry = {
'path': file_path,
'size': os.path.getsize(file_path),
'last_modified': os.path.getmtime(file_path),
'hash_str': digest(file_path)
}
buf.append(entry)
if len(buf) >= 256:
print('Writing chunks until', file_name)
models.Entry.insert_many(buf).execute()
buf.clear()
def reduce():
from models import Entry
from peewee import fn, SQL
duplicates = Entry
.select(Entry.hash_str, fn.COUNT(Entry.hash_str).alias('occurrence'))
.group_by(Entry.hash_str).having(SQL('occurrence') > 1)
return duplicates
|
Remove unneeded import of dataService | 'use strict';
/**
* @ngdoc directive
* @name midjaApp.directive:googlechart
* @description
* # googlechart
*/
angular.module('midjaApp')
.directive('googlechart', function() {
return {
template: '<div style="height:{{ minHeight }}px;"></div>',
restrict: 'E',
link: link,
replace: true,
scope: {
data: '=',
chartobj: '='
}
};
function link(scope, element, attrs) {
var minHeight = 500;
// export a chartobj back for triggers
scope.chartobj = {};
activate();
scope.chartobj.redraw = redraw;
function activate() {
scope.minHeight = minHeight;
scope.$watch('data', drawStuff);
}
var options = {
legend: {
position: "none"
},
bars: 'horizontal'
};
function drawStuff(data) {
if (!data) {
return;
}
if (!data.length) {
return;
}
if (!scope.data) {
element.html('');
return;
}
var chart = new google.charts.Bar(element[0]);
chart.draw(new google.visualization.arrayToDataTable(data), options);
scope.chartobj.chart = chart;
}
function redraw() {
scope.chartobj.chart.draw(new google.visualization.arrayToDataTable(
scope.data), options);
}
}
});
| 'use strict';
/**
* @ngdoc directive
* @name midjaApp.directive:googlechart
* @description
* # googlechart
*/
angular.module('midjaApp')
.directive('googlechart', function(dataService) {
return {
template: '<div style="height:{{ minHeight }}px;"></div>',
restrict: 'E',
link: link,
replace: true,
scope: {
data: '=',
chartobj: '='
}
};
function link(scope, element, attrs) {
var minHeight = 500;
// export a chartobj back for triggers
scope.chartobj = {};
activate();
scope.chartobj.redraw = redraw;
function activate() {
scope.minHeight = minHeight;
scope.$watch('data', drawStuff);
}
var options = {
legend: {
position: "none"
},
bars: 'horizontal'
};
function drawStuff(data) {
if (!data) {
return;
}
if (!data.length) {
return;
}
if (!scope.data) {
element.html('');
return;
}
var chart = new google.charts.Bar(element[0]);
chart.draw(new google.visualization.arrayToDataTable(data), options);
scope.chartobj.chart = chart;
}
function redraw() {
scope.chartobj.chart.draw(new google.visualization.arrayToDataTable(
scope.data), options);
}
}
});
|
Remove transactionTypes table and specify column nullablility |
exports.up = (knex, Promise) => Promise.all([
knex.schema.createTable('users', table => {
table.uuid('id')
.primary()
.defaultTo(knex.raw('uuid_generate_v4()'));
table.string('username', 20)
.notNullable()
.unique();
table.string('password')
.notNullable();
table.float('saldo')
.notNullable()
.defaultTo(0);
}),
knex.schema.createTable('transactions', table => {
table.increments('id')
.primary();
table.uuid('userId')
.notNullable()
.references('id')
.inTable('users')
.onDelete('SET NULL');
table.timestamp('timestamp')
.defaultTo(knex.raw('now()'));
table.float('oldSaldo')
.notNullable();
table.float('newSaldo')
.notNullable();
table.string('comment')
.nullable();
})
]);
exports.down = (knex, Promise) => Promise.all([
knex.schema.dropTable('transactions'),
knex.schema.dropTable('users')
]);
|
exports.up = (knex, Promise) => Promise.all([
knex.schema.createTable('users', table => {
table.uuid('id')
.primary()
.defaultTo(knex.raw('uuid_generate_v4()'));
table.string('username', 20)
.unique();
table.string('password');
table.float('saldo')
.defaultTo(0);
}),
knex.schema.createTable('transactionTypes', table => {
table.increments('id')
.primary();
table.string('typename');
}),
knex.schema.createTable('transactions', table => {
table.increments('id')
.primary();
table.integer('typeId')
.unsigned()
.references('id')
.inTable('transactionTypes')
.onDelete('SET NULL');
table.uuid('userId')
.references('id')
.inTable('users')
.onDelete('SET NULL');
table.timestamp('timestamp')
.defaultTo(knex.raw('now()'));
table.float('oldSaldo');
table.float('newSaldo');
table.string('comment');
})
]);
exports.down = (knex, Promise) => Promise.all([
knex.schema.dropTable('transactions'),
knex.schema.dropTable('users'),
knex.schema.dropTable('transactionTypes')
]);
|
Check for the specific error being thrown | <?php
class ArraysTest extends \PHPUnit\Framework\TestCase
{
public function testFlatten()
{
$this->assertEquals(
['a', 'b', 'c', 'd'],
Missing\Arrays::flatten([
['a', 'b'],
'c',
[[['d']]],
])
);
}
public function testSortByInt()
{
$this->assertEquals(
['a', 'a', 'ab', 'abc', 'abcd'],
Missing\Arrays::sortBy(
['abcd', 'ab', 'a', 'abc', 'a'],
function ($a) {
return strlen($a);
}
)
);
}
public function testSortByString()
{
$this->assertEquals(
['a333', 'b22', 'c1', 'd55555'],
Missing\Arrays::sortBy(
['d55555', 'b22', 'a333', 'c1'],
function ($a) {
return $a;
}
)
);
}
public function testSortByArray()
{
$this->assertEquals(
[[2, 'b'], [2, 'c'], [19, 'a']],
Missing\Arrays::sortBy(
[[19, 'a'], [2, 'c'], [2, 'b']],
function ($a) {
return $a;
}
)
);
}
public function testSortByTriggersError()
{
$this->expectException(\TypeError::class);
Missing\Arrays::sortBy(function () {
}, []);
}
}
| <?php
class ArraysTest extends \PHPUnit\Framework\TestCase
{
public function testFlatten()
{
$this->assertEquals(
['a', 'b', 'c', 'd'],
Missing\Arrays::flatten([
['a', 'b'],
'c',
[[['d']]],
])
);
}
public function testSortByInt()
{
$this->assertEquals(
['a', 'a', 'ab', 'abc', 'abcd'],
Missing\Arrays::sortBy(
['abcd', 'ab', 'a', 'abc', 'a'],
function ($a) {
return strlen($a);
}
)
);
}
public function testSortByString()
{
$this->assertEquals(
['a333', 'b22', 'c1', 'd55555'],
Missing\Arrays::sortBy(
['d55555', 'b22', 'a333', 'c1'],
function ($a) {
return $a;
}
)
);
}
public function testSortByArray()
{
$this->assertEquals(
[[2, 'b'], [2, 'c'], [19, 'a']],
Missing\Arrays::sortBy(
[[19, 'a'], [2, 'c'], [2, 'b']],
function ($a) {
return $a;
}
)
);
}
public function testSortByTriggersError()
{
$this->expectException(\PHPUnit\Framework\Error\Error::class);
Missing\Arrays::sortBy(function () {
}, []);
}
}
|
BAP-12112: Add migration to update current workflow definitions
- added save of step labels | <?php
namespace Oro\Bundle\WorkflowBundle\Migrations\Data\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowDefinition;
use Oro\Bundle\WorkflowBundle\Translation\TranslationProcessor;
class UpdateDefinitionTranslations extends AbstractFixture implements ContainerAwareInterface
{
use ContainerAwareTrait;
/**
* {@inheritdoc}
*/
public function load(ObjectManager $manager)
{
/* @var $processor TranslationProcessor */
$processor = $this->container->get('oro_workflow.translation.processor');
/* @var $definitions WorkflowDefinition[] */
$definitions = $manager->getRepository(WorkflowDefinition::class)->findBy(['system' => false]);
foreach ($definitions as $definition) {
$configuration = $this->process($processor, $definition);
$definition->setConfiguration($configuration);
$definition->setLabel($configuration['label']);
foreach ($definition->getSteps() as $step) {
$step->setLabel($configuration['steps'][$step->getName()]['label']);
}
}
$manager->flush();
}
/**
* @param TranslationProcessor $processor
* @param WorkflowDefinition $definition
* @return array
*/
protected function process(TranslationProcessor $processor, WorkflowDefinition $definition)
{
$configuration = array_merge(
$definition->getConfiguration(),
[
'name' => $definition->getName(),
'label' => $definition->getLabel(),
]
);
return $processor->prepare($definition->getName(), $processor->handle($configuration));
}
}
| <?php
namespace Oro\Bundle\WorkflowBundle\Migrations\Data\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Oro\Bundle\WorkflowBundle\Entity\WorkflowDefinition;
use Oro\Bundle\WorkflowBundle\Translation\TranslationProcessor;
class UpdateDefinitionTranslations extends AbstractFixture implements ContainerAwareInterface
{
use ContainerAwareTrait;
/**
* {@inheritdoc}
*/
public function load(ObjectManager $manager)
{
/* @var $processor TranslationProcessor */
$processor = $this->container->get('oro_workflow.translation.processor');
/* @var $definitions WorkflowDefinition[] */
$definitions = $manager->getRepository(WorkflowDefinition::class)->findBy(['system' => false]);
foreach ($definitions as $definition) {
$configuration = $this->process($processor, $definition);
$definition->setConfiguration($configuration);
$definition->setLabel($configuration['label']);
}
$manager->flush();
}
/**
* @param TranslationProcessor $processor
* @param WorkflowDefinition $definition
* @return array
*/
protected function process(TranslationProcessor $processor, WorkflowDefinition $definition)
{
$configuration = array_merge(
$definition->getConfiguration(),
[
'name' => $definition->getName(),
'label' => $definition->getLabel(),
]
);
return $processor->prepare($definition->getName(), $processor->handle($configuration));
}
}
|
Add const for error message of not logged in user | <?php
namespace AppBundle\API;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class Webservice
{
const ERROR_NOT_LOGGED_IN = "Error. Not logged in.";
private $DB;
public function __construct(\AppBundle\DB $DB)
{
$this->DB = $DB;
}
/**
* @param ParameterBag $query
* @param SessionInterface $session
* @return array result
*/
public function execute(ParameterBag $query, SessionInterface $session = null){
return array();
}
/**
* @param $namespace string
* @param $classname string
* @return Webservice|null
*/
public function factory($namespace, $classname)
{
$serviceNamespace = '\\AppBundle\\API\\' . ucfirst($namespace);
$class = $serviceNamespace . '\\' . ucfirst($classname);
if (!class_exists($class)) {
return null;
}
return new $class($this->DB);
}
/**
* @param $query ParameterBag
* @return \PDO db connection
*/
protected function getDbFromQuery($query){
if (! $query->has('dbversion')){
throw new Exception('No valid dbversion provided');
}
return $this->DB->getDbForVersion($query->get('dbversion'));
}
} | <?php
namespace AppBundle\API;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class Webservice
{
private $DB;
public function __construct(\AppBundle\DB $DB)
{
$this->DB = $DB;
}
/**
* @param ParameterBag $query
* @param SessionInterface $session
* @return array result
*/
public function execute(ParameterBag $query, SessionInterface $session = null){
return array();
}
/**
* @param $namespace string
* @param $classname string
* @return Webservice|null
*/
public function factory($namespace, $classname)
{
$serviceNamespace = '\\AppBundle\\API\\' . ucfirst($namespace);
$class = $serviceNamespace . '\\' . ucfirst($classname);
if (!class_exists($class)) {
return null;
}
return new $class($this->DB);
}
/**
* @param $query ParameterBag
* @return \PDO db connection
*/
protected function getDbFromQuery($query){
if (! $query->has('dbversion')){
throw new Exception('No valid dbversion provided');
}
return $this->DB->getDbForVersion($query->get('dbversion'));
}
} |
Upgrade to support Django 1.7 | from django_rocket import __version__, __author__, __email__, __license__
from setuptools import setup, find_packages
README = open('README.rst').read()
# Second paragraph has the short description
description = README.split('\n')[1]
setup(
name='django-rocket',
version=__version__,
description=description,
long_description=README,
author=__author__,
author_email=__email__,
license=__license__,
url='https://github.com/mariocesar/django-rocket',
download_url='https://pypi.python.org/pypi/django-rocket',
packages=find_packages(exclude=['tests', 'tests.*', 'example', 'docs', 'env']),
install_requires=[
'django>1.5,<1.8',
'wheel',
],
extras_require={
'develop': ["coverage", "sphinx", "sphinx_rtd_theme"],
},
zip_safe=False,
classifiers=[
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django'
]
)
| from django_rocket import __version__, __author__, __email__, __license__
from setuptools import setup, find_packages
README = open('README.rst').read()
# Second paragraph has the short description
description = README.split('\n')[1]
setup(
name='django-rocket',
version=__version__,
description=description,
long_description=README,
author=__author__,
author_email=__email__,
license=__license__,
url='https://github.com/mariocesar/django-rocket',
download_url='https://pypi.python.org/pypi/django-rocket',
packages=find_packages(exclude=['tests', 'tests.*', 'example', 'docs', 'env']),
install_requires=[
'django>1.5,<1.7',
'wheel',
],
extras_require={
'Docs': ["sphinx", "sphinx_rtd_theme"],
'develop': ["coverage"],
},
zip_safe=False,
classifiers=[
'Operating System :: OS Independent',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django'
]
)
|
Fix newline handling in autoreload test | from __future__ import absolute_import, division, print_function
import os
import subprocess
from subprocess import Popen
import sys
from tempfile import mkdtemp
from tornado.test.util import unittest
MAIN = """\
import os
import sys
from tornado import autoreload
# This import will fail if path is not set up correctly
import testapp
print('Starting')
if 'TESTAPP_STARTED' not in os.environ:
os.environ['TESTAPP_STARTED'] = '1'
sys.stdout.flush()
autoreload._reload()
"""
class AutoreloadTest(unittest.TestCase):
def test_reload_module(self):
# Create temporary test application
path = mkdtemp()
os.mkdir(os.path.join(path, 'testapp'))
open(os.path.join(path, 'testapp/__init__.py'), 'w').close()
with open(os.path.join(path, 'testapp/__main__.py'), 'w') as f:
f.write(MAIN)
# Make sure the tornado module under test is available to the test
# application
pythonpath = os.getcwd()
if 'PYTHONPATH' in os.environ:
pythonpath += os.pathsep + os.environ['PYTHONPATH']
p = Popen(
[sys.executable, '-m', 'testapp'], stdout=subprocess.PIPE,
cwd=path, env=dict(os.environ, PYTHONPATH=pythonpath),
universal_newlines=True)
out = p.communicate()[0]
self.assertEqual(out, 'Starting\nStarting\n')
| from __future__ import absolute_import, division, print_function
import os
import subprocess
from subprocess import Popen
import sys
from tempfile import mkdtemp
from tornado.test.util import unittest
MAIN = """\
import os
import sys
from tornado import autoreload
# This import will fail if path is not set up correctly
import testapp
print('Starting')
if 'TESTAPP_STARTED' not in os.environ:
os.environ['TESTAPP_STARTED'] = '1'
sys.stdout.flush()
autoreload._reload()
"""
class AutoreloadTest(unittest.TestCase):
def test_reload_module(self):
# Create temporary test application
path = mkdtemp()
os.mkdir(os.path.join(path, 'testapp'))
open(os.path.join(path, 'testapp/__init__.py'), 'w').close()
with open(os.path.join(path, 'testapp/__main__.py'), 'w') as f:
f.write(MAIN)
# Make sure the tornado module under test is available to the test
# application
pythonpath = os.getcwd()
if 'PYTHONPATH' in os.environ:
pythonpath += os.pathsep + os.environ['PYTHONPATH']
p = Popen([sys.executable, '-m', 'testapp'], stdout=subprocess.PIPE,
cwd=path, env=dict(os.environ, PYTHONPATH=pythonpath))
out = p.communicate()[0].decode()
self.assertEqual(out, 'Starting\nStarting\n')
|
Add more verbose to HTTP events | <?php
namespace Athena\Event\Adapter;
use Athena\Event\HttpTransactionCompleted;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
class GuzzleReportMiddleware
{
public static function eventCapture(EventDispatcher $emitter)
{
return function (callable $handler) use ($emitter) {
return function (RequestInterface $request, array $options) use ($handler, $emitter) {
$promise = $handler($request, $options);
return $promise->then(
function (ResponseInterface $response) use ($handler, $request, $emitter) {
$emitter->dispatch(HttpTransactionCompleted::AFTER,
new HttpTransactionCompleted(
(string) static::formatRequest($request),
(string) static::formatResponse($response),
(string) $request->getUri(),
$request->getMethod()
)
);
return $response;
}
);
};
};
}
private function formatRequest(RequestInterface $message)
{
$method = $message->getMethod();
$target = $message->getRequestTarget();
$headers = static::formatHeaders($message->getHeaders());
$body = $message->getBody()->getContents();
$message->getBody()->rewind();
return <<<EOF
$method $target
$headers
$body
EOF;
}
private static function formatHeaders(array $headers)
{
$string = "";
foreach ($headers as $key => $value) {
$string .= sprintf("%s: %s", $key, implode("\n", $value))."\n";
}
return $string;
}
private function formatResponse(ResponseInterface $response)
{
$reason = $response->getReasonPhrase();
$version = $response->getProtocolVersion();
$status = $response->getStatusCode();
$headers = static::formatHeaders($response->getHeaders());
$body = $response->getBody()->getContents();
$response->getBody()->rewind();
return <<<EOF
HTTP/$version $status $reason
$headers
$body
EOF;
}
} | <?php
namespace Athena\Event\Adapter;
use Athena\Event\HttpTransactionCompleted;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
class GuzzleReportMiddleware
{
public static function eventCapture(EventDispatcher $emitter)
{
return function (callable $handler) use ($emitter) {
return function (RequestInterface $request, array $options) use ($handler, $emitter) {
$promise = $handler($request, $options);
return $promise->then(
function (ResponseInterface $response) use ($handler, $request, $emitter) {
$requestBody = $request->getBody()->getContents();
$responseBody = $response->getBody()->getContents();
$request->getBody()->rewind();
$response->getBody()->rewind();
$emitter->dispatch(HttpTransactionCompleted::AFTER,
new HttpTransactionCompleted(
(string) $requestBody,
(string) $responseBody,
(string) $request->getUri(),
$request->getMethod()
)
);
return $response;
}
);
};
};
}
} |
Fix build errors when using optional switches. | module.exports = function(grunt) {
//"use strict";
//This is disabled because it's picking up octal literal notation that is quoted in a string.
//usage: grunt [server | watch | (--minify &| --syncload)]
//server: Start a testing server for the website.
//watch: Automatically recompile part of the project when files are changed.
//--minify: Compress the build. (Has no effect when server option in use.)
// Compile a list of paths and output files for our modules for requirejs to compile.
// TODO: Translate the command-line code to this.
grunt.initConfig({
requirejs: {
compile: {
options: {
mainConfigFile: "rjs_require_config.js",
name: "Readium",
optimize: grunt.option('minify')?"uglify":"none",
out: "out/Readium" +
(grunt.option('syncload')?".syncload":"") +
(grunt.option('minify')?".min":"") + ".js",
include: grunt.option('syncload')?"epub-modules/readium-js/src/define-sync":undefined,
almond: grunt.option('minify'),
wrap: grunt.option('syncload')?{
start: "(function (root, ReadiumModuleFactory) {\nroot.Readium = ReadiumModuleFactory();\n}(this, function () {",
end: "var Readium = require('Readium');\nreturn Readium;\n}));",
}:undefined
}
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['requirejs']);
};
| module.exports = function(grunt) {
//"use strict";
//This is disabled because it's picking up octal literal notation that is quoted in a string.
//usage: grunt [server | watch | (--minify &| --syncload)]
//server: Start a testing server for the website.
//watch: Automatically recompile part of the project when files are changed.
//--minify: Compress the build. (Has no effect when server option in use.)
// Compile a list of paths and output files for our modules for requirejs to compile.
// TODO: Translate the command-line code to this.
grunt.initConfig({
requirejs: {
compile: {
options: {
mainConfigFile: "rjs_require_config.js",
name: "Readium",
optimize: grunt.option('minify')?undefined:"none",
out: "out/Readium" +
(grunt.option('syncload')?".syncload":"") +
(grunt.option('minify')?".min":"") + ".js",
include: grunt.option('syncload')?"define-sync":undefined,
almond: grunt.option('minify')
}
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['requirejs']);
}; |
Fix error where self.config was undefined
These decorators are harsh | import zirc
import ssl
import socket
import utils
import commands
debug = False
class Bot(zirc.Client):
def __init__(self):
self.connection = zirc.Socket(family=socket.AF_INET6,
wrapper=ssl.wrap_socket)
self.config = zirc.IRCConfig(host="chat.freenode.net",
port=6697,
nickname="zIRCBot2",
ident="zirc",
realname="A zIRC bot",
channels=["##wolfy1339", "##powder-bots"],
sasl_user="BigWolfy1339",
sasl_pass="")
self.connect(self.config)
self.start()
@staticmethod
def on_ctcp(irc, raw):
utils.print_(raw, flush=True)
@classmethod
def on_privmsg(self, event, irc, arguments):
if " ".join(arguments).startswith("?"):
utils.call_command(self, event, irc, arguments)
def on_all(self, event, irc):
if debug:
utils.print_(event.raw, flush=True)
def on_send(self, event, irc):
if debug:
utils.print_(event.raw, flush=True)
def on_nicknameinuse(self, event, irc):
irc.nick(self.config['nickname'] + "_")
Bot()
| import zirc
import ssl
import socket
import utils
import commands
debug = False
class Bot(zirc.Client):
def __init__(self):
self.connection = zirc.Socket(family=socket.AF_INET6,
wrapper=ssl.wrap_socket)
self.config = zirc.IRCConfig(host="chat.freenode.net",
port=6697,
nickname="zIRCBot2",
ident="zirc",
realname="A zIRC bot",
channels=["##wolfy1339", "##powder-bots"],
sasl_user="BigWolfy1339",
sasl_pass="")
self.connect(self.config)
self.start()
@staticmethod
def on_ctcp(irc, raw):
utils.print_(raw, flush=True)
@classmethod
def on_privmsg(self, event, irc, arguments):
if " ".join(arguments).startswith("?"):
utils.call_command(self, event, irc, arguments)
@classmethod
def on_all(self, event, irc):
if debug:
utils.print_(event.raw, flush=True)
@classmethod
def on_send(self, event, irc):
if debug:
utils.print_(event.raw, flush=True)
@classmethod
def on_nicknameinuse(self, event, irc):
irc.nick(bot.config['nickname'] + "_")
Bot()
|
Revert bad renaming of route url parameter | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <[email protected]>
#
# The licence is in the file __manifest__.py
#
##############################################################################
import logging
from odoo import http
from odoo.http import request
from odoo.addons.sbc_compassion.controllers.b2s_image import RestController
_logger = logging.getLogger(__name__)
class B2sControllerSwitzerland(RestController):
@http.route('/b2s_image', type='http', auth='public', methods=['GET'])
def handler_b2s_image(self, id=None):
"""
URL for downloading a correspondence PDF
(or ZIP when multiple letters are attached).
Find the associated communication and mark all related letters
as opened and read.
:param image_id: uuid of the correspondence holding the data.
:return: file data for user
"""
res = super(B2sControllerSwitzerland, self).handler_b2s_image(id)
correspondence_obj = request.env['correspondence'].sudo()
correspondence = correspondence_obj.search([('uuid', '=', id)])
if correspondence.communication_id:
all_letters = correspondence.communication_id.get_objects()
all_letters.write({
'letter_delivered': True,
'email_read': True
})
return res
| # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <[email protected]>
#
# The licence is in the file __manifest__.py
#
##############################################################################
import logging
from odoo import http
from odoo.http import request
from odoo.addons.sbc_compassion.controllers.b2s_image import RestController
_logger = logging.getLogger(__name__)
class B2sControllerSwitzerland(RestController):
@http.route('/b2s_image', type='http', auth='public', methods=['GET'])
def handler_b2s_image(self, image_id=None):
"""
URL for downloading a correspondence PDF
(or ZIP when multiple letters are attached).
Find the associated communication and mark all related letters
as opened and read.
:param image_id: uuid of the correspondence holding the data.
:return: file data for user
"""
res = super(B2sControllerSwitzerland, self).handler_b2s_image(image_id)
correspondence_obj = request.env['correspondence'].sudo()
correspondence = correspondence_obj.search([('uuid', '=', image_id)])
if correspondence.communication_id:
all_letters = correspondence.communication_id.get_objects()
all_letters.write({
'letter_delivered': True,
'email_read': True
})
return res
|
Update St. Olaf calendar URL
We have changed calendar backend systems, so the old URL will go away soon. This is, I believe, the new ID for the master St. Olaf calendar.
It has the (dis)advantage of including Alumni and Athletics events, but we're not sure how to exclude them yet. | // @flow
/**
* All About Olaf
* Calendar page
*/
import React from 'react'
import {TabNavigator} from '../components/tabbed-view'
import {TabBarIcon} from '../components/tabbar-icon'
import {GoogleCalendarView} from './calendar-google'
export {EventDetail} from './event-detail'
export default TabNavigator(
{
StOlafCalendarView: {
screen: ({navigation}) => (
<GoogleCalendarView
navigation={navigation}
calendarId=" [email protected]"
/>
),
navigationOptions: {
tabBarLabel: 'St. Olaf',
tabBarIcon: TabBarIcon('school'),
},
},
OlevilleCalendarView: {
screen: ({navigation}) => (
<GoogleCalendarView
navigation={navigation}
calendarId="[email protected]"
/>
),
navigationOptions: {
tabBarLabel: 'Oleville',
tabBarIcon: TabBarIcon('happy'),
},
},
NorthfieldCalendarView: {
screen: ({navigation}) => (
<GoogleCalendarView
navigation={navigation}
calendarId="[email protected]"
/>
),
navigationOptions: {
tabBarLabel: 'Northfield',
tabBarIcon: TabBarIcon('pin'),
},
},
},
{
navigationOptions: {
title: 'Calendar',
},
},
)
| // @flow
/**
* All About Olaf
* Calendar page
*/
import React from 'react'
import {TabNavigator} from '../components/tabbed-view'
import {TabBarIcon} from '../components/tabbar-icon'
import {GoogleCalendarView} from './calendar-google'
export {EventDetail} from './event-detail'
export default TabNavigator(
{
StOlafCalendarView: {
screen: ({navigation}) => (
<GoogleCalendarView
navigation={navigation}
calendarId="[email protected]"
/>
),
navigationOptions: {
tabBarLabel: 'St. Olaf',
tabBarIcon: TabBarIcon('school'),
},
},
OlevilleCalendarView: {
screen: ({navigation}) => (
<GoogleCalendarView
navigation={navigation}
calendarId="[email protected]"
/>
),
navigationOptions: {
tabBarLabel: 'Oleville',
tabBarIcon: TabBarIcon('happy'),
},
},
NorthfieldCalendarView: {
screen: ({navigation}) => (
<GoogleCalendarView
navigation={navigation}
calendarId="[email protected]"
/>
),
navigationOptions: {
tabBarLabel: 'Northfield',
tabBarIcon: TabBarIcon('pin'),
},
},
},
{
navigationOptions: {
title: 'Calendar',
},
},
)
|
Remove unnecessary value on inline prop | import React from 'react';
import { FormattedMessage, FormattedNumber } from 'react-intl';
import { Button, Popover, Position, Spinner } from '@blueprintjs/core';
const SearchFilterCountries = ({ loaded, countries, currentValue, onOpen, onChange }) => {
function toggleCountryId(countryId) {
const newValue = currentValue.indexOf(countryId) > -1 ?
currentValue.filter(i => i !== countryId) : [...currentValue, countryId];
onChange(newValue);
}
return (
<Popover position={Position.BOTTOM} popoverWillOpen={onOpen} inline>
<Button rightIconName="caret-down">
<FormattedMessage id="search.countries" defaultMessage="Countries"/>
{loaded && <span> (<FormattedNumber value={countries.length} />)</span>}
</Button>
<div className="search-filter-countries">
{loaded ?
<ul className="search-filter-countries-list">
{countries.map(country => (
<li onClick={toggleCountryId.bind(null, country.id)} key={country.id}>
<span className="pt-icon-standard pt-icon-tick"
style={{'visibility': currentValue.indexOf(country.id) > -1 ? 'visible': 'hidden'}} />
{country.label}
</li>
))}
</ul> :
<Spinner className="pt-large" />}
</div>
</Popover>
);
};
export default SearchFilterCountries;
| import React from 'react';
import { FormattedMessage, FormattedNumber } from 'react-intl';
import { Button, Popover, Position, Spinner } from '@blueprintjs/core';
const SearchFilterCountries = ({ loaded, countries, currentValue, onOpen, onChange }) => {
function toggleCountryId(countryId) {
const newValue = currentValue.indexOf(countryId) > -1 ?
currentValue.filter(i => i !== countryId) : [...currentValue, countryId];
onChange(newValue);
}
return (
<Popover position={Position.BOTTOM} popoverWillOpen={onOpen} inline={true}>
<Button rightIconName="caret-down">
<FormattedMessage id="search.countries" defaultMessage="Countries"/>
{loaded && <span> (<FormattedNumber value={countries.length} />)</span>}
</Button>
<div className="search-filter-countries">
{loaded ?
<ul className="search-filter-countries-list">
{countries.map(country => (
<li onClick={toggleCountryId.bind(null, country.id)} key={country.id}>
<span className="pt-icon-standard pt-icon-tick"
style={{'visibility': currentValue.indexOf(country.id) > -1 ? 'visible': 'hidden'}} />
{country.label}
</li>
))}
</ul> :
<Spinner className="pt-large" />}
</div>
</Popover>
);
};
export default SearchFilterCountries;
|
Remove Head/Tail conflict in form.java | package com.google.sps.data;
import java.io.*;
import com.google.appengine.api.datastore.Entity;
public class Form {
private String editURL;
private String URL;
private String id;
private boolean isPublished;
public Form(String editURL, String URL, String id) {
this.editURL = editURL;
this.URL = URL;
this.id = id;
this.isPublished = false;
}
public Form(Entity entity){
this.editURL = (String) entity.getProperty("editURL");
this.URL = (String) entity.getProperty("URL");
this.id = (String) entity.getProperty("id");
this.isPublished = Boolean.parseBoolean((String) entity.getProperty("isPublished"));
}
// Getters
public String getEditURL() {
return this.editURL;
}
public String getURL() {
return this.URL;
}
public String getID() {
return this.id;
}
public boolean isPublished() {
return this.isPublished;
}
// Setters
public void publish(){
this.isPublished = true;
}
public void unpublish(){
this.isPublished = false;
}
public Entity toDatastoreEntity(){
Entity formEntity = new Entity("Form");
formEntity.setProperty("editURL", this.editURL);
formEntity.setProperty("URL", this.URL);
formEntity.setProperty("id", this.id);
formEntity.setProperty("isPublished", this.isPublished);
return formEntity;
}
} | package com.google.sps.data;
import java.io.*;
import com.google.appengine.api.datastore.Entity;
public class Form {
private String editURL;
private String URL;
private String id;
private boolean isPublished;
public Form(String editURL, String URL, String id) {
this.editURL = editURL;
this.URL = URL;
this.id = id;
this.isPublished = false;
}
public Form(Entity entity){
this.editURL = (String) entity.getProperty("editURL");
this.URL = (String) entity.getProperty("URL");
this.id = (String) entity.getProperty("id");
this.isPublished = Boolean.parseBoolean((String) entity.getProperty("isPublished"));
}
// Getters
public String getEditURL() {
return this.editURL;
}
public String getURL() {
return this.URL;
}
public String getID() {
return this.id;
}
public boolean isPublished() {
return this.isPublished;
}
// Setters
public void publish(){
this.isPublished = true;
}
public void unpublish(){
this.isPublished = false;
}
public Entity toDatastoreEntity(){
Entity formEntity = new Entity("Form");
formEntity.setProperty("editURL", this.editURL);
formEntity.setProperty("URL", this.URL);
formEntity.setProperty("id", this.id);
<<<<<<< HEAD
formEntity.setProperty("isPublished", this.isPublished);
=======
>>>>>>> MVP-K
return formEntity;
}
} |
Change tooltip to "Question Grid" | export default class {
constructor($scope, auth, toast) {
'ngInject';
$scope.buttons = [
{
name: 'View Code',
icon: 'code',
show: true,
href: 'https://github.com/mjhasbach/material-qna'
},
{
name: 'Question Grid',
icon: 'grid_on',
get show() {
return $scope.user.data && $scope.view.current !== 'qna';
},
onClick: function() {
$scope.view.current = 'qna';
}
},
{
name: 'Dashboard',
icon: 'view_list',
get show() {
return $scope.user.data && $scope.view.current !== 'dashboard';
},
onClick: function() {
$scope.view.current = 'dashboard';
}
},
{
name: 'Logout',
icon: 'exit_to_app',
get show() {
return $scope.user.data;
},
onClick: function() {
auth.logout().then(function() {
$scope.user.data = null;
$scope.view.current = 'auth';
}).catch(function() {
toast.show('Unable to log out');
});
}
}
];
}
} | export default class {
constructor($scope, auth, toast) {
'ngInject';
$scope.buttons = [
{
name: 'View Code',
icon: 'code',
show: true,
href: 'https://github.com/mjhasbach/material-qna'
},
{
name: 'QnA',
icon: 'grid_on',
get show() {
return $scope.user.data && $scope.view.current !== 'qna';
},
onClick: function() {
$scope.view.current = 'qna';
}
},
{
name: 'Dashboard',
icon: 'view_list',
get show() {
return $scope.user.data && $scope.view.current !== 'dashboard';
},
onClick: function() {
$scope.view.current = 'dashboard';
}
},
{
name: 'Logout',
icon: 'exit_to_app',
get show() {
return $scope.user.data;
},
onClick: function() {
auth.logout().then(function() {
$scope.user.data = null;
$scope.view.current = 'auth';
}).catch(function() {
toast.show('Unable to log out');
});
}
}
];
}
} |
Edit slides by finding them from the collection | define([
"backbone",
"jquery",
"view/HomeView",
"collection/Presentation",
"view/PresentationView",
"model/Slide",
"view/SlideView"
], function (Backbone, $, HomeView, Presentation, PresentationView, Slide, SlideView) {
var presentation = new Presentation();
return Backbone.Router.extend({
routes: {
"home": "home",
"loadpresentation": "loadPresentation",
"editslide/:id": "editSlide"
},
home: function () {
$("#container").html(new HomeView().render().el);
},
loadPresentation: function () {
var presentationView = new PresentationView({ collection: presentation});
presentation.fetch({
success: function () {
$("#container").html(presentationView.render().el);
}
});
},
editSlide: function (id) {
var slide = presentation.find(function (model) {
return model.get("id") === id;
});
$("#container").html(new SlideView({ model: slide }).render().el);
}
});
}); | define([
"backbone",
"jquery",
"view/HomeView",
"collection/Presentation",
"view/PresentationView",
"model/Slide",
"view/SlideView"
], function (Backbone, $, HomeView, Presentation, PresentationView, Slide, SlideView) {
return Backbone.Router.extend({
routes: {
"home": "home",
"loadpresentation": "loadPresentation",
"editslide/:id": "editSlide"
},
home: function () {
$("#container").html(new HomeView().render().el);
},
loadPresentation: function () {
var presentation = new Presentation();
var presentationView = new PresentationView({ collection: presentation});
presentation.fetch({
success: function () {
$("#container").html(presentationView.render().el);
}
});
},
editSlide: function (id) {
var slide = new Slide({ id: id});
slide.fetch({
success: function () {
$("#container").html(new SlideView({ model: slide }).render().el);
}
});
}
});
}); |
Fix syntax error in fallback download script | <?php
require_once "config.inc.php";
$router=$_REQUEST["router"];
$fileExtension = '';
$baseurl="./";
switch ($_REQUEST["type"]) {
case '0':
$type = 'factory';
break;
case '1':
$type = 'sysupgrade';
$fileExtension = '-sysupgrade';
break;
default:
$type = 'factory';
}
switch ($_REQUEST["choose_comunity"]) {
case '0':
$community = 'notset';
break;
case '1':
$community = 'nordlab';
break;
default:
$community = 'notset';
}
$router = $_REQUEST["router"];
if($router === '-1') {
backlink('Bitte wähle eine Router aus. Den genauen Namen und die Version deines Routers findest du auf seiner Unterseite.');
} else{
if($community == 'notset'){
backlink('Bitte gib eine Comunity an.');
}
else {
$href=$baseurl.'media/firmware/' . $community . '/' . $type . '/' . $firmware_prefix . $router . $fileExtension . '.bin';
header('Location: '.$href);
echo '<a href="'.$href.'">redirecting</a>';
}
}
function backlink($t){
echo $t;
?><br>
<br><a href="<?=$_SERVER["referer"]?>">zurück</a>
}
| <?php
require_once "config.inc.php";
$router=$_REQUEST["router"];
$fileExtension = '';
$baseurl="./";
switch ($_REQUEST["type"]) {
case '0':
$type = 'factory';
break;
case '1':
$type = 'sysupgrade';
$fileExtension = '-sysupgrade';
break;
default:
$type = 'factory';
}
switch ($_REQUEST["choose_comunity"]) {
case '0':
$community = 'notset';
break;
case '1':
$community = 'nordlab';
break;
default:
$community = 'notset';
}
$router = $_REQUEST["router"];
if($router === '-1') {
backlink('Bitte wähle eine Router aus. Den genauen Namen und die Version deines Routers findest du auf seiner Unterseite.');
} else{
if($community == 'notset'){
backlink('Bitte gib eine Comunity an.');
}
else {
$href=$baseurl.'media/firmware/' . $community . '/' . $type . '/' . $firmware_prefix . $router . $fileExtension . '.bin';
header('location: '.$href);
echo '<a href="'.$href.'">redirecting</a>';
}
}
function backlink($t){
echo $t;
?><br>
<br><a href="<?=$_SERVER["referer"]?>">zurück</a><?
}
|
Fix incorrect ne_NP locale tests
This test incorrectly assumes a call to name() will
yield only a first/last name, which isn't always true for this
locale. I suspect it hasn't been uncovered yet because the
tests are seeded the same at the beginning of every run. It only
becomes a problem when you start moving tests around. This change
addresses the incorrect assertions as well as makes the file PEP8
compliant. | from __future__ import unicode_literals
import unittest
from faker import Factory
from .. import string_types
class NeNPFactoryTestCase(unittest.TestCase):
def setUp(self):
self.factory = Factory.create('ne_NP')
def test_address(self):
from faker.providers.address.ne_NP import Provider
country = self.factory.country()
assert isinstance(country, string_types)
assert country in Provider.countries
district = self.factory.district()
assert isinstance(district, string_types)
assert district in Provider.districts
city = self.factory.city()
assert isinstance(city, string_types)
assert city in Provider.cities
def test_names(self):
from faker.providers.person.ne_NP import Provider
for _ in range(10000):
name = self.factory.name().split()
assert all(isinstance(n, string_types) for n in name)
# name should always be 2-3 words. If 3, first word
# should be a prefix.
assert name[-2] in Provider.first_names
assert name[-1] in Provider.last_names
prefixes = Provider.prefixes_male + Provider.prefixes_female
if len(name) == 3:
assert name[0] in prefixes
| from __future__ import unicode_literals
import unittest
import re
from faker import Factory
from faker.utils import text
from .. import string_types
class ne_NP_FactoryTestCase(unittest.TestCase):
def setUp(self):
self.factory = Factory.create('ne_NP')
def test_address(self):
from faker.providers.address.ne_NP import Provider
countries = Provider.countries
country = self.factory.country()
assert country
assert isinstance(country, string_types)
assert country in countries
districts = Provider.districts
district = self.factory.district()
assert district
assert isinstance(district, string_types)
assert district in districts
cities = Provider.cities
city = self.factory.city()
assert city
assert isinstance(city, string_types)
assert city in cities
def test_names(self):
from faker.providers.person.ne_NP import Provider
first_names = Provider.first_names
name = self.factory.name()
first_name, last_name = name.split()
assert first_name
assert isinstance(first_name, string_types)
assert first_name in first_names
last_names = Provider.last_names
assert last_names
assert isinstance(last_name, string_types)
assert last_name in last_names
|
Change path to correct location | <?php
class Kwc_Favourites_Box_Component extends Kwc_Abstract
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['assets']['files'][] = 'kwf/Kwc/Favourites/Box/Component.js';
$ret['favouritesPageComponent'] = 'KWC_FAVOURITES_PAGE'; //TODO set to kwc-favourites-page
$ret['viewCache'] = false;
$ret['placeholder']['linkText'] = trlStatic('FAVORITEN ({0})');
return $ret;
}
public function getTemplateVars()
{
$ret = parent::getTemplateVars();
$user = Kwf_Model_Abstract::getInstance('Users')->getAuthedUser();
if ($user) {
$model = Kwf_Model_Abstract::getInstance('Kwc_Favourites_Model');
$select = new Kwf_Model_Select();
$select->whereEquals('user_id', $user->id);
$count = $model->countRows($select);
$ret['linkText'] = str_replace('{0}', "<span class=\"cnt\">$count</span>", $this->_getPlaceholder('linkText'));
}
$ret['favourite'] = Kwf_Component_Data_Root::getInstance()
->getComponentByClass(Kwc_Abstract::getSetting($this->getData()->getComponentClass(), 'favouritesPageComponent'));
return $ret;
}
}
| <?php
class Kwc_Favourites_Box_Component extends Kwc_Abstract
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['assets']['files'][] = 'web/components/Favourites/Box/Component.js';
$ret['favouritesPageComponent'] = 'KWC_FAVOURITES_PAGE'; //TODO set to kwc-favourites-page
$ret['viewCache'] = false;
$ret['placeholder']['linkText'] = trlStatic('FAVORITEN ({0})');
return $ret;
}
public function getTemplateVars()
{
$ret = parent::getTemplateVars();
$user = Kwf_Model_Abstract::getInstance('Users')->getAuthedUser();
if ($user) {
$model = Kwf_Model_Abstract::getInstance('Kwc_Favourites_Model');
$select = new Kwf_Model_Select();
$select->whereEquals('user_id', $user->id);
$count = $model->countRows($select);
$ret['linkText'] = str_replace('{0}', "<span class=\"cnt\">$count</span>", $this->_getPlaceholder('linkText'));
}
$ret['favourite'] = Kwf_Component_Data_Root::getInstance()
->getComponentByClass(Kwc_Abstract::getSetting($this->getData()->getComponentClass(), 'favouritesPageComponent'));
return $ret;
}
}
|
Update filter to use Grammar modifiers | <?php
namespace Romans\Filter;
use Romans\Grammar\Grammar;
use Romans\Grammar\GrammarAwareTrait;
/**
* Int to Roman
*/
class IntToRoman
{
use GrammarAwareTrait;
/**
* Default Constructor
*
* @param Grammar $grammar Grammar Object
*/
public function __construct(Grammar $grammar = null)
{
if (! isset($grammar)) {
$grammar = new Grammar();
}
$this->setGrammar($grammar);
}
/**
* Filter Integer to Roman Number
*
* @param int Integer
* @return string Roman Number Result
*/
public function filter(int $value) : string
{
if ($value < 0) {
throw new Exception(sprintf('Invalid integer: %d', $value), Exception::INVALID_INTEGER);
}
$tokens = $this->getGrammar()->getTokens();
$values = array_reverse($this->getGrammar()->getValuesWithModifiers(), true /* preserve keys */);
$result = '';
if ($value === 0) {
$dataset = $values[0];
foreach ($dataset as $token) {
$result = $result . $tokens[$token];
}
return $result;
}
foreach ($values as $current => $dataset) {
while ($current > 0 && $value >= $current) {
$value = $value - $current;
foreach ($dataset as $token) {
$result = $result . $tokens[$token];
}
}
}
return $result;
}
}
| <?php
namespace Romans\Filter;
use Romans\Grammar\Grammar;
use Romans\Grammar\GrammarAwareTrait;
/**
* Int to Roman
*/
class IntToRoman
{
use GrammarAwareTrait;
/**
* Default Constructor
*
* @param Grammar $grammar Grammar Object
*/
public function __construct(Grammar $grammar = null)
{
if (! isset($grammar)) {
$grammar = new Grammar();
}
$this->setGrammar($grammar);
}
/**
* Filter Integer to Roman Number
*
* @param int Integer
* @return string Roman Number Result
*/
public function filter(int $value) : string
{
if ($value < 0) {
throw new Exception(sprintf('Invalid integer: %d', $value), Exception::INVALID_INTEGER);
}
$tokens = $this->getGrammar()->getTokens();
$values = array_reverse($this->getGrammar()->getValues());
if ($value === 0) {
$token = array_search(0, $values);
return $tokens[$token];
}
$result = '';
foreach ($values as $token => $current) {
while ($current > 0 && $value >= $current) {
$value = $value - $current;
$result = $result . $tokens[$token];
}
}
return $result;
}
}
|
Update openfisca-core requirement from <28.0,>=27.0 to >=27.0,<32.0
Updates the requirements on [openfisca-core](https://github.com/openfisca/openfisca-core) to permit the latest version.
- [Release notes](https://github.com/openfisca/openfisca-core/releases)
- [Changelog](https://github.com/openfisca/openfisca-core/blob/master/CHANGELOG.md)
- [Commits](https://github.com/openfisca/openfisca-core/compare/27.0.0...31.0.0)
Signed-off-by: dependabot[bot] <[email protected]> | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.8.0",
author = "OpenFisca Team",
author_email = "[email protected]",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description = "OpenFisca tax and benefit system for Country-Template",
keywords = "benefit microsimulation social tax",
license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html",
url = "https://github.com/openfisca/country-template",
include_package_data = True, # Will read MANIFEST.in
data_files = [
("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]),
],
install_requires = [
"OpenFisca-Core[web-api] >=27.0,<32.0",
],
extras_require = {
"dev": [
"autopep8 == 1.4.0",
"flake8 >= 3.5.0, < 3.6.0",
"flake8-print",
"pycodestyle >= 2.3.0, < 2.4.0", # To avoid incompatibility with flake
]
},
packages=find_packages(),
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.8.0",
author = "OpenFisca Team",
author_email = "[email protected]",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description = "OpenFisca tax and benefit system for Country-Template",
keywords = "benefit microsimulation social tax",
license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html",
url = "https://github.com/openfisca/country-template",
include_package_data = True, # Will read MANIFEST.in
data_files = [
("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]),
],
install_requires = [
"OpenFisca-Core[web-api] >= 27.0, < 28.0",
],
extras_require = {
"dev": [
"autopep8 == 1.4.0",
"flake8 >= 3.5.0, < 3.6.0",
"flake8-print",
"pycodestyle >= 2.3.0, < 2.4.0", # To avoid incompatibility with flake
]
},
packages=find_packages(),
)
|
[DEV-3932] Remove unnecesasry dependency from demo | const bodyParser = require('body-parser')
const express = require('express');
const hellosign = require('hellosign-sdk');
const app = express();
app.use(bodyParser.json());
app.use(express.static(__dirname + '/dist'));
app.post('/create-signature-request', (req, res) => {
const { apiKey, clientId } = req.body;
const client = hellosign({
key: apiKey,
client_id: clientId
});
client.signatureRequest.createEmbedded({
test_mode: 1,
subject: 'NDA with Acme Co.',
message: 'Please sign this NDA and then we can discuss more.',
signers: [
{
email_address: '[email protected]',
name: 'Alice',
order: 0
}
],
cc_email_addresses: ['[email protected]', '[email protected]'],
files: [__dirname + '/files/nda.docx']
}).then((data) => {
const firstSignature = data.signature_request.signatures[0];
const signatureId = firstSignature.signature_id;
client.embedded.getSignUrl(signatureId).then((signatureData) => {
res.json({
success: true,
data: {
signUrl: signatureData.embedded.sign_url
}
});
});
}).catch((err) => {
res.json({
success: false
});
});
});
app.listen(3000, () => {
console.log('Server running at http://locahost:3000');
});
| const bodyParser = require('body-parser')
const express = require('express');
const hellosign = require('hellosign-sdk');
const path = require('path');
const app = express();
app.use(bodyParser.json());
app.use(express.static(__dirname + '/dist'));
app.post('/create-signature-request', (req, res) => {
const { apiKey, clientId } = req.body;
const client = hellosign({
key: apiKey,
client_id: clientId
});
client.signatureRequest.createEmbedded({
test_mode: 1,
subject: 'NDA with Acme Co.',
message: 'Please sign this NDA and then we can discuss more.',
signers: [
{
email_address: '[email protected]',
name: 'Alice',
order: 0
}
],
cc_email_addresses: ['[email protected]', '[email protected]'],
files: [__dirname + '/files/nda.docx']
}).then((data) => {
const firstSignature = data.signature_request.signatures[0];
const signatureId = firstSignature.signature_id;
client.embedded.getSignUrl(signatureId).then((signatureData) => {
res.json({
success: true,
data: {
signUrl: signatureData.embedded.sign_url
}
});
});
}).catch((err) => {
res.json({
success: false
});
});
});
app.listen(3000, () => {
console.log('Server running at http://locahost:3000');
});
|
Remove folder from files search | // Requires
var _ = require('lodash');
var glob = require("glob");
var Q = require('q');
function setup(options, imports, register) {
// Import
var vfs = imports.vfs;
var workspace = imports.workspace;
// Construct
var filesSearch = function(args) {
var d = Q.defer();
args = _.defaults({}, args || {}, {
'start': 0,
'limit': 30
});
glob("**/*"+args.query+"*", {
'cwd': workspace.root,
'mark': true
}, function (err, files) {
if (err) {
d.reject(err);
} else {
var results = _.chain(files)
.filter(function(path) {
return !(!path.length || path[path.length-1] == "/");
})
.map(function(path) {
return "/"+path;
})
.value();
d.resolve({
'files': results.slice(args.start, args.start+args.limit),
'n': _.size(results)
});
}
});
return d.promise;
};
// Register
register(null, {
"search": {
files: filesSearch
}
});
}
// Exports
module.exports = setup;
| // Requires
var _ = require('lodash');
var glob = require("glob");
var Q = require('q');
function setup(options, imports, register) {
// Import
var vfs = imports.vfs;
var workspace = imports.workspace;
// Construct
var filesSearch = function(args) {
var d = Q.defer();
args = _.defaults({}, args || {}, {
'start': 0,
'limit': 30
});
glob("**/*"+args.query+"*", {
'cwd': workspace.root
}, function (err, files) {
if (err) {
d.reject(err);
} else {
var results = _.map(files.slice(args.start, args.start+args.limit), function(path) {
return "/"+path;
});
d.resolve({
'files': results,
'n': _.size(files)
});
}
});
return d.promise;
};
// Register
register(null, {
"search": {
files: filesSearch
}
});
}
// Exports
module.exports = setup;
|
Use timeout for lldb expr eval (PY-14252). | # This file is meant to be run inside lldb as a command after
# the attach_linux.dylib dll has already been loaded to settrace for all threads.
def __lldb_init_module(debugger, internal_dict):
# Command Initialization code goes here
# print('Startup LLDB in Python!')
import lldb
try:
show_debug_info = 1
is_debug = 0
options = lldb.SBExpressionOptions()
options.SetFetchDynamicValue()
options.SetTryAllThreads(run_others=False)
options.SetTimeoutInMicroSeconds(timeout=10000000)
target = debugger.GetSelectedTarget()
if target:
process = target.GetProcess()
if process:
for thread in process:
# Get the first frame
# print('Thread %s, suspended %s\n'%(thread, thread.IsStopped()))
if internal_dict.get('_thread_%d' % thread.GetThreadID(), False):
process.SetSelectedThread(thread)
if not thread.IsStopped():
# thread.Suspend()
error = process.Stop()
frame = thread.GetSelectedFrame()
if frame:
print('Will settrace in: %s' % (frame,))
res = frame.EvaluateExpression("(int) SetSysTraceFunc(%s, %s)" % (
show_debug_info, is_debug), options)
error = res.GetError()
if error:
print(error)
thread.Resume()
except:
import traceback;traceback.print_exc()
| # This file is meant to be run inside lldb as a command after
# the attach_linux.dylib dll has already been loaded to settrace for all threads.
def __lldb_init_module(debugger, internal_dict):
# Command Initialization code goes here
# print('Startup LLDB in Python!')
import lldb
try:
show_debug_info = 0
is_debug = 0
target = debugger.GetSelectedTarget()
if target:
process = target.GetProcess()
if process:
for thread in process:
# Get the first frame
# print('Thread %s, suspended %s\n'%(thread, thread.IsStopped()))
process.SetSelectedThread(thread)
if internal_dict.get('_thread_%d' % thread.GetThreadID(), False):
frame = thread.GetSelectedFrame()
if frame:
print('Will settrace in: %s' % (frame,))
res = frame.EvaluateExpression("(int) SetSysTraceFunc(%s, %s)" % (
show_debug_info, is_debug), lldb.eDynamicCanRunTarget)
error = res.GetError()
if error:
print(error)
thread.Resume()
except:
import traceback;traceback.print_exc()
|
Update recipe for Google Benchmark | #!/usr/bin/env python
def setup(root_dir):
import confu.git
repo = confu.git.clone("https://github.com/google/benchmark.git", root_dir)
from os import path
recipes_dir = path.dirname(path.abspath(__file__))
import shutil
shutil.copyfile(
path.join(recipes_dir, "googlebenchmark.yaml"),
path.join(root_dir, "confu.yaml"))
def main(args, root_dir=None):
import confu
options = confu.standard_parser("Google micro-Benchmark framework configuration script").parse_args(args)
build = confu.Build.from_options(options, root_dir=root_dir)
build.export_cpath("include", ["benchmark/*.h"])
source_files = [
"benchmark.cc",
"benchmark_register.cc",
"colorprint.cc",
"commandlineflags.cc",
"complexity.cc",
"console_reporter.cc",
"counter.cc",
"csv_reporter.cc",
"json_reporter.cc",
"reporter.cc",
"sleep.cc",
"statistics.cc",
"string_util.cc",
"sysinfo.cc",
"timers.cc",
]
macros = [
"HAVE_POSIX_REGEX",
"NDEBUG",
]
with build.options(source_dir="src", macros=macros, extra_include_dirs="src"):
build.static_library("googlebenchmark",
[build.cxx(source) for source in source_files])
return build
| #!/usr/bin/env python
def setup(root_dir):
import confu.git
repo = confu.git.clone("https://github.com/google/benchmark.git", root_dir)
from os import path
recipes_dir = path.dirname(path.abspath(__file__))
import shutil
shutil.copyfile(
path.join(recipes_dir, "googlebenchmark.yaml"),
path.join(root_dir, "confu.yaml"))
def main(args, root_dir=None):
import confu
options = confu.standard_parser("Google micro-Benchmark framework configuration script").parse_args(args)
build = confu.Build.from_options(options, root_dir=root_dir)
build.export_cpath("include", ["benchmark/*.h"])
source_files = [
"benchmark.cc",
"benchmark_register.cc",
"colorprint.cc",
"commandlineflags.cc",
"complexity.cc",
"console_reporter.cc",
"counter.cc",
"csv_reporter.cc",
"json_reporter.cc",
"reporter.cc",
"sleep.cc",
"string_util.cc",
"sysinfo.cc",
"timers.cc",
]
macros = [
"HAVE_POSIX_REGEX",
"NDEBUG",
]
with build.options(source_dir="src", macros=macros, extra_include_dirs="src"):
build.static_library("googlebenchmark",
[build.cxx(source) for source in source_files])
return build
|
Add button class to Comments form | @php
if (post_password_required()) {
return;
}
@endphp
<section id="comments" class="comments">
@if (have_comments())
<h2>
{!! sprintf(_nx('One response to “%2$s”', '%1$s responses to “%2$s”', get_comments_number(), 'comments title', 'sage'), number_format_i18n(get_comments_number()), '<span>' . get_the_title() . '</span>') !!}
</h2>
<ol class="comment-list">
{!! wp_list_comments(['style' => 'ol', 'short_ping' => true]) !!}
</ol>
@if (get_comment_pages_count() > 1 && get_option('page_comments'))
<nav>
<ul class="pager">
@if (get_previous_comments_link())
<li class="previous">@php(previous_comments_link(__('← Older comments', 'sage')))</li>
@endif
@if (get_next_comments_link())
<li class="next">@php(next_comments_link(__('Newer comments →', 'sage')))</li>
@endif
</ul>
</nav>
@endif
@endif
@if (!comments_open() && get_comments_number() != '0' && post_type_supports(get_post_type(), 'comments'))
<div class="alert alert-warning">
{{ __('Comments are closed.', 'sage') }}
</div>
@endif
@php(comment_form(['class_submit' => 'button']))
</section>
| @php
if (post_password_required()) {
return;
}
@endphp
<section id="comments" class="comments">
@if (have_comments())
<h2>
{!! sprintf(_nx('One response to “%2$s”', '%1$s responses to “%2$s”', get_comments_number(), 'comments title', 'sage'), number_format_i18n(get_comments_number()), '<span>' . get_the_title() . '</span>') !!}
</h2>
<ol class="comment-list">
{!! wp_list_comments(['style' => 'ol', 'short_ping' => true]) !!}
</ol>
@if (get_comment_pages_count() > 1 && get_option('page_comments'))
<nav>
<ul class="pager">
@if (get_previous_comments_link())
<li class="previous">@php(previous_comments_link(__('← Older comments', 'sage')))</li>
@endif
@if (get_next_comments_link())
<li class="next">@php(next_comments_link(__('Newer comments →', 'sage')))</li>
@endif
</ul>
</nav>
@endif
@endif
@if (!comments_open() && get_comments_number() != '0' && post_type_supports(get_post_type(), 'comments'))
<div class="alert alert-warning">
{{ __('Comments are closed.', 'sage') }}
</div>
@endif
@php(comment_form())
</section>
|
Change formatting of log file to enhance readability | package bakatxt.log;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class BakaLogFormatter extends Formatter {
private static final int MAX_BUFFER = 1000;
private static final String DATE_FORMAT = "HH:mm:ss:SSS";
private static final String SPACE = " ";
private static final String COLON = ":";
private static final String LINE_SEPARATOR = System
.getProperty("line.separator");
@Override
public String format(LogRecord record) {
StringBuffer output = new StringBuffer(MAX_BUFFER);
output.append(calculateDate(record.getMillis()));
output.append(SPACE);
output.append(record.getSourceClassName());
output.append(SPACE);
output.append(record.getSourceMethodName());
output.append(LINE_SEPARATOR + "\t");
output.append(record.getLevel());
output.append(COLON + SPACE);
output.append(formatMessage(record));
output.append(LINE_SEPARATOR);
return output.toString();
}
private static String calculateDate(long ms) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date rawDate = new Date(ms);
return dateFormat.format(rawDate);
}
@Override
public String getHead(Handler handler) {
Date now = new Date();
return "Session: " + now.toString() + LINE_SEPARATOR;
}
@Override
public String getTail(Handler h) {
return "End Session" + LINE_SEPARATOR + LINE_SEPARATOR;
}
}
| package bakatxt.log;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class BakaLogFormatter extends Formatter {
private static final int MAX_BUFFER = 1000;
private static final String DATE_FORMAT = "HH:mm:ss:SSS";
private static final String SPACE = " ";
private static final String COLON = ":";
private static final String LINE_SEPARATOR = System
.getProperty("line.separator");
@Override
public String format(LogRecord record) {
StringBuffer output = new StringBuffer(MAX_BUFFER);
output.append(calculateDate(record.getMillis()));
output.append(SPACE);
output.append(record.getSourceClassName());
output.append(SPACE);
output.append(record.getSourceMethodName());
output.append("\t");
output.append(record.getLevel());
output.append(COLON + SPACE);
output.append(formatMessage(record));
output.append(LINE_SEPARATOR);
return output.toString();
}
private static String calculateDate(long ms) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date rawDate = new Date(ms);
return dateFormat.format(rawDate);
}
@Override
public String getHead(Handler handler) {
Date now = new Date();
return "Session: " + now.toString() + LINE_SEPARATOR;
}
@Override
public String getTail(Handler h) {
return "End Session" + LINE_SEPARATOR + LINE_SEPARATOR;
}
}
|
Move mergeConfigFrom to register method
According to http://laravel.com/docs/5.0/packages#configuration it should be in register() and not in boot() | <?php namespace Kyslik\ColumnSortable;
use Illuminate\Support\ServiceProvider;
class ColumnSortableServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->publishes([__DIR__ . '/../../config/columnsortable.php' => config_path('columnsortable.php')]);
$this->registerBladeExtensions();
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__ . '/../../config/columnsortable.php', 'columnsortable');
}
/**
* Register Blade extensions.
*
* @return void
*/
protected function registerBladeExtensions()
{
$blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
$blade->extend(function ($view, $compiler)
{
$pattern = $compiler->createMatcher('sortablelink');
$replace = '<?php echo \Kyslik\ColumnSortable\Sortable::link(array $2);?>';
return preg_replace($pattern, $replace, $view);
});
}
}
| <?php namespace Kyslik\ColumnSortable;
use Illuminate\Support\ServiceProvider;
class ColumnSortableServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->publishes([__DIR__ . '/../../config/columnsortable.php' => config_path('columnsortable.php')]);
$this->mergeConfigFrom(__DIR__ . '/../../config/columnsortable.php', 'columnsortable');
$this->registerBladeExtensions();
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
/**
* Register Blade extensions.
*
* @return void
*/
protected function registerBladeExtensions()
{
$blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
$blade->extend(function ($view, $compiler)
{
$pattern = $compiler->createMatcher('sortablelink');
$replace = '<?php echo \Kyslik\ColumnSortable\Sortable::link(array $2);?>';
return preg_replace($pattern, $replace, $view);
});
}
}
|
Update command docs for conda index | from __future__ import absolute_import, division, print_function
import os
from locale import getpreferredencoding
from os.path import abspath
from conda.compat import PY3
from conda.cli.conda_argparse import ArgumentParser
from conda_build.index import update_index
def main():
p = ArgumentParser(
description="Update package index metadata files in given directories.")
p.add_argument(
'dir',
help='Directory that contains an index to be updated.',
nargs='*',
default=[os.getcwd()],
)
p.add_argument(
'-c', "--check-md5",
action="store_true",
help="""Use MD5 values instead of file modification times for determining if a
package's metadata needs to be updated.""",
)
p.add_argument(
'-f', "--force",
action="store_true",
help="Force reading all files.",
)
p.add_argument(
'-q', "--quiet",
action="store_true",
help="Don't show any output.",
)
args = p.parse_args()
dir_paths = [abspath(path) for path in args.dir]
# Don't use byte strings in Python 2
if not PY3:
dir_paths = [path.decode(getpreferredencoding()) for path in dir_paths]
for path in dir_paths:
update_index(path, verbose=(not args.quiet), force=args.force)
if __name__ == '__main__':
main()
| from __future__ import absolute_import, division, print_function
import argparse
import os
from locale import getpreferredencoding
from os.path import abspath
from conda.compat import PY3
from conda_build.index import update_index
def main():
p = argparse.ArgumentParser(
description="Update package index metadata files in given directories")
p.add_argument('dir',
help='Directory that contains an index to be updated.',
nargs='*',
default=[os.getcwd()])
p.add_argument('-c', "--check-md5",
action="store_true",
help="Use MD5 values instead of file modification times for\
determining if a package's metadata needs to be \
updated.")
p.add_argument('-f', "--force",
action="store_true",
help="force reading all files")
p.add_argument('-q', "--quiet",
action="store_true")
args = p.parse_args()
dir_paths = [abspath(path) for path in args.dir]
# Don't use byte strings in Python 2
if not PY3:
dir_paths = [path.decode(getpreferredencoding()) for path in dir_paths]
for path in dir_paths:
update_index(path, verbose=(not args.quiet), force=args.force)
if __name__ == '__main__':
main()
|
Increase scroll timeout for smoother performance | ngGridDirectives.directive('ngViewport', [function() {
return function($scope, elm) {
var isMouseWheelActive;
var prevScollLeft;
var prevScollTop = 0;
var ensureDigest = function() {
if (!$scope.$root.$$phase) {
$scope.$digest();
}
};
var scrollTimer;
elm.bind('scroll', function(evt) {
var scrollLeft = evt.target.scrollLeft,
scrollTop = evt.target.scrollTop;
if ($scope.$headerContainer) {
$scope.$headerContainer.scrollLeft(scrollLeft);
}
$scope.adjustScrollLeft(scrollLeft);
$scope.adjustScrollTop(scrollTop);
if ($scope.forceSyncScrolling) {
ensureDigest();
} else {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(ensureDigest, 150);
}
prevScollLeft = scrollLeft;
prevScollTop = scrollTop;
isMouseWheelActive = false;
return true;
});
elm.bind("mousewheel DOMMouseScroll", function() {
isMouseWheelActive = true;
if (elm.focus) { elm.focus(); }
return true;
});
if (!$scope.enableCellSelection) {
$scope.domAccessProvider.selectionHandlers($scope, elm);
}
};
}]); | ngGridDirectives.directive('ngViewport', [function() {
return function($scope, elm) {
var isMouseWheelActive;
var prevScollLeft;
var prevScollTop = 0;
var ensureDigest = function() {
if (!$scope.$root.$$phase) {
$scope.$digest();
}
};
var scrollTimer;
elm.bind('scroll', function(evt) {
var scrollLeft = evt.target.scrollLeft,
scrollTop = evt.target.scrollTop;
if ($scope.$headerContainer) {
$scope.$headerContainer.scrollLeft(scrollLeft);
}
$scope.adjustScrollLeft(scrollLeft);
$scope.adjustScrollTop(scrollTop);
if ($scope.forceSyncScrolling) {
ensureDigest();
} else {
clearTimeout(scrollTimer);
scrollTimer = setTimeout(ensureDigest, 50);
}
prevScollLeft = scrollLeft;
prevScollTop = scrollTop;
isMouseWheelActive = false;
return true;
});
elm.bind("mousewheel DOMMouseScroll", function() {
isMouseWheelActive = true;
if (elm.focus) { elm.focus(); }
return true;
});
if (!$scope.enableCellSelection) {
$scope.domAccessProvider.selectionHandlers($scope, elm);
}
};
}]); |
Increase timeout from 1000 ms to 3000 when requesting ELIQ API | var RSVP = require('rsvp'),
request = require('request'),
date = require('./date');
module.exports = function (config) {
'use strict';
var eliqUrl = require('./eliqurl')(config);
function fetchData (url) {
return new RSVP.Promise(function (resolve, reject) {
var options = {
url: url,
json: true,
timeout: 3000
};
request(options, function (error, response, body) {
if (!error && response && (response.statusCode === 200 || response.statusCode === 201)) {
resolve(body);
} else {
error = error || 'Got status code ' + response.statusCode + ' for ' + options.url;
reject(error);
}
});
});
}
function getFrom (age, resolution) {
var startdate = date.hoursAgoFromNow(age);
return fetchData(eliqUrl.from(startdate, resolution));
}
function getFromTo (startdate, enddate, resolution) {
return fetchData(eliqUrl.fromTo(startdate, enddate, resolution));
}
function getToday () {
return fetchData(eliqUrl.day(new Date()));
}
function getThisHour () {
return fetchData(eliqUrl.hour(new Date()));
}
return {
getFrom: getFrom,
getFromTo: getFromTo,
getToday: getToday,
getThisHour: getThisHour
};
};
| var RSVP = require('rsvp'),
request = require('request'),
date = require('./date');
module.exports = function (config) {
'use strict';
var eliqUrl = require('./eliqurl')(config);
function fetchData (url) {
return new RSVP.Promise(function (resolve, reject) {
var options = {
url: url,
json: true,
timeout: 1000
};
request(options, function (error, response, body) {
if (!error && response && (response.statusCode === 200 || response.statusCode === 201)) {
resolve(body);
} else {
error = error || 'Got status code ' + response.statusCode + ' for ' + options.url;
reject(error);
}
});
});
}
function getFrom (age, resolution) {
var startdate = date.hoursAgoFromNow(age);
return fetchData(eliqUrl.from(startdate, resolution));
}
function getFromTo (startdate, enddate, resolution) {
return fetchData(eliqUrl.fromTo(startdate, enddate, resolution));
}
function getToday () {
return fetchData(eliqUrl.day(new Date()));
}
function getThisHour () {
return fetchData(eliqUrl.hour(new Date()));
}
return {
getFrom: getFrom,
getFromTo: getFromTo,
getToday: getToday,
getThisHour: getThisHour
};
};
|
Add preloader queries for navigation | import Relay from 'react-relay';
import fromGraphQL from 'react-relay/lib/fromGraphQL';
const QUERIES = {
"organization/show": Relay.QL`
query PipelinesList($organization: ID!, $teamsCount: Int!) {
organization(slug: $organization) {
id
slug
name
teams(first: $teamsCount) {
edges {
node {
id
name
slug
description
}
cursor
}
pageInfo {
hasNextPage
hasPreviousPage
}
}
}
}
`,
"navigation/organization": Relay.QL`
query NavigationOrganization($organization: ID!) {
organization(slug: $organization) {
name
id
slug
agents {
count
}
permissions {
organizationUpdate {
allowed
}
organizationMemberCreate {
allowed
}
notificationServiceUpdate {
allowed
}
organizationBillingUpdate {
allowed
}
teamAdmin {
allowed
}
}
}
}
`,
"navigation/viewer": Relay.QL`
query NavigationViewer {
viewer {
user {
name,
avatar {
url
}
id
}
organizations(first: 500) {
edges {
node {
slug,
name,
id
}
cursor
}
pageInfo {
hasNextPage,
hasPreviousPage
}
}
unreadChangelogs: changelogs(read: false) {
count
}
runningBuilds: builds(state: BUILD_STATE_RUNNING) {
count
}
scheduledBuilds: builds(state: BUILD_STATE_SCHEDULED) {
count
}
}
}
`
};
class RelayPreloader {
preload(id, payload, variables) {
// Get the concrete query
const concrete = QUERIES[id];
if (!concrete) {
throw "No concrete query defined for `" + id + "`";
}
// Create a Relay-readable GraphQL query with the variables loaded in
const query = fromGraphQL.Query(concrete);
query.__variables__ = variables;
// Load it with the payload into the Relay store
Relay.Store.getStoreData().handleQueryPayload(query, payload);
}
}
export default new RelayPreloader();
| import Relay from 'react-relay';
import fromGraphQL from 'react-relay/lib/fromGraphQL';
const QUERIES = {
"organization/show": Relay.QL`
query PipelinesList($organization: ID!, $teamsCount: Int!) {
organization(slug: $organization) {
id
slug
name
teams(first: $teamsCount) {
edges {
node {
id
name
slug
description
}
cursor
}
pageInfo {
hasNextPage
hasPreviousPage
}
}
}
}
`
};
class RelayPreloader {
preload(id, payload, variables) {
// Get the concrete query
const concrete = QUERIES[id];
if (!concrete) {
throw "No concrete query defined for `" + id + "`";
}
// Create a Relay-readable GraphQL query with the variables loaded in
const query = fromGraphQL.Query(concrete);
query.__variables__ = variables;
// Load it with the payload into the Relay store
Relay.Store.getStoreData().handleQueryPayload(query, payload);
}
}
export default new RelayPreloader();
|
Use our own code, when possible. | from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from comrade.views.simple import direct_to_template
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
return direct_to_template(template_name, status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
| from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
def authorized(test_func, template_name='401.html'):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the unauthorized page if it fails. The test should be a
callable that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user, *args, **kwargs):
return view_func(request, *args, **kwargs)
path = urlquote(request.get_full_path())
t = loader.get_template(template_name)
return HttpResponse(t.render(RequestContext(request)), status=401)
return wraps(view_func,
assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def load_instance(model):
def decorator(view):
def _wrapper(request, object_id=None, *args, **kwargs):
if object_id:
instance = get_object_or_404(model, pk=object_id)
return view(request, instance, *args, **kwargs)
return view(request, *args, **kwargs)
return wraps(view)(_wrapper)
return decorator
|
Include CHANGES.rst in long description. | from setuptools import setup, find_packages
version = '1.0a5.dev0'
long_description = (
open('README.rst').read() +
'\n' +
'\n' +
open('CHANGES.rst').read() +
'\n')
setup(
name='robotframework-djangolibrary',
version=version,
description="A robot framework library for Django.",
long_description=long_description,
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: Apache Software License',
'Environment :: Web Environment',
'Framework :: Robot Framework',
'Framework :: Django',
'Framework :: Django :: 1.5',
'Framework :: Django :: 1.6',
'Framework :: Django :: 1.7',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
],
# Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='robotframework django test',
author='Timo Stollenwerk',
author_email='[email protected]',
url='http://kitconcept.com',
license='Apache License 2.0',
packages=find_packages(
exclude=['ez_setup', 'examples', 'tests']
),
include_package_data=True,
zip_safe=False,
install_requires=[
'Django',
'robotframework',
'robotframework-selenium2library',
'robotframework-debuglibrary',
],
entry_points="""
# -*- Entry points: -*-
""",
)
| from setuptools import setup, find_packages
version = '1.0a5.dev0'
setup(
name='robotframework-djangolibrary',
version=version,
description="A robot framework library for Django.",
long_description="""\
""",
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: Apache Software License',
'Environment :: Web Environment',
'Framework :: Robot Framework',
'Framework :: Django',
'Framework :: Django :: 1.5',
'Framework :: Django :: 1.6',
'Framework :: Django :: 1.7',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
],
# Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='robotframework django test',
author='Timo Stollenwerk',
author_email='[email protected]',
url='http://kitconcept.com',
license='Apache License 2.0',
packages=find_packages(
exclude=['ez_setup', 'examples', 'tests']
),
include_package_data=True,
zip_safe=False,
install_requires=[
'Django',
'robotframework',
'robotframework-selenium2library',
'robotframework-debuglibrary',
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
Order by date on server side before finding uniques | const {
History,
Song
} = require('../models')
const _ = require('lodash')
module.exports = {
async index (req, res) {
try {
const userId = req.user.id
const histories = await History.findAll({
where: {
UserId: userId
},
include: [
{
model: Song
}
],
order: [
['createdAt', 'DESC']
]
})
.map(history => history.toJSON())
.map(history => _.extend(
{},
history.Song,
history
))
res.send(_.uniqBy(histories, history => history.SongId))
} catch (err) {
res.status(500).send({
error: 'an error has occured trying to fetch the history'
})
}
},
async post (req, res) {
try {
const userId = req.user.id
const {songId} = req.body
const history = await History.create({
SongId: songId,
UserId: userId
})
res.send(history)
} catch (err) {
console.log(err)
res.status(500).send({
error: 'an error has occured trying to create the history object'
})
}
}
}
| const {
History,
Song
} = require('../models')
const _ = require('lodash')
module.exports = {
async index (req, res) {
try {
const userId = req.user.id
const histories = await History.findAll({
where: {
UserId: userId
},
include: [
{
model: Song
}
]
})
.map(history => history.toJSON())
.map(history => _.extend(
{},
history.Song,
history
))
res.send(_.uniqBy(histories, history => history.SongId))
} catch (err) {
res.status(500).send({
error: 'an error has occured trying to fetch the history'
})
}
},
async post (req, res) {
try {
const userId = req.user.id
const {songId} = req.body
const history = await History.create({
SongId: songId,
UserId: userId
})
res.send(history)
} catch (err) {
console.log(err)
res.status(500).send({
error: 'an error has occured trying to create the history object'
})
}
}
}
|
booster-bdd: Replace hardcoded Forge API URL by variable. | import pytest
import time
import requests
import support.helpers as helpers
import sys
import re
import os
class ImportBooster(object):
def importGithubRepo(self, gitRepo):
###############################################
# Environment variables
#
# Note: Pipelines = https://forge.api.openshift.io/api/services/jenkins/pipelines
# Tokens are stored in a form of "<access_token>;<refresh_token>(;<username>)"
theToken = helpers.get_user_tokens().split(";")[0]
projectName = os.getenv('PROJECT_NAME')
pipeline = os.getenv('PIPELINE')
spaceId = helpers.getSpaceID()
authHeader = 'Bearer {}'.format(theToken)
print('Starting test.....')
###############################################
# Import the booster
headers = {'Accept': 'application/json',
'Authorization': authHeader,
'X-App': 'osio',
'X-Git-Provider': 'GitHub',
'Content-Type': 'application/x-www-form-urlencoded'}
data = {'gitRepository': gitRepo,
'projectName': projectName,
'pipeline': pipeline,
'space': spaceId}
forgeApi = os.getenv("FORGE_API")
print('Making request to import...')
r = requests.post(
'{}/api/osio/import'.format(forgeApi),
headers=headers,
data=data
)
# print 'request results = {}'.format(r.text)
result = r.text
if re.search('uuid', result):
return 'Success'
else:
return 'Fail'
| import pytest
import time
import requests
import support.helpers as helpers
import sys
import re
import os
class ImportBooster(object):
def importGithubRepo(self, gitRepo):
###############################################
# Environment variables
#
# Note: Pipelines = https://forge.api.openshift.io/api/services/jenkins/pipelines
# Tokens are stored in a form of "<access_token>;<refresh_token>(;<username>)"
theToken = helpers.get_user_tokens().split(";")[0]
projectName = os.environ.get('PROJECT_NAME')
pipeline = os.environ.get('PIPELINE')
spaceId = helpers.getSpaceID()
authHeader = 'Bearer {}'.format(theToken)
print 'Starting test.....'
###############################################
# Import the booster
headers = {'Accept': 'application/json',
'Authorization': authHeader,
'X-App': 'osio',
'X-Git-Provider': 'GitHub',
'Content-Type': 'application/x-www-form-urlencoded'}
data = {'gitRepository': gitRepo,
'projectName': projectName,
'pipeline': pipeline,
'space': spaceId}
print 'Making request to import...'
r = requests.post('https://forge.api.openshift.io/api/osio/import',
headers=headers, data=data)
# print 'request results = {}'.format(r.text)
result = r.text
if re.search('uuid', result):
return 'Success'
else:
return 'Fail'
|
Fix crash in python 3.8 due to a mismatch on the ArgumentParser parameter | """ArgumentParser with Italian translation."""
import argparse
import sys
def _callable(obj):
return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
class ArgParser(argparse.ArgumentParser):
def __init__(self, **kwargs):
if kwargs.get('parent', None) is None:
kwargs['parents'] = []
super().__init__(**kwargs)
def set_default_subparser(self, name, args=None):
"""
Default subparser selection.
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
"""
subparser_found = False
for arg in sys.argv[1:]:
if arg in ['-h', '--help']: # global help if no subparser
break
else:
for x in self._subparsers._actions:
if not isinstance(x, argparse._SubParsersAction):
continue
for sp_name in x._name_parser_map.keys():
if sp_name in sys.argv[1:]:
subparser_found = True
if not subparser_found:
# insert default in first position, this implies no
# global options without a sub_parsers specified
if args is None:
sys.argv.insert(1, name)
else:
args.insert(0, name) | """ArgumentParser with Italian translation."""
import argparse
import sys
def _callable(obj):
return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
class ArgParser(argparse.ArgumentParser):
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
parents=None,
formatter_class=argparse.HelpFormatter,
prefix_chars='-',
fromfile_prefix_chars=None,
argument_default=None,
conflict_handler='error',
add_help=True,
allow_abbrev=True,
exit_on_error=True):
if parents is None:
parents = []
super().__init__(prog, usage, description, epilog, parents, formatter_class,
prefix_chars, fromfile_prefix_chars, argument_default,
conflict_handler, add_help, allow_abbrev, exit_on_error)
def set_default_subparser(self, name, args=None):
"""
Default subparser selection.
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
"""
subparser_found = False
for arg in sys.argv[1:]:
if arg in ['-h', '--help']: # global help if no subparser
break
else:
for x in self._subparsers._actions:
if not isinstance(x, argparse._SubParsersAction):
continue
for sp_name in x._name_parser_map.keys():
if sp_name in sys.argv[1:]:
subparser_found = True
if not subparser_found:
# insert default in first position, this implies no
# global options without a sub_parsers specified
if args is None:
sys.argv.insert(1, name)
else:
args.insert(0, name) |
Add a default fallback URL. | 'use strict';
const hiredis = require('hiredis');
const URL = require('url');
const reader = new hiredis.Reader();
class YoRedis {
constructor(config) {
if (config instanceof Function)
this.config = config;
else
this.config = function() { return config || {} };
}
connect() {
if (this.socket)
return Promise.resolve(this.socket);
else {
return Promise.resolve(this.config())
.then(config => {
const url = URL.parse(
config.url || process.env.REDIS_URL || 'redis://127.0.0.1:6379'
);
this.socket = hiredis.createConnection(url.port, url.hostname);
this.socket
.on('reply', data => {
if (data instanceof Error)
this._operations.shift()[1](data);
else
this._operations.shift()[0](data);
})
.on('error', error => {
this._operations.shift()[1](error);
});
this._operations = [];
});
}
}
call() {
return this.connect()
.then(() => {
return new Promise((resolve, reject) => {
this._operations.push([ resolve, reject ]);
this.socket.write.apply(this.socket, arguments);
});
});
}
end() {
if (this.socket) {
this.socket.end();
this.socket = null;
}
}
}
module.exports = YoRedis;
| 'use strict';
const hiredis = require('hiredis');
const URL = require('url');
const reader = new hiredis.Reader();
class YoRedis {
constructor(config) {
if (config instanceof Function)
this.config = config;
else
this.config = function() { return config || {} };
}
connect() {
if (this.socket)
return Promise.resolve(this.socket);
else {
return Promise.resolve(this.config())
.then(config => {
this.url = URL.parse(config.url || process.env.REDIS_URL);
this.socket = hiredis.createConnection(this.url.port, this.url.hostname);
this.socket
.on('reply', data => {
if (data instanceof Error)
this._operations.shift()[1](data);
else
this._operations.shift()[0](data);
})
.on('error', error => {
this._operations.shift()[1](error);
});
this._operations = [];
});
}
}
call() {
return this.connect()
.then(() => {
return new Promise((resolve, reject) => {
this._operations.push([ resolve, reject ]);
this.socket.write.apply(this.socket, arguments);
});
});
}
end() {
if (this.socket) {
this.socket.end();
this.socket = null;
}
}
}
module.exports = YoRedis;
|
Revert "Disable test that fails on bot"
This reverts commit e214e46e748881e6418ffac374a87d6ad30fcfea.
I have reverted the swift commit that was causing this failure.
rdar://35264910 | # TestPOUnwrapping.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
"""Test that we can correctly handle a nested generic type."""
import lldbsuite.test.lldbrepl as lldbrepl
import lldbsuite.test.decorators as decorators
class REPLBasicTestCase(lldbrepl.REPLTest):
mydir = lldbrepl.REPLTest.compute_mydir(__file__)
def doTest(self):
self.command(
'''class Foo<T,U> {
var t: T?
var u: U?
init() { t = nil; u = nil }
init(_ x: T, _ y: U) { t = x; u = y }
};(Foo<String,Double>(),Foo<Double,String>(3.14,"hello"))''',
patterns=[
r'\$R0: \(Foo<String, Double>, Foo<Double, String>\) = {',
r'0 = {',
r't = nil',
r'u = nil',
r'1 = {',
r't = 3\.14[0-9]+', 'u = "hello"'])
| # TestPOUnwrapping.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
"""Test that we can correctly handle a nested generic type."""
import lldbsuite.test.lldbrepl as lldbrepl
import lldbsuite.test.decorators as decorators
class REPLBasicTestCase(lldbrepl.REPLTest):
mydir = lldbrepl.REPLTest.compute_mydir(__file__)
@decorators.expectedFailureAll(
oslist=[
"macosx",
"linux"],
bugnumber="rdar://35264910")
def doTest(self):
self.command(
'''class Foo<T,U> {
var t: T?
var u: U?
init() { t = nil; u = nil }
init(_ x: T, _ y: U) { t = x; u = y }
};(Foo<String,Double>(),Foo<Double,String>(3.14,"hello"))''',
patterns=[
r'\$R0: \(Foo<String, Double>, Foo<Double, String>\) = {',
r'0 = {',
r't = nil',
r'u = nil',
r'1 = {',
r't = 3\.14[0-9]+', 'u = "hello"'])
|
Use new namespaced auth API methods | import Ember from 'ember';
import Base from 'simple-auth/authenticators/base';
import ENV from 'wordset/config/environment';
export default Base.extend({
restore: function(properties) {
var propertiesObject = Ember.Object.create(properties);
return new Ember.RSVP.Promise(function(resolve, reject) {
if (!Ember.isEmpty(propertiesObject.get("username")) && !Ember.isEmpty(propertiesObject.get("auth_key"))) {
resolve(properties);
} else {
reject();
}
});
},
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var data = {};
data = {
username: credentials.identification,
password: credentials.password
};
_this.makeRequest(data).then(function(response) {
Ember.run(function() {
resolve(response);
});
}, function(xhr) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},
invalidate: function() {
return Ember.RSVP.resolve();
},
makeRequest: function(data) {
return Ember.$.ajax({
url: ENV.api + '/auth/login',
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Accept', settings.accepts.json);
}
});
}
});
| import Ember from 'ember';
import Base from 'simple-auth/authenticators/base';
import ENV from 'wordset/config/environment';
export default Base.extend({
restore: function(properties) {
var propertiesObject = Ember.Object.create(properties);
return new Ember.RSVP.Promise(function(resolve, reject) {
if (!Ember.isEmpty(propertiesObject.get("username")) && !Ember.isEmpty(propertiesObject.get("auth_key"))) {
resolve(properties);
} else {
reject();
}
});
},
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
var data = {};
data = {
username: credentials.identification,
password: credentials.password
};
_this.makeRequest(data).then(function(response) {
Ember.run(function() {
resolve(response);
});
}, function(xhr) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},
invalidate: function() {
return Ember.RSVP.resolve();
},
makeRequest: function(data) {
return Ember.$.ajax({
url: ENV.api + '/login',
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Accept', settings.accepts.json);
}
});
}
});
|
Update to v0.2.0 and translate the description. | <?php
/*********************************************************************
The MIT License (MIT)
Copyright (c) 2015 William Hiver
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*********************************************************************/
if (!defined('DC_RC_PATH')) { return; }
$this->registerModule(
/* Name */ 'Majordome',
/* Description*/ __('A Dotclear plugin which allow user to easily create and manage user forms.'),
/* Author */ 'William Hiver',
/* Version */ '0.2.0',
array(
'type' => 'plugin',
'permissions' => 'usage,contentadmin'
)
);
?>
| <?php
/*********************************************************************
The MIT License (MIT)
Copyright (c) 2015 William Hiver
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*********************************************************************/
if (!defined('DC_RC_PATH')) { return; }
__('A Dotclear plugin which allow user to easily create and manage user forms.'); /* Description */
$this->registerModule(
/* Name */ 'Majordome',
/* Description*/ 'A Dotclear plugin which allow user to easily create and manage user forms.',
/* Author */ 'William Hiver',
/* Version */ '0.1.0',
array(
'type' => 'plugin',
'permissions' => 'usage,contentadmin'
)
);
?>
|
Enable only if really needed | <?php
use Timber\Loader;
use Timber\Menu;
use Timber\Site;
use Timber\Timber;
class TheSite extends Site
{
function __construct()
{
add_filter('timber_context', [$this, 'addToContext']);
add_filter('get_twig', [$this, 'addToTwig']);
add_action('init', [$this, 'registerPostTypes']);
$this->setupCache();
parent::__construct();
}
function setupCache()
{
Timber::$cache = false;
if (defined('WP_ENV') && 'production' === WP_ENV) {
Timber::$cache = true;
add_filter('timber/cache/mode', function ($cacheMode) {
$cacheMode = Loader::CACHE_OBJECT;
return $cacheMode;
});
}
}
function registerPostTypes()
{
}
function addToContext($context)
{
//$context['settings'] = get_fields('options');
//$context['menu'] = new Menu('primary');
if (current_theme_supports('nanga-sidebar')) {
$context['sidebar'] = Timber::get_sidebar('sidebar.php');
}
$context['site'] = $this;
return $context;
}
function addToTwig($twig)
{
//$twig->addFilter('antispam', new Twig_Filter_Function([$this, 'antispam']));
$twig->addExtension(new Twig_Extension_StringLoader());
return $twig;
}
function antispam($email)
{
return antispambot($email);
}
}
new TheSite();
| <?php
use Timber\Loader;
use Timber\Menu;
use Timber\Site;
use Timber\Timber;
class TheSite extends Site
{
function __construct()
{
add_filter('timber_context', [$this, 'addToContext']);
add_filter('get_twig', [$this, 'addToTwig']);
add_action('init', [$this, 'registerPostTypes']);
$this->setupCache();
parent::__construct();
}
function setupCache()
{
Timber::$cache = false;
if (defined('WP_ENV') && 'production' === WP_ENV) {
Timber::$cache = true;
add_filter('timber/cache/mode', function ($cacheMode) {
$cacheMode = Loader::CACHE_OBJECT;
return $cacheMode;
});
}
}
function registerPostTypes()
{
}
function addToContext($context)
{
$context['settings'] = get_fields('options');
$context['menu'] = new Menu('primary');
if (current_theme_supports('nanga-sidebar')) {
$context['sidebar'] = Timber::get_sidebar('sidebar.php');
}
$context['site'] = $this;
return $context;
}
function addToTwig($twig)
{
//$twig->addFilter('antispam', new Twig_Filter_Function([$this, 'antispam']));
$twig->addExtension(new Twig_Extension_StringLoader());
return $twig;
}
function antispam($email)
{
return antispambot($email);
}
}
new TheSite();
|
Include card count in deck directory | #!/usr/bin/env node
var _ = require('underscore'),
glob = require('glob'),
fs = require('fs'),
mkdirp = require('mkdirp'),
path = require('path'),
generateEntry,
sanitizePath;
generateEntry = function(filepath) {
var contents, entry;
console.log('Creating index entry for: ' + filepath);
// TODO: This require is ugly and should be fixed in a better way later
contents = require('../' + filepath);
entry = {
file: sanitizePath(filepath),
name: contents.name,
cardCount: contents.cards.length
};
if (contents.percentDone) {
entry.percentDone = contents.percentDone;
};
return entry;
};
sanitizePath = function(filepath) {
// TODO: This trim is ugly. Please clean up
return filepath.replace(/^data\//,"");
};
glob("data/**/*.json", function (err, files) {
if (err) {
console.log('Encountered file search error, aborting...');
console.log(err);
return;
}
var index = _.map(files, generateEntry),
targetFile = 'dist/data/directory.json';
console.log(index);
mkdirp(path.dirname(targetFile), function (err) {
if (err) {
console.log(err);
return;
}
fs.writeFile(targetFile, JSON.stringify(index), function(err) {
if(err) {
console.log(err);
return;
}
console.log('The index was sucessfully saved to: ' + targetFile);
});
});
});
| #!/usr/bin/env node
var _ = require('underscore'),
glob = require('glob'),
fs = require('fs'),
mkdirp = require('mkdirp'),
path = require('path'),
generateEntry,
sanitizePath;
generateEntry = function(filepath) {
var contents, entry;
console.log('Creating index entry for: ' + filepath);
// TODO: This require is ugly and should be fixed in a better way later
contents = require('../' + filepath);
entry = {
file: sanitizePath(filepath),
name: contents.name
};
if (contents.percentDone) {
entry.percentDone = contents.percentDone;
};
return entry;
};
sanitizePath = function(filepath) {
// TODO: This trim is ugly. Please clean up
return filepath.replace(/^data\//,"");
};
glob("data/**/*.json", function (err, files) {
if (err) {
console.log('Encountered file search error, aborting...');
console.log(err);
return;
}
var index = _.map(files, generateEntry),
targetFile = 'dist/data/directory.json';
console.log(index);
mkdirp(path.dirname(targetFile), function (err) {
if (err) {
console.log(err);
return;
}
fs.writeFile(targetFile, JSON.stringify(index), function(err) {
if(err) {
console.log(err);
return;
}
console.log('The index was sucessfully saved to: ' + targetFile);
});
});
});
|
Make queued jobs the default. | <?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class JobMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:job';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new job class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Job';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
if ($this->option('sync')) {
return __DIR__.'/stubs/job.stub';
} else {
return __DIR__.'/stubs/job-queued.stub';
}
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Jobs';
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['sync', null, InputOption::VALUE_NONE, 'Indicates that job should be synchronous.'],
];
}
}
| <?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
class JobMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:job';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new job class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Job';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
if ($this->option('queued')) {
return __DIR__.'/stubs/job-queued.stub';
} else {
return __DIR__.'/stubs/job.stub';
}
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Jobs';
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['queued', null, InputOption::VALUE_NONE, 'Indicates that job should be queued.'],
];
}
}
|
Make kafka client a field in Reader | # -*- coding: utf-8 -*-
import logging
import time
from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
class KafkaReader(object):
def __init__(self, host, port, group, topic, connection_wait_time=2):
""" Initialize Kafka reader """
self.host = host
self.port = port
self.group = group
self.topic = topic
self.connection_wait_time = connection_wait_time
def connect(self):
connection = "{0}:{1}".format(self.host, self.port)
logging.info("Connecting to Kafka at {}...", connection)
self.kafka_client = KafkaClient(connection)
self.consumer = SimpleConsumer(self.kafka_client,
self.group,
self.topic)
def read(self):
""" Yield messages from Kafka topic """
while True:
try:
self.connect()
for raw_message in self.consumer:
yield raw_message.message.value
except Exception:
logging.error("Connection to Kafka lost. Trying to reconnect to {}:{}...",
self.host, self.port)
time.sleep(self.connection_wait_time)
| # -*- coding: utf-8 -*-
import logging
import time
from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
class KafkaReader(object):
def __init__(self, host, port, group, topic, connection_wait_time=2):
""" Initialize Kafka reader """
self.host = host
self.port = port
self.group = group
self.topic = topic
self.connection_wait_time = connection_wait_time
def connect(self):
connection = "{0}:{1}".format(self.host, self.port)
logging.info("Connecting to Kafka at {}...", connection)
kafka_client = KafkaClient(connection)
self.consumer = SimpleConsumer(kafka_client,
self.group,
self.topic)
def read(self):
""" Yield messages from Kafka topic """
while True:
try:
self.connect()
for raw_message in self.consumer:
yield raw_message.message.value
except Exception:
logging.error("Connection to Kafka lost. Trying to reconnect to {}:{}...",
self.host, self.port)
time.sleep(self.connection_wait_time)
|
Add a command to find a measurement by id. | # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
)
def define_tables(metadata):
Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('note', String(140), nullable=True),
Column('date_measured', Date(), nullable=False),
)
class Db(object):
def __init__(self, engine):
self._meta = MetaData(engine)
define_tables(self._meta)
def make_tables(self):
self._meta.create_all()
def drop_tables(self):
self._meta.drop_all()
@property
def measurement(self):
return self._meta.tables['measurement']
class MeasurementService(object):
def __init__(self, table):
self._table = table
def find(self, id):
stmt = self._table.select(self._table.c.id == id)
row = stmt.execute().fetchone()
return self.make_exposable(row)
def find_all(self):
s = self._table.select()
items = []
for item in s.execute():
items.append(self.make_exposable(item))
return items
def create(self, **kwargs):
i = self._table.insert()
i.execute(**kwargs)
def make_exposable(self, measurement):
return {
'id': measurement.id,
'weight': float(measurement.weight),
'code': measurement.code,
}
| # -*- coding: utf-8 -*-
from sqlalchemy import (
Column,
Date,
Integer,
MetaData,
Numeric,
String,
Table,
)
def define_tables(metadata):
Table('measurement', metadata,
Column('id', Integer, primary_key=True),
Column('weight', Numeric(4, 1), nullable=False),
Column('code', String(25), nullable=False),
Column('note', String(140), nullable=True),
Column('date_measured', Date(), nullable=False),
)
class Db(object):
def __init__(self, engine):
self._meta = MetaData(engine)
define_tables(self._meta)
def make_tables(self):
self._meta.create_all()
def drop_tables(self):
self._meta.drop_all()
@property
def measurement(self):
return self._meta.tables['measurement']
class MeasurementService(object):
def __init__(self, table):
self._table = table
def find_all(self):
s = self._table.select()
items = []
for item in s.execute():
items.append(self.make_exposable(item))
return items
def create(self, **kwargs):
i = self._table.insert()
i.execute(**kwargs)
def make_exposable(self, measurement):
return {
'id': measurement.id,
'weight': float(measurement.weight),
'code': measurement.code,
}
|
Add connect function to mockBluetooth | /* global navigator, Promise*/
import Ember from 'ember';
const Mock = Ember.Object.extend({
available: true,
name: null,
value: null,
isAvailable(value) {
return this._setAndMock('available', value);
},
deviceName(deviceName) {
return this._setAndMock('name', deviceName);
},
characteristicValue(value) {
return this._setAndMock('value', value);
},
_setAndMock(key, value) {
this.set(key, value);
this._mock();
return this;
},
_mock() {
let isAvailable = this.get('available');
let deviceName = this.get('name');
let characteristicValue = this.get('value');
let bluetooth;
if (isAvailable) {
bluetooth = {
requestDevice: function() {
return Promise.resolve({
name: deviceName,
gatt: {
connect: function() {
return Promise.resolve({
getPrimaryService: function() {
return Promise.resolve({
getCharacteristic: function() {
return Promise.resolve({
readValue: function() {
return Promise.resolve({
getUint8: function() {
return characteristicValue;
}
});
}
});
}
});
}
});
}
}
});
}
};
}
this._createGetter(bluetooth);
},
_createGetter(value) {
navigator.__defineGetter__('bluetooth', function(){
return value;
});
}
});
export default function mockBluetooth() {
let instance = Mock.create();
return instance;
}
| /* global navigator, Promise*/
import Ember from 'ember';
const Mock = Ember.Object.extend({
available: true,
name: null,
value: null,
isAvailable(value) {
return this._setAndMock('available', value);
},
deviceName(deviceName) {
return this._setAndMock('name', deviceName);
},
characteristicValue(value) {
return this._setAndMock('value', value);
},
_setAndMock(key, value) {
this.set(key, value);
this._mock();
return this;
},
_mock() {
let isAvailable = this.get('available');
let deviceName = this.get('name');
let characteristicValue = this.get('value');
let bluetooth;
if (isAvailable) {
bluetooth = {
requestDevice: function() {
return Promise.resolve({
name: deviceName,
gatt: function() {
return Promise.resolve({
getPrimaryService: function() {
return Promise.resolve({
getCharacteristic: function() {
return Promise.resolve({
readValue: function() {
return Promise.resolve({
getUint8: function() {
return characteristicValue;
}
});
}
});
}
});
}
});
}
});
}
};
}
this._createGetter(bluetooth);
},
_createGetter(value) {
navigator.__defineGetter__('bluetooth', function(){
return value;
});
}
});
export default function mockBluetooth() {
let instance = Mock.create();
return instance;
}
|
FIX tests: add connection parameters | <?php
namespace CassandraPDO4Doctrine\tests;
use CassandraPDO4Doctrine\Doctrine\DBAL\DriverManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;
class CP4DBaseTestCase extends \PHPUnit_Framework_TestCase {
static protected function _getDataDir() {
return realpath(__DIR__ . '/../data');
}
static public function setUpBeforeClass() {
$D = self::_getDataDir();
system("cqlsh < {$D}/db_create.cql3");
}
static public function tearDownAfterClass() {
$D = self::_getDataDir();
system("cqlsh < {$D}/db_drop.cql3");
}
public function setUp() {
$D = self::_getDataDir();
system("cqlsh < {$D}/db_data.cql3");
}
/**
* @return EntityManager
* @throws \Doctrine\ORM\ORMException
*/
public function getEntityManager() {
$paths = array(__DIR__ . "/entity/");
$isDevMode = true;
// the connection configuration
$dbParams = array(
'driver' => 'pdo_cassandra',
'host' => 'localhost',
'port' => '9160',
'cqlversion' => '3.0.0',
'user' => $GLOBALS['DB_USER'],
'password' => $GLOBALS['DB_PASSWD'],
'dbname' => $GLOBALS['DB_DBNAME'],
);
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode,null,null,false);
$conn = DriverManager::getConnection($dbParams,$config);
$entityManager = EntityManager::create($conn, $config);
return $entityManager;
}
} | <?php
namespace CassandraPDO4Doctrine\tests;
use CassandraPDO4Doctrine\Doctrine\DBAL\DriverManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;
class CP4DBaseTestCase extends \PHPUnit_Framework_TestCase {
static protected function _getDataDir() {
return realpath(__DIR__ . '/../data');
}
static public function setUpBeforeClass() {
$D = self::_getDataDir();
system("cqlsh < {$D}/db_create.cql3");
}
static public function tearDownAfterClass() {
$D = self::_getDataDir();
system("cqlsh < {$D}/db_drop.cql3");
}
public function setUp() {
$D = self::_getDataDir();
system("cqlsh < {$D}/db_data.cql3");
}
/**
* @return EntityManager
* @throws \Doctrine\ORM\ORMException
*/
public function getEntityManager() {
$paths = array(__DIR__ . "/entity/");
$isDevMode = true;
// the connection configuration
$dbParams = array(
'driver' => 'pdo_cassandra',
'user' => $GLOBALS['DB_USER'],
'password' => $GLOBALS['DB_PASSWD'],
'dbname' => $GLOBALS['DB_DBNAME'],
);
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode,null,null,false);
$conn = DriverManager::getConnection($dbParams,$config);
$entityManager = EntityManager::create($conn, $config);
return $entityManager;
}
} |
Allow updating of pick lock time | <?php
namespace SofaChamps\Bundle\BowlPickemBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class SeasonAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General')
->add('season')
->add('picksLockAt', null, array('required' => false))
->add('locked', null, array('required' => false))
->end()
->with('Points')
->add('gamePoints')
->add('championshipPoints')
->end()
->with('Championship/Playoffs')
->add('hasChampionship', null, array('required' => false))
->add('championshipWinner')
->end()
;
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('season')
;
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('season')
->add('locked')
->add('picksLockAt')
;
}
}
| <?php
namespace SofaChamps\Bundle\BowlPickemBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class SeasonAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General')
->add('season')
->add('locked', null, array('required' => false))
->end()
->with('Points')
->add('gamePoints')
->add('championshipPoints')
->end()
->with('Championship/Playoffs')
->add('hasChampionship', null, array('required' => false))
->add('championshipWinner')
->end()
;
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('season')
;
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('season')
->add('locked')
->add('picksLockAt')
;
}
}
|
Fix: Use Manager to annotate vote count | import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
| import json
from django import template
from django.utils.html import format_html
from rest_framework.renderers import JSONRenderer
from .. import serializers
register = template.Library()
@register.simple_tag(takes_context=True)
def react_polls(context, question):
user = context['request'].user
user_choices = question.user_choices_list(user)
# TODO: use serializer
data = {
'label': question.label,
'choices': [{
'label': choice.label,
'count': choice.vote_count,
'ownChoice': (choice.pk in user_choices)
} for choice in question.choices.annotate_with_vote_count()]
}
return format_html(
(
'<div id="{id}" data-question="{question}"></div>'
'<script>window.adhocracy4.renderPolls("{id}")</script>'
),
id='question-%s' % (question.pk,),
question=json.dumps(data)
)
@register.simple_tag
def react_poll_form(poll):
serializer = serializers.PollSerializer(poll)
data_poll = JSONRenderer().render(serializer.data)
return format_html(
(
'<div id="{id}" data-poll="{poll}"></div>'
'<script>window.adhocracy4.renderPollManagement("{id}")</script>'
),
id='question-%s' % (poll.pk,),
poll=data_poll
)
|
Rewrite the main script according to the whole refactoring. |
( function( mdash, $ )
{
$( document ).ready( function()
{
var manager = new mdash.Manager(),
fontCtrl = new mdash.FontCtrl( $( '#fontctrl > a' ) ),
helpCtrl = new mdash.HelpCtrl( $( '#helpctrl' ), $( '#getstarted' ), $( '#bookmarks' ) );
manager.init( function()
{
fontCtrl.init();
helpCtrl.init();
var leftColumn = new mdash.Column( $( '#bookmarks > .left' ) ),
rightColumn = new mdash.Column( $( '#bookmarks > .right' ) );
manager.getSections( 'left', function( sections )
{
leftColumn.sections = sections;
leftColumn.render();
} );
manager.getSections( 'right', function( sections )
{
rightColumn.sections = sections;
rightColumn.render();
} );
} );
} );
} )( window.mdash, Zepto );
|
( function( $, d, undefined )
{
d._ = window.console.debug.bind( window.console );
d.init = function()
{
d.initFontSize();
d.initHelp();
d.initManager();
};
d.initManager = function()
{
this.manager = new d.Manager();
this.manager.initialize( this.initView.bind( this ) );
};
d.initFontSize = ( function()
{
var $sizes = $( '#fontSize > a' );
return function()
{
if( localStorage.fontSize )
{
document.body.className = localStorage.fontSize;
$sizes.removeClass( 'selected' );
$sizes.parent().find( 'a[data-size="' + localStorage.fontSize + '"]' ).addClass( 'selected' );
}
$sizes.bind( 'click', function( e )
{
var $this = $( e.target );
$this.siblings().removeClass( 'selected' );
$this.addClass( 'selected' );
document.body.className = localStorage.fontSize = $this.attr( 'data-size' );
} );
}
} )();
d.initView = function()
{
var self = this;
this.manager.hasBookmarks( function( hasBoomarks )
{
if( hasBoomarks )
{
self.view = new d.View( $( '#bookmarks' ), self.manager );
self.view.display();
}
else
{
self.showHelp();
}
} );
};
d.initHelp = function()
{
$( '#help' ).bind( 'click', d.toggleHelp.bind( d ) );
};
d.showHelp = function()
{
$( '#getstarted' ).show();
$( '#bookmarks' ).hide();
};
d.toggleHelp = function()
{
$( '#getstarted' ).toggle();
$( '#bookmarks' ).toggle();
};
d.init();
} )( Zepto, this.Dashboard );
|
Add test for custom css | from django.test import TestCase, RequestFactory
from molo.core.tests.base import MoloTestCaseMixin
from freebasics.views import HomeView
from freebasics.templatetags import freebasics_tags
class EnvTestCase(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
def test_block_ordering(self):
with self.settings(BLOCK_POSITION_BANNER=4,
BLOCK_POSITION_LATEST=3,
BLOCK_POSITION_QUESTIONS=2,
BLOCK_POSITION_SECTIONS=1):
factory = RequestFactory()
request = factory.get('/')
request.site = self.site
home = HomeView()
home.request = request
context = home.get_context_data()
self.assertEquals(context['blocks'][0], (
'blocks/sections.html', 1))
self.assertEquals(context['blocks'][1], (
'blocks/questions.html', 2))
self.assertEquals(context['blocks'][2], ('blocks/latest.html', 3))
self.assertEquals(context['blocks'][3], ('blocks/banners.html', 4))
def test_css_vars(self):
with self.settings(CUSTOM_CSS_BLOCK_TEXT_TRANSFORM="lowercase",
CUSTOM_CSS_ACCENT_2="red"):
styles = freebasics_tags.custom_css(context='')
self.assertEquals(styles['accent_2'], 'red')
self.assertEquals(styles['text_transform'], 'lowercase')
def test_custom_css(self):
response = self.client.get('/')
self.assertContains(response, '.fb-body .base-bcolor')
self.assertContains(response, '.fb-body .block-heading')
self.assertContains(response, '.section-nav__items')
| from django.test import TestCase, RequestFactory
from molo.core.tests.base import MoloTestCaseMixin
from freebasics.views import HomeView
from freebasics.templatetags import freebasics_tags
class EnvTestCase(TestCase, MoloTestCaseMixin):
def setUp(self):
self.mk_main()
def test_block_ordering(self):
with self.settings(BLOCK_POSITION_BANNER=4,
BLOCK_POSITION_LATEST=3,
BLOCK_POSITION_QUESTIONS=2,
BLOCK_POSITION_SECTIONS=1):
factory = RequestFactory()
request = factory.get('/')
request.site = self.site
home = HomeView()
home.request = request
context = home.get_context_data()
self.assertEquals(context['blocks'][0], (
'blocks/sections.html', 1))
self.assertEquals(context['blocks'][1], (
'blocks/questions.html', 2))
self.assertEquals(context['blocks'][2], ('blocks/latest.html', 3))
self.assertEquals(context['blocks'][3], ('blocks/banners.html', 4))
def test_css_vars(self):
with self.settings(CUSTOM_CSS_BLOCK_TEXT_TRANSFORM="lowercase",
CUSTOM_CSS_ACCENT_2="red"):
styles = freebasics_tags.custom_css(context='')
self.assertEquals(styles['accent_2'], 'red')
self.assertEquals(styles['text_transform'], 'lowercase')
|
Make it easier to generate images for each demo | module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
// Store your Package file so you can reference its specific data whenever necessary
pkg: grunt.file.readJSON('package.json'),
imageDirectory: {
default: 'Demo - Grunt/Assets/Images/',
lazyload: 'Demo - Lazy Load/Assets/Images/'
},
// grunt responsive_images:dev:default
// grunt responsive_images:dev:lazyload
responsive_images: {
dev: {
options: {
sizes: [
{
width: 320,
},
{
width: 640
},
{
width: 1024
}
]
},
files: [{
expand: true,
cwd: '<%= imageDirectory[grunt.task.current.args[0]] %>',
src: ['*.{jpg,gif,png}'],
dest: '<%= imageDirectory[grunt.task.current.args[0]] %>Generated/'
}]
}
}
});
// Load NPM Tasks
grunt.loadNpmTasks('grunt-responsive-images');
// Default Task
grunt.registerTask('default', ['responsive_images:dev']);
};
| module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
// Store your Package file so you can reference its specific data whenever necessary
pkg: grunt.file.readJSON('package.json'),
imageDirectory: 'Demo - Grunt/Assets/Images/',
responsive_images: {
dev: {
options: {
sizes: [
{
width: 320,
},
{
width: 640
},
{
width: 1024
}
]
},
files: [{
expand: true,
cwd: '<%= imageDirectory %>',
src: ['*.{jpg,gif,png}'],
dest: '<%= imageDirectory %>Generated/'
}]
}
}
});
// Load NPM Tasks
grunt.loadNpmTasks('grunt-responsive-images');
// Default Task
grunt.registerTask('default', ['responsive_images:dev']);
};
|
Update title for the sub sidebar
Fix https://github.com/ProtonMail/proton-vpn-settings/issues/105 | import React, { useState, useEffect } from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
const SubSidebar = ({ list = [], children }) => {
const clean = (h = '') => h.replace(/#/g, '');
const [hash, setHash] = useState(clean(location.hash));
const onHashChange = () => setHash(clean(location.hash));
useEffect(() => {
window.addEventListener('hashchange', onHashChange);
return () => {
window.removeEventListener('hashchange', onHashChange);
};
}, []);
return (
<div className="subnav notablet nomobile bg-global-light noprint">
<div className="subnav-inner">
<p className="uppercase smaller">{c('Title').t`Navigation`}</p>
<ul className="unstyled subnav-list">
{list.map(({ id = '', text }) => {
const isCurrent = hash === id;
return (
<li key={id} className="mb0-5">
<a
href={`${location.pathname}#${id}`}
className="subnav-link"
disabled={isCurrent}
aria-current={isCurrent}
>
{text}
</a>
</li>
);
})}
</ul>
<div>{children}</div>
</div>
</div>
);
};
SubSidebar.propTypes = {
list: PropTypes.array,
children: PropTypes.node
};
export default SubSidebar;
| import React, { useState, useEffect } from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
const SubSidebar = ({ list = [], children }) => {
const clean = (h = '') => h.replace(/#/g, '');
const [hash, setHash] = useState(clean(location.hash));
const onHashChange = () => setHash(clean(location.hash));
useEffect(() => {
window.addEventListener('hashchange', onHashChange);
return () => {
window.removeEventListener('hashchange', onHashChange);
};
}, []);
return (
<div className="subnav notablet nomobile bg-global-light noprint">
<div className="subnav-inner">
<p className="uppercase smaller">{c('Title').t`Jump to`}</p>
<ul className="unstyled subnav-list">
{list.map(({ id = '', text }) => {
const isCurrent = hash === id;
return (
<li key={id} className="mb0-5">
<a
href={`${location.pathname}#${id}`}
className="subnav-link"
disabled={isCurrent}
aria-current={isCurrent}
>
{text}
</a>
</li>
);
})}
</ul>
<div>{children}</div>
</div>
</div>
);
};
SubSidebar.propTypes = {
list: PropTypes.array,
children: PropTypes.node
};
export default SubSidebar;
|
Add checkbox to API permissions | import React from "react";
import PropTypes from "prop-types";
import { map, sortBy } from "lodash-es";
import { ListGroup, Panel } from "react-bootstrap";
import { ListGroupItem, Checkbox } from "../../../base/index";
export default function APIPermissions ({ style, userPermissions, keyPermissions, onChange }) {
const permissions = map(keyPermissions, (value, key) => ({name: key, allowed: value}));
const rowComponents = map(sortBy(permissions, "name"), permission => {
const disabled = !userPermissions[permission.name];
return (
<ListGroupItem
key={permission.name}
onClick={disabled ? null : () => onChange(permission.name, !permission.allowed)}
disabled={disabled}
>
<code>{permission.name}</code>
<Checkbox
checked={permission.allowed}
pullRight
/>
</ListGroupItem>
);
});
return (
<Panel style={style}>
<Panel.Body>
<ListGroup>
{rowComponents}
</ListGroup>
</Panel.Body>
</Panel>
);
}
APIPermissions.propTypes = {
userPermissions: PropTypes.object.isRequired,
keyPermissions: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
style: PropTypes.object
};
| import React from "react";
import PropTypes from "prop-types";
import { map, sortBy } from "lodash-es";
import { ListGroup, Panel } from "react-bootstrap";
import { Icon, ListGroupItem } from "../../../base/index";
export default function APIPermissions ({ style, userPermissions, keyPermissions, onChange }) {
const permissions = map(keyPermissions, (value, key) => ({name: key, allowed: value}));
const rowComponents = map(sortBy(permissions, "name"), permission => {
const disabled = !userPermissions[permission.name];
return (
<ListGroupItem
key={permission.name}
onClick={disabled ? null : () => onChange(permission.name, !permission.allowed)}
disabled={disabled}
>
<code>{permission.name}</code>
<Icon name={`checkbox-${permission.allowed ? "checked" : "unchecked"}`} pullRight />
</ListGroupItem>
);
});
return (
<Panel style={style}>
<Panel.Body>
<ListGroup>
{rowComponents}
</ListGroup>
</Panel.Body>
</Panel>
);
}
APIPermissions.propTypes = {
userPermissions: PropTypes.object.isRequired,
keyPermissions: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
style: PropTypes.object
};
|
Add getter returning access token with bearer prefix | // Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.api;
import java.util.Objects;
/**
* Represents an Athenz Access Token
*
* @author bjorncs
*/
public class AthenzAccessToken {
public static final String HTTP_HEADER_NAME = "Authorization";
private static final String BEARER_TOKEN_PREFIX = "Bearer ";
private final String value;
public AthenzAccessToken(String value) {
this.value = stripBearerTokenPrefix(value);
}
private static String stripBearerTokenPrefix(String rawValue) {
String stripped = rawValue.strip();
String prefixRemoved = stripped.startsWith(BEARER_TOKEN_PREFIX)
? stripped.substring(BEARER_TOKEN_PREFIX.length()).strip()
: stripped;
if (prefixRemoved.isBlank()) {
throw new IllegalArgumentException(String.format("Access token is blank: '%s'", prefixRemoved));
}
return prefixRemoved;
}
public String value() { return value; }
public String valueWithBearerPrefix() { return BEARER_TOKEN_PREFIX + value; }
@Override public String toString() { return "AthenzAccessToken{value='" + value + "'}"; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AthenzAccessToken that = (AthenzAccessToken) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
| // Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.api;
import java.util.Objects;
/**
* Represents an Athenz Access Token
*
* @author bjorncs
*/
public class AthenzAccessToken {
public static final String HTTP_HEADER_NAME = "Authorization";
private static final String BEARER_TOKEN_PREFIX = "Bearer ";
private final String value;
public AthenzAccessToken(String value) {
this.value = stripBearerTokenPrefix(value);
}
private static String stripBearerTokenPrefix(String rawValue) {
String stripped = rawValue.strip();
String prefixRemoved = stripped.startsWith(BEARER_TOKEN_PREFIX)
? stripped.substring(BEARER_TOKEN_PREFIX.length()).strip()
: stripped;
if (prefixRemoved.isBlank()) {
throw new IllegalArgumentException(String.format("Access token is blank: '%s'", prefixRemoved));
}
return prefixRemoved;
}
public String value() { return value; }
@Override public String toString() { return "AthenzAccessToken{value='" + value + "'}"; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AthenzAccessToken that = (AthenzAccessToken) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
|
CRM-1321: Refactor sync commands
- minor unit tests fixesxy | <?php
namespace Oro\Bundle\IntegrationBundle\Tests\Unit\Utils;
use Oro\Bundle\IntegrationBundle\Utils\FormUtils;
use Oro\Bundle\IntegrationBundle\Manager\TypesRegistry;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestConnector;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestIntegrationType;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestTwoWayConnector;
class FormUtilsTest extends \PHPUnit_Framework_TestCase
{
/** @var TypesRegistry */
protected $typesRegistry;
/** @var FormUtils */
protected $utils;
public function setUp()
{
$this->typesRegistry = new TypesRegistry();
$this->utils = new FormUtils($this->typesRegistry);
}
public function tearDown()
{
unset($this->utils, $this->typesRegistry);
}
public function testHasTwoWaySyncConnectors()
{
$testType = 'type2';
$testTypeThatHasConnectors = 'type1';
$this->typesRegistry->addChannelType($testType, new TestIntegrationType());
$this->typesRegistry->addChannelType($testTypeThatHasConnectors, new TestIntegrationType());
$this->typesRegistry->addConnectorType(uniqid('type'), $testType, new TestConnector());
$this->typesRegistry->addConnectorType(uniqid('type'), $testTypeThatHasConnectors, new TestTwoWayConnector());
$this->assertTrue($this->utils->hasTwoWaySyncConnectors($testTypeThatHasConnectors));
$this->assertFalse($this->utils->hasTwoWaySyncConnectors($testType));
}
}
| <?php
namespace Oro\Bundle\IntegrationBundle\Tests\Unit\Utils;
use Oro\Bundle\IntegrationBundle\Utils\FormUtils;
use Oro\Bundle\IntegrationBundle\Manager\TypesRegistry;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestChannelType;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestConnector;
use Oro\Bundle\IntegrationBundle\Tests\Unit\Fixture\TestTwoWayConnector;
class FormUtilsTest extends \PHPUnit_Framework_TestCase
{
/** @var TypesRegistry */
protected $typesRegistry;
/** @var FormUtils */
protected $utils;
public function setUp()
{
$this->typesRegistry = new TypesRegistry();
$this->utils = new FormUtils($this->typesRegistry);
}
public function tearDown()
{
unset($this->utils, $this->typesRegistry);
}
public function testHasTwoWaySyncConnectors()
{
$testType = 'type2';
$testTypeThatHasConnectors = 'type1';
$this->typesRegistry->addChannelType($testType, new TestChannelType());
$this->typesRegistry->addChannelType($testTypeThatHasConnectors, new TestChannelType());
$this->typesRegistry->addConnectorType(uniqid('type'), $testType, new TestConnector());
$this->typesRegistry->addConnectorType(uniqid('type'), $testTypeThatHasConnectors, new TestTwoWayConnector());
$this->assertTrue($this->utils->hasTwoWaySyncConnectors($testTypeThatHasConnectors));
$this->assertFalse($this->utils->hasTwoWaySyncConnectors($testType));
}
}
|
Use a setter for max_depth | import ab_bridge
import alpha_beta
from gui import *
from player import *
import threading
class AIPlayer(Player):
""" Yes there is a circular dependancy between AIPlayer and Game """
def __init__(self, *args, **vargs):
Player.__init__(self, *args, **vargs)
self.max_depth = 1
def set_max_depth(self, max_depth):
self.max_depth = max_depth
def attach_to_game(self, base_game):
self.ab_game = ab_bridge.ABGame(base_game)
def prompt_for_action(self, base_game, gui, test=False):
if test:
self.search_thread(gui, True)
else:
t = threading.Thread(target=self.search_thread, args=(gui,))
# Allow the program to be exited quickly
t.daemon = True
t.start()
return "%s is thinking" % self.get_name()
def get_type(self):
return "computer"
def search_thread(self, gui, test=False):
ab_game = self.ab_game
move, value = alpha_beta.alphabeta_search(ab_game.current_state, ab_game,
max_depth=self.max_depth)
action = move[0]
if test:
self.action = action
else:
gui.enqueue_action(action)
gui.trig()
# TODO This is only for testing!
def get_action(self, game, gui):
return self.action
| import ab_bridge
import alpha_beta
from gui import *
from player import *
import threading
class AIPlayer(Player):
""" Yes there is a circular dependancy between AIPlayer and Game """
def __init__(self, max_depth, *args, **vargs):
Player.__init__(self, *args, **vargs)
self.max_depth = max_depth
'''
#TODO use super?
def __init__(self, max_depth, *args, **kwargs):
super(AIPlayer, self).__init__(*args, **kwargs)
'''
def attach_to_game(self, base_game):
self.ab_game = ab_bridge.ABGame(base_game)
def prompt_for_action(self, base_game, gui, test=False):
if test:
self.search_thread(gui, True)
else:
t = threading.Thread(target=self.search_thread, args=(gui,))
# Allow the program to be exited quickly
t.daemon = True
t.start()
return "%s is thinking" % self.get_name()
def get_type(self):
return "computer"
def search_thread(self, gui, test=False):
ab_game = self.ab_game
move, value = alpha_beta.alphabeta_search(ab_game.current_state, ab_game,
max_depth=self.max_depth)
action = move[0]
if test:
self.action = action
else:
gui.enqueue_action(action)
gui.trig()
# TODO This is only for testing!
def get_action(self, game, gui):
return self.action
|
Select all fields from from table in song type | <?php
class Denkmal_Elasticsearch_Type_Song extends CM_Elastica_Type_Abstract {
const INDEX_NAME = 'song';
protected $_mapping = array(
'label' => array('type' => 'string'),
);
protected $_indexParams = array(
'index' => array(
'number_of_shards' => 1,
'number_of_replicas' => 0
),
);
protected function _getQuery($ids = null, $limit = null) {
$query = '
SELECT `song`.*
FROM `denkmal_model_song` `song`
';
if (is_array($ids)) {
$query .= ' WHERE song.id IN (' . implode(',', $ids) . ')';
}
if (($limit = (int) $limit) > 0) {
$query .= ' LIMIT ' . $limit;
}
return $query;
}
protected function _getDocument(array $data) {
$doc = new Elastica_Document($data['id'],
array(
'label' => $data['label'],
)
);
return $doc;
}
/**
* @param Denkmal_Model_Song $item
* @return int
*/
protected static function _getIdForItem($item) {
return $item->getId();
}
}
| <?php
class Denkmal_Elasticsearch_Type_Song extends CM_Elastica_Type_Abstract {
const INDEX_NAME = 'song';
protected $_mapping = array(
'label' => array('type' => 'string'),
);
protected $_indexParams = array(
'index' => array(
'number_of_shards' => 1,
'number_of_replicas' => 0
),
);
protected function _getQuery($ids = null, $limit = null) {
$query = '
SELECT song.id, song.label
FROM `denkmal_model_song` song
';
if (is_array($ids)) {
$query .= ' WHERE song.id IN (' . implode(',', $ids) . ')';
}
if (($limit = (int) $limit) > 0) {
$query .= ' LIMIT ' . $limit;
}
return $query;
}
protected function _getDocument(array $data) {
$doc = new Elastica_Document($data['id'],
array(
'label' => $data['label'],
)
);
return $doc;
}
/**
* @param Denkmal_Model_Song $item
* @return int
*/
protected static function _getIdForItem($item) {
return $item->getId();
}
}
|
Add spaces to increase readability.
"OSF-4419" |
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
from rest_framework import status
from rest_framework.exceptions import APIException
def json_api_exception_handler(exc, context):
""" Custom exception handler that returns errors object as an array """
# Import inside method to avoid errors when the OSF is loaded without Django
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
# Error objects may have the following members. Title removed to avoid clash with node "title" errors.
top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta']
errors = []
if response:
message = response.data
if isinstance(message, dict):
for key, value in message.iteritems():
if key in top_level_error_keys:
errors.append({key: value})
else:
if isinstance(value, list):
for reason in value:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': reason})
else:
errors.append({'source': {'pointer': '/data/attributes/' + key}, 'detail': value})
elif isinstance(message, (list, tuple)):
for error in message:
errors.append({'detail': error})
else:
errors.append({'detail': message})
response.data = {'errors': errors}
return response
# Custom Exceptions the Django Rest Framework does not support
class Gone(APIException):
status_code = status.HTTP_410_GONE
default_detail = ('The requested resource is no longer available.')
|
Update integration test coverage threshold | const TEST_TYPE = ((argv) => {
let match = argv[argv.length - 1].match(/npm\/test-(\w+).js/);
return match && match[1] || '';
})(process.argv);
function configOverrides (testType) {
switch (testType) {
case 'cli':
return {
statements: 80,
branches: 65,
functions: 85,
lines: 80
};
case 'integration':
return {
statements: 35,
branches: 20,
functions: 35,
lines: 35
};
case 'library':
return {
statements: 55,
branches: 40,
functions: 55,
lines: 55
};
case 'unit':
return {
statements: 70,
branches: 55,
functions: 75,
lines: 75
};
default:
return {}
}
}
module.exports = {
all: true,
'check-coverage': true,
'report-dir': '.coverage',
'temp-dir': '.nyc_output',
include: ['lib/**/*.js', 'bin/**/*.js'],
reporter: ['lcov', 'json', 'text', 'text-summary'],
...configOverrides(TEST_TYPE),
};
| const TEST_TYPE = ((argv) => {
let match = argv[argv.length - 1].match(/npm\/test-(\w+).js/);
return match && match[1] || '';
})(process.argv);
function configOverrides (testType) {
switch (testType) {
case 'cli':
return {
statements: 80,
branches: 65,
functions: 85,
lines: 80
};
case 'integration':
return {
statements: 40,
branches: 20,
functions: 40,
lines: 40
};
case 'library':
return {
statements: 55,
branches: 40,
functions: 55,
lines: 55
};
case 'unit':
return {
statements: 70,
branches: 55,
functions: 75,
lines: 75
};
default:
return {}
}
}
module.exports = {
all: true,
'check-coverage': true,
'report-dir': '.coverage',
'temp-dir': '.nyc_output',
include: ['lib/**/*.js', 'bin/**/*.js'],
reporter: ['lcov', 'json', 'text', 'text-summary'],
...configOverrides(TEST_TYPE),
};
|
Fix incorrect unit test annotations | <?php
namespace Gamajo\EmailAddress;
class EmailAddressTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \Gamajo\EmailAddress\EmailAddress::__construct
* @expectedException \InvalidArgumentException
*/
public function testCannotBeConstructedFromInvalidEmailAddress()
{
new EmailAddress('abc.example.com');
}
/**
* @covers \Gamajo\EmailAddress\EmailAddress::__construct
* @dataProvider emailAddresses
*/
public function testCanBeConstructedFromValidEmailAddress($address)
{
$e = new EmailAddress($address);
$this->assertInstanceOf('Gamajo\\EmailAddress\\EmailAddress', $e);
}
/**
* @covers \Gamajo\EmailAddress\EmailAddress::__construct
* @covers \Gamajo\EmailAddress\EmailAddress::getLocalPart
* @dataProvider emailAddresses
*/
public function testEmailAddressLocalPart($address, $localpart, $domain)
{
$a = new EmailAddress($address);
$this->assertEquals(
$localpart,
$a->getLocalPart()
);
}
/**
* @covers \Gamajo\EmailAddress\EmailAddress::__construct
* @covers \Gamajo\EmailAddress\EmailAddress::getDomain
* @dataProvider emailAddresses
*/
public function testEmailAddressDomain($address, $localpart, $domain)
{
$a = new EmailAddress($address);
$this->assertEquals(
$domain,
$a->getDomain()
);
}
public function emailAddresses() {
return [
['[email protected]', 'me', 'example.com'],
['"S@m"@example.com', '"S@m"', 'example.com'],
];
}
}
| <?php
namespace Gamajo\EmailAddress;
class EmailAddressTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \Gamajo\EmailAddress::__construct
* @expectedException \InvalidArgumentException
*/
public function testCannotBeConstructedFromInvalidEmailAddress()
{
new EmailAddress('abc.example.com');
}
/**
* @covers \Gamajo\EmailAddress::__construct
* @dataProvider emailAddresses
*/
public function testCanBeConstructedFromValidEmailAddress($address)
{
$e = new EmailAddress($address);
$this->assertInstanceOf('Gamajo\\EmailAddress\\EmailAddress', $e);
}
/**
* @covers \Gamajo\EmailAddress::__construct
* @dataProvider emailAddresses
*/
public function testEmailAddressLocalPart($address, $localpart, $domain)
{
$a = new EmailAddress($address);
$this->assertEquals(
$localpart,
$a->getLocalPart()
);
}
/**
* @covers \Gamajo\EmailAddress::__construct
* @dataProvider emailAddresses
*/
public function testEmailAddressDomain($address, $localpart, $domain)
{
$a = new EmailAddress($address);
$this->assertEquals(
$domain,
$a->getDomain()
);
}
public function emailAddresses() {
return [
['[email protected]', 'me', 'example.com'],
['"S@m"@example.com', '"S@m"', 'example.com'],
];
}
}
|
Allow setting the plates file extension | <?php
namespace Rych\Silex\Provider;
use Silex\Application;
use Silex\ServiceProviderInterface;
use Rych\Plates\Extension\RoutingExtension;
use Rych\Plates\Extension\SecurityExtension;
class PlatesServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['plates.path'] = null;
$app['plates.extension'] = 'php';
$app['plates.folders'] = array();
$app['plates.engine'] = $app->share(function ($app) {
$engine = new \League\Plates\Engine(
$app['plates.path'],
$app['plates.extension']
);
foreach ($app['plates.folders'] as $name => $path) {
$engine->addFolder($name, $path);
}
if (isset($app['url_generator'])) {
$engine->loadExtension(new RoutingExtension($app['url_generator']));
}
if (isset($app['security'])) {
$engine->loadExtension(new SecurityExtension($app['security']));
}
return $engine;
});
$app['plates'] = function ($app) {
$plates = $app['plates.engine'];
$plates->addData([
'app' => $app
]);
return $plates;
};
}
public function boot(Application $app)
{
}
}
| <?php
namespace Rych\Silex\Provider;
use Silex\Application;
use Silex\ServiceProviderInterface;
use Rych\Plates\Extension\RoutingExtension;
use Rych\Plates\Extension\SecurityExtension;
class PlatesServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['plates.path'] = null;
$app['plates.folders'] = array ();
$app['plates.engine'] = $app->share(function ($app) {
$engine = new \League\Plates\Engine($app['plates.path']);
foreach ($app['plates.folders'] as $name => $path) {
$engine->addFolder($name, $path);
}
if (isset($app['url_generator'])) {
$engine->loadExtension(new RoutingExtension($app['url_generator']));
}
if (isset($app['security'])) {
$engine->loadExtension(new SecurityExtension($app['security']));
}
return $engine;
});
$app['plates'] = function ($app) {
$plates = $app['plates.engine'];
$plates->addData([
'app' => $app
]);
return $plates;
};
}
public function boot(Application $app)
{
}
}
|
Add privilege check on follow button | var addFollowers = require('./follow');
var checkAuth = require('./check_auth');
var checkPrivilege = require('./privilege_check');
var githubOAuth = require('./github_oauth');
var users = require('./db').get('users');
module.exports = function(app) {
app.get('/me', checkAuth, function(req, res) {
checkPrivilege(req.session.user.login, function(err, privilege) {
users.find({
following: req.session.user.login
}, function(err, following) {
res.json({
privilege: privilege,
following: following
});
});
});
});
app.get('/user', checkAuth, function(req, res) {
return res.json(req.session.user);
});
app.post('/follow/:login', checkAuth, function(req, res) {
checkPrivilege(req.session.user.login, function(err, privilege) {
users.findOne({
login: req.session.user.login
}, function(error, user) {
var amount = privilege.following - user.following;
addFollowers(req.session.user.login, amount, function(err, result) {
res.json(result);
});
});
});
});
githubOAuth.addRoutes(app, function(err, token, res, ignore, req) {
if (token.error) {
return res.send('There was an error logging in: ' + token.error_description);
}
req.session.token = token.access_token;
res.redirect('/');
});
};
| var addFollowers = require('./follow');
var checkAuth = require('./check_auth');
var checkPrivilege = require('./privilege_check');
var githubOAuth = require('./github_oauth');
var users = require('./db').get('users');
module.exports = function(app) {
app.get('/me', checkAuth, function(req, res) {
checkPrivilege(req.session.user.login, function(err, privilege) {
users.find({
following: req.session.user.login
}, function(err, following) {
res.json({
privilege: privilege,
following: following
});
});
});
});
app.get('/user', checkAuth, function(req, res) {
return res.json(req.session.user);
});
app.post('/follow/:login', function(req, res) {
if (!req.session.user) {
return res.status(401).json({
error: 'Not logged in'
});
}
var amount = req.body.amount;
if (!amount) {
amount = 10;
}
addFollowers(req.session.user.login, -1, function(err, result) {
res.json(result);
});
});
githubOAuth.addRoutes(app, function(err, token, res, ignore, req) {
if (token.error) {
return res.send('There was an error logging in: ' + token.error_description);
}
req.session.token = token.access_token;
res.redirect('/');
});
};
|
Add Display.html_contact js method that injects rendered contact template onto page | $(document).ready(function(){
console.log("Connected");
Search.form_listener();
Display.list_listener();
})
var Search = (function(){
return{
form_listener: function(){
$("#search_container").on("submit", "#search_form", function(event){
event.preventDefault();
var formData = $("input[name='search']").serialize();
Search.request_search(formData);
})
},
request_search: function(formData){
var ajaxFind =
$.ajax({
type: "POST",
url: "search/find",
data: formData,
dataType: "HTML"
});
ajaxFind.done(function(response){
Search.html_results(response);
})
},
html_results: function(responsePackage){
$("#results_container").html(responsePackage);
}
}
}())
var Display = (function(){
return {
list_listener: function(){
$("#results_container").on("click", "a", function(event){
event.preventDefault();
var contact_id = $(this).attr("data-id");
Display.request_contact_template(contact_id);
})
},
request_contact_template: function(id){
var packageData = {id: id};
var ajaxDisplay =
$.ajax({
type: "POST",
url: "search/display",
data: packageData,
dataType: "HTML"
});
ajaxDisplay.done(function(response){
Display.html_contact(response);
})
},
html_contact: function(responsePackage){
$("#show_container").html(responsePackage);
}
};
}()) | $(document).ready(function(){
console.log("Connected");
Search.form_listener();
Display.list_listener();
})
var Search = (function(){
return{
form_listener: function(){
$("#search_container").on("submit", "#search_form", function(event){
event.preventDefault();
var formData = $("input[name='search']").serialize();
Search.request_search(formData);
})
},
request_search: function(formData){
var ajaxFind =
$.ajax({
type: "POST",
url: "search/find",
data: formData,
dataType: "HTML"
});
ajaxFind.done(function(response){
Search.html_results(response);
})
},
html_results: function(responsePackage){
$("#results_container").html(responsePackage);
}
}
}())
var Display = (function(){
return {
list_listener: function(){
$("#results_container").on("click", "a", function(event){
event.preventDefault();
var contact_id = $(this).attr("data-id");
Display.request_contact_template(contact_id);
})
},
request_contact_template: function(id){
var packageData = {id: id};
var ajaxDisplay =
$.ajax({
type: "POST",
url: "search/display",
data: packageData,
dataType: "HTML"
});
ajaxDisplay.done(function(response){
console.log(response);
})
}
};
}()) |
Remove useless parameters in createShortLink | <?php
$__ROOT__ = dirname(__FILE__)."../..";
require_once $__ROOT__."/lib/lib.php";
if(isset($_POST["k"]))
{
if(apiKeyExist($_POST["k"]))
{
$filename = cleanString(basename($_FILES["img"]["name"]));
$outpath = $_SERVER["DOCUMENT_ROOT"]."/ciconia/img/".$_POST["k"]."/";
if(!file_exists($outpath.$filename))
{
if(filesize($_FILES["img"]["tmp_name"]) < __MAX_SIZE__)
{
if(move_uploaded_file($_FILES["img"]["tmp_name"], $outpath.$filename))
{
createThumbnail($outpath, $filename);
echo(createShortLink("img/".$_POST["k"]."/".$filename));
}
else
{
echo("-1\n");
}
}
else
{
echo("-4\n");
}
}
else
{
echo("-2\n");
}
}
else
{
echo("-5\n");
}
}
else
{
echo("-3\n");
}
?>
| <?php
$__ROOT__ = dirname(__FILE__)."../..";
require_once $__ROOT__."/lib/lib.php";
if(isset($_POST["k"]))
{
if(apiKeyExist($_POST["k"]))
{
$filename = cleanString(basename($_FILES["img"]["name"]));
$outpath = $_SERVER["DOCUMENT_ROOT"]."/ciconia/img/".$_POST["k"]."/";
if(!file_exists($outpath.$filename))
{
if(filesize($_FILES["img"]["tmp_name"]) < __MAX_SIZE__)
{
if(move_uploaded_file($_FILES["img"]["tmp_name"], $outpath.$filename))
{
createThumbnail($outpath, $filename);
echo(createShortLink("img/".$_POST["k"]."/".$filename, $_POST['k']));
}
else
{
echo("-1\n");
}
}
else
{
echo("-4\n");
}
}
else
{
echo("-2\n");
}
}
else
{
echo("-5\n");
}
}
else
{
echo("-3\n");
}
?>
|
Improve interpunction in error messages | <?php
namespace Mollie\Api\Exceptions;
class ApiException extends \Exception
{
/**
* @var string
*/
protected $field;
/**
* @var string
*/
protected $documentationUrl;
/**
* @param string $message
* @param int $code
* @param string|null $field
* @param string|null $documentationUrl
* @param \Throwable|null $previous
*/
public function __construct($message = "", $code = 0, $field = null, $documentationUrl = null, \Throwable $previous = null)
{
if (!empty($field)) {
$this->field = (string)$field;
$message .= ". Field: {$this->field}";
}
if (!empty($documentationUrl)) {
$this->documentationUrl = (string)$documentationUrl;
$message .= ". Documentation: {$this->documentationUrl}";
}
parent::__construct($message, $code, $previous);
}
/**
* @return string
*/
public function getField()
{
return $this->field;
}
/**
* @return string
*/
public function getDocumentationUrl()
{
return $this->documentationUrl;
}
}
| <?php
namespace Mollie\Api\Exceptions;
class ApiException extends \Exception
{
/**
* @var string
*/
protected $field;
/**
* @var string
*/
protected $documentationUrl;
/**
* @param string $message
* @param int $code
* @param string|null $field
* @param string|null $documentationUrl
* @param \Throwable|null $previous
*/
public function __construct($message = "", $code = 0, $field = null, $documentationUrl = null, \Throwable $previous = null)
{
if (!empty($field)) {
$this->field = (string)$field;
$message .= " Field: {$this->field}.";
}
if (!empty($documentationUrl)) {
$this->documentationUrl = (string)$documentationUrl;
$message .= " Documentation: {$this->documentationUrl}.";
}
parent::__construct($message, $code, $previous);
}
/**
* @return string
*/
public function getField()
{
return $this->field;
}
/**
* @return string
*/
public function getDocumentationUrl()
{
return $this->documentationUrl;
}
}
|
Remove traditional way of getting logged in username. | package space.hideaway.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import space.hideaway.model.SearchModel;
import space.hideaway.services.UserService;
@Controller
public class RouteController
{
@Autowired
UserService userService;
/**
* The endpoint for the application home page.
* Secured: No
* Method: GET
* <p>
* Sample URL: / or /home
*
* @return The path to the index page template.
*/
@GetMapping({"/", "/home"})
public String index(Model model)
{
model.addAttribute("searchModel", new SearchModel());
return "index";
}
/**
* The endpoint for the application about page.
* Secured: No
* Method: GET
* <p>
* Sample URL: /about
*
* @return The path to the about page template.
*/
@GetMapping("/about")
public String about()
{
return "about";
}
/**
* The endpoint for the contact page.
* Secured: No
* Method: GET
* <p>
* Sample URL: /contact
*
* @return The name of the contact page template.
*/
@GetMapping("/contact")
public String contact()
{
return "contact";
}
}
| package space.hideaway.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import space.hideaway.model.SearchModel;
import space.hideaway.services.UserService;
@Controller
public class RouteController
{
@Autowired
UserService userService;
/**
* The endpoint for the application home page.
* Secured: No
* Method: GET
* <p>
* Sample URL: / or /home
*
* @return The path to the index page template.
*/
@GetMapping({"/", "/home"})
public String index(Model model)
{
model.addAttribute("searchModel", new SearchModel());
model.addAttribute("user", userService.getCurrentLoggedInUser());
return "index";
}
/**
* The endpoint for the application about page.
* Secured: No
* Method: GET
* <p>
* Sample URL: /about
*
* @return The path to the about page template.
*/
@GetMapping("/about")
public String about()
{
return "about";
}
/**
* The endpoint for the contact page.
* Secured: No
* Method: GET
* <p>
* Sample URL: /contact
*
* @return The name of the contact page template.
*/
@GetMapping("/contact")
public String contact()
{
return "contact";
}
}
|
[WEB-585] Fix border style for sticky table headers | export default ({ borders, colors, fonts, fontSizes, shadows }) => {
const defaultStyles = {
color: colors.text.primary,
fontFamily: fonts.default,
fontSize: `${fontSizes[0]}px`,
'.MuiTableCell-head': {
paddingY: 1,
borderTop: borders.default,
borderBottom: 'none',
},
'&.MuiTable-stickyHeader': {
'.MuiTableCell-stickyHeader': {
backgroundColor: colors.white,
borderBottom: borders.default,
},
'.MuiTableBody-root .MuiTableRow-root:first-child': {
'.MuiTableCell-body': {
borderTop: 'none',
},
},
},
'.MuiTableBody-root .MuiTableRow-root': {
'.MuiTableCell-body': {
padding: 3,
borderColor: colors.border.default,
borderBottom: 'none',
borderTop: borders.default,
},
'&:last-child .MuiTableCell-body': {
borderBottom: borders.default,
},
'&.MuiTableRow-hover:hover': {
backgroundColor: colors.white,
boxShadow: shadows.medium,
'.MuiTableCell-body': {
borderColor: 'transparent',
},
'+ .MuiTableRow-root .MuiTableCell-body': {
borderTopColor: 'transparent',
},
},
},
};
return {
default: {
...defaultStyles,
},
condensed: {
...defaultStyles,
'.MuiTableBody-root .MuiTableRow-root .MuiTableCell-body': {
paddingY: 2,
},
},
};
};
| export default ({ borders, colors, fonts, fontSizes, shadows }) => {
const defaultStyles = {
color: colors.text.primary,
fontFamily: fonts.default,
fontSize: `${fontSizes[0]}px`,
'.MuiTableCell-head': {
paddingY: 1,
borderTop: borders.default,
borderBottom: 'none',
},
'.MuiTableCell-stickyHeader': {
backgroundColor: colors.white,
},
'.MuiTableBody-root .MuiTableRow-root': {
'.MuiTableCell-body': {
padding: 3,
borderColor: colors.border.default,
borderBottom: 'none',
borderTop: borders.default,
},
'&:last-child .MuiTableCell-body': {
borderBottom: borders.default,
},
'&.MuiTableRow-hover:hover': {
backgroundColor: colors.white,
boxShadow: shadows.medium,
'.MuiTableCell-body': {
borderColor: 'transparent',
},
'+ .MuiTableRow-root .MuiTableCell-body': {
borderTopColor: 'transparent',
},
},
},
};
return {
default: {
...defaultStyles,
},
condensed: {
...defaultStyles,
'.MuiTableBody-root .MuiTableRow-root .MuiTableCell-body': {
paddingY: 2,
},
},
};
};
|
Fix accidental clobbering of item variable | define(['mac/roman'], function(macintoshRoman) {
'use strict';
return function(item) {
return item.getBytes().then(function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var dataObject = {
id: dv.getUint16(0, false),
definitionProcedureResourceID: dv.getUint16(6, false),
enabledState: dv.getUint32(10, false),
title: macintoshRoman(bytes, 15, bytes[14]),
};
var pos = 15 + bytes[14];
if (dataObject.definitionProcedureResourceID === 0) {
delete dataObject.definitionProcedureResourceID;
dataObject.items = [];
while (pos < bytes.length && bytes[pos] !== 0) {
var text = macintoshRoman(bytes, pos + 1, bytes[pos]);
pos += 1 + text.length;
var menuItem = {
text: text,
iconNumberOrScriptCode: bytes[pos],
keyboardEquivalent: bytes[pos + 1],
markingCharacterOrSubmenuID: bytes[pos + 2],
style: bytes[pos + 3],
};
dataObject.items.push(menuItem);
pos += 4;
}
}
else {
dataObject.itemData = atob(String.fromCharCode.apply(null, bytes.subarray(pos)));
}
item.setDataObject(dataObject);
});
};
});
| define(['mac/roman'], function(macintoshRoman) {
'use strict';
return function(item) {
return item.getBytes().then(function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var dataObject = {
id: dv.getUint16(0, false),
definitionProcedureResourceID: dv.getUint16(6, false),
enabledState: dv.getUint32(10, false),
title: macintoshRoman(bytes, 15, bytes[14]),
};
var pos = 15 + bytes[14];
if (dataObject.definitionProcedureResourceID === 0) {
delete dataObject.definitionProcedureResourceID;
dataObject.items = [];
while (pos < bytes.length && bytes[pos] !== 0) {
var text = macintoshRoman(bytes, pos + 1, bytes[pos]);
pos += 1 + text.length;
var item = {
text: text,
iconNumberOrScriptCode: bytes[pos],
keyboardEquivalent: bytes[pos + 1],
markingCharacterOrSubmenuID: bytes[pos + 2],
style: bytes[pos + 3],
};
dataObject.items.push(item);
pos += 4;
}
}
else {
dataObject.itemData = atob(String.fromCharCode.apply(null, bytes.subarray(pos)));
}
item.setDataObject(dataObject);
});
};
});
|
Include more info about project in route / | <!DOCTYPE html>
<html>
<head>
<title>Rest Birita</title>
<link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 96px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Rest Birita</div>
<h2>RestBeer for Birita/Pinga/Cachaça!</h2>
<p><a href="https://github.com/rogeriopradoj/restbirita">https://github.com/rogeriopradoj/restbirita</a></p>
</div>
</div>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<title>Rest Birita</title>
<link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
.title {
font-size: 96px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Rest Birita</div>
<p><a href="https://github.com/rogeriopradoj/restbirita">https://github.com/rogeriopradoj/restbirita</a></p>
</div>
</div>
</body>
</html>
|
Save favourites with the page title | define(['jquery', 'backbone', 'underscore', 'moxie.conf', 'favourites/collections/Favourites'],
function($, Backbone, _, conf, Favourites) {
var FavouriteButtonView = Backbone.View.extend({
initialize: function() {
_.bindAll(this);
this.favourites = new Favourites();
this.favourites.fetch();
this.updateButton();
this.favourites.on("remove add", this.updateButton, this);
window.addEventListener("hashchange", this.updateButton, false);
},
attributes: {
'class': 'generic free-text'
},
events: {'click': 'toggleFavourite'},
toggleFavourite: function(e) {
e.preventDefault();
var fav = this.favourites.getCurrentPage();
if (fav) {
this.removeFavourite(fav);
} else {
this.addFavourite();
}
console.log(this.favourites.toJSON());
},
addFavourite: function() {
var fragment = Backbone.history.fragment;
var title = document.title.split(conf.titlePrefix, 2)[1];
this.favourites.create({fragment: fragment, title: title});
},
removeFavourite: function(favourite) {
favourite.destroy();
},
updateButton: function(favourite) {
if (this.favourites.getCurrentPage()) {
this.$el.addClass('favourited');
} else {
this.$el.removeClass('favourited');
}
}
});
return FavouriteButtonView;
}
);
| define(['jquery', 'backbone', 'underscore', 'favourites/models/Favourite', 'favourites/collections/Favourites'],
function($, Backbone, _, Favourite, Favourites) {
var FavouriteButtonView = Backbone.View.extend({
initialize: function() {
_.bindAll(this);
this.favourites = new Favourites();
this.favourites.fetch();
this.updateButton();
this.favourites.on("remove add", this.updateButton, this);
window.addEventListener("hashchange", this.updateButton, false);
},
events: {'click': 'toggleFavourite'},
toggleFavourite: function(e) {
e.preventDefault();
var fav = this.favourites.getCurrentPage();
if (fav) {
this.removeFavourite(fav);
} else {
this.addFavourite();
}
console.log(this.favourites.toJSON());
},
addFavourite: function() {
var fragment = Backbone.history.fragment;
this.favourites.create({fragment: fragment});
},
removeFavourite: function(favourite) {
favourite.destroy();
},
updateButton: function(favourite) {
if (this.favourites.getCurrentPage()) {
this.$el.addClass('favourited');
} else {
this.$el.removeClass('favourited');
}
}
});
return FavouriteButtonView;
}
);
|
CRM-3483: Change origin syncs (IMAP/EWS) to use origin
- Fix migration for oro_email_origin | <?php
namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_15;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class UpdateEmailOriginRelation implements Migration, OrderedMigrationInterface
{
/**
* {@inheritDoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
self::addOwnerAndOrganizationColumns($schema);
}
public static function addOwnerAndOrganizationColumns(Schema $schema)
{
$table = $schema->getTable('oro_email_origin');
$table->addColumn('owner_id', 'integer', ['notnull' => false]);
$table->addColumn('organization_id', 'integer', ['notnull' => false]);
$table->addForeignKeyConstraint(
$schema->getTable('oro_user'),
['owner_id'],
['id'],
['onDelete' => 'CASCADE', 'onUpdate' => null]
);
$table->addForeignKeyConstraint(
$schema->getTable('oro_organization'),
['organization_id'],
['id'],
['onDelete' => 'CASCADE', 'onUpdate' => null]
);
}
/**
* {@inheritDoc}
*/
public function getOrder()
{
return 0;
}
}
| <?php
namespace Oro\Bundle\UserBundle\Migrations\Schema\v1_15;
use Doctrine\DBAL\Schema\Schema;
use Oro\Bundle\MigrationBundle\Migration\Migration;
use Oro\Bundle\MigrationBundle\Migration\OrderedMigrationInterface;
use Oro\Bundle\MigrationBundle\Migration\QueryBag;
class UpdateEmailOriginRelation implements Migration, OrderedMigrationInterface
{
/**
* {@inheritDoc}
*/
public function up(Schema $schema, QueryBag $queries)
{
self::addOwnerAndOrganizationColumns($schema);
}
public static function addOwnerAndOrganizationColumns(Schema $schema)
{
$table = $schema->getTable('oro_email_origin');
$table->addColumn('owner_id', 'integer', ['notnull' => false]);
$table->addColumn('organization_id', 'integer', ['notnull' => false]);
$table->addForeignKeyConstraint(
$schema->getTable('oro_user'),
['owner_id'],
['id'],
['onDelete' => 'CASCADE', 'onUpdate' => null]
);
$table->addForeignKeyConstraint(
$schema->getTable('oro_organization'),
['organization_id'],
['id'],
['onDelete' => 'SET NULL', 'onUpdate' => null]
);
}
/**
* {@inheritDoc}
*/
public function getOrder()
{
return 0;
}
}
|
Fix String to Integer conversion bug | package example;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class SocketClient {
public static void main( String[] args ) throws IOException {
// Check arguments
if (args.length < 3) {
System.err.println("Argument(s) missing!");
System.err.printf("Usage: java %s host port file%n", SocketClient.class.getName());
return;
}
String host = args[0];
// Convert port from String to int
int port = Integer.parseInt(args[1]);
// Concatenate arguments using a string builder
StringBuilder sb = new StringBuilder();
for (int i = 2; i < args.length; i++) {
sb.append(args[i]);
if (i < args.length-1) {
sb.append(" ");
}
}
String text = sb.toString();
// Create client socket
Socket socket = new Socket(host, port);
System.out.printf("Connected to server %s on port %d %n", host, Integer.valueOf(port));
// Create stream to send data to server
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// Send text to server as bytes
out.writeBytes(text);
out.writeBytes("\n");
System.out.println("Sent text: " + text);
// Close client socket
socket.close();
System.out.println("Connection closed");
}
}
| package example;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class SocketClient {
public static void main( String[] args ) throws IOException {
// Check arguments
if (args.length < 3) {
System.err.println("Argument(s) missing!");
System.err.printf("Usage: java %s host port file%n", SocketClient.class.getName());
return;
}
String host = args[0];
// Convert port from String to int
int port = Integer.parseInt(args[1]);
// Concatenate arguments using a string builder
StringBuilder sb = new StringBuilder();
for (int i = 2; i < args.length; i++) {
sb.append(args[i]);
if (i < args.length-1) {
sb.append(" ");
}
}
String text = sb.toString();
// Create client socket
Socket socket = new Socket(host, port);
System.out.printf("Connected to server %s on port %d %n", Integer.valueOf(host), Integer.valueOf(port));
// Create stream to send data to server
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
// Send text to server as bytes
out.writeBytes(text);
out.writeBytes("\n");
System.out.println("Sent text: " + text);
// Close client socket
socket.close();
System.out.println("Connection closed");
}
}
|
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present | import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model
"""
def handle(self, *args, **options):
org_groups = GroupProfile.objects.filter(group_type='organization')
for org in org_groups:
data = json.loads(org.data)
name = org.name
display_name = data.get('display_name', name)
contact_name = data.get('contact_name', None)
contact_email = data.get('email', None)
if contact_email is None:
contact_email = data.get('contact_email', None)
contact_phone = data.get('phone', None)
if contact_phone is None:
contact_phone = data.get('contact_phone', None)
migrated_org = Organization.objects.create(
name=name,
display_name=display_name,
contact_name=contact_name,
contact_email=contact_email,
contact_phone=contact_phone
)
group = Group.objects.get(groupprofile=org.id)
users = group.user_set.all()
for user in users:
migrated_org.users.add(user)
linked_groups = group.grouprelationship.get_linked_group_relationships()
for linked_group in linked_groups:
if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component
actual_group = Group.objects.get(id=linked_group.to_group_relationship_id)
migrated_org.groups.add(actual_group)
| import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model
"""
def handle(self, *args, **options):
org_groups = GroupProfile.objects.filter(group_type='organization')
for org in org_groups:
data = json.loads(org.data)
migrated_org = Organization.objects.create(
name=data['name'],
display_name=data['display_name'],
contact_name=data['contact_name'],
contact_email=data['contact_email'],
contact_phone=data['contact_phone']
)
group = Group.objects.get(groupprofile=org.id)
users = group.user_set.all()
for user in users:
migrated_org.users.add(user)
linked_groups = group.grouprelationship.get_linked_group_relationships()
for linked_group in linked_groups:
if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component
actual_group = Group.objects.get(id=linked_group.to_group_relationship_id)
migrated_org.groups.add(actual_group)
|
Add untested support for change lists | /* global django */
/* eslint indent:[2,4] */
/* eslint comma-dangle:[2,"never"] */
django.jQuery(function($){
var context = document.getElementById('admin-ordering-context');
if (!context) return;
var data = JSON.parse(context.getAttribute('data-context'));
if (data.tabular) {
$('#' + data.prefix + '-group tbody').sortable({
update: function(event, ui) {
$('.dynamic-' + data.prefix).each(function(index) {
var row = $(this);
row.find('.field-' + data.field + ' input').val(10 * (index + 1));
row.removeClass('row1 row2').addClass((index % 2) ? 'row2' : 'row1');
});
}
});
} else if (data.stacked) {
$('#' + data.prefix + '-group').sortable({
items: '>.inline-related',
update: function(event, ui) {
$('.dynamic-' + data.prefix).each(function(index) {
var row = $(this);
row.find('.field-' + data.field + ' input').val(10 * (index + 1));
row.removeClass('row1 row2').addClass((index % 2) ? 'row2' : 'row1');
});
}
});
} else {
$('#result_list tbody').sortable({
update: function(event, ui) {
$('#result_list tbody tr').each(function(index) {
var row = $(this);
row.find('.field-' + data.field + ' input').val(10 * (index + 1));
row.removeClass('row1 row2').addClass((index % 2) ? 'row2' : 'row1');
});
}
});
}
});
| /* global django */
/* eslint indent:[2,4] */
/* eslint comma-dangle:[2,"never"] */
django.jQuery(function($){
var context = document.getElementById('admin-ordering-context');
if (!context) return;
var data = JSON.parse(context.getAttribute('data-context'));
if (data.tabular) {
$('#' + data.prefix + '-group tbody').sortable({
update: function(event, ui) {
$('.dynamic-' + data.prefix).each(function(index) {
var row = $(this);
row.find('.field-' + data.field + ' input').val(10 * (index + 1));
row.removeClass('row1 row2').addClass((index % 2) ? 'row2' : 'row1');
});
}
});
} else if (data.stacked) {
$('#' + data.prefix + '-group').sortable({
items: '>.inline-related',
update: function(event, ui) {
$('.dynamic-' + data.prefix).each(function(index) {
var row = $(this);
row.find('.field-' + data.field + ' input').val(10 * (index + 1));
row.removeClass('row1 row2').addClass((index % 2) ? 'row2' : 'row1');
});
}
});
}
});
|
Create only one MDAnalysis selection | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
selection = universe.select_atoms("backbone")
for ts in universe.trajectory:
structure = Chain()
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Local module
from .structure import Chain, Atom
from .PDB import PDB
# Conditional import
try:
import MDAnalysis
except ImportError:
IS_MDANALYSIS = False
else:
IS_MDANALYSIS = True
# Create the __all__ keyword according to the conditional import
__all__ = ['chains_from_files']
if IS_MDANALYSIS:
__all__ += ['chains_from_trajectory']
def chains_from_files(path_list):
for pdb_name in path_list:
pdb = PDB(pdb_name)
for chain in pdb.get_chains():
# build comment
comment = pdb_name
if chain.model:
comment += " | model %s" % (chain.model)
if chain.name:
comment += " | chain %s" % (chain.name)
yield comment, chain
def chains_from_trajectory(trajectory, topology):
comment = ""
universe = MDAnalysis.Universe(topology, trajectory)
for ts in universe.trajectory:
structure = Chain()
selection = universe.select_atoms("backbone")
for atm in selection:
atom = Atom()
atom.read_from_xtc(atm)
# append structure with atom
structure.add_atom(atom)
# define structure comment
# when the structure contains 1 atom
if structure.size() == 1:
comment = "%s | frame %s" % (trajectory, ts.frame)
yield comment, structure
|
Implement proper parameter matching rules | module.exports = class Call {
constructor(callee, args) {
this.callee = callee;
this.args = args;
}
analyze(context) {
this.callee.analyze(context);
context.assertIsFunction(this.callee.referent);
this.checkArgumentMatching(this.callee.referent);
}
checkArgumentMatching(callee) {
let keywordArgumentSeen = false;
const matchedParameterNames = new Set([]);
this.args.forEach((arg, index) => {
if (index >= callee.params.length) {
throw new Error('Too many arguments in call');
}
if (arg.id) {
keywordArgumentSeen = true;
} else if (keywordArgumentSeen) {
throw new Error('Positional argument in call after keyword argument');
}
const parameterName = arg.id ? arg.id : callee.params[index].id;
if (!callee.allParameterNames.has(parameterName)) {
throw new Error(`Function does not have a parameter called ${parameterName}`);
}
if (matchedParameterNames.has(parameterName)) {
throw new Error(`Multiple arguments for parameter ${parameterName}`);
}
matchedParameterNames.add(parameterName);
});
// Look for and report a required parameter that is not matched
const miss = [...callee.requiredParameterNames].find(name => !matchedParameterNames.has(name));
if (miss) {
throw new Error(`Required parameter ${miss} is not matched in call`);
}
}
};
| module.exports = class Call {
constructor(callee, args) {
this.callee = callee;
this.args = args;
}
analyze(context) {
this.callee.analyze(context);
context.assertIsFunction(this.callee.referent);
this.checkNumberOfArguments(this.callee.referent);
this.checkArgumentNamesAndPositionalRules(this.callee.referent);
}
checkNumberOfArguments(callee) {
const numArgs = this.args.length;
const numRequiredParams = callee.requiredParameterNames.size;
const numParams = callee.allParameterNames.size;
if (numArgs < numRequiredParams) {
// We have to at least cover all the required parameters
throw new Error(`Expected at least ${numRequiredParams} arguments but called with ${numArgs}`);
}
if (numArgs > numParams) {
// We can't pass more arguments than the total number of parameters
throw new Error(`Expected at most ${numParams} arguments but called with ${numArgs}`);
}
}
checkArgumentNamesAndPositionalRules(callee) {
let keywordArgumentSeen = false;
this.args.forEach((arg) => {
if (arg.id) {
// This is a keyword argument, record that fact and check that it's okay
keywordArgumentSeen = true;
if (!callee.allParameterNames.has(arg.id)) {
throw new Error(`Function does not have a parameter called ${arg.id}`);
}
} else if (keywordArgumentSeen) {
// This is a positional argument, but a prior one was a keyword one
throw new Error('Positional argument in call after keyword argument');
}
});
}
};
|
Fix error in visual layout editor
Avoid setting PhoneNumberFormattingTextWatcher in MobileNumberEditText
when in edit mode.
Fixes #24 | package com.braintreepayments.cardform.view;
import android.content.Context;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.telephony.PhoneNumberUtils;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.text.InputType;
import android.util.AttributeSet;
import com.braintreepayments.cardform.R;
/**
* Input for mobile number. Validated for presence only due to the wide variation of mobile number formats worldwide.
*/
public class MobileNumberEditText extends ErrorEditText {
public MobileNumberEditText(Context context) {
super(context);
init();
}
public MobileNumberEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MobileNumberEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
if (isInEditMode()) {
return;
}
setInputType(InputType.TYPE_CLASS_PHONE);
InputFilter[] filters = { new LengthFilter(14) };
setFilters(filters);
addTextChangedListener(new PhoneNumberFormattingTextWatcher());
}
/**
* @return the unformatted mobile number entered by the user
*/
public String getMobileNumber() {
return PhoneNumberUtils.stripSeparators(getText().toString());
}
@Override
public boolean isValid() {
return isOptional() || getText().toString().length() >= 8;
}
@Override
public String getErrorMessage() {
return getContext().getString(R.string.bt_mobile_number_required);
}
}
| package com.braintreepayments.cardform.view;
import android.content.Context;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.telephony.PhoneNumberUtils;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.text.InputType;
import android.util.AttributeSet;
import com.braintreepayments.cardform.R;
/**
* Input for mobile number. Validated for presence only due to the wide variation of mobile number formats worldwide.
*/
public class MobileNumberEditText extends ErrorEditText {
public MobileNumberEditText(Context context) {
super(context);
init();
}
public MobileNumberEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MobileNumberEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setInputType(InputType.TYPE_CLASS_PHONE);
InputFilter[] filters = { new LengthFilter(14) };
setFilters(filters);
addTextChangedListener(new PhoneNumberFormattingTextWatcher());
}
/**
* @return the unformatted mobile number entered by the user
*/
public String getMobileNumber() {
return PhoneNumberUtils.stripSeparators(getText().toString());
}
@Override
public boolean isValid() {
return isOptional() || getText().toString().length() >= 8;
}
@Override
public String getErrorMessage() {
return getContext().getString(R.string.bt_mobile_number_required);
}
}
|
Update floating task name constraints message | package seedu.jimi.model.task;
import seedu.jimi.commons.exceptions.IllegalValueException;
/**
* Represents a FloatingTask's name in the address book.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class Name {
public static final String MESSAGE_NAME_CONSTRAINTS = "Floating task names can be any text.";
public static final String NAME_VALIDATION_REGEX = ".+";
public final String fullName;
/**
* Validates given name.
*
* @throws IllegalValueException if given name string is invalid.
*/
public Name(String name) throws IllegalValueException {
assert name != null;
name = name.trim();
if (!isValidName(name)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = name;
}
/**
* Returns true if a given string is a valid task name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Name // instanceof handles nulls
&& this.fullName.equals(((Name) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
}
| package seedu.jimi.model.task;
import seedu.jimi.commons.exceptions.IllegalValueException;
/**
* Represents a FloatingTask's name in the address book.
* Guarantees: immutable; is valid as declared in {@link #isValidName(String)}
*/
public class Name {
public static final String MESSAGE_NAME_CONSTRAINTS = "Floating task names should be spaces or alphanumeric characters";
public static final String NAME_VALIDATION_REGEX = ".+";
public final String fullName;
/**
* Validates given name.
*
* @throws IllegalValueException if given name string is invalid.
*/
public Name(String name) throws IllegalValueException {
assert name != null;
name = name.trim();
if (!isValidName(name)) {
throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS);
}
this.fullName = name;
}
/**
* Returns true if a given string is a valid task name.
*/
public static boolean isValidName(String test) {
return test.matches(NAME_VALIDATION_REGEX);
}
@Override
public String toString() {
return fullName;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Name // instanceof handles nulls
&& this.fullName.equals(((Name) other).fullName)); // state check
}
@Override
public int hashCode() {
return fullName.hashCode();
}
}
|
Make ultimate question ever more ultimate | from pywps import Process, LiteralOutput
from pywps.app.Common import Metadata
class UltimateQuestion(Process):
def __init__(self):
inputs = []
outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')]
super(UltimateQuestion, self).__init__(
self._handler,
identifier='ultimate_question',
version='2.0',
title='Answer to the ultimate question',
abstract='This process gives the answer to the ultimate question of life, the universe, and everything.',
profile='',
metadata=[Metadata('Ultimate Question'), Metadata('What is the meaning of life')],
inputs=inputs,
outputs=outputs,
store_supported=True,
status_supported=True
)
@staticmethod
def _handler(request, response):
import time
sleep_delay = .1
response.update_status('PyWPS Process started.', 0)
time.sleep(sleep_delay)
response.update_status("Contacting the Deep Thought supercomputer.", 10)
time.sleep(sleep_delay)
response.update_status('Thinking...', 20)
time.sleep(sleep_delay)
response.update_status('Thinking...', 40)
time.sleep(sleep_delay)
response.update_status('Thinking...', 60)
time.sleep(sleep_delay)
response.update_status('Thinking...', 80)
response.outputs['answer'].data = '42'
response.update_status('PyWPS Process completed.', 100)
return response
| from pywps import Process, LiteralOutput
from pywps.app.Common import Metadata
class UltimateQuestion(Process):
def __init__(self):
inputs = []
outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')]
super(UltimateQuestion, self).__init__(
self._handler,
identifier='ultimate_question',
version='2.0',
title='Answer to the ultimate question',
abstract='This process gives the answer to the ultimate question of "What is the meaning of life?"',
profile='',
metadata=[Metadata('Ultimate Question'), Metadata('What is the meaning of life')],
inputs=inputs,
outputs=outputs,
store_supported=True,
status_supported=True
)
@staticmethod
def _handler(request, response):
import time
response.update_status('PyWPS Process started.', 0)
sleep_delay = .1
time.sleep(sleep_delay)
response.update_status('Thinking...', 20)
time.sleep(sleep_delay)
response.update_status('Thinking...', 40)
time.sleep(sleep_delay)
response.update_status('Thinking...', 60)
time.sleep(sleep_delay)
response.update_status('Thinking...', 80)
response.outputs['answer'].data = '42'
response.update_status('PyWPS Process completed.', 100)
return response
|
Fix firefox invocation as browser | import os.path, os
def run_as_browser(fn):
def wrapped(*args, **kwargs):
rv = fn(*args, **kwargs)
return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv
return wrapped
class Helpers:
@property
@run_as_browser
def default_firefox_bin(self):
candidates = [
'/usr/local/lib/firefox/firefox-bin',
'/usr/local/lib/firefox3/firefox-bin',
'/usr/bin/iceweasel',
]
return self._pick(candidates, os.path.exists)
@property
@run_as_browser
def default_firefox_wrapper(self):
candidates = [
'firefox', 'firefox3'
]
return self._pick(candidates, self._wrapper_tester)
default_firefox = default_firefox_wrapper
@property
def as_browser(self):
return 'sudo -Hiu browser'
@property
def opera(self):
return 'sudo -Hiu browser opera'
@property
def chrome(self):
return 'sudo -Hiu browser chrome'
def have_bin(self, basename):
return self._wrapper_tester(basename)
def _wrapper_tester(self, candidate):
dirs = os.environ['PATH'].split(':')
for dir in dirs:
path = os.path.join(dir, candidate)
if os.path.exists(path):
return True
return False
def _pick(self, candidates, tester):
for candidate in candidates:
if tester(candidate):
return candidate
# consider raising here
return None
| import os.path, os
def run_as_browser(fn):
def wrapped(*args, **kwargs):
rv = fn(*args, **kwargs)
return 'sudo -Hiu browser %s' % rv
return wrapped
class Helpers:
@property
@run_as_browser
def default_firefox_bin(self):
candidates = [
'/usr/local/lib/firefox/firefox-bin',
'/usr/local/lib/firefox3/firefox-bin',
'/usr/bin/iceweasel',
]
return self._pick(candidates, os.path.exists)
@property
@run_as_browser
def default_firefox_wrapper(self):
candidates = [
'firefox', 'firefox3'
]
return self._pick(candidates, self._wrapper_tester)
default_firefox = default_firefox_wrapper
@property
def as_browser(self):
return 'sudo -Hiu browser'
@property
def opera(self):
return 'sudo -Hiu browser opera'
@property
def chrome(self):
return 'sudo -Hiu browser chrome'
def have_bin(self, basename):
return self._wrapper_tester(basename)
def _wrapper_tester(self, candidate):
dirs = os.environ['PATH'].split(':')
for dir in dirs:
path = os.path.join(dir, candidate)
if os.path.exists(path):
return True
return False
def _pick(self, candidates, tester):
for candidate in candidates:
if tester(candidate):
return candidate
# consider raising here
return None
|
Use AugmentedContent instead of Content
Do not touch the Content field: it is used also for database handling
and modifying it will introduce a lot of issues. Instead, added the new
AugmentedContent element to be used instead of Content in templates. | <?php
class Autotoc extends DataExtension {
private $_tocifier;
private static function _convertNode($node) {
$data = new ArrayData(array(
'Id' => $node['id'],
'Title' => $node['title']
));
if (isset($node['children']))
$data->setField('Children', self::_convertChildren($node['children']));
return $data;
}
private static function _convertChildren($children) {
$list = new ArrayList;
foreach ($children as $child)
$list->push(self::_convertNode($child));
return $list;
}
private function _getTocifier() {
if (is_null($this->_tocifier)) {
$tocifier = new Tocifier($this->owner->Content);
$this->_tocifier = $tocifier->process() ? $tocifier : false;
}
return $this->_tocifier;
}
public function getAugmentedContent() {
$tocifier = $this->_getTocifier();
if (! $tocifier)
return $this->owner->Content;
return $tocifier->getHtml();
}
public function getAutotoc() {
$tocifier = $this->_getTocifier();
if (! $tocifier)
return null;
$toc = $tocifier->getTOC();
if (empty($toc))
return '';
return new ArrayData(array(
'Children' => self::_convertChildren($toc)
));
}
};
| <?php
class Autotoc extends DataExtension {
private $_tocifier;
private static function _convertNode($node) {
$data = new ArrayData(array(
'Id' => $node['id'],
'Title' => $node['title']
));
if (isset($node['children']))
$data->setField('Children', self::_convertChildren($node['children']));
return $data;
}
private static function _convertChildren($children) {
$list = new ArrayList;
foreach ($children as $child)
$list->push(self::_convertNode($child));
return $list;
}
private function _getTocifier() {
if (is_null($this->_tocifier)) {
$html = $this->owner->getField('Content');
$tocifier = new Tocifier($html);
$this->_tocifier = $tocifier->process() ? $tocifier : false;
}
return $this->_tocifier;
}
public function getContent() {
$tocifier = $this->_getTocifier();
if (! $tocifier)
return $this->owner->getField('Content');
return $tocifier->getHtml();
}
public function getAutotoc() {
$tocifier = $this->_getTocifier();
if (! $tocifier)
return null;
$toc = $tocifier->getTOC();
if (empty($toc))
return '';
return new ArrayData(array(
'Children' => self::_convertChildren($toc)
));
}
};
|
Change nature endpoint to return lakes | 'use strict';
var _ = require('lodash');
var instagram = require('instagram-node').instagram();
instagram.use({
access_token: '1035958982.117ba06.4abe0116ea094d489f0b6f2218942979',
client_id: '117ba064c0dc48249c0804d1b36f9524',
client_secret: '01e9ed98b82a4cee91769631dd3122cb'
});
exports.nature = function(fromTime, callback) {
instagram.tag_media_recent('järvi', {}, function(err, medias, remaining, limit) {
console.log(medias);
if (err) {
callback(err, null);
} else {
if (fromTime) {
medias = _.filter(medias, function(media) {
return media.created_time > fromTime;
});
}
medias = _.map(medias, function(media) {
return {
timestamp: parseInt(media.created_time),
url: media.images.standard_resolution.url
};
});
callback(null, {
images: medias
});
}
});
};
| 'use strict';
var _ = require('lodash');
var instagram = require('instagram-node').instagram();
instagram.use({
access_token: '1035958982.117ba06.4abe0116ea094d489f0b6f2218942979',
client_id: '117ba064c0dc48249c0804d1b36f9524',
client_secret: '01e9ed98b82a4cee91769631dd3122cb'
});
exports.nature = function(fromTime, callback) {
instagram.media_search(60.170833, 24.9375, {}, function(err, medias, remaining, limit) {
console.log(medias);
if (err) {
callback(err, null);
} else {
if (fromTime) {
medias = _.filter(medias, function(media) {
return media.created_time > fromTime;
});
}
medias = _.map(medias, function(media) {
return {
timestamp: parseInt(media.created_time),
url: media.images.standard_resolution.url
};
});
callback(null, {
images: medias
});
}
});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.