text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Use string interpolation in toString functions | 'use strict';
class Character {
constructor(x, y) {
this.x = x;
this.y = y;
this.health_ = 100;
}
damage() {
this.health_ -= 10;
}
getHealth() {
return this.health_;
}
toString() {
return `x: ${this.x} y: ${this.y} health: ${this.health_}`
}
}
class Player extends Character {
constructor(x, y, name) {
super(x, y);
this.name = name;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
}
toString() {
return `name: ${this.name} ${super.toString()}`;
}
}
var x = process.argv[2];
var y = process.argv[3];
var name = process.argv[4];
var character = new Character(+x, +y);
character.damage();
console.log(character.toString());
var player = new Player(+x, +y, name);
player.damage();
player.move(7, 8);
console.log(player.toString());
| 'use strict';
class Character {
constructor(x, y) {
this.x = x;
this.y = y;
this.health_ = 100;
}
damage() {
this.health_ -= 10;
}
getHealth() {
return this.health_;
}
toString() {
return "x: " + this.x + " y: " + this.y + " health: " + this.health_;
}
}
class Player extends Character {
constructor(x, y, name) {
super(x, y);
this.name = name;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
}
toString() {
return "name: " + this.name + " " + super.toString();
}
}
var x = process.argv[2];
var y = process.argv[3];
var name = process.argv[4];
var character = new Character(+x, +y);
character.damage();
console.log(character.toString());
var player = new Player(+x, +y, name);
player.damage();
player.move(7, 8);
console.log(player.toString());
|
Update Anime to Use New Communicator
Change the Anime details controller to use the renamed communicator
service. | <?php
namespace Atarashii\APIBundle\Controller;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Atarashii\APIBundle\Parser\AnimeParser;
//Temporary for offline testing
use Symfony\Component\Finder\Finder;
class AnimeController extends FOSRestController
{
/**
* Anime get action
* @var integer $id Id of the anime
* @return array
*
* @Rest\View()
*/
public function getAction($id)
{
#http://myanimelist.net/anime/#{id}
$downloader = $this->get('atarashii_api.communicator');
$animedetails = $downloader->fetch('/anime/' . $id);
$anime = AnimeParser::parse($animedetails);
return $anime;
}
} | <?php
namespace Atarashii\APIBundle\Controller;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations as Rest;
use Atarashii\APIBundle\Parser\AnimeParser;
//Temporary for offline testing
use Symfony\Component\Finder\Finder;
class AnimeController extends FOSRestController
{
/**
* Anime get action
* @var integer $id Id of the anime
* @return array
*
* @Rest\View()
*/
public function getAction($id)
{
#http://myanimelist.net/anime/#{id}
$downloader = $this->get('atarashii_api.downloader');
$animedetails = $downloader->fetch('/anime/' . $id);
$anime = AnimeParser::parse($animedetails);
return $anime;
}
} |
Fix osxfuse locations (forgot to add to last commit) | // +build darwin
package libfuse
import (
"os"
"bazil.org/fuse"
)
func getPlatformSpecificMountOptions(m Mounter) ([]fuse.MountOption, error) {
options := []fuse.MountOption{}
// Add kbfuse support.
// Workaround osxfuse and bazil.org/fuse issue with a required env for the
// daemon path. The issue is being tracked here: https://github.com/bazil/fuse/issues/113
os.Setenv("MOUNT_KBFUSE_DAEMON_PATH", "/Library/Filesystems/kbfuse.fs/Contents/Resources/mount_kbfuse")
kbfusePath := fuse.OSXFUSEPaths{
DevicePrefix: "/dev/kbfuse",
Load: "/Library/Filesystems/kbfuse.fs/Contents/Resources/load_kbfuse",
Mount: "/Library/Filesystems/kbfuse.fs/Contents/Resources/mount_kbfuse",
}
// Allow both kbfuse and osxfuse 3.x locations by default.
options = append(options, fuse.OSXFUSELocations(kbfusePath, fuse.OSXFUSELocationV3))
// Volume name option is only used on OSX (ignored on other platforms).
volName, err := volumeName(m.Dir())
if err != nil {
return nil, err
}
options = append(options, fuse.VolumeName(volName))
return options, nil
}
| // +build darwin
package libfuse
import (
"os"
"bazil.org/fuse"
)
func getPlatformSpecificMountOptions(m Mounter) ([]fuse.MountOption, error) {
options := []fuse.MountOption{}
// Add kbfuse support.
// Workaround osxfuse and bazil.org/fuse issue with a required env for the
// daemon path. The issue is being tracked here: https://github.com/bazil/fuse/issues/113
os.Setenv("MOUNT_KBFUSE_DAEMON_PATH", "/Library/Filesystems/kbfuse.fs/Contents/Resources/mount_kbfuse")
kbfusePath := fuse.OSXFUSEPaths{
DevicePrefix: "/dev/kbfuse",
Load: "/Library/Filesystems/kbfuse.fs/Contents/Resources/load_kbfuse",
Mount: "/Library/Filesystems/kbfuse.fs/Contents/Resources/mount_kbfuse",
}
// Allow both kbfuse and osxfuse 3.x locations by default.
options = append(options,
fuse.OSXFUSELocations(kbfusePath),
fuse.OSXFUSELocations(fuse.OSXFUSELocationV3))
// Volume name option is only used on OSX (ignored on other platforms).
volName, err := volumeName(m.Dir())
if err != nil {
return nil, err
}
options = append(options, fuse.VolumeName(volName))
return options, nil
}
|
Rename the Memcached test to be more accurate
Apparently, Memcached is the only Backend that implements expirations,
so it tests Expirations seperately (and not very well!) outside of
`AbstractBackendTest`. More more accurate in naming this. | <?php
require_once 'AbstractBackendTest.php';
use iFixit\Matryoshka;
class MemcachedTest extends AbstractBackendTest {
protected function setUp() {
if (!Matryoshka\Memcached::isAvailable()) {
$this->markTestSkipped('Backend not available!');
}
return parent::setUp();
}
protected function getBackend() {
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
$memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$memcached->setOption(Memcached::OPT_TCP_NODELAY, true);
return Matryoshka\Memcached::create($memcached);
}
public function testExpiration() {
$backend = $this->getBackend();
list($key, $value) = $this->getRandomKeyValue();
$this->assertTrue($backend->set($key, $value, 1));
// Wait for it to expire.
sleep(2);
$this->assertNull($backend->get($key));
}
}
| <?php
require_once 'AbstractBackendTest.php';
use iFixit\Matryoshka;
class MemcachedTest extends AbstractBackendTest {
protected function setUp() {
if (!Matryoshka\Memcached::isAvailable()) {
$this->markTestSkipped('Backend not available!');
}
return parent::setUp();
}
protected function getBackend() {
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);
$memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$memcached->setOption(Memcached::OPT_TCP_NODELAY, true);
return Matryoshka\Memcached::create($memcached);
}
public function testMemcached() {
$backend = $this->getBackend();
list($key, $value) = $this->getRandomKeyValue();
$this->assertTrue($backend->set($key, $value, 1));
// Wait for it to expire.
sleep(2);
$this->assertNull($backend->get($key));
}
}
|
provider/aws: Rename the Basic Import test for CloudFront distributions | package aws
import (
"testing"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccAWSCloudFrontDistribution_importBasic(t *testing.T) {
resourceName := "aws_cloudfront_distribution.s3_distribution"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckCloudFrontDistributionDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSCloudFrontDistributionS3Config,
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
// Ignore retain_on_delete since it doesn't come from the AWS
// API.
ImportStateVerifyIgnore: []string{"retain_on_delete"},
},
},
})
}
| package aws
import (
"testing"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccCloudFrontDistribution_importBasic(t *testing.T) {
resourceName := "aws_cloudfront_distribution.s3_distribution"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckCloudFrontDistributionDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSCloudFrontDistributionS3Config,
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
// Ignore retain_on_delete since it doesn't come from the AWS
// API.
ImportStateVerifyIgnore: []string{"retain_on_delete"},
},
},
})
}
|
[IMP] event_registration_hr_contract: Remove the dependence with the module hr_contract_stage. | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Event Registration Hr Contract",
'version': '8.0.1.1.0',
'license': "AGPL-3",
'author': "AvanzOSC",
'website': "http://www.avanzosc.es",
'contributors': [
"Ana Juaristi <anajuaristi@avanzosc.es>",
"Alfredo de la Fuente <alfredodelafuente@avanzosc.es",
],
"category": "Event Management",
"depends": [
'event_track_presence_hr_holidays',
],
"data": [
'wizard/wiz_calculate_employee_calendar_view.xml',
'wizard/wiz_event_append_assistant_view.xml',
'views/event_event_view.xml',
'views/hr_contract_view.xml',
'views/event_track_presence_view.xml',
'views/res_partner_calendar_view.xml',
'views/res_partner_calendar_day_view.xml'
],
"installable": True,
}
| # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Event Registration Hr Contract",
'version': '8.0.1.1.0',
'license': "AGPL-3",
'author': "AvanzOSC",
'website': "http://www.avanzosc.es",
'contributors': [
"Ana Juaristi <anajuaristi@avanzosc.es>",
"Alfredo de la Fuente <alfredodelafuente@avanzosc.es",
],
"category": "Event Management",
"depends": [
'event_track_presence_hr_holidays',
'hr_contract_stages'
],
"data": [
'wizard/wiz_calculate_employee_calendar_view.xml',
'wizard/wiz_event_append_assistant_view.xml',
'views/event_event_view.xml',
'views/hr_contract_view.xml',
'views/event_track_presence_view.xml',
'views/res_partner_calendar_view.xml',
'views/res_partner_calendar_day_view.xml'
],
"installable": True,
}
|
Make sure app when executed returns empty object if not set to custom
engine. | function Application (cb) {
this._logger = function () {};
this._app = function () { return {}; };
cb.call(this);
}
Application.prototype.init = function () {
this._app = this._app();
};
Application.prototype.setLogger = function (logger) {
this._logger = logger || function () {};
};
Application.prototype.setApp = function (app) {
this._app = app || function () {};
};
Application.prototype.log = function () {
this._logger.apply(this._logger, arguments);
};
Application.prototype.serve = function (port) {
this._app.listen(port, function () {
this.log('Server listening on port ' + port);
}.bind(this));
};
// var app = require('../app');
// app.set('port', cli.port);
// console.log(app.get('env'));
// var server = app.listen(app.get('port'), function() {
// debug('Server listening on port ' + server.address().port);
// });
module.exports = Application;
| function Application (cb) {
this._logger = function () {};
this._app = function () {};
cb.call(this);
}
Application.prototype.init = function () {
this._app = this._app();
};
Application.prototype.setLogger = function (logger) {
this._logger = logger || function () {};
};
Application.prototype.setApp = function (app) {
this._app = app || function () {};
};
Application.prototype.log = function () {
this._logger.apply(this._logger, arguments);
};
Application.prototype.serve = function (port) {
this._app.listen(port, function () {
this.log('Server listening on port ' + port);
}.bind(this));
};
// var app = require('../app');
// app.set('port', cli.port);
// console.log(app.get('env'));
// var server = app.listen(app.get('port'), function() {
// debug('Server listening on port ' + server.address().port);
// });
module.exports = Application;
|
Fix race condition in cync.Sema test | package cync
import (
"sync"
"testing"
"github.com/thatguystone/cog/check"
)
func TestSemaphore(t *testing.T) {
c := check.New(t)
s := NewSemaphore(2)
for i := 0; i < s.count; i++ {
s.Lock()
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
s.Lock()
wg.Done()
}()
go func() {
for i := 0; i < s.count; i++ {
s.Unlock()
}
}()
s.Lock()
wg.Wait()
for i := 0; i < s.count*2; i++ {
s.Unlock()
}
c.Equal(0, s.used)
}
func BenchmarkSemaphore(b *testing.B) {
s := NewSemaphore(2)
for i := 0; i < b.N; i++ {
for i := 0; i < s.count; i++ {
s.Lock()
}
for i := 0; i < s.count; i++ {
s.Unlock()
}
}
}
| package cync
import (
"sync"
"testing"
"github.com/thatguystone/cog/check"
)
func TestSemaphore(t *testing.T) {
c := check.New(t)
s := NewSemaphore(2)
for i := 0; i < s.count; i++ {
s.Lock()
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
s.Lock()
wg.Done()
}()
go func() {
for i := 0; i < s.count; i++ {
s.Unlock()
}
}()
s.Lock()
for i := 0; i < s.count*2; i++ {
s.Unlock()
}
c.Equal(0, s.used)
}
func BenchmarkSemaphore(b *testing.B) {
s := NewSemaphore(2)
for i := 0; i < b.N; i++ {
for i := 0; i < s.count; i++ {
s.Lock()
}
for i := 0; i < s.count; i++ {
s.Unlock()
}
}
}
|
Check config if not null in migrations | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
if not org.config:
old_config = dict()
else:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-07 08:24
from __future__ import unicode_literals
import json
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('orgs', '0018_auto_20170301_0914'),
]
def migrate_api_token_and_common_org_config(apps, schema_editor):
Org = apps.get_model("orgs", "Org")
orgs = Org.objects.all()
for org in orgs:
old_config = json.loads(self.config)
if "common" in old_config and "rapidpro" in old_config:
print("Skipped org(%d), it looks like already migrated" % org.id)
continue
new_config = {"common": old_config, "rapidro": {"api_token": org.api_token}}
self.config = json.dumps(new_config)
self.save()
def noop(apps, schema_editor):
pass
operations = [
migrations.RunPython(migrate_api_token_and_common_org_config, noop)
]
|
Add few functions and connect to query builder | const mysql = require('mysql')
const qBuilder = require('./QueryBuilder')
let _query = ''
let _params = []
module.exports = (dbSetting) => {
let connection = mysql.createConnection({
host: dbSetting.hostname,
user: dbSetting.username,
password: dbSetting.password,
database: dbSetting.database
})
return {
makeQuery: () => {
return qBuilder
},
prepare: () => {
_query = qBuilder.prepare()
},
setParameters: (params) => {
_params = params
qBuilder.setParameters(params)
},
getParameters: () => {
_params = qBuilder.getParameters()
},
execute: () => {
// connection.query(_query)
},
get: () => {
},
connectToDatabase: () => {
connection.connect()
},
endConnection: () => {
connection.end()
}
}
}
| const mysql = require('mysql')
const qBuilder = require('./QueryBuilder')
let query = ''
let params = []
module.exports = (dbSetting) => {
let connection = mysql.createConnection({
host: dbSetting.hostname,
user: dbSetting.username,
password: dbSetting.password,
database: dbSetting.database
})
connection.connect()
return {
makeQuery: () => {
return qBuilder
},
prepare: () => {
query = qBuilder.prepare()
},
setParameters: (params) => {
qBuilder.setParameters(params)
},
getParameters: () => {
params = qBuilder.getParameters()
},
execute: () => {
// connection.query(query)
},
get: () => {
}
}
}
|
Add newlines in output for formatting purposes | #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
* check more explicitly for errors in JSON files
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except:
sys.exit('{} has a syntax error'.format(inFn))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
| #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
* check more explicitly for errors in JSON files
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except:
sys.exit('{} has a syntax error'.format(inFn))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
|
Comment Licenses and Profile top-menu buttons for interface RFL.
Closes #78 | import * as deps from '../deps';
import { closeMobileMenu } from '../actions';
export const initialHeaderItems = [];
const closeMobileMenuAction = () => deps.store.dispatch(closeMobileMenu());
export const loggedInItems = [
{
name: 'Sites',
type: 'button',
url: 'sites',
link: '/sites',
icon: 'th',
action: closeMobileMenuAction,
},
/*
{
name: 'Licenses',
type: 'button',
url: 'licenses',
link: '/licenses',
icon: 'list-ul',
action: closeMobileMenuAction,
},
{
name: 'Profile',
type: 'button',
url: 'profile',
link: '/profile',
icon: 'user',
action: closeMobileMenuAction,
},
*/
{
name: 'Logout',
type: 'button',
icon: 'power-off',
action: () => deps.store.dispatch(deps.actions.logoutRequested()),
},
];
| import * as deps from '../deps';
import { closeMobileMenu } from '../actions';
export const initialHeaderItems = [];
const closeMobileMenuAction = () => deps.store.dispatch(closeMobileMenu());
export const loggedInItems = [
{
name: 'Sites',
type: 'button',
url: 'sites',
link: '/sites',
icon: 'th',
action: closeMobileMenuAction,
},
{
name: 'Licenses',
type: 'button',
url: 'licenses',
link: '/licenses',
icon: 'list-ul',
action: closeMobileMenuAction,
},
{
name: 'Profile',
type: 'button',
url: 'profile',
link: '/profile',
icon: 'user',
action: closeMobileMenuAction,
},
{
name: 'Logout',
type: 'button',
icon: 'power-off',
action: () => deps.store.dispatch(deps.actions.logoutRequested()),
},
];
|
Remove some indirection, set db password | from pathlib import Path
from hoover.site.settings.common import *
INSTALLED_APPS = INSTALLED_APPS + [
'hoover.contrib.twofactor',
'django_otp',
'django_otp.plugins.otp_totp',
]
MIDDLEWARE = MIDDLEWARE + [
'django_otp.middleware.OTPMiddleware',
'hoover.contrib.twofactor.middleware.AutoLogout',
'hoover.contrib.twofactor.middleware.RequireAuth',
]
testsuite_dir = Path(__file__).absolute().parent
SECRET_KEY = 'testing secret key'
HOOVER_UPLOADS_ROOT = str(testsuite_dir / 'uploads')
HOOVER_UI_ROOT = str(testsuite_dir / 'mock_ui')
HOOVER_BASE_URL = 'http://testserver'
HOOVER_RATELIMIT_USER = (30, 60) # 30 per minute
HOOVER_TWOFACTOR_RATELIMIT = (3, 60) # 3 per minute
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'search',
'USER': 'search',
'HOST': 'search-pg',
'PORT': 5432,
},
}
HOOVER_ELASTICSEARCH_URL = 'http://search-es:9200'
| from pathlib import Path
from hoover.site.settings.common import *
INSTALLED_APPS = INSTALLED_APPS + [
'hoover.contrib.twofactor',
'django_otp',
'django_otp.plugins.otp_totp',
]
MIDDLEWARE = MIDDLEWARE + [
'django_otp.middleware.OTPMiddleware',
'hoover.contrib.twofactor.middleware.AutoLogout',
'hoover.contrib.twofactor.middleware.RequireAuth',
]
testsuite_dir = Path(__file__).absolute().parent
del HOOVER_ELASTICSEARCH_URL
SECRET_KEY = 'testing secret key'
HOOVER_UPLOADS_ROOT = str(testsuite_dir / 'uploads')
HOOVER_UI_ROOT = str(testsuite_dir / 'mock_ui')
HOOVER_BASE_URL = 'http://testserver'
HOOVER_RATELIMIT_USER = (30, 60) # 30 per minute
HOOVER_TWOFACTOR_RATELIMIT = (3, 60) # 3 per minute
from hoover.site.settings.testing_local import *
|
Remove search form on search results template | <section class="no-results not-found">
<header class="page-header">
<h1 class="page-title"><?php _e('Nothing Found', 'twentyseventeen'); ?></h1>
</header>
<div class="page-content">
<?php if (is_home() && current_user_can('publish_posts')) : ?>
<p><?php printf(__('Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'twentyseventeen'), esc_url(admin_url('post-new.php'))); ?></p>
<?php else : ?>
<p><?php _e('It seems we can’t find what you’re looking for. Perhaps searching can help.', 'twentyseventeen'); ?></p>
<?php
if (!is_search()):
get_search_form();
endif;
endif;
?>
</div><!-- .page-content -->
</section><!-- .no-results -->
| <section class="no-results not-found">
<header class="page-header">
<h1 class="page-title"><?php _e( 'Nothing Found', 'twentyseventeen' ); ?></h1>
</header>
<div class="page-content">
<?php if ( is_home() && current_user_can( 'publish_posts' ) ) : ?>
<p><?php printf( __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'twentyseventeen' ), esc_url( admin_url( 'post-new.php' ) ) ); ?></p>
<?php else : ?>
<p><?php _e( 'It seems we can’t find what you’re looking for. Perhaps searching can help.', 'twentyseventeen' ); ?></p>
<?php
get_search_form();
endif;
?>
</div><!-- .page-content -->
</section><!-- .no-results -->
|
Add missing new line at end of file | package com.documents4j.ws.endpoint;
import com.documents4j.api.DocumentType;
import com.documents4j.job.MockConversion;
import com.documents4j.ws.application.WebConverterTestConfiguration;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.core.Response;
import static org.junit.Assert.*;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
public class MonitoringHealthCreateDocumentResourceTest {
@Test
public void testHealthCreateDocument() {
final MonitoringHealthCreateDocumentResource monitoringHealthCreateDocumentResource = spy(new MonitoringHealthCreateDocumentResource());
doReturn(MockConversion.OK.toInputStream("")).when(monitoringHealthCreateDocumentResource).getTestStream();
monitoringHealthCreateDocumentResource.webConverterConfiguration = new WebConverterTestConfiguration(
true, 2000L, DocumentType.DOCX, DocumentType.PDF
);
final Response response = monitoringHealthCreateDocumentResource.serverInformation();
assertEquals(200, response.getStatus());
}
}
| package com.documents4j.ws.endpoint;
import com.documents4j.api.DocumentType;
import com.documents4j.job.MockConversion;
import com.documents4j.ws.application.WebConverterTestConfiguration;
import org.junit.Before;
import org.junit.Test;
import javax.ws.rs.core.Response;
import static org.junit.Assert.*;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
public class MonitoringHealthCreateDocumentResourceTest {
@Test
public void testHealthCreateDocument() {
final MonitoringHealthCreateDocumentResource monitoringHealthCreateDocumentResource = spy(new MonitoringHealthCreateDocumentResource());
doReturn(MockConversion.OK.toInputStream("")).when(monitoringHealthCreateDocumentResource).getTestStream();
monitoringHealthCreateDocumentResource.webConverterConfiguration = new WebConverterTestConfiguration(
true, 2000L, DocumentType.DOCX, DocumentType.PDF
);
final Response response = monitoringHealthCreateDocumentResource.serverInformation();
assertEquals(200, response.getStatus());
}
} |
Add transaction to project requirements | from setuptools import setup
setup(
name='sandbox',
version=open('VERSION').read().strip(),
long_description=(open('README.rst').read() + '\n' +
open('CHANGELOG.rst').read()),
py_modules=[
'sandbox',
],
setup_requires=[
],
install_requires=[
'aiohttp',
'aiohttp_traversal',
'BTrees',
'cchardet',
'setuptools',
'transaction',
'ZODB',
],
tests_require=[
],
entry_points = {
'console_scripts': [
'sandbox = sandbox:main',
]
}
)
| from setuptools import setup
setup(
name='sandbox',
version=open('VERSION').read().strip(),
long_description=(open('README.rst').read() + '\n' +
open('CHANGELOG.rst').read()),
py_modules=[
'sandbox',
],
setup_requires=[
],
install_requires=[
'aiohttp',
'aiohttp_traversal',
'BTrees',
'cchardet',
'setuptools',
'ZODB',
],
tests_require=[
],
entry_points = {
'console_scripts': [
'sandbox = sandbox:main',
]
}
)
|
Add missing validation of radio button form field value
See #2509 | <?php
namespace wcf\system\form\builder\field;
use wcf\system\form\builder\field\validation\FormFieldValidationError;
/**
* Implementation of a radio buttons form field for selecting a single value.
*
* @author Matthias Schmidt
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Form\Builder\Field
* @since 3.2
*/
class RadioButtonFormField extends AbstractFormField implements ISelectionFormField {
use TSelectionFormField;
/**
* @inheritDoc
*/
protected $templateName = '__radioButtonFormField';
/**
* @inheritDoc
*/
public function readValue() {
if ($this->getDocument()->hasRequestData($this->getPrefixedId())) {
$value = $this->getDocument()->getRequestData($this->getPrefixedId());
if (is_string($value)) {
$this->__value = $value;
}
}
return $this;
}
/**
* @inheritDoc
*/
public function supportsNestedOptions() {
return false;
}
/**
* @inheritDoc
*/
public function validate() {
if (!isset($this->getOptions()[$this->getValue()])) {
$this->addValidationError(new FormFieldValidationError(
'invalidValue',
'wcf.global.form.error.noValidSelection'
));
}
parent::validate();
}
}
| <?php
namespace wcf\system\form\builder\field;
/**
* Implementation of a radio buttons form field for selecting a single value.
*
* @author Matthias Schmidt
* @copyright 2001-2018 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package WoltLabSuite\Core\System\Form\Builder\Field
* @since 3.2
*/
class RadioButtonFormField extends AbstractFormField implements ISelectionFormField {
use TSelectionFormField;
/**
* @inheritDoc
*/
protected $templateName = '__radioButtonFormField';
/**
* @inheritDoc
*/
public function readValue() {
if ($this->getDocument()->hasRequestData($this->getPrefixedId())) {
$value = $this->getDocument()->getRequestData($this->getPrefixedId());
if (is_string($value)) {
$this->__value = $value;
}
}
return $this;
}
/**
* @inheritDoc
*/
public function supportsNestedOptions() {
return false;
}
}
|
Revert "casing lock on usernames. force lowercase"
This reverts commit cd8caf39b99c0eb2a1757a92563b869406fac94f. | /**
* Created by nightpaws on 08/02/2016.
*/
angular.module('user')
.controller('user.login.controller', ['$scope', 'user.service', function($scope, userService){
$scope.user = {
username: null,
password: null,
email: null
};
$scope.login = function(isValid){
if(!isValid){
return;
}
userService.login($scope.user.username, $scope.user.password);
};
$scope.register = function(isValid){
if(!isValid){
return;
}
userService.register($scope.user.username, $scope.user.email, $scope.user.password);
};
}]); | /**
* Created by nightpaws on 08/02/2016.
*/
angular.module('user')
.controller('user.login.controller', ['$scope', 'user.service', function($scope, userService){
$scope.user = {
username: null,
password: null,
email: null
};
$scope.login = function(isValid){
if(!isValid){
return;
}
userService.login($filter('lowercase')($scope.user.username), $scope.user.password);
};
$scope.register = function(isValid){
if(!isValid){
return;
}
userService.register($filter('lowercase')($scope.user.username), $scope.user.email, $scope.user.password);
};
}]); |
Update to work with lingon 2.* | 'use strict';
var gulp = require('gulp'); // for gulp.watch
module.exports = function(lingon, config) {
if(!config) config = {};
config.watchDir = config.watchDir || process.cwd() + '/' + lingon.config.sourcePath;
config.watchDir += "/**/*";
console.log(config.watchDir);
var watchFn = function(callback) {
gulp.task('default', function(){
lingon.log("Go!");
gulp.watch(config.watchDir, function(){
lingon.log("Build triggered by watch");
lingon.build({
'callback': callback
});
});
});
gulp.start();
};
lingon.registerTask('watch', watchFn, {
message: "Lingon watching " + config.watchDir + "."
});
};
| 'use strict';
var gulp = require('gulp'); // for gulp.watch
module.exports = function(lingon, config) {
if(!config) config = {};
config.watchDir = config.watchDir || process.cwd() + '/' + lingon.sourcePath;
config.watchDir += "/**/*";
console.log(config.watchDir);
var watchFn = function() {
gulp.task('default', function(){
lingon.log("Go!");
gulp.watch(config.watchDir, function(){
lingon.log("Build triggered by watch");
lingon.build();
});
});
gulp.start();
};
lingon.registerTask('watch', watchFn, {
message: "Lingon watching " + config.watchDir + "."
});
};
|
Extend ID validator to lookdev | import pyblish.api
class ValidateMindbenderID(pyblish.api.InstancePlugin):
"""All models must have an ID attribute"""
label = "Mindbender ID"
order = pyblish.api.ValidatorOrder
hosts = ["maya"]
families = ["mindbender.model", "mindbender.lookdev"]
def process(self, instance):
from maya import cmds
nodes = list(instance)
nodes += cmds.listRelatives(instance, allDescendents=True) or list()
missing = list()
for node in nodes:
# Only check transforms with a shape
if not cmds.listRelatives(node, shapes=True):
continue
try:
self.log.info("Checking '%s'" % node)
cmds.getAttr(node + ".mbID")
except ValueError:
missing.append(node)
assert not missing, ("Missing ID attribute on: %s"
% ", ".join(missing))
| import pyblish.api
class ValidateMindbenderID(pyblish.api.InstancePlugin):
"""All models must have an ID attribute"""
label = "Mindbender ID"
order = pyblish.api.ValidatorOrder
hosts = ["maya"]
families = ["mindbender.model"]
def process(self, instance):
from maya import cmds
nodes = list(instance)
nodes += cmds.listRelatives(instance, allDescendents=True) or list()
missing = list()
for node in nodes:
# Only check transforms with a shape
if not cmds.listRelatives(node, shapes=True):
continue
try:
self.log.info("Checking '%s'" % node)
cmds.getAttr(node + ".mbID")
except ValueError:
missing.append(node)
assert not missing, ("Missing ID attribute on: %s"
% ", ".join(missing))
|
Remove newline at end of file | var trexApp = angular.module('trexApp',
['ngRoute', 'trexControllers', 'trexFilters']);
trexApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when("/projects/", {
templateUrl: 'static/html/projects.html',
controller: 'ProjectListCtrl'
}).
when("/projects/:id", {
templateUrl: 'static/html/project-detail.html',
controller: 'ProjectDetailCtrl'
}).
otherwise({
redirectTo: '/'
});
}]
);
| var trexApp = angular.module('trexApp',
['ngRoute', 'trexControllers', 'trexFilters']);
trexApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when("/projects/", {
templateUrl: 'static/html/projects.html',
controller: 'ProjectListCtrl'
}).
when("/projects/:id", {
templateUrl: 'static/html/project-detail.html',
controller: 'ProjectDetailCtrl'
}).
otherwise({
redirectTo: '/'
});
}]
);
|
Add a restart() method to Timer. | inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def update(self, time):
if self.expired:
return
if self.elapsed > self.duration:
return
self.elapsed += time
if self.elapsed > self.duration:
self.expired = True
for callback in self.callbacks:
callback()
def restart(self):
self.expired = False
self.elapsed = 0
def pause(self):
self.paused = True
def unpause(self):
self.pause = False
def register(self, callback):
self.callbacks.append(callback)
def unregister(self, callback):
self.callbacks.remove(callback)
def has_expired(self):
return self.expired
| inf = infinity = float('inf')
class Timer:
def __init__(self, duration, *callbacks):
self.duration = duration
self.callbacks = list(callbacks)
self.elapsed = 0
self.expired = False
self.paused = False
def register(self, callback):
self.callbacks.append(callback)
def unregister(self, callback):
self.callbacks.remove(callback)
def pause(self):
self.paused = True
def unpause(self):
self.pause = False
def update(self, time):
if self.expired:
return
if self.elapsed > self.duration:
return
self.elapsed += time
if self.elapsed > self.duration:
self.expired = True
for callback in self.callbacks:
callback()
def has_expired(self):
return self.expired
|
Fix hcalendar module __doc__ missing | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
python-hcalendar is a basic hCalendar parser
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__version_info__ = {
'major': 0,
'minor': 2,
'micro': 0,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final':
vers.append('%(releaselevel)s' % __version_info__)
return ''.join(vers)
__version__ = get_version()
try:
from .hcalendar import hCalendar
except ImportError:
pass
__all__ = ['hCalendar']
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
"""
python-hcalendar is a basic hCalendar parser
"""
__version_info__ = {
'major': 0,
'minor': 2,
'micro': 0,
'releaselevel': 'final',
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final':
vers.append('%(releaselevel)s' % __version_info__)
return ''.join(vers)
__version__ = get_version()
try:
from .hcalendar import hCalendar
except ImportError:
pass
__all__ = ['hCalendar']
|
Add simple call test for set_connect_async | import pytest
from bonsai.utils import escape_filter_exp
from bonsai.utils import escape_attribute_value
from bonsai.utils import set_connect_async
def test_escape_attribute_value():
""" Test escaping special characters in attribute values. """
assert (
escape_attribute_value(" dummy=test,something+somethingelse")
== r"\ dummy\=test\,something\+somethingelse"
)
assert escape_attribute_value("#dummy=test ") == r"\#dummy\=test\ "
assert escape_attribute_value(r"term\0") == r"term\\0"
def test_escape_filter_exp():
""" Test escaping filter expressions. """
assert escape_filter_exp("(parenthesis)") == "\\28parenthesis\\29"
assert escape_filter_exp("cn=*") == "cn=\\2A"
assert escape_filter_exp("\\backslash") == "\\5Cbackslash"
assert escape_filter_exp("term\0") == "term\\0"
def test_set_async_connect(client):
""" Dummy test for set_connect_async. """
with pytest.raises(TypeError):
set_connect_async("true")
set_connect_async(False)
conn = client.connect()
assert conn is not None | import pytest
from bonsai.utils import escape_filter_exp
from bonsai.utils import escape_attribute_value
def test_escape_attribute_value():
""" Test escaping special characters in attribute values. """
assert (
escape_attribute_value(" dummy=test,something+somethingelse")
== r"\ dummy\=test\,something\+somethingelse"
)
assert escape_attribute_value("#dummy=test ") == r"\#dummy\=test\ "
assert escape_attribute_value(r"term\0") == r"term\\0"
def test_escape_filter_exp():
""" Test escaping filter expressions. """
assert escape_filter_exp("(parenthesis)") == "\\28parenthesis\\29"
assert escape_filter_exp("cn=*") == "cn=\\2A"
assert escape_filter_exp("\\backslash") == "\\5Cbackslash"
assert escape_filter_exp("term\0") == "term\\0"
|
Fix tests for udata/datagouvfr backend | import json
from six.moves.urllib_parse import urlencode
from .oauth import OAuth2Test
class DatagouvfrOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
user_data_url = 'https://www.data.gouv.fr/api/1/me/'
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_type': 'bearer',
'first_name': 'foobar',
'email': 'foobar@example.com'
})
request_token_body = urlencode({
'oauth_token_secret': 'foobar-secret',
'oauth_token': 'foobar',
'oauth_callback_confirmed': 'true'
})
user_data_body = json.dumps({})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
| import json
from six.moves.urllib_parse import urlencode
from .oauth import OAuth2Test
class DatagouvfrOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.udata.DatagouvfrOAuth2'
user_data_url = 'https://www.data.gouv.fr/api/1/me/'
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_type': 'bearer'
})
request_token_body = urlencode({
'oauth_token_secret': 'foobar-secret',
'oauth_token': 'foobar',
'oauth_callback_confirmed': 'true'
})
user_data_body = json.dumps({})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
|
Throw 500 error on multiple account in LocaleMiddleware so we can fix them.
git-svn-id: 51ba99f60490c2ee9ba726ccda75a38950f5105d@1120 45601e1e-1555-4799-bd40-45c8c71eef50 | from django.utils.cache import patch_vary_headers
from django.utils import translation
from account.models import Account
class LocaleMiddleware(object):
"""
This is a very simple middleware that parses a request
and decides what translation object to install in the current
thread context depending on the user's account. This allows pages
to be dynamically translated to the language the user desires
(if the language is available, of course).
"""
def get_language_for_user(self, request):
if request.user.is_authenticated():
try:
account = Account.objects.get(user=request.user)
return account.language
except Account.DoesNotExist:
pass
return translation.get_language_from_request(request)
def process_request(self, request):
translation.activate(self.get_language_for_user(request))
request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response):
patch_vary_headers(response, ('Accept-Language',))
response['Content-Language'] = translation.get_language()
translation.deactivate()
return response
| from django.utils.cache import patch_vary_headers
from django.utils import translation
from account.models import Account
class LocaleMiddleware(object):
"""
This is a very simple middleware that parses a request
and decides what translation object to install in the current
thread context depending on the user's account. This allows pages
to be dynamically translated to the language the user desires
(if the language is available, of course).
"""
def get_language_for_user(self, request):
if request.user.is_authenticated():
try:
account = Account.objects.get(user=request.user)
return account.language
except (Account.DoesNotExist, Account.MultipleObjectsReturned):
pass
return translation.get_language_from_request(request)
def process_request(self, request):
translation.activate(self.get_language_for_user(request))
request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response):
patch_vary_headers(response, ('Accept-Language',))
response['Content-Language'] = translation.get_language()
translation.deactivate()
return response
|
Remove application flag, not an application | # -*- coding: utf-8 -*-
# Copyright 2013-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
{'name': 'Connector',
'version': '10.0.1.0.0',
'author': 'Camptocamp,Openerp Connector Core Editors,'
'Odoo Community Association (OCA)',
'website': 'http://odoo-connector.com',
'license': 'AGPL-3',
'category': 'Generic Modules',
'depends': ['mail',
'queue_job',
],
'data': ['security/connector_security.xml',
'security/ir.model.access.csv',
'checkpoint/checkpoint_view.xml',
'connector_menu.xml',
'setting_view.xml',
'res_partner_view.xml',
],
'installable': True,
}
| # -*- coding: utf-8 -*-
# Copyright 2013-2017 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html)
{'name': 'Connector',
'version': '10.0.1.0.0',
'author': 'Camptocamp,Openerp Connector Core Editors,'
'Odoo Community Association (OCA)',
'website': 'http://odoo-connector.com',
'license': 'AGPL-3',
'category': 'Generic Modules',
'depends': ['mail',
'queue_job',
],
'data': ['security/connector_security.xml',
'security/ir.model.access.csv',
'checkpoint/checkpoint_view.xml',
'connector_menu.xml',
'setting_view.xml',
'res_partner_view.xml',
],
'installable': True,
'application': True,
}
|
Remove call to deprecated method
This will break in symfony 5.0, it has an easy replacement though. | <?php
declare(strict_types=1);
namespace App\EventListener;
use App\Service\Config;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use function Sentry\init as sentryInit;
use function Sentry\captureException as sentryCaptureException;
/**
* Sends errors to symfony
*/
class SentryCaptureListener
{
/**
* @var bool
*/
protected $errorCaptureEnabled;
public function __construct(
Config $config,
string $sentryDSN
) {
$this->errorCaptureEnabled = $config->get('errorCaptureEnabled');
if ($this->errorCaptureEnabled) {
sentryInit(['dsn' => $sentryDSN]);
}
}
public function onKernelException(ExceptionEvent $event)
{
if ($this->errorCaptureEnabled) {
$exception = $event->getThrowable();
//don't report 404s to Sentry
if ($exception instanceof NotFoundHttpException) {
return;
}
sentryCaptureException($exception);
}
}
}
| <?php
declare(strict_types=1);
namespace App\EventListener;
use App\Service\Config;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use function Sentry\init as sentryInit;
use function Sentry\captureException as sentryCaptureException;
/**
* Sends errors to symfony
*/
class SentryCaptureListener
{
/**
* @var bool
*/
protected $errorCaptureEnabled;
public function __construct(
Config $config,
string $sentryDSN
) {
$this->errorCaptureEnabled = $config->get('errorCaptureEnabled');
if ($this->errorCaptureEnabled) {
sentryInit(['dsn' => $sentryDSN]);
}
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
if ($this->errorCaptureEnabled) {
$exception = $event->getException();
//don't report 404s to Sentry
if ($exception instanceof NotFoundHttpException) {
return;
}
sentryCaptureException($exception);
}
}
}
|
Revert "Make config loading even lazier"
This reverts commit be7f9963eab041026853df68c4b9eeed46bf730d. | import fs from 'fs'
import _ from 'lodash'
import postcss from 'postcss'
import stylefmt from 'stylefmt'
import defaultConfig from './defaultConfig'
import mergeConfig from './util/mergeConfig'
import generateUtilities from './lib/generateUtilities'
import substituteHoverableAtRules from './lib/substituteHoverableAtRules'
import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules'
import substituteBreakpointAtRules from './lib/substituteBreakpointAtRules'
import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules'
const plugin = postcss.plugin('tailwind', (options = {}) => {
if (_.isFunction(options)) {
options = options()
}
const config = mergeConfig(defaultConfig, options)
return postcss([
generateUtilities(config),
substituteHoverableAtRules(config),
substituteResponsiveAtRules(config),
substituteBreakpointAtRules(config),
substituteClassApplyAtRules(config),
stylefmt,
])
})
module.exports = plugin
| import fs from 'fs'
import _ from 'lodash'
import postcss from 'postcss'
import stylefmt from 'stylefmt'
import defaultConfig from './defaultConfig'
import mergeConfig from './util/mergeConfig'
import generateUtilities from './lib/generateUtilities'
import substituteHoverableAtRules from './lib/substituteHoverableAtRules'
import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules'
import substituteBreakpointAtRules from './lib/substituteBreakpointAtRules'
import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules'
const plugin = postcss.plugin('tailwind', (options = {}) => {
return (root, result) => {
if (_.isFunction(options)) {
options = options()
}
const config = mergeConfig(defaultConfig, options)
return postcss([
generateUtilities(config),
substituteHoverableAtRules(config),
substituteResponsiveAtRules(config),
substituteBreakpointAtRules(config),
substituteClassApplyAtRules(config),
stylefmt,
]).process(result)
}
})
module.exports = plugin
|
Add a webpack output key for library name. | const path = require('path')
module.exports = {
context: __dirname,
entry: './src/index.js',
devtool: 'source-map',
output: {
library: 'es2016-starter',
libraryTarget: 'umd',
path: path.resolve('dist'),
filename: 'es2015-starter.js',
},
resolve: {
extensions: ['.js'],
modules: [
path.resolve('node_modules'),
path.resolve('src'),
],
},
module: {
loaders: [
{
use: ['babel-loader'],
test: /\.js$/,
exclude: [path.resolve('node_modules')],
},
{
use: 'file-loader',
test: /.*/,
exclude: [/\.js$/],
},
],
},
watchOptions: {
ignored: /node_modules/,
},
devServer: {
port: 3030,
contentBase: path.resolve('src'),
stats: 'errors-only',
overlay: {
warnings: true,
errors: true,
},
},
}
| const path = require('path')
module.exports = {
context: __dirname,
entry: './src/index.js',
devtool: 'source-map',
output: {
libraryTarget: 'umd',
path: path.resolve('dist'),
filename: 'es2015-starter.js',
},
resolve: {
extensions: ['.js'],
modules: [
path.resolve('node_modules'),
path.resolve('src'),
],
},
module: {
loaders: [
{
use: ['babel-loader'],
test: /\.js$/,
exclude: [path.resolve('node_modules')],
},
{
use: 'file-loader',
test: /.*/,
exclude: [/\.js$/],
},
],
},
watchOptions: {
ignored: /node_modules/,
},
devServer: {
port: 3030,
contentBase: path.resolve('src'),
stats: 'errors-only',
overlay: {
warnings: true,
errors: true,
},
},
}
|
Test needs skipping if on p3k | from .request_test import test_app
def test_200_for_normal_response_validation():
settings = {
'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/',
'pyramid_swagger.enable_swagger_spec_validation': False,
'pyramid_swagger.enable_response_validation': True,
}
test_app(settings).post_json(
'/sample',
{'foo': 'test', 'bar': 'test'},
status=200
)
def test_200_skip_validation_with_wrong_response():
settings = {
'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/',
'pyramid_swagger.skip_validation': '/(sample)\\b',
}
test_app(settings).get(
'/sample/path_arg1/resource',
params={'required_arg': 'test'},
status=200
)
| from .request_test import test_app
def test_200_for_normal_response_validation():
settings = {
'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/',
'pyramid_swagger.enable_response_validation': True,
}
test_app(settings).post_json(
'/sample',
{'foo': 'test', 'bar': 'test'},
status=200
)
def test_200_skip_validation_with_wrong_response():
settings = {
'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/',
'pyramid_swagger.skip_validation': '/(sample)\\b',
}
test_app(settings).get(
'/sample/path_arg1/resource',
params={'required_arg': 'test'},
status=200
)
|
Test de modification de squareSize non concluent | (function() {
tinymce.create('tinymce.plugins.chessPlug', {
init : function(ed, url) {
ed.addButton('chessBtn', {
title : 'Chess embed', image : url+'/chess.png',
onclick : function() { ed.selection.setContent('[pgn layout=vertical squareSize=58 initialHalfmove=28 autoplayMode=none showMoves=figurine]'+ed.selection.getContent()+'[/pgn]'); } });
},
createControl : function(n, cm) {
return null;
},
});
tinymce.PluginManager.add('chessBtn', tinymce.plugins.chessPlug);
})();
| (function() {
tinymce.create('tinymce.plugins.chessPlug', {
init : function(ed, url) {
ed.addButton('chessBtn', {
title : 'Chess embed', image : url+'/chess.png',
onclick : function() { ed.selection.setContent('[pgn layout=vertical initialHalfmove=28 autoplayMode=none showMoves=figurine]'+ed.selection.getContent()+'[/pgn]'); } });
},
createControl : function(n, cm) {
return null;
},
});
tinymce.PluginManager.add('chessBtn', tinymce.plugins.chessPlug);
})();
|
Add support for Dates to stringify, also improve stringify Object and Array | // based on the qs module, but handles null objects as expected
// fixes by Tomas Pollak.
var toString = Object.prototype.toString;
function stringify(obj, prefix) {
if (prefix && (obj === null || typeof obj == 'undefined')) {
return prefix + '=';
} else if (toString.call(obj) == '[object Array]') {
return stringifyArray(obj, prefix);
} else if (toString.call(obj) == '[object Object]') {
return stringifyObject(obj, prefix);
} else if (toString.call(obj) == '[object Date]') {
return obj.toISOString();
} else if (prefix) { // string inside array or hash
return prefix + '=' + encodeURIComponent(String(obj));
} else if (String(obj).indexOf('=') !== -1) { // string with equal sign
return String(obj);
} else {
throw new TypeError('Cannot build a querystring out of: ' + obj);
}
};
function stringifyArray(arr, prefix) {
var ret = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (prefix)
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
else
ret.push(stringify(arr[i]));
}
return ret.join('&');
}
function stringifyObject(obj, prefix) {
var ret = [];
Object.keys(obj).forEach(function(key) {
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
})
return ret.join('&');
}
exports.build = stringify;
| // based on the qs module, but handles null objects as expected
// fixes by Tomas Pollak.
function stringify(obj, prefix) {
if (prefix && (obj === null || typeof obj == 'undefined')) {
return prefix + '=';
} else if (obj.constructor == Array) {
return stringifyArray(obj, prefix);
} else if (obj !== null && typeof obj == 'object') {
return stringifyObject(obj, prefix);
} else if (prefix) { // string inside array or hash
return prefix + '=' + encodeURIComponent(String(obj));
} else if (String(obj).indexOf('=') !== -1) { // string with equal sign
return String(obj);
} else {
throw new TypeError('Cannot build a querystring out of: ' + obj);
}
};
function stringifyArray(arr, prefix) {
var ret = [];
for (var i = 0, len = arr.length; i < len; i++) {
if (prefix)
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
else
ret.push(stringify(arr[i]));
}
return ret.join('&');
}
function stringifyObject(obj, prefix) {
var ret = [];
Object.keys(obj).forEach(function(key) {
ret.push(stringify(obj[key], prefix
? prefix + '[' + encodeURIComponent(key) + ']'
: encodeURIComponent(key)));
})
return ret.join('&');
}
exports.build = stringify;
|
Remove trailing numbers from base. | package org.metaborg.meta.nabl2.solver;
import java.io.Serializable;
import java.util.Map;
import com.google.common.collect.Maps;
public class Fresh implements Serializable {
private static final long serialVersionUID = 42L;
private final Map<String,Integer> counters;
public Fresh() {
counters = Maps.newConcurrentMap();
}
public String fresh(String base) {
// remove any number suffix from the base
base = base.replaceFirst("-[0-9]+$", "");
// to prevent accidental name clashes, ensure the base contains no dashes,
// and then use dashes as our connecting character.
base = base.replaceAll("-", "_");
int k = counters.getOrDefault(base, 0) + 1;
counters.put(base, k);
return base + "-" + k;
}
public void reset() {
counters.clear();
}
} | package org.metaborg.meta.nabl2.solver;
import java.io.Serializable;
import java.util.Map;
import com.google.common.collect.Maps;
public class Fresh implements Serializable {
private static final long serialVersionUID = 42L;
private final Map<String,Integer> counters;
public Fresh() {
counters = Maps.newConcurrentMap();
}
public String fresh(String base) {
// to prevent accidental name clashes, ensure the base contains no dashes,
// and then use dashes as our connecting character.
base = base.replaceAll("-", "_");
int k = counters.getOrDefault(base, 0) + 1;
counters.put(base, k);
return base + "-" + k;
}
public void reset() {
counters.clear();
}
} |
Add proper Factory name for `ValidatorPluginManager` and add `ValidatorManager` as alias for it | <?php
/**
* @link http://github.com/zendframework/zend-validator for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
class ConfigProvider
{
/**
* Return configuration for this component.
* @return array
*/
public function __invoke()
{
return [
'dependencies' => $this->getDependencyConfig(),
];
}
/**
* Return dependency mappings for this component.
* @return array
*/
public function getDependencyConfig()
{
return [
'factories' => [
ValidatorPluginManager::class => ValidatorPluginManagerFactory::class,
],
'aliases' => [
'ValidatorManager' => ValidatorPluginManager::class,
],
];
}
}
| <?php
/**
* @link http://github.com/zendframework/zend-validator for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
class ConfigProvider
{
/**
* Return configuration for this component.
*
* @return array
*/
public function __invoke()
{
return [
'dependencies' => $this->getDependencyConfig(),
];
}
/**
* Return dependency mappings for this component.
*
* @return array
*/
public function getDependencyConfig()
{
return [
'factories' => [
'ValidatorManager' => ValidatorPluginManagerFactory::class,
],
];
}
}
|
Add ability to reverse views with args and kwargs | from django import VERSION as DJANGO_VERSION
from django import template
from django.conf import settings
if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
register = template.Library()
@register.simple_tag(takes_context=True)
def active_link(context, viewname, css_class=None, strict=None, *args, **kwargs):
"""
Renders the given CSS class if the request path matches the path of the view.
:param context: The context where the tag was called. Used to access the request object.
:param viewname: The name of the view (include namespaces if any).
:param css_class: The CSS class to render.
:param strict: If True, the tag will perform an exact match with the request path.
:return:
"""
if css_class is None:
css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active')
if strict is None:
strict = getattr(settings, 'ACTIVE_LINK_STRICT', False)
request = context.get('request')
if request is None:
# Can't work without the request object.
return ''
path = reverse(viewname, args=args, kwargs=kwargs)
if strict:
active = request.path == path
else:
active = request.path.find(path) == 0
if active:
return css_class
return ''
| from django import VERSION as DJANGO_VERSION
from django import template
from django.conf import settings
if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
register = template.Library()
@register.simple_tag(takes_context=True)
def active_link(context, viewname, css_class=None, strict=None):
"""
Renders the given CSS class if the request path matches the path of the view.
:param context: The context where the tag was called. Used to access the request object.
:param viewname: The name of the view (include namespaces if any).
:param css_class: The CSS class to render.
:param strict: If True, the tag will perform an exact match with the request path.
:return:
"""
if css_class is None:
css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active')
if strict is None:
strict = getattr(settings, 'ACTIVE_LINK_STRICT', False)
request = context.get('request')
if request is None:
# Can't work without the request object.
return ''
path = reverse(viewname)
if strict:
active = request.path == path
else:
active = request.path.find(path) == 0
if active:
return css_class
return ''
|
Remove print("failing back on pretty_print") when using dolo-recs | #from __future__ import print_function
# This module is supposed to be imported first
# it contains global variables used for configuration
# try to register printing methods if IPython is running
save_plots = False
try:
import dolo.misc.printing as printing
from numpy import ndarray
from dolo.symbolic.model import Model
from dolo.numeric.decision_rules import DynareDecisionRule
ip = get_ipython()
# there could be some kind of autodecovery there
ip.display_formatter.formatters['text/html'].for_type( ndarray, printing.print_array )
ip.display_formatter.formatters['text/html'].for_type( Model, printing.print_model )
ip.display_formatter.formatters['text/html'].for_type( DynareDecisionRule, printing.print_dynare_decision_rule )
from IPython.core.display import display
except:
import re
import sys
if not re.search('dolo-recs',sys.argv[0]):
print("failing back on pretty_print")
from pprint import pprint
def display(txt):
pprint(txt)
| #from __future__ import print_function
# This module is supposed to be imported first
# it contains global variables used for configuration
# try to register printing methods if IPython is running
save_plots = False
try:
import dolo.misc.printing as printing
from numpy import ndarray
from dolo.symbolic.model import Model
from dolo.numeric.decision_rules import DynareDecisionRule
ip = get_ipython()
# there could be some kind of autodecovery there
ip.display_formatter.formatters['text/html'].for_type( ndarray, printing.print_array )
ip.display_formatter.formatters['text/html'].for_type( Model, printing.print_model )
ip.display_formatter.formatters['text/html'].for_type( DynareDecisionRule, printing.print_dynare_decision_rule )
from IPython.core.display import display
except:
print("failing back on pretty_print")
from pprint import pprint
def display(txt):
pprint(txt)
|
Fix in string representation of product model. | from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
from ckeditor.fields import RichTextField
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class ProductType(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-type-list')
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30, unique=True)
def get_absolute_url(self):
return reverse('uom-list')
def __str__(self):
return "%(self.unit)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
product_type = models.ForeignKey(ProductType, default=0)
category = models.ForeignKey(ProductCategory)
description = RichTextField(blank=True, default='')
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "{}".format(self.name)
| from django.db import models
from amadaa.models import AmadaaModel
from django.urls import reverse
from ckeditor.fields import RichTextField
# Create your models here.
class ProductCategory(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-category-detail', kwargs={'pk': self.pk})
def __str__(self):
return "{}".format(self.name)
class ProductType(AmadaaModel):
name = models.CharField(max_length=100, unique=True)
def get_absolute_url(self):
return reverse('product-type-list')
def __str__(self):
return "{}".format(self.name)
class UnitOfMeasurement(AmadaaModel):
unit = models.CharField(max_length=30, unique=True)
def get_absolute_url(self):
return reverse('uom-list')
def __str__(self):
return "%(self.unit)s"
class Product(AmadaaModel):
name = models.CharField(max_length=100)
internal_ref = models.CharField(max_length=100, default='')
product_type = models.ForeignKey(ProductType, default=0)
category = models.ForeignKey(ProductCategory)
description = RichTextField(blank=True, default='')
def get_absolute_url(self):
return reverse('product-list')
def __str__(self):
return "%(self.name)s"
|
Fix styling issue in URLConf. | from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url
urlpatterns = patterns('pytask.profile.views',
url(r'^view/$', 'view_profile', name='view_profile'),
url(r'^edit/$', 'edit_profile', name='edit_profile'),
url(r'^notification/browse/$', 'browse_notifications',
name='browse_notifications'),
url(r'^notification/view/(?P<notification_id>\d+)$',
'view_notification', name='view_notification'),
url(r'^notification/delete/(?P<notification_id>\d+)$',
'delete_notification', name='delete_notification'),
url(r'^notification/unread/(?P<notification_id>\d+)$',
'unread_notification', name='unread_notification'),
url(r'^user/view/(?P<user_id>\d+)$', 'view_user',
name='view_user'),
)
| from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url
urlpatterns = patterns('pytask.profile.views',
url(r'^view/$', 'view_profile', name='view_profile'),
url(r'^edit/$', 'edit_profile', name='edit_profile'),
url(r'^notf/browse/$', 'browse_notifications',
name='edit_profile'),
url(r'^notf/view/(?P<notification_id>\d+)$', 'view_notification',
name='view_notification'),
url(r'^notf/del/(?P<notification_id>\d+)$', 'delete_notification',
name='delete_notification'),
url(r'^notf/unr/(?P<notification_id>\d+)$', 'unread_notification',
name='unread_notification'),
url(r'^user/view/(?P<user_id>\d+)$', 'view_user',
name='view_user'),
)
|
Make application function more like a backbone view | class GelatoApplication extends Backbone.View {
constructor(options) {
options = options || {};
options.tagName = 'gelato-application';
super(options);
}
render() {
$(document.body).prepend(this.el);
this.$el.append('<gelato-navbar></gelato-navbar>');
this.$el.append('<gelato-pages></gelato-pages>');
this.$el.append('<gelato-footer></gelato-footer>');
this.$el.append('<gelato-dialogs></gelato-dialogs>');
return this;
}
getHeight() {
return Backbone.$('gelato-application').height();
}
getWidth() {
return Backbone.$('gelato-application').width();
}
isLandscape() {
return this.getWidth() > this.getHeight();
}
isPortrait() {
return this.getWidth() <= this.getHeight();
}
}
Gelato = Gelato || {};
Gelato.Application = GelatoApplication;
| class GelatoApplication extends Backbone.Model {
constructor() {
Backbone.$('body').prepend('<gelato-application></gelato-application>');
Backbone.$('gelato-application').append('<gelato-dialogs></gelato-dialogs>');
Backbone.$('gelato-application').append('<gelato-navbar></gelato-navbar>');
Backbone.$('gelato-application').append('<gelato-pages></gelato-pages>');
Backbone.$('gelato-application').append('<gelato-footer></gelato-footer>');
super(arguments);
}
getHeight() {
return Backbone.$('gelato-application').height();
}
getWidth() {
return Backbone.$('gelato-application').width();
}
isLandscape() {
return this.getWidth() > this.getHeight();
}
isPortrait() {
return this.getWidth() <= this.getHeight();
}
reload(forcedReload) {
location.reload(forcedReload);
}
}
Gelato = Gelato || {};
Gelato.Application = GelatoApplication;
|
Remove lodash dependency and improve code quality.
This code was initially written in CoffeeScript and then compiled
directly into ES5. | var slice = [].slice;
var EventStream = (function() {
function EventStream() {
if (!(this instanceof EventStream)) {
return new EventStream();
}
this.callbacks = {};
}
EventStream.prototype.unregisterAllCallbacks = function unregisterAllCallbacks() {
this.callbacks = {};
};
EventStream.prototype.on = function on(event, callback) {
if (!this.callbacks[event]) {
this.callbacks[event] = [];
}
this.callbacks[event].push(callback);
};
EventStream.prototype.publish = function publish() {
var event = arguments[0];
var args = arguments.length >= 2 ? slice.call(arguments, 1) : [];
if (this.callbacks && this.callbacks[event]) {
this.callbacks[event].forEach(function(callback) {
callback.apply(null, args);
});
}
};
return EventStream;
})();
module.exports = EventStream;
| var lodash = require('lodash');
var each = lodash.each;
var slice = [].slice;
var EventStream = (function() {
function EventStream() {
if(!(this instanceof EventStream))
return new EventStream();
this.callbacks = {};
}
EventStream.prototype.unregisterAllCallbacks = function unregisterAllCallbacks() {
this.callbacks = {};
};
EventStream.prototype.on = function on(event, callback) {
if (!this.callbacks[event]) {
this.callbacks[event] = [];
}
this.callbacks[event].push(callback);
};
EventStream.prototype.publish = function publish() {
var args, event;
event = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
if (this.callbacks) {
return each(this.callbacks[event], (function(_this) {
return function(callback) {
return callback.apply(null, args);
};
})(this));
}
};
return EventStream;
})();
module.exports = EventStream;
|
Refactor list append to list comprehension. | # -*- coding: utf-8 -*-
import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from syntax import clause
def phrases(n=20, lf=' '):
phrase_list = [repr(clause()).capitalize() + '.'
for i in range(n)]
return lf.join(phrase_list)
class MainPage(webapp.RequestHandler):
def get(self):
n = int(self.request.get('num_phrases') or '20')
lf = '<br>\n' if self.request.get('break_line') == 'true' else ' '
text = phrases(n, lf)
template_values = {
'text': text,
'num_phrases': self.request.get('num_phrases'),
'checked': 'checked' if self.request.get('break_line') == 'true' else ''
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication([('/', MainPage)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
| # -*- coding: utf-8 -*-
import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from syntax import clause
def phrases(n=20, lf=' '):
phrase_list = []
for i in range(n):
phrase_list.append(repr(clause()).capitalize() + '.')
return lf.join(phrase_list)
class MainPage(webapp.RequestHandler):
def get(self):
n = int(self.request.get('num_phrases') or '20')
lf = '<br>\n' if self.request.get('break_line') == 'true' else ' '
text = phrases(n, lf)
template_values = {
'text': text,
'num_phrases': self.request.get('num_phrases'),
'checked': 'checked' if self.request.get('break_line') == 'true' else ''
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication([('/', MainPage)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
|
Add comments for wod controller. | angular.module('myApp')
.controller('WodController', function($scope, $routeParams, $sce, Wod, Video) {
// Extract workout configuration parameters passed in url.
var settings = $routeParams.id;
settings = settings.replace(/[\[\]']+/g,'');
settings = settings.split(",");
var parameters = "intensity="+settings[0]+"&focus="+settings[1]+"&format="+settings[2];
// Call service to obatain WOD (workout of the day) by passing configuration parameters.
$scope.wod = Wod.query({id: parameters});
$scope.wod.$promise.then(function (result) {
$scope.wod = result;
$scope.reps = $scope.wod[0];
$scope.exercise = $scope.wod[1];
$scope.clock = $scope.wod[2];
// Call Video service pass exercises to use them as hashtags and extract them as videos using Instagram API.
$scope.video = Video.query({id: "exercise="+$scope.exercise});
$scope.video.$promise.then(function (result) {
$scope.video = result;
$scope.src = $sce.trustAsResourceUrl($scope.video[0]);
});
});
}); | angular.module('myApp')
.controller('WodController', function($scope, $routeParams, $sce, Wod, Video) {
var settings = $routeParams.id;
settings = settings.replace(/[\[\]']+/g,'');
settings = settings.split(",");
var parameters = "intensity="+settings[0]+"&focus="+settings[1]+"&format="+settings[2];
$scope.wod = Wod.query({id: parameters});
$scope.wod.$promise.then(function (result) {
$scope.wod = result;
$scope.reps = $scope.wod[0];
$scope.exercise = $scope.wod[1];
$scope.clock = $scope.wod[2];
$scope.video = Video.query({id: $scope.exercise});
$scope.video.$promise.then(function (result) {
$scope.video = result;
$scope.src = $sce.trustAsResourceUrl($scope.video[0]);
});
});
}); |
Fix prettier config to remove unecessary diff | const { readBsConfig, readBsConfigSync } = require('../')
test('Read bsconfig from process.cwd()', () => {
expect(readBsConfig()).rejects.toBeDefined()
})
test('Read bsconfig from __dirname', async () => {
const bsConfig = await readBsConfig(__dirname)
expect(bsConfig).toEqual({
name: 'reason-scripts',
sources: ['src'],
'bs-dependencies': ['reason-react', 'bs-jest'],
reason: {
'react-jsx': 2
},
'bsc-flags': ['-bs-super-errors']
})
})
test('Read bsconfig from __dirname synchronously', () => {
const bsConfig = readBsConfigSync(__dirname)
expect(bsConfig).toEqual({
name: 'reason-scripts',
sources: ['src'],
'bs-dependencies': ['reason-react', 'bs-jest'],
reason: {
'react-jsx': 2
},
'bsc-flags': ['-bs-super-errors']
})
})
| const { readBsConfig, readBsConfigSync } = require('../')
test('Read bsconfig from process.cwd()', () => {
expect(readBsConfig()).rejects.toBeDefined()
})
test('Read bsconfig from __dirname', async () => {
const bsConfig = await readBsConfig(__dirname)
expect(bsConfig).toEqual({
name: 'reason-scripts',
sources: ['src'],
'bs-dependencies': ['reason-react', 'bs-jest'],
reason: {
'react-jsx': 2,
},
'bsc-flags': ['-bs-super-errors'],
})
})
test('Read bsconfig from __dirname synchronously', () => {
const bsConfig = readBsConfigSync(__dirname)
expect(bsConfig).toEqual({
name: 'reason-scripts',
sources: ['src'],
'bs-dependencies': ['reason-react', 'bs-jest'],
reason: {
'react-jsx': 2,
},
'bsc-flags': ['-bs-super-errors'],
})
})
|
Build APIException all exceptions must be handled | from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not response and settings.FRIENDLY_CATCH_ALL_EXCEPTIONS:
response = exception_handler(APIException(exc), context)
if response is not None:
if is_pretty(response):
return response
error_message = response.data['detail']
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data.pop('detail', {})
response.data['code'] = error_code
response.data['message'] = error_message
response.data['status_code'] = response.status_code
# response.data['exception'] = exc.__class__.__name__
return response
| from rest_framework.views import exception_handler
from rest_framework_friendly_errors import settings
from rest_framework_friendly_errors.utils import is_pretty
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if response is not None:
if is_pretty(response):
return response
error_message = response.data['detail']
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data.pop('detail', {})
response.data['code'] = error_code
response.data['message'] = error_message
response.data['status_code'] = response.status_code
# response.data['exception'] = exc.__class__.__name__
return response
|
Change name manager Publisher to Published | #!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublishedMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublishedMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
| #!/usr/bin/env python
from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
class PublisherMnager(models.Manager):
def all_published(self):
return super(PublisherMnager, self).get_query_set().filter(
date_available__lte=datetime.now(), published=True)
class Published(models.Model):
date_available = models.DateTimeField(_(u"Date available"),
default=datetime.now, null=True)
published = models.BooleanField(_(u"Published"), default=False)
objects = PublisherMnager()
class Meta:
abstract = True
def is_published(self):
return self.published and \
self.date_available.replace(tzinfo=None) <= datetime.now()
|
Change log file size to 1MB | import string
template = string.Template("""#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
# DNS configuration options
#
[DEFAULT]
# dns_config_file=dns_config.xml
hostip=$__contrail_host_ip__ # Resolved IP of `hostname`
hostname=$__contrail_hostname__ # Retrieved as `hostname`
# http_server_port=8092
# log_category=
# log_disable=0
log_file=/var/log/contrail/dns.log
# log_files_count=10
# log_file_size=1048576 # 1MB
# log_level=SYS_NOTICE
# log_local=0
# test_mode=0
[COLLECTOR]
# port=8086
# server= # Provided by discovery server
[DISCOVERY]
# port=5998
server=$__contrail_discovery_ip__ # discovery-server IP address
[IFMAP]
certs_store=$__contrail_cert_ops__
password=$__contrail_ifmap_paswd__
# server_url= # Provided by discovery server, e.g. https://127.0.0.1:8443
user=$__contrail_ifmap_usr__
""")
| import string
template = string.Template("""#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
# DNS configuration options
#
[DEFAULT]
# dns_config_file=dns_config.xml
hostip=$__contrail_host_ip__ # Resolved IP of `hostname`
hostname=$__contrail_hostname__ # Retrieved as `hostname`
# http_server_port=8092
# log_category=
# log_disable=0
log_file=/var/log/contrail/dns.log
# log_files_count=10
# log_file_size=10485760 # 10MB
# log_level=SYS_NOTICE
# log_local=0
# test_mode=0
[COLLECTOR]
# port=8086
# server= # Provided by discovery server
[DISCOVERY]
# port=5998
server=$__contrail_discovery_ip__ # discovery-server IP address
[IFMAP]
certs_store=$__contrail_cert_ops__
password=$__contrail_ifmap_paswd__
# server_url= # Provided by discovery server, e.g. https://127.0.0.1:8443
user=$__contrail_ifmap_usr__
""")
|
Fix js bug for heroku | var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: centerFinder(),
zoom: 12
});
if (window.hasOwnProperty('placesInfo')) {
window.placesInfo.forEach(function(location_obj){
return markerMaker(location_obj)
})
}
}
function centerFinder(){
if (window.hasOwnProperty('placesInfo')) {
if (window.placesInfo.length > 0) {
return window.placesInfo[0]["loc_lat_lng"]
}
} else {
return window.mapCenterLocation
}
};
function markerMaker(location_obj){
var locationDetails = "<strong>" + location_obj['loc_name'] + "</strong><br>" + location_obj['loc_address'] + ""
var infoWindow = new google.maps.InfoWindow({
content: locationDetails
});
var marker = new google.maps.Marker({
position: location_obj["loc_lat_lng"],
map: map,
animation: google.maps.Animation.DROP
});
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
| var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: centerFinder(),
zoom: 12
});
window.placesInfo.forEach(function(location_obj){
return markerMaker(location_obj)
})
}
function centerFinder(){
if (window.hasOwnProperty('placesInfo')) {
if (window.placesInfo.length > 0) {
return window.placesInfo[0]["loc_lat_lng"]
}
} else {
return window.mapCenterLocation
}
};
function markerMaker(location_obj){
var locationDetails = "<strong>" + location_obj['loc_name'] + "</strong><br>" + location_obj['loc_address'] + ""
var infoWindow = new google.maps.InfoWindow({
content: locationDetails
});
var marker = new google.maps.Marker({
position: location_obj["loc_lat_lng"],
map: map,
animation: google.maps.Animation.DROP
});
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
|
Set serializer_class on ObtainAuthToken view | from rest_framework.views import APIView
from rest_framework import parsers
from rest_framework import renderers
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
class ObtainAuthToken(APIView):
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
obtain_auth_token = ObtainAuthToken.as_view()
| from rest_framework.views import APIView
from rest_framework import parsers
from rest_framework import renderers
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
class ObtainAuthToken(APIView):
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
def post(self, request):
serializer = AuthTokenSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
obtain_auth_token = ObtainAuthToken.as_view()
|
Make the script respond to ctrl-c | """Pusher intergration for messages from the cloud."""
import json
import logging
import Queue
import sys
from common import creds
from pusherclient import Pusher
class PushRPC(object):
"""Wrapper for pusher integration."""
def __init__(self):
self._queue = Queue.Queue()
self._pusher = Pusher(creds.pusher_key)
self._pusher.connection.bind('pusher:connection_established',
self._connect_handler)
self._pusher.connect()
def _connect_handler(self, _):
channel = self._pusher.subscribe('test')
channel.bind('event', self._callback_handler)
def _callback_handler(self, data):
"""Callback for when messages are recieved from pusher."""
try:
data = json.loads(data)
except ValueError:
logging.error('Error parsing message', exc_info=sys.exc_info())
return
self._queue.put(data)
def events(self):
while True:
# if we specify a timeout, queues become keyboard interruptable
try:
yield self._queue.get(block=True, timeout=1000)
except Queue.Empty:
pass
| """Pusher intergration for messages from the cloud."""
import json
import logging
import Queue
import sys
from common import creds
from pusherclient import Pusher
class PushRPC(object):
"""Wrapper for pusher integration."""
def __init__(self):
self._queue = Queue.Queue()
self._pusher = Pusher(creds.pusher_key)
self._pusher.connection.bind('pusher:connection_established',
self._connect_handler)
self._pusher.connect()
def _connect_handler(self, _):
channel = self._pusher.subscribe('test')
channel.bind('event', self._callback_handler)
def _callback_handler(self, data):
"""Callback for when messages are recieved from pusher."""
try:
data = json.loads(data)
except ValueError:
logging.error('Error parsing message', exc_info=sys.exc_info())
return
self._queue.put(data)
def events(self):
while True:
yield self._queue.get(block=True)
|
Use regularized covariance in CSP by default | # Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch", reg="ledoit_wolf")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
| # Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
|
Allow null configs in docblock | <?php
namespace League\Flysystem;
/**
* @internal
*/
trait ConfigAwareTrait
{
/**
* @var Config
*/
protected $config;
/**
* Set the config.
*
* @param Config|array|null $config
*/
protected function setConfig($config)
{
$this->config = $config ? Util::ensureConfig($config) : null;
}
/**
* Get the Config.
*
* @return Config config object
*/
public function getConfig()
{
if ($this->config === null) {
return $this->config = new Config;
}
return $this->config;
}
/**
* Convert a config array to a Config object with the correct fallback.
*
* @param array $config
*
* @return Config
*/
protected function prepareConfig(array $config)
{
$config = new Config($config);
$config->setFallback($this->getConfig());
return $config;
}
}
| <?php
namespace League\Flysystem;
/**
* @internal
*/
trait ConfigAwareTrait
{
/**
* @var Config
*/
protected $config;
/**
* Set the config.
*
* @param Config|array $config
*/
protected function setConfig($config)
{
$this->config = $config ? Util::ensureConfig($config) : null;
}
/**
* Get the Config.
*
* @return Config config object
*/
public function getConfig()
{
if ($this->config === null) {
return $this->config = new Config;
}
return $this->config;
}
/**
* Convert a config array to a Config object with the correct fallback.
*
* @param array $config
*
* @return Config
*/
protected function prepareConfig(array $config)
{
$config = new Config($config);
$config->setFallback($this->getConfig());
return $config;
}
}
|
Add comment for timer.unref check | module.exports = function (promise, timeout, opts) {
var Promise = promise.constructor;
var rejectWith = opts && opts.rejectWith;
var resolveWith = opts && opts.resolveWith;
var timer;
var timeoutPromise = new Promise(function (resolve, reject) {
timer = setTimeout(function () {
if (rejectWith !== void 0)
reject(rejectWith);
else
resolve(resolveWith);
}, timeout);
});
return Promise.race([timeoutPromise, promise])
.then(function (value) {
// For browser support: timer.unref is only available in Node.
if (timer.unref) timer.unref();
return value;
}, function (error) {
// For browser support: timer.unref is only available in Node.
if (timer.unref) timer.unref();
throw error;
});
};
| module.exports = function (promise, timeout, opts) {
var Promise = promise.constructor;
var rejectWith = opts && opts.rejectWith;
var resolveWith = opts && opts.resolveWith;
var timer;
var timeoutPromise = new Promise(function (resolve, reject) {
timer = setTimeout(function () {
if (rejectWith !== void 0)
reject(rejectWith);
else
resolve(resolveWith);
}, timeout);
});
return Promise.race([timeoutPromise, promise])
.then(function (value) {
if (timer.unref) timer.unref();
return value;
}, function (error) {
if (timer.unref) timer.unref();
throw error;
});
};
|
[Glitch] Fix unnecessary service worker registration and preloading when logged out
Port 894ce3726a38733ea7b8c880658b962f92d021ae to glitch-soc
Signed-off-by: Claire <82b964c50e9d1d222e48cf5046e6484a966a7b07@sitedethib.com> | import React from 'react';
import ReactDOM from 'react-dom';
import { setupBrowserNotifications } from 'flavours/glitch/actions/notifications';
import Mastodon, { store } from 'flavours/glitch/containers/mastodon';
import ready from 'flavours/glitch/ready';
const perf = require('flavours/glitch/performance');
/**
* @returns {Promise<void>}
*/
function main() {
perf.start('main()');
return ready(async () => {
const mountNode = document.getElementById('mastodon');
const props = JSON.parse(mountNode.getAttribute('data-props'));
ReactDOM.render(<Mastodon {...props} />, mountNode);
store.dispatch(setupBrowserNotifications());
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
const [{ Workbox }, { me }] = await Promise.all([
import('workbox-window'),
import('flavours/glitch/initial_state'),
]);
if (me) {
const wb = new Workbox('/sw.js');
try {
await wb.register();
} catch (err) {
console.error(err);
return;
}
const registerPushNotifications = await import('flavours/glitch/actions/push_notifications');
store.dispatch(registerPushNotifications.register());
}
}
perf.stop('main()');
});
}
export default main;
| import React from 'react';
import ReactDOM from 'react-dom';
import { setupBrowserNotifications } from 'flavours/glitch/actions/notifications';
import Mastodon, { store } from 'flavours/glitch/containers/mastodon';
import ready from 'flavours/glitch/ready';
const perf = require('flavours/glitch/performance');
/**
* @returns {Promise<void>}
*/
function main() {
perf.start('main()');
return ready(async () => {
const mountNode = document.getElementById('mastodon');
const props = JSON.parse(mountNode.getAttribute('data-props'));
ReactDOM.render(<Mastodon {...props} />, mountNode);
store.dispatch(setupBrowserNotifications());
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
const [{ Workbox }, { me }] = await Promise.all([
import('workbox-window'),
import('flavours/glitch/initial_state'),
]);
const wb = new Workbox('/sw.js');
try {
await wb.register();
} catch (err) {
console.error(err);
return;
}
if (me) {
const registerPushNotifications = await import('flavours/glitch/actions/push_notifications');
store.dispatch(registerPushNotifications.register());
}
}
perf.stop('main()');
});
}
export default main;
|
Fix bug causing extraneous notifications on repos with mixed-state modules | import Notify from 'notifyjs';
import WatchingProvider from './WatchingProvider';
let lastModuleStates = {};
let BuildsNotifier = {
updateModules: function(modules) {
modules.forEach((module) => {
if (WatchingProvider.isWatching({ repo: module.repository, branch: module.branch }) === -1) {
return;
}
let id = JSON.stringify({ repo: module.repository, branch: module.branch, build: module.module });
if (lastModuleStates[id] === 'IN_PROGRESS' && module.inProgressBuildLink === undefined) {
this.showNotification(module.repository, module.branch, module.module, module.lastBuildState, module.link);
}
lastModuleStates[id] = (module.inProgressBuildLink !== undefined ? 'IN_PROGRESS' : module.lastBuildState);
});
},
showNotification: function(repo, branch, module, state, link) {
let body = `${repo}[${branch}] ${module}: ${state}`;
var notification = new Notify('Build Complete', {
body: body,
icon: '/images/icon.jpg',
notifyClick: () => {
window.open(link);
}
});
notification.show();
}
};
export default BuildsNotifier;
| import Notify from 'notifyjs';
import WatchingProvider from './WatchingProvider';
let lastModuleStates = {};
let BuildsNotifier = {
updateModules: function(modules) {
modules.forEach((module) => {
let id = { repo: module.repository, branch: module.branch };
if (WatchingProvider.isWatching(id) === -1) {
return;
}
if (lastModuleStates[id] === 'IN_PROGRESS' && module.inProgressBuildLink === undefined) {
this.showNotification(module.repository, module.branch, module.module, module.lastBuildState, module.link);
}
lastModuleStates[id] = (module.inProgressBuildLink !== undefined ? 'IN_PROGRESS' : module.lastBuildState);
});
},
showNotification: function(repo, branch, module, state, link) {
let body = `${repo}[${branch}] ${module}: ${state}`;
var notification = new Notify('Build Complete', {
body: body,
icon: '/images/icon.jpg',
notifyClick: () => {
window.open(link);
}
});
notification.show();
}
};
export default BuildsNotifier;
|
Rename null description test case | package edu.pdx.cs410J.chances;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Unit tests for the {@link Appointment} class.
*/
public class AppointmentTest {
@Test
public void getBeginTimeStringNeedsToBeImplemented() {
Appointment appointment = new Appointment();
appointment.getBeginTimeString();
}
@Test
public void initiallyDescriptionIsNull() {
Appointment appointment = new Appointment();
assertThat(appointment.getDescription(), is(nullValue()));
}
@Test
public void initiallyGetBeginTimeReturnsNull() {
Appointment appointment = new Appointment();
assertThat(appointment.getBeginTime(), is(nullValue()));
}
@Test
public void initiallyGetEndTimeReturnsNull() {
Appointment appointment = new Appointment();
assertThat(appointment.getEndTime(), is(nullValue()));
}
}
| package edu.pdx.cs410J.chances;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* Unit tests for the {@link Appointment} class.
*/
public class AppointmentTest {
@Test
public void getBeginTimeStringNeedsToBeImplemented() {
Appointment appointment = new Appointment();
appointment.getBeginTimeString();
}
@Test
public void initiallyAllAppointmentsHaveNullDescription() {
Appointment appointment = new Appointment();
assertThat(appointment.getDescription(), is(nullValue()));
}
@Test
public void initiallyGetBeginTimeReturnsNull() {
Appointment appointment = new Appointment();
assertThat(appointment.getBeginTime(), is(nullValue()));
}
@Test
public void initiallyGetEndTimeReturnsNull() {
Appointment appointment = new Appointment();
assertThat(appointment.getEndTime(), is(nullValue()));
}
}
|
Fix code examples in PHPDoc | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Http\EntryPoint;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/**
* Implement this interface for any classes that will be called to "start"
* the authentication process (see method for more details).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface AuthenticationEntryPointInterface
{
/**
* Returns a response that directs the user to authenticate.
*
* This is called when an anonymous request accesses a resource that
* requires authentication. The job of this method is to return some
* response that "helps" the user start into the authentication process.
*
* Examples:
*
* - For a form login, you might redirect to the login page
*
* return new RedirectResponse('/login');
*
* - For an API token authentication system, you return a 401 response
*
* return new Response('Auth header required', 401);
*
* @param Request $request The request that resulted in an AuthenticationException
* @param AuthenticationException $authException The exception that started the authentication process
*
* @return Response
*/
public function start(Request $request, AuthenticationException $authException = null);
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Http\EntryPoint;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/**
* Implement this interface for any classes that will be called to "start"
* the authentication process (see method for more details).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface AuthenticationEntryPointInterface
{
/**
* Returns a response that directs the user to authenticate.
*
* This is called when an anonymous request accesses a resource that
* requires authentication. The job of this method is to return some
* response that "helps" the user start into the authentication process.
*
* Examples:
* A) For a form login, you might redirect to the login page
* return new RedirectResponse('/login');
* B) For an API token authentication system, you return a 401 response
* return new Response('Auth header required', 401);
*
* @param Request $request The request that resulted in an AuthenticationException
* @param AuthenticationException $authException The exception that started the authentication process
*
* @return Response
*/
public function start(Request $request, AuthenticationException $authException = null);
}
|
Fix small typo with hasWinRT. | // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
define([
'./_Global'
], function baseCoreUtilsInit(_Global) {
"use strict";
var hasWinRT = !!_Global.Windows;
function markSupportedForProcessing(func) {
/// <signature helpKeyword="WinJS.Utilities.markSupportedForProcessing">
/// <summary locid="WinJS.Utilities.markSupportedForProcessing">
/// Marks a function as being compatible with declarative processing, such as WinJS.UI.processAll
/// or WinJS.Binding.processAll.
/// </summary>
/// <param name="func" type="Function" locid="WinJS.Utilities.markSupportedForProcessing_p:func">
/// The function to be marked as compatible with declarative processing.
/// </param>
/// <returns type="Function" locid="WinJS.Utilities.markSupportedForProcessing_returnValue">
/// The input function.
/// </returns>
/// </signature>
func.supportedForProcessing = true;
return func;
}
return {
hasWinRT: hasWinRT,
markSupportedForProcessing: markSupportedForProcessing,
_setImmediate: _Global.setImmediate ? _Global.setImmediate.bind(_Global) : function (handler) {
setTimeout(handler, 0);
}
};
}); | // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
define([
'./_Global'
], function baseCoreUtilsInit(_Global) {
"use strict";
var hasWinRT = !!_Global.Windows;
function markSupportedForProcessing(func) {
/// <signature helpKeyword="WinJS.Utilities.markSupportedForProcessing">
/// <summary locid="WinJS.Utilities.markSupportedForProcessing">
/// Marks a function as being compatible with declarative processing, such as WinJS.UI.processAll
/// or WinJS.Binding.processAll.
/// </summary>
/// <param name="func" type="Function" locid="WinJS.Utilities.markSupportedForProcessing_p:func">
/// The function to be marked as compatible with declarative processing.
/// </param>
/// <returns type="Function" locid="WinJS.Utilities.markSupportedForProcessing_returnValue">
/// The input function.
/// </returns>
/// </signature>
func.supportedForProcessing = true;
return func;
}
return {
_hasWinRT: hasWinRT,
markSupportedForProcessing: markSupportedForProcessing,
_setImmediate: _Global.setImmediate ? _Global.setImmediate.bind(_Global) : function (handler) {
setTimeout(handler, 0);
}
};
}); |
Remove remaining django-mptt 0.7 compatibility code | """
The manager classes.
"""
import django
from django.db.models.query import QuerySet
from mptt.managers import TreeManager
from mptt.querysets import TreeQuerySet
from parler.managers import TranslatableManager, TranslatableQuerySet
class CategoryQuerySet(TranslatableQuerySet, TreeQuerySet):
"""
The Queryset methods for the Category model.
"""
def as_manager(cls):
# Make sure the Django way of creating managers works.
manager = CategoryManager.from_queryset(cls)()
manager._built_with_as_manager = True
return manager
as_manager.queryset_only = True
as_manager = classmethod(as_manager)
class CategoryManager(TreeManager, TranslatableManager):
"""
Base manager class for the categories.
"""
_queryset_class = CategoryQuerySet
| """
The manager classes.
"""
import django
from django.db.models.query import QuerySet
from mptt.managers import TreeManager
from mptt.querysets import TreeQuerySet
from parler.managers import TranslatableManager, TranslatableQuerySet
class CategoryQuerySet(TranslatableQuerySet, TreeQuerySet):
"""
The Queryset methods for the Category model.
"""
def as_manager(cls):
# Make sure the Django way of creating managers works.
manager = CategoryManager.from_queryset(cls)()
manager._built_with_as_manager = True
return manager
as_manager.queryset_only = True
as_manager = classmethod(as_manager)
class CategoryManager(TreeManager, TranslatableManager):
"""
Base manager class for the categories.
"""
_queryset_class = CategoryQuerySet
def get_queryset(self):
# Nasty: In some django-mptt 0.7 versions, TreeManager.get_querset() no longer calls super()
# Hence, redefine get_queryset() here to have the logic from django-parler and django-mptt.
return self._queryset_class(self.model, using=self._db).order_by(
self.tree_id_attr, self.left_attr
)
|
Store date when viewing a month | var calendar;
$(document).ready(function() {
var calendar_container = document.getElementById('calendar');
if (!calendar_container) { return }
calendar = new FullCalendar.Calendar(calendar_container, {
'initialDate': sessionStorage.getItem('lastDate') || null,
'events': 'assignments.json',
'startParam': 'start_date',
'endParam': 'end_date',
'dayCellClassNames': 'day-empty',
'eventDidMount': function(info) {
var date = info.event.start;
while (date < info.event.end) {
var dateString = date.toISOString().split('T')[0];
$('td[data-date=' + dateString + ']').removeClass('day-empty');
date.setDate(date.getDate() + 1);
}
},
'datesSet': function(info) {
var currentStart = info.view.currentStart.toISOString();
sessionStorage.setItem('lastDate', currentStart);
}
});
calendar.render();
$('#calendar').on('click', 'td.day-empty', function() {
window.location = 'assignments/new?date=' + $(this).data('date');
});
});
| var calendar;
$(document).ready(function() {
var calendar_container = document.getElementById('calendar');
if (!calendar_container) { return }
calendar = new FullCalendar.Calendar(calendar_container, {
'events': 'assignments.json',
'startParam': 'start_date',
'endParam': 'end_date',
'dayCellClassNames': 'day-empty',
'eventDidMount': function(info) {
var date = info.event.start;
while (date < info.event.end) {
var dateString = date.toISOString().split('T')[0];
$('td[data-date=' + dateString + ']').removeClass('day-empty');
date.setDate(date.getDate() + 1);
}
}
});
calendar.render();
$('#calendar').on('click', 'td.day-empty', function() {
window.location = 'assignments/new?date=' + $(this).data('date');
});
});
|
Throw error when a field renderer is missing in the Plain JavaScript template. | /**
* Renders a formulate Field.
* @param fieldData The data for the form field to render.
* @param fieldRenderers The associative array of field rendering functions.
* @param fieldValidators The associative array of the field validating functions.
* @param extraOptions Additional options that are less commonly used.
* @returns {HTMLInputElement} The DOM element created by the field renderer.
*/
function renderField(fieldData, fieldRenderers, fieldValidators, extraOptions) {
// Variables.
let renderer, cssClasses, renderResult;
// Get the field rendering function for the current field type.
renderer = fieldRenderers[fieldData.fieldType];
// Create CSS classes to be attached to the DOM element.
cssClasses = [];
cssClasses.push("formulate__field");
cssClasses.push("formulate__field--" + fieldData.fieldType);
// Render the field.
if (!renderer) {
throw Error("Unable to find renderer for field of type " + fieldData.fieldType + ".");
}
renderResult = new renderer(fieldData, fieldValidators, cssClasses, extraOptions);
// Return the rendered field (an object that has information about the rendered field).
return renderResult;
}
// Export the function that renders a field.
module.exports = renderField; | /**
* Renders a formulate Field.
* @param fieldData The data for the form field to render.
* @param fieldRenderers The associative array of field rendering functions.
* @param fieldValidators The associative array of the field validating functions.
* @param extraOptions Additional options that are less commonly used.
* @returns {HTMLInputElement} The DOM element created by the field renderer.
*/
function renderField(fieldData, fieldRenderers, fieldValidators, extraOptions) {
// Variables.
let renderer, cssClasses, renderResult;
// Get the field rendering function for the current field type.
renderer = fieldRenderers[fieldData.fieldType];
// Create CSS classes to be attached to the DOM element.
cssClasses = [];
cssClasses.push("formulate__field");
cssClasses.push("formulate__field--" + fieldData.fieldType);
// Render the field.
renderResult = new renderer(fieldData, fieldValidators, cssClasses, extraOptions);
// Return the rendered field (an object that has information about the rendered field).
return renderResult;
}
// Export the function that renders a field.
module.exports = renderField; |
Add .json suffix to comments API call | module.exports = function getSubjectReplies(reddit,subject){
var opts = {};
if (subject.comment) {
opts.comment = subject.comment;
opts.depth = 2;
opts.context = 0;
} else {
opts.depth = 1;
}
return reddit('/comments/'+subject.article+'.json').get(opts)
.then(function (result) {
var combo = {
article: result[0].data.children[0].data
};
if (subject.comment) {
combo.comment = result[1].data.children[0].data;
combo.replies = combo.comment.replies.data.children;
} else {
combo.replies = result[1].data.children;
}
// TODO: handle morecomments
if (combo.replies[combo.replies.length].kind == 'more')
combo.replies.pop();
// Unwrap replies
for (var i=combo.replies.length; i>=0; i--) {
combo.replies[i] = combo.replies[i].data;
}
return combo;
});
};
| module.exports = function getSubjectReplies(reddit,subject){
var opts = {};
if (subject.comment) {
opts.comment = subject.comment;
opts.depth = 2;
opts.context = 0;
} else {
opts.depth = 1;
}
return reddit('/comments/'+subject.article).get(opts)
.then(function (result) {
var combo = {
article: result[0].data.children[0].data
};
if (subject.comment) {
combo.comment = result[1].data.children[0].data;
combo.replies = combo.comment.replies.data.children;
} else {
combo.replies = result[1].data.children;
}
// TODO: handle morecomments
if (combo.replies[combo.replies.length].kind == 'more')
combo.replies.pop();
// Unwrap replies
for (var i=combo.replies.length; i>=0; i--) {
combo.replies[i] = combo.replies[i].data;
}
return combo;
});
};
|
Allow affiliation address2 and zip to be null for some of our school records | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAffiliationTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('affiliation', function (Blueprint $table) {
$table->increments('id');
$table->string("type");
$table->string("name");
$table->string("address_street");
$table->string("address_street2")->nullable();
$table->string("address_city");
$table->string("address_state");
$table->string("address_zip")->nullable();
$table->string("phone");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('affiliation');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAffiliationTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('affiliation', function (Blueprint $table) {
$table->increments('id');
$table->string("type");
$table->string("name");
$table->string("address_street");
$table->string("address_street2");
$table->string("address_city");
$table->string("address_state");
$table->string("address_zip");
$table->string("phone");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('affiliation');
}
}
|
[fa] Bring back the accidentally removed comment | /* LanguageTool, a natural language style checker
* Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.tokenizers;
import org.junit.Test;
import org.languagetool.TestTools;
import org.languagetool.language.Persian;
public class PersianSRXSentenceTokenizerTest {
private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Persian());
@Test
public void test() {
// NOTE: sentences here need to end with a space character so they
// have correct whitespace when appended:
testSplit("این یک جمله است. ", "حملهٔ بعدی");
}
private void testSplit(String... sentences) {
TestTools.testSplit(sentences, stokenizer);
}
}
| /* LanguageTool, a natural language style checker
* Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.tokenizers;
import org.junit.Test;
import org.languagetool.TestTools;
import org.languagetool.language.Persian;
public class PersianSRXSentenceTokenizerTest {
private final SRXSentenceTokenizer stokenizer = new SRXSentenceTokenizer(new Persian());
@Test
public void test() {
testSplit("این یک جمله است. ", "حملهٔ بعدی");
}
private void testSplit(String... sentences) {
TestTools.testSplit(sentences, stokenizer);
}
}
|
provider/aws: Change the resource name expected as part of sqs queue import test | package aws
import (
"testing"
"fmt"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccAWSSQSQueue_importBasic(t *testing.T) {
resourceName := "aws_sqs_queue.queue"
queueName := fmt.Sprintf("sqs-queue-%s", acctest.RandString(5))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSSQSQueueDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSSQSConfigWithDefaults(queueName),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
| package aws
import (
"testing"
"fmt"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
)
func TestAccAWSSQSQueue_importBasic(t *testing.T) {
resourceName := "aws_sqs_queue.queue-with-defaults"
queueName := fmt.Sprintf("sqs-queue-%s", acctest.RandString(5))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSSQSQueueDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSSQSConfigWithDefaults(queueName),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
//The name is never returned after the initial create of the queue.
//It is part of the URL and can be split down if needed
//ImportStateVerifyIgnore: []string{"name"},
},
},
})
}
|
Add documentation of the new functions |
"""Example of irreversible reaction."""
import os
from chemkinlib.utils import Parser
from chemkinlib.reactions import ReactionSystems
from chemkinlib.config import DATA_DIRECTORY
import numpy
# USER INPUT: reaction (xml) file
xml_filename = os.path.join(DATA_DIRECTORY, "rxnset_long.xml")
parser = Parser.ReactionParser(xml_filename)
# USER INPUTS (concentrations and temperatures)
concentration = ({'H':1, 'H2':1, 'H2O':0, 'H2O2':1, 'HO2':1, 'O':1, "O2":1, "OH":1})
temperature = 1000
# Set up reaction system
rxnsys = ReactionSystems.ReactionSystem(parser.reaction_list,
parser.NASA_poly_coefs,
temperature,
concentration)
#compute the concentration change with timestep
for i in range(10):
dt = 0.001
print(rxnsys.step(dt))
# Compute and sort reaction rates
rxnrates_dict = rxnsys.sort_reaction_rates()
# display reaction rates by species
for k, v in rxnrates_dict.items():
print("d[{0}]/dt : \t {1:e}".format(k, v))
|
"""Example of irreversible reaction."""
import os
from chemkinlib.utils import Parser
from chemkinlib.reactions import ReactionSystems
from chemkinlib.config import DATA_DIRECTORY
import numpy
# USER INPUT: reaction (xml) file
xml_filename = os.path.join(DATA_DIRECTORY, "rxnset_long.xml")
parser = Parser.ReactionParser(xml_filename)
# USER INPUTS (concentrations and temperatures)
concentration = ({'H':1, 'H2':1, 'H2O':1, 'H2O2':1, 'HO2':1, 'O':1, "O2":1, "OH":1})
temperature = 1000
# Set up reaction system
rxnsys = ReactionSystems.ReactionSystem(parser.reaction_list,
parser.NASA_poly_coefs,
temperature,
concentration)
for i in range(10):
dt = 0.001
rxnsys.step(dt)
# Compute and sort reaction rates
rxnrates_dict = rxnsys.sort_reaction_rates()
# display reaction rates by species
for k, v in rxnrates_dict.items():
print("d[{0}]/dt : \t {1:e}".format(k, v))
|
Make inject throw an exception if no injection took place. | package toothpick;
import toothpick.registries.memberinjector.MemberInjectorRegistryLocator;
/**
* Default implementation of an injector.
*/
public final class InjectorImpl implements Injector {
/**
* {@inheritDoc}
*
* <p>
* <em><b>⚠ Warning</b> ⚠ : This implementation needs a proper setup of {@link toothpick.registries.MemberInjectorRegistry} instances
* at the annotation processor level. We will bubble up the hierarchy, starting at class {@code T}. As soon
* as a {@link MemberInjector} is found, we use it to inject the members of {@code obj}. If registries are not find then
* you will observe strange behaviors at runtime : only members defined in super class will be injected.</em>
* </p>
*/
@Override
public <T> void inject(T obj, Scope scope) {
Class<? super T> currentClass = (Class<T>) obj.getClass();
do {
MemberInjector<? super T> memberInjector = MemberInjectorRegistryLocator.getMemberInjector(currentClass);
if (memberInjector != null) {
memberInjector.inject(obj, scope);
return;
} else {
currentClass = currentClass.getSuperclass();
}
} while (currentClass != null);
throw new RuntimeException(String.format("Object %s of class %s could not be injected. Make sure all registries are setup properly.", obj,
obj != null ? obj.getClass() : "(N/A)"));
}
}
| package toothpick;
import toothpick.registries.memberinjector.MemberInjectorRegistryLocator;
/**
* Default implementation of an injector.
*/
public final class InjectorImpl implements Injector {
/**
* {@inheritDoc}
*
* <p>
* <em><b>⚠ Warning</b> ⚠ : This implementation needs a proper setup of {@link toothpick.registries.MemberInjectorRegistry} instances
* at the annotation processor level. We will bubble up the hierarchy, starting at class {@code T}. As soon
* as a {@link MemberInjector} is found, we use it to inject the members of {@code obj}. If registries are not find then
* you will observe strange behaviors at runtime : only members defined in super class will be injected.</em>
* </p>
*/
@Override
public <T> void inject(T obj, Scope scope) {
Class<? super T> currentClass = (Class<T>) obj.getClass();
do {
MemberInjector<? super T> memberInjector = MemberInjectorRegistryLocator.getMemberInjector(currentClass);
if (memberInjector != null) {
memberInjector.inject(obj, scope);
return;
} else {
currentClass = currentClass.getSuperclass();
}
} while (currentClass != null);
}
}
|
Use owner_id if owner_name of playlist doesn't exist | import url from 'url';
import {
formatOpenURL,
parse,
} from 'spotify-uri';
export const getCountryParam = (urlString) => {
const parsed = url.parse(urlString);
if (parsed.query && parsed.query.country) {
return parsed.query.country;
}
return 'us';
};
export const getOwnerName = playlist => playlist.owner_name || playlist.owner_id;
export const getUrl = (playlist) => {
if (!playlist || !playlist.identifier) {
return null;
}
const id = playlist.identifier;
switch (playlist.provider) {
case 'YouTube':
return `https://www.youtube.com/playlist?list=${id}`;
case 'SoundCloud':
return `https://soundcloud.com/playlists/${id}`;
case 'Spotify':
return formatOpenURL(parse(playlist.url));
case 'AppleMusic': {
const country = getCountryParam(playlist.url);
return `http://tools.applemusic.com/embed/v1/playlist/pl.${id}?country=${country}`;
}
default:
return playlist.url;
}
};
| import url from 'url';
import {
formatOpenURL,
parse,
} from 'spotify-uri';
export const getCountryParam = (urlString) => {
const parsed = url.parse(urlString);
if (parsed.query && parsed.query.country) {
return parsed.query.country;
}
return 'us';
};
export const getUrl = (playlist) => {
if (!playlist || !playlist.identifier) {
return null;
}
const id = playlist.identifier;
switch (playlist.provider) {
case 'YouTube':
return `https://www.youtube.com/playlist?list=${id}`;
case 'SoundCloud':
return `https://soundcloud.com/playlists/${id}`;
case 'Spotify':
return formatOpenURL(parse(playlist.url));
case 'AppleMusic': {
const country = getCountryParam(playlist.url);
return `http://tools.applemusic.com/embed/v1/playlist/pl.${id}?country=${country}`;
}
default:
return playlist.url;
}
};
|
Set the version to 0.8.1 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="xutils",
version="0.8.1",
description="A Fragmentary Python Library.",
author="xgfone",
author_email="xgfone@126.com",
maintainer="xgfone",
maintainer_email="xgfone@126.com",
url="https://github.com/xgfone/xutils",
packages=["xutils"],
classifiers=[
"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.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
],
)
| try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="xutils",
version="0.8",
description="A Fragmentary Python Library.",
author="xgfone",
author_email="xgfone@126.com",
maintainer="xgfone",
maintainer_email="xgfone@126.com",
url="https://github.com/xgfone/xutils",
packages=["xutils"],
classifiers=[
"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.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
],
)
|
Exclude Containers From Form Data Set | export function findNearestView(view, selector, predicate) {
if (!view || !selector || view.matches("[data-jsua-app]")) return null;
var matching = view.querySelector(selector);
if (!matching) return findNearestView(view.parentElement, selector, predicate);
if (predicate) {
if (predicate(matching)) return matching;
return findNearestView(view.parentElement, selector, predicate);
}
return matching;
}
export function findNearestAncestorView(view, selector) {
if (!view || !selector || view.matches("[data-jsua-app]")) return null;
var parent = view.parentElement;
if (parent && parent.matches(selector)) return parent;
return findNearestAncestorView(parent, selector);
}
export function buildFormData(submitView) {
var formView = exports.findNearestAncestorView(submitView, "[data-lynx-hints~=form]");
if (!formView) return null;
var formData;
if (submitView.formEnctype === "multipart/form-data") {
formData = new FormData();
} else {
formData = new URLSearchParams();
}
var inputViews = formView.querySelectorAll("[data-lynx-input]:not([data-lynx-hints~=container])");
Array.from(inputViews).forEach(function (inputView) {
var inputValues = inputView.lynxGetValue();
if (!Array.isArray(inputValues)) inputValues = [ inputValues ];
inputValues.forEach(function (inputValue) {
formData.append(inputView.getAttribute("data-lynx-input"), inputValue);
});
});
return formData;
}
| export function findNearestView(view, selector, predicate) {
if (!view || !selector || view.matches("[data-jsua-app]")) return null;
var matching = view.querySelector(selector);
if (!matching) return findNearestView(view.parentElement, selector, predicate);
if (predicate) {
if (predicate(matching)) return matching;
return findNearestView(view.parentElement, selector, predicate);
}
return matching;
}
export function findNearestAncestorView(view, selector) {
if (!view || !selector || view.matches("[data-jsua-app]")) return null;
var parent = view.parentElement;
if (parent && parent.matches(selector)) return parent;
return findNearestAncestorView(parent, selector);
}
export function buildFormData(submitView) {
var formView = exports.findNearestAncestorView(submitView, "[data-lynx-hints~=form]");
if (!formView) return null;
var formData;
if (submitView.formEnctype === "multipart/form-data") {
formData = new FormData();
} else {
formData = new URLSearchParams();
}
var inputViews = formView.querySelectorAll("[data-lynx-input]");
Array.from(inputViews).forEach(function (inputView) {
var inputValues = inputView.lynxGetValue();
if (!Array.isArray(inputValues)) inputValues = [ inputValues ];
inputValues.forEach(function (inputValue) {
formData.append(inputView.getAttribute("data-lynx-input"), inputValue);
});
});
return formData;
}
|
Add missing metadata to suppress warning
Doesn't fix the "503 Backend is unhealthy" error I'm getting from
`python setup.py register`, however. | from __future__ import absolute_import, division, print_function, unicode_literals
from setuptools import setup
setup( name='dependency_injection'
, author='Gittip, LLC'
, author_email='support@gittip.com'
, description="dependency_injection helpers"
, url='https://dependency-injection-py.readthedocs.org'
, version='0.0.0-dev'
, py_modules=['dependency_injection']
, classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication',
'Operating System :: OS Independent',
'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 :: Database :: Front-Ends',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| from __future__ import absolute_import, division, print_function, unicode_literals
from setuptools import setup
setup( name='dependency_injection'
, author='Gittip, LLC'
, description="dependency_injection helpers"
, url='https://dependency-injection-py.readthedocs.org'
, version='0.0.0-dev'
, py_modules=['dependency_injection']
, classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication',
'Operating System :: OS Independent',
'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 :: Database :: Front-Ends',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Fix order for installer API routes | # pylint: disable=C0103
from __future__ import absolute_import
from django.conf.urls import url
from games.views import installers as views
urlpatterns = [
url(r'game/(?P<slug>[\w\-]+)$',
views.GameInstallerList.as_view(),
name='api_game_installer_list'),
url(r'game/(?P<slug>[\w\-]+)/revisions$',
views.GameRevisionListView.as_view(),
name='api_game_revisions_list'),
url(r'(?P<pk>[\d]+)/revisions$',
views.InstallerRevisionListView.as_view(),
name="api_installer_revision_list"),
url(r'revisions/(?P<pk>[\d]+)$',
views.InstallerRevisionDetailView.as_view(),
name="api_installer_revision_detail"),
url(r'(?P<pk>[\d]+)$',
views.InstallerDetailView.as_view(),
name='api_installer_detail'),
url(r'^$',
views.InstallerListView.as_view(),
name='api_installer_list'),
]
| # pylint: disable=C0103
from __future__ import absolute_import
from django.conf.urls import url
from games.views import installers as views
urlpatterns = [
url(r'revisions/(?P<pk>[\d]+)$',
views.InstallerRevisionDetailView.as_view(),
name="api_installer_revision_detail"),
url(r'(?P<pk>[\d]+)/revisions$',
views.InstallerRevisionListView.as_view(),
name="api_installer_revision_list"),
url(r'game/(?P<slug>[\w\-]+)$',
views.GameInstallerList.as_view(),
name='api_game_installer_list'),
url(r'game/(?P<slug>[\w\-]+)/revisions$',
views.GameRevisionListView.as_view(),
name='api_game_revisions_list'),
url(r'(?P<pk>[\d]+)$',
views.InstallerDetailView.as_view(),
name='api_installer_detail'),
url(r'^$',
views.InstallerListView.as_view(),
name='api_installer_list'),
]
|
Fix indentation in example plugin comments | bespoke.plugins.<%= pluginNameCamelized %> = function(deck) {
/*
Interact with the deck
https://github.com/markdalgleish/bespoke.js#deck-instances
*/
deck.next();
deck.prev();
deck.slide(0);
/*
Slide events
https://github.com/markdalgleish/bespoke.js#events
*/
deck.on('activate', function(e) {
console.log('Slide #' + e.index + ' was activated!', e.slide);
});
deck.on('deactivate', function(e) {
console.log('Slide #' + e.index + ' was deactivated!', e.slide);
});
/*
Deck interaction events, return false to cancel
https://github.com/markdalgleish/bespoke.js#deck-interaction-events
*/
deck.on('next', function(e) {
console.log('The next slide is #' + (e.index + 1), deck.slides[e.index + 1]);
});
deck.on('prev', function(e) {
console.log('The previous slide is #' + (e.index - 1), deck.slides[e.index - 1]);
});
deck.on('slide', function(e) {
console.log('The requested slide is #' + e.index, e.slide);
});
};
| bespoke.plugins.<%= pluginNameCamelized %> = function(deck) {
/*
Interact with the deck
https://github.com/markdalgleish/bespoke.js#deck-instances
*/
deck.next();
deck.prev();
deck.slide(0);
/*
Slide events
https://github.com/markdalgleish/bespoke.js#events
*/
deck.on('activate', function(e) {
console.log('Slide #' + e.index + ' was activated!', e.slide);
});
deck.on('deactivate', function(e) {
console.log('Slide #' + e.index + ' was deactivated!', e.slide);
});
/*
Deck interaction events, return false to cancel
https://github.com/markdalgleish/bespoke.js#deck-interaction-events
*/
deck.on('next', function(e) {
console.log('The next slide is #' + (e.index + 1), deck.slides[e.index + 1]);
});
deck.on('prev', function(e) {
console.log('The previous slide is #' + (e.index - 1), deck.slides[e.index - 1]);
});
deck.on('slide', function(e) {
console.log('The requested slide is #' + e.index, e.slide);
});
};
|
Use APP_ENV to determine if you use dev or not
Leaving app_dev.php to ease migration | <?php
use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
if(extension_loaded('apc') && ini_get('apc.enabled')){
// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts with other applications also using APC.
// The Kunstmaan build system does this automatically.
$apcLoader = new ApcClassLoader('sf2', $loader);
$loader->unregister();
$apcLoader->register(true);
}
require_once __DIR__.'/../app/AppKernel.php';
if (getenv('APP_ENV') === 'dev') {
Debug::enable();
$kernel = new AppKernel('dev', true);
} else {
$kernel = new AppKernel('prod', false);
}
$kernel->loadClassCache();
if (getenv('APP_ENV') !== 'dev') {
if (!isset($_SERVER['HTTP_SURROGATE_CAPABILITY']) || false === strpos($_SERVER['HTTP_SURROGATE_CAPABILITY'], 'ESI/1.0')) {
require_once __DIR__.'/../app/AppCache.php';
$kernel = new AppCache($kernel);
}
}
Request::enableHttpMethodParameterOverride();
Request::setTrustedProxies(array('127.0.0.1'));
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\ClassLoader\ApcClassLoader;
use Symfony\Component\HttpFoundation\Request;
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
if(extension_loaded('apc') && ini_get('apc.enabled')){
// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.
$apcLoader = new ApcClassLoader('sf2', $loader);
$loader->unregister();
$apcLoader->register(true);
}
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
if (!isset($_SERVER['HTTP_SURROGATE_CAPABILITY']) || false === strpos($_SERVER['HTTP_SURROGATE_CAPABILITY'], 'ESI/1.0')) {
require_once __DIR__.'/../app/AppCache.php';
$kernel = new AppCache($kernel);
}
// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
//Request::enableHttpMethodParameterOverride();
//Request::setTrustedProxies(array('127.0.0.1'));
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Support messages on search result page | // ==UserScript==
// @name Amazon age-verification autoredirect
// @namespace curipha
// @description Click the "I'm over 18" link automatically at amazon.co.jp.
// @include http://www.amazon.co.jp/*
// @include https://www.amazon.co.jp/*
// @version 0.1.2
// @grant none
// ==/UserScript==
(function() {
var pattern = /black\-curtain\-redirect\.html/;
var t = 0;
var clickit = function(elem) {
var hrefs = elem.getElementsByTagName('a');
for (var a of hrefs) {
if (pattern.test(a.href)) {
location.href = a.href;
return;
}
}
};
var clickit_wrap = function(mr) {
if (t) return;
t = setTimeout(function() {
for (var mre of mr) {
if (mre.target.id !== 'nav_flyout_anchor') continue;
clickit(mre.target);
}
t = 0;
}, 120);
};
clickit(document);
var mo = new MutationObserver(clickit_wrap);
mo.observe(document.getElementById('nav-cross-shop'), { childList: true, subtree: true });
})();
| // ==UserScript==
// @id Amazon age-verification autoredirect
// @name Amazon age-verification autoredirect
// @version 0.0.5
// @namespace curipha
// @author curipha
// @description Automatic click an "I'm over 18." link at amazon.co.jp.
// @include http://www.amazon.co.jp/*
// @run-at document-end
// @grant none
// ==/UserScript==
(function() {
var hrefs = document.getElementsByTagName('a');
for (var a of hrefs) {
if (/black\-curtain\-redirect\.html/.test(a.href)) {
location.href = a.href;
return;
}
}
})();
|
Delete all containers on the Docker daemon before running test | from unittest import TestCase
from docker import Client
from plum import Service
class ServiceTestCase(TestCase):
def setUp(self):
self.client = Client('http://127.0.0.1:4243')
self.client.pull('ubuntu')
for c in self.client.containers(all=True):
self.client.kill(c['Id'])
self.client.remove_container(c['Id'])
self.service = Service(
client=self.client,
image="ubuntu",
command=["/bin/sleep", "300"],
)
def test_up_scale_down(self):
self.assertEqual(len(self.service.containers), 0)
self.service.start()
self.assertEqual(len(self.service.containers), 1)
self.service.start()
self.assertEqual(len(self.service.containers), 1)
self.service.scale(2)
self.assertEqual(len(self.service.containers), 2)
self.service.scale(1)
self.assertEqual(len(self.service.containers), 1)
self.service.stop()
self.assertEqual(len(self.service.containers), 0)
self.service.stop()
self.assertEqual(len(self.service.containers), 0)
| from unittest import TestCase
from docker import Client
from plum import Service
class ServiceTestCase(TestCase):
def setUp(self):
self.client = Client('http://127.0.0.1:4243')
self.client.pull('ubuntu')
for c in self.client.containers():
self.client.kill(c['Id'])
self.service = Service(
client=self.client,
image="ubuntu",
command=["/bin/sleep", "300"],
)
def test_up_scale_down(self):
self.assertEqual(len(self.service.containers), 0)
self.service.start()
self.assertEqual(len(self.service.containers), 1)
self.service.start()
self.assertEqual(len(self.service.containers), 1)
self.service.scale(2)
self.assertEqual(len(self.service.containers), 2)
self.service.scale(1)
self.assertEqual(len(self.service.containers), 1)
self.service.stop()
self.assertEqual(len(self.service.containers), 0)
self.service.stop()
self.assertEqual(len(self.service.containers), 0)
|
KULRICE-1857: Synchronize DTOs with BOs. @Override caused problems | /*
* Copyright 2007 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kim.dto;
/**
* This is the Data Transfer Object (DTO) that is used for our service layer.
*
* This class represents a Principal entity in the system.
*
* @author Kuali Rice Team (kuali-rice@googlegroups.com)
*/
public class PrincipalDTO extends AbstractEntityBaseDTO implements java.security.Principal {
private static final long serialVersionUID = -7894319178912177679L;
private String name;
/**
*
* @see java.security.Principal#getName()
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
| /*
* Copyright 2007 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kim.dto;
/**
* This is the Data Transfer Object (DTO) that is used for our service layer.
*
* This class represents a Principal entity in the system.
*
* @author Kuali Rice Team (kuali-rice@googlegroups.com)
*/
public class PrincipalDTO extends AbstractEntityBaseDTO implements java.security.Principal {
private static final long serialVersionUID = -7894319178912177679L;
private String name;
/**
* This overridden method ...
*
* @see java.security.Principal#getName()
*/
@Override
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
|
Determine the rules that are run matching the context passed into the rules with the package name. Include some more tests. Remove redundant logging classes. | package uk.gov.dvla.services.enquiry;
import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.services.ManagedService;
public interface DriverEnquiry extends ManagedService
{
public static final String DRIVER_URI = "/driver/";
public static final String CUSTOMER_PORTAL = "customer.portal";
public static final String MIB = "mib";
public static final String DLN_PARAM = "dln";
public static final String ENQUIRY_ID_PARAM = "id";
public static final String FORENAME_PARAM = "fn";
public static final String SURNAME_PARAM = "sn";
public static final String DOB_PARAM = "d";
public static final String GENDER_PARAM = "g";
public static final String POSTCODE_PARAM = "p";
public Driver get(String dln);
public Driver get(Person person);
public Driver get(String forename, String surname, String dob,
String gender, String postCode);
}
| package uk.gov.dvla.services.enquiry;
import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.services.ManagedService;
public interface DriverEnquiry extends ManagedService
{
public static final String DRIVER_URI = "/driver/";
public static final String CUSTOMER_PORTAL = "customer_portal";
public static final String MIB = "mib";
public static final String DLN_PARAM = "dln";
public static final String ENQUIRY_ID_PARAM = "id";
public static final String FORENAME_PARAM = "fn";
public static final String SURNAME_PARAM = "sn";
public static final String DOB_PARAM = "d";
public static final String GENDER_PARAM = "g";
public static final String POSTCODE_PARAM = "p";
public Driver get(String dln);
public Driver get(Person person);
public Driver get(String forename, String surname, String dob,
String gender, String postCode);
}
|
Revert "Revert "added accessor for getting marker ID""
This reverts commit 8774cdfa1cf8706b06ef2eeedb183576fd8b3be0. | L.SmoothMarkerTransition = L.Marker.extend({
options: {
traverseTime: 1000,
clickable: false,
markerID: ''
},
initialize: function (latlngs, options) {
L.Marker.prototype.initialize.call(this, latlngs, options);
},
transition: function(latlngs) {
if (L.DomUtil.TRANSITION) {
if (this._icon) { this._icon.style[L.DomUtil.TRANSITION] = ('all ' + this.options.traverseTime + 'ms linear'); }
if (this._shadow) { this._shadow.style[L.DomUtil.TRANSITION] = 'all ' + this.options.traverseTime + 'ms linear'; }
}
// Move to the next position
this.setLatLng(latlngs);
},
getMarkerID: function(){
return this.options.markerID;
}
});
L.smoothMarkerTransition = function (latlngs, options) {
return new L.smoothMarkerTransition(latlngs, options);
};
| L.SmoothMarkerTransition = L.Marker.extend({
options: {
traverseTime: 1000,
clickable: false
},
initialize: function (latlngs, options) {
L.Marker.prototype.initialize.call(this, latlngs, options);
},
transition: function(latlngs) {
if (L.DomUtil.TRANSITION) {
if (this._icon) { this._icon.style[L.DomUtil.TRANSITION] = ('all ' + this.options.traverseTime + 'ms linear'); }
if (this._shadow) { this._shadow.style[L.DomUtil.TRANSITION] = 'all ' + this.options.traverseTime + 'ms linear'; }
}
// Move to the next position
this.setLatLng(latlngs);
}
});
L.smoothMarkerTransition = function (latlngs, options) {
return new L.smoothMarkerTransition(latlngs, options);
};
|
Remove duplicate word "searchable" in class Javadoc. | package uk.ac.ebi.quickgo.annotation.service.search;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields;
import uk.ac.ebi.quickgo.common.SearchableDocumentFields;
import uk.ac.ebi.quickgo.rest.search.SearchableField;
import java.util.stream.Stream;
import org.springframework.stereotype.Component;
/**
* Checks if a given field is searchable.
*
* @author Ricardo Antunes
*/
@Component
public class AnnotationSearchableField implements SearchableField, SearchableDocumentFields {
@Override public boolean isDocumentSearchable(String field) {
return AnnotationFields.Searchable.isSearchable(field);
}
@Override public Stream<String> searchableDocumentFields() {
return AnnotationFields.Searchable.searchableFields().stream();
}
@Override public boolean isSearchable(String field) {
return AnnotationFields.Searchable.isSearchable(field);
}
}
| package uk.ac.ebi.quickgo.annotation.service.search;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields;
import uk.ac.ebi.quickgo.common.SearchableDocumentFields;
import uk.ac.ebi.quickgo.rest.search.SearchableField;
import java.util.stream.Stream;
import org.springframework.stereotype.Component;
/**
* Checks if a given field is searchable searchable.
*
* @author Ricardo Antunes
*/
@Component
public class AnnotationSearchableField implements SearchableField, SearchableDocumentFields {
@Override public boolean isDocumentSearchable(String field) {
return AnnotationFields.Searchable.isSearchable(field);
}
@Override public Stream<String> searchableDocumentFields() {
return AnnotationFields.Searchable.searchableFields().stream();
}
@Override public boolean isSearchable(String field) {
return AnnotationFields.Searchable.isSearchable(field);
}
}
|
Change default location of local NVD | package main
import (
"fmt"
"github.com/docopt/docopt-go"
)
func main() {
usage := `Usage: nvd-search [-c CVE | -k KEY] [-v VENDOR] [-p PRODUCT] [-n NVD]
Options:
-h --help show this
-c CVE --cve CVE CVE-ID of the vulnerability [default: ]
-k KEY --key KEY keyword search [default: ]
-v VENDOR --vendor VENDOR CPE vendor name [default: ]
-p PRODUCT --product PRODUCT CPE product name [default: ]
-n NVD --nvd NVD Location of the local NVD [default: ~/.config/nvd-cli/db]
`
args, _ := docopt.Parse(usage, nil, true, "nvd-search 0.1", false)
fmt.Println(args)
}
| package main
import (
"fmt"
"github.com/docopt/docopt-go"
)
func main() {
usage := `Usage: nvd-search [-c CVE | -k KEY] [-v VENDOR] [-p PRODUCT] [-n NVD]
Options:
-h --help show this
-c CVE --cve CVE CVE-ID of the vulnerability [default: ]
-k KEY --key KEY keyword search [default: ]
-v VENDOR --vendor VENDOR CPE vendor name [default: ]
-p PRODUCT --product PRODUCT CPE product name [default: ]
-n NVD --nvd NVD Location of the local NVD [default: ./nvd]
`
args, _ := docopt.Parse(usage, nil, true, "nvd-search 0.1", false)
fmt.Println(args)
}
|
Simplify the repo param as review comment | // Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Install Ubuntu',
injectableName: 'Task.Os.Install.Ubuntu',
implementsTask: 'Task.Base.Os.Install',
options: {
osType: 'linux', //readonly options, should avoid change it
profile: 'install-ubuntu.ipxe',
hostname: 'localhost',
comport: 'ttyS0',
domain: 'rackhd',
completionUri: 'renasar-ansible.pub',
version: 'trusty',
repo: '{{api.server}}/ubuntu',
rootPassword: "RackHDRocks!",
rootSshKey: null,
users: [],
networkDevices: [],
dnsServers: [],
installDisk: null,
kvm: false
},
properties: {
os: {
linux: {
distribution: 'ubuntu'
}
}
}
};
| // Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Install Ubuntu',
injectableName: 'Task.Os.Install.Ubuntu',
implementsTask: 'Task.Base.Os.Install',
options: {
osType: 'linux', //readonly options, should avoid change it
profile: 'install-ubuntu.ipxe',
hostname: 'localhost',
comport: 'ttyS0',
domain: 'rackhd',
completionUri: 'renasar-ansible.pub',
version: 'trusty',
repo: '{{api.server}}/ubuntu/dists/{{options.version}}/main/installer-amd64/current/images/netboot/ubuntu-installer/amd64', // jshint ignore:line
rootPassword: "RackHDRocks!",
rootSshKey: null,
users: [],
networkDevices: [],
dnsServers: [],
installDisk: null,
kvm: false
},
properties: {
os: {
linux: {
distribution: 'ubuntu'
}
}
}
};
|
Fix grovepi import in sensor driver | """
Class for communicating with the GrovePi ultrasonic ranger.
Here we treat it as a binary sensor.
"""
import logging
logging.basicConfig()
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.getLevelName('INFO'))
try:
from grovepi import ultrasonicRead
except ImportError:
LOGGER.warning("GrovePi lib unavailable. Using dummy.")
from drivers.dummy_grovepi_interface import ultrasonicRead
class GrovePiUltrasonicRangerBinary:
"""A module to read from the GrovePi Ultrasonic as a binary sensor."""
def __init__(self, port, binary_threshold):
"""Create a GrovePi Ultrasonic Ranger (Binary) driver module."""
self.port = int(port)
self.binary_threshold = binary_threshold
print(f"Setting up GrovePi Ultrasonic Ranger (Binary) on port {port}")
def is_high(self):
"""HIGH, meaning "not seeing something"."""
# to match the old GPIO sensors, we'll make this sensor active low
# False output means object detected
# True output means no object detected
return ultrasonicRead(self.port) > self.binary_threshold
| """
Class for communicating with the GrovePi ultrasonic ranger.
Here we treat it as a binary sensor.
"""
import logging
logging.basicConfig()
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.getLevelName('INFO'))
try:
from GrovePi.Software.Python.grovepi import ultrasonicRead
except ImportError:
LOGGER.warning("GrovePi lib unavailable. Using dummy.")
from drivers.dummy_grovepi_interface import ultrasonicRead
class GrovePiUltrasonicRangerBinary:
"""A module to read from the GrovePi Ultrasonic as a binary sensor."""
def __init__(self, port, binary_threshold):
"""Create a GrovePi Ultrasonic Ranger (Binary) driver module."""
self.port = int(port)
self.binary_threshold = binary_threshold
print(f"Setting up GrovePi Ultrasonic Ranger (Binary) on port {port}")
def is_high(self):
"""HIGH, meaning "not seeing something"."""
# to match the old GPIO sensors, we'll make this sensor active low
# False output means object detected
# True output means no object detected
return ultrasonicRead(self.port) > self.binary_threshold
|
Write test helper for testing lexer | package edn
import . "testing"
func assertLexerYieldsCorrectTokens(
t *T,
source string,
types []tokenType,
values []string) {
tokens := make([]token, 0)
for token := range Lex(source).tokens {
tokens = append(tokens, token)
}
if len(tokens) != len(types) {
t.Errorf("Got %d tokens, expecting %d", len(tokens), len(types))
}
for i, actual := range(tokens) {
expected := token{
kind: types[i],
value: values[i],
}
if actual != expected {
t.Errorf("Expecting %#v; actual %#v", expected, actual)
}
}
}
func tokens(tokens ...tokenType) []tokenType {
return tokens
}
func values(values ...string) []string {
return values
}
func TestEmptyGivesOnlyEOF(t *T) {
assertLexerYieldsCorrectTokens(t,
"",
tokens(tEOF),
values(""))
}
func TestOpenCloseParens(t *T) {
assertLexerYieldsCorrectTokens(t,
"()",
tokens(tOpenParen, tCloseParen, tEOF),
values("(", ")", ""))
}
| package edn
import . "testing"
func TestEmptyGivesOnlyEOF(t *T) {
lexer := Lex("")
token, _ := lexer.Next()
if token.kind != tEOF {
t.Error("expecting EOF")
}
}
// I suspect there's a potential race condition here first since
// the lexer is in a different thread. If `Next()` is called while the lexer
// is still in its main `for{}` loop, `done` could still be `false`
func TestEmptyIsDoneAfterFirstToken(t *T) {
lexer := Lex("")
_, done := lexer.Next()
if !done {
t.Error("expecting no more tokens")
}
}
func TestOpenCloseParens(t *T) {
lexer := Lex("()")
token, _ := lexer.Next()
if token.kind != tOpenParen || token.value != "(" {
t.Error("expecting open parenthesis")
}
token, _ = lexer.Next()
if token.kind != tCloseParen || token.value != ")" {
t.Error("expecting close parenthesis")
}
token, _ = lexer.Next()
if token.kind != tEOF {
t.Error("expecting EOF")
}
}
|
: Create documentation of DataSource Settings
Task-Url: | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "/Cell:" + AdminControl.getCell() + "/"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
dbs = dbs.split('(')
print dbs
for db in dbs.splitlines():
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ) | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "/Cell:" + AdminControl.getCell() + "/"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
dbs = dbs.splitlines()
print dbs
for db in dbs.splitlines():
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ) |
Convert copy_reg test to PyUnit. | import copy_reg
import test_support
import unittest
class C:
pass
class CopyRegTestCase(unittest.TestCase):
def test_class(self):
self.assertRaises(TypeError, copy_reg.pickle,
C, None, None)
def test_noncallable_reduce(self):
self.assertRaises(TypeError, copy_reg.pickle,
type(1), "not a callable")
def test_noncallable_constructor(self):
self.assertRaises(TypeError, copy_reg.pickle,
type(1), int, "not a callable")
test_support.run_unittest(CopyRegTestCase)
| import copy_reg
class C:
pass
try:
copy_reg.pickle(C, None, None)
except TypeError, e:
print "Caught expected TypeError:"
print e
else:
print "Failed to catch expected TypeError when registering a class type."
print
try:
copy_reg.pickle(type(1), "not a callable")
except TypeError, e:
print "Caught expected TypeError:"
print e
else:
print "Failed to catch TypeError " \
"when registering a non-callable reduction function."
print
try:
copy_reg.pickle(type(1), int, "not a callable")
except TypeError, e:
print "Caught expected TypeError:"
print e
else:
print "Failed to catch TypeError " \
"when registering a non-callable constructor."
|
Change old style class defined to new style class definition | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import unicode_literals
class Align(object):
class __AlignData(object):
@property
def align_code(self):
return self.__align_code
@property
def align_string(self):
return self.__align_string
def __init__(self, code, string):
self.__align_code = code
self.__align_string = string
def __repr__(self):
return self.align_string
AUTO = __AlignData(1 << 0, "auto")
LEFT = __AlignData(1 << 1, "left")
RIGHT = __AlignData(1 << 2, "right")
CENTER = __AlignData(1 << 3, "center")
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import unicode_literals
class Align:
class __AlignData(object):
@property
def align_code(self):
return self.__align_code
@property
def align_string(self):
return self.__align_string
def __init__(self, code, string):
self.__align_code = code
self.__align_string = string
def __repr__(self):
return self.align_string
AUTO = __AlignData(1 << 0, "auto")
LEFT = __AlignData(1 << 1, "left")
RIGHT = __AlignData(1 << 2, "right")
CENTER = __AlignData(1 << 3, "center")
|
Add scope to status node | /**
* Copyright 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
module.exports = function(RED) {
"use strict";
function StatusNode(n) {
RED.nodes.createNode(this,n);
var node = this;
this.scope = n.scope;
this.on("input", function(msg) {
this.send(msg);
});
}
RED.nodes.registerType("status",StatusNode);
}
| /**
* Copyright 2015 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
module.exports = function(RED) {
"use strict";
function StatusNode(n) {
RED.nodes.createNode(this,n);
var node = this;
this.on("input", function(msg) {
this.send(msg);
});
}
RED.nodes.registerType("status",StatusNode);
}
|
Disable application views from oauth2-toolkit | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.http import HttpResponse
from django.conf.urls.static import static
from django.contrib.staticfiles import views as static_views
from django.views.defaults import permission_denied
from .api import UserView, GetJWTView
from users.views import LoginView
def show_login(request):
html = "<html><body>"
if request.user.is_authenticated:
html += "%s" % request.user
else:
html += "not logged in"
html += "</body></html>"
return HttpResponse(html)
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^saml2/', include('djangosaml2.urls')),
url(r'^accounts/profile/', show_login),
url(r'^accounts/', include('allauth.urls')),
url(r'^oauth2/applications/', permission_denied),
url(r'^oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')),
url(r'^user/(?P<username>[\w.@+-]+)/?$', UserView.as_view()),
url(r'^user/$', UserView.as_view()),
url(r'^jwt-token/$', GetJWTView.as_view()),
url(r'^login/$', LoginView.as_view()),
)
if settings.DEBUG:
urlpatterns += [url(r'^static/(?P<path>.*)$', static_views.serve)]
| from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.http import HttpResponse
from django.conf.urls.static import static
from django.contrib.staticfiles import views as static_views
from .api import UserView, GetJWTView
from users.views import LoginView
def show_login(request):
html = "<html><body>"
if request.user.is_authenticated:
html += "%s" % request.user
else:
html += "not logged in"
html += "</body></html>"
return HttpResponse(html)
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^saml2/', include('djangosaml2.urls')),
url(r'^accounts/profile/', show_login),
url(r'^accounts/', include('allauth.urls')),
url(r'^oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')),
url(r'^user/(?P<username>[\w.@+-]+)/?$', UserView.as_view()),
url(r'^user/$', UserView.as_view()),
url(r'^jwt-token/$', GetJWTView.as_view()),
url(r'^login/$', LoginView.as_view()),
)
if settings.DEBUG:
urlpatterns += [url(r'^static/(?P<path>.*)$', static_views.serve)]
|
Load first project if only one project | App.Router.map(function () {
this.resource('projects', {path: '/'}, function(){
this.resource('project', {path: '/project/:project_id'}, function(){
this.resource('investigation', {path: 'investigations/:investigation_id'});
});
});
});
App.Router.reopen({
rootURL: '/portal'
})
App.ProjectsRoute = Ember.Route.extend({
model: function () {
return this.store.find('project');
},
afterModel: function(projects, transition) {
if (projects.get('length') === 1) {
this.transitionTo('project', projects.objectAt(0));
}
},
renderTemplate: function() {
this.render('projects', {
outlet: 'off-canvas'
});
}
});
App.ProjectRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('project', params.project_id);
},
renderTemplate: function() {
this.render('investigations', {
outlet: 'main'
});
this.render({
outlet: 'title'
})
}
});
| App.Router.map(function () {
this.resource('projects', {path: '/'}, function(){
this.resource('project', {path: '/project/:project_id'}, function(){
this.resource('investigation', {path: 'investigations/:investigation_id'});
});
});
});
App.Router.reopen({
rootURL: '/portal'
})
App.ProjectsRoute = Ember.Route.extend({
model: function () {
return this.store.find('project');
},
renderTemplate: function() {
this.render('projects', {
outlet: 'off-canvas'
});
}
});
App.ProjectRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('project', params.project_id);
},
renderTemplate: function() {
this.render('investigations', {
outlet: 'main'
});
this.render({
outlet: 'title'
})
}
});
|
Add special method for HTML urls issue with / when using the default hmac method | package tools
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"strings"
"unicode"
"unicode/utf8"
)
func ComputeHmac256(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func ComputeHmac256Html(message string, secret string) string {
t := ComputeHmac256(message, secret)
return strings.Replace(t, "/", "_", -1)
}
func Capitalize(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[n:]
}
func JsonToGolang(in *string) (out string) {
res := strings.Split(*in, "_")
out = ""
for _, s := range res {
out += Capitalize(s)
}
return out
}
func CaseInsensitiveContains(s, substr string) bool {
s, substr = strings.ToUpper(s), strings.ToUpper(substr)
return strings.Contains(s, substr)
}
| package tools
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"strings"
"unicode"
"unicode/utf8"
)
func ComputeHmac256(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func Capitalize(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[n:]
}
func JsonToGolang(in *string) (out string) {
res := strings.Split(*in, "_")
out = ""
for _, s := range res {
out += Capitalize(s)
}
return out
}
func CaseInsensitiveContains(s, substr string) bool {
s, substr = strings.ToUpper(s), strings.ToUpper(substr)
return strings.Contains(s, substr)
}
|
Call up the table header reducer when we receive headers | import apiClient from '../config/apiClient'
import {prefixify} from '../lib/regionUtil'
import resolveQuery from '../lib/resolveQuery'
import {queryResultPresenter} from '../lib/queryResultPresenter'
export const REQUEST_CHART_DATA = 'REQUEST_CHART_DATA'
export const RECEIVE_CHART_DATA = 'RECEIVE_CHART_DATA'
export const RECEIVE_TABLE_HEADERS = 'RECEIVE_TABLE_HEADERS'
export function loadChartData(region, userQuery, chartKind) {
return (dispatch, getState) => {
dispatch({
type: REQUEST_CHART_DATA,
query: userQuery
})
apiClient.getHeaderGroups(userQuery.tableName).then(headerGroups => {
dispatch({
type: RECEIVE_TABLE_HEADERS,
headers: headerGroups,
tableName: userQuery.tableName
})
const newQuery = Object.assign({}, userQuery, {region: prefixify(region)})
const resolvedQuery = resolveQuery(region, newQuery, headerGroups)
apiClient.query(resolvedQuery).then(queryResults => {
const data = {}
data[userQuery.tableName] = queryResultPresenter(resolvedQuery, queryResults, {chartKind})
dispatch({
type: RECEIVE_CHART_DATA,
userQuery: userQuery,
query: resolvedQuery,
data: data
})
})
})
}
}
| import apiClient from '../config/apiClient'
import {prefixify} from '../lib/regionUtil'
import resolveQuery from '../lib/resolveQuery'
import {queryResultPresenter} from '../lib/queryResultPresenter'
export const REQUEST_CHART_DATA = 'REQUEST_CHART_DATA'
export const RECEIVE_CHART_DATA = 'RECEIVE_CHART_DATA'
export function loadChartData(region, userQuery, chartKind) {
return (dispatch, getState) => {
dispatch({
type: REQUEST_CHART_DATA,
query: userQuery
})
apiClient.getHeaderGroups(userQuery.tableName).then(headerGroups => {
const newQuery = Object.assign({}, userQuery, {region: prefixify(region)})
const resolvedQuery = resolveQuery(region, newQuery, headerGroups)
apiClient.query(resolvedQuery).then(queryResults => {
const data = {}
data[userQuery.tableName] = queryResultPresenter(resolvedQuery, queryResults, {chartKind})
dispatch({
type: RECEIVE_CHART_DATA,
userQuery: userQuery,
query: resolvedQuery,
data: data
})
})
})
}
}
|
Add trace ID to footer of member UI | <footer class="footer">
<div class="container" style="overflow: hidden; height: 100%">
<div class="d-flex justify-content-between">
<div>
<p class="text-muted text-right"><a class="text-muted" href="https://github.com/RoboJackets/apiary">Made with ♥ by RoboJackets</a> • <a class="text-muted" href="/privacy">Privacy Policy</a></p>
</div>
<div>
<p>
<a class="text-muted text-left" target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSelERsYq3gLmHbWvVCWha5iCU8z3r9VYC0hCN4ArLpMAiysaQ/viewform?entry.1338203640={{ $request->fullUrl()}}">Make a Wish</a>
@if(\Sentry\Laravel\Integration::currentTracingSpan() !== null)
@if(auth()->user()->hasRole('admin'))
• <a class="text-muted" href="https://sentry.io/organizations/robojackets/performance/trace/{{ \Sentry\Laravel\Integration::currentTracingSpan()->getTraceId() }}">Trace ID: {{ \Sentry\Laravel\Integration::currentTracingSpan()->getTraceId() }}</a>
@else
• <a class="text-muted" href="#">Trace ID: {{ \Sentry\Laravel\Integration::currentTracingSpan()->getTraceId() }}</a>
@endif
@endif
</p>
</div>
</div>
</div>
</footer>
| <footer class="footer">
<div class="container" style="overflow: hidden; height: 100%">
<div class="d-flex justify-content-between">
<div>
<p class="text-muted text-right"><a class="text-muted" href="https://github.com/RoboJackets/apiary">Made with ♥ by RoboJackets</a> • <a class="text-muted" href="/privacy">Privacy Policy</a></p>
</div>
<div>
<a class="text-muted text-left" target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSelERsYq3gLmHbWvVCWha5iCU8z3r9VYC0hCN4ArLpMAiysaQ/viewform?entry.1338203640={{ $request->fullUrl()}}">Make a Wish</a>
</div>
</div>
</div>
</footer> |
Use absolute path for lua binary in tests | import os
import subprocess
from pylua.tests.helpers import test_file
class TestCompiled(object):
"""
Tests compiled binary
"""
PYLUA_BIN = os.path.join(os.path.dirname(os.path.abspath(__file__)), ('../../bin/pylua'))
def test_addition(self, capsys):
f = test_file(src="""
-- short add
x = 10
y = 5
z = y + y + x
print(z)
print(z+y)
--a = 100+y
lx = 1234567890
ly = 99999999
print(lx+ly)
--print(lx+1234567890)
""", suffix=".l"
)
out = subprocess.check_output([TestCompiled.PYLUA_BIN, f.name])
assert out == "20.000000\n25.000000\n1334567889.000000\n"
| import os
import subprocess
from pylua.tests.helpers import test_file
class TestCompiled(object):
"""
Tests compiled binary
"""
def test_addition(self, capsys):
f = test_file(src="""
-- short add
x = 10
y = 5
z = y + y + x
print(z)
print(z+y)
--a = 100+y
lx = 1234567890
ly = 99999999
print(lx+ly)
--print(lx+1234567890)
""", suffix=".l"
)
out = subprocess.check_output(['bin/pylua', f.name])
assert out == "20.000000\n25.000000\n1334567889.000000\n"
|
Add comments
Comment out test sections of the work | // Back-end
// Front-end
$(document).ready(function () {
// Make about section clickable and open about overlay
$(".about").on('click', function (event) {
event.preventDefault();
$('.overlay').addClass('open');
// Test
// console.log("open");
});
// Close the about overlay
$('.closeNav').on('click', function (event) {
event.preventDefault();
$('.overlay').removeClass('open');
});
// Navigate to play console
$('form.player').submit( function (event) {
event.preventDefault();
window.location.assign("play.html");
});
// Click the start button for the timer to start
$('#start').click(function (event) {
event.preventDefault();
var min = 0;
var sec = 30;
var myVar = setInterval( function() { countDownTimer() } ,1000 );
function countDownTimer() {
var displayCountdown = $('.timer').text( min +" : " + sec );
sec--;
if(sec === -1) {
clearInterval(myVar);
};
};
});
});
| // Back-end
// Front-end
$(document).ready(function () {
// Make about section clickable and open about overlay
$(".about").on('click', function (event) {
event.preventDefault();
$('.overlay').addClass('open');
// Test
// console.log("open");
});
// Close the about overlay
$('.closeNav').on('click', function (event) {
event.preventDefault();
$('.overlay').removeClass('open');
});
// Store and Display player name in the console
$('form.player').submit( function (event) {
event.preventDefault();
// Navigate to play console
window.location.assign("play.html");
});
// Click the start button for the timer to start
$('#start').click(function (event) {
event.preventDefault();
var min = 0;
var sec = 30;
var myVar = setInterval( function() { countDownTimer() } ,1000 );
function countDownTimer() {
var displayCountdown = $('.timer').text( min +" : " + sec );
sec--;
if(sec === -1) {
clearInterval(myVar);
};
};
});
});
|
Remove spaces at the end of lines. | # -*- coding: utf-8 -*-
# Copyright (C) 2009-2010, Luis Pedro Coelho <lpc@cmu.edu>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# 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.
from __future__ import division
import numpy as np
| # -*- coding: utf-8 -*-
# Copyright (C) 2009-2010, Luis Pedro Coelho <lpc@cmu.edu>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# 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.
from __future__ import division
import numpy as np
|
Replace double quotes with single ones | """Test the native server."""
import pytest
from requests_toolbelt import sessions
import cherrypy._cpnative_server
pytestmark = pytest.mark.skipif(
'sys.platform == "win32"',
reason='tests fail on Windows',
)
@pytest.fixture
def cp_native_server(request):
"""A native server."""
class Root(object):
@cherrypy.expose
def index(self):
return 'Hello World!'
cls = cherrypy._cpnative_server.CPHTTPServer
cherrypy.server.httpserver = cls(cherrypy.server)
cherrypy.tree.mount(Root(), '/')
cherrypy.engine.start()
request.addfinalizer(cherrypy.engine.stop)
url = 'http://localhost:{cherrypy.server.socket_port}'.format(**globals())
return sessions.BaseUrlSession(url)
def test_basic_request(cp_native_server):
"""A request to a native server should succeed."""
cp_native_server.get('/')
| """Test the native server."""
import pytest
from requests_toolbelt import sessions
import cherrypy._cpnative_server
pytestmark = pytest.mark.skipif(
'sys.platform == "win32"',
reason="tests fail on Windows",
)
@pytest.fixture
def cp_native_server(request):
"""A native server."""
class Root(object):
@cherrypy.expose
def index(self):
return 'Hello World!'
cls = cherrypy._cpnative_server.CPHTTPServer
cherrypy.server.httpserver = cls(cherrypy.server)
cherrypy.tree.mount(Root(), '/')
cherrypy.engine.start()
request.addfinalizer(cherrypy.engine.stop)
url = 'http://localhost:{cherrypy.server.socket_port}'.format(**globals())
return sessions.BaseUrlSession(url)
def test_basic_request(cp_native_server):
"""A request to a native server should succeed."""
cp_native_server.get('/')
|
Add stub code for the mapping between digits and the alphabet | /* Implement a URL shortening algorithm in GoLang based on a tutorial
on Stack Overflow */
package main
import (
"fmt"
)
/* Reverse an array of digits. Implemented natively for now, although
there might be an in-built library function that does this already */
func reverse(digits []uint16) (reversed []uint16) {
for i := len(digits) - 1; i >= 0; i-- {
reversed = append(reversed, digits[i])
}
return
}
/* Declare the return array in the signature itself. The function
converts between bases and reverses the result before returning it */
func convert(key, alphabetSize uint16) (digits []uint16){
for num := key; num > 0; num = num / alphabetSize {
remainder := num % alphabetSize
digits = append(digits, remainder)
}
return reverse(digits)
}
/* Map the indices obtained from the convert and reverse functions
above into our alphabet. The alphabet is a-zA-Z0-9 */
func mapToAlphabet(digits []uint16, alphabetMap map[uint16]string) string {
var shortUrl string
for _, digit := range digits {
shortUrl += alphabetMap[digit]
fmt.Println(digit)
}
return shortUrl
}
func main() {
fmt.Println("Starting the URL shortening procedure")
const key uint16 = 125
const alphabetSize uint16 = 62
var alphabetMap map[uint16]string= make(map[uint16]string, alphabetSize)
fmt.Println("Converted 125_10 to X_62,", convert(key, alphabetSize))
fmt.Println(mapToAlphabet(convert(key, alphabetSize), alphabetMap))
}
| package main
import (
"fmt"
)
/* Reverse an array of digits. Implemented natively for now, although
there might be an in-built library function that does this already */
func reverse(digits []uint16) (reversed []uint16) {
for i := len(digits) - 1; i >= 0; i-- {
reversed = append(reversed, digits[i])
}
return
}
/* Declare the return array in the signature itself. The function
converts between bases and reverses the result before returning it */
func convert(key, alphabetSize uint16) (digits []uint16){
for num := key; num > 0; num = num / alphabetSize {
remainder := num % alphabetSize
digits = append(digits, remainder)
}
return reverse(digits)
}
func main() {
fmt.Println("Starting the URL shortening procedure")
const key uint16 = 125
const alphabetSize uint16 = 62
fmt.Println("Converted 125_10 to X_62,", convert(key, alphabetSize))
}
|
Use helper to print whitespace characters with encodings | package org.spoofax.jsglr2.parser;
import org.metaborg.parsetable.characterclasses.CharacterClassFactory;
import org.spoofax.jsglr2.parser.result.ParseFailureCause;
public class ParseException extends Exception {
private static final long serialVersionUID = 5070826083429554841L;
public ParseException(ParseFailureCause.Type failureType, Position position, Integer character) {
super(message(failureType, position, character));
}
private static String message(ParseFailureCause.Type failureType, Position position, Integer character) {
StringBuilder message = new StringBuilder();
message.append(failureType.message);
if(position != null)
message.append(
" at offset " + position.offset + "(line " + position.line + ", column " + position.column + ")");
if(character != null)
message.append(" at character " + CharacterClassFactory.intToString(character));
return message.toString();
}
}
| package org.spoofax.jsglr2.parser;
import org.spoofax.jsglr2.parser.result.ParseFailureCause;
public class ParseException extends Exception {
private static final long serialVersionUID = 5070826083429554841L;
public ParseException(ParseFailureCause.Type failureType, Position position, Integer character) {
super(message(failureType, position, character));
}
private static String message(ParseFailureCause.Type failureType, Position position, Integer character) {
StringBuilder message = new StringBuilder();
message.append(failureType.message);
if(position != null)
message.append(
" at offset " + position.offset + "(line " + position.line + ", column " + position.column + ")");
if(character != null)
message.append(" at character " + new String(Character.toChars(character)));
return message.toString();
}
}
|
Correct order for post hooks | 'use strict';
var _ = require('lodash');
var themeFunctions = require('theme/functions') || {};
var config = require('config');
var applyHooks = function (posts, functionArray) {
var posts = posts;
functionArray.forEach(function(callback){
posts = callback(posts);
console.log('posts after!!!!!!', posts);
});
return posts;
}
var getFunctions = function (hookName) {
var functions = [];
if (themeFunctions[hookName]) {
functions.push(themeFunctions[hookName]);
}
// if (config.plugins) {
// _.each(config.plugins, function (pluginName) {
// var plugin = require(pluginName);
// if(plugin && plugin.functions && plugin.functions[hookName]) {
// functions.push(plugin.functions[hookName]);
// }
// });
// }
if (config.site.functions && config.site.functions[hookName]) {
functions.push(config.site.functions[hookName]);
}
return functions;
}
module.exports = {
preProcessPosts: function (posts) {
return applyHooks(posts, getFunctions('preProcessPosts'));
},
postProcessPosts: function (posts) {
return applyHooks(posts, getFunctions('postProcessPosts'));
}
}
| 'use strict';
var _ = require('lodash');
var themeFunctions = require('theme/functions') || {};
var config = require('config');
var applyHooks = function (posts, functionArray) {
var posts = posts;
functionArray.forEach(function(callback){
posts = callback(posts);
console.log('posts after!!!!!!', posts);
});
return posts;
}
var getFunctions = function (hookName) {
var functions = [];
if (themeFunctions[hookName]) {
functions.push(themeFunctions[hookName]);
}
if (config.site.functions && config.site.functions[hookName]) {
functions.push(config.site.functions[hookName]);
}
// if (config.plugins) {
// _.each(config.plugins, function (pluginName) {
// var plugin = require(pluginName);
// if(plugin && plugin.functions && plugin.functions[hookName]) {
// functions.push(plugin.functions[hookName]);
// }
// });
// }
return functions;
}
module.exports = {
preProcessPosts: function (posts) {
return applyHooks(posts, getFunctions('preProcessPosts'));
},
postProcessPosts: function (posts) {
return applyHooks(posts, getFunctions('postProcessPosts'));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.