text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Enable KeepAlives and set timeout in http transport.
|
package s3gof3r
import (
"net"
"net/http"
"time"
)
type deadlineConn struct {
Timeout time.Duration
net.Conn
}
func (c *deadlineConn) Read(b []byte) (n int, err error) {
if err = c.Conn.SetDeadline(time.Now().Add(c.Timeout)); err != nil {
return
}
return c.Conn.Read(b)
}
func (c *deadlineConn) Write(b []byte) (n int, err error) {
if err = c.Conn.SetDeadline(time.Now().Add(c.Timeout)); err != nil {
return
}
return c.Conn.Write(b)
}
func ClientWithTimeout(timeout time.Duration) *http.Client {
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: func(netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout(netw, addr, timeout)
if err != nil {
return nil, err
}
if tc, ok := c.(*net.TCPConn); ok {
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(timeout)
}
return &deadlineConn{timeout, c}, nil
},
ResponseHeaderTimeout: timeout,
MaxIdleConnsPerHost: 20,
}
return &http.Client{Transport: transport}
}
|
package s3gof3r
import (
"net"
"net/http"
"time"
)
type deadlineConn struct {
Timeout time.Duration
net.Conn
}
func (c *deadlineConn) Read(b []byte) (n int, err error) {
if err = c.Conn.SetDeadline(time.Now().Add(c.Timeout)); err != nil {
return
}
return c.Conn.Read(b)
}
func (c *deadlineConn) Write(b []byte) (n int, err error) {
if err = c.Conn.SetDeadline(time.Now().Add(c.Timeout)); err != nil {
return
}
return c.Conn.Write(b)
}
func ClientWithTimeout(timeout time.Duration) *http.Client {
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: func(netw, addr string) (net.Conn, error) {
c, err := net.DialTimeout(netw, addr, timeout)
if err != nil {
return nil, err
}
return &deadlineConn{timeout, c}, nil
},
ResponseHeaderTimeout: timeout,
}
return &http.Client{Transport: transport}
}
|
Add the new timeline fields to the javascript that helps with entering dates.
|
/* Copyright 2013 the Melange authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
melange.templates.inherit(
function (_self, context) {
var config = {
changeMonth: true,
changeYear: false,
dateFormat: "yy-mm-dd",
showButtonPanel: true
};
var fields_to_enhance = [
"#program_start",
"#program_end",
"#accepted_organization_announced_deadline",
"#student_signup_start",
"#student_signup_end",
"#application_review_deadline",
"#student_application_matched_deadline",
"#accepted_students_announced_deadline",
"#form_submission_start",
"#bonding_start",
"#bonding_end",
"#coding_start",
"#coding_end",
"#suggested_coding_deadline",
"#mentor_summit_start",
"#mentor_summit_end"
].join(",");
jQuery(fields_to_enhance).datetimepicker(config);
}
);
|
/* Copyright 2013 the Melange authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
melange.templates.inherit(
function (_self, context) {
var config = {
changeMonth: true,
changeYear: false,
dateFormat: "yy-mm-dd",
showButtonPanel: true
};
var fields_to_enhance = [
"#program_start",
"#program_end",
"#accepted_organization_announced_deadline",
"#student_signup_start",
"#student_signup_end",
"#application_review_deadline",
"#student_application_matched_deadline",
"#accepted_students_announced_deadline",
"#form_submission_start"
].join(",");
jQuery(fields_to_enhance).datetimepicker(config);
}
);
|
Change copyright in Apache 2 license to 2013
|
/**
* Copyright © 2011-2013 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.phenotype.util;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
/**
* Provides an SSL certification implementation that claims all certificates
* are valid -- without actually checking them (!).
*
* This is required because, for instance,
* dev.mousephenotype.org has an invalid SSL cert
*
*/
public class CustomizedHostNameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
|
/**
* Copyright © 2011-2012 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.phenotype.util;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class CustomizedHostNameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
|
Fix picking invalid env variable for tests
|
import os
import dj_database_url
import pytest
from django.conf import settings
pytest_plugins = [
"saleor.tests.fixtures",
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
"saleor.graphql.channel.tests.fixtures",
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.graphql.order.tests.benchmark.fixtures",
"saleor.graphql.giftcard.tests.benchmark.fixtures",
"saleor.graphql.webhook.tests.benchmark.fixtures",
"saleor.plugins.webhook.tests.subscription_webhooks.fixtures",
]
if os.environ.get("PYTEST_DB_URL"):
@pytest.fixture(scope="session")
def django_db_setup():
settings.DATABASES = {
settings.DATABASE_CONNECTION_DEFAULT_NAME: dj_database_url.config(
env="PYTEST_DB_URL", conn_max_age=600
),
}
|
import os
import dj_database_url
import pytest
from django.conf import settings
pytest_plugins = [
"saleor.tests.fixtures",
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
"saleor.graphql.channel.tests.fixtures",
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.graphql.order.tests.benchmark.fixtures",
"saleor.graphql.giftcard.tests.benchmark.fixtures",
"saleor.graphql.webhook.tests.benchmark.fixtures",
"saleor.plugins.webhook.tests.subscription_webhooks.fixtures",
]
if os.environ.get("PYTEST_DB_URL"):
@pytest.fixture(scope="session")
def django_db_setup():
settings.DATABASES = {
settings.DATABASE_CONNECTION_DEFAULT_NAME: dj_database_url.config(
default=os.environ.get("PYTEST_DB_URL"), conn_max_age=600
),
}
|
Use headless Firefox for Protractor tests
(see https://github.com/angular/protractor/blob/master/docs/browser-setup.md)
|
'use strict'
exports.config = {
directConnect: true,
allScriptsTimeout: 80000,
specs: [
'test/e2e/*.js'
],
capabilities: {
browserName: 'firefox',
'moz:firefoxOptions': {
args: [ "--headless" ]
}
},
baseUrl: 'http://localhost:3000',
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 80000
},
onPrepare: function () {
var jasmineReporters = require('jasmine-reporters')
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: 'build/reports/e2e_results'
}))
// Get cookie consent popup out of the way
browser.get('/#')
browser.manage().addCookie({ name: 'cookieconsent_status', value: 'dismiss' })
}
}
|
'use strict'
exports.config = {
directConnect: true,
allScriptsTimeout: 80000,
specs: [
'test/e2e/*.js'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://localhost:3000',
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 80000
},
onPrepare: function () {
var jasmineReporters = require('jasmine-reporters')
jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: 'build/reports/e2e_results'
}))
// Get cookie consent popup out of the way
browser.get('/#')
browser.manage().addCookie({ name: 'cookieconsent_status', value: 'dismiss' })
}
}
|
Add a protected $finfo variable for testing.
|
<?php
namespace Estey\EvernoteOCR;
use Finfo;
/**
* File
*
* A simple local file class.
*/
class File
{
/**
* File path.
* @var string
*/
protected $path;
/**
* Finfo.
* @var Finfo
*/
protected $finfo;
/**
* Set the file path.
*
* @param string $path
* @return $this
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get full file path.
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Get the file's mimetype.
*
* @return string
*/
public function getMimetype()
{
if (!$this->finfo) {
$this->finfo = new Finfo(FILEINFO_MIME_TYPE);
}
return $this->finfo->file($this->path);
}
}
|
<?php
namespace Estey\EvernoteOCR;
use Finfo;
/**
* File
*
* A simple local file class.
*/
class File
{
/**
* File path.
* @var string
*/
protected $path;
/**
* Set the file path.
*
* @param string $path
* @return $this
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get full file path.
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Get the file's mimetype.
*
* @return string
*/
public function getMimetype()
{
$finfo = new Finfo(FILEINFO_MIME_TYPE);
return $finfo->file($this->path);
}
}
|
Add builtAssets to webserver-writable dirs
|
#!/usr/bin/env python
"""
Set the file permissions appropriately for deployment. Call with the argument
of the webserver user (e.g. 'www-data') that should have permissions to uploads
and log files.
"""
import os
import sys
import subprocess
server_writable_directories = [
"vendor/solr/apache-solr-4.0.0/example/solr/collection1/data/",
"vendor/solr/apache-solr-4.0.0/example/solr-webapp/",
"lib/dotstorm/assets/dotstorm/uploads/",
"lib/www/assets/group_logos/",
"lib/www/assets/user_icons/",
"builtAssets/",
]
BASE = os.path.join(os.path.dirname(__file__), "..")
def set_permissions(user):
for path in server_writable_directories:
print user, path
if not os.path.exists(path):
os.makedirs(path)
subprocess.check_call(["chown", "-R", user, os.path.join(BASE, path)])
if __name__ == "__main__":
try:
target_user = sys.argv[1]
except IndexError:
print "Missing required parameter `target user`."
print "Usage: set_deploy_permissions.py [username]"
sys.exit(1)
set_permissions(target_user)
|
#!/usr/bin/env python
"""
Set the file permissions appropriately for deployment. Call with the argument
of the webserver user (e.g. 'www-data') that should have permissions to uploads
and log files.
"""
import os
import sys
import subprocess
server_writable_directories = [
"vendor/solr/apache-solr-4.0.0/example/solr/collection1/data/",
"vendor/solr/apache-solr-4.0.0/example/solr-webapp/",
"lib/dotstorm/assets/dotstorm/uploads/",
"lib/www/assets/group_logos/",
"lib/www/assets/user_icons/",
]
BASE = os.path.join(os.path.dirname(__file__), "..")
def set_permissions(user):
for path in server_writable_directories:
print user, path
if not os.path.exists(path):
os.makedirs(path)
subprocess.check_call(["chown", "-R", user, os.path.join(BASE, path)])
if __name__ == "__main__":
try:
target_user = sys.argv[1]
except IndexError:
print "Missing required parameter `target user`."
print "Usage: set_deploy_permissions.py [username]"
sys.exit(1)
set_permissions(target_user)
|
Fix how `HTMLElement.prototype` is set.
|
/**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
/**
* This shim allows elements written in, or compiled to, ES5 to work on native
* implementations of Custom Elements v1. It sets new.target to the value of
* this.constructor so that the native HTMLElement constructor can access the
* current under-construction element's definition.
*/
(function() {
if (
// No Reflect, no classes, no need for shim because native custom elements
// require ES2015 classes or Reflect.
window.Reflect === undefined ||
window.customElements === undefined ||
// The webcomponentsjs custom elements polyfill doesn't require
// ES2015-compatible construction (`super()` or `Reflect.construct`).
window.customElements.hasOwnProperty('polyfillWrapFlushCallback')
) {
return;
}
const BuiltInHTMLElement = HTMLElement;
window.HTMLElement = function() {
return Reflect.construct(BuiltInHTMLElement, [], this.constructor);
};
HTMLElement.prototype = BuiltInHTMLElement.prototype;
HTMLElement.prototype.constructor = HTMLElement;
Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement);
})();
|
/**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
/**
* This shim allows elements written in, or compiled to, ES5 to work on native
* implementations of Custom Elements v1. It sets new.target to the value of
* this.constructor so that the native HTMLElement constructor can access the
* current under-construction element's definition.
*/
(function() {
if (
// No Reflect, no classes, no need for shim because native custom elements
// require ES2015 classes or Reflect.
window.Reflect === undefined ||
window.customElements === undefined ||
// The webcomponentsjs custom elements polyfill doesn't require
// ES2015-compatible construction (`super()` or `Reflect.construct`).
window.customElements.hasOwnProperty('polyfillWrapFlushCallback')
) {
return;
}
const BuiltInHTMLElement = HTMLElement;
window.HTMLElement = function() {
return Reflect.construct(BuiltInHTMLElement, [], this.constructor);
};
Object.setPrototypeOf(HTMLElement.prototype, BuiltInHTMLElement.prototype);
Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement);
})();
|
Add beat 2 video and description
|
module.exports = [
{
"direct": "https://d24kjznqej0s8a.cloudfront.net/2016/encryption_campaign/moz.final.3.emailpartner_1",
"social": "https://d24kjznqej0s8a.cloudfront.net/2016/encryption_campaign/moz.final.2.social_3",
"title": "Privacy Lets You Be You",
"description": "Privacy depends on encryption. Learn more about how it works, why it's essential, and why it's worth protecting.",
"date": "February 08, 2016",
"duration": "0:58",
"poster": "/assets/encrypt-poster-dark-1920x1080.jpg",
"thumbnail": "/assets/thumbnail-beat1.jpg"
},{
"direct": "https://d24kjznqej0s8a.cloudfront.net/2016/encryption_campaign/Mozilla_Encrypt_Beat2_landingpage",
"social": "https://d24kjznqej0s8a.cloudfront.net/2016/encryption_campaign/Mozilla_Encrypt_Beat2_landingpage",
"title": "Meet Encryption",
"description": "Meet Encryption, and learn how she's hard at work to keep you safe online.",
"date": "February 24, 2016",
"duration": "1:16",
"poster": "/assets/video2poster.jpg",
"thumbnail": "/assets/thumbnail-beat2.jpg"
}
]
|
module.exports = [
{
"direct": "https://d24kjznqej0s8a.cloudfront.net/2016/encryption_campaign/moz.final.3.emailpartner_1",
"social": "https://d24kjznqej0s8a.cloudfront.net/2016/encryption_campaign/moz.final.2.social_3",
"title": "Privacy Lets You Be You",
"description": "Privacy depends on encryption. Learn more about how it works, why it's essential, and why it's worth protecting.",
"date": "February 08, 2016",
"duration": "0:58",
"poster": "/assets/encrypt-poster-dark-1920x1080.jpg",
"thumbnail": "/assets/thumbnail-beat1.jpg"
},{
"direct": "http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480",
"social": "http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480",
"title": "Meet Encryption",
"description": "Description of the second video",
"date": "February 24, 2016",
"duration": "0:58",
"poster": "/assets/video2poster.jpg",
"thumbnail": "/assets/thumbnail-beat2.jpg"
}
]
|
Allow use of GoogleMaps plugin without Multilingual support
|
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
from cms.plugins.googlemap.models import GoogleMap
from cms.plugins.googlemap.settings import GOOGLE_MAPS_API_KEY
from django.forms.widgets import Media
class GoogleMapPlugin(CMSPluginBase):
model = GoogleMap
name = _("Google Map")
render_template = "cms/plugins/googlemap.html"
def render(self, context, instance, placeholder):
context.update({
'object':instance,
'placeholder':placeholder,
})
return context
def get_plugin_media(self, request, context, plugin):
if 'GOOGLE_MAPS_API_KEY' in context:
key = context['GOOGLE_MAPS_API_KEY']
else:
key = GOOGLE_MAPS_API_KEY
lang = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE[0:2])
return Media(js = ('http://maps.google.com/maps?file=api&v=2&key=%s&hl=%s' % (key, lang),))
plugin_pool.register_plugin(GoogleMapPlugin)
|
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
from cms.plugins.googlemap.models import GoogleMap
from cms.plugins.googlemap.settings import GOOGLE_MAPS_API_KEY
from cms.plugins.googlemap import settings
from django.forms.widgets import Media
class GoogleMapPlugin(CMSPluginBase):
model = GoogleMap
name = _("Google Map")
render_template = "cms/plugins/googlemap.html"
def render(self, context, instance, placeholder):
context.update({
'object':instance,
'placeholder':placeholder,
})
return context
def get_plugin_media(self, request, context, plugin):
if 'GOOGLE_MAPS_API_KEY' in context:
key = context['GOOGLE_MAPS_API_KEY']
else:
key = GOOGLE_MAPS_API_KEY
return Media(js = ('http://maps.google.com/maps?file=api&v=2&key=%s&hl=%s' % (key, request.LANGUAGE_CODE),))
plugin_pool.register_plugin(GoogleMapPlugin)
|
Update ptvsd version number for 2.1 RTM
|
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
from distutils.core import setup
setup(name='ptvsd',
version='2.1.0',
description='Python Tools for Visual Studio remote debugging server',
license='Apache License 2.0',
author='Microsoft Corporation',
author_email='ptvshelp@microsoft.com',
url='https://pytools.codeplex.com/',
classifiers=[
'Development Status :: 5 - Stable',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License'],
packages=['ptvsd']
)
|
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
from distutils.core import setup
setup(name='ptvsd',
version='2.1.0rc1',
description='Python Tools for Visual Studio remote debugging server',
license='Apache License 2.0',
author='Microsoft Corporation',
author_email='ptvshelp@microsoft.com',
url='https://pytools.codeplex.com/',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License'],
packages=['ptvsd']
)
|
Remove the `cache` prefix from the url
|
var express = require('express'),
app = express(),
compress = require('compression'),
bodyParser = require('body-parser'),
redisHelper = require('./helpers/redis'),
requestHelper = require('./helpers/request');
require('colors');
app.use(bodyParser.json());
app.use(compress());
var port = process.env.PORT || 8181;
var redisClient = redisHelper.getClient(process.env.REDIS_URL || 'redis://localhost:6379');
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();
router.get('/ping', (req, res) => {
'use strict';
res.json({
message: 'hooray! welcome to acidseed!'
});
});
router.get('/', requestHelper.handle.bind(this, redisClient));
router.post('/', requestHelper.handle.bind(this, redisClient));
// START THE SERVER
// =============================================================================
app.listen(port, () => {
'use strict';
console.log(('acidseed: magic is happening on port ' + port).green);
console.log(('Connected to redis: ' + redisClient.address).green);
});
|
var express = require('express'),
app = express(),
compress = require('compression'),
bodyParser = require('body-parser'),
redisHelper = require('./helpers/redis'),
requestHelper = require('./helpers/request');
require('colors');
app.use(bodyParser.json());
app.use(compress());
var port = process.env.PORT || 8181;
var redisClient = redisHelper.getClient(process.env.REDIS_URL || 'redis://localhost:6379');
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();
router.get('/ping', (req, res) => {
'use strict';
res.json({
message: 'hooray! welcome to acidseed!'
});
});
router.get('/', requestHelper.handle.bind(this, redisClient));
router.post('/', requestHelper.handle.bind(this, redisClient));
// REGISTER ROUTES -------------------------------
// All routes will be prefixed with /cache
app.use('/cache', router);
// START THE SERVER
// =============================================================================
app.listen(port, () => {
'use strict';
console.log(('acidseed: magic is happening on port ' + port).green);
console.log(('Connected to redis: ' + redisClient.address).green);
});
|
Add commentary explaining and/or lists
|
from pyparsing import *
from ...constants.math.deff import NUM, FULLNUM
from ...constants.zones.deff import TOP, BOTTOM
from ...constants.verbs.deff import *
from ...mana.deff import color
from ...types.deff import nontype, supertype
from ...functions.deff import delimitedListAnd, delimitedListOr
from decl import *
topnum << (TOP|BOTTOM) + (NUM|FULLNUM)
attacking << ATTACK
blocking << BLOCK
tapped << TAP
untapped << UNTAP
enchanted << ENCHANT
equipped << EQUIP
exiled << EXILE
sacrificed << SACRIFICE
haunted << HAUNT
adjective << (
color
| nontype
| supertype
| topnum
| attacking
| blocking
| tapped
| untapped
| enchanted
| equipped
| exiled
| sacrificed
| haunted
)
# 'and' captures both 'legendary creature' (juxtaposed) and 'black and red' (joined)
# 'or' will capture explicit disjunctions 'black or red'
# but since it will come after the ^, not juxtapositions (taken by 'and')
# so the 'one or more' allows 'legendary black or red'
# to be correctly interpreted as (A and (B or C))
# it's non-intuitive, but it works
# at the same time, it forces us to use ^ instead of |
# or "target artifact, enchantment or land"
# becomes ((A and B) or C)
andadjectives << delimitedListAnd(adjective)
oradjectives << delimitedListOr(adjective)
adjectives << OneOrMore(andadjectives ^ oradjectives)
|
from pyparsing import *
from ...constants.math.deff import NUM, FULLNUM
from ...constants.zones.deff import TOP, BOTTOM
from ...constants.verbs.deff import *
from ...mana.deff import color
from ...types.deff import nontype, supertype
from ...functions.deff import delimitedListAnd, delimitedListOr
from decl import *
topnum << (TOP|BOTTOM) + (NUM|FULLNUM)
attacking << ATTACK
blocking << BLOCK
tapped << TAP
untapped << UNTAP
enchanted << ENCHANT
equipped << EQUIP
exiled << EXILE
sacrificed << SACRIFICE
haunted << HAUNT
adjective << (
color
| nontype
| supertype
| topnum
| attacking
| blocking
| tapped
| untapped
| enchanted
| equipped
| exiled
| sacrificed
| haunted
)
andadjectives << delimitedListAnd(adjective)
oradjectives << delimitedListOr(adjective)
adjectives << OneOrMore(andadjectives ^ oradjectives)
|
Use ember getter/setters the correct way
|
var SortHeaderView = Ember.View.extend({
tagName: 'th',
classNameBindings: ['asc', 'desc', 'sorted'],
classNames: ['sortable'],
attributeBindings: ['style'],
style: "cursor: pointer",
asc: false,
desc: false,
sorted: false,
sortField: "",
init: function() {
var headerList = this.get('controller.sortHeaderList');
if(headerList === undefined) {
headerList = [];
this.set('controller.sortHeaderList', headerList);
}
headerList.pushObject(this);
this._super();
},
click: function(){
if(this.get('sorted') === true) {
this.toggleProperty('asc');
this.toggleProperty('desc');
} else {
var headerList = this.get('controller.sortHeaderList');
headerList.setEach('asc', false);
headerList.setEach('desc', false);
headerList.setEach('sorted', false);
this.set('asc', true);
this.set('desc', false);
this.set('sorted', true);
}
this.get('controller').send('sort', this.get('sortField'), this.get('asc'));
}
});
export default SortHeaderView;
|
var SortHeaderView = Ember.View.extend({
tagName: 'th',
classNameBindings: ['asc', 'desc', 'sorted'],
classNames: ['sortable'],
attributeBindings: ['style'],
style: "cursor: pointer",
asc: false,
desc: false,
sorted: false,
sortField: "",
init: function() {
var headerList = this.get('controller').get('sortHeaderList');
if(headerList === undefined) {
headerList = new Array();
this.get('controller').set('sortHeaderList', headerList);
}
headerList.pushObject(this);
this._super();
},
click: function(){
if(this.get('sorted') === true) {
this.toggleProperty('asc');
this.toggleProperty('desc');
} else {
var headerList = this.get('controller').get('sortHeaderList');
headerList.setEach('asc', false);
headerList.setEach('desc', false);
headerList.setEach('sorted', false);
this.set('asc', true);
this.set('desc', false);
this.set('sorted', true);
}
this.get('controller').send('sort', this.get('sortField'), this.get('asc'));
}
});
export default SortHeaderView;
|
Disable query string auth for django compressor.
|
from firecares.settings.base import *
INSTALLED_APPS = (
'django_statsd',
) + INSTALLED_APPS
STATSD_HOST = 'stats.garnertb.com'
STATSD_PREFIX = 'firecares'
STATSD_PATCHES = [
'django_statsd.patches.db',
'django_statsd.patches.cache',
]
MIDDLEWARE_CLASSES = (
'django_statsd.middleware.GraphiteRequestTimingMiddleware',
'django_statsd.middleware.GraphiteMiddleware',
'django_statsd.middleware.TastyPieRequestTimingMiddleware'
) + MIDDLEWARE_CLASSES
STATSD_PATCHES = [
'django_statsd.patches.db',
'django_statsd.patches.cache',
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
AWS_STORAGE_BUCKET_NAME = 'firecares-static'
COMPRESS_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
COMPRESS_URL = "https://s3.amazonaws.com/firecares-static/"
COMPRESS_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATICFILES_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATIC_URL = COMPRESS_URL
DEBUG = False
AWS_QUERYSTRING_AUTH = False
try:
from local_settings import * # noqa
except ImportError:
pass
|
from firecares.settings.base import *
INSTALLED_APPS = (
'django_statsd',
) + INSTALLED_APPS
STATSD_HOST = 'stats.garnertb.com'
STATSD_PREFIX = 'firecares'
STATSD_PATCHES = [
'django_statsd.patches.db',
'django_statsd.patches.cache',
]
MIDDLEWARE_CLASSES = (
'django_statsd.middleware.GraphiteRequestTimingMiddleware',
'django_statsd.middleware.GraphiteMiddleware',
'django_statsd.middleware.TastyPieRequestTimingMiddleware'
) + MIDDLEWARE_CLASSES
STATSD_PATCHES = [
'django_statsd.patches.db',
'django_statsd.patches.cache',
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
AWS_STORAGE_BUCKET_NAME = 'firecares-static'
COMPRESS_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
COMPRESS_URL = "https://s3.amazonaws.com/firecares-static/"
COMPRESS_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATICFILES_STORAGE = "firecares.utils.CachedS3BotoStorage"
STATIC_URL = COMPRESS_URL
DEBUG = False
try:
from local_settings import * # noqa
except ImportError:
pass
|
Add messages to rooms objects
|
const getRoomData = require('../db/controllers/getRoomIdsAndUserIdsGivenSelfId.js');
const getBasicInfo = require('../db/controllers/getUserBasicInfoGivenUserId.js');
const helpers = require('../db/controllers/helpers.js');
const getUsersInfoForRoom = (roomObj) =>
getBasicInfo.bulk(roomObj.users)
.then(helpers.pluckUsers)
.then(users => {
roomObj.users = users;
return roomObj;
});
const getUsersInfoForRooms = (roomObjs) =>
Promise.all(roomObjs.map(roomObj => getUsersInfoForRoom(roomObj)));
const addMessagesToRooms = (rooms) =>
rooms.map(room => {
room.messages = room.messages || [];
return room;
});
module.exports = (req, res, next) => {
const selfId = req.idioma.profile.id;
getRoomData(selfId)
.then(getUsersInfoForRooms)
.then(addMessagesToRooms)
.then(modifiedArray => req.idioma.rooms = modifiedArray)
.then(() => next())
.catch((error) => {
res.status(404).send(error);
});
};
|
const getRoomData = require('../db/controllers/getRoomIdsAndUserIdsGivenSelfId.js');
const getBasicInfo = require('../db/controllers/getUserBasicInfoGivenUserId.js');
const helpers = require('../db/controllers/helpers.js');
const getUsersInfoForRoom = (roomObj) =>
getBasicInfo.bulk(roomObj.users)
.then(helpers.pluckUsers)
.then(users => {
roomObj.users = users;
return roomObj;
});
const getUsersInfoForRooms = (roomObjs) =>
Promise.all(roomObjs.map(roomObj => getUsersInfoForRoom(roomObj)));
module.exports = (req, res, next) => {
const selfId = req.idioma.profile.id;
getRoomData(selfId)
.then(getUsersInfoForRooms)
.then(modifiedArray => req.idioma.rooms = modifiedArray)
.then(() => next())
.catch((error) => {
res.status(404).send(error);
});
};
|
Add check that heartbeat timeout is integer
|
import os
import platform
import sys
import click
prog = os.path.basename(sys.argv[0])
@click.command('heartbeat', short_help='Send a heartbeat')
@click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1]))
@click.option('--tag', '-T', 'tags', multiple=True)
@click.option('--timeout', metavar='EXPIRES', type=int, help='Seconds before heartbeat is stale')
@click.option('--delete', '-D', metavar='ID', help='Delete hearbeat')
@click.pass_obj
def cli(obj, origin, tags, timeout, delete):
"""Send or delete a heartbeat."""
client = obj['client']
if delete:
if origin or tags or timeout:
raise click.UsageError('Option "--delete" is mutually exclusive.')
client.delete_heartbeat(delete)
else:
try:
heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout)
except Exception as e:
click.echo('ERROR: {}'.format(e))
sys.exit(1)
click.echo(heartbeat.id)
|
import os
import platform
import sys
import click
prog = os.path.basename(sys.argv[0])
@click.command('heartbeat', short_help='Send a heartbeat')
@click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1]))
@click.option('--tag', '-T', 'tags', multiple=True)
@click.option('--timeout', metavar='EXPIRES', help='Seconds before heartbeat is stale')
@click.option('--delete', '-D', metavar='ID', help='Delete hearbeat')
@click.pass_obj
def cli(obj, origin, tags, timeout, delete):
"""Send or delete a heartbeat."""
client = obj['client']
if delete:
if origin or tags or timeout:
raise click.UsageError('Option "--delete" is mutually exclusive.')
client.delete_heartbeat(delete)
else:
try:
heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout)
except Exception as e:
click.echo('ERROR: {}'.format(e))
sys.exit(1)
click.echo(heartbeat.id)
|
Improve service and error handling a bit
|
function SearchService ($http, $route) {
var omdbUrl = 'http://www.omdbapi.com/';
var apiUrl = 'http://localhost:3020/';
var SearchService = {};
SearchService.loading = false;
SearchService.getMovieByTitle = function (title) {
return $http.get(omdbUrl + '?s=' + title)
.success(function (data) {
if (!data.hasOwnProperty('Error')) {
// omdb returns a Search object containing all the movies
SearchService.movies = data.Search;
}
})
.error(function (error) {
console.log(error);
});
};
SearchService.getMovieByID = function (id) {
SearchService.loading = true;
return $http.get(apiUrl + '?i=' + id)
.success(function (data) {
SearchService.loading = false;
if (!data.hasOwnProperty('Error')) {
SearchService.movie = data;
}
})
.error(function () {
// TODO: Handle this with Growl..
$route.reload();
});
};
return SearchService;
}
angular.module('ngMovies')
.factory('SearchService', SearchService);
|
function SearchService ($http) {
var omdbUrl = 'http://www.omdbapi.com/';
var apiUrl = 'http://localhost:3020/';
var Search = {};
SearchService.loading = false;
SearchService.getMovieByTitle = function (title) {
return $http.get(omdbUrl + '?s=' + title)
.success(function (data) {
if (!data.hasOwnProperty('Error')) {
// omdb returns a Search object containing all the movies
SearchService.movies = data.Search;
}
})
.error(function (error) {
console.log(error);
});
};
SearchService.getMovieByID = function (id) {
SearchService.loading = true;
return $http.get(apiUrl + '?i=' + id)
.success(function (data) {
SearchService.loading = false;
if (!data.hasOwnProperty('Error')) {
SearchService.movie = data;
}
})
.error(function (error) {
console.log(error);
});
};
return SearchService;
}
angular.module('ngMovies')
.factory('SearchService', SearchService);
|
Use single Executor for all tests
... so it doesn't leak for every test.
|
/**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package rx.schedulers;
import rx.Scheduler;
import rx.internal.util.RxThreadFactory;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class ExecutorSchedulerTest extends AbstractSchedulerConcurrencyTests {
final static Executor executor = Executors.newFixedThreadPool(2, new RxThreadFactory("TestCustomPool-"));
@Override
protected Scheduler getScheduler() {
return Schedulers.from(executor);
}
}
|
/**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package rx.schedulers;
import rx.Scheduler;
import rx.internal.util.RxThreadFactory;
import java.util.concurrent.Executors;
public class ExecutorSchedulerTest extends AbstractSchedulerConcurrencyTests {
@Override
protected Scheduler getScheduler() {
return Schedulers.from(Executors.newFixedThreadPool(2, new RxThreadFactory("TestCustomPool-")));
}
}
|
Fix typo in repository name validator errors
|
package repository
import (
"fmt"
"gopkg.in/asaskevich/govalidator.v6"
)
func ValidateCreate(r *Repository) error {
if err := validateName(r.Name); err != nil {
return err
}
if err := validateDescription(r.Description); err != nil {
return err
}
if err := validateWebsite(r.Website); err != nil {
return err
}
return nil
}
func validateID(id string) error {
if ok := govalidator.IsUUIDv4(id); !ok {
return fmt.Errorf("id is not a valid uuid v4")
}
return nil
}
func validateName(name string) error {
if ok := govalidator.IsAlphanumeric(name); !ok {
return fmt.Errorf("name is not alphanumeric")
}
if ok := govalidator.IsByteLength(name, 4, 32); !ok {
return fmt.Errorf("name is not between 4 and 32 characters long")
}
return nil
}
func validateDescription(description string) error {
return nil
}
func validateWebsite(website string) error {
if ok := govalidator.IsURL(website); !ok {
return fmt.Errorf("%s is not a url", website)
}
return nil
}
|
package repository
import (
"fmt"
"gopkg.in/asaskevich/govalidator.v6"
)
func ValidateCreate(r *Repository) error {
if err := validateName(r.Name); err != nil {
return err
}
if err := validateDescription(r.Description); err != nil {
return err
}
if err := validateWebsite(r.Website); err != nil {
return err
}
return nil
}
func validateID(id string) error {
if ok := govalidator.IsUUIDv4(id); !ok {
return fmt.Errorf("id is not a valid uuid v4")
}
return nil
}
func validateName(name string) error {
if ok := govalidator.IsAlphanumeric(name); !ok {
return fmt.Errorf("username is not alphanumeric")
}
if ok := govalidator.IsByteLength(name, 4, 32); !ok {
return fmt.Errorf("username is not between 4 and 32 characters long")
}
return nil
}
func validateDescription(description string) error {
return nil
}
func validateWebsite(website string) error {
if ok := govalidator.IsURL(website); !ok {
return fmt.Errorf("%s is not a url", website)
}
return nil
}
|
Stop Loading... component displaying from react-komposer
|
import { compose, composeWithTracker } from 'react-komposer'
import { inject } from '@mindhive/di'
const Empty = () => null
export const withAsync = (asyncFunc, shouldResubscribe) =>
compose(
inject((appContext, ownProps, onData) => {
const pushProps = (props = {}) =>
onData(null, props)
asyncFunc(appContext, pushProps, ownProps)
}),
Empty,
null,
{ shouldResubscribe },
)
/*
Inside meteorDataUsingFunc calls to Meteor reactive calls are tracked,
and meteorDataUsingFunc rerun if the result of those Meteor calls changes
meteorDataUsingFunc: (appContext, pushProps, ownProps)
Call pushProps with the props to push to the child component.
Note: we don't use the loading and error component of react-komposer.
Push that data through props to handle it nicely.
*/
export const withLiveData = (meteorDataUsingFunc) =>
composeWithTracker(
inject((appContext, ownProps, onData) => {
const pushProps = (props = {}) =>
onData(null, props)
meteorDataUsingFunc(appContext, pushProps, ownProps)
}),
Empty,
)
|
import { compose, composeWithTracker } from 'react-komposer'
import { inject } from '@mindhive/di'
export const withAsync = (asyncFunc, shouldResubscribe) =>
compose(
inject((appContext, ownProps, onData) => {
const pushProps = (props = {}) =>
onData(null, props)
asyncFunc(appContext, pushProps, ownProps)
}),
null, null,
{ shouldResubscribe },
)
/*
Inside meteorDataUsingFunc calls to Meteor reactive calls are tracked,
and meteorDataUsingFunc rerun if the result of those Meteor calls changes
meteorDataUsingFunc: (appContext, pushProps, ownProps)
Call pushProps with the props to push to the child component.
Note: we don't use the loading and error component of react-komposer.
Push that data through props to handle it nicely.
*/
export const withLiveData = (meteorDataUsingFunc) =>
composeWithTracker(
inject((appContext, ownProps, onData) => {
const pushProps = (props = {}) =>
onData(null, props)
meteorDataUsingFunc(appContext, pushProps, ownProps)
})
)
|
Make \r in topics optional
|
package de.tuberlin.dima.schubotz.fse.mappers;
import eu.stratosphere.api.java.functions.FlatMapFunction;
import eu.stratosphere.util.Collector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Cleans main task queries. TODO find way to do this using stratosphere built in data input?
* Required due to Stratosphere split on {@link de.tuberlin.dima.schubotz.fse.MainProgram#QUERY_SEPARATOR}
*/
public class QueryCleaner extends FlatMapFunction<String, String> {
Log LOG = LogFactory.getLog(QueryCleaner.class);
@Override
public void flatMap(String in, Collector<String> out) throws Exception {
//TODO: check if \r is required
if (in.trim().length() == 0 || in.startsWith("\r\n</topics>")) {
if (LOG.isWarnEnabled()) {
LOG.warn("Corrupt query " + in);
}
return;
}
if (in.startsWith("<?xml")) {
in += "</topic></topics>";
}else if (!in.endsWith( "</topic>" )) {
in += "</topic>";
}
out.collect(in);
}
}
|
package de.tuberlin.dima.schubotz.fse.mappers;
import eu.stratosphere.api.java.functions.FlatMapFunction;
import eu.stratosphere.util.Collector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Cleans main task queries. TODO find way to do this using stratosphere built in data input?
* Required due to Stratosphere split on {@link de.tuberlin.dima.schubotz.fse.MainProgram#QUERY_SEPARATOR}
*/
public class QueryCleaner extends FlatMapFunction<String, String> {
Log LOG = LogFactory.getLog(QueryCleaner.class);
@Override
public void flatMap(String in, Collector<String> out) throws Exception {
if (in.trim().length() == 0 || in.startsWith("\r\n</topics>")) {
if (LOG.isWarnEnabled()) {
LOG.warn("Corrupt query " + in);
}
return;
}
if (in.startsWith("<?xml")) {
in += "</topic></topics>";
}else if (!in.endsWith( "</topic>" )) {
in += "</topic>";
}
out.collect(in);
}
}
|
Use single quotes for strings
|
# -*- coding: utf-8; -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Flavien Charlon
#
# 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.
"""
Reference implementation of the Open Assets Protocol.
"""
__version__ = '1.0'
|
# -*- coding: utf-8; -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Flavien Charlon
#
# 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.
"""
Reference implementation of the Open Assets Protocol.
"""
__version__ = "1.0"
|
Set optional class on map widget if class attribute passed
|
from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
"""Custom map widget for displaying interactive google map to geocode
addresses of learning centers.
This widget displays a readonly input box to store lat+lng data, an empty
help div, a map div for the google map, and a button to initiate geocoding.
"""
def render(self, name, value, attrs=None):
"""Overrides the render method. This controls the actual html output of a form
on the page
See widget docs for more information:
https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
"""
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60" class="%s">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, self.attrs.get('class', None), widget))
|
from django.forms import widgets
from django.utils.safestring import mark_safe
class MapWidget(widgets.HiddenInput):
"""Custom map widget for displaying interactive google map to geocode
addresses of learning centers.
This widget displays a readonly input box to store lat+lng data, an empty
help div, a map div for the google map, and a button to initiate geocoding.
"""
def render(self, name, value, attrs=None):
"""Overrides the render method. This controls the actual html output of a form
on the page
See widget docs for more information:
https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
"""
widget = super(MapWidget, self).render(name, value, attrs)
return mark_safe("""<input name="geom" readonly="readonly" value="%s" type="text" id="id_geom" size="60">
<br>
<input type="button" value="Geocode Address" onclick=ecepAdmin.geocodeAddress()>
(<a onclick=ecepAdmin.mapHelp() href="#">?</a>)
<div id='map-help'></div><div id="map">%s</div>""" % (value, widget))
|
ADD base location to logos as it is necesary for security rules
|
# -*- coding: utf-8 -*-
{
'name': 'Logos Set Up Data',
'version': '1.0',
'category': 'Accounting',
'sequence': 14,
'summary': '',
'description': """
Logos Set Up Data
=====================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'crm',
'purchase',
'sale',
'portal_sale_distributor',
'website_sale',
'base_location',
'price_security',
'product_price_currency',
'logos_product_attributes',
'product_catalog_aeroo_report',
],
'data': [
# Para arreglar error
'security/ir.model.access.csv',
'security/logos_security.xml',
'report_data.xml',
'product_view.xml',
'crm_view.xml'
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# -*- coding: utf-8 -*-
{
'name': 'Logos Set Up Data',
'version': '1.0',
'category': 'Accounting',
'sequence': 14,
'summary': '',
'description': """
Logos Set Up Data
=====================
""",
'author': 'Ingenieria ADHOC',
'website': 'www.ingadhoc.com',
'images': [
],
'depends': [
'crm',
'purchase',
'sale',
'portal_sale_distributor',
'website_sale',
# 'base_location',
'price_security',
'product_price_currency',
'logos_product_attributes',
'product_catalog_aeroo_report',
],
'data': [
# Para arreglar error
'security/ir.model.access.csv',
'security/logos_security.xml',
'report_data.xml',
'product_view.xml',
'crm_view.xml'
],
'demo': [
],
'test': [
],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Add eol id to expectation
|
<?php
namespace Tests\AppBundle\API\Details;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class OrganismTest extends WebserviceTestCase
{
public function testExecute()
{
$default_db = $this->default_db;
$session = null;
$organisms = $this->webservice->factory('details', 'organism');
$parameterBag = new ParameterBag(array('dbversion' => $default_db, 'id' => 42));
$results = $organisms->execute($parameterBag, $session);
$expected = array(
"fennec_id" => 42,
"scientific_name" => "Trebouxiophyceae sp. TP-2016a",
"eol_identifier" => "909148",
"ncbi_identifier" => "3083"
);
$this->assertEquals($expected, $results);
}
}
|
<?php
namespace Tests\AppBundle\API\Details;
use Symfony\Component\HttpFoundation\ParameterBag;
use Tests\AppBundle\API\WebserviceTestCase;
class OrganismTest extends WebserviceTestCase
{
public function testExecute()
{
$default_db = $this->default_db;
$session = null;
$organisms = $this->webservice->factory('details', 'organism');
$parameterBag = new ParameterBag(array('dbversion' => $default_db, 'id' => 42));
$results = $organisms->execute($parameterBag, $session);
$expected = array(
"fennec_id" => 42,
"scientific_name" => "Trebouxiophyceae sp. TP-2016a",
"eol_identifier" => "",
"ncbi_identifier" => "3083"
);
$this->assertEquals($expected, $results);
}
}
|
Select all when editing in angular-xeditable by default
|
var app = angular.module('swot', [
'ui.bootstrap',
'ui.utils',
'ui.sortable',
'focus',
'confirmExit',
'ngDebounce',
'ngAnimate',
'xeditable',
'angularBootstrapNavTree'
]);
app.config(['$httpProvider', function ($httpProvider) {
// Add support for HTTP PATCH verb for sending partial updates.
$httpProvider.defaults.headers.patch = {
'Content-Type': 'application/json;charset=utf-8'
};
}]);
app.run(function (editableOptions, editableThemes) {
// Set options for angular-xeditable
editableOptions.theme = 'bs3';
editableOptions.activate = 'select';
editableThemes.bs3.inputClass = 'input-sm';
editableThemes.bs3.buttonsClass = 'btn-sm';
});
|
var app = angular.module('swot', [
'ui.bootstrap',
'ui.utils',
'ui.sortable',
'focus',
'confirmExit',
'ngDebounce',
'ngAnimate',
'xeditable',
'angularBootstrapNavTree'
]);
app.config(['$httpProvider', function ($httpProvider) {
// Add support for HTTP PATCH verb for sending partial updates.
$httpProvider.defaults.headers.patch = {
'Content-Type': 'application/json;charset=utf-8'
};
}]);
app.run(function (editableOptions, editableThemes) {
// Set options for angular-xeditable
editableOptions.theme = 'bs3';
editableThemes.bs3.inputClass = 'input-sm';
editableThemes.bs3.buttonsClass = 'btn-sm';
});
|
Update libchromiumcontent to disable zygote process
|
#!/usr/bin/env python
import platform
import sys
BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'c01b10faf0d478e48f537210ec263fabd551578d'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
verbose_mode = False
def enable_verbose_mode():
print 'Running in verbose mode'
global verbose_mode
verbose_mode = True
def is_verbose_mode():
return verbose_mode
|
#!/usr/bin/env python
import platform
import sys
BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '26dd65a62e35aa98b25c10cbfc00f1a621fd4c4b'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
verbose_mode = False
def enable_verbose_mode():
print 'Running in verbose mode'
global verbose_mode
verbose_mode = True
def is_verbose_mode():
return verbose_mode
|
Add helpers.js to ignore from tests
|
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var eslint = require('gulp-eslint');
var coveralls = require('gulp-coveralls');
gulp.task('pre-test', function () {
return gulp.src(['lib/**/*.js', '!lib/micro-whalla.js', '!lib/helpers.js'])
.pipe(istanbul({ includeUntested: true }))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['lint', 'pre-test'], function () {
return gulp.src('test/*.test.js')
.pipe(mocha())
.pipe(istanbul.writeReports());
});
gulp.task('lint', function () {
return gulp.src(['**/*.js', '!node_modules/**', '!coverage/**'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('coveralls', function () {
return gulp.src('coverage/**/lcov.info')
.pipe(coveralls());
});
gulp.task('default', ['test'], function () {
});
|
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var eslint = require('gulp-eslint');
var coveralls = require('gulp-coveralls');
gulp.task('pre-test', function () {
return gulp.src(['lib/**/*.js', '!lib/micro-whalla.js'])
.pipe(istanbul({ includeUntested: true }))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['lint', 'pre-test'], function () {
return gulp.src('test/*.test.js')
.pipe(mocha())
.pipe(istanbul.writeReports());
});
gulp.task('lint', function () {
return gulp.src(['**/*.js', '!node_modules/**', '!coverage/**'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('coveralls', function () {
return gulp.src('coverage/**/lcov.info')
.pipe(coveralls());
});
gulp.task('default', ['test'], function () {
});
|
Refactor magic port number into constant.
git-svn-id: c455d203a03ec41bf444183aad31e7cce55db786@1349874 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.sftp;
import org.apache.commons.vfs2.provider.FileNameParser;
import org.apache.commons.vfs2.provider.URLFileNameParser;
/**
* Implementation for sftp. set default port to 22.
*/
public class SftpFileNameParser extends URLFileNameParser
{
private static final int DEFAULT_PORT = 22;
private static final SftpFileNameParser INSTANCE = new SftpFileNameParser();
public SftpFileNameParser()
{
super(DEFAULT_PORT);
}
public static FileNameParser getInstance()
{
return INSTANCE;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.sftp;
import org.apache.commons.vfs2.provider.FileNameParser;
import org.apache.commons.vfs2.provider.URLFileNameParser;
/**
* Implementation for sftp. set default port to 22.
*/
public class SftpFileNameParser extends URLFileNameParser
{
private static final SftpFileNameParser INSTANCE = new SftpFileNameParser();
public SftpFileNameParser()
{
super(22);
}
public static FileNameParser getInstance()
{
return INSTANCE;
}
}
|
Update contact form to send email inquiries
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'dewar1@djpeedee.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@djpeedee.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
<?php
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'djpeedee1@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@djpeedee.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
|
Implement loading of dictionary and postings list
|
import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
|
import io
import getopt
import sys
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
|
Update a Phabricator -> Arcanist include path for scripts in Phabricator
Summary: Ref T13395. Since there's very little code which really makes sense in "scripts/", I've moved most of it to other places.
Test Plan: Ran `bin/phd`.
Maniphest Tasks: T13395
Differential Revision: https://secure.phabricator.com/D20994
|
<?php
function init_phabricator_script(array $options) {
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
$include_path = ini_get('include_path');
ini_set(
'include_path',
$include_path.PATH_SEPARATOR.dirname(__FILE__).'/../../../');
$ok = @include_once 'arcanist/support/init/init-script.php';
if (!$ok) {
echo
'FATAL ERROR: Unable to load the "Arcanist" library. '.
'Put "arcanist/" next to "phabricator/" on disk.';
echo "\n";
exit(1);
}
phutil_load_library('arcanist/src');
phutil_load_library(dirname(__FILE__).'/../../src/');
$config_optional = $options['config.optional'];
PhabricatorEnv::initializeScriptEnvironment($config_optional);
}
|
<?php
function init_phabricator_script(array $options) {
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
$include_path = ini_get('include_path');
ini_set(
'include_path',
$include_path.PATH_SEPARATOR.dirname(__FILE__).'/../../../');
$ok = @include_once 'arcanist/scripts/init/init-script.php';
if (!$ok) {
echo
'FATAL ERROR: Unable to load the "Arcanist" library. '.
'Put "arcanist/" next to "phabricator/" on disk.';
echo "\n";
exit(1);
}
phutil_load_library('arcanist/src');
phutil_load_library(dirname(__FILE__).'/../../src/');
$config_optional = $options['config.optional'];
PhabricatorEnv::initializeScriptEnvironment($config_optional);
}
|
Fix the build to test Hudson
git-svn-id: ec6ef1d57ec0831ce4cbff3b75527511e63bfbe3@736937 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jsecurity.util;
/**
* Interface implemented by components that can be named, such as via configuration, and wish to have that name
* set once it has been configured.
*
* @author Les Hazlewood
* @since 0.9
*/
public interface Nameable {
/**
* Sets the (preferably application unique) name for this component.
* @param name the preferably application unique name for this component.
*/
void setName(String name);
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jsecurity.util;
BREAK BUILD
/**
* Interface implemented by components that can be named, such as via configuration, and wish to have that name
* set once it has been configured.
*
* @author Les Hazlewood
* @since 0.9
*/
public interface Nameable {
/**
* Sets the (preferably application unique) name for this component.
* @param name the preferably application unique name for this component.
*/
void setName(String name);
}
|
Add a state not to call the task continuously.
|
import sys
sys.path.append('../py')
from iroha import *
from iroha.iroha import *
d = IDesign()
mod = IModule(d, "mod")
callee_tab = ITable(mod)
task = design_tool.CreateSiblingTask(callee_tab)
entry_insn = IInsn(task)
st1 = IState(callee_tab)
st1.insns.append(entry_insn)
callee_tab.states.append(st1)
callee_tab.initialSt = st1
print_res = design_tool.GetResource(callee_tab, "print")
print_insn = IInsn(print_res)
print_insn.inputs.append(design_tool.AllocConstNum(callee_tab, False, 32, 123))
st1.insns.append(print_insn)
caller_tab = ITable(mod)
call = design_tool.CreateSiblingTaskCall(caller_tab, callee_tab)
call_insn = IInsn(call)
st20 = IState(caller_tab)
st20.insns.append(call_insn)
caller_tab.states.append(st20)
caller_tab.initialSt = st20
st21 = IState(caller_tab)
caller_tab.states.append(st21)
design_tool.AddNextState(st20, st21)
design_tool.ValidateIds(d)
w = DesignWriter(d)
w.Write()
|
import sys
sys.path.append('../py')
from iroha import *
from iroha.iroha import *
d = IDesign()
mod = IModule(d, "mod")
callee_tab = ITable(mod)
task = design_tool.CreateSiblingTask(callee_tab)
entry_insn = IInsn(task)
st1 = IState(callee_tab)
st1.insns.append(entry_insn)
callee_tab.states.append(st1)
callee_tab.initialSt = st1
caller_tab = ITable(mod)
call = design_tool.CreateSiblingTaskCall(caller_tab, callee_tab)
call_insn = IInsn(call)
st2 = IState(caller_tab)
st2.insns.append(call_insn)
caller_tab.states.append(st2)
caller_tab.initialSt = st2
design_tool.ValidateIds(d)
w = DesignWriter(d)
w.Write()
|
Remove log call, add docs
|
/* globals onmessage: true, postMessage: true */
/**
* Extract the compilers used for the build.
*
* @param {Object} message
**/
onmessage = function(message) {
'use strict';
var gCompilers;
gCompilers = {};
function parseBuildData(build) {
var compiler;
var compilerArray;
compiler = build.compiler_version_full;
if (compiler) {
if (!gCompilers.hasOwnProperty(build.arch)) {
gCompilers[build.arch] = compilerArray = [];
} else {
compilerArray = gCompilers[build.arch];
}
if (compilerArray.indexOf(compiler) === -1) {
compilerArray.push(compiler);
}
}
}
if (message.data) {
message.data.forEach(parseBuildData);
}
postMessage(gCompilers);
};
|
/* globals onmessage: true, postMessage: true */
onmessage = function(message) {
'use strict';
var gCompilers;
gCompilers = {};
function parseBuildData(build) {
var compiler;
var compilerArray;
compiler = build.compiler_version_full;
if (compiler) {
if (!gCompilers.hasOwnProperty(build.arch)) {
gCompilers[build.arch] = compilerArray = [];
} else {
compilerArray = gCompilers[build.arch];
}
if (compilerArray.indexOf(compiler) === -1) {
compilerArray.push(compiler);
}
}
}
if (message.data) {
message.data.forEach(parseBuildData);
}
console.log(gCompilers);
postMessage(gCompilers);
};
|
Fix so you don't get banned after 5 refreshes.
|
var auth = require('http-auth');
var util = require('util');
var app = require('../src/app');
var ip = require('./ip');
var loginAttempts= {};
var authCallback = function(user, pass, callback) {
callback(user === app.config.admin.user && pass === app.config.admin.password);
};
var basic = auth.basic({
realm: "Admin area"
},
authCallback
);
module.exports = function(req, res, next) {
var userIp = ip(req);
loginAttempts[userIp] = loginAttempts[userIp] || 0;
loginAttempts[userIp]++;
if (loginAttempts[userIp] > 5) {
// Ban user for the lifetime of this node process.
app.log(util.format('Banning user with ip %s after more than 5 login attempts', userIp));
app.banned[userIp] = true;
return res.send(403);
}
return basic.check(req, res, function() {
// If this went OK, we decrease loginAttempts for this person.
loginAttempts[userIp]--;
return next();
});
};
|
var auth = require('http-auth');
var util = require('util');
var app = require('../src/app');
var ip = require('./ip');
var loginAttempts= {};
var authCallback = function(user, pass, callback) {
callback(user === app.config.admin.user && pass === app.config.admin.password);
};
var basic = auth.basic({
realm: "Admin area"
},
authCallback
);
module.exports = function(req, res, next) {
var userIp = ip(req);
loginAttempts[userIp] = loginAttempts[userIp] || 0;
loginAttempts[userIp]++;
if (loginAttempts[userIp] > 5) {
// Ban user for the lifetime of this node process.
app.log(util.format('Banning user with ip %s after more than 5 login attempts', userIp));
app.banned[userIp] = true;
return res.send(403);
}
return basic.check(req, res, function() {
return next();
});
};
|
Remove dendropy from required packages
Let the users decide for themselves whether to install DendroPy and/or
BioPython.
|
from setuptools import setup, find_packages
from os.path import join, dirname
setup(
name='pandas-charm',
version='0.1.0',
description=(
'A small Python library for getting character matrices '
'(alignments) into and out of pandas'),
long_description=open(
join(dirname(__file__), 'README.rst'), encoding='utf-8').read(),
packages=find_packages(exclude=['docs', 'tests*']),
py_modules=['pandascharm'],
install_requires=['pandas>=0.16', 'numpy'],
extras_require={'test': ['coverage', 'pytest', 'pytest-cov']},
author='Markus Englund',
author_email='jan.markus.englund@gmail.com',
url='https://github.com/jmenglund/pandas-charm',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3'],
keywords=['alignment', 'biopython', 'DendroPy', 'pandas'],
)
|
from setuptools import setup, find_packages
from os.path import join, dirname
setup(
name='pandas-charm',
version='0.1.0',
description=(
'A small Python library for getting character matrices '
'(alignments) into and out of pandas'),
long_description=open(
join(dirname(__file__), 'README.rst'), encoding='utf-8').read(),
packages=find_packages(exclude=['docs', 'tests*']),
py_modules=['pandascharm'],
install_requires=['pandas>=0.16', 'numpy', 'dendropy>=4'],
extras_require={'test': ['coverage', 'pytest', 'pytest-cov']},
author='Markus Englund',
author_email='jan.markus.englund@gmail.com',
url='https://github.com/jmenglund/pandas-charm',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3'],
keywords=['alignment', 'biopython', 'DendroPy', 'pandas'],
)
|
Make snippet parameters to form_output tag.
|
<section class="title">
<h4><?php echo sprintf(lang('snippets.edit_snippet'), $snippet->name);?></h4>
</section>
<section class="item">
<?php echo form_open_multipart($this->uri->uri_string(), 'class="crud"'); ?>
<div class="form_inputs">
<ul>
<li>
<label for="name"><?php echo lang('snippets.snippet_content');?> <span>*</span></label>
<?php echo $this->snippets_m->snippets->{$snippet->type}->form_output($snippet->content, $snippet->params); ?>
</li>
</ul>
</div><!--.form_input-->
<?php $this->load->view('admin/partials/buttons', array('buttons' => array('save', 'save_exit', 'cancel') )); ?>
<?php echo form_close(); ?>
</section>
|
<section class="title">
<h4><?php echo sprintf(lang('snippets.edit_snippet'), $snippet->name);?></h4>
</section>
<section class="item">
<?php echo form_open_multipart($this->uri->uri_string(), 'class="crud"'); ?>
<div class="form_inputs">
<ul>
<li>
<label for="name"><?php echo lang('snippets.snippet_content');?> <span>*</span></label>
<?php echo $this->snippets_m->snippets->{$snippet->type}->form_output($snippet->content); ?>
</li>
</ul>
</div><!--.form_input-->
<?php $this->load->view('admin/partials/buttons', array('buttons' => array('save', 'save_exit', 'cancel') )); ?>
<?php echo form_close(); ?>
</section>
|
Use single quotes for the JSON string, double quotes for the values within it
|
'use strict';
var _ = require('lodash');
var Brain = require('../lib/brain');
var Configuration = require('../lib/configuration.js');
var State = require('../lib/constants/state.js');
describe('Brain', function() {
var config = null;
var brain = null;
beforeEach(function () {
var commandLine = JSON.parse('{"_":[],"mockBTC":"1EyE2nE4hf8JVjV51Veznz9t9vTFv8uRU5","mockBv":"/dev/pts/7","mockTrader":true,"mockCam":true,"mockBillDispenser":true}');
config = Configuration.loadConfig(commandLine);
brain = new Brain(config);
});
it('can be configured with default values', function() {
expect(brain).toBeDefined();
});
it('starts off in the state \'start\'', function () {
expect(brain.state).toBe(State.START);
});
it('initializes its trader correctly', function () {
var expectedTraderEvents = [State.POLL_UPDATE, 'networkDown', 'networkUp', 'dispenseUpdate', 'error', 'unpair'];
brain._initTraderEvents();
_.each(expectedTraderEvents, function(el/*, idx, list*/) { var arr = brain.trader.listeners(el); expect(arr.length).toBe(1); });
});
});
|
'use strict';
var _ = require('lodash');
var Brain = require('../lib/brain');
var Configuration = require('../lib/configuration.js');
var State = require('../lib/constants/state.js');
describe('Brain', function() {
var config = null;
var brain = null;
beforeEach(function () {
var commandLine = JSON.parse("{'_':[],'mockBTC':'1EyE2nE4hf8JVjV51Veznz9t9vTFv8uRU5','mockBv':'/dev/pts/7','mockTrader':true,'mockCam':true,'mockBillDispenser':true}");
config = Configuration.loadConfig(commandLine);
brain = new Brain(config);
});
it('can be configured with default values', function() {
expect(brain).toBeDefined();
});
it('starts off in the state \'start\'', function () {
expect(brain.state).toBe(State.START);
});
it('initializes its trader correctly', function () {
var expectedTraderEvents = [State.POLL_UPDATE, 'networkDown', 'networkUp', 'dispenseUpdate', 'error', 'unpair'];
brain._initTraderEvents();
_.each(expectedTraderEvents, function(el/*, idx, list*/) { var arr = brain.trader.listeners(el); expect(arr.length).toBe(1); });
});
});
|
Fix more spacing from merge conflict
|
package com.malpo.sliver.sample.ui.sample;
import com.malpo.sliver.sample.models.Message;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import rx.Observable;
import timber.log.Timber;
class SampleInteractor implements SampleContract.Interactor {
private String log;
public SampleInteractor(String log) {
this.log = log;
}
@Override
public Observable<Message> sendMessageToApi(Message message) {
Timber.d(log);
Timber.d("Sending message!");
return Observable.fromCallable(mockApiCall(message));
}
private Callable<Message> mockApiCall(Message message) {
Timber.d("Inside callable!");
return () -> new Message("New Message", "Woah, sick message bro");
}
}
|
package com.malpo.sliver.sample.ui.sample;
import com.malpo.sliver.sample.models.Message;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import rx.Observable;
import timber.log.Timber;
class SampleInteractor implements SampleContract.Interactor {
private String log;
public SampleInteractor(String log) {
this.log = log;
}
@Override
public Observable<Message> sendMessageToApi(Message message) {
Timber.d(log);
Timber.d("Sending message!");
return Observable.fromCallable(mockApiCall(message));
}
private Callable<Message> mockApiCall(Message message) {
Timber.d("Inside callable!");
return () -> new Message("New Message", "Woah, sick message bro");
}
}
|
Add URL for checking for deleted packages
|
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask, render_template, flash, request, Markup, \
session, redirect, url_for, escape, Response, abort, send_file
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import func
from datetime import datetime
from iatidataquality import app
from iatidataquality import db
from iatidq import dqdownload, dqregistry, dqindicators, dqorganisations, dqpackages
import usermanagement
@app.route("/registry/refresh/")
@usermanagement.perms_required()
def registry_refresh():
dqregistry.refresh_packages()
return "Refreshed"
@app.route("/registry/download/")
@usermanagement.perms_required()
def registry_download():
dqdownload.run()
return "Downloading"
@app.route("/registry/deleted/")
@usermanagement.perms_required()
def registry_deleted():
num_deleted = dqregistry.check_deleted_packages()
if num_deleted >0:
msg = '%s packages were set to deleted' % num_deleted
else:
msg = "No packages were set to deleted"
flash(msg, '')
return redirect(url_for('packages_manage'))
|
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3.0
from flask import Flask, render_template, flash, request, Markup, \
session, redirect, url_for, escape, Response, abort, send_file
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import func
from datetime import datetime
from iatidataquality import app
from iatidataquality import db
from iatidq import dqdownload, dqregistry, dqindicators, dqorganisations, dqpackages
import usermanagement
@app.route("/registry/refresh/")
@usermanagement.perms_required()
def registry_refresh():
dqregistry.refresh_packages()
return "Refreshed"
@app.route("/registry/download/")
@usermanagement.perms_required()
def registry_download():
dqdownload.run()
return "Downloading"
|
Update code with new Transformation method
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package cx2x.translator.transformation;
import cx2x.translator.language.base.ClawLanguage;
import cx2x.translator.transformation.ClawTransformation;
import cx2x.xcodeml.transformation.Transformation;
import cx2x.xcodeml.transformation.Translator;
import cx2x.xcodeml.xnode.XcodeProgram;
/**
* Simple transformation for documentation example
*/
public class MyFirstTransformation extends ClawTransformation {
// Constructor that received the analyzed pragma as argument
public MyFirstTransformation(ClawLanguage directive) {
super(directive);
}
// The analyzis step
public boolean analyze(XcodeProgram xcodeml, Translator translator) {
return true;
}
// The transformation step
public void transform(XcodeProgram xcodeml, Translator translator,
Transformation other) throws Exception
{
removePragma();
}
// Only used by dependent transformation
public boolean canBeTransformedWith(Transformation other) {
return false; // Independent transformation
}
}
|
/*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package cx2x.translator.transformation;
import cx2x.translator.language.base.ClawLanguage;
import cx2x.translator.transformation.ClawTransformation;
import cx2x.xcodeml.transformation.Transformation;
import cx2x.xcodeml.transformation.Translator;
import cx2x.xcodeml.xnode.XcodeProgram;
/**
* Simple transformation for documentation example
*/
public class MyFirstTransformation extends ClawTransformation {
// Constructor that received the analyzed pragma as argument
public MyFirstTransformation(ClawLanguage directive) {
super(directive);
}
// The analyzis step
public boolean analyze(XcodeProgram xcodeml, Translator translator) {
return true;
}
// The transformation step
public void transform(XcodeProgram xcodeml, Translator translator,
Transformation other) throws Exception
{
_claw.delete();
}
// Only used by dependent transformation
public boolean canBeTransformedWith(Transformation other) {
return false; // Independent transformation
}
}
|
Use shutil instead of `os.rename`
|
import os
import shutil
import argparse
from astropy.utils import data
from astroplan import download_IERS_A
def download_all_files(data_folder="{}/astrometry/data".format(os.getenv('PANDIR'))):
download_IERS_A()
for i in range(4214, 4219):
fn = 'index-{}.fits'.format(i)
dest = "{}/{}".format(data_folder, fn)
if not os.path.exists(dest):
url = "http://data.astrometry.net/4200/{}".format(fn)
df = data.download_file(url)
try:
shutil.move(df, dest)
except OSError as e:
print("Problem saving. (Maybe permissions?): {}".format(e))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--folder', help='Folder to place astrometry data')
args = parser.parse_args()
if not os.path.exists(args.folder):
print("{} does not exist.".format(args.folder))
download_all_files(data_folder=args.folder)
|
import os
import argparse
from astropy.utils import data
from astroplan import download_IERS_A
def download_all_files(data_folder="{}/astrometry/data".format(os.getenv('PANDIR'))):
download_IERS_A()
for i in range(4214, 4219):
fn = 'index-{}.fits'.format(i)
dest = "{}/{}".format(data_folder, fn)
if not os.path.exists(dest):
url = "http://data.astrometry.net/4200/{}".format(fn)
df = data.download_file(url)
try:
os.rename(df, dest)
except OSError as e:
print("Problem saving. (Maybe permissions?): {}".format(e))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--folder', help='Folder to place astrometry data')
args = parser.parse_args()
if not os.path.exists(args.folder):
print("{} does not exist.".format(args.folder))
download_all_files(data_folder=args.folder)
|
Make project Java 6 compliant
|
package io.mkremins.whydah.interpreter;
import io.mkremins.whydah.ast.Expression;
import io.mkremins.whydah.ast.ExpressionUtils;
import java.util.HashMap;
import java.util.Map;
public class Scope {
private final Map<String, Expression> vars;
private final Scope parent;
public Scope(final Scope parent) {
vars = new HashMap<String, Expression>();
this.parent = parent;
}
public Scope() {
this(null);
}
public void delete(final String varName) {
getDeclaringScope(varName).vars.remove(varName);
}
public Expression get(final String varName) {
return getDeclaringScope(varName).vars.get(varName);
}
public void set(final String varName, final Expression value) {
Scope scope = getDeclaringScope(varName);
if (scope == null) {
scope = this;
}
scope.vars.put(varName, ExpressionUtils.fullyEvaluate(value, scope));
}
private Scope getDeclaringScope(final String varName) {
Scope scope = this;
while (scope != null && scope.vars.get(varName) == null) {
scope = scope.parent;
}
return scope;
}
}
|
package io.mkremins.whydah.interpreter;
import io.mkremins.whydah.ast.Expression;
import io.mkremins.whydah.ast.ExpressionUtils;
import java.util.HashMap;
import java.util.Map;
public class Scope {
private final Map<String, Expression> vars;
private final Scope parent;
public Scope(final Scope parent) {
vars = new HashMap<>();
this.parent = parent;
}
public Scope() {
this(null);
}
public void delete(final String varName) {
getDeclaringScope(varName).vars.remove(varName);
}
public Expression get(final String varName) {
return getDeclaringScope(varName).vars.get(varName);
}
public void set(final String varName, final Expression value) {
Scope scope = getDeclaringScope(varName);
if (scope == null) {
scope = this;
}
scope.vars.put(varName, ExpressionUtils.fullyEvaluate(value, scope));
}
private Scope getDeclaringScope(final String varName) {
Scope scope = this;
while (scope != null && scope.vars.get(varName) == null) {
scope = scope.parent;
}
return scope;
}
}
|
Allow prop file to be missing.
|
package io.muoncore.spring.boot;
import io.muoncore.spring.annotations.EnableMuonControllers;
import io.muoncore.spring.repository.DefaultMuonEventStoreRepository;
import io.muoncore.spring.repository.MuonEventStoreRepository;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@EnableConfigurationProperties(MuonConfigurationProperties.class)
@EnableMuonControllers(streamKeepAliveTimeout = 100)
@PropertySource(value="classpath:application.properties", ignoreResourceNotFound=true)
public class MuonAutoConfiguration {
@Bean
@ConditionalOnMissingBean(MuonEventStoreRepository.class)
MuonEventStoreRepository muonEventStore(ApplicationContext applicationContext) {
MuonEventStoreRepository repo = new DefaultMuonEventStoreRepository();
return repo;
}
}
|
package io.muoncore.spring.boot;
import io.muoncore.spring.annotations.EnableMuonControllers;
import io.muoncore.spring.repository.DefaultMuonEventStoreRepository;
import io.muoncore.spring.repository.MuonEventStoreRepository;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@EnableConfigurationProperties(MuonConfigurationProperties.class)
@EnableMuonControllers(streamKeepAliveTimeout = 100)
@PropertySource("classpath:application.properties")
public class MuonAutoConfiguration {
@Bean
@ConditionalOnMissingBean(MuonEventStoreRepository.class)
MuonEventStoreRepository muonEventStore(ApplicationContext applicationContext) {
MuonEventStoreRepository repo = new DefaultMuonEventStoreRepository();
return repo;
}
}
|
Fix spacing. Update mfcc test to check columns
|
import numpy as np
from unittest import TestCase
from cartography.extractor import LibrosaFeatureExtractor
def gen_signal(dur, sr, freq):
return np.pi * 2 * freq * np.arange(dur * sr) / float(sr)
class TestLibrosaFeatureExtractor(TestCase):
@classmethod
def setUpClass(cls):
cls.test_dur = 2
cls.test_freq = 440
cls.test_sr = 22050
cls.test_signal = gen_signal(cls.test_dur, cls.test_sr, cls.test_freq)
def test_mfcc(self):
extractor = LibrosaFeatureExtractor(None)
num_mfccs = 13
mfccs_kwargs = {
'num_mfccs': num_mfccs,
'delta_mfccs': False,
'delta2_mfccs': False
}
expected_columns = 13
got = extractor._mfcc(self.test_signal, self.test_sr, **mfccs_kwargs)
self.assertEqual(expected_columns, got.shape[0])
|
import numpy as np
from unittest import TestCase
from cartography.extractor import LibrosaFeatureExtractor
def gen_signal(dur, sr, freq):
return np.pi * 2 * freq * np.arange(dur * sr) / float(sr)
class TestLibrosaFeatureExtractor(TestCase):
@classmethod
def setUpClass(cls):
cls.test_dur = 2
cls.test_freq = 440
cls.test_sr = 22050
cls.test_signal = gen_signal(cls.test_dur, cls.test_sr, cls.test_freq)
def test_mfcc(self):
extractor = LibrosaFeatureExtractor(None)
num_mfccs = 13
mfccs_kwargs = {
'num_mfccs': num_mfccs,
'delta_mfccs': False,
'delta2_mfccs': False
}
expected_shape = ((13, 1000))
got = extractor._mfcc(self.test_signal, self.test_sr, **mfccs_kwargs)
self.assertEqual(expected_shape, got.shape) # TODO figure out num hops
|
Add arg parser to balancing script
|
#!/usr/bin/env python
from __future__ import division, print_function
from multiprocessing import Pool
import argparse
import numpy as np
import h5py
import cooler
import cooler.ice
N_CPUS = 5
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Compute a genome-wide balancing/bias/normalization vector. Assumes uniform binning.")
parser.add_argument(
"cooler_file",
help="Cooler file",
metavar="COOLER_PATH")
args = vars(parser.parse_args())
chunksize = int(100e6)
try:
pool = Pool(N_CPUS)
with h5py.File(args['cooler_file'], 'a') as h5:
bias = cooler.ice.iterative_correction(
h5, chunksize=chunksize, tol=1e-05, min_nnz=100,
cis_only=False, ignore_diags=3, map=pool.map)
# add the bias column to the file
if 'weight' in h5['bins']:
del h5['bins']['weight']
h5['bins'].create_dataset('weight', data=bias, **h5opts)
finally:
pool.close()
|
#!/usr/bin/env python
from __future__ import division, print_function
from multiprocessing import Pool
import numpy as np
import h5py
import cooler
import cooler.ice
N_CPUS = 5
if __name__ == '__main__':
# Compute a genome-wide balancing/bias/normalization vector
# *** assumes uniform binning ***
chunksize = int(100e6)
try:
pool = Pool(N_CPUS)
with h5py.File(COOLER_PATH, 'a') as h5:
bias = cooler.ice.iterative_correction(
h5, chunksize=chunksize, tol=1e-05, min_nnz=100,
cis_only=False, ignore_diags=3, map=pool.map)
# add the bias column to the file
if 'weight' in h5['bins']:
del h5['bins']['weight']
h5['bins'].create_dataset('weight', data=bias, **h5opts)
finally:
pool.close()
|
Make type propType of field lazy
|
import {PropTypes} from 'react'
function lazy(fn) {
let cachedFn
return (...args) => (cachedFn || (cachedFn = fn()))(...args)
}
let type
const field = PropTypes.shape({
name: PropTypes.string,
type: lazy(() => type)
})
type = PropTypes.shape({
name: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string,
placeholder: PropTypes.string,
type: lazy(() => type),
to: lazy(() => PropTypes.arrayOf(type)),
fields: lazy(() => PropTypes.arrayOf(field)),
of: lazy(() => PropTypes.arrayOf(type))
})
const validation = {
fields: PropTypes.objectOf(lazy(() => PropTypes.shape(validation))),
messages: PropTypes.arrayOf(PropTypes.shape({
type: PropTypes.oneOf(['error', 'warning']),
id: PropTypes.string,
message: PropTypes.string
}))
}
const schema = PropTypes.shape({
name: PropTypes.string,
fields: PropTypes.arrayOf(type)
})
export default {
type,
field,
schema,
validation
}
|
import {PropTypes} from 'react'
function lazy(fn) {
let cachedFn
return (...args) => (cachedFn || (cachedFn = fn()))(...args)
}
const field = PropTypes.shape({
name: PropTypes.string,
type: type
})
const type = PropTypes.shape({
name: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string,
placeholder: PropTypes.string,
type: lazy(() => type),
to: lazy(() => PropTypes.arrayOf(type)),
fields: lazy(() => PropTypes.arrayOf(field)),
of: lazy(() => PropTypes.arrayOf(type))
})
const validation = {
fields: PropTypes.objectOf(lazy(() => PropTypes.shape(validation))),
messages: PropTypes.arrayOf(PropTypes.shape({
type: PropTypes.oneOf(['error', 'warning']),
id: PropTypes.string,
message: PropTypes.string
}))
}
const schema = PropTypes.shape({
name: PropTypes.string,
fields: PropTypes.arrayOf(type)
})
export default {
type,
field,
schema,
validation
}
|
Add crud for folder in navigation
|
<?php
namespace PHPOrchestra\ModelBundle\Document;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\Collection;
use PHPOrchestra\ModelBundle\Model\MediaFolderInterface;
use PHPOrchestra\ModelBundle\Model\MediaInterface;
/**
* Class MediaFolder
*
* @ODM\Document(
* repositoryClass="PHPOrchestra\ModelBundle\Repository\FolderRepository"
* )
*/
class MediaFolder extends Folder implements MediaFolderInterface
{
/**
* @var Collection
*
* @ODM\ReferenceMany(targetDocument="PHPOrchestra\ModelBundle\Document\Media", mappedBy="folder")
*/
protected $medias;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->medias = new ArrayCollection();
}
/**
* @return Collection
*/
public function getMedias()
{
return $this->medias;
}
/**
* @param MediaInterface $media
*/
public function addMedia(MediaInterface $media)
{
$this->medias->add($media);
$media->setMedialFolder($this);
}
/**
* @param MediaInterface $media
*/
public function removeMedia(MediaInterface $media)
{
$this->medias->removeElement($media);
}
}
|
<?php
namespace PHPOrchestra\ModelBundle\Document;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\Common\Collections\Collection;
use PHPOrchestra\ModelBundle\Model\MediaFolderInterface;
use PHPOrchestra\ModelBundle\Model\MediaInterface;
/**
* Class MediaFolder
*
* @ODM\Document(
* repositoryClass="PHPOrchestra\ModelBundle\Repository\FolderRepository"
* )
*/
class MediaFolder extends Folder implements MediaFolderInterface
{
/**
* @var Collection
*
* @ODM\ReferenceMany(targetDocument="PHPOrchestra\ModelBundle\Document\Media", mappedBy="folder")
*/
protected $medias;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->medias = new ArrayCollection();
}
/**
* @return Collection
*/
public function getMedias()
{
return $this->medias;
}
/**
* @param MediaInterface $media
*/
public function addMedia(MediaInterface $media)
{
$this->medias->add($media);
}
/**
* @param MediaInterface $media
*/
public function removeMedia(MediaInterface $media)
{
$this->medias->removeElement($media);
}
}
|
Fix the freeze functional test
|
"""Test the ``dtool dataset create`` command."""
import os
import shutil
from click.testing import CliRunner
from dtoolcore import DataSet, ProtoDataSet
from . import chdir_fixture, tmp_dir_fixture # NOQA
from . import SAMPLE_FILES_DIR
def test_dataset_freeze_functional(chdir_fixture): # NOQA
from dtool_create.dataset import create, freeze
runner = CliRunner()
dataset_name = "my_dataset"
result = runner.invoke(create, [dataset_name])
assert result.exit_code == 0
# At this point we have a proto dataset
dataset_abspath = os.path.abspath(dataset_name)
dataset_uri = "disk:{}".format(dataset_abspath)
dataset = ProtoDataSet.from_uri(dataset_uri)
# Add a file to the proto dataset.
sample_file_abspath = os.path.join(dataset_abspath, "data", "hello.txt")
with open(sample_file_abspath, "w") as fh:
fh.write("hello world")
result = runner.invoke(freeze, [dataset_uri])
assert result.exit_code == 0
# Now we have a dataset.
dataset = DataSet.from_uri(dataset_uri)
# Manifest has been updated.
assert len(dataset.identifiers) == 1
|
"""Test the ``dtool dataset create`` command."""
import os
import shutil
from click.testing import CliRunner
from dtoolcore import DataSet
from . import chdir_fixture, tmp_dir_fixture # NOQA
from . import SAMPLE_FILES_DIR
def test_dataset_freeze_functional(chdir_fixture): # NOQA
from dtool_create.dataset import freeze
runner = CliRunner()
# Create an empty dataset
dataset_name = "my_dataset"
dataset = DataSet(dataset_name, data_directory="data")
dataset.persist_to_path(".")
# Add some files to it.
dest_dir = os.path.join(".", dataset.data_directory, "sample_files")
shutil.copytree(SAMPLE_FILES_DIR, dest_dir)
# At this point the manifest has not been updated.
assert len(dataset.identifiers) == 0
result = runner.invoke(freeze, ["."])
assert result.exit_code == 0
# Manifest has been updated.
assert len(dataset.identifiers) == 2
|
Fix typo on add new layer button
|
export default {
'opacity-label': {
'tooltip': 'Видимость слоя'
},
'attributes-button': {
'tooltip': 'Показать панель атрибутов слоя'
},
'bounds-button': {
'tooltip': 'Приблизить к границам слоя'
},
'add-button': {
'tooltip': 'Добавить новый дочерний слой'
},
'copy-button': {
'tooltip': 'Создать копию слоя'
},
'edit-button': {
'tooltip': 'Редактировать настройки слоя'
},
'remove-button': {
'tooltip': 'Удалить слой'
}
};
|
export default {
'opacity-label': {
'tooltip': 'Видимость слоя'
},
'attributes-button': {
'tooltip': 'Показать панель атрибутов слоя'
},
'bounds-button': {
'tooltip': 'Приблизить к границам слоя'
},
'add-button': {
'tooltip': 'Добавить новй дочерний слой'
},
'copy-button': {
'tooltip': 'Создать копию слоя'
},
'edit-button': {
'tooltip': 'Редактировать настройки слоя'
},
'remove-button': {
'tooltip': 'Удалить слой'
}
};
|
Mark for completion after GameStartListener
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 CrystalCraftMC
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.crystalcraftmc.pvpstorm;
import org.bukkit.command.CommandExecutor;
import org.bukkit.event.Listener;
public class GameEndListener implements Listener, CommandExecutor {
// TODO Finish and test GameStartListener before working on this.
PvPStorm plugin;
public GameEndListener(PvPStorm plugin) {
this.plugin = plugin;
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 CrystalCraftMC
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.crystalcraftmc.pvpstorm;
import org.bukkit.command.CommandExecutor;
import org.bukkit.event.Listener;
public class GameEndListener implements Listener, CommandExecutor {
PvPStorm plugin;
public GameEndListener(PvPStorm plugin) {
this.plugin = plugin;
}
}
|
Make Storybook work with babel 7
|
/* eslint-disable no-param-reassign, global-require */
module.exports = baseConfig => {
// Replace storybook baseConfig rule.
baseConfig.module.rules.splice(0, 1, {
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['./babel.config.js'],
},
},
],
});
baseConfig.module.rules.push({
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]-[local]_[hash:base64:5]',
importLoaders: 1,
},
},
{
loader: 'postcss-loader',
options: {
plugins: [require('../src/theme')({ appendVariables: true })],
},
},
],
});
return baseConfig;
};
|
/* eslint-disable no-param-reassign, global-require */
module.exports = baseConfig => {
baseConfig.module.rules.push({
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]-[local]_[hash:base64:5]',
importLoaders: 1,
},
},
{
loader: 'postcss-loader',
options: {
plugins: [require('../src/theme')({ appendVariables: true })],
},
},
],
});
return baseConfig;
};
|
Fix emoji picker on firefox :ok_hand:
|
/* globals Template chatMessages*/
Template.messageBox.events({
'click .emoji-picker-icon'(event) {
event.stopPropagation();
event.preventDefault();
if (RocketChat.EmojiPicker.isOpened()) {
RocketChat.EmojiPicker.close();
} else {
RocketChat.EmojiPicker.open(event.currentTarget, (emoji) => {
console.log('test');
const {input} = chatMessages[RocketChat.openedRoom];
const emojiValue = `:${ emoji }:`;
const caretPos = input.selectionStart;
const textAreaTxt = input.value;
input.focus();
if (!document.execCommand || !document.execCommand('insertText', false, emojiValue)) {
input.value = textAreaTxt.substring(0, caretPos) + emojiValue + textAreaTxt.substring(caretPos);
}
input.focus();
input.selectionStart = caretPos + emojiValue.length;
input.selectionEnd = caretPos + emojiValue.length;
});
}
}
});
Template.messageBox.onCreated(function() {
RocketChat.EmojiPicker.init();
});
|
/* globals Template chatMessages*/
Template.messageBox.events({
'click .emoji-picker-icon'(event) {
event.stopPropagation();
event.preventDefault();
if (RocketChat.EmojiPicker.isOpened()) {
RocketChat.EmojiPicker.close();
} else {
RocketChat.EmojiPicker.open(event.currentTarget, (emoji) => {
console.log('test');
const {input} = chatMessages[RocketChat.openedRoom];
const emojiValue = `:${ emoji }:`;
const caretPos = input.selectionStart;
const textAreaTxt = input.value;
input.focus();
if (!document.execCommand || !document.execCommand('insertText', false, emojiValue)) {
// document.execCommand('insertText', false, emojiValue);
input.value = textAreaTxt.substring(0, caretPos) + emojiValue + textAreaTxt.substring(caretPos);
}
input.focus();
input.selectionStart = caretPos + emojiValue.length;
input.selectionEnd = caretPos + emojiValue.length;
});
}
}
});
Template.messageBox.onCreated(function() {
RocketChat.EmojiPicker.init();
});
|
Use exceptionMessage for the widget error page as all other error pages
|
package uk.ac.ebi.atlas.widget;
import org.springframework.dao.RecoverableDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import uk.ac.ebi.atlas.web.controllers.ResourceNotFoundException;
public abstract class HeatmapWidgetErrorHandler {
@ExceptionHandler(value = {ResourceNotFoundException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ModelAndView widgetSpecific404(Exception e) {
ModelAndView mav = new ModelAndView("widget-error");
mav.addObject("exceptionMessage", e.getMessage());
return mav;
}
@ExceptionHandler(value = {RecoverableDataAccessException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ModelAndView blah(Exception e) {
ModelAndView mav = new ModelAndView("widget-error");
mav.addObject("exceptionMessage", e.getMessage());
return mav;
}
}
|
package uk.ac.ebi.atlas.widget;
import org.springframework.dao.RecoverableDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import uk.ac.ebi.atlas.web.controllers.ResourceNotFoundException;
public abstract class HeatmapWidgetErrorHandler {
@ExceptionHandler(value = {ResourceNotFoundException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ModelAndView widgetSpecific404(Exception e) {
ModelAndView mav = new ModelAndView("widget-error");
mav.addObject("errorMessage", e.getMessage());
return mav;
}
@ExceptionHandler(value = {RecoverableDataAccessException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ModelAndView blah(Exception e) {
ModelAndView mav = new ModelAndView("widget-error");
mav.addObject("errorMessage", e.getMessage());
return mav;
}
}
|
[INTERNAL] Grunt: Disable proxy "secure" option for better local testing
As the "grunt serve" server is only intended to be used for local
testing it is fine to allow insecure connections.
Change-Id: I7141af5d6340340f27ce80ecc7413f50ee553408
|
// configure the openui5 connect server
module.exports = function(grunt, config) {
// libraries are sorted alphabetically
var aLibraries = config.allLibraries.slice();
aLibraries.sort(function(a, b) {
return a.name.localeCompare(b.name);
});
var openui5_connect = {
options: {
contextpath: config.testsuite.name,
proxypath: 'proxy',
proxyOptions: {
secure: false
},
cors: {
origin: "*"
}
},
src: {
options: {
appresources: config.testsuite.path + '/src/main/webapp',
resources: aLibraries.map(function(lib) {
return lib.path + '/src';
}),
testresources: aLibraries.map(function(lib) {
return lib.path + '/test';
})
}
},
target: {
options: {
appresources: 'target/openui5-testsuite',
resources: aLibraries.map(function(lib) {
return 'target/openui5-' + lib.name + '/resources';
}),
testresources: aLibraries.map(function(lib) {
return 'target/openui5-' + lib.name + '/test-resources';
})
}
}
};
return openui5_connect;
};
|
// configure the openui5 connect server
module.exports = function(grunt, config) {
// libraries are sorted alphabetically
var aLibraries = config.allLibraries.slice();
aLibraries.sort(function(a, b) {
return a.name.localeCompare(b.name);
});
var openui5_connect = {
options: {
contextpath: config.testsuite.name,
proxypath: 'proxy',
cors: {
origin: "*"
}
},
src: {
options: {
appresources: config.testsuite.path + '/src/main/webapp',
resources: aLibraries.map(function(lib) {
return lib.path + '/src';
}),
testresources: aLibraries.map(function(lib) {
return lib.path + '/test';
})
}
},
target: {
options: {
appresources: 'target/openui5-testsuite',
resources: aLibraries.map(function(lib) {
return 'target/openui5-' + lib.name + '/resources';
}),
testresources: aLibraries.map(function(lib) {
return 'target/openui5-' + lib.name + '/test-resources';
})
}
}
};
return openui5_connect;
};
|
Add latest version of PnetCDF
|
from spack import *
class ParallelNetcdf(Package):
"""Parallel netCDF (PnetCDF) is a library providing high-performance
parallel I/O while still maintaining file-format compatibility with
Unidata's NetCDF."""
homepage = "https://trac.mcs.anl.gov/projects/parallel-netcdf"
url = "http://cucis.ece.northwestern.edu/projects/PnetCDF/Release/parallel-netcdf-1.6.1.tar.gz"
version('1.7.0', '267eab7b6f9dc78c4d0e6def2def3aea4bc7c9f0')
version('1.6.1', '62a094eb952f9d1e15f07d56e535052604f1ac34')
depends_on("m4")
depends_on("mpi")
def install(self, spec, prefix):
configure("--prefix=%s" % prefix,
"--with-mpi=%s" % spec['mpi'].prefix)
make()
make("install")
|
from spack import *
class ParallelNetcdf(Package):
"""Parallel netCDF (PnetCDF) is a library providing high-performance
parallel I/O while still maintaining file-format compatibility with
Unidata's NetCDF."""
homepage = "https://trac.mcs.anl.gov/projects/parallel-netcdf"
url = "http://cucis.ece.northwestern.edu/projects/PnetCDF/Release/parallel-netcdf-1.6.1.tar.gz"
version('1.6.1', '62a094eb952f9d1e15f07d56e535052604f1ac34')
depends_on("m4")
depends_on("mpi")
def install(self, spec, prefix):
configure("--prefix=%s" % prefix,
"--with-mpi=%s" % spec['mpi'].prefix)
make()
make("install")
|
Revise docstring & comment, reduce redundant for loop
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(nums):
"""Selection sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from pos=n-1,..1, select next max num to swap with its num.
for i in reversed(range(1, len(nums))):
i_max = 0
for j in range(1, i + 1):
if nums[j] > nums[i_max]:
i_max = j
nums[i_max], nums[i] = nums[i], nums[i_max]
def main():
nums = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('By selection sort: ')
selection_sort(nums)
print(nums)
if __name__ == '__main__':
main()
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(nums):
"""Selection Sort algortihm.
Time complexity: O(n^2).
Space complexity: O(1).
"""
# Start from the last num, select next max num to swap.
for i in reversed(range(len(nums))):
i_max = 0
for j in range(1, i + 1):
if nums[j] > nums[i_max]:
i_max = j
nums[i_max], nums[i] = nums[i], nums[i_max]
def main():
nums = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('By selection sort: ')
selection_sort(nums)
print(nums)
if __name__ == '__main__':
main()
|
Update author to CSC - IT Center for Science Ltd.
|
from setuptools import setup, find_packages
version = '0.2'
setup(
name='ckanext-oaipmh',
version=version,
description="OAI-PMH harvester for CKAN",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='CSC - IT Center for Science Ltd.',
author_email='kata-project@postit.csc.fi',
url='https://github.com/kata-csc/ckanext-oaipmh',
license='AGPL',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=['ckanext', 'ckanext.oaipmh'],
include_package_data=True,
zip_safe=False,
install_requires=[
# -*- Extra requirements: -*-
'pyoai',
'ckanext-harvest',
'lxml',
'rdflib',
'beautifulsoup4',
'pointfree',
'functionally',
'fn',
],
entry_points=\
"""
[ckan.plugins]
# Add plugins here, eg
oaipmh_harvester=ckanext.oaipmh.harvester:OAIPMHHarvester
""",
)
|
from setuptools import setup, find_packages
version = '0.2'
setup(
name='ckanext-oaipmh',
version=version,
description="OAI-PMH harvester for CKAN",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Mikael Karlsson',
author_email='i8myshoes@gmail.com',
url='https://github.com/kata-csc/ckanext-oaipmh',
license='AGPL',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
namespace_packages=['ckanext', 'ckanext.oaipmh'],
include_package_data=True,
zip_safe=False,
install_requires=[
# -*- Extra requirements: -*-
'pyoai',
'ckanext-harvest',
'lxml',
'rdflib',
'beautifulsoup4',
'pointfree',
'functionally',
'fn',
],
entry_points=\
"""
[ckan.plugins]
# Add plugins here, eg
oaipmh_harvester=ckanext.oaipmh.harvester:OAIPMHHarvester
""",
)
|
Load environment variable first in express app
|
// Load environment variables
if (process.env.NODE_ENV !== 'integration') {
require('dotenv').config({ path: './env/.env' });
}
var express = require('express');
var passport = require('passport');
var util = require('./lib/utility.js');
var app = express();
// Initial Configuration, Static Assets, & View Engine Configuration
require('./config/initialize.js')(app, express);
// Authentication Middleware: Express Sessions, Passport Strategy
require('./config/auth.js')(app, express, passport);
// Pre-Authentication Routes & OAuth Requests
require('./routes/auth-routes.js')(app, passport);
//Authentication check currently commented out, uncomment line to re-activate
app.use(util.ensureAuthenticated);
// View Routes
require('./routes/view-routes.js')(app);
// API Routes
// require('./routes/api-routes.js')(app);
// Wildcard route
app.get('/*', function(req, res) {
res.redirect('/');
})
app.listen(Number(process.env.PORT), process.env.HOST, function() {
console.log(process.env.APP_NAME + ' is listening at ' + process.env.HOST + ' on port ' + process.env.PORT + '.')
});
|
var express = require('express');
var passport = require('passport');
var util = require('./lib/utility.js');
// Load environment variables
if (process.env.NODE_ENV !== 'integration') {
require('dotenv').config({ path: './env/.env' });
}
var app = express();
// Initial Configuration, Static Assets, & View Engine Configuration
require('./config/initialize.js')(app, express);
// Authentication Middleware: Express Sessions, Passport Strategy
require('./config/auth.js')(app, express, passport);
// Pre-Authentication Routes & OAuth Requests
require('./routes/auth-routes.js')(app, passport);
//Authentication check currently commented out, uncomment line to re-activate
app.use(util.ensureAuthenticated);
// View Routes
require('./routes/view-routes.js')(app);
// API Routes
// require('./routes/api-routes.js')(app);
// Wildcard route
app.get('/*', function(req, res) {
res.redirect('/');
})
app.listen(Number(process.env.PORT), process.env.HOST, function() {
console.log(process.env.APP_NAME + ' is listening at ' + process.env.HOST + ' on port ' + process.env.PORT + '.')
});
|
Support for shortcodes to transform block content
|
<?php
namespace WordpressLib\Editor\Block;
class Block {
public function __construct($pluginSlug, $blockSlug, $frontAssets, $editorAssets) {
$this->pluginSlug = $pluginSlug;
$this->blockSlug = $blockSlug;
$this->frontAssets = $frontAssets;
$this->editorAssets = $editorAssets;
add_action('init', [$this, 'register']);
}
protected function createSettings() {
$ed_js_handle = $this->editorAssets->js("block-editor/blocks/$this->blockSlug", ['wp-blocks','wp-element','wp-editor'], FALSE);
$ed_css_handle = $this->editorAssets->css("block-editor/blocks/$this->blockSlug", [], FALSE);
$fr_css_handle = $this->frontAssets->css("block-editor/blocks/$this->blockSlug", [], FALSE);
return [
'editor_script' => $ed_js_handle,
'editor_style' => $ed_css_handle,
'style' => $fr_css_handle,
];
}
public function registerShortcode() {
add_filter('the_content', [$this, 'contentToShortcode'], -10);
}
public function register() {
register_block_type("$this->pluginSlug/$this->blockSlug", $this->createSettings());
if (method_exists($this, 'contentToShortcode') && !is_admin()) $this->registerShortcode();
}
}
|
<?php
namespace WordpressLib\Editor\Block;
class Block {
public function __construct($pluginSlug, $blockSlug, $frontAssets, $editorAssets) {
$this->pluginSlug = $pluginSlug;
$this->blockSlug = $blockSlug;
$this->frontAssets = $frontAssets;
$this->editorAssets = $editorAssets;
add_action('init', [$this, 'register']);
}
protected function createSettings() {
$ed_js_handle = $this->editorAssets->js("block-editor/blocks/$this->blockSlug", ['wp-blocks','wp-element','wp-editor'], FALSE);
$ed_css_handle = $this->editorAssets->css("block-editor/blocks/$this->blockSlug", [], FALSE);
$fr_css_handle = $this->frontAssets->css("block-editor/blocks/$this->blockSlug", [], FALSE);
return [
'editor_script' => $ed_js_handle,
'editor_style' => $ed_css_handle,
'style' => $fr_css_handle,
];
}
public function register() {
register_block_type("$this->pluginSlug/$this->blockSlug", $this->createSettings());
}
}
|
Add a dependency on healpy
|
#!/usr/bin/env python
import os
from numpy.distutils.core import setup, Extension
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
wrapper = Extension('fortran_routines',
sources=['src/fortran_routines.f90'],
extra_f90_compile_args=["-std=f2003"])
setup(name='stripsim',
version='0.1',
description='A simulation pipeline for the LSPE/Strip instrument',
author='Maurizio Tomasi',
author_email='maurizio.tomasi@unimi.it',
license='MIT',
url='https://github.com/ziotom78/stripsim',
long_description=read('README.md'),
py_modules=['src/stripsim'],
install_requires=['healpy', 'pyyaml'],
ext_modules=[wrapper]
)
|
#!/usr/bin/env python
import os
from numpy.distutils.core import setup, Extension
# Utility function to read the README file.
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
wrapper = Extension('fortran_routines',
sources=['src/fortran_routines.f90'],
extra_f90_compile_args=["-std=f2003"])
setup(name='stripsim',
version='0.1',
description='A simulation pipeline for the LSPE/Strip instrument',
author='Maurizio Tomasi',
author_email='maurizio.tomasi@unimi.it',
license='MIT',
url='https://github.com/ziotom78/stripsim',
long_description=read('README.md'),
py_modules=['src/stripsim'],
install_requires=['pyyaml'],
ext_modules=[wrapper]
)
|
Add option to download via SSH
|
# 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.
"""\
Usage:
gh_user_download [-s] <who> <where>
gh_user_download -h | --help
Options:
-s, --ssh Checks out via ssh
"""
from __future__ import print_function
import os
from pygithub3 import Github
from docopt import docopt
def main():
arguments = docopt(__doc__, version="1.0")
who = arguments['<who>']
where = arguments['<where>']
ssh = arguments['--ssh']
gh = Github()
repos = gh.repos.list(who).all()
for repo in repos:
if ssh:
url = 'git@github.com:' + who + '/' + repo.name
else:
url = repo.git_url
path = os.path.join(where, repo.name)
print(url, 'to', path)
os.system('git clone ' + url + ' ' + path)
if __name__ == '__main__':
main()
|
# 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.
"""\
Usage:
gh_user_download <who> <where>
gh_user_download -h | --help
"""
from __future__ import print_function
import os
from pygithub3 import Github
from docopt import docopt
def main():
arguments = docopt(__doc__, version="testing")
who = arguments['<who>']
where = arguments['<where>']
gh = Github()
repos = gh.repos.list(who).all()
for repo in repos:
url = repo.git_url
print(url, 'to', os.path.join(where, repo.name))
os.system('git clone ' + url + ' ' + os.path.join(where, repo.name))
if __name__ == '__main__':
main()
|
Use _super.methodName instead of bare super.
Older versions of ember-cli do not support invoking _super as an argument (yet all versions that I am aware of support this syntax).
|
/* jshint node: true */
'use strict';
var path = require('path');
var replace = require('broccoli-string-replace');
var mergeTrees = require('broccoli-merge-trees');
var Funnel = require('broccoli-funnel');
module.exports = {
name: 'lodash',
_shouldCompileJS: function() {
return true;
},
treeForAddon: function(tree) {
var lodashPath = path.dirname(require.resolve('lodash-es'));
let lodashTree = replace(lodashPath, {
files: [ '*.js' ],
pattern: {
match: /\.js/g,
replacement: ''
}
});
lodashTree = new Funnel(lodashTree, {
getDestinationPath: function(path) {
if (path === 'lodash.js') {
return 'index.js';
}
return path;
}
});
lodashTree = replace(lodashTree, {
files: [ '_getNative.js' ],
pattern: {
match: /undefined/g,
replacement: 'null'
}
});
if (tree) {
tree = mergeTrees([lodashTree, tree], {
overwrite: true
});
} else {
tree = lodashTree;
}
return this._super.treeForAddon.call(this, tree);
}
};
|
/* jshint node: true */
'use strict';
var path = require('path');
var replace = require('broccoli-string-replace');
var mergeTrees = require('broccoli-merge-trees');
var Funnel = require('broccoli-funnel');
module.exports = {
name: 'lodash',
_shouldCompileJS: function() {
return true;
},
treeForAddon: function(tree) {
var lodashPath = path.dirname(require.resolve('lodash-es'));
let lodashTree = replace(lodashPath, {
files: [ '*.js' ],
pattern: {
match: /\.js/g,
replacement: ''
}
});
lodashTree = new Funnel(lodashTree, {
getDestinationPath: function(path) {
if (path === 'lodash.js') {
return 'index.js';
}
return path;
}
});
lodashTree = replace(lodashTree, {
files: [ '_getNative.js' ],
pattern: {
match: /undefined/g,
replacement: 'null'
}
});
if (tree) {
tree = mergeTrees([lodashTree, tree], {
overwrite: true
});
} else {
tree = lodashTree;
}
return this._super(tree);
}
};
|
Make string example a bit less confusing
|
import collections
import collections.abc
def strings_have_format_map_method():
"""
As of Python 3.2 you can use the .format_map() method on a string object
to use mapping objects (not just builtin dictionaries) when formatting
a string.
"""
class Default(dict):
def __missing__(self, key):
return key
print("This prints key1 and key2: {key1} and {key2}".format_map(Default(key1="key1")))
mapping = collections.defaultdict(int, a=2)
print("This prints the value 2000: {a}{b}{c}{d}".format_map(mapping))
class MyMapping(collections.abc.Mapping):
def __init__(self):
self._data = {'a': 'A', 'b': 'B', 'c': 'C'}
def __getitem__(self, key):
return self._data[key]
def __len__(self):
return len(self._data)
def __iter__(self):
for item in self._data:
yield item
mapping = MyMapping()
print("This prints ABC: {a}{b}{c}".format_map(mapping))
|
import collections
import collections.abc
def strings_have_format_map_method():
"""
As of Python 3.2 you can use the .format_map() method on a string object
to use mapping objects (not just builtin dictionaries) when formatting
a string.
"""
class Default(dict):
def __missing__(self, key):
return key
print("This prints the keys: {a} {key2}".format_map(Default(a="key1")))
mapping = collections.defaultdict(int, a=2)
print("This prints the value 2000: {a}{b}{c}{d}".format_map(mapping))
class MyMapping(collections.abc.Mapping):
def __init__(self):
self._data = {'a': 'A', 'b': 'B', 'c': 'C'}
def __getitem__(self, key):
return self._data[key]
def __len__(self):
return len(self._data)
def __iter__(self):
for item in self._data:
yield item
mapping = MyMapping()
print("This prints ABC: {a}{b}{c}".format_map(mapping))
|
Disable keyboard shortcuts when editing input field
|
window.GLOBAL_ACTIONS = {
'play': function () {
wavesurfer.playPause();
},
'back': function () {
wavesurfer.skipBackward();
},
'forth': function () {
wavesurfer.skipForward();
},
'toggle-mute': function () {
wavesurfer.toggleMute();
}
};
// Bind actions to buttons and keypresses
document.addEventListener('DOMContentLoaded', function () {
document.addEventListener('keydown', function (e) {
var map = {
32: 'play', // space
37: 'back', // left
39: 'forth' // right
};
if(e.target.nodeName.toLowerCase() === 'input'){
return;
}
var action = map[e.keyCode];
if (action in GLOBAL_ACTIONS) {
e.preventDefault();
GLOBAL_ACTIONS[action](e);
}
});
[].forEach.call(document.querySelectorAll('[data-action]'), function (el) {
el.addEventListener('click', function (e) {
var action = e.currentTarget.dataset.action;
if (action in GLOBAL_ACTIONS) {
e.preventDefault();
GLOBAL_ACTIONS[action](e);
}
});
});
});
|
window.GLOBAL_ACTIONS = {
'play': function () {
wavesurfer.playPause();
},
'back': function () {
wavesurfer.skipBackward();
},
'forth': function () {
wavesurfer.skipForward();
},
'toggle-mute': function () {
wavesurfer.toggleMute();
}
};
// Bind actions to buttons and keypresses
document.addEventListener('DOMContentLoaded', function () {
document.addEventListener('keydown', function (e) {
var map = {
32: 'play', // space
37: 'back', // left
39: 'forth' // right
};
var action = map[e.keyCode];
if (action in GLOBAL_ACTIONS) {
e.preventDefault();
GLOBAL_ACTIONS[action](e);
}
});
[].forEach.call(document.querySelectorAll('[data-action]'), function (el) {
el.addEventListener('click', function (e) {
var action = e.currentTarget.dataset.action;
if (action in GLOBAL_ACTIONS) {
e.preventDefault();
GLOBAL_ACTIONS[action](e);
}
});
});
});
|
Change version 1.1.2 to 1.1.3
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__author__ = 'Takahiro Ikeuchi'
setup(
name="slackpy",
version="1.1.3",
py_modules=['slackpy'],
package_dir={'': 'slackpy'},
install_requires=open('requirements.txt').read().splitlines(),
description="Simple Slack client library",
long_description=open('README.txt').read(),
author='Takahiro Ikeuchi',
author_email='takahiro.ikeuchi@gmail.com',
url='https://github.com/iktakahiro/slackpy',
keywords=["Slack", "Slack Client"],
license='MIT',
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.4",
"Topic :: System :: Logging",
"Topic :: Communications :: Chat"
],
entry_points={
"console_scripts": [
"slackpy=slackpy:main",
],
},
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
__author__ = 'Takahiro Ikeuchi'
setup(
name="slackpy",
version="1.1.2",
py_modules=['slackpy'],
package_dir={'': 'slackpy'},
install_requires=open('requirements.txt').read().splitlines(),
description="Simple Slack client library",
long_description=open('README.txt').read(),
author='Takahiro Ikeuchi',
author_email='takahiro.ikeuchi@gmail.com',
url='https://github.com/iktakahiro/slackpy',
keywords=["Slack", "Slack Client"],
license='MIT',
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3.4",
"Topic :: System :: Logging",
"Topic :: Communications :: Chat"
],
entry_points={
"console_scripts": [
"slackpy=slackpy:main",
],
},
)
|
Fix: Check if url is defined
|
'use strict';
/**
* @ngdoc filter
* @name SubSnoopApp.filter:isImage
* @function
* @description
* # isContent
* Filter in the SubSnoopApp.
*/
angular.module('SubSnoopApp')
.filter('isContent', function () {
/*
Returns true if url is a format ending in png, jpg, or gif
*/
function isImage(url) {
var formats = ['.png', '.jpg', '.gif'];
if (url) {
for (var i = 0; i < formats.length; i++) {
var format = formats[i];
if (url.indexOf(format) >= 0) {
return true;
}
}
}
return false;
}
/*
Checks whether the content of a submission post has valid data
- Selftext_html/html: For self posts
- Media: For posts with embedded html, e.g. Youtube videos
- Preview: For link posts with attached images
- Spoiler posts can also contain images, therefore also check if the url is an image
*/
return function (input) {
return input.selftext_html || input.html || input.media || input.preview || isImage(input.url);
};
});
|
'use strict';
/**
* @ngdoc filter
* @name SubSnoopApp.filter:isImage
* @function
* @description
* # isContent
* Filter in the SubSnoopApp.
*/
angular.module('SubSnoopApp')
.filter('isContent', function () {
/*
Returns true if url is a format ending in png, jpg, or gif
*/
function isImage(url) {
var formats = ['.png', '.jpg', '.gif'];
for (var i = 0; i < formats.length; i++) {
var format = formats[i];
if (url.indexOf(format) >= 0) {
return true;
}
}
return false;
}
/*
Checks whether the content of a submission post has valid data
- Selftext_html/html: For self posts
- Media: For posts with embedded html, e.g. Youtube videos
- Preview: For link posts with attached images
- Spoiler posts can also contain images, therefore also check if the url is an image
*/
return function (input) {
return input.selftext_html || input.html || input.media || input.preview || isImage(input.url);
};
});
|
Tools: Add --list to variable tool.
|
#!/usr/bin/env python
import sys
sys.path.append('..')
from cli import *
from optparse import OptionParser
parse = OptionParser()
parse.add_option('-a', '--variable', dest='variables',
help='Add variable',
default=[], action='append', type=str)
parse.add_option('-r', '--random', dest='randoms',
help='Add random (is_var=0)',
default=[], action='append', type=str)
parse.add_option('-l', '--list', dest='list_vars',
default=False, action='store_true')
o = parse.parse_args()[0]
if o.list_vars:
vars = session.query(Variable).all()
for x in vars:
print x
exit()
for var in o.variables:
exists = session.query(Variable).filter(Variable.name == var).first()
if exists is not None:
print '%s already exists!' % var
exit()
v = Variable(var, 1)
session.add(v)
for var in o.randoms:
exists = session.query(Variable).filter(Variable.name == var).first()
if exists is not None:
print '%s already exists!' % var
exit()
v = Variable(var, 0)
session.add(v)
session.commit()
|
#!/usr/bin/env python
import sys
sys.path.append('..')
from cli import *
from optparse import OptionParser
parse = OptionParser()
parse.add_option('-a', '--variable', dest='variables',
help='Add variable',
default=[], action='append', type=str)
parse.add_option('-r', '--random', dest='randoms',
help='Add random (is_var=0)',
default=[], action='append', type=str)
o = parse.parse_args()[0]
for var in o.variables:
exists = session.query(Variable).filter(Variable.name == var).first()
if exists is not None:
print '%s already exists!' % var
exit()
v = Variable(var, 1)
session.add(v)
for var in o.randoms:
exists = session.query(Variable).filter(Variable.name == var).first()
if exists is not None:
print '%s already exists!' % var
exit()
v = Variable(var, 0)
session.add(v)
session.commit()
|
Fix the unknown entity type test
We want to check if any user-supplied entity name is unkown, not if any
of the known types are not in the user-supplied list
|
import argparse
from .schema import SCHEMA
def reindex(args):
known_entities = SCHEMA.keys()
if args['entities'] is not None:
entities = []
for e in args['entities']:
entities.extend(e.split(','))
unknown_entities = set(entities) - set(known_entities)
if unknown_entities:
raise ValueError("{0} are unkown entity types".format(unknown_entities))
else:
entities = known_entities
print(entities)
def watch(args):
raise NotImplementedError
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
reindex_parser = subparsers.add_parser("reindex", help="Reindexes all or a single entity type")
reindex_parser.set_defaults(func=reindex)
reindex_parser.add_argument('--entities', action='append', help='The entities to reindex' )
watch_parser = subparsers.add_parser("watch", help="Watches for incoming messages on an AMQP queue")
watch_parser.set_defaults(func=watch)
args = parser.parse_args()
args.func(vars(args))
if __name__ == '__main__':
main()
|
import argparse
from .schema import SCHEMA
def reindex(args):
known_entities = SCHEMA.keys()
if args['entities'] is not None:
entities = []
for e in args['entities']:
entities.extend(e.split(','))
unknown_entities = set(known_entities) - set(entities)
if unknown_entities:
raise ValueError("{0} are unkown entity types".format(unknown_entities))
else:
entities = known_entities
print(entities)
def watch(args):
raise NotImplementedError
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
reindex_parser = subparsers.add_parser("reindex", help="Reindexes all or a single entity type")
reindex_parser.set_defaults(func=reindex)
reindex_parser.add_argument('--entities', action='append', help='The entities to reindex' )
watch_parser = subparsers.add_parser("watch", help="Watches for incoming messages on an AMQP queue")
watch_parser.set_defaults(func=watch)
args = parser.parse_args()
args.func(vars(args))
if __name__ == '__main__':
main()
|
Clear the operator default engines before running operator tests
Reviewed By: akyrola
Differential Revision: D5729024
fbshipit-source-id: f2850d5cf53537b22298b39a07f64dfcc2753c75
|
## @package test_util
# Module caffe2.python.test_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import core, workspace
import unittest
def rand_array(*dims):
# np.random.rand() returns float instead of 0-dim array, that's why need to
# do some tricks
return np.array(np.random.rand(*dims) - 0.5).astype(np.float32)
class TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
])
# clear the default engines settings to separate out its
# affect from the ops tests
core.SetEnginePref({}, {})
def setUp(self):
self.ws = workspace.C.Workspace()
workspace.ResetWorkspace()
def tearDown(self):
workspace.ResetWorkspace()
|
## @package test_util
# Module caffe2.python.test_util
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from caffe2.python import workspace
import unittest
def rand_array(*dims):
# np.random.rand() returns float instead of 0-dim array, that's why need to
# do some tricks
return np.array(np.random.rand(*dims) - 0.5).astype(np.float32)
class TestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
workspace.GlobalInit([
'caffe2',
'--caffe2_log_level=0',
])
def setUp(self):
self.ws = workspace.C.Workspace()
workspace.ResetWorkspace()
def tearDown(self):
workspace.ResetWorkspace()
|
Make single post thumbnail bigger
on single post pages
|
<article <?php post_class(); ?>>
<header class="mt-15">
<!-- Displays the title of the post without a link -->
<h1 class="entry-title"><?php the_title(); ?></h1>
</header>
<div class="entry-content">
<!-- Displays the content of the current post -->
<?php the_content(); ?>
<!-- Displays the post thumbnail in the 'medium' format -->
<?php the_post_thumbnail('large'); ?>
</div>
<aside class="entry-navigation clearfix">
<!-- Buttons to navigate to the previous and next posts -->
<?php
previous_post_link('<span class="button button-border prev-post">%link</span>', '<strong>Previous Post</strong><br/>');
next_post_link('<span class="button button-border next-post">%link</span>', '<strong>Next Post</strong>');
?>
</aside>
</article>
|
<article <?php post_class(); ?>>
<header class="mt-15">
<!-- Displays the title of the post without a link -->
<h1 class="entry-title"><?php the_title(); ?></h1>
</header>
<div class="entry-content">
<!-- Displays the content of the current post -->
<?php the_content(); ?>
<!-- Displays the post thumbnail in the 'medium' format -->
<?php the_post_thumbnail('medium'); ?>
</div>
<aside class="entry-navigation clearfix">
<!-- Buttons to navigate to the previous and next posts -->
<?php
previous_post_link('<span class="button button-border prev-post">%link</span>', '<strong>Previous Post</strong><br/>');
next_post_link('<span class="button button-border next-post">%link</span>', '<strong>Next Post</strong>');
?>
</aside>
</article>
|
Replace empty list creation with Collections.emptyList()
|
package com.alexrnl.subtitlecorrector.correctionstrategy;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;
import com.alexrnl.subtitlecorrector.service.SessionParameters;
/**
* Abstract strategy implementation.<br />
* Provide a basic body for the actual strategies. There is no logic in this class.
* @author Alex
*/
public abstract class AbstractStrategy implements Strategy {
/** Logger */
private static final Logger LG = Logger.getLogger(AbstractStrategy.class.getName());
@Override
public void startSession (final SessionParameters parameters) {
// Nothing to do here, override if strategy depends on session state
}
@Override
public void stopSession () {
// Nothing to do here, override if strategy depends on session state
}
@Override
public List<Parameter<?>> getParameters () {
return Collections.emptyList();
}
@Override
public Parameter<?> getParameterByName (final String name) {
Objects.requireNonNull(name);
for (final Parameter<?> parameter : getParameters()) {
if (parameter.getDescription().equals(name)) {
return parameter;
}
}
LG.info("No parameter with name " + name + " found");
return null;
}
}
|
package com.alexrnl.subtitlecorrector.correctionstrategy;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.logging.Logger;
import com.alexrnl.subtitlecorrector.service.SessionParameters;
/**
* Abstract strategy implementation.<br />
* Provide a basic body for the actual strategies. There is no logic in this class.
* @author Alex
*/
public abstract class AbstractStrategy implements Strategy {
/** Logger */
private static final Logger LG = Logger.getLogger(AbstractStrategy.class.getName());
@Override
public void startSession (final SessionParameters parameters) {
// Nothing to do here, override if strategy depends on session state
}
@Override
public void stopSession () {
// Nothing to do here, override if strategy depends on session state
}
@Override
public List<Parameter<?>> getParameters () {
return new ArrayList<>(0);
}
@Override
public Parameter<?> getParameterByName (final String name) {
Objects.requireNonNull(name);
for (final Parameter<?> parameter : getParameters()) {
if (parameter.getDescription().equals(name)) {
return parameter;
}
}
LG.info("No parameter with name " + name + " found");
return null;
}
}
|
[API][Cart] Add token value based cart context
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Order\Repository;
use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
interface OrderRepositoryInterface extends RepositoryInterface
{
public function countPlacedOrders(): int;
/**
* @return array|OrderInterface[]
*/
public function findLatest(int $count): array;
public function findLatestCart(): ?OrderInterface;
public function findOneByNumber(string $number): ?OrderInterface;
public function findOneByTokenValue(string $tokenValue): ?OrderInterface;
public function findCartByTokenValue(string $tokenValue): ?OrderInterface;
public function findCartById($id): ?OrderInterface;
/**
* @return array|OrderInterface[]
*/
public function findCartsNotModifiedSince(\DateTimeInterface $terminalDate): array;
public function createCartQueryBuilder(): QueryBuilder;
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Order\Repository;
use Doctrine\ORM\QueryBuilder;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
interface OrderRepositoryInterface extends RepositoryInterface
{
public function countPlacedOrders(): int;
/**
* @return array|OrderInterface[]
*/
public function findLatest(int $count): array;
public function findLatestCart(): ?OrderInterface;
public function findOneByNumber(string $number): ?OrderInterface;
public function findOneByTokenValue(string $tokenValue): ?OrderInterface;
public function findCartById($id): ?OrderInterface;
/**
* @return array|OrderInterface[]
*/
public function findCartsNotModifiedSince(\DateTimeInterface $terminalDate): array;
public function createCartQueryBuilder(): QueryBuilder;
}
|
Add new test for all classes
|
package org.verapdf.model.impl;
import org.junit.Assert;
import org.junit.Test;
import org.verapdf.model.ModelHelper;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
* @author Evgeniy Muravitskiy
*/
public abstract class BaseTest {
protected static org.verapdf.model.baselayer.Object actual;
protected static String expectedType;
protected static String expectedID;
@Test
public void testTypeAndID() {
Assert.assertEquals(expectedType, actual.getType());
Assert.assertEquals(expectedID, actual.getID());
}
@Test
public void testLinksMethod() {
List<String> expectedLinks = ModelHelper.getListOfLinks(actual.getType());
for (String link : expectedLinks) {
Assert.assertNotNull(actual.getLinkedObjects(link));
}
expectedLinks.clear();
}
@Test(expected = IllegalAccessError.class)
public void testNonexistentParentLink() {
actual.getLinkedObjects("Wrong link.");
}
protected static String getSystemIndependentPath(String path) throws URISyntaxException {
URL resourceUrl = ClassLoader.class.getResource(path);
Path resourcePath = Paths.get(resourceUrl.toURI());
return resourcePath.toString();
}
}
|
package org.verapdf.model.impl;
import org.junit.Assert;
import org.junit.Test;
import org.verapdf.model.ModelHelper;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
* @author Evgeniy Muravitskiy
*/
public abstract class BaseTest {
protected static org.verapdf.model.baselayer.Object actual;
protected static String TYPE;
protected static String ID;
@Test
public void testTypeAndID() {
Assert.assertEquals(TYPE, actual.getType());
Assert.assertEquals(ID, actual.getID());
}
@Test
public void testLinksMethod() {
List<String> expectedLinks = ModelHelper.getListOfLinks(actual.getType());
for (String link : expectedLinks) {
Assert.assertNotNull(actual.getLinkedObjects(link));
}
expectedLinks.clear();
}
protected static String getSystemIndependentPath(String path) throws URISyntaxException {
URL resourceUrl = ClassLoader.class.getResource(path);
Path resourcePath = Paths.get(resourceUrl.toURI());
return resourcePath.toString();
}
}
|
Add service to retrieve list of Applications by team
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.repository.api;
import io.gravitee.repository.model.Application;
import java.util.Optional;
import java.util.Set;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface ApplicationRepository {
Set<Application> findAll();
Set<Application> findByTeam(String teamName);
Set<Application> findByUser(String username);
Application create(Application application);
Application update(Application application);
Optional<Application> findByName(String applicationName);
void delete(String apiName);
int countByUser(String username);
int countByTeam(String teamName);
}
|
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.repository.api;
import io.gravitee.repository.model.Application;
import java.util.Optional;
import java.util.Set;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public interface ApplicationRepository {
Set<Application> findAll();
Set<Application> findByUser(String username);
Application create(Application application);
Application update(Application application);
Optional<Application> findByName(String applicationName);
void delete(String apiName);
int countByUser(String username);
int countByTeam(String teamName);
}
|
Add reminder to myself to to importlib fallback.
|
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
# TODO: When Python 2.7 is released this becomes a try/except falling
# back to Django's implementation.
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
|
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.core.exceptions.ImproperlyConfigured`` if the specified
backend cannot be located.
"""
i = settings.REGISTRATION_BACKEND.rfind('.')
module, attr = settings.REGISTRATION_BACKEND[:i], settings.REGISTRATION_BACKEND[i+1:]
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured('Error loading registration backend %s: "%s"' % (module, e))
try:
backend_class = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a registration backend named "%s"' % (module, attr))
return backend_class()
|
Add max Memory to statitic collector
|
package org.csstudio.platform.statistic;
import org.csstudio.platform.logging.CentralLogger;
public class BackgroundCollectorThread extends Thread{
private int timeout = 0;
private boolean runForever = true;
final static double MB = 1024.0*1024.0;
BackgroundCollectorThread ( int timeout) {
this.timeout = timeout;
CentralLogger.getInstance().info(this, "BackgroundCollectorThread started");
this.start();
}
public void run() {
while (runForever) {
BackgroundCollector.getInstance().getMemoryAvailableApplication().setValue( new Double(Runtime.getRuntime().freeMemory()/MB));
BackgroundCollector.getInstance().getMemoryUsedApplication().setValue( new Double(Runtime.getRuntime().totalMemory()/MB));
BackgroundCollector.getInstance().getMemoryUsedSystem().setValue( new Double(Runtime.getRuntime().maxMemory()/MB));
// TODO: find out how to fill these!
// before uncommenting: enable instanciating in BackgroundCollector!!
// BackgroundCollector.getInstance().getCpuUsedApplication().setValue
// BackgroundCollector.getInstance().getCpuUsedSystem().setValue
try {
Thread.sleep(this.timeout);
} catch (InterruptedException e) {
// TODO: handle exception
} finally {
//clean up
}
}
CentralLogger.getInstance().info(this, "BackgroundCollectorThread stopped");
}
}
|
package org.csstudio.platform.statistic;
import org.csstudio.platform.logging.CentralLogger;
public class BackgroundCollectorThread extends Thread{
private int timeout = 0;
private boolean runForever = true;
BackgroundCollectorThread ( int timeout) {
this.timeout = timeout;
CentralLogger.getInstance().info(this, "BackgroundCollectorThread started");
this.start();
}
public void run() {
while (runForever) {
BackgroundCollector.getInstance().getMemoryAvailableApplication().setValue( new Double(Runtime.getRuntime().totalMemory()/1000.0));
BackgroundCollector.getInstance().getMemoryUsedApplication().setValue( new Double(Runtime.getRuntime().maxMemory()/1000.0));
// TODO: find out how to fill these!
// before uncommenting: enable instanciating in BackgroundCollector!!
// BackgroundCollector.getInstance().getCpuUsedApplication().setValue
// BackgroundCollector.getInstance().getCpuUsedSystem().setValue
// BackgroundCollector.getInstance().getMemoryUsedSystem().setValue
try {
Thread.sleep(this.timeout);
} catch (InterruptedException e) {
// TODO: handle exception
} finally {
//clean up
}
}
CentralLogger.getInstance().info(this, "BackgroundCollectorThread stopped");
}
}
|
Fix passing of params to optimizer in Softmax
|
from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
@describe.attributes(
W=Synapses("Weights matrix",
lambda obj: (obj.nO, obj.nI),
lambda W, ops: None)
)
class Softmax(Affine):
name = 'softmax'
def predict(self, input__BI):
output__BO = self.ops.affine(self.W, self.b, input__BI)
self.ops.softmax(output__BO, inplace=True)
return output__BO
def begin_update(self, input__BI, drop=0.):
output__BO = self.predict(input__BI)
def finish_update(grad__BO, sgd=None):
self.d_W += self.ops.batch_outer(grad__BO, input__BI)
self.d_b += grad__BO.sum(axis=0)
if sgd is not None:
sgd(self._mem.weights, self._mem.gradient,
key=id(self._mem))
return self.ops.batch_dot(grad__BO, self.W.T)
return output__BO, finish_update
|
from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
@describe.attributes(
W=Synapses("Weights matrix",
lambda obj: (obj.nO, obj.nI),
lambda W, ops: None)
)
class Softmax(Affine):
def predict(self, input__BI):
output__BO = self.ops.affine(self.W, self.b, input__BI)
self.ops.softmax(output__BO, inplace=True)
return output__BO
def begin_update(self, input__BI, drop=0.):
output__BO = self.predict(input__BI)
def finish_update(grad__BO, sgd=None):
self.d_W += self.ops.batch_outer(grad__BO, input__BI)
self.d_b += grad__BO.sum(axis=0)
if sgd is not None:
sgd(self._mem.weights, self._mem.gradient, key=self.id)
return self.ops.batch_dot(grad__BO, self.W.T)
return output__BO, finish_update
|
Allow 'ignore' as valid vendor extension severity level
|
<?php
namespace webignition\CssValidatorWrapper\Configuration;
class VendorExtensionSeverityLevel {
const LEVEL_IGNORE = 'ignore';
const LEVEL_ERROR = 'error';
const LEVEL_WARN = 'warn';
/**
*
* @var array
*/
private static $validValues = array(
self::LEVEL_ERROR,
self::LEVEL_WARN,
self::LEVEL_IGNORE
);
/**
*
* @param string $severityLevel
* @return boolean
*/
public static function isValid($severityLevel) {
return in_array($severityLevel, self::$validValues);
}
/**
*
* @return array
*/
public static function getValidValues() {
return self::$validValues;
}
}
|
<?php
namespace webignition\CssValidatorWrapper\Configuration;
class VendorExtensionSeverityLevel {
const LEVEL_ERROR = 'error';
const LEVEL_WARN = 'warn';
/**
*
* @var array
*/
private static $validValues = array(
self::LEVEL_ERROR,
self::LEVEL_WARN
);
/**
*
* @param string $severityLevel
* @return boolean
*/
public static function isValid($severityLevel) {
return in_array($severityLevel, self::$validValues);
}
/**
*
* @return array
*/
public static function getValidValues() {
return self::$validValues;
}
}
|
Drop unused sourcemap reset API
|
var fs = require('fs'),
sourceMap = require('source-map');
module.exports.create = function() {
var cache = {};
function loadSourceMap(file) {
try {
var body = fs.readFileSync(file + '.map');
return new sourceMap.SourceMapConsumer(body.toString());
} catch (err) {
/* NOP */
}
}
return {
map: function(file, line, column) {
if (cache[file] === undefined) {
cache[file] = loadSourceMap(file) || false;
}
if (!cache[file]) {
return {source: file, line: line, column: column};
} else {
return cache[file].originalPositionFor({line: line, column: column || 1});
}
}
};
};
|
var fs = require('fs'),
sourceMap = require('source-map');
module.exports.create = function() {
var cache = {};
function loadSourceMap(file) {
try {
var body = fs.readFileSync(file + '.map');
return new sourceMap.SourceMapConsumer(body.toString());
} catch (err) {
/* NOP */
}
}
return {
map: function(file, line, column) {
if (cache[file] === undefined) {
cache[file] = loadSourceMap(file) || false;
}
if (!cache[file]) {
return {source: file, line: line, column: column};
} else {
return cache[file].originalPositionFor({line: line, column: column || 1});
}
},
reset: function() {
cache = {};
}
};
};
|
Fix it gau! oh godgp
|
window.onload = function() {
d3.json("examples/data/gitstats.json", function(data) {
data.forEach(function(d) {
d.date = new Date(d.date);
d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name;
});
var dataset = {data: data, metadata: {}};
var commitSVG = d3.select("#intro-chart");
sizeSVG(commitSVG);
commitChart(commitSVG, dataset);
var scatterFullSVG = d3.select("#scatter-full");
sizeSVG(scatterFullSVG);
scatterFull(scatterFullSVG, dataset);
var lineSVG = d3.select("#line-chart");
sizeSVG(lineSVG);
lineChart(lineSVG, dataset);
});
}
function sizeSVG(svg) {
var width = svg.node().clientWidth;
var height = Math.min(width*.75, 600);
svg.attr("height", height);
}
|
window.onload = function() {
d3.json("../examples/data/gitstats.json", function(data) {
data.forEach(function(d) {
d.date = new Date(d.date);
d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name;
});
var dataset = {data: data, metadata: {}};
var commitSVG = d3.select("#intro-chart");
sizeSVG(commitSVG);
commitChart(commitSVG, dataset);
var scatterFullSVG = d3.select("#scatter-full");
sizeSVG(scatterFullSVG);
scatterFull(scatterFullSVG, dataset);
var lineSVG = d3.select("#line-chart");
sizeSVG(lineSVG);
lineChart(lineSVG, dataset);
});
}
function sizeSVG(svg) {
var width = svg.node().clientWidth;
var height = Math.min(width*.75, 600);
svg.attr("height", height);
}
|
Test runner infinite counter fix
|
new BrowserDb({
db:"saveDb",
collections:["one", "two", "three"]
}, function (error, browserDb) {
module("Save");
asyncTest("Save an object", 3, function () {
browserDb.one.save({
name:"Sri"
}, function (error, savedObject) {
ok(savedObject, "savedObject must be created");
deepEqual(savedObject.name, "Sri", "savedObject.name === 'Sri'");
ok(savedObject._id, "savedObject._id must be auto generated");
start();
});
});
asyncTest("Save an object with manual _id", 1, function () {
browserDb.two.save({
_id:"wtf",
name:"Sri"
}, function (error, savedObject) {
deepEqual(savedObject._id, "wtf", "savedObject._id === 'wtf'");
start();
});
});
asyncTest("Update an object", 1, function () {
browserDb.two.save({
_id:"wtf",
name:"Srirangan"
}, function (error, savedObject) {
deepEqual(savedObject.name, "Srirangan", "savedObject.name === 'Srirangan'");
start();
});
});
QUnit.done(function () {
browserDb.delete();
});
});
|
new BrowserDb({
db:"saveDb",
collections:["one", "two", "three"]
}, function (error, browserDb) {
module("Save");
asyncTest("Save an object", 3, function () {
browserDb.one.save({
name:"Sri"
}, function (error, savedObject) {
ok(savedObject, "savedObject must be created");
deepEqual(savedObject.name, "Sri", "savedObject.name === 'Sri'");
ok(savedObject._id, "savedObject._id must be auto generated");
start();
});
});
asyncTest("Save an object with manual _id", 1, function () {
browserDb.two.save({
_id:"wtf",
name:"Sri"
}, function (error, savedObject) {
deepEqual(savedObject._id, "wtf", "savedObject._id === 'wtf'");
start();
});
});
asyncTest("Update an object", 1, function () {
browserDb.two.save({
_id:"wtf",
name:"Srirangan"
}, function (error, savedObject) {
deepEqual(savedObject.name, "Srirangan", "savedObject.name === 'Srirangan'");
start();
});
});
QUnit.done(function () {
browserDb.delete();
start();
});
});
|
Fix error with Service Calls Wrapper
|
package by.bsuir.mpp.computershop.controller.exception.wrapper;
import by.bsuir.mpp.computershop.controller.exception.ControllerException;
import by.bsuir.mpp.computershop.controller.exception.ResourceNotFoundException;
import by.bsuir.mpp.computershop.service.exception.EntityNotFoundException;
import by.bsuir.mpp.computershop.service.exception.ServiceException;
import by.bsuir.mpp.computershop.utils.WrappedFunctions.Function;
import by.bsuir.mpp.computershop.utils.WrappedFunctions.VoidFunction;
import org.apache.log4j.Logger;
public class ServiceCallWrapper {
public static <T> T wrapServiceCall(Function<T> func, Logger logger) throws ControllerException {
T result;
try {
result = func.call();
} catch (EntityNotFoundException e) {
logger.warn(e);
throw new ResourceNotFoundException(e);
} catch (ServiceException e) {
logger.warn(e);
throw new ControllerException(e);
}
return result;
}
public static void wrapServiceCall(VoidFunction func, Logger logger) throws ControllerException {
wrapServiceCall(() -> {
func.call();
return null;
}, logger);
}
}
|
package by.bsuir.mpp.computershop.controller.exception.wrapper;
import by.bsuir.mpp.computershop.controller.exception.ControllerException;
import by.bsuir.mpp.computershop.controller.exception.ResourceNotFoundException;
import by.bsuir.mpp.computershop.utils.WrappedFunctions.Function;
import by.bsuir.mpp.computershop.utils.WrappedFunctions.VoidFunction;
import by.bsuir.mpp.computershop.service.exception.EntityNotFoundException;
import by.bsuir.mpp.computershop.service.exception.ServiceException;
import org.apache.log4j.Logger;
public class ServiceCallWrapper {
public static <T> T wrapServiceCall(Function<T> func, Logger logger) throws ControllerException {
T result;
try {
result = func.call();
} catch (EntityNotFoundException e) {
logger.warn(e);
throw new ResourceNotFoundException(e);
} catch (ServiceException e) {
logger.warn(e);
throw new ControllerException(e);
}
return result;
}
public static void wrapServiceCall(VoidFunction func, Logger logger) throws ControllerException {
wrapServiceCall(() -> func, logger);
}
}
|
Remove some test code that got left behind
|
import platform
from stats_file_backend import StatsFileBackend
class StatsBackend:
"""
This is a class to manage the Stats backend.
"""
def __init__(self, options={}):
if options == {}:
if platform.system() == "Darwin": # For my local dev I need this hack
options = {"db_path":"/tmp/stats.json"}
else:
options = {"db_path":"/var/lib/omniwallet/www/stats.json"}
self.engine = StatsFileBackend(options)
def put(self, key, val):
self.engine.put(key, val)
def increment(self, key):
val = self.engine.get(key)
if val == None:
val = 0
val += 1
self.engine.put(key, val)
def get(self, val):
return self.engine.get(val)
|
import platform
from stats_file_backend import StatsFileBackend
class StatsBackend:
"""
This is a class to manage the Stats backend.
"""
def __init__(self, options={}):
if options == {}:
if platform.system() == "Darwin": # For my local dev I need this hack
options = {"db_path":"/tmp/stats.json"}
else:
options = {"db_path":"/var/lib/omniwallet/www/stats.json"}
self.engine = StatsFileBackend(options)
def put(self, key, val):
self.engine.put(key, val)
def increment(self, key):
val = self.engine.get(key)
if val == None:
val = 0
val += 1
self.engine.put(key, val)
def get(self, val):
return self.engine.get(val)
stats = StatsBackend()
stats.increment("amount_of_transactions")
|
Fix TestRun factory missing base_url
|
import factory
from fortuitus.feditor.factories import TestProjectF
from fortuitus.frunner import models
class TestRunF(factory.Factory):
FACTORY_FOR = models.TestRun
project = factory.SubFactory(TestProjectF)
base_url = 'http://api.example.com/'
class TestCaseF(factory.Factory):
FACTORY_FOR = models.TestCase
testrun = factory.SubFactory(TestRunF)
name = factory.Sequence(lambda n: 'TestCase #%s' % n)
order = 1
login_type = models.models_base.LoginType.NONE
class TestCaseStepF(factory.Factory):
FACTORY_FOR = models.TestCaseStep
testcase = factory.SubFactory(TestCaseF)
order = 1
method = models.models_base.Method.GET
url = 'user_list.json'
class TestCaseAssertF(factory.Factory):
FACTORY_FOR = models.TestCaseAssert
step = factory.SubFactory(TestCaseStepF)
order = 1
lhs = ''
rhs = ''
operator = models.models_base.method_choices[0][0]
|
import factory
from fortuitus.feditor.factories import TestProjectF
from fortuitus.frunner import models
class TestRunF(factory.Factory):
FACTORY_FOR = models.TestRun
project = factory.SubFactory(TestProjectF)
class TestCaseF(factory.Factory):
FACTORY_FOR = models.TestCase
testrun = factory.SubFactory(TestRunF)
name = factory.Sequence(lambda n: 'TestCase #%s' % n)
order = 1
login_type = models.models_base.LoginType.NONE
class TestCaseStepF(factory.Factory):
FACTORY_FOR = models.TestCaseStep
testcase = factory.SubFactory(TestCaseF)
order = 1
method = models.models_base.Method.GET
url = 'user_list.json'
class TestCaseAssertF(factory.Factory):
FACTORY_FOR = models.TestCaseAssert
step = factory.SubFactory(TestCaseStepF)
order = 1
lhs = ''
rhs = ''
operator = models.models_base.method_choices[0][0]
|
Remove unnecessary binding of action creator
|
import React from 'react';
import { connect } from 'react-redux';
import EntityList from '../components/EntityList';
import { fetchEntities } from '../actions/index';
import { getEntityItems, getEntityStatus, getEntityError } from '../reducers/index';
class AllEntitiesList extends React.Component {
componentDidMount() {
this.props.fetchEntities();
}
render() {
return <EntityList entities={this.props.entities} />;
}
}
AllEntitiesList.propTypes = {
fetchEntities: React.PropTypes.func.isRequired,
entities: React.PropTypes.arrayOf(React.PropTypes.shape({ name: React.PropTypes.string.isRequired })),
status: React.PropTypes.string.isRequired,
error: React.PropTypes.string
};
const mapStateToProps = (state) => ({
entities: getEntityItems(state),
status: getEntityStatus(state),
error: getEntityError(state)
});
export default connect(mapStateToProps, { fetchEntities })(AllEntitiesList);
|
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import EntityList from '../components/EntityList';
import { fetchEntities } from '../actions/index';
import { getEntityItems, getEntityStatus, getEntityError } from '../reducers/index';
class AllEntitiesList extends React.Component {
componentDidMount() {
this.props.fetchEntities();
}
render() {
return <EntityList entities={this.props.entities} />;
}
}
AllEntitiesList.propTypes = {
fetchEntities: React.PropTypes.func.isRequired,
entities: React.PropTypes.arrayOf(React.PropTypes.shape({ name: React.PropTypes.string.isRequired })),
status: React.PropTypes.string.isRequired,
error: React.PropTypes.string
};
const mapStateToProps = (state) => ({
entities: getEntityItems(state),
status: getEntityStatus(state),
error: getEntityError(state)
});
function mapDispatchToProps(dispatch) {
return bindActionCreators({ fetchEntities }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(AllEntitiesList);
|
Set the button to be at the minimum width possible.
|
qx.Class.define("vcms.client.widgets.WidgetList",
{
extend : qx.ui.tabview.TabView,
construct : function()
{
this.base(arguments);
for (i = 0, n = 3; i < n; i++)
{
var page = new qx.ui.tabview.Page("Page #" + i);
page.setLayout(new qx.ui.layout.VBox().set({ spacing: 2 }));
page.add(new qx.ui.form.List());
var buttons_container = new qx.ui.container.Composite(new qx.ui.layout.HBox());
page.add(buttons_container);
buttons_container.add(new qx.ui.form.Button("Remove widget from page"), {flex: 0});
buttons_container.add(new qx.ui.core.Spacer(), {flex: 1});
this.add(page);
}
}
});
|
qx.Class.define("vcms.client.widgets.WidgetList",
{
extend : qx.ui.tabview.TabView,
construct : function()
{
this.base(arguments);
for (i = 0, n = 3; i < n; i++)
{
var page = new qx.ui.tabview.Page("Page #" + i);
page.setLayout(new qx.ui.layout.VBox().set({ spacing: 2 }));
page.add(new qx.ui.form.List());
page.add(new qx.ui.form.Button("Remove widget from page"));
this.add(page);
}
}
});
|
Fix breakage. The website is looking for user-agent header
|
#!/usr/bin/python
# Maybank Gold Investment Account price scraper
# Using BeautifulSoup package
# Developed and tested on Debian Testing (Jessie)
# Initial development 25 July 2012
# Copyright (C) 2012,2013 Sharuzzaman Ahmat Raslan (sharuzzaman@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import urllib2
from BeautifulSoup import BeautifulSoup
import datetime
#maybank website looking for user-agent header
req = urllib2.Request('http://www.maybank2u.com.my/mbbfrx/gold_rate.htm')
req.add_header('User-Agent', 'Mozilla')
website=urllib2.urlopen(req)
data=website.read()
soup = BeautifulSoup(data)
date=soup('td')[31].string
selling=soup('td')[32].string
buying=soup('td')[33].string
print "%s,%s,%s" % (date,selling,buying)
|
#!/usr/bin/python
# Maybank Gold Investment Account price scraper
# Using BeautifulSoup package
# Developed and tested on Debian Testing (Jessie)
# Initial development 25 July 2012
# Copyright (C) 2012,2013 Sharuzzaman Ahmat Raslan (sharuzzaman@gmail.com)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import urllib2
from BeautifulSoup import BeautifulSoup
import datetime
website=urllib2.urlopen('http://www.maybank2u.com.my/mbbfrx/gold_rate.htm')
data=website.read()
soup = BeautifulSoup(data)
date=soup('td')[31].string
selling=soup('td')[32].string
buying=soup('td')[33].string
print "%s,%s,%s" % (date,selling,buying)
|
Update string tests to reflect new behaviour.
|
from protobuf3.fields.string import StringField
from protobuf3.message import Message
from unittest import TestCase
class TestStringField(TestCase):
def setUp(self):
class StringTestMessage(Message):
b = StringField(field_number=2)
self.msg_cls = StringTestMessage
def test_get(self):
msg = self.msg_cls()
msg.parse_from_bytes(bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67]))
self.assertEqual(msg.b, 'testing')
def test_default_get(self):
msg = self.msg_cls()
self.assertEqual(msg.b, '')
def test_set(self):
msg = self.msg_cls()
msg.b = 'test'
self.assertEqual(msg.b, 'test')
def test_invalid_set(self):
msg = self.msg_cls()
def failure():
msg.b = 123
self.assertRaises(ValueError, failure)
|
from protobuf3.fields.string import StringField
from protobuf3.message import Message
from unittest import TestCase
class TestStringField(TestCase):
def setUp(self):
class StringTestMessage(Message):
b = StringField(field_number=2)
self.msg_cls = StringTestMessage
def test_get(self):
msg = self.msg_cls()
msg.parse_from_bytes([0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6E, 0x67])
self.assertEqual(msg.b, 'testing')
def test_default_get(self):
msg = self.msg_cls()
self.assertEqual(msg.b, '')
def test_set(self):
msg = self.msg_cls()
msg.b = 'test'
self.assertEqual(msg.b, 'test')
def test_invalid_set(self):
msg = self.msg_cls()
def failure():
msg.b = 123
self.assertRaises(ValueError, failure)
|
Increment version after making parser properties non-private
|
import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis_metadata_parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.2.2',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'frozendict>=1.2', 'parserutils>=1.1', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis_metadata_parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.2.1',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'frozendict>=1.2', 'parserutils>=1.1', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
Add test for withdraw exception response
|
#!/usr/bin/env python
# coding=utf-8
from binance.client import Client
from binance.exceptions import BinanceAPIException, BinanceRequestException, BinanceWithdrawException
import pytest
import requests_mock
client = Client('api_key', 'api_secret')
def test_invalid_json():
"""Test Invalid response Exception"""
with pytest.raises(BinanceRequestException):
with requests_mock.mock() as m:
m.get('https://www.binance.com/exchange/public/product', text='<head></html>')
client.get_products()
def test_api_exception():
"""Test API response Exception"""
with pytest.raises(BinanceAPIException):
with requests_mock.mock() as m:
json_obj = {"code": 1002, "msg": "Invalid API call"}
m.get('https://www.binance.com/api/v1/time', json=json_obj, status_code=400)
client.get_server_time()
def test_withdraw_api_exception():
"""Test Withdraw API response Exception"""
with pytest.raises(BinanceWithdrawException):
with requests_mock.mock() as m:
json_obj = {"success": False, "msg": "Insufficient funds"}
m.register_uri('POST', requests_mock.ANY, json=json_obj, status_code=200)
client.withdraw(asset='BTC', address='BTCADDRESS', amount=100)
|
#!/usr/bin/env python
# coding=utf-8
from binance.client import Client
from binance.exceptions import BinanceAPIException, BinanceRequestException
import pytest
import requests_mock
client = Client('api_key', 'api_secret')
def test_invalid_json():
"""Test Invalid response Exception"""
with pytest.raises(BinanceRequestException):
with requests_mock.mock() as m:
m.get('https://www.binance.com/exchange/public/product', text='<head></html>')
client.get_products()
def test_api_exception():
"""Test API response Exception"""
with pytest.raises(BinanceAPIException):
with requests_mock.mock() as m:
json_obj = {"code": 1002, "msg": "Invalid API call"}
m.get('https://www.binance.com/api/v1/time', json=json_obj, status_code=400)
client.get_server_time()
|
Fix polygon handler to show correct label text
|
L.Polygon.Draw = L.Polyline.Draw.extend({
Poly: L.Polygon,
options: {
shapeOptions: {
stroke: true,
color: '#f06eaa',
weight: 4,
opacity: 0.5,
fill: true,
fillColor: null, //same as color by default
fillOpacity: 0.2,
clickable: true
}
},
_updateMarkerHandler: function () {
// The first marker shold have a click handler to close the polygon
if (this._markers.length === 1) {
this._markers[0].on('click', this._finishShape, this);
}
},
_getLabelText: function () {
var text;
if (this._markers.length === 0) {
text = 'Click to start drawing shape.';
} else if (this._markers.length < 3) {
text = 'Click to continue drawing shape.';
} else {
text = 'Click first point to close this shape.';
}
return {
text: text
};
},
_vertexAdded: function (latlng) {
//calc area here
},
_cleanUpShape: function () {
if (this._markers.length > 0) {
this._markers[0].off('click', this._finishShape);
}
}
});
|
L.Polygon.Draw = L.Polyline.Draw.extend({
Poly: L.Polygon,
options: {
shapeOptions: {
stroke: true,
color: '#f06eaa',
weight: 4,
opacity: 0.5,
fill: true,
fillColor: null, //same as color by default
fillOpacity: 0.2,
clickable: true
}
},
_updateMarkerHandler: function () {
// The first marker shold have a click handler to close the polygon
if (this._markers.length === 1) {
this._markers[0].on('click', this._finishShape, this);
}
},
_getLabelText: function (markerCount) {
var text;
if (markerCount === 0) {
text = 'Click to start drawing shape.';
} else if (markerCount < 3) {
text = 'Click to continue drawing shape.';
} else {
text = 'Click first point to close this shape.';
}
return {
text: text
};
},
_vertexAdded: function (latlng) {
//calc area here
},
_cleanUpShape: function () {
if (this._markers.length > 0) {
this._markers[0].off('click', this._finishShape);
}
}
});
|
Make code more self documenting and remove (* title).
|
<?php
header('Content-Type: application/json');
header('Content-type: text/html; charset=UTF-8');
include_once("config/config.php");
include_once("inc/params.php");
include_once("inc/contact.php");
$lines = file($markdownPath);
$faqs = array();
$currentTitle = "";
$currentContent = "";
foreach ($lines as $line) {
if(isTitleLine($line)) {
$hasFinishedSection = strlen($currentTitle)>0;
if ($hasFinishedSection) {
$faqs[] = array("title"=>$currentTitle, "detail"=>$currentContent);
}
$currentTitle = $line;
$currentContent = "";
}else{
$currentContent .= $line."\n";
}
}
$help = array('faqs' => $faqs, 'contact' => $contactMarkdown);
print_r(json_encode($help));
function isTitleLine($line) {
return preg_match('/^# .*/', $line);
}
?>
|
<?php
header('Content-Type: application/json');
header('Content-type: text/html; charset=UTF-8');
include_once("config/config.php");
include_once("inc/params.php");
include_once("inc/contact.php");
$lines = file($markdownPath);
$faqs = array();
$currentTitle = "";
$currentContent = "";
foreach ($lines as $line) {
$subject = $line;
$pattern = '/^\* .*/';
if (substr($line, 0, 1) == "#") {
$pattern = '/^# .*/';
}
if(preg_match($pattern, $subject)) {
if (strlen($currentTitle)>0) {
$faqs[] = array("title"=>$currentTitle, "detail"=>$currentContent);
}
$currentTitle = $line;
$currentContent = "";
}else{
$currentContent .= $line."\n";
}
}
$help = array('faqs' => $faqs, 'contact' => $contactMarkdown);
print_r(json_encode($help));
?>
|
Raise error when plugin is not configured
|
'use strict';
const path = require('path');
const jade = require('jade');
const _ = require('lodash');
module.exports = function(env, callback) {
class Sitemap extends env.plugins.Page {
getFilename() {
return 'sitemap.xml';
}
getView() {
// jshint maxparams: 5
return (env, locals, contents, templates, callback) => {
if (locals.url) {
const filename = path.join(__dirname, 'templates', 'sitemap.jade');
const template = jade.compileFile(filename);
const context = _.merge({
'entries': env.helpers.contents.list(contents).filter((entry) => (
entry instanceof env.plugins.MarkdownPage &&
!entry.metadata.noindex
)),
}, locals);
callback(null, new Buffer(template(context)));
} else {
callback(new Error('locals.url must be defined.'));
}
};
}
}
env.registerGenerator('sitemap', (contents, callback) => {
callback(null, {'sitemap.xml': new Sitemap()});
});
callback();
};
|
'use strict';
const path = require('path');
const jade = require('jade');
const _ = require('lodash');
module.exports = function(env, callback) {
class Sitemap extends env.plugins.Page {
getFilename() {
return 'sitemap.xml';
}
getView() {
// jshint maxparams: 5
return (env, locals, contents, templates, callback) => {
const filename = path.join(__dirname, 'templates', 'sitemap.jade');
const template = jade.compileFile(filename);
const context = _.merge({
'entries': env.helpers.contents.list(contents).filter((entry) => (
entry instanceof env.plugins.MarkdownPage && !entry.metadata.noindex
)),
}, locals);
callback(null, new Buffer(template(context)));
};
}
}
env.registerGenerator('sitemap', (contents, callback) => {
callback(null, {'sitemap.xml': new Sitemap()});
});
callback();
};
|
Add a comment to CreateUserInfo
|
package zoom // Use this file for /user endpoints
// CreateUserPath - v2 path for creating a user
const CreateUserPath = "/users"
// CreateUserInfo are details about a user to create
type CreateUserInfo struct {
Email string `json:"email"`
Type UserType `json:"type"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
Password string `json:"password,omitempty"`
}
// CreateUserOptions are the options to create a user with
type CreateUserOptions struct {
Action CreateUserAction `json:"action"`
UserInfo CreateUserInfo `json:"user_info"`
}
// CreateUser calls POST /users/{userId}/meetings
func CreateUser(opts CreateUserOptions) (User, error) {
return defaultClient.CreateUser(opts)
}
// CreateUser calls POST /users
// https://marketplace.zoom.us/docs/api-reference/zoom-api/users/usercreate
func (c *Client) CreateUser(opts CreateUserOptions) (User, error) {
var ret = User{}
return ret, c.requestV2(requestV2Opts{
Method: Post,
Path: CreateUserPath,
DataParameters: &opts,
Ret: &ret,
})
}
|
package zoom // Use this file for /user endpoints
// CreateUserPath - v2 path for creating a user
const CreateUserPath = "/users"
type CreateUserInfo struct {
Email string `json:"email"`
Type UserType `json:"type"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
Password string `json:"password,omitempty"`
}
// CreateUserOptions are the options to create a user with
type CreateUserOptions struct {
Action CreateUserAction `json:"action"`
UserInfo CreateUserInfo `json:"user_info"`
}
// CreateUser calls POST /users/{userId}/meetings
func CreateUser(opts CreateUserOptions) (User, error) {
return defaultClient.CreateUser(opts)
}
// CreateUser calls POST /users
// https://marketplace.zoom.us/docs/api-reference/zoom-api/users/usercreate
func (c *Client) CreateUser(opts CreateUserOptions) (User, error) {
var ret = User{}
return ret, c.requestV2(requestV2Opts{
Method: Post,
Path: CreateUserPath,
DataParameters: &opts,
Ret: &ret,
})
}
|
Make treebuilder configuration backwards compatible with older Symfony versions
|
<?php
namespace AshleyDawson\GlideBundle\DependencyInjection;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
/**
* Class Configuration
*
* @package AshleyDawson\GlideBundle\DependencyInjection
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('ashley_dawson_glide');
$rootNode = \method_exists($treeBuilder, 'getRootNode')
? $treeBuilder->getRootNode()
: $treeBuilder->root('ashley_dawson_glide');
$rootNode
->children()
->integerNode('max_image_size')->defaultValue(4000000)->end()
->scalarNode('image_manager_driver')->defaultValue('gd')->end()
->end()
;
return $treeBuilder;
}
}
|
<?php
namespace AshleyDawson\GlideBundle\DependencyInjection;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
/**
* Class Configuration
*
* @package AshleyDawson\GlideBundle\DependencyInjection
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('ashley_dawson_glide');
$rootNode = $treeBuilder->getRootNode();
$rootNode
->children()
->integerNode('max_image_size')->defaultValue(4000000)->end()
->scalarNode('image_manager_driver')->defaultValue('gd')->end()
->end()
;
return $treeBuilder;
}
}
|
Use experimental object observers for mocking. only works in chromium for now.
|
// ==UserScript==
// @name Kill nrcQ restrictions
// @namespace http://use.i.E.your.homepage/
// @version 0.2
// @description When browsing nrcq with more than 10 views you need to sign in to view the content, this plugin disables the lay-over.
// @match http://www.nrcq.nl/*
// @copyright 2015+, You
// @run-at document-start
// @grant none
// ==/UserScript==
// initialize the objects
window.nmt = window.nmt || {};
nmt.q = nmt.q || {};
// The observer function.
var observer = function(changes) {
changes.forEach(function(change) {
// Any time boxy is added to nmt.q
if (change.name == 'boxy') {
// mock the boxy inDom func.
nmt.q.boxy = function(x) {
this.inDom = false;
}
// destroy the observer
doUnobserve(nmt.q);
};
});
};
// Use experimental feature.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe#Browser_compatibility
Object.observe(nmt.q, observer, ["add"]);
function doUnobserve(obj) {
Object.unobserve(obj, observer);
}
|
// ==UserScript==
// @name Kill nrcQ restrictions
// @namespace http://use.i.E.your.homepage/
// @version 0.1
// @description When browsing nrcq with more than 10 views you need to sign in to view the content, this plugin disables the lay-over.
// @match http://www.nrcq.nl/*
// @copyright 2015+, You
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
// ==/UserScript==
// Load the jquery library.
this.$ = this.jQuery = jQuery.noConflict(true);
$(document).ready(function()
{
// change the class from opened to closed
$(document.body).removeClass("boxy-opened").addClass("boxy-closed");
// Remove the overlays.
$('div.boxy-overlay').remove();
$('div.boxy').remove();
}
);
|
Allow props proxy on Text
|
import React from 'react';
import PropTypes from 'prop-types';
import { primaryFontStyle, secondaryFontStyle } from 'styles/font';
/**
* Text component with automatic typeface formatting.
*/
const Text = (props) => {
const {
secondary,
size,
color,
bold,
inline,
uppercase,
style: overrides,
children,
...proxyProps
} = props;
const styleFactory = secondary ? secondaryFontStyle : primaryFontStyle;
const style = {
...styleFactory(size, color, bold),
textTransform: uppercase ? 'uppercase' : 'none',
...overrides,
};
if (inline) {
return (
<span style={style} {...proxyProps}>
{children}
</span>
);
}
return (
<p style={style} {...proxyProps}>
{children}
</p>
);
};
Text.propTypes = {
secondary: PropTypes.bool,
size: PropTypes.string,
color: PropTypes.string,
bold: PropTypes.bool,
inline: PropTypes.bool,
uppercase: PropTypes.bool,
style: PropTypes.object,
children: PropTypes.any,
};
Text.defaultProps = {
secondary: false,
size: 'iota',
color: 'gray80',
bold: false,
inline: false,
uppercase: false,
style: {},
children: null,
};
export default Text;
|
import React from 'react';
import PropTypes from 'prop-types';
import { primaryFontStyle, secondaryFontStyle } from 'styles/font';
/**
* Text component with automatic typeface formatting.
*/
const Text = (props) => {
const { secondary, size, color, bold, inline, uppercase, style: overrides, children } = props;
const styleFactory = secondary ? secondaryFontStyle : primaryFontStyle;
const style = {
...styleFactory(size, color, bold),
textTransform: uppercase ? 'uppercase' : 'none',
...overrides,
};
if (inline) {
return (
<span style={style}>
{children}
</span>
);
}
return (
<p style={style}>
{children}
</p>
);
};
Text.propTypes = {
secondary: PropTypes.bool,
size: PropTypes.string,
color: PropTypes.string,
bold: PropTypes.bool,
inline: PropTypes.bool,
uppercase: PropTypes.bool,
style: PropTypes.object,
children: PropTypes.any,
};
Text.defaultProps = {
secondary: false,
size: 'iota',
color: 'gray80',
bold: false,
inline: false,
uppercase: false,
style: {},
children: null,
};
export default Text;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.