text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add better error support for answers file | import tweepy, time, random
def main():
CONSUMER_KEY = 'your_consumer_key'
CONSUMER_SECRET = 'your_consumer_secret'
ACCESS_KEY = 'your_access_key'
ACCESS_SECRET = 'your_access_secret'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
while True:
minion_tweets = api.search(q="minions")
try:
answers_file = open('custom/answers/answers.txt', 'r')
minion_answers = answers_file.read().splitlines()
answers_file.close()
except IOError:
print "Oops, something went wrong. Could not find answers.txt file."
for minion_tweet in minion_tweets:
sn = minion_tweet.user.screen_name
minion_answer = "@%s %s" % (sn, random.choice(minion_answers))
api.update_status(status=minion_answer, in_reply_to_status_id=minion_tweet.id)
time.sleep(900)
if __name__ == '__main__':
main() | import tweepy, time, random
def main():
CONSUMER_KEY = 'your_consumer_key'
CONSUMER_SECRET = 'your_consumer_secret'
ACCESS_KEY = 'your_access_key'
ACCESS_SECRET = 'your_access_secret'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
while True:
minion_tweets = api.search(q="minions")
answers_file = open('custom/answers/answers.txt', 'r')
minion_answers = answers_file.read().splitlines()
answers_file.close()
for minion_tweet in minion_tweets:
sn = minion_tweet.user.screen_name
minion_answer = "@%s %s" % (sn, random.choice(minion_answers))
api.update_status(status=minion_answer, in_reply_to_status_id=minion_tweet.id)
time.sleep(900)
if __name__ == '__main__':
main() |
Add missing language string in English | <?php
return [
'again' => 'Again',
'close' => 'Close',
'connection' => 'Connection',
'cpu' => 'CPU',
'current_password' => 'Current Password',
'disabled' => 'Disabled',
'email' => 'Email',
'enabled' => 'Enabled',
'language' => 'Language',
'location' => 'Location',
'login' => 'Login',
'memory' => 'Memory',
'no' => 'No',
'node' => 'Node',
'password' => 'Password',
'players' => 'Players',
'registered' => 'Registered',
'restart' => 'Restart',
'root_administrator' => 'Root Administrator',
'save' => 'Save',
'start' => 'Start',
'status' => 'Status',
'stop' => 'Stop',
'submit' => 'Submit',
'success' => 'Success',
'whoops' => 'Whoops',
'yes' => 'Yes',
];
| <?php
return [
'again' => 'Again',
'close' => 'Close',
'connection' => 'Connection',
'cpu' => 'CPU',
'current_password' => 'Current Password',
'disabled' => 'Disabled',
'email' => 'Email',
'enabled' => 'Enabled',
'language' => 'Language',
'location' => 'Location',
'login' => 'Login',
'memory' => 'Memory',
'no' => 'No',
'node' => 'Node',
'players' => 'Players',
'registered' => 'Registered',
'restart' => 'Restart',
'root_administrator' => 'Root Administrator',
'save' => 'Save',
'start' => 'Start',
'status' => 'Status',
'stop' => 'Stop',
'submit' => 'Submit',
'success' => 'Success',
'whoops' => 'Whoops',
'yes' => 'Yes',
];
|
Bump version: 0.0.1 -> 0.0.2
[ci skip] | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class ToolingCMakeUtilConan(ConanFile):
name = "tooling-find-pkg-util"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/tooling-find-pkg-util"
license = "MIT"
def source(self):
zip_name = "tooling-find-pkg-util.zip"
download("https://github.com/polysquare/"
"tooling-find-pkg-util/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/tooling-find-pkg-util",
src="tooling-find-pkg-util-" + VERSION,
keep_path=True)
| from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.1"
class ToolingCMakeUtilConan(ConanFile):
name = "tooling-find-pkg-util"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/tooling-find-pkg-util"
license = "MIT"
def source(self):
zip_name = "tooling-find-pkg-util.zip"
download("https://github.com/polysquare/"
"tooling-find-pkg-util/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/tooling-find-pkg-util",
src="tooling-find-pkg-util-" + VERSION,
keep_path=True)
|
Use inspector. prefix for "inpsector.fullStacktrace" sys prop | /*
* Copyright 2014 Johan Parent
*
* 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 org.pareto4j.inspector.collections;
import java.util.EnumSet;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: gebruiker
* Date: 3/12/13
* Time: 20:36
* To change this template use File | Settings | File Templates.
*/
public class Profile {
static final Set<DelegateTypes> modify = EnumSet.noneOf(DelegateTypes.class);
static final boolean fullStacktrace = System.getProperty("inspector.fullStacktrace") != null;
static {
for (DelegateTypes delegateTypes : DelegateTypes.values()) {
if (System.getProperty("skip"+delegateTypes.name()) == null) {
modify.add(delegateTypes);
System.err.println("Will inspect " + delegateTypes);
}
}
}
}
| /*
* Copyright 2014 Johan Parent
*
* 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 org.pareto4j.inspector.collections;
import java.util.EnumSet;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: gebruiker
* Date: 3/12/13
* Time: 20:36
* To change this template use File | Settings | File Templates.
*/
public class Profile {
static final Set<DelegateTypes> modify = EnumSet.noneOf(DelegateTypes.class);
static final boolean fullStacktrace = System.getProperty("fullStacktrace") != null;
static {
for (DelegateTypes delegateTypes : DelegateTypes.values()) {
if (System.getProperty("skip"+delegateTypes.name()) == null) {
modify.add(delegateTypes);
System.err.println("Will inspect " + delegateTypes);
}
}
}
}
|
Remove temporary test for ResultCtrl | /**
* 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.
*/
'use strict';
describe('Controller: ResultCtrl', function () {
// load the controller's module
beforeEach(module('ocwUiApp'));
var ResultCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
ResultCtrl = $controller('ResultCtrl', {
$scope: scope
});
}));
});
| /**
* 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.
*/
'use strict';
describe('Controller: ResultCtrl', function () {
// load the controller's module
beforeEach(module('ocwUiApp'));
var ResultCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
ResultCtrl = $controller('ResultCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
Modify slide and fade features | $(document).ready(function() {
$(".welcome").on("click", function() {
console.log("YES");
$(this).fadeOut(1400);
$(this).parent().slideUp(1800);
// $(this).slideUp(1200);
// $(this).parent().animate({ height: 'toggle', opacity: 0.5 }, 1500);
});
$("#about").on("click", function() {
var popupBox = $(".popup-about");
popupBox.fadeIn(400);
$('body').append('<div class="container" id="mask"></div>');
$("#mask").fadeIn(400);
});
$("#start").on("click", function() {
var popupBox = $(".popup-start");
popupBox.fadeIn(400);
$('body').append('<div class="container" id="mask"></div>');
$("#mask").fadeIn(400);
});
$("#meet").on("click", function() {
var popupBox = $(".popup-meet");
popupBox.fadeIn(400);
$('body').append('<div class="container" id="mask"></div>');
$("#mask").fadeIn(400);
});
});
| $(document).ready(function() {
$(".welcome").on("click", function() {
console.log("YES");
$(this).slideUp(1500);
// $(this).parent().slideUp(1500);
$(this).parent().animate({ height: 'toggle', opacity: 0.5 }, 1500);
});
$("#about").on("click", function() {
var popupBox = $(".popup-about");
popupBox.fadeIn(400);
$('body').append('<div class="container" id="mask"></div>');
$("#mask").fadeIn(400);
});
$("#start").on("click", function() {
var popupBox = $(".popup-start");
popupBox.fadeIn(400);
$('body').append('<div class="container" id="mask"></div>');
$("#mask").fadeIn(400);
});
$("#meet").on("click", function() {
var popupBox = $(".popup-meet");
popupBox.fadeIn(400);
$('body').append('<div class="container" id="mask"></div>');
$("#mask").fadeIn(400);
});
});
|
Print exception message on RegEx fail | (function() {
var __WS_send = WebSocket.prototype.send;
window.__WS_send = WebSocket.prototype.send;
WebSocket.prototype.send = function(data) {
console.log(this.url);
try {
var re = /((?:[0-9]{1,3}(?:\.|\-)){1,3}[0-9]{1,3})(?:.*?)?(\:[0-9]{1,5})/;
var match = re.exec(this.url);
console.log("http://agar.io/?sip=" + match[1].replace(/-/g, '.') + match[2]);
} catch (err) {
console.error(err.message);
}
try {
__WS_send.apply(this, [data]);
WebSocket.prototype.send = __WS_send;
} catch (err) {
window.__WS_send.apply(this, [data]);
WebSocket.prototype.send = window.__WS_send;
}
}
})(); | (function() {
var __WS_send = WebSocket.prototype.send;
window.__WS_send = WebSocket.prototype.send;
WebSocket.prototype.send = function(data) {
console.log(this.url);
try {
var re = /((?:[0-9]{1,3}(?:\.|\-)){1,3}[0-9]{1,3})(?:.*?)?(\:[0-9]{1,5})/;
var match = re.exec(this.url);
console.log("http://agar.io/?sip=" + match[1].replace(/-/g, '.') + match[2]);
} catch (err) {}
try {
__WS_send.apply(this, [data]);
WebSocket.prototype.send = __WS_send;
} catch (err) {
window.__WS_send.apply(this, [data]);
WebSocket.prototype.send = window.__WS_send;
}
}
})();
|
Update JS style: use 2 spaces, not 4 | // Initialize an OpenTok Session object
var session = OT.initSession(apiKey, sessionId);
// Initialize a Publisher, and place it into the element with id="publisher"
var publisher = OT.initPublisher('publisher');
// Attach an event handler for when the session dispatches the 'streamCreated' event.
session.on('streamCreated', function(event) {
// This function runs when another client publishes a stream (eg. session.publish())
// Subscribe to the stream that caused this event, put it inside the DOM element with id='subscribers'
session.subscribe(event.stream, 'subscribers', {
insertMode: 'append'
}, function(error) {
if (error) {
console.error('Failed to subscribe', error);
}
});
});
// Connect to the Session using the 'apiKey' of the application and a 'token' for permission
session.connect(token, function(error) {
// This function runs when session.connect() asynchronously completes
// Handle connection errors
if (error) {
console.error('Failed to connect', error);
} else {
// Publish the publisher we initialzed earlier (this will trigger 'streamCreated' on other
// clients)
session.publish(publisher, function(error) {
if (error) {
console.error('Failed to publish', error);
}
});
}
});
| // Initialize an OpenTok Session object
var session = OT.initSession(apiKey, sessionId);
// Initialize a Publisher, and place it into the element with id="publisher"
var publisher = OT.initPublisher('publisher');
// Attach an event handler for when the session dispatches the 'streamCreated' event.
session.on('streamCreated', function(event) {
// This function runs when another client publishes a stream (eg. session.publish())
// Subscribe to the stream that caused this event, put it inside the DOM element with id='subscribers'
session.subscribe(event.stream, 'subscribers', {
insertMode: 'append'
}, function(error) {
if (error) {
console.error('Failed to subscribe', error);
}
});
});
// Connect to the Session using the 'apiKey' of the application and a 'token' for permission
session.connect(token, function(error) {
// This function runs when session.connect() asynchronously completes
// Handle connection errors
if (error) {
console.error('Failed to connect', error);
} else {
// Publish the publisher we initialzed earlier (this will trigger 'streamCreated' on other
// clients)
session.publish(publisher, function(error) {
if (error) {
console.error('Failed to publish', error);
}
});
}
});
|
Fix spelling of Restaurant in web backend | from __future__ import unicode_literals
from django.db import models
from model_utils import Choices
class Report(models.Model):
"""Store report information"""
REPORT_TYPES = Choices(
('A', 'Shop/Market'),
('B', 'Restaurant/Eatery'),
('C', 'Live Animal Display'),
('D', 'Poaching'),
('E', 'Other'),
)
latitude = models.DecimalField(max_digits=9, decimal_places=6)
longitude = models.DecimalField(max_digits=9, decimal_places=6)
event_time = models.DateTimeField()
arrival_time = models.DateTimeField(auto_now_add=True)
modified_time = models.DateTimeField(auto_now=True)
report_type = models.CharField(max_length=2, choices=REPORT_TYPES)
device_id = models.CharField(max_length=50)
def __unicode__(self):
return u"({0}, {1}) {2}".format(self.latitude, self.longitude,
self.get_report_type_display())
| from __future__ import unicode_literals
from django.db import models
from model_utils import Choices
class Report(models.Model):
"""Store report information"""
REPORT_TYPES = Choices(
('A', 'Shop/Market'),
('B', 'Restaraunt/Eatery'),
('C', 'Live Animal Display'),
('D', 'Poaching'),
('E', 'Other'),
)
latitude = models.DecimalField(max_digits=9, decimal_places=6)
longitude = models.DecimalField(max_digits=9, decimal_places=6)
event_time = models.DateTimeField()
arrival_time = models.DateTimeField(auto_now_add=True)
modified_time = models.DateTimeField(auto_now=True)
report_type = models.CharField(max_length=2, choices=REPORT_TYPES)
device_id = models.CharField(max_length=50)
def __unicode__(self):
return u"({0}, {1}) {2}".format(self.latitude, self.longitude,
self.get_report_type_display())
|
Add modal for ipad links | <?php
function ipadPopUpScript(){
?>
jQuery("a[href$='http://bullettstoreat.wpengine.com/p/ipad-magazine-subscription/']").attr('data-reveal-id', 'ipadPopUp');
<?php
}
function ipadPopUpModal(){
?>
jQuery('#colophon').after('<div id="ipadPopUp" class="reveal-modal"><h2>Th'+
'is will open a new tab.</h2><p class="lead">The following link will open a'+
' new window to the iTunes AppStore. You can subscribe to the Bullett maga'+
'zine from there.</p><p>If you have any items in your shopping cart, they '+
'won\'t go anywhere (as long as you don\'t close the window).</p><a href="'+
'https://itunes.apple.com/us/app/bullett/id557294227?mt=8" class="button l'+
'arge single_add_to_cart_button" target="_blank">Get it!<\/a><a class="clo'+
'se-reveal-modal">×<\/a><\/div>');
<?php
}
function PopUpModal(){
?>
<script>
<?php ipadPopUpScript(); ?>
<?php ipadPopUpModal(); ?>
</script>
<?php
}
add_action('wp_footer', 'PopUpModal', 33);
?> | <?php
function ipadPopUpScript(){
?>
jQuery("a[href$='http://bullettstoreat.wpengine.com/p/ipad-magazine-subscr'+
'iption/']").attr('data-reveal-id', 'ipadPopUp');
<?php
}
function ipadPopUpModal(){
?>
jQuery('#colophon').after('<div id="ipadPopUp" class="reveal-modal"><h2>Th'+
'is will open a new tab.</h2><p class="lead">The following link will open a'+
' new window to the iTunes AppStore. You can subscribe to the Bullett maga'+
'zine from there.</p><p>If you have any items in your shopping cart, they '+
'won\'t go anywhere (as long as you don\'t close the window).</p><a href="'+
'https://itunes.apple.com/us/app/bullett/id557294227?mt=8" class="button l'+
'arge single_add_to_cart_button" target="_blank">Get it!<\/a><a class="clo'+
'se-reveal-modal">×<\/a><\/div>');
<?php
}
function PopUpModal(){
?>
<script>
<?php ipadPopUpScript(); ?>
<?php ipadPopUpModal(); ?>
</script>
<?php
}
add_action('wp_footer', 'PopUpModal', 33);
?> |
Use protocol-specific URL for media. | from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'docs',
'USER': 'postgres', # Not used with sqlite3.
'PASSWORD': '',
'HOST': '10.177.73.97',
'PORT': '',
}
}
DEBUG = False
TEMPLATE_DEBUG = False
CELERY_ALWAYS_EAGER = False
MEDIA_URL = '//media.readthedocs.org/'
ADMIN_MEDIA_PREFIX = MEDIA_URL + 'admin/'
CACHE_BACKEND = 'memcached://localhost:11211/'
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://odin:8983/solr',
}
}
SLUMBER_API_HOST = 'http://readthedocs.org'
WEBSOCKET_HOST = 'websocket.readthedocs.org:8088'
try:
from local_settings import *
except:
pass
| from .base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'docs',
'USER': 'postgres', # Not used with sqlite3.
'PASSWORD': '',
'HOST': '10.177.73.97',
'PORT': '',
}
}
DEBUG = False
TEMPLATE_DEBUG = False
CELERY_ALWAYS_EAGER = False
MEDIA_URL = 'http://media.readthedocs.org/'
ADMIN_MEDIA_PREFIX = MEDIA_URL + 'admin/'
CACHE_BACKEND = 'memcached://localhost:11211/'
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://odin:8983/solr',
}
}
SLUMBER_API_HOST = 'http://readthedocs.org'
WEBSOCKET_HOST = 'websocket.readthedocs.org:8088'
try:
from local_settings import *
except:
pass
|
Fix serving of user uploaded files | //
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const path = require('path'),
send = require('koa-send'),
conf = require('../lib/conf');
const oneYearInSeconds = 60 * 60 * 24 * 365;
let dataDirectory = path.normalize(conf.get('files:upload_directory'));
// TBD: move this to library. Add exists check.
if (dataDirectory.charAt(0) !== path.sep) {
dataDirectory = path.join(__dirname, '..', '..', dataDirectory);
}
module.exports = function*() {
let file = this.params.file;
let filePath = path.join(file.substring(0, 2), file);
yield send(this, filePath, { root: dataDirectory });
this.set('Cache-Control', 'public, max-age=' + oneYearInSeconds);
};
| //
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const path = require('path'),
send = require('koa-send'),
conf = require('../lib/conf');
const oneYearInSeconds = 60 * 60 * 24 * 365;
let dataDirectory = path.normalize(conf.get('files:upload_directory'));
// TBD: move this to library. Add exists check.
if (dataDirectory.charAt(0) !== path.sep) {
dataDirectory = path.join(__dirname, '..', '..', dataDirectory);
}
module.exports = function*() {
let file = this.params.file;
let firstTwo = file.substring(0, 2);
yield send(this, dataDirectory + path.sep + firstTwo + path.sep + file);
this.set('Cache-Control', 'public, max-age=' + oneYearInSeconds);
};
|
Increase re-running limit of test_profiler | # -*- coding: utf-8 -*-
from __future__ import division
import sys
import pytest
from profiling.sampling import SamplingProfiler
from profiling.sampling.samplers import ItimerSampler
from utils import find_stat, spin
def spin_100ms():
spin(0.1)
def spin_500ms():
spin(0.5)
@pytest.mark.flaky(reruns=10)
def test_profiler():
profiler = SamplingProfiler(top_frame=sys._getframe(),
sampler=ItimerSampler(0.0001))
with profiler:
spin_100ms()
spin_500ms()
stat1 = find_stat(profiler.stats, 'spin_100ms')
stat2 = find_stat(profiler.stats, 'spin_500ms')
ratio = stat1.deep_count / stat2.deep_count
assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5
| # -*- coding: utf-8 -*-
from __future__ import division
import sys
import pytest
from profiling.sampling import SamplingProfiler
from profiling.sampling.samplers import ItimerSampler
from utils import find_stat, spin
def spin_100ms():
spin(0.1)
def spin_500ms():
spin(0.5)
@pytest.mark.flaky(reruns=5)
def test_profiler():
profiler = SamplingProfiler(top_frame=sys._getframe(),
sampler=ItimerSampler(0.0001))
with profiler:
spin_100ms()
spin_500ms()
stat1 = find_stat(profiler.stats, 'spin_100ms')
stat2 = find_stat(profiler.stats, 'spin_500ms')
ratio = stat1.deep_count / stat2.deep_count
assert 0.8 <= ratio * 5 <= 1.2 # 1:5 expaected, but tolerate (0.8~1.2):5
|
Update script to remove extension from filename
Before, the script added the extension .json to whatever the file
name was. Now, it removes the last extension and then appends .json. | #!/usr/bin/env python
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for fi in input_files:
with codecs.open(fi) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
saf_data = frog_to_saf(parse_frog(lines))
head, tail = os.path.split(fi)
fname = tail.replace(os.path.splitext(tail)[1], '')
out_file = os.path.join(output_dir, '{}.json'.format(fname))
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
json.dump(saf_data, f, indent=4)
if __name__ == '__main__':
frog2saf()
| #!/usr/bin/env python
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for fi in input_files:
with codecs.open(fi) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
saf_data = frog_to_saf(parse_frog(lines))
head, tail = os.path.split(fi)
out_file = os.path.join(output_dir, '{}.json'.format(tail))
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
json.dump(saf_data, f, indent=4)
if __name__ == '__main__':
frog2saf()
|
Fix for the pyinstall unit test | from __future__ import absolute_import
import os
import sys
import pytest
from mock import patch
from pkglib.scripts import pyinstall
from zc.buildout.easy_install import _get_index
def test_pyinstall_respects_i_flag():
"""Ensure that pyinstall allows us to override the PyPI URL with -i,
even if it's already set in the config.
"""
pypi_url = "http://some-pypi-host/simple"
package_name = "some-package"
expected_url = "%s/%s/" % (pypi_url, package_name)
class OpenedCorrectUrl(Exception):
pass
def fake_urlopen(request, *args, **kwargs):
assert request.get_full_url() == expected_url
# We don't actually want pyinstall to install anything, so we
# raise an exception so we terminate here.
raise OpenedCorrectUrl()
def get_index(*args, **kwargs):
index = _get_index(*args, **kwargs)
index.opener = fake_urlopen
return index
with patch('zc.buildout.easy_install._get_index', get_index):
# Call pyinstall with the -i flag.
args = ['pyinstall', '-i', pypi_url, package_name]
with patch.object(sys, 'argv', args):
try:
pyinstall.main()
except OpenedCorrectUrl:
pass
| import os
import sys
import pytest
from mock import patch
import pytest
from pkglib.scripts import pyinstall
@pytest.mark.skipif('TRAVIS' in os.environ,
reason="Our monkey patch doesn't work with the version of setuptools on Travis. FIXME.")
def test_pyinstall_respects_i_flag():
"""Ensure that pyinstall allows us to override the PyPI URL with -i,
even if it's already set in the config.
"""
pypi_url = "http://some-pypi-host/simple"
package_name = "some-package"
expected_url = "%s/%s/" % (pypi_url, package_name)
class OpenedCorrectUrl(Exception): pass
def fake_urlopen(request, *args, **kwargs):
assert request.get_full_url() == expected_url
# We don't actually want pyinstall to install anything, so we
# raise an exception so we terminate here.
raise OpenedCorrectUrl()
with patch('setuptools.package_index.urllib2.urlopen', fake_urlopen):
# Call pyinstall with the -i flag.
args = ['pyinstall', '-i', pypi_url, package_name]
with patch.object(sys, 'argv', args):
try:
pyinstall.main()
except OpenedCorrectUrl:
pass
|
Add util to node namedExports | export default {
declarationKeyword: 'const',
// As listed in https://github.com/nodejs/node/tree/master/lib
//
// Note that we do not include `process` in this list because that is
// available globally in node environments and will cause the following error
// if imported:
//
// Error: Cannot find module 'process' from 'Foo.js'
coreModules: [
'assert',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'dns',
'domain',
'events',
'fs',
'http',
'https',
'module',
'net',
'os',
'path',
'punycode',
'querystring',
'readline',
'repl',
'stream',
'string_decoder',
'sys',
'timers',
'tls',
'tty',
'url',
'util',
'v8',
'vm',
'zlib',
],
namedExports: {
util: [
'callbackify',
'debugLog',
'deprecate',
'format',
'inherits',
'inspect',
'promisify',
],
},
};
| export default {
declarationKeyword: 'const',
// As listed in https://github.com/nodejs/node/tree/master/lib
//
// Note that we do not include `process` in this list because that is
// available globally in node environments and will cause the following error
// if imported:
//
// Error: Cannot find module 'process' from 'Foo.js'
coreModules: [
'assert',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'dns',
'domain',
'events',
'fs',
'http',
'https',
'module',
'net',
'os',
'path',
'punycode',
'querystring',
'readline',
'repl',
'stream',
'string_decoder',
'sys',
'timers',
'tls',
'tty',
'url',
'util',
'v8',
'vm',
'zlib',
],
};
|
Add raw_request method for FakeDiamondashApiClient to correspond to the recently added DiamondashApiClient.raw_request() | import json
from go.dashboard import DiamondashApiError, DiamondashApiClient
class FakeDiamondashApiClient(DiamondashApiClient):
def __init__(self):
self.requests = []
self._response = None
@property
def response(self):
if isinstance(self._response, Exception):
raise self._response
return self._response
def set_error_response(self, code, message):
data = json.dumps({
'success': False,
'message': message
})
self._response = DiamondashApiError("(%s) %s" % (code, data))
def set_response(self, response):
self._response = response
def get_requests(self):
return self.requests
def request(self, method, url, data):
self.requests.append({
'method': method,
'url': url,
'data': data,
})
return self.response
def raw_request(self, method, url, content=""):
self.requests.append({
'method': method,
'url': url,
'content': content,
})
return self.response
| import json
from go.dashboard import DiamondashApiError, DiamondashApiClient
class FakeDiamondashApiClient(DiamondashApiClient):
def __init__(self):
self.requests = []
self.response = None
def get_requests(self):
return self.requests
def set_error_response(self, code, message):
data = json.dumps({
'success': False,
'message': message
})
self.response = DiamondashApiError("(%s) %s" % (code, data))
def set_response(self, response):
self.response = response
def request(self, method, url, data):
self.requests.append({
'method': method,
'url': url,
'data': data,
})
if isinstance(self.response, Exception):
raise self.response
return self.response
|
Remove some methods that shouldn't have been exposed | package tc.oc.projectares.api;
import java.util.Collection;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nonnull;
import org.bukkit.World;
public interface Match {
@Nonnull World getWorld();
@Nonnull UUID getUUID();
@Nonnull boolean isRunning();
@Nonnull boolean start();
@Nonnull boolean end();
@Nonnull boolean end(@Nonnull Team winningTeam);
@Nonnull Collection<Player> getPlayers();
@Nonnull Set<Player> getParticipatingPlayers();
@Nonnull Set<Player> getObservingPlayers();
void broadcast(String message);
@Nonnull Set<Team> getTeams();
@Nonnull Set<Team> getParticipatingTeams();
@Nonnull Set<Team> getObservingTeams();
Team getFirstOther(Team exclude);
}
| package tc.oc.projectares.api;
import java.util.Collection;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nonnull;
import org.bukkit.World;
public interface Match {
@Nonnull World getWorld();
@Nonnull UUID getUUID();
@Nonnull boolean isRunning();
@Nonnull boolean start();
@Nonnull boolean end();
@Nonnull boolean end(@Nonnull Team winningTeam);
@Nonnull Collection<Player> getPlayers();
@Nonnull Set<Player> getParticipatingPlayers();
@Nonnull Set<Player> getObservingPlayers();
Player getPlayer(org.bukkit.entity.Player player);
@Nonnull Player addPlayer(org.bukkit.entity.Player player);
void removePlayer(org.bukkit.entity.Player player);
void removeAllPlayers();
void broadcast(String message);
@Nonnull Set<Team> getTeams();
@Nonnull Set<Team> getParticipatingTeams();
@Nonnull Set<Team> getObservingTeams();
Team getFirstOther(Team exclude);
}
|
Fix the django debug toolbar not appearing and the user echo thing slowing my loadings in development. | # Debug-toolbar related
INSTALLED_APPS += ('debug_toolbar', )
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', )
INTERNAL_IPS = (
'127.0.0.1',
# gurney.licorn.org
'109.190.93.141',
# my LAN
'192.168.111.23',
'192.168.111.111',
)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'template_timings_panel.panels.TemplateTimings.TemplateTimings',
'debug_toolbar.panels.logger.LoggingPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
'debug_toolbar.panels.version.VersionDebugPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'ENABLE_STACKTRACES' : True,
#'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
#'EXTRA_SIGNALS': ['myproject.signals.MySignal'],
#'HIDE_DJANGO_SQL': False,
#'TAG': 'div',
}
| # Debug-toolbar related
INSTALLED_APPS += ('debug_toolbar', )
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware', )
INTERNAL_IPS = (
'127.0.0.1',
# leto.licorn.org
'82.236.133.193',
)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
'debug_toolbar.panels.headers.HeaderDebugPanel',
'debug_toolbar.panels.template.TemplateDebugPanel',
'template_timings_panel.panels.TemplateTimings.TemplateTimings',
'debug_toolbar.panels.logger.LoggingPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.signals.SignalDebugPanel',
'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',
'debug_toolbar.panels.version.VersionDebugPanel',
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'ENABLE_STACKTRACES' : True,
#'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
#'EXTRA_SIGNALS': ['myproject.signals.MySignal'],
#'HIDE_DJANGO_SQL': False,
#'TAG': 'div',
}
|
Fix colorspace determinism with OrderedDict | import collections
from .psparser import LIT
import six #Python 2+3 compatibility
## PDFColorSpace
##
LITERAL_DEVICE_GRAY = LIT('DeviceGray')
LITERAL_DEVICE_RGB = LIT('DeviceRGB')
LITERAL_DEVICE_CMYK = LIT('DeviceCMYK')
class PDFColorSpace(object):
def __init__(self, name, ncomponents):
self.name = name
self.ncomponents = ncomponents
return
def __repr__(self):
return '<PDFColorSpace: %s, ncomponents=%d>' % (self.name, self.ncomponents)
PREDEFINED_COLORSPACE = collections.OrderedDict()
for (name, n) in [
('CalRGB', 3),
('CalGray', 1),
('Lab', 3),
('DeviceRGB', 3),
('DeviceCMYK', 4),
('DeviceGray', 1),
('Separation', 1),
('Indexed', 1),
('Pattern', 1),
]:
PREDEFINED_COLORSPACE[name]=PDFColorSpace(name, n)
|
from .psparser import LIT
import six #Python 2+3 compatibility
## PDFColorSpace
##
LITERAL_DEVICE_GRAY = LIT('DeviceGray')
LITERAL_DEVICE_RGB = LIT('DeviceRGB')
LITERAL_DEVICE_CMYK = LIT('DeviceCMYK')
class PDFColorSpace(object):
def __init__(self, name, ncomponents):
self.name = name
self.ncomponents = ncomponents
return
def __repr__(self):
return '<PDFColorSpace: %s, ncomponents=%d>' % (self.name, self.ncomponents)
PREDEFINED_COLORSPACE = {}
for (name, n) in six.iteritems({
'CalRGB': 3,
'CalGray': 1,
'Lab': 3,
'DeviceRGB': 3,
'DeviceCMYK': 4,
'DeviceGray': 1,
'Separation': 1,
'Indexed': 1,
'Pattern': 1,
}) :
PREDEFINED_COLORSPACE[name]=PDFColorSpace(name, n)
|
Fix typo that broke inventory breadcrumb links | @extends('layouts.blog')
@section('content')
<section class="col-sm-8 blog-main blog-inventory">
<ol class="breadcrumb">
<li><a href="/blog">Blog</a></li>
@if (isset($group_title) && $group_title !== '')
<li><a href="/blog/{{strtolower($group_title)}}">{{ucfirst(strtolower($group_title))}}</a></li>
@endif
@if (isset($group) && $group !== '')
{{date_links($group, "li")}}
@endif
</ol>
@foreach ($results as $result)
@include('blog.item')
@endforeach
@include('layouts.pagination')
</section><!-- /.blog-main -->
@include('blog.sidebar')
@stop
| @extends('layouts.blog')
@section('content')
<section class="col-sm-8 blog-main blog-inventory">
<ol class="breadcrumb">
<li><a href="/blog">Blog</a></li>
@if (isset($group_title) && $group_title !== '')
<li><a href="/blog/{{strtolower($group_title)}}'">{{ucfirst(strtolower($group_title))}}</a></li>
@endif
@if (isset($group) && $group !== '')
{{date_links($group, "li")}}
@endif
</ol>
@foreach ($results as $result)
@include('blog.item')
@endforeach
@include('layouts.pagination')
</section><!-- /.blog-main -->
@include('blog.sidebar')
@stop
|
Enable the SmartyPants filter; need to document it later
git-svn-id: 4b29f3e8959dfd6aa2f99bd14fd314e33970d95d@74 d6b9e1ad-042d-0410-a639-15a354c1509c | """
Filters for converting plain text to HTML and enhancing the
typographic appeal of text on the Web.
"""
from django.conf import settings
from django.template import Library
from template_utils.markup import formatter
def apply_markup(value, arg=None):
"""
Applies text-to-HTML conversion.
Takes an optional argument to specify the name of a filter to use.
"""
if arg is not None:
return formatter(value, filter_name=arg)
return formatter(value)
def smartypants(value):
"""
Applies SmartyPants to a piece of text, applying typographic
niceties.
Requires the Python SmartyPants library to be installed; see
http://web.chad.org/projects/smartypants.py/
"""
try:
from smartypants import smartyPants
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in smartypants filter: the Python smartypants module is not installed or could not be imported")
return value
else:
return smartyPants(value)
register = Library()
register.filter(apply_markup)
register.filter(smartypants)
| """
Filters for converting plain text to HTML and enhancing the
typographic appeal of text on the Web.
"""
from django.conf import settings
from django.template import Library
from template_utils.markup import formatter
def apply_markup(value, arg=None):
"""
Applies text-to-HTML conversion.
Takes an optional argument to specify the name of a filter to use.
"""
if arg is not None:
return formatter(value, filter_name=arg)
return formatter(value)
def smartypants(value):
"""
Applies SmartyPants to a piece of text, applying typographic
niceties.
Requires the Python SmartyPants library to be installed; see
http://web.chad.org/projects/smartypants.py/
"""
try:
from smartypants import smartyPants
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError("Error in smartypants filter: the Python smartypants module is not installed or could not be imported")
return value
else:
return smartyPants(value)
register = Library()
register.filter(apply_markup)
|
Change `assign` to not use a for-in loop
Apparently, v8’s JIT engineers require that we, as JavaScript developers
perform this very simple transformation, since they do not seem capable
of performing it themselves. | import keys from 'ember-metal/keys';
/**
Merge the contents of two objects together into the first object.
```javascript
Ember.merge({first: 'Tom'}, {last: 'Dale'}); // {first: 'Tom', last: 'Dale'}
var a = {first: 'Yehuda'};
var b = {last: 'Katz'};
Ember.merge(a, b); // a == {first: 'Yehuda', last: 'Katz'}, b == {last: 'Katz'}
```
@method merge
@for Ember
@param {Object} original The object to merge into
@param {Object} updates The object to copy properties from
@return {Object}
*/
export default function merge(original, updates) {
if (!updates || typeof updates !== 'object') {
return original;
}
var props = keys(updates);
var prop;
var length = props.length;
for (var i = 0; i < length; i++) {
prop = props[i];
original[prop] = updates[prop];
}
return original;
}
export function assign(original, ...args) {
for (let i=0, l=args.length; i<l; i++) {
let arg = args[i];
if (!arg) { continue; }
let updates = keys(arg);
for (let i=0, l=updates.length; i<l; i++) {
let prop = updates[i];
original[prop] = arg[prop];
}
}
return original;
}
| import keys from 'ember-metal/keys';
/**
Merge the contents of two objects together into the first object.
```javascript
Ember.merge({first: 'Tom'}, {last: 'Dale'}); // {first: 'Tom', last: 'Dale'}
var a = {first: 'Yehuda'};
var b = {last: 'Katz'};
Ember.merge(a, b); // a == {first: 'Yehuda', last: 'Katz'}, b == {last: 'Katz'}
```
@method merge
@for Ember
@param {Object} original The object to merge into
@param {Object} updates The object to copy properties from
@return {Object}
*/
export default function merge(original, updates) {
if (!updates || typeof updates !== 'object') {
return original;
}
var props = keys(updates);
var prop;
var length = props.length;
for (var i = 0; i < length; i++) {
prop = props[i];
original[prop] = updates[prop];
}
return original;
}
export function assign(original, ...args) {
for (let i=0, l=args.length; i<l; i++) {
let arg = args[i];
if (!arg) { continue; }
for (let prop in arg) {
if (arg.hasOwnProperty(prop)) { original[prop] = arg[prop]; }
}
}
return original;
}
|
Fix logic around what constitutes a connection failure | package redis
import (
"log"
"time"
redis "github.com/go-redis/redis"
try "github.com/matryer/try"
)
// ConnectToClient Connects to a Redis server
func ConnectToClient(ip string, port string, config Config) *redis.Client {
client := redis.NewClient(&redis.Options{
Addr: ip + ":" + port,
})
return client
}
// IsWorkingInstance Checks that a registered IP is up and running. Blocking
func IsWorkingInstance(client *redis.Client) (bool, error) {
err := try.Do(func(attempt int) (bool, error) {
pong, err := client.Ping().Result()
if err != nil && pong != "PONG" {
log.Printf("Client (%s) not ready, will retry", client.Options().Addr)
} else {
log.Printf("Client (%s) ready", client.Options().Addr)
}
if err != nil {
time.Sleep(2 * time.Second)
}
return attempt < 10, err
})
if err == nil {
return true, err
}
return false, err
}
| package redis
import (
"log"
"time"
redis "github.com/go-redis/redis"
try "github.com/matryer/try"
)
// ConnectToClient Connects to a Redis server
func ConnectToClient(ip string, port string, config Config) *redis.Client {
client := redis.NewClient(&redis.Options{
Addr: ip + ":" + port,
})
return client
}
// IsWorkingInstance Checks that a registered IP is up and running. Blocking
func IsWorkingInstance(client *redis.Client) (bool, error) {
err := try.Do(func(attempt int) (bool, error) {
pong, err := client.Ping().Result()
if err != nil && pong != "PONG" {
log.Printf("Client (%s) not ready, will retry", client.Options().Addr)
} else {
log.Printf("Client (%s) ready", client.Options().Addr)
}
if err != nil {
time.Sleep(2 * time.Second)
}
return true, err // infinite retry
})
if err != nil {
return true, err
}
return false, err
}
|
Remove debug console output from ParametersEditor. | App.module("Predictor", function(Mod, App, Backbone, Marionette, $, _) {
Mod.views.FlightParametersEditor = Marionette.ItemView.extend({
template: 'flightParametersEditor',
model: Mod.FlightModel,
tagName: 'form',
events: {
'click #next': 'next',
'click #prev': 'prev'
},
onShow: function() {
// Populate form with current data
Backbone.Syphon.deserialize(this, Mod.currentPrediction.attributes);
},
next: function() {
// Serialize the form
var data = Backbone.Syphon.serialize(this);
// Store the data in the current model
if(data.brand) Mod.currentPrediction.set({'brand':data.brand});
if(data.size) Mod.currentPrediction.set({'size':data.size});
if(data.mass) Mod.currentPrediction.set({'mass':data.mass});
if(data.lift) Mod.currentPrediction.set({'lift':data.lift});
// Save the model
Mod.currentPrediction.save();
// Go to the next step
App.vent.trigger('ForwardPrediction:Display', 3);
},
prev: function() {
App.vent.trigger('ForwardPrediction:Display', 1);
}
});
}); | App.module("Predictor", function(Mod, App, Backbone, Marionette, $, _) {
Mod.views.FlightParametersEditor = Marionette.ItemView.extend({
template: 'flightParametersEditor',
model: Mod.FlightModel,
tagName: 'form',
events: {
'click #next': 'next',
'click #prev': 'prev'
},
onShow: function() {
// Populate form with current data
Backbone.Syphon.deserialize(this, Mod.currentPrediction.attributes);
},
next: function() {
// Serialize the form
var data = Backbone.Syphon.serialize(this);
console.log(data);
// Store the data in the current model
if(data.brand) Mod.currentPrediction.set({'brand':data.brand});
if(data.size) Mod.currentPrediction.set({'size':data.size});
if(data.mass) Mod.currentPrediction.set({'mass':data.mass});
if(data.lift) Mod.currentPrediction.set({'lift':data.lift});
// Save the model
Mod.currentPrediction.save();
// Go to the next step
App.vent.trigger('ForwardPrediction:Display', 3);
},
prev: function() {
App.vent.trigger('ForwardPrediction:Display', 1);
}
});
}); |
Add "id" so usable with JPA or JDO application-identity | /**********************************************************************
Copyright (c) 2005 Erik Bengtson and others.
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.
Contributors:
...
**********************************************************************/
package org.jpox.samples.types.color;
/**
* Object with a Color.
*/
public class ColorHolder
{
long id;
private java.awt.Color colorA;
public void setId(long id)
{
this.id = id;
}
public long getId()
{
return id;
}
public java.awt.Color getColorA()
{
return colorA;
}
public void setColorA(java.awt.Color colorA)
{
this.colorA = colorA;
}
} | /**********************************************************************
Copyright (c) 2005 Erik Bengtson and others.
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.
Contributors:
...
**********************************************************************/
package org.jpox.samples.types.color;
/**
* Object with a Color.
*
* @version $Revision: 1.1 $
*/
public class ColorHolder
{
private java.awt.Color colorA;
/**
* @return Returns the colorA.
*/
public java.awt.Color getColorA()
{
return colorA;
}
/**
* @param colorA The colorA to set.
*/
public void setColorA(java.awt.Color colorA)
{
this.colorA = colorA;
}
} |
Core: Use cmd comma for options | /*
* Copyright 2017 Patrik Karlsson.
*
* 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 org.nbgames.core.actions;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
/**
*
* @author Patrik Karlsson
*/
public class CallbackOptionsAction {
@ActionID(category = "Game",
id = "org.nbgames.core.actions.OptionsAction")
@ActionRegistration(displayName = "#CTL_OptionsAction")
@ActionReferences({
@ActionReference(path = "Shortcuts", name = "D-P")
,
@ActionReference(path = "Shortcuts", name = "D-COMMA")
})
@NbBundle.Messages("CTL_OptionsAction=Options")
public static final String KEY = "OptionsAction";
}
| /*
* Copyright 2017 Patrik Karlsson.
*
* 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 org.nbgames.core.actions;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
/**
*
* @author Patrik Karlsson
*/
public class CallbackOptionsAction {
@ActionID(category = "Game",
id = "org.nbgames.core.actions.OptionsAction")
@ActionRegistration(displayName = "#CTL_OptionsAction")
@ActionReferences({
@ActionReference(path = "Shortcuts", name = "D-P")
,
@ActionReference(path = "Shortcuts", name = "C-PERIOD")
})
@NbBundle.Messages("CTL_OptionsAction=Options")
public static final String KEY = "OptionsAction";
}
|
Fix code style in TodoMVC Flux example | /**
* Copyright 2013-2014 Facebook, 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.
*
* @jsx React.DOM
*/
var React = require('react');
var TodoActions = require('../actions/TodoActions');
var TodoTextInput = require('./TodoTextInput.react');
var Header = React.createClass({
/**
* @return {object}
*/
render: function() {
return (
<header id="header">
<h1>todos</h1>
<TodoTextInput
id="new-todo"
placeholder="What needs to be done?"
onSave={this._onSave}
/>
</header>
);
},
/**
* Event handler called within TodoTextInput.
* Defining this here allows TodoTextInput to be used in multiple places
* in different ways.
* @param {string} text
*/
_onSave: function(text) {
if (text.trim()){
TodoActions.create(text);
}
}
});
module.exports = Header;
| /**
* Copyright 2013-2014 Facebook, 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.
*
* @jsx React.DOM
*/
var React = require('react');
var TodoActions = require('../actions/TodoActions');
var TodoTextInput = require('./TodoTextInput.react');
var Header = React.createClass({
/**
* @return {object}
*/
render: function() {
return (
<header id="header">
<h1>todos</h1>
<TodoTextInput
id="new-todo"
placeholder="What needs to be done?"
onSave={this._onSave}
/>
</header>
);
},
/**
* Event handler called within TodoTextInput.
* Defining this here allows TodoTextInput to be used in multiple places
* in different ways.
* @param {string} text
*/
_onSave: function(text) {
if(text.trim()){
TodoActions.create(text);
}
}
});
module.exports = Header;
|
Fix crash on missing classes (it will crash later, but nobody will blame us | package openmods.asm;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import com.google.common.base.Preconditions;
public class OpenModsClassTransformer implements IClassTransformer {
public static interface TransformProvider {
public ClassVisitor createVisitor(ClassVisitor cv);
}
private final static TransformProvider INCLUDING_CV = new TransformProvider() {
@Override
public ClassVisitor createVisitor(ClassVisitor cv) {
return new IncludingClassVisitor(cv);
}
};
public static byte[] applyVisitor(byte[] bytes, int flags, TransformProvider context) {
Preconditions.checkNotNull(bytes);
ClassReader cr = new ClassReader(bytes);
ClassWriter cw = new ClassWriter(cr, flags);
ClassVisitor mod = context.createVisitor(cw);
try {
cr.accept(mod, 0);
return cw.toByteArray();
} catch (StopTransforming e) {
return bytes;
}
}
@Override
public byte[] transform(final String name, String transformedName, byte[] bytes) {
if (bytes == null || name.startsWith("openmods.asm") || name.startsWith("net.minecraft.")) return bytes;
// / no need for COMPUTE_FRAMES, we can handle simple stuff
return applyVisitor(bytes, 0, INCLUDING_CV);
}
}
| package openmods.asm;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
public class OpenModsClassTransformer implements IClassTransformer {
public static interface TransformProvider {
public ClassVisitor createVisitor(ClassVisitor cv);
}
private final static TransformProvider INCLUDING_CV = new TransformProvider() {
@Override
public ClassVisitor createVisitor(ClassVisitor cv) {
return new IncludingClassVisitor(cv);
}
};
public static byte[] applyVisitor(byte[] bytes, int flags, TransformProvider context) {
ClassReader cr = new ClassReader(bytes);
ClassWriter cw = new ClassWriter(cr, flags);
ClassVisitor mod = context.createVisitor(cw);
try {
cr.accept(mod, 0);
return cw.toByteArray();
} catch (StopTransforming e) {
return bytes;
}
}
@Override
public byte[] transform(final String name, String transformedName, byte[] bytes) {
if (name.startsWith("openmods.asm")) return bytes;
// / no need for COMPUTE_FRAMES, we can handle simple stuff
return applyVisitor(bytes, 0, INCLUDING_CV);
}
}
|
Fix href macro called without path parameter. | include('ringo/markdown');
require('core/string');
exports.href_macro = function(tag) {
var req = require('ringo/webapp/env').getRequest();
return req.rootPath + (tag.parameters[0] || '');
};
exports.matchPath_macro = function(tag) {
var req = require('ringo/webapp/env').getRequest();
if (req && req.path &&
req.path.substring(req.rootPath.length).match(tag.parameters[0])) {
return tag.parameters[1] || "match";
}
};
exports.markdown_filter = function(content) {
var markdown = new Markdown({});
return markdown.process(content);
};
exports.ifOdd_macro = function(tag, context) {
var number = context["index"];
if (isFinite(number) && number % 2 === 1)
return tag.parameters.join("");
};
exports.ifEven_macro = function(tag, context) {
var number = context["index"];
if (isFinite(number) && number % 2 === 0)
return tag.parameters.join("");
};
| include('ringo/markdown');
require('core/string');
exports.href_macro = function(tag) {
var req = require('ringo/webapp/env').getRequest();
return req.rootPath + tag.parameters[0] || '';
};
exports.matchPath_macro = function(tag) {
var req = require('ringo/webapp/env').getRequest();
if (req && req.path &&
req.path.substring(req.rootPath.length).match(tag.parameters[0])) {
return tag.parameters[1] || "match";
}
};
exports.markdown_filter = function(content) {
var markdown = new Markdown({});
return markdown.process(content);
};
exports.ifOdd_macro = function(tag, context) {
var number = context["index"];
if (isFinite(number) && number % 2 === 1)
return tag.parameters.join("");
};
exports.ifEven_macro = function(tag, context) {
var number = context["index"];
if (isFinite(number) && number % 2 === 0)
return tag.parameters.join("");
};
|
Update get route to "name" | var ApiBuilder = require('claudia-api-builder'),
api = new ApiBuilder();
module.exports = api;
api.get('/', function () {
'use strict';
return 'Hello World';
});
api.get('/echo', function (request) {
'use strict';
return request;
});
api.get('/name', function (request) {
'use strict';
return 'My name is ' + request.queryString.name;
});
api.get('/people/{name}', function (request) {
'use strict';
return request.pathParams.name + ' is ' + superb();
});
api.get('/json', function (request) {
'use strict';
return {
name: 'John',
surname: 'Doe',
email: 'johndoe@example.com'
};
});
api.post('/echo', function (request) {
'use strict';
return request.body;
}); | var ApiBuilder = require('claudia-api-builder'),
api = new ApiBuilder();
module.exports = api;
api.get('/', function () {
'use strict';
return 'Hello World';
});
api.get('/echo', function (request) {
'use strict';
return request;
});
api.get('/greet', function (request) {
'use strict';
return 'My name is ' + request.queryString.name;
});
api.get('/people/{name}', function (request) {
'use strict';
return request.pathParams.name + ' is ' + superb();
});
api.get('/json', function (request) {
'use strict';
return {
name: 'John',
surname: 'Doe',
email: 'johndoe@example.com'
};
});
api.post('/echo', function (request) {
'use strict';
return request.body;
}); |
Use HTTP as HTTPS is paid for. | var request = require("request");
var Q = require("q");
var log4js = require("log4js");
var logger = log4js.getLogger("OpenWeatherMapInterface");
function OpenWeatherMapInterface(options) {
this.apiKey = options.api_key;
}
OpenWeatherMapInterface.prototype.queryPostCode = function(postCode, countryCode) {
// Use HTTP instead of HTTPS because HTTPS is paid for
var url = "http://api.openweathermap.org/data/2.5/weather?zip=" + postCode + "," + countryCode + "&APPID=" + this.apiKey;
var deferred = Q.defer();
logger.debug("Making request to: ", url);
request.get(url, function(err, res, body) {
if(err) {
return deferred.reject(err);
}
console.log(body);
deferred.resolve(JSON.parse(body));
});
return deferred.promise;
};
module.exports = OpenWeatherMapInterface;
| var request = require("request");
var Q = require("q");
var log4js = require("log4js");
var logger = log4js.getLogger("OpenWeatherMapInterface");
function OpenWeatherMapInterface(options) {
this.apiKey = options.api_key;
}
OpenWeatherMapInterface.prototype.queryPostCode = function(postCode, countryCode) {
var url = "https://api.openweathermap.org/data/2.5/weather?zip=" + postCode + "," + countryCode + "&APPID=" + this.apiKey;
var deferred = Q.defer();
logger.debug("Making request to: ", url);
request.get(url, function(err, res, body) {
if(err) {
return deferred.reject(err);
}
console.log(body);
deferred.resolve(JSON.parse(body));
});
return deferred.promise;
};
module.exports = OpenWeatherMapInterface;
|
Add missing requirements for websockets
HBMQTT-25 | # Copyright (c) 2015 Nicolas JOUANIN
#
# See the file license.txt for copying permission.
from setuptools import setup, find_packages
from hbmqtt.version import get_version
setup(
name="hbmqtt",
version=get_version(),
description="HBMQTT - HomeBrew MQTT\nclient/brocker using Python 3.4 asyncio library",
author="Nicolas Jouanin",
author_email='nico@beerfactory.org',
url="https://github.com/beerfactory/hbmqtt",
license='MIT',
packages=find_packages(exclude=['tests']),
install_requires=[
'transitions==0.2.5',
'blinker',
'websockets'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python :: 3.4',
'Topic :: Communications',
'Topic :: Internet'
]
) | # Copyright (c) 2015 Nicolas JOUANIN
#
# See the file license.txt for copying permission.
from setuptools import setup, find_packages
from hbmqtt.version import get_version
setup(
name="hbmqtt",
version=get_version(),
description="HBMQTT - HomeBrew MQTT\nclient/brocker using Python 3.4 asyncio library",
author="Nicolas Jouanin",
author_email='nico@beerfactory.org',
url="https://github.com/beerfactory/hbmqtt",
license='MIT',
packages=find_packages(exclude=['tests']),
install_requires=['transitions', 'blinker'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python :: 3.4',
'Topic :: Communications',
'Topic :: Internet'
]
) |
Update RMG example minimal_sensitivity with multiplicity label | # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# Constraints on generated species
generatedSpeciesConstraints(
maximumRadicalElectrons = 2,
)
# List of species
species(
label='ethane',
multiplicity = 1,
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
| # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
|
Add trove classifier for Python 3 | from distutils.core import setup
setup(name = "bitey",
description="Bitcode Import Tool",
long_description = """
Bitey allows LLVM bitcode to be directly imported into Python as
an high performance extension module without the need for writing wrappers.
""",
license="""BSD""",
version = "0.0",
author = "David Beazley",
author_email = "dave@dabeaz.com",
maintainer = "David Beazley",
maintainer_email = "dave@dabeaz.com",
url = "https://github.com/dabeaz/bitey/",
packages = ['bitey'],
classifiers = [
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
| from distutils.core import setup
setup(name = "bitey",
description="Bitcode Import Tool",
long_description = """
Bitey allows LLVM bitcode to be directly imported into Python as
an high performance extension module without the need for writing wrappers.
""",
license="""BSD""",
version = "0.0",
author = "David Beazley",
author_email = "dave@dabeaz.com",
maintainer = "David Beazley",
maintainer_email = "dave@dabeaz.com",
url = "https://github.com/dabeaz/bitey/",
packages = ['bitey'],
classifiers = [
'Programming Language :: Python :: 2',
]
)
|
refactor(babel): Remove direct transform runtime requirement and turn on the userBuiltIns flag for b | const addExports = require('babel-plugin-add-module-exports')
const babelEnv = require('@babel/preset-env')
const flow = require('@babel/preset-flow')
const react = require('@babel/preset-react')
const reactRequire = require('babel-plugin-react-require').default
const lodash = require('babel-plugin-lodash')
const reactDisplayName = require('@babel/plugin-transform-react-display-name')
const classProperties = require('@babel/plugin-proposal-class-properties')
const exportFrom = require('@babel/plugin-proposal-export-namespace-from')
const browsers = require('./constants').BROWSER_SUPPORT
module.exports = function (env) {
const plugins = [
addExports,
classProperties,
exportFrom,
lodash,
reactDisplayName,
reactRequire
]
return {
plugins,
presets: [
[
babelEnv,
{
loose: false, // Loose mode breaks spread operator on `Set`s
targets: { browsers },
useBuiltIns: 'usage'
}
],
flow,
react
]
}
}
| const addExports = require('babel-plugin-add-module-exports')
const babelEnv = require('@babel/preset-env')
const flow = require('@babel/preset-flow')
const react = require('@babel/preset-react')
const reactRequire = require('babel-plugin-react-require').default
const lodash = require('babel-plugin-lodash')
const reactDisplayName = require('@babel/plugin-transform-react-display-name')
const transformRuntime = require('@babel/plugin-transform-runtime')
const classProperties = require('@babel/plugin-proposal-class-properties')
const exportFrom = require('@babel/plugin-proposal-export-namespace-from')
const browsers = require('./constants').BROWSER_SUPPORT
module.exports = function (env) {
const plugins = [
addExports,
classProperties,
exportFrom,
lodash,
reactDisplayName,
reactRequire,
transformRuntime
]
return {
plugins,
presets: [
[
babelEnv,
{
loose: false, // Loose mode breaks spread operator on `Set`s
targets: { browsers }
}
],
flow,
react
]
}
}
|
Fix "Expected '===' and instead saw '=='" | var fs = require('fs');
var path = require('path');
var CssFile = require('./cssfile');
var HtmlFile = require('./htmlfile');
function walk(dir, result) {
var stat = fs.statSync(dir);
if (stat.isFile()) {
result.push(dir);
} else if (stat.isDirectory()) {
fs.readdirSync(dir).forEach(function(item) {
var fullpath = path.join(dir, item);
walk(fullpath, result);
});
}
}
function find(dir, options) {
var result = [];
walk(dir, result);
if (options.ext) {
return result.filter(function(f) {
return path.extname(f) === '.' + options.ext;
});
} else {
return result;
}
}
function findCssFiles(dir) {
var files = this.find(dir, {ext: 'css'});
return files.map(function(f) {
return new CssFile(f);
});
}
function findHtmlFiles(dir) {
var files = this.find(dir, {ext: 'html'});
return files.map(function(f) {
return new HtmlFile(f);
});
}
exports.find = find;
exports.findCssFiles = findCssFiles;
exports.findHtmlFiles = findHtmlFiles;
| var fs = require('fs');
var path = require('path');
var CssFile = require('./cssfile');
var HtmlFile = require('./htmlfile');
function walk(dir, result) {
var stat = fs.statSync(dir);
if (stat.isFile()) {
result.push(dir);
} else if (stat.isDirectory()) {
fs.readdirSync(dir).forEach(function(item) {
var fullpath = path.join(dir, item);
walk(fullpath, result);
});
}
}
function find(dir, options) {
var result = [];
walk(dir, result);
if (options.ext) {
return result.filter(function(f) {
return path.extname(f) == '.' + options.ext;
});
} else {
return result;
}
}
function findCssFiles(dir) {
var files = this.find(dir, {ext: 'css'});
return files.map(function(f) {
return new CssFile(f);
});
}
function findHtmlFiles(dir) {
var files = this.find(dir, {ext: 'html'});
return files.map(function(f) {
return new HtmlFile(f);
});
}
exports.find = find;
exports.findCssFiles = findCssFiles;
exports.findHtmlFiles = findHtmlFiles;
|
Update pyuntl source to match aubrey's requirement | #!/usr/bin/env python
from setuptools import setup
setup(
name='aubreylib',
version='2.0.0',
description='A helper library for the Aubrey access system.',
author='University of North Texas Libraries',
author_email='mark.phillips@unt.edu',
url='https://github.com/unt-libraries/aubreylib',
license='BSD',
packages=['aubreylib'],
install_requires=[
'lxml>=3.3.3',
'pypairtree>=1.0.0',
'pyuntl @ git+https://github.com/unt-libraries/pyuntl.git@master#egg=pyuntl',
],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 3.7',
]
)
| #!/usr/bin/env python
from setuptools import setup
setup(
name='aubreylib',
version='2.0.0',
description='A helper library for the Aubrey access system.',
author='University of North Texas Libraries',
author_email='mark.phillips@unt.edu',
url='https://github.com/unt-libraries/aubreylib',
license='BSD',
packages=['aubreylib'],
install_requires=[
'lxml>=3.3.3',
'pypairtree>=1.0.0',
'pyuntl @ git+https://github.com/unt-libraries/pyuntl@master',
],
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 3.7',
]
)
|
Update hash link tests to use enzyme. | /* Copyright (C) 2017 Canonical Ltd. */
'use strict';
const React = require('react');
const enzyme = require('enzyme');
const HashLink = require('./hash-link');
const SvgIcon = require('../svg-icon/svg-icon');
describe('HashLink', () => {
const renderComponent = (options = {}) => enzyme.shallow(
<HashLink
changeState={options.changeState || sinon.stub()}
hash={options.hash || 'readme'} />
);
it('can render', () => {
const wrapper = renderComponent();
const expected = (
<div className="hash-link"
onClick={wrapper.prop('onClick')}>
<SvgIcon
name="anchor_16"
size="16" />
</div>);
assert.compareJSX(wrapper, expected);
});
it('can change the hash state', () => {
const changeState = sinon.stub();
const wrapper = renderComponent({ changeState });
wrapper.props().onClick();
assert.equal(changeState.callCount, 1);
assert.deepEqual(changeState.args[0][0], {
hash: 'readme'
});
});
});
| /* Copyright (C) 2017 Canonical Ltd. */
'use strict';
const React = require('react');
const HashLink = require('./hash-link');
const SvgIcon = require('../svg-icon/svg-icon');
const jsTestUtils = require('../../utils/component-test-utils');
describe('HashLink', () => {
it('can render', () => {
const renderer = jsTestUtils.shallowRender(
<HashLink
changeState={sinon.stub()}
hash="readme" />, true);
const instance = renderer.getMountedInstance();
const output = renderer.getRenderOutput();
const expected = (
<div className="hash-link"
onClick={instance._handleClick}>
<SvgIcon
name="anchor_16"
size="16" />
</div>);
expect(output).toEqualJSX(expected);
});
it('can change the has state', () => {
const changeState = sinon.stub();
const renderer = jsTestUtils.shallowRender(
<HashLink
changeState={changeState}
hash="readme" />, true);
const output = renderer.getRenderOutput();
output.props.onClick();
assert.equal(changeState.callCount, 1);
assert.deepEqual(changeState.args[0][0], {
hash: 'readme'
});
});
});
|
Bump httplib2 from 0.9.1 to 0.19.0
Bumps [httplib2](https://github.com/httplib2/httplib2) from 0.9.1 to 0.19.0.
- [Release notes](https://github.com/httplib2/httplib2/releases)
- [Changelog](https://github.com/httplib2/httplib2/blob/master/CHANGELOG)
- [Commits](https://github.com/httplib2/httplib2/compare/0.9.1...v0.19.0)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@github.com> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from setuptools import setup
required = [
'pytest',
'requests',
'requests_oauthlib',
'httplib2==0.19.0',
'python-dateutil',
]
# Python 2 dependencies
if sys.version_info[0] == 2:
required += [
'mock',
]
setup(
name='readability-api',
version='1.0.2',
description='Python client for the Readability Reader and Parser APIs.',
long_description=open('README.rst').read(),
author='The Readability Team',
author_email='philip@readability.com',
url='https://github.com/arc90/python-readability-api',
packages=['readability'],
install_requires=required,
license='MIT',
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: PyPy',
),
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from setuptools import setup
required = [
'pytest',
'requests',
'requests_oauthlib',
'httplib2==0.9.1',
'python-dateutil',
]
# Python 2 dependencies
if sys.version_info[0] == 2:
required += [
'mock',
]
setup(
name='readability-api',
version='1.0.2',
description='Python client for the Readability Reader and Parser APIs.',
long_description=open('README.rst').read(),
author='The Readability Team',
author_email='philip@readability.com',
url='https://github.com/arc90/python-readability-api',
packages=['readability'],
install_requires=required,
license='MIT',
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: PyPy',
),
)
|
Return original text if it contains no native function declarations. | const Applause = require('applause');
module.exports = {
// Here, you can strip out any non-JS content
// and split into multiple strings to lint.
preprocess(text, fileName) {
const applause = Applause.create({
patterns: [
{
match: /native\s+function\s+(\w+)\s*\(\)/g,
replacement: 'var $1 = function() {}'
}
]
});
const substitute = applause.replace(text);
return substitute.content ? [substitute.content] : [text];
},
// `messages` argument contains two-dimensional array of Message objects
// where each top-level array item contains array of lint messages related
// to the text that was returned in array from preprocess() method.
postprocess(messages, fileName) {
const message = messages[0];
return message;
}
};
| const Applause = require('applause');
module.exports = {
// Here, you can strip out any non-JS content
// and split into multiple strings to lint.
preprocess(text, fileName) {
const applause = Applause.create({
patterns: [
{
match: /native\s+function\s+(\w+)\s*\(\)/g,
replacement: 'var $1 = function() {}'
}
]
});
const substitute = applause.replace(text);
return [substitute.content];
},
// `messages` argument contains two-dimensional array of Message objects
// where each top-level array item contains array of lint messages related
// to the text that was returned in array from preprocess() method.
postprocess(messages, fileName) {
const message = messages[0];
return message;
}
};
|
Add parameter to specificy ADC read repeats | """ Access ADCs vias SysFS interface """
import glob
class adc(object):
def __init__(self, num, repeat=8):
self.num = num
# need to read a glob here, since numbering is not consistent
# TODO: verify num is reasonable (0-6)
self.sysfs = glob.glob('/sys/devices/ocp.*/helper.*/AIN' + str(num))[0]
self.repeat = repeat
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self, repeat=None):
if not repeat:
repeat = self.repeat
for i in range(repeat):
val = None
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
return int(val)
| """ Access ADCs vias SysFS interface """
import glob
class adc(object):
def __init__(self, num):
self.num = num
# need to read a glob here, since numbering is not consistent
# TODO: verify num is reasonable (0-6)
self.sysfs = glob.glob('/sys/devices/ocp.*/helper.*/AIN' + str(num))[0]
def __str__(self):
out = "ADC#%d (%s)" % (self.num, self.sysfs)
return out
def read(self):
val = None
while not val:
try:
with open(self.sysfs, 'r') as f:
val = f.read()
except:
pass
# No longer seems to be necessary with the bone26+ kernels?
# val = None
# # Read a second time to ensure we get the current value (bug in ADC driver)
# while not val:
# try:
# with open(self.sysfs, 'r') as f:
# val = f.read()
# except:
# pass
return int(val)
|
Add support for weather queries | package ee.ioc.phon.android.arvutaja.command;
import ee.ioc.phon.android.arvutaja.R;
import android.content.Context;
public class CommandParser {
public static Command getCommand(Context context, String command) throws CommandParseException {
if (command == null) {
throw new CommandParseException();
}
if (Alarm.isCommand(command))
return new Alarm(command, context.getString(R.string.alarmExtraMessage));
if (command.startsWith("weather "))
return new DefaultCommand(command);
if (Dial.isCommand(command))
return new Dial(command);
if (Expr.isCommand(command))
return new Expr(command);
if (Search.isCommand(command))
return new Search(command);
if (Unitconv.isCommand(command))
return new Unitconv(command);
if (Direction.isCommand(command))
return new Direction(command);
return new DefaultCommand(command);
}
} | package ee.ioc.phon.android.arvutaja.command;
import ee.ioc.phon.android.arvutaja.R;
import android.content.Context;
public class CommandParser {
public static Command getCommand(Context context, String command) throws CommandParseException {
if (command == null) {
throw new CommandParseException();
}
if (Alarm.isCommand(command))
return new Alarm(command, context.getString(R.string.alarmExtraMessage));
if (Dial.isCommand(command))
return new Dial(command);
if (Expr.isCommand(command))
return new Expr(command);
if (Search.isCommand(command))
return new Search(command);
if (Unitconv.isCommand(command))
return new Unitconv(command);
if (Direction.isCommand(command))
return new Direction(command);
return new DefaultCommand(command);
}
} |
Fix dewdrop_activity_log_id reference in log query. | <?php
namespace DeltaCli\Log;
class DewdropActivityLog extends AbstractDatabaseLog
{
public function getName()
{
return 'dewdrop-activity-log';
}
public function getDescription()
{
return "dewdrop_activity_log table of the {$this->getDatabase()->getDatabaseName()} database.";
}
public function assembleSql($afterId = null)
{
$whereClause = '';
$limitClause = '';
$params = [];
if (null === $afterId) {
$limitClause = 'LIMIT 10';
} else {
$whereClause = 'WHERE dewdrop_activity_log_id > %s';
$params[] = $afterId;
}
$sql = "SELECT
dewdrop_activity_log_id AS id,
{$this->getDatabase()->getReplaceNewlinesExpression('message')} AS message,
date_created
FROM dewdrop_activity_log
{$whereClause}
ORDER BY dewdrop_activity_log_id DESC
{$limitClause}";
return ['sql' => $sql, 'params' => $params];
}
} | <?php
namespace DeltaCli\Log;
class DewdropActivityLog extends AbstractDatabaseLog
{
public function getName()
{
return 'dewdrop-activity-log';
}
public function getDescription()
{
return "dewdrop_activity_log table of the {$this->getDatabase()->getDatabaseName()} database.";
}
public function assembleSql($afterId = null)
{
$whereClause = '';
$limitClause = '';
$params = [];
if (null === $afterId) {
$limitClause = 'LIMIT 10';
} else {
$whereClause = 'WHERE dewdrop_activity_log_id > %s';
$params[] = $afterId;
}
$sql = "SELECT
delta_log_id AS id,
{$this->getDatabase()->getReplaceNewlinesExpression('message')} AS message,
date_created
FROM dewdrop_activity_log
{$whereClause}
ORDER BY dewdrop_activity_log_id DESC
{$limitClause}";
return ['sql' => $sql, 'params' => $params];
}
} |
Fix bad comments for LabelView | // go.components.views
// ===================
// Generic, re-usable views for Go
(function(exports) {
var utils = go.utils,
functor = utils.functor;
// View for a label which can be attached to an element.
//
// Options:
// - text: A string or a function returning a string containing the text to
// be displayed by the label
// - of: The target element this label should be attached to
// - my: The point on the label to align with the of
// - at: The point on the target element to align the label against
var LabelView = Backbone.View.extend({
tagName: 'span',
className: 'label',
initialize: function(options) {
this.$of = $(options.of);
this.text = functor(options.text);
this.my = options.my;
this.at = options.at;
},
render: function() {
// Append the label to the of element so it can follow the of
// around (in the case of moving or draggable ofs)
this.$of.append(this.$el);
this.$el
.text(this.text())
.position({
of: this.$of,
my: this.my,
at: this.at
})
.css('position', 'absolute')
.css('pointer-events', 'none');
}
});
_.extend(exports, {
LabelView: LabelView
});
})(go.components.views = {});
| // go.components.views
// ===================
// Generic, re-usable views for Go
(function(exports) {
var utils = go.utils,
functor = utils.functor;
// View for a label which can be attached to an element.
//
// Options:
// - text: A string or a function returning a string containing the text to
// be displayed by the label
// - of: The element this label should be attached to
// - my: The my on the label to align with the of
// - at: The my on the of to align the label against
var LabelView = Backbone.View.extend({
tagName: 'span',
className: 'label',
initialize: function(options) {
this.$of = $(options.of);
this.text = functor(options.text);
this.my = options.my;
this.at = options.at;
},
render: function() {
// Append the label to the of element so it can follow the of
// around (in the case of moving or draggable ofs)
this.$of.append(this.$el);
this.$el
.text(this.text())
.position({
of: this.$of,
my: this.my,
at: this.at
})
.css('position', 'absolute')
.css('pointer-events', 'none');
}
});
_.extend(exports, {
LabelView: LabelView
});
})(go.components.views = {});
|
Add spawn strategy missing export. | 'use strict';
class SpawnStrategy {
constructor(spawn) {
this.spawn = spawn;
this.memory = {};
Memory.strategy = this.memory;
}
isSpawnReady(thresholdEnergy) {
if (!this.spawn) {
return false;
}
if (this.spawn.spawning) {
return false;
}
thresholdEnergy = thresholdEnergy || 0;
if (thresholdEnergy > this.spawn.energy) {
return false;
}
return true;
}
createCreep(parts, name, memory) {
memory.spawnName = memory.spawnName || this.spawn.name;
return this.spawn.createCreep(parts, name, memory);
}
}
module.exports = SpawnStrategy;
| 'use strict';
class SpawnStrategy {
constructor(spawn) {
this.spawn = spawn;
this.memory = {};
Memory.strategy = this.memory;
}
isSpawnReady(thresholdEnergy) {
if (!this.spawn) {
return false;
}
if (this.spawn.spawning) {
return false;
}
thresholdEnergy = thresholdEnergy || 0;
if (thresholdEnergy > this.spawn.energy) {
return false;
}
return true;
}
createCreep(parts, name, memory) {
memory.spawnName = memory.spawnName || this.spawn.name;
return this.spawn.createCreep(parts, name, memory);
}
}
|
Add temporary error logging for debugging
Now just print out the Exception message for debugging,
it will change to logging in the future | import os
class Worker():
def __init__(self,job,name):
self.fn = job
self.name = name
def do(self,timestamp):
pid = None
try:
print('[{timestamp}] {name}'.format(timestamp=timestamp,name=self.name))
pid = os.fork()
if pid == 0:
self.fn()
exit(0)
else:
return 0
except Exception as e:
#TODO logging the error message
print(str(e))
if pid is not None and pid == 0: # child fn() raise exception
exit(1)
else: # fork fail
return 1
| import os
class Worker():
def __init__(self,job,name):
self.fn = job
self.name = name
def do(self,timestamp):
pid = None
try:
print('[{timestamp}] {name}'.format(timestamp=timestamp,name=self.name))
pid = os.fork()
if pid == 0:
self.fn()
exit(0)
else:
return 0
except Exception as e:
if pid is not None and pid == 0: # child fn() raise exception
exit(1)
else: # fork fail
return 1
|
Fix these class names and imports so it works | from armstrong import hatband
from . import models
from django.db.models import TextField
from django.forms.widgets import TextInput
class ArticleAdmin(hatband.ModelAdmin):
class Meta:
model = models.TestArticle
class ArticleOverrideAdmin(hatband.ModelAdmin):
formfield_overrides = {
TextField: {'widget': TextInput},
}
class Meta:
model = models.TestArticle
class ArticleTabularInline(hatband.TabularInline):
class Meta:
model = models.TestArticle
class ArticleStackedInline(hatband.StackedInline):
class Meta:
model = models.TestArticle
class CategoryAdminTabbed(hatband.ModelAdmin):
inlines = ArticleTabularInline
class Meta:
model = models.TestCategory
class CategoryAdminStacked(hatband.ModelAdmin):
inlines = ArticleStackedInline
class Meta:
model = models.TestCategory
| from armstrong import hatband
from hatband_support import models
from django.forms.widgets import TextInput
class ArticleAdmin(hatband.ModelAdmin):
class Meta:
model = models.TestArticle
class ArticleOverrideAdmin(hatband.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': TextInput},
}
class Meta:
model = models.TestArticle
class ArticleTabbedInline(hatband.TabbedInline):
class Meta:
model = models.TestArticle
class ArticleStackedInline(hatband.StackedInline):
class Meta:
model = models.TestArticle
class CategoryAdminTabbed(hatband.ModelAdmin):
inlines = ArticleTabbedInline
class Meta:
model = models.TestCategory
class CategoryAdminStacked(hatband.ModelAdmin):
inlines = ArticleStackedInline
class Meta:
model = models.TestCategory
|
Use path parameters in http routes | "use strict";
const Shortlink = require("./shortlink");
const trim_slashes = require("./string_utility").trim_slashes;
module.exports = (server) => {
server.get("/", (req, res) => {
res.redirect(301, "http://jotaen.net");
});
server.get("/:token", (req, res) => {
const path = trim_slashes(req.params.token);
Shortlink.findOne({
path: path
}).then((shortlink) => {
if (shortlink) {
res.redirect(301, shortlink.url);
} else {
res.sendStatus(404);
}
});
});
server.put("/:token", (req, res) => {
const shortlink = new Shortlink({
url: req.query.url,
path: trim_slashes(req.params.token)
});
shortlink
.save()
.then(() => {
res.sendStatus(200);
})
.catch((error) => {
res.status(500).send(error);
});
});
};
| "use strict";
const Shortlink = require("./shortlink");
const trim_slashes = require("./string_utility").trim_slashes;
module.exports = (server) => {
server.get("/", (req, res) => {
res.redirect(301, "http://jotaen.net");
});
server.get("*", (req, res) => {
const path = trim_slashes(req.params[0]);
Shortlink.findOne({
path: path
}).then((shortlink) => {
if (shortlink) {
res.redirect(301, shortlink.url);
} else {
res.sendStatus(404);
}
});
});
server.put("*", (req, res) => {
const shortlink = new Shortlink({
url: req.query.url,
path: trim_slashes(req.params[0])
});
shortlink
.save()
.then(() => {
res.sendStatus(200);
})
.catch((error) => {
res.status(500).send(error);
});
});
};
|
Make http server listen only on localhost | var express = require('express')
, app = express()
, http = require('http').Server(app)
, Q = require('q');
var ROOT = GLOBAL.proj_root
, SENDFILE_OPTS = { root: ROOT }
, PORT = 55221
, START_TIMEOUT = 5;
// Static content
app.use('/components', express.static(ROOT + '/components'));
app.use('/dist', express.static(ROOT + '/dist'));
app.use('/fonts', express.static(ROOT + '/fonts'));
app.get('/', function(req, res) {
res.sendFile('atom-app.html', SENDFILE_OPTS);
});
// App routes
require('./routes')(app);
module.exports = {
start: function startServer() {
return Q.promise(function(resolve, reject) {
var timeout = setTimeout(function() {
reject('Server did not start within ' + START_TIMEOUT + ' seconds');
}, START_TIMEOUT * 1000);
http.listen(PORT, 'localhost');
http.on('listening', function() {
clearTimeout(timeout);
console.log('Server listening on port %s', PORT);
resolve(http);
});
});
}
} | var express = require('express')
, app = express()
, http = require('http').Server(app)
, Q = require('q');
var ROOT = GLOBAL.proj_root
, SENDFILE_OPTS = { root: ROOT }
, PORT = 55221
, START_TIMEOUT = 5;
// Static content
app.use('/components', express.static(ROOT + '/components'));
app.use('/dist', express.static(ROOT + '/dist'));
app.use('/fonts', express.static(ROOT + '/fonts'));
app.get('/', function(req, res) {
res.sendFile('atom-app.html', SENDFILE_OPTS);
});
// App routes
require('./routes')(app);
module.exports = {
start: function startServer() {
return Q.promise(function(resolve, reject) {
var timeout = setTimeout(function() {
reject('Server did not start within ' + START_TIMEOUT + ' seconds');
}, START_TIMEOUT * 1000);
http.listen(PORT, function() {
clearTimeout(timeout);
console.log('Server listening on port %s', PORT);
resolve(http);
});
});
}
} |
Upgrade release number to 0.6.0 (oq-engine 1.3.0) | # The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# 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/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.13.0'
__version__ += general.git_suffix(__file__)
| # The Hazard Library
# Copyright (C) 2012-2014, GEM Foundation
#
# 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/>.
"""
hazardlib stands for Hazard Library.
"""
from openquake.hazardlib import (
calc, geo, gsim, mfd, scalerel, source, const, correlation, imt, pmf, site,
tom, general
)
# the version is managed by packager.sh with a sed
__version__ = '0.12.1'
__version__ += general.git_suffix(__file__)
|
Change version number to 1.0.0 and development status to stable | from setuptools import setup, find_packages
long_description = open('README.rst').read()
packages = find_packages(exclude=['tests", "tests.*'])
setup(
name='pyflare',
version='1.0.0',
packages=packages,
url='https://github.com/jlinn/pyflare',
license='LICENSE.txt',
author='Joe Linn',
author_email='',
description="An adapter for CloudFlare's client API",
long_description=long_description,
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Development Status :: 5 - Production/Stable',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP'
]
)
| from setuptools import setup, find_packages
long_description = open('README.rst').read()
packages = find_packages(exclude=['tests", "tests.*'])
setup(
name='pyflare',
version='1.0.0b',
packages=packages,
url='https://github.com/jlinn/pyflare',
license='LICENSE.txt',
author='Joe Linn',
author_email='',
description="An adapter for CloudFlare's client API",
long_description=long_description,
install_requires=['requests'],
classifiers=[
'Intended Audience :: Developers',
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP'
]
)
|
Fix issue with non-existing color in compute_histo_RYG | import PIL.Image
import PIL.ImageMath
import urllib.request
from io import BytesIO
def load_img_url(url):
req = urllib.request.urlopen(url)
data = BytesIO(req.read())
return PIL.Image.open(data)
def load_img_file(fname):
return PIL.Image.open(fname)
def compute_histo_RYG(img, mask):
img = img.convert(mode='RGB')
mask = mask.convert(mode='1')
black = PIL.Image.new('RGB', mask.size, color=(0, 0, 0, 0))
masked = PIL.Image.composite(img, black, mask)
palette = PIL.Image.new('P', (1, 1))
palette.putpalette(
[0, 0, 0, # black
255, 0, 0, # red
255, 255, 0, # yellow
0, 255, 0]) # green
quantized = masked.quantize(palette=palette)
colors = quantized.getcolors()
r = next((c[0] for c in colors if c[1] == 1), 0)
y = next((c[0] for c in colors if c[1] == 2), 0)
g = next((c[0] for c in colors if c[1] == 3), 0)
return r, y, g
| import PIL.Image
import PIL.ImageMath
import urllib.request
from io import BytesIO
def load_img_url(url):
req = urllib.request.urlopen(url)
data = BytesIO(req.read())
return PIL.Image.open(data)
def load_img_file(fname):
return PIL.Image.open(fname)
def compute_histo_RYG(img, mask):
img = img.convert(mode='RGB')
mask = mask.convert(mode='1')
black = PIL.Image.new('RGB', mask.size, color=(0, 0, 0, 0))
masked = PIL.Image.composite(img, black, mask)
palette = PIL.Image.new('P', (1, 1))
palette.putpalette(
[0, 0, 0, # black
255, 0, 0, # red
255, 255, 0, # yellow
0, 255, 0]) # green
quantized = masked.quantize(palette=palette)
colors = quantized.getcolors()
return colors[1][0], colors[2][0], colors[3][0]
|
Return JSON from pypuppetdbquery.parse() by default
This will be the most useful mode of operation when combined with
pypuppetdb, so make life easy for people. | # -*- coding: utf-8 -*-
#
# This file is part of pypuppetdbquery.
# Copyright © 2016 Chris Boot <bootc@bootc.net>
#
# 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 json import dumps as json_dumps
from .evaluator import Evaluator
from .parser import Parser
def parse(s, json=True, parser_opts=None, evaluator_opts=None):
parser = Parser(**(parser_opts or {}))
evaluator = Evaluator(**(evaluator_opts or {}))
ast = parser.parse(s)
raw = evaluator.evaluate(ast)
if json and raw is not None:
return json_dumps(raw)
else:
return raw
| # -*- coding: utf-8 -*-
#
# This file is part of pypuppetdbquery.
# Copyright © 2016 Chris Boot <bootc@bootc.net>
#
# 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 .evaluator import Evaluator
from .parser import Parser
def parse(s, parser_opts=None, evaluator_opts=None):
parser = Parser(**(parser_opts or {}))
evaluator = Evaluator(**(evaluator_opts or {}))
ast = parser.parse(s)
return evaluator.evaluate(ast)
|
Fix a misspelled variable name
This appears to be unused anywhere in the source code. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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.
###############################################################################
# The path that will be mounted in docker containers for data IO
DOCKER_DATA_VOLUME = '/mnt/girder_worker/data'
# The path that will be mounted in docker containers for utility scripts
DOCKER_SCRIPTS_VOLUME = '/mnt/girder_worker/scripts'
# Settings where plugin information is stored
class PluginSettings(object):
BROKER = 'worker.broker'
BACKEND = 'worker.backend'
API_URL = 'worker.api_url'
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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.
###############################################################################
# The path that will be mounted in docker containers for data IO
DOCKER_DATA_VOLUME = '/mnt/girder_worker/data'
# The path that will be mounted in docker containers for utility scripts
DOCKER_SCRIPTS_VOUME = '/mnt/girder_worker/scripts'
# Settings where plugin information is stored
class PluginSettings(object):
BROKER = 'worker.broker'
BACKEND = 'worker.backend'
API_URL = 'worker.api_url'
|
Optimize imports. No functional changes | /*
* 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.wicket.examples.cdi;
import org.apache.wicket.Page;
import org.apache.wicket.cdi.CdiConfiguration;
import org.apache.wicket.protocol.http.WebApplication;
public class CdiApplication extends WebApplication
{
@Override
public Class<? extends Page> getHomePage()
{
return CdiHomePage.class;
}
@Override
protected void init()
{
super.init();
// configure wicket/cdi
new CdiConfiguration().configure(this);
mountPage("injection", InjectionPage.class);
mountPage("conversation", ConversationPage1.class);
mountPage("autoConversation", AutoConversationPage1.class);
}
}
| /*
* 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.wicket.examples.cdi;
import javax.enterprise.inject.spi.BeanManager;
import org.apache.wicket.Page;
import org.apache.wicket.cdi.CdiConfiguration;
import org.apache.wicket.protocol.http.WebApplication;
import org.jboss.weld.environment.servlet.Listener;
public class CdiApplication extends WebApplication
{
@Override
public Class<? extends Page> getHomePage()
{
return CdiHomePage.class;
}
@Override
protected void init()
{
super.init();
// configure wicket/cdi
new CdiConfiguration().configure(this);
mountPage("injection", InjectionPage.class);
mountPage("conversation", ConversationPage1.class);
mountPage("autoConversation", AutoConversationPage1.class);
}
}
|
Enforce strict routing (handled in compiler) | /**
server
The backbone of the server module. In development, this runs proxied through
BrowserSync server.
@param {Object} options Options passed on to "globals"
@param {Function} next Called when server successfully initialized
**/
var reorg = require("reorg");
module.exports = reorg(function(options, next) {
// Globals
require("./globals")(options);
var server = global.shipp.framework({ strict: true }),
middleware = require("./middleware"),
Utils = require("./utils");
[
// User-defined middleware
middleware("beforeAll"),
// Common middleware: logging, favicons, cookie parsing, sessions and body parsing
require("./common")(),
// User-defined middleware
middleware("beforeRoutes"),
// Static and compiled routes
require("./routes")(),
// Data-server
require("./data-server")(),
// User-defined middleware
middleware("afterRoutes")
].forEach(function(library) {
Utils.useMiddleware(server, library);
});
// Error handling: please see errors middleware for explanation of structure
require("./errors")(server, middleware("errorHandler"));
// Find open port and set up graceful shutdown
require("./lifecycle")(server, next);
}, "object", ["function", function() {}]);
| /**
server
The backbone of the server module. In development, this runs proxied through
BrowserSync server.
@param {Object} options Options passed on to "globals"
@param {Function} next Called when server successfully initialized
**/
var reorg = require("reorg");
module.exports = reorg(function(options, next) {
// Globals
require("./globals")(options);
var server = global.shipp.framework(),
middleware = require("./middleware"),
Utils = require("./utils");
[
// User-defined middleware
middleware("beforeAll"),
// Common middleware: logging, favicons, cookie parsing, sessions and body parsing
require("./common")(),
// User-defined middleware
middleware("beforeRoutes"),
// Static and compiled routes
require("./routes")(),
// Data-server
require("./data-server")(),
// User-defined middleware
middleware("afterRoutes")
].forEach(function(library) {
Utils.useMiddleware(server, library);
});
// Error handling: please see errors middleware for explanation of structure
require("./errors")(server, middleware("errorHandler"));
// Find open port and set up graceful shutdown
require("./lifecycle")(server, next);
}, "object", ["function", function() {}]);
|
Allow setting config individual value | <?php
namespace Ghc\Rosetta;
use Illuminate\Config\Repository;
trait Configurable
{
/**
* Configuration options
*
* @var Repository
*/
protected $config;
/**
* @return array
*/
public function getConfig()
{
return $this->config->all();
}
/**
* @param array|string $config
* @param mixed $value
* @return Configurable
*/
public function setConfig($config, $value = null)
{
if (is_string($config)) {
$this->config->set($config, $value);
} else {
$this->config = new Repository($config);
}
return $this;
}
/**
* @param array $config
*/
protected function addDefaultConfig($config)
{
$this->setConfig(array_merge($config, $this->getConfig()));
}
}
| <?php
namespace Ghc\Rosetta;
use Illuminate\Config\Repository;
trait Configurable
{
/**
* Configuration options
*
* @var Repository
*/
protected $config;
/**
* @return array
*/
public function getConfig()
{
return $this->config->all();
}
/**
* @param array $config
* @return self
*/
public function setConfig($config)
{
$this->config = new Repository($config);
return $this;
}
/**
* @param array $config
*/
protected function addDefaultConfig($config)
{
$this->setConfig(array_merge($config, $this->getConfig()));
}
}
|
Fix a bug in the tests. | import StringIO
import unittest
from testdoc.formatter import WikiFormatter
class WikiFormatterTest(unittest.TestCase):
def setUp(self):
self.stream = StringIO.StringIO()
self.formatter = WikiFormatter(self.stream)
def test_title(self):
self.formatter.title('foo')
self.assertEqual(self.stream.getvalue(), '= foo =\n\n')
def test_section(self):
self.formatter.section('foo')
self.assertEqual(self.stream.getvalue(), '\n== foo ==\n\n')
def test_subsection(self):
self.formatter.subsection('foo')
self.assertEqual(self.stream.getvalue(), '=== foo ===\n\n')
def test_paragraph(self):
self.formatter.paragraph('\nfoo\nbar\n')
self.assertEqual(self.stream.getvalue(), 'foo\nbar\n\n')
| import StringIO
import unittest
from testdoc.formatter import WikiFormatter
class WikiFormatterTest(unittest.TestCase):
def setUp(self):
self.stream = StringIO.StringIO()
self.formatter = WikiFormatter(self.stream)
def test_title(self):
self.formatter.title('foo')
self.assertEqual(self.stream.getvalue(), '= foo =\n\n')
def test_section(self):
self.formatter.section('foo')
self.assertEqual(self.stream.getvalue(), '== foo ==\n\n')
def test_subsection(self):
self.formatter.subsection('foo')
self.assertEqual(self.stream.getvalue(), '=== foo ===\n\n')
def test_paragraph(self):
self.formatter.paragraph('\nfoo\nbar\n')
self.assertEqual(self.stream.getvalue(), 'foo\nbar\n\n')
|
[OWL-277] Fix ambiguous message while connecting to database | package db
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/open-falcon/hbs/g"
"log"
)
var DB *sql.DB
func Init() {
err := dbInit(g.Config().Database)
if err != nil {
log.Fatalln(err)
}
DB.SetMaxIdleConns(g.Config().MaxIdle)
}
func dbInit(dsn string) (err error) {
if DB, err = sql.Open("mysql", dsn)
err != nil {
return fmt.Errorf("Open DB error: %v", err)
}
if err = DB.Ping()
err != nil {
return fmt.Errorf("Ping DB error: %v", err)
}
return
}
// Convenient IoC for transaction processing
func inTx(txCallback func(tx *sql.Tx) error) (err error) {
var tx *sql.Tx
if tx, err = DB.Begin()
err != nil {
return
}
/**
* The transaction result by whether or not the callback has error
*/
defer func() {
if err == nil {
tx.Commit()
} else {
tx.Rollback()
}
}()
// :~)
err = txCallback(tx)
return
}
| package db
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/open-falcon/hbs/g"
"log"
)
var DB *sql.DB
func Init() {
err := dbInit(g.Config().Database)
if err != nil {
log.Fatalf("open db fail: %v", err)
}
DB.SetMaxIdleConns(g.Config().MaxIdle)
}
func dbInit(dsn string) (err error) {
if DB, err = sql.Open("mysql", dsn)
err != nil {
return
}
if err = DB.Ping()
err != nil {
return
}
return
}
// Convenient IoC for transaction processing
func inTx(txCallback func(tx *sql.Tx) error) (err error) {
var tx *sql.Tx
if tx, err = DB.Begin()
err != nil {
return
}
/**
* The transaction result by whether or not the callback has error
*/
defer func() {
if err == nil {
tx.Commit()
} else {
tx.Rollback()
}
}()
// :~)
err = txCallback(tx)
return
}
|
Add test module for globals | var assertionsModifier = require('../src/modifiers/assertions');
var testsModifier = require('../src/modifiers/tests');
var globalsModifier = require('../src/modifiers/globals');
var assert = require('assert');
var fs = require('fs');
var noOfData = 3;
var oneToTenArray = [];
for(var i = 1; i <= noOfData; i++) {
oneToTenArray.push(i);
}
var testData = oneToTenArray.map(function (i) {
return fs.readFileSync('tests/data/' + i + '/actual.js').toString();
})
var expectedData = oneToTenArray.map(function (i) {
return fs.readFileSync('tests/data/' + i + '/expected.js').toString();
})
describe('Assertions modules', function () {
it('should have a working assertion modifier', function () {
for(var i = 0; i < 1; i++) {
var result = assertionsModifier(testData[i]);
assert.equal(result, expectedData[i]);
}
});
});
describe('Tests working', function () {
it('should have a workign tests modifier', function () {
for(var i = 1; i < 2; i++) {
var result = testsModifier(testData[i]);
assert.equal(result, expectedData[i]);
}
});
});
describe('Globals working', function () {
it('should have a workign tests modifier', function () {
for(var i = 2; i < 3; i++) {
var result = globalsModifier(testData[i]);
assert.equal(result, expectedData[i]);
}
});
});
| var assertionsModifier = require('../src/modifiers/assertions');
var testsModifier = require('../src/modifiers/tests');
var assert = require('assert');
var fs = require('fs');
var noOfData = 2;
var oneToTenArray = [];
for(var i = 1; i <= noOfData; i++) {
oneToTenArray.push(i);
}
var testData = oneToTenArray.map(function (i) {
return fs.readFileSync('tests/data/' + i + '/actual.js').toString();
})
var expectedData = oneToTenArray.map(function (i) {
return fs.readFileSync('tests/data/' + i + '/expected.js').toString();
})
describe('Assertions modules', function () {
it('should have a working assertion modifier', function () {
for(var i = 0; i < 1; i++) {
var result = assertionsModifier(testData[i]);
assert.equal(result, expectedData[i]);
}
});
});
describe('Tests working', function () {
it('should have a workign tests modifier', function () {
for(var i = 1; i < 2; i++) {
var result = testsModifier(testData[i]);
assert.equal(result, expectedData[i]);
}
});
});
|
Fix pecan error message not available in body for Trigger.post
When a trigger_id resource is not found, the API returns a 202 status
code, the error message could not be added in the body of the request
because pecan.response.text was used instead of pecan.response.body.
Change-Id: I8b03210b5a2f2b5c0ea24bfc8149cca122dffeea
Closes-Bug: #1324940 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pecan
from pecan import rest
from solum.api.handlers import assembly_handler
from solum.common import exception
class TriggerController(rest.RestController):
"""Manages triggers."""
@pecan.expose()
def post(self, trigger_id):
"""Trigger a new event on Solum."""
handler = assembly_handler.AssemblyHandler(None)
try:
handler.trigger_workflow(trigger_id)
pecan.response.status = 202
except exception.ResourceNotFound as excp:
pecan.response.status = excp.code
pecan.response.body = excp.message
| # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pecan
from pecan import rest
from solum.api.handlers import assembly_handler
from solum.common import exception
class TriggerController(rest.RestController):
"""Manages triggers."""
@pecan.expose()
def post(self, trigger_id):
"""Trigger a new event on Solum."""
handler = assembly_handler.AssemblyHandler(None)
try:
handler.trigger_workflow(trigger_id)
except exception.ResourceNotFound as excp:
pecan.response.status = excp.code
pecan.response.text = excp.message
return
pecan.response.status = 202
|
Update comments to better explain what everything does | <?php
error_reporting(E_ALL);
require 'vendor/autoload.php';
// Get your credentials from a safe place when using in production
$username = 'your_username';
$password = 'your_password';
$domrobot = new \INWX\Domrobot();
$result = $domrobot->setLanguage('en')
// use the OTE endpoint
->useOte()
// or use the LIVE endpoint instead
// ->useLive()
// use the JSON-RPC API
->useJson()
// or use the XML-RPC API instead
//->useXml()
// debug will let you see everything you're sending and receiving
->setDebug(true)
->login($username, $password);
if ($result['code'] == 1000) {
$object = 'domain';
$method = 'check';
$params = ['domain' => 'mydomain.com'];
$result = $domrobot->call($object, $method, $params);
// $res now contains an array with the complete response
// the basic format of this array is the same whether you use our JSON or XML API
// there are however some differences with files and dates in the response
// you should try out your code in our OTE system, to be sure that everything works
}
print_r($result);
$domrobot->logout();
| <?php
error_reporting(E_ALL);
require 'vendor/autoload.php';
// Get your credentials from a safe place when using in production
$username = 'your_username';
$password = 'your_password';
$domrobot = new \INWX\Domrobot();
$result = $domrobot->setLanguage('en')
// use our OTE endpoint
->useOte()
// Uncomment to use our Live endpoint instead
// ->useLive()
// use the JSON-RPC API
->useJson()
// Or use the XML-RPC API instead
//->useXml()
// Uncomment to see everything you're sending and receiving
->setDebug(true)
->login($username, $password);
if ($result['code'] == 1000) {
$object = 'domain';
$method = 'check';
$params = ['domain' => 'mydomain.com'];
$result = $domrobot->call($object, $method, $params);
// $res now contains an array with the complete response
// the basic format of this array is the same whether you use our JSON or XML API
// there are however some differences with files and dates in the response
// you should try out your code in our OTE system, to be sure that everything works
}
print_r($result);
$domrobot->logout();
|
Fix issue of carry over of negative allowances when the feature is OFF |
'use strict';
const
moment = require('moment'),
Promise= require('bluebird');
const calculateCarryOverAllowance = ({users}) => {
const
yearFrom = moment.utc().add(-1, 'y').year(),
yearTo = moment.utc().year();
console.log(`${yearFrom} -> ${yearTo}`);
let flow = Promise.resolve(users);
flow = flow.then(users => Promise.map(
users,
user => {
let carryOver;
return Promise.resolve(user.getCompany().then(c => carryOver = c.carry_over))
.then(() => user.reload_with_leave_details({year:moment.utc(yearFrom, 'YYYY')}))
.then(user => user.promise_allowance({year:moment.utc(yearFrom, 'YYYY')}))
.then(allowance => {
const carried_over_allowance = (carryOver === 0)
? 0
: Math.min(allowance.number_of_days_available_in_allowance, carryOver);
return user.promise_to_update_carried_over_allowance({
carried_over_allowance,
year: yearTo,
});
})
.then(() => console.log(`Done with user ${user.id}`));
},
{concurrency : 1}
));
return flow;
};
module.exports = { calculateCarryOverAllowance };
|
'use strict';
const
moment = require('moment'),
Promise= require('bluebird');
const calculateCarryOverAllowance = ({users}) => {
const
yearFrom = moment.utc().add(-1, 'y').year(),
yearTo = moment.utc().year();
console.log(`${yearFrom} -> ${yearTo}`);
let flow = Promise.resolve(users);
flow = flow.then(users => Promise.map(
users,
user => {
let carryOver;
return Promise.resolve(user.getCompany().then(c => carryOver = c.carry_over))
.then(() => user.reload_with_leave_details({year:moment.utc(yearFrom, 'YYYY')}))
.then(user => user.promise_allowance({year:moment.utc(yearFrom, 'YYYY')}))
.then(allowance => {
return user.promise_to_update_carried_over_allowance({
year : yearTo,
carried_over_allowance : Math.min(allowance.number_of_days_available_in_allowance, carryOver),
});
})
.then(() => console.log(`Done with user ${user.id}`));
},
{concurrency : 1}
));
return flow;
};
module.exports = { calculateCarryOverAllowance };
|
Use term end date as timestamp for term reports | <?php
namespace Slate\Progress;
class SectionTermReport extends AbstractSectionTermReport
{
public static $cssTpl = 'section-term-reports/_css';
public static $bodyTpl = 'section-term-reports/_body';
public static $tableName = 'section_term_reports';
public static $singularNoun = 'section term report';
public static $pluralNoun = 'section term reports';
public static $collectionRoute = '/progress/section-term-reports';
public static $defaultClass = __CLASS__;
public static $subClasses = [__CLASS__];
public static $fields = [
'Notes' => [
'type' => 'clob',
'default' => null
],
'NotesFormat' => [
'type' => 'enum',
'values' => ['markdown', 'html'],
'default' => 'markdown'
]
];
public static $indexes = [
'StudentSectionTerm' => [
'fields' => ['StudentID', 'SectionID', 'TermID'],
'unique' => true
]
];
public static function getNoun($count = 1)
{
return $count == 1 ? 'term report' : 'term reports';
}
public function getTimestamp()
{
return strtotime($this->getTerm()->EndDate);
}
} | <?php
namespace Slate\Progress;
class SectionTermReport extends AbstractSectionTermReport
{
public static $cssTpl = 'section-term-reports/_css';
public static $bodyTpl = 'section-term-reports/_body';
public static $tableName = 'section_term_reports';
public static $singularNoun = 'section term report';
public static $pluralNoun = 'section term reports';
public static $collectionRoute = '/progress/section-term-reports';
public static $defaultClass = __CLASS__;
public static $subClasses = [__CLASS__];
public static $fields = [
'Notes' => [
'type' => 'clob',
'default' => null
],
'NotesFormat' => [
'type' => 'enum',
'values' => ['markdown', 'html'],
'default' => 'markdown'
]
];
public static $indexes = [
'StudentSectionTerm' => [
'fields' => ['StudentID', 'SectionID', 'TermID'],
'unique' => true
]
];
public static function getNoun($count = 1)
{
return $count == 1 ? 'term report' : 'term reports';
}
} |
Add method to access an element of load-button | (function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var dom = app.dom || require('../dom.js');
var SidebarToggleButton = app.SidebarToggleButton || require('./sidebar-toggle-button.js');
var ContentHeader = helper.inherits(function(props) {
ContentHeader.super_.call(this);
this.element = this.prop(props.element);
this.sidebarToggleButton = this.prop(new SidebarToggleButton({
element: this.sidebarToggleButtonElement(),
collapser: props.sidebarCollapser,
expander: props.sidebarExpander
}));
this.sidebarToggleButton().registerTapListener();
}, jCore.Component);
ContentHeader.prototype.sidebarToggleButtonElement = function() {
return dom.child(this.element(), 0);
};
ContentHeader.prototype.loadButtonElement = function() {
return dom.child(this.element(), 1);
};
ContentHeader.prototype.redraw = function() {
this.sidebarToggleButton().redraw();
};
if (typeof module !== 'undefined' && module.exports)
module.exports = ContentHeader;
else
app.ContentHeader = ContentHeader;
})(this.app || (this.app = {}));
| (function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var dom = app.dom || require('../dom.js');
var SidebarToggleButton = app.SidebarToggleButton || require('./sidebar-toggle-button.js');
var ContentHeader = helper.inherits(function(props) {
ContentHeader.super_.call(this);
this.element = this.prop(props.element);
this.sidebarToggleButton = this.prop(new SidebarToggleButton({
element: this.sidebarToggleButtonElement(),
collapser: props.sidebarCollapser,
expander: props.sidebarExpander
}));
this.sidebarToggleButton().registerTapListener();
}, jCore.Component);
ContentHeader.prototype.sidebarToggleButtonElement = function() {
return dom.child(this.element(), 0);
};
ContentHeader.prototype.redraw = function() {
this.sidebarToggleButton().redraw();
};
if (typeof module !== 'undefined' && module.exports)
module.exports = ContentHeader;
else
app.ContentHeader = ContentHeader;
})(this.app || (this.app = {}));
|
Swap out double quotes with single quotes | angular.module('hyperContentFor', [])
.value('HYPER_CONTENT_FOR_IDS', { })
.directive('hyperContent', function() {
return {
scope: { 'for': '@' },
restrict: 'E',
transclude: true,
controller: function($scope, $transclude, HYPER_CONTENT_FOR_IDS) {
HYPER_CONTENT_FOR_IDS[$scope['for']] = $transclude();
}
};
})
.directive('hyperYield', function(HYPER_CONTENT_FOR_IDS) {
return {
scope: { to: '@' },
restrict: 'E',
link: function(scope, elem) {
interval = null;
watchFn = function() { return HYPER_CONTENT_FOR_IDS[scope.to]; };
scope.$watch(watchFn, function(newValue) {
elem.empty();
elem.append(newValue);
});
}
};
});
| angular.module("hyperContentFor", [])
.value("HYPER_CONTENT_FOR_IDS", { })
.directive("hyperContent", function() {
return {
scope: { "for": "@" },
restrict: "E",
transclude: true,
controller: function($scope, $transclude, HYPER_CONTENT_FOR_IDS) {
HYPER_CONTENT_FOR_IDS[$scope["for"]] = $transclude();
}
};
})
.directive("hyperYield", function(HYPER_CONTENT_FOR_IDS) {
return {
scope: { to: "@" },
restrict: "E",
link: function(scope, elem) {
interval = null;
watchFn = function() { return HYPER_CONTENT_FOR_IDS[scope.to]; };
scope.$watch(watchFn, function(newValue) {
elem.empty();
elem.append(newValue);
});
}
};
});
|
Update volumes variable name for LaunchContainer | package orchestrators
import (
log "github.com/Sirupsen/logrus"
"github.com/camptocamp/conplicity/handler"
"github.com/camptocamp/conplicity/volume"
)
// Orchestrator implements a container Orchestrator interface
type Orchestrator interface {
GetHandler() *handler.Conplicity
GetVolumes() ([]*volume.Volume, error)
LaunchContainer(image string, env map[string]string, cmd []string, volumes []*volume.Volume) (state int, stdout string, err error)
GetMountedVolumes() ([]*volume.MountedVolumes, error)
ContainerExec(containerID string, command []string) error
}
// GetOrchestrator returns the Orchestrator as specified in configuration
func GetOrchestrator(c *handler.Conplicity) Orchestrator {
orch := c.Config.Orchestrator
log.Debugf("orchestrator=%s", orch)
switch orch {
case "docker":
return NewDockerOrchestrator(c)
}
log.Fatalf("Unknown orchestrator %s", orch)
return nil
}
| package orchestrators
import (
log "github.com/Sirupsen/logrus"
"github.com/camptocamp/conplicity/handler"
"github.com/camptocamp/conplicity/volume"
)
// Orchestrator implements a container Orchestrator interface
type Orchestrator interface {
GetHandler() *handler.Conplicity
GetVolumes() ([]*volume.Volume, error)
LaunchContainer(image string, env map[string]string, cmd []string, v []*volume.Volume) (state int, stdout string, err error)
GetMountedVolumes() ([]*volume.MountedVolumes, error)
ContainerExec(containerID string, command []string) error
}
// GetOrchestrator returns the Orchestrator as specified in configuration
func GetOrchestrator(c *handler.Conplicity) Orchestrator {
orch := c.Config.Orchestrator
log.Debugf("orchestrator=%s", orch)
switch orch {
case "docker":
return NewDockerOrchestrator(c)
}
log.Fatalf("Unknown orchestrator %s", orch)
return nil
}
|
Change the false param to true. | describe("About Expects", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(true).toBeTruthy(); //This should be true
});
//To understand reality, we must compare our expectations against reality.
it("should expect equality", function () {
var expectedValue = FILL_ME_IN;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
//Some ways of asserting equality are better than others.
it("should assert equality a better way", function () {
var expectedValue = FILL_ME_IN;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
//Sometimes you need to be really exact about what you "type".
it("should assert equality with ===", function () {
var expectedValue = FILL_ME_IN;
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
//Sometimes we will ask you to fill in the values.
it("should have filled in values", function () {
expect(1 + 1).toEqual(FILL_ME_IN);
});
});
| describe("About Expects", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(false).toBeTruthy(); //This should be true
});
//To understand reality, we must compare our expectations against reality.
it("should expect equality", function () {
var expectedValue = FILL_ME_IN;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
//Some ways of asserting equality are better than others.
it("should assert equality a better way", function () {
var expectedValue = FILL_ME_IN;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
//Sometimes you need to be really exact about what you "type".
it("should assert equality with ===", function () {
var expectedValue = FILL_ME_IN;
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
//Sometimes we will ask you to fill in the values.
it("should have filled in values", function () {
expect(1 + 1).toEqual(FILL_ME_IN);
});
});
|
Remove mnt patch from non-windows now that FLIF-WASM fixed /mnt/ bug | /* eslint-disable no-multi-spaces */
function test () {
var runAllTests = require('../testers/loopOverAllTestSets.js');
var testName = 'identify';
var path = require('path');
var testData = [
{ expected: { file: path.join(process.cwd(), 'sample', 'cat.flif'), dimensions: '80x64', color: '8-bit RGBA', interlace: 'non-interlaced', size: 103 }, arguments: ['"' + path.resolve('.', 'sample', 'cat.flif') + '"'] },
{ expected: { file: path.join(process.cwd(), 'sample', 'output.flif'), dimensions: '768x512', color: '8-bit RGB', interlace: 'interlaced', size: 475578 }, arguments: ['"' + path.resolve('.', 'sample', 'output.flif') + '"'] }
];
runAllTests(testName, 'information', testData);
var amountOfTests = testData.length * Object.keys(testData[0].expected).length;
return [testName, amountOfTests];
}
module.exports = test;
| /* eslint-disable no-multi-spaces */
function test () {
var runAllTests = require('../testers/loopOverAllTestSets.js');
var testName = 'identify';
var path = require('path');
var mnt = '/mnt';
if (process.platform === 'win32') {
mnt = '';
}
var testData = [
{ expected: { file: mnt + path.join(process.cwd(), 'sample', 'cat.flif'), dimensions: '80x64', color: '8-bit RGBA', interlace: 'non-interlaced', size: 103 }, arguments: ['"' + path.resolve('.', 'sample', 'cat.flif') + '"'] },
{ expected: { file: mnt + path.join(process.cwd(), 'sample', 'output.flif'), dimensions: '768x512', color: '8-bit RGB', interlace: 'interlaced', size: 475578 }, arguments: ['"' + path.resolve('.', 'sample', 'output.flif') + '"'] }
];
runAllTests(testName, 'information', testData);
var amountOfTests = testData.length * Object.keys(testData[0].expected).length;
return [testName, amountOfTests];
}
module.exports = test;
|
Rewrite ternary operator. Remove unnecessary casting of the object to compare | package entity;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Jakob Pfeiffer on 19.10.17.
*/
public abstract class BaseEntity implements Comparable<BaseEntity> {
private long identity;
private int version;
private long creationTimestamp;
Set<Message> messagesCaused;
public BaseEntity() {
this.version = 1;
this.messagesCaused = new HashSet<>();
this.creationTimestamp = System.currentTimeMillis();
}
public long getIdentity() {
return identity;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public long getCreationTimestamp() {
return creationTimestamp;
}
public Set<Message> getMessagesCaused() {
return messagesCaused;
}
@Override
public int compareTo(BaseEntity o) {
if (this.identity == o.identity) {
return 0;
}
return this.identity < o.identity ? -1 : +1;
}
}
| package entity;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Jakob Pfeiffer on 19.10.17.
*/
public abstract class BaseEntity implements Comparable<BaseEntity> {
private long identity;
private int version;
private long creationTimestamp;
Set<Message> messagesCaused;
public BaseEntity() {
this.version = 1;
this.messagesCaused = new HashSet<>();
this.creationTimestamp = System.currentTimeMillis();
}
public long getIdentity() {
return identity;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public long getCreationTimestamp() {
return creationTimestamp;
}
public Set<Message> getMessagesCaused() {
return messagesCaused;
}
@Override
public int compareTo(BaseEntity o) {
return this.identity < ((BaseEntity) o).identity ? -1 : this.identity > ((BaseEntity) o).identity ? +1 : 0;
}
}
|
Tidy up the pot search javascript | // Visit The Stimulus Handbook for more details
// https://stimulusjs.org/handbook/introduction
//
// This example controller works with specially annotated HTML like:
//
// <div data-controller="hello">
// <h1 data-target="hello.output"></h1>
// </div>
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "pot", "form", "query" ]
initialize() {
this.setHidden(false, this.formTarget);
this.resetFilter();
}
resetFilter() {
this.queryTarget.value = "";
for (let pot of this.potTargets) { this.setHidden(false, pot); }
}
applyFilter(query) {
let nameMatcher = query.toLowerCase();
for (let pot of this.potTargets) {
let name = pot.getAttribute("data-name");
let match = name.includes(nameMatcher);
this.setHidden(!match, pot);
}
}
search() {
let query = this.queryTarget.value.trim();
if (query.length == 0) {
this.resetFilter();
} else {
this.applyFilter(query);
}
}
setHidden(hidden, element) {
let classes = element.classList;
hidden ? classes.add("d-none") : classes.remove("d-none");
}
}
| // Visit The Stimulus Handbook for more details
// https://stimulusjs.org/handbook/introduction
//
// This example controller works with specially annotated HTML like:
//
// <div data-controller="hello">
// <h1 data-target="hello.output"></h1>
// </div>
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ "pot", "form", "query" ]
initialize() {
this.formTarget.classList.remove("d-none");
this.resetFilter();
}
resetFilter() {
this.queryTarget.value = "";
for (let pot of this.potTargets) { pot.classList.remove("d-none"); }
}
applyFilter(query) {
for (let pot of this.potTargets) {
if (pot.getAttribute("data-name").includes(query.toLowerCase())) {
pot.classList.remove("d-none");
} else {
pot.classList.add("d-none");
}
}
}
search() {
let query = this.queryTarget.value;
if (query === '') {
this.resetFilter();
} else {
this.applyFilter(query);
}
}
}
|
Remove mistakenly committed manual XML serializer injection | package edu.northwestern.bioinformatics.studycalendar.restlets;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.Role;
import edu.northwestern.bioinformatics.studycalendar.xml.writers.StudyXmlSerializer;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Method;
import org.restlet.Context;
import org.springframework.beans.factory.annotation.Required;
/**
* Resource representing a study and its planned calendar, including all amendments.
*
* @author Rhett Sutphin
*/
public class TemplateResource extends AbstractStorableDomainObjectResource<Study> {
private StudyDao studyDao;
@Override
public void init(Context context, Request request, Response response) {
super.init(context, request, response);
setAllAuthorizedFor(Method.GET);
setAuthorizedFor(Method.PUT, Role.STUDY_ADMIN);
}
@Override
protected Study loadRequestedObject(Request request) {
String studyIdent = UriTemplateParameters.STUDY_IDENTIFIER.extractFrom(request);
return studyDao.getByAssignedIdentifier(studyIdent);
}
////// CONFIGURATION
@Required
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
}
| package edu.northwestern.bioinformatics.studycalendar.restlets;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.Role;
import edu.northwestern.bioinformatics.studycalendar.xml.writers.StudyXmlSerializer;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Method;
import org.restlet.Context;
import org.springframework.beans.factory.annotation.Required;
/**
* Resource representing a study and its planned calendar, including all amendments.
*
* @author Rhett Sutphin
*/
public class TemplateResource extends AbstractStorableDomainObjectResource<Study> {
private StudyDao studyDao;
@Override
public void init(Context context, Request request, Response response) {
super.init(context, request, response);
setAllAuthorizedFor(Method.GET);
setAuthorizedFor(Method.PUT, Role.STUDY_ADMIN);
// TODO: temporary
setXmlSerializer(new StudyXmlSerializer());
}
@Override
protected Study loadRequestedObject(Request request) {
String studyIdent = UriTemplateParameters.STUDY_IDENTIFIER.extractFrom(request);
return studyDao.getByAssignedIdentifier(studyIdent);
}
////// CONFIGURATION
@Required
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
}
|
Change from IDs to pl-js- classes | /*!
* Simple Layout Rendering for Pattern Lab
*
* Copyright (c) 2014 Dave Olsen, http://dmolsen.com
* Licensed under the MIT license
*/
try {
/* load pattern nav */
var template = document.querySelector(".pl-js-pattern-nav-template");
var templateCompiled = Hogan.compile(template.innerHTML);
var templateRendered = templateCompiled.render(navItems);
document.querySelector(".pl-js-pattern-nav-target").innerHTML = templateRendered;
/* load ish controls */
var template = document.querySelector(".pl-js-ish-controls-template");
var templateCompiled = Hogan.compile(template.innerHTML);
var templateRendered = templateCompiled.render(ishControls);
document.querySelector(".pl-js-controls").innerHTML = templateRendered;
} catch(e) {
var message = "<p>Please generate your site before trying to view it.</p>";
document.querySelector(".pl-js-pattern-nav-target").innerHTML = message;
}
| /*!
* Simple Layout Rendering for Pattern Lab
*
* Copyright (c) 2014 Dave Olsen, http://dmolsen.com
* Licensed under the MIT license
*/
try {
/* load pattern nav */
var template = document.getElementById("pl-pattern-nav-template");
var templateCompiled = Hogan.compile(template.innerHTML);
var templateRendered = templateCompiled.render(navItems);
document.querySelector(".pl-js-pattern-nav-target").innerHTML = templateRendered;
/* load ish controls */
var template = document.getElementById("pl-ish-controls-template");
var templateCompiled = Hogan.compile(template.innerHTML);
var templateRendered = templateCompiled.render(ishControls);
document.querySelector(".pl-js-controls").innerHTML = templateRendered;
} catch(e) {
var message = "<p>Please generate your site before trying to view it.</p>";
document.querySelector(".pl-js-pattern-nav-target").innerHTML = message;
}
|
Fix issue with WP loading wrong index.php | <?php
/**
* Do not edit anything in this file unless you know what you're doing
*/
/**
* Here's what's happening with these hooks:
* 1. WordPress detects theme in themes/sage
* 2. When we activate, we tell WordPress that the theme is actually in themes/sage/templates
* 3. When we call get_template_directory() or get_template_directory_uri(), we point it back to themes/sage
*
* We do this so that the Template Hierarchy will look in themes/sage/templates for core WordPress themes
* But functions.php, style.css, and index.php are all still located in themes/sage
*
* themes/sage/index.php also contains some self-correcting code, just in case the template option gets reset
*/
add_filter('stylesheet', function ($stylesheet) {
return dirname($stylesheet);
});
add_action('after_switch_theme', function () {
$stylesheet = get_option('stylesheet');
basename($stylesheet) == 'templates' || update_option('stylesheet', $stylesheet . '/templates');
});
/**
* Require composer autoloader
*/
require_once __DIR__ . '/vendor/autoload.php';
| <?php
/**
* Do not edit anything in this file unless you know what you're doing
*/
/**
* Here's what's happening with these hooks:
* 1. WordPress detects theme in themes/sage
* 2. When we activate, we tell WordPress that the theme is actually in themes/sage/templates
* 3. When we call get_template_directory() or get_template_directory_uri(), we point it back to themes/sage
*
* We do this so that the Template Hierarchy will look in themes/sage/templates for core WordPress themes
* But functions.php, style.css, and index.php are all still located in themes/sage
*
* themes/sage/index.php also contains some self-correcting code, just in case the template option gets reset
*/
add_filter('template', function ($template) {
return dirname($template);
});
add_action('after_switch_theme', function () {
update_option('template', get_option('template') . '/templates');
});
/**
* Require composer autoloader
*/
require_once __DIR__ . '/vendor/autoload.php';
|
Save the data fron cron | import urllib, json
import numpy as np
import time
from secrets import API_KEY # JCDECAUX's API KEY
def retrieve_data(contract="paris"):
url = "https://api.jcdecaux.com/vls/v1/stations?apiKey={}&contract={}".format(API_KEY, contract)
response = urllib.urlopen(url)
data = json.loads(response.read())
return data
def extract_data(data):
y = -np.array([p['position']['lat'] for p in data])
x = np.array([p['position']['lng'] for p in data])
st_free = np.array([p['available_bike_stands']
for p in data]).astype(np.float32)
st_busy = np.array([p['available_bikes']
for p in data]).astype(np.float32)
return (x, y), (st_free, st_busy)
def save_data(data, ofile="output/data.npy"):
np.save(ofile, data)
if __name__ == '__main__':
data = extract_data(retrieve_data())
save_data(data, 'output/{}.npy'.format(int(time.time())))
| import urllib, json
import numpy as np
from secrets import API_KEY # JCDECAUX's API KEY
def retrieve_data(contract="paris"):
url = "https://api.jcdecaux.com/vls/v1/stations?apiKey={}&contract={}".format(API_KEY, contract)
response = urllib.urlopen(url)
data = json.loads(response.read())
return data
def extract_data(data):
y = -np.array([p['position']['lat'] for p in data])
x = np.array([p['position']['lng'] for p in data])
st_free = np.array([p['available_bike_stands']
for p in data]).astype(np.float32)
st_busy = np.array([p['available_bikes']
for p in data]).astype(np.float32)
return (x, y), (st_free, st_busy)
|
Refactor model test to test added properties | from context import models
from models import model
import unittest
class test_model(unittest.TestCase):
def setUp(self):
self.room = model.Room(20, 'new_room')
self.room1 = model.Room(6, 'new_room1')
self.livingspace = model.LivingSpace('orange')
self.office = model.Office('manjaro')
def test_Room_instance(self):
self.assertIsInstance(self.room, model.Room)
self.assertIsInstance(self.room1, model.Room)
def test_Room_max_occupation(self):
self.assertEqual(20, self.room.max_occupants)
def test_Room_name(self):
self.assertEqual('new_room1', self.room1.name)
self.room1.name = "changedname"
self.assertEqual('changedname', self.room1.name)
def test_office_ocupants(self):
self.assertEqual(6, self.office.max_occupants)
def test_livingspace_ocupants(self):
self.assertEqual(4, self.livingspace.max_occupants)
def test_sublclass_Room(self):
self.assertTrue(issubclass(model.Office, model.Room))
self.assertTrue(issubclass(model.LivingSpace, model.Room))
def test_room_current_population(self):
self.assertEqual(self.room.current_population, 0)
| from context import models
from models import model
import unittest
class test_logic_core(unittest.TestCase):
def setUp(self):
self.room = model.Room(20, 'new_room')
self.room1 = model.Room(6, 'new_room1')
self.livingspace = model.LivingSpace('orange')
self.office = model.Office('manjaro')
def test_Room_instance(self):
self.assertIsInstance(self.room, model.Room)
self.assertIsInstance(self.room1, model.Room)
def test_Room_max_occupation(self):
self.assertEqual(20, self.room.max_occupants)
def test_Room_name(self):
self.assertEqual('new_room1', self.room1.name)
def test_office_ocupants(self):
self.assertEqual(6, self.office.max_occupants)
def test_livingspace_ocupants(self):
self.assertEqual(4, self.livingspace.max_occupants)
def test_sublclass_Room(self):
self.assertTrue(issubclass(model.Office, model.Room))
self.assertTrue(issubclass(model.LivingSpace, model.Room))
|
Return added stop in StopBin.add_stop() | """Stop Bins."""
import util
import errors
import registry
import entities
class StopBin(object):
def __init__(self, prefix):
self.prefix = prefix
self._stops = {}
def stops(self):
return self._stops.values()
def add_stop(self, stop):
key = stop.onestop()
# New stop
if key not in self._stops:
self._stops[key] = stop
else:
self._stops[key].merge(stop)
return self._stops[key]
@classmethod
def from_json(cls, data):
stopbin = cls(prefix=data['prefix'])
for feature in data['features']:
stop = entities.OnestopStop.from_json(feature)
stopbin.add_stop(stop)
return stopbin
def json(self):
return {
'type': 'FeatureCollection',
'properties': {},
'prefix': self.prefix,
'features': [
i.json()
for i in
sorted(self.stops(), key=lambda x:x.onestop())
]
}
| """Stop Bins."""
import util
import errors
import registry
import entities
class StopBin(object):
def __init__(self, prefix):
self.prefix = prefix
self._stops = {}
def stops(self):
return self._stops.values()
def add_stop(self, stop):
key = stop.onestop()
# New stop
if key not in self._stops:
self._stops[key] = stop
else:
self._stops[key].merge(stop)
@classmethod
def from_json(cls, data):
stopbin = cls(prefix=data['prefix'])
for feature in data['features']:
stop = entities.OnestopStop.from_json(feature)
stopbin.add_stop(stop)
return stopbin
def json(self):
return {
'type': 'FeatureCollection',
'properties': {},
'prefix': self.prefix,
'features': [
i.json()
for i in
sorted(self.stops(), key=lambda x:x.onestop())
]
}
|
Remove debugger from water grid calendar | Ext4.namespace('EHR.reports');
EHR.reports.waterGridCalendar = function (panel, tab) {
var filterArray = panel.getFilterArray(tab);
//debugger;
var title = panel.getTitleSuffix();
var target = tab.add({tag: 'span', style: 'padding-bottom: 20px'});
tab.doLayout();
var curDate = new Date();
curDate = curDate.format(LABKEY.extDefaultDateFormat)
var config = panel.getQWPConfig({
title: 'Water Grid Calendar',
schemaName: 'study',
queryName: 'WaterScheduleCoalesced',
parameters: {'NumDays': '180', 'StartDate': curDate},
filters: filterArray.nonRemovable,
frame: true
});
tab.add({
xtype: 'ldk-querypanel',
style: 'margin-bottom:20px;',
queryConfig: config
});
};
| Ext4.namespace('EHR.reports');
EHR.reports.waterGridCalendar = function (panel, tab) {
var filterArray = panel.getFilterArray(tab);
debugger;
var title = panel.getTitleSuffix();
var target = tab.add({tag: 'span', style: 'padding-bottom: 20px'});
tab.doLayout();
var curDate = new Date();
curDate = curDate.format(LABKEY.extDefaultDateFormat)
var config = panel.getQWPConfig({
title: 'Water Grid Calendar',
schemaName: 'study',
queryName: 'WaterScheduleCoalesced',
parameters: {'NumDays': '180', 'StartDate': curDate},
filters: filterArray.nonRemovable,
frame: true
});
tab.add({
xtype: 'ldk-querypanel',
style: 'margin-bottom:20px;',
queryConfig: config
});
}; |
Add non-processable method for testing | /*
* Copyright 2016 requery.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.requery.test.modelautovalue;
import com.google.auto.value.AutoValue;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
@Entity
@AutoValue
public abstract class Phone {
public static Phone create(int id, String phoneNumber, boolean normalized, int ownerId) {
return new AutoValue_Phone(id, phoneNumber, normalized, ownerId);
}
@Id @GeneratedValue
public abstract int getId();
public abstract String getPhoneNumber();
public abstract boolean isNormalized();
@JoinColumn(foreignKey = @ForeignKey, table = "Person")
public abstract int getOwnerId();
// this method should not be processed
public boolean isValid() {
return getPhoneNumber() != null && isNormalized();
}
}
| /*
* Copyright 2016 requery.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.requery.test.modelautovalue;
import com.google.auto.value.AutoValue;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
@Entity
@AutoValue
public abstract class Phone {
public static Phone create(int id, String phoneNumber, boolean normalized, int ownerId) {
return new AutoValue_Phone(id, phoneNumber, normalized, ownerId);
}
@Id @GeneratedValue
public abstract int getId();
public abstract String getPhoneNumber();
public abstract boolean isNormalized();
@JoinColumn(foreignKey = @ForeignKey, table = "Person")
public abstract int getOwnerId();
}
|
Revert proxy handler change for coverage | module.exports = function mutableProxyFactory(defaultTarget) {
let mutableHandler;
let mutableTarget;
function setTarget(target) {
if (!(target instanceof Object)) {
throw new Error(`Target "${target}" is not an object`);
}
mutableTarget = target;
}
function setHandler(handler) {
Object.keys(handler).forEach(key => {
const value = handler[key];
if (typeof value !== 'function') {
throw new Error(`Trap "${key}: ${value}" is not a function`);
}
if (!Reflect[key]) {
throw new Error(`Trap "${key}: ${value}" is not a valid trap`);
}
});
mutableHandler = handler;
}
if (defaultTarget) {
setTarget(defaultTarget);
}
setHandler(Reflect);
// Dynamically forward all the traps to the associated methods on the mutable handler
const handler = new Proxy({}, {
get(target, property) {
return (...args) => mutableHandler[property].apply(null, [mutableTarget, ...args.slice(1)]);
}
});
return {
setTarget,
setHandler,
getTarget() {
return mutableTarget;
},
getHandler() {
return mutableHandler;
},
proxy: new Proxy(() => {}, handler)
};
};
| module.exports = function mutableProxyFactory(defaultTarget) {
let mutableHandler;
let mutableTarget;
function setTarget(target) {
if (!(target instanceof Object)) {
throw new Error(`Target "${target}" is not an object`);
}
mutableTarget = target;
}
function setHandler(handler) {
Object.keys(handler).forEach(key => {
const value = handler[key];
if (typeof value !== 'function') {
throw new Error(`Trap "${key}: ${value}" is not a function`);
}
if (!Reflect[key]) {
throw new Error(`Trap "${key}: ${value}" is not a valid trap`);
}
});
mutableHandler = handler;
}
if (defaultTarget) {
setTarget(defaultTarget);
}
setHandler(Reflect);
// Dynamically forward all the traps to the associated methods on the mutable handler
const handler = new Proxy({}, {
get(target, property) {
return (...args) => {
const patched = [mutableTarget].concat(...args.slice(1));
return mutableHandler[property].apply(null, patched);
};
}
});
return {
setTarget,
setHandler,
getTarget() {
return mutableTarget;
},
getHandler() {
return mutableHandler;
},
proxy: new Proxy(() => {}, handler)
};
};
|
Remove extra whitespace in newline | from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
| from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
|
Tests: Fix version_info check for Python2.6 | import sys
import doctest
def fix_doctests(suite):
if sys.version_info[0] >= 3:
return
for case in suite._tests:
# Add some more flags.
case._dt_optionflags = (
(case._dt_optionflags or 0) |
doctest.IGNORE_EXCEPTION_DETAIL |
doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE
)
test = case._dt_test
for example in test.examples:
# Remove b prefix from strings.
if example.want.startswith("b'"):
example.want = example.want[1:]
def get_doctests(mod):
suite = doctest.DocTestSuite(mod)
fix_doctests(suite)
return suite
| import sys
import doctest
def fix_doctests(suite):
if sys.version_info.major >= 3:
return
for case in suite._tests:
# Add some more flags.
case._dt_optionflags = (
(case._dt_optionflags or 0) |
doctest.IGNORE_EXCEPTION_DETAIL |
doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE
)
test = case._dt_test
for example in test.examples:
# Remove b prefix from strings.
if example.want.startswith("b'"):
example.want = example.want[1:]
def get_doctests(mod):
suite = doctest.DocTestSuite(mod)
fix_doctests(suite)
return suite
|
Use args to create the desired instance of transit | // Copyright (c) Cognitect, Inc.
// All rights reserved.
package com.cognitect.transit;
public class TestRoundtrip {
public static void main(String [] args) throws Exception {
String encoding = args[0];
Reader reader;
Writer writer;
if(encoding.equals("msgpack")) {
reader = Reader.getMsgpackInstance(System.in, Reader.defaultDecoders());
writer = Writer.getMsgpackInstance(System.out, Writer.defaultHandlers());
}
else {
reader = Reader.getJsonInstance(System.in, Reader.defaultDecoders());
writer = Writer.getJsonInstance(System.out, Writer.defaultHandlers());
}
try {
while(true) {
Object o = reader.read();
writer.write(o);
}
}
catch(Exception e) {
// exit
}
}
}
| // Copyright (c) Cognitect, Inc.
// All rights reserved.
package com.cognitect.transit;
public class TestRoundtrip {
public static void main(String [] args) throws Exception {
// TODO: use argument to set up json or msgpack
Reader reader = Reader.getJsonInstance(System.in, Reader.defaultDecoders());
Writer writer = Writer.getJsonInstance(System.out, Writer.defaultHandlers());
try {
while(true) {
Object o = reader.read();
writer.write(o);
}
}
catch(Exception e) {
// exit
}
}
}
|
Fix another bug in dagre | import * as dagre from "dagre"
export default function() {
let width = 1,
height = 1;
function layout(dag) {
const g = new dagre.graphlib.Graph(),
info = {};
g.setGraph(info);
dag.nodes().forEach(n => g.setNode(n.id, n));
dag.links().forEach(l => g.setEdge(l.source.id, l.target.id, l));
dagre.layout(g);
// Rescale
dag.links().forEach(link => {
const { source, target, points } = link;
// XXX These are because of perceived bugs in dagre
if (points) {
points[0].y = source.y;
points[points.length - 1].y = target.y;
points.forEach(p => {
p.x *= width / info.width;
p.y *= height / info.height;
});
} else {
link.points = [{x: source.x, y: source.y}, {x: target.x, y: target.y}];
}
});
dag.nodes().forEach(node => {
node.x *= width / info.width;
node.y *= height / info.height;
});
return dag;
}
layout.size = function(x) {
return arguments.length ? ([width, height] = x, layout) : [width, height];
}
return layout;
}
| import * as dagre from "dagre"
export default function() {
let width = 1,
height = 1;
function layout(dag) {
const g = new dagre.graphlib.Graph(),
info = {};
g.setGraph(info);
dag.nodes().forEach(n => g.setNode(n.id, n));
dag.links().forEach(l => g.setEdge(l.source.id, l.target.id, l));
dagre.layout(g);
// Rescale
dag.links().forEach(({source, target, points}) => {
// XXX This seems to be a bug in dagre
points[0].y = source.y;
points[points.length - 1].y = target.y;
points.forEach(p => {
p.x *= width / info.width;
p.y *= height / info.height;
});
});
dag.nodes().forEach(node => {
node.x *= width / info.width;
node.y *= height / info.height;
});
return dag;
}
layout.size = function(x) {
return arguments.length ? ([width, height] = x, layout) : [width, height];
}
return layout;
}
|
Add ref back to the ignore list - we still have three non-passing tests | <?php
namespace JsonSchema\Tests\Drafts;
class Draft4Test extends BaseDraftTestCase
{
protected function getFilePaths()
{
return array(
realpath(__DIR__ . $this->relativeTestsRoot . '/draft4'),
realpath(__DIR__ . $this->relativeTestsRoot . '/draft4/optional')
);
}
protected function getSkippedTests()
{
return array(
// Not Yet Implemented
'definitions.json',
// Partially Implemented
'ref.json',
'refRemote.json',
// Optional
'bignum.json',
'zeroTerminatedFloats.json'
);
}
}
| <?php
namespace JsonSchema\Tests\Drafts;
class Draft4Test extends BaseDraftTestCase
{
protected function getFilePaths()
{
return array(
realpath(__DIR__ . $this->relativeTestsRoot . '/draft4'),
realpath(__DIR__ . $this->relativeTestsRoot . '/draft4/optional')
);
}
protected function getSkippedTests()
{
return array(
// Not Yet Implemented
'definitions.json',
// Partially Implemented
//'ref.json',
'refRemote.json',
// Optional
'bignum.json',
'zeroTerminatedFloats.json'
);
}
}
|
Set possible to use ~ | // http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
},
extends: 'airbnb-base',
// required to lint *.vue files
plugins: [
'html'
],
// check if imports actually resolve
'settings': {
'import/resolver': {
'webpack': {
'config': 'build/webpack.base.conf.js'
}
}
},
// add your custom rules here
'rules': {
// don't require .vue extension when importing
'import/extensions': ['error', 'always', {
'js': 'never',
'vue': 'never'
}],
// allow optionalDependencies
'import/no-extraneous-dependencies': ['error', {
'optionalDependencies': ['test/unit/index.js']
}],
'no-bitwise': [2, { allow: ["~"] }],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}
| // http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
},
extends: 'airbnb-base',
// required to lint *.vue files
plugins: [
'html'
],
// check if imports actually resolve
'settings': {
'import/resolver': {
'webpack': {
'config': 'build/webpack.base.conf.js'
}
}
},
// add your custom rules here
'rules': {
// don't require .vue extension when importing
'import/extensions': ['error', 'always', {
'js': 'never',
'vue': 'never'
}],
// allow optionalDependencies
'import/no-extraneous-dependencies': ['error', {
'optionalDependencies': ['test/unit/index.js']
}],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
} |
Remove an old version of the Filter() wrapper function | from _botan import *
# Initialize the library when the module is imported
init = LibraryInitializer()
class SymmetricKey(OctetString):
pass
class InitializationVector(OctetString):
pass
def Filter(name, key = None, iv = None, dir = None):
if key != None and iv != None and dir != None:
return make_filter(name, key, iv, dir)
elif key != None and dir != None:
return make_filter(name, key, dir)
elif key != None:
return make_filter(name, key)
else:
return make_filter(name)
def Pipe(*filters):
pipe = PipeObj()
for filter in filters:
if filter:
pipe.append(filter)
return pipe
| from _botan import *
init = LibraryInitializer()
class SymmetricKey(OctetString):
pass
class InitializationVector(OctetString):
pass
def Filter(name, key = None, iv = None, dir = None):
if key != None and iv != None and dir != None:
return make_filter(name, key, iv, dir)
elif key != None and dir != None:
return make_filter(name, key, dir)
elif key != None:
return make_filter(name, key)
else:
return make_filter(name)
def Pipe(*filters):
pipe = PipeObj()
for filter in filters:
if filter:
pipe.append(filter)
return pipe
#def Filter(name, key):
# return make_filter(name, key)
|
Make it runnable directly from cli, no python in front | #! /bin/env python
import sys
import argparse
import os
from harvester.couchdb_init import get_couchdb
import couchdb
from harvester.couchdb_sync_db_by_collection import delete_collection
def confirm_deletion(cid):
prompt = "Are you sure you want to delete all couchdb " + \
"documents for %s? yes to confirm\n" % cid
while True:
ans = raw_input(prompt).lower()
if ans == "yes":
return True
else:
return False
if __name__=='__main__':
parser = argparse.ArgumentParser(
description='Delete all documents in given collection')
parser.add_argument('collection_id',
help='Registry id for the collection')
parser.add_argument('--yes', action='store_true',
help="Don't prompt for deletion, just do it")
args = parser.parse_args(sys.argv[1:])
if args.yes or confirm_deletion(args.collection_id):
print 'DELETING COLLECTION {}'.format(args.collection_id)
num, deleted_ids = delete_collection(args.collection_id)
print "DELETED {} DOCS".format(num)
else:
print "Exiting without deleting"
| import sys
import argparse
import os
from harvester.couchdb_init import get_couchdb
import couchdb
from harvester.couchdb_sync_db_by_collection import delete_collection
def confirm_deletion(cid):
prompt = "Are you sure you want to delete all couchdb " + \
"documents for %s? yes to confirm\n" % cid
while True:
ans = raw_input(prompt).lower()
if ans == "yes":
return True
else:
return False
if __name__=='__main__':
parser = argparse.ArgumentParser(
description='Delete all documents in given collection')
parser.add_argument('collection_id',
help='Registry id for the collection')
parser.add_argument('--yes', action='store_true',
help="Don't prompt for deletion, just do it")
args = parser.parse_args(sys.argv[1:])
if args.yes or confirm_deletion(args.collection_id):
print 'DELETING COLLECTION {}'.format(args.collection_id)
num, deleted_ids = delete_collection(args.collection_id)
print "DELETED {} DOCS".format(num)
else:
print "Exiting without deleting"
|
Use larger values for stable test. | import unittest
import numpy
import chainer.functions as F
from chainer import testing
def make_data(dtype, shape):
x = numpy.random.uniform(0.1, 5, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
#
# sqrt
@testing.math_function_test(F.sqrt, make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
def rsqrt(x, dtype=numpy.float32):
return numpy.reciprocal(numpy.sqrt(x, dtype=dtype))
@testing.math_function_test(F.rsqrt, func_expected=rsqrt, make_data=make_data)
class TestRsqrt(unittest.TestCase):
pass
testing.run_module(__name__, __file__)
| import unittest
import numpy
import chainer.functions as F
from chainer import testing
def make_data(dtype, shape):
x = numpy.random.uniform(0.1, 1, shape).astype(dtype)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
return x, gy
#
# sqrt
@testing.math_function_test(F.sqrt, make_data=make_data)
class TestSqrt(unittest.TestCase):
pass
#
# rsqrt
def rsqrt(x, dtype=numpy.float32):
return numpy.reciprocal(numpy.sqrt(x, dtype=dtype))
@testing.math_function_test(F.rsqrt, func_expected=rsqrt, make_data=make_data)
class TestRsqrt(unittest.TestCase):
pass
testing.run_module(__name__, __file__)
|
Allow for setting NULL value | <?php namespace Inkwell\HTTP
{
use Dotink\Flourish\Collection;
class CookieCollection extends Collection
{
/**
*
*/
public function get($name = NULL, $default = NULL)
{
if ($name !== NULL) {
$value = parent::get($name, $default);
return is_array($value)
? $value[0]
: $value;
}
$values = array();
foreach (array_keys(parent::get()) as $name) {
$values[$name] = $this->get($name, $default);
}
return $values;
}
/**
*
*/
public function set($name, $value = NULL, $expire = 0, $path = NULL, $domain = NULL, $secure = FALSE, $httponly = FALSE)
{
if ($value === NULL && is_array($values = func_get_arg(0))) {
foreach ($values as $name => $value) {
$this->set($name, $value);
}
} else {
parent::set($name, array_slice(func_get_args(), 1));
}
return $this;
}
}
}
| <?php namespace Inkwell\HTTP
{
use Dotink\Flourish\Collection;
class CookieCollection extends Collection
{
/**
*
*/
public function get($name = NULL, $default = NULL)
{
if ($name !== NULL) {
$value = parent::get($name, $default);
return is_array($value)
? $value[0]
: $value;
}
$values = array();
foreach (array_keys(parent::get()) as $name) {
$values[$name] = $this->get($name, $default);
}
return $values;
}
/**
*
*/
public function set($name, $value = NULL, $expire = 0, $path = NULL, $domain = NULL, $secure = FALSE, $httponly = FALSE)
{
if ($value !== NULL) {
return parent::set($name, array_slice(func_get_args(), 1));
}
if (is_array($values = func_get_arg(0))) {
foreach ($values as $name => $value) {
$this->set($name, $value);
}
}
return $this;
}
}
}
|
Fix button block new tab bug. | /* @flow */
import React from 'react';
import Button from 'grommet/components/Button';
import Anchor from 'grommet/components/Anchor';
import type { AssetType, ButtonType } from './BlockButtonForm';
export type Props = {
label?: string,
path?: string,
href?: string,
assetType?: AssetType,
buttonType?: ButtonType,
primary?: boolean,
}
export default function BlockButton({
buttonType,
href,
path,
label,
primary,
assetType,
}: Props) {
const isPrimary = primary === 'True';
let props = { label, primary: isPrimary, target: '_blank' };
if (assetType === 'path' && path && path.indexOf('.') < 0) {
props = { ...props, path };
} else if (assetType === 'path' && path && path.indexOf('.') > -1) {
props = { ...props, href: path, target: '_blank' };
} else {
props = { ...props, href };
}
if (buttonType === 'Button') {
return (
<Button {...props} />
);
} else if (buttonType === 'Anchor') {
return (
<Anchor {...props} />
);
}
}
| /* @flow */
import React from 'react';
import Button from 'grommet/components/Button';
import Anchor from 'grommet/components/Anchor';
import type { AssetType, ButtonType } from './BlockButtonForm';
export type Props = {
label?: string,
path?: string,
href?: string,
assetType?: AssetType,
buttonType?: ButtonType,
primary?: boolean,
}
export default function BlockButton({
buttonType,
href,
path,
label,
primary,
assetType,
}: Props) {
const isPrimary = primary === 'True';
let props = { label, primary: isPrimary, target: '_blank' };
if (assetType === 'path' && path && path.indexOf('.') < 0) {
props = { ...props, path };
} else if (assetType === 'path' && path && path.indexOf('.') > -1) {
props = { ...props, href: path };
} else {
props = { ...props, href };
}
if (buttonType === 'Button') {
return (
<Button {...props} />
);
} else if (buttonType === 'Anchor') {
return (
<Anchor {...props} />
);
}
}
|
Add better pytest test support | """
A utility to package subsets of large ASPECT PVD files to visualize elsewhere
without access to the original filesystem.
"""
import sys
from setuptools import find_packages, setup
needs_pytest = {'pytest', 'test'}.intersection(sys.argv)
pytest_runner = ['pytest_runner'] if needs_pytest else []
package = 'sci_parameter_utils'
version = '0.2.0'
dependencies = [
'click',
'pyyaml',
'sympy',
]
setup_deps = [
] + pytest_runner
test_deps = [
'pytest',
]
setup(
name=package,
version=version,
package_dir={'': 'src'},
packages=find_packages('src', exclude=['tests']),
install_requires=dependencies,
setup_requires=setup_deps,
tests_require=test_deps,
entry_points={
'console_scripts': [
'sci_parameter_utils = sci_parameter_utils.cli:cli_main'
]
},
)
| """
A utility to package subsets of large ASPECT PVD files to visualize elsewhere
without access to the original filesystem.
"""
from setuptools import find_packages, setup
package = 'sci_parameter_utils'
version = '0.2.0'
dependencies = [
'click',
'pyyaml',
'sympy'
]
test_deps = [
'pytest'
]
setup(
name=package,
version=version,
package_dir={'': 'src'},
packages=find_packages('src', exclude=['tests']),
install_requires=dependencies,
tests_require=test_deps,
entry_points={
'console_scripts': [
'sci_parameter_utils = sci_parameter_utils.cli:cli_main'
]
}
)
|
Throw if passed non-function as first param | var placeholder = {},
endOfArgs = {},
slice = Array.prototype.slice.call.bind(Array.prototype.slice);
function shuv(fn){
var outerArgs = slice(arguments, 1);
if(typeof fn !== 'function'){
throw new Error('No or non-function passed to shuv');
}
return function(){
var context = this,
innerArgs = slice(arguments),
finalArgs = [],
append = true;
for(var i = 0; i < outerArgs.length; i++){
var outerArg = outerArgs[i];
if(outerArg === endOfArgs){
append = false;
break;
}
if(outerArg === placeholder){
finalArgs.push(innerArgs.shift());
continue;
}
finalArgs.push(outerArg);
}
if(append){
finalArgs = finalArgs.concat(innerArgs);
}
return fn.apply(context, finalArgs);
};
}
shuv._ = placeholder;
shuv.$ = endOfArgs;
module.exports = shuv; | var placeholder = {},
endOfArgs = {},
slice = Array.prototype.slice.call.bind(Array.prototype.slice);
function shuv(fn){
var outerArgs = slice(arguments, 1);
return function(){
var context = this,
innerArgs = slice(arguments),
finalArgs = [],
append = true;
for(var i = 0; i < outerArgs.length; i++){
var outerArg = outerArgs[i];
if(outerArg === endOfArgs){
append = false;
break;
}
if(outerArg === placeholder){
finalArgs.push(innerArgs.shift());
continue;
}
finalArgs.push(outerArg);
}
if(append){
finalArgs = finalArgs.concat(innerArgs);
}
return fn.apply(context, finalArgs);
};
}
shuv._ = placeholder;
shuv.$ = endOfArgs;
module.exports = shuv; |
Update export path to new structure | from enum import Enum
class Constants:
app_title = "RTGraph"
app_version = '0.2.0'
app_export_path = "data"
app_sources = ["Serial", "Simulator"]
app_encoding = "utf-8"
plot_update_ms = 16
plot_xlabel_title = "Time"
plot_xlabel_unit = "s"
plot_colors = ['#0072bd', '#d95319', '#edb120', '#7e2f8e', '#77ac30', '#4dbeee', '#a2142f']
process_join_timeout_ms = 1000
argument_default_samples = 500
serial_default_speed = 115200
serial_timeout_ms = 0.5
simulator_default_speed = 0.002
csv_default_filename = "%Y-%m-%d_%H-%M-%S"
csv_delimiter = ","
csv_extension = "csv"
parser_timeout_ms = 0.05
log_filename = "{}.log".format(app_title)
log_max_bytes = 5120
log_default_level = 1
log_default_console_log = False
class MinimalPython:
major = 3
minor = 2
release = 0
class SourceType(Enum):
simulator = 1
serial = 0
| from enum import Enum
class Constants:
app_title = "RTGraph"
app_version = '0.2.0'
app_export_path = "../data"
app_sources = ["Serial", "Simulator"]
app_encoding = "utf-8"
plot_update_ms = 16
plot_xlabel_title = "Time"
plot_xlabel_unit = "s"
plot_colors = ['#0072bd', '#d95319', '#edb120', '#7e2f8e', '#77ac30', '#4dbeee', '#a2142f']
process_join_timeout_ms = 1000
argument_default_samples = 500
serial_default_speed = 115200
serial_timeout_ms = 0.5
simulator_default_speed = 0.002
csv_default_filename = "%Y-%m-%d_%H-%M-%S"
csv_delimiter = ","
csv_extension = "csv"
parser_timeout_ms = 0.05
log_filename = "{}.log".format(app_title)
log_max_bytes = 5120
log_default_level = 1
log_default_console_log = False
class MinimalPython:
major = 3
minor = 2
release = 0
class SourceType(Enum):
simulator = 1
serial = 0
|
Change to raw strings in exercise 4 checking | from learntools.core import *
import tensorflow as tf
class Q1A(ThoughtExperiment):
_solution = ""
class Q1B(ThoughtExperiment):
_solution = ""
Q1 = MultipartProblem(Q1A, Q1B)
class Q2A(ThoughtExperiment):
_hint = r"Stacking the second layer expanded the receptive field by one neuron on each side, giving $3+1+1=5$ for each dimension. If you expanded by one neuron again, what would you get?"
_solution = r"The third layer would have a $7 \times 7$ receptive field."
class Q2B(ThoughtExperiment):
_hint = r"This pooling layer collapses a $2 \times 2$ patch into a single pixel, effectively *doubling* the number of connections along each dimension. "
_solution = r"Doubling a $7 \times 7$ field produces a $14 \times 14$ field for the final outputs."
Q2 = MultipartProblem(Q2A, Q2B)
class Q3(CodingProblem):
_hint = "You just need a list of numbers, maybe three to five."
_solution = CS("""
kernel = tf.constant([0.1, 0.2, 0.3, 0.4])
""")
def check(self):
pass
qvars = bind_exercises(globals(), [
Q1, Q2, Q3,
],
var_format='q_{n}',
)
__all__ = list(qvars)
| from learntools.core import *
import tensorflow as tf
class Q1A(ThoughtExperiment):
_solution = ""
class Q1B(ThoughtExperiment):
_solution = ""
Q1 = MultipartProblem(Q1A, Q1B)
class Q2A(ThoughtExperiment):
_hint = "Stacking the second layer expanded the receptive field by one neuron on each side, giving $3+1+1=5$ for each dimension. If you expanded by one neuron again, what would you get?"
_solution = "The third layer would have a $7\times 7$ receptive field."
class Q2B(ThoughtExperiment):
_hint = "This pooling layer collapses a $2\times 2$ patch into a single pixel, effectively *doubling* the number of connections along each dimension. "
_solution = "Doubling a $7 \times 7$ field produces a $14 \times 14$ field for the final outputs."
Q2 = MultipartProblem(Q2A, Q2B)
class Q3(CodingProblem):
_hint = "You just need a list of numbers, maybe three to five."
_solution = CS("""
kernel = tf.constant([0.1, 0.2, 0.3, 0.4])
""")
def check(self):
pass
qvars = bind_exercises(globals(), [
Q1, Q2, Q3,
],
var_format='q_{n}',
)
__all__ = list(qvars)
|
Remove the upper bound constraint on tensorflow_datasets dependency.
PiperOrigin-RevId: 371241485 | # Lint as: python3
# Copyright 2020 Google LLC. 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.
"""Setup configuration of TensorFlow Cloud client-side library."""
def make_required_install_packages():
return [
"absl-py",
"docker",
"google-api-python-client",
"google-auth",
"google-cloud-storage",
"keras-tuner",
"tensorboard>=2.3.0",
"tensorflow>=1.15.0,<3.0",
"tensorflow_datasets",
"tensorflow_transform",
]
def make_required_test_packages():
return [
"absl-py",
"flake8",
"mock",
"numpy",
"nbconvert",
]
| # Lint as: python3
# Copyright 2020 Google LLC. 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.
"""Setup configuration of TensorFlow Cloud client-side library."""
def make_required_install_packages():
return [
"absl-py",
"docker",
"google-api-python-client",
"google-auth",
"google-cloud-storage",
"keras-tuner",
"tensorboard>=2.3.0",
"tensorflow>=1.15.0,<3.0",
"tensorflow_datasets<3.1.0",
"tensorflow_transform",
]
def make_required_test_packages():
return [
"absl-py",
"flake8",
"mock",
"numpy",
"nbconvert",
]
|
Make Container widgets take children as the first positional argument
This makes creating containers less cumbersome: Container([list, of, children]), rather than Container(children=[list, of, children]) | """ContainerWidget class.
Represents a container that can be used to group other widgets.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Tuple, TraitError
class ContainerWidget(DOMWidget):
_view_name = Unicode('ContainerView', sync=True)
# Child widgets in the container.
# Using a tuple here to force reassignment to update the list.
# When a proper notifying-list trait exists, that is what should be used here.
children = Tuple(sync=True)
def __init__(self, children = None, **kwargs):
kwargs['children'] = children
super(ContainerWidget, self).__init__(**kwargs)
self.on_displayed(ContainerWidget._fire_children_displayed)
def _fire_children_displayed(self):
for child in self.children:
child._handle_displayed()
class PopupWidget(ContainerWidget):
_view_name = Unicode('PopupView', sync=True)
description = Unicode(sync=True)
button_text = Unicode(sync=True)
| """ContainerWidget class.
Represents a container that can be used to group other widgets.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget
from IPython.utils.traitlets import Unicode, Tuple, TraitError
class ContainerWidget(DOMWidget):
_view_name = Unicode('ContainerView', sync=True)
# Child widgets in the container.
# Using a tuple here to force reassignment to update the list.
# When a proper notifying-list trait exists, that is what should be used here.
children = Tuple(sync=True)
def __init__(self, **kwargs):
super(ContainerWidget, self).__init__(**kwargs)
self.on_displayed(ContainerWidget._fire_children_displayed)
def _fire_children_displayed(self):
for child in self.children:
child._handle_displayed()
class PopupWidget(ContainerWidget):
_view_name = Unicode('PopupView', sync=True)
description = Unicode(sync=True)
button_text = Unicode(sync=True)
|
Add default port for HAProxy | var fork = require('child_process').fork;
var async = require('async');
var amountConcurrentUsers = process.argv[2] || 200;
var host = process.argv[3] || 'http://localhost';
var initialPort = process.argv[4] || 3000;
var totalServers = process.argv[5] || 50;
var Client = require('./client');
var defaultHAProxyPort = 80;
var clientIdentifiers = [];
var clients = [];
for(var i = 0; i < amountConcurrentUsers; i++) {
clientIdentifiers.push(i);
};
console.log('Here we go');
console.log('amountConcurrentUsers: ' + amountConcurrentUsers);
console.log('Host: ' + host);
console.log('Initial port: ' + initialPort);
for(var j = 0; j < totalServers; j++) {
var port = (isHAProxyPort(defaultHAProxyPort, initialPort)) ? defaultHAProxyPort : initialPort + j;
console.log('Connecting to port: ' + port);
async.each(clientIdentifiers, function(clientIdentifier) {
// clients[clientIdentifier] = fork('client.js', [host, port, clientIdentifier] );
console.log('Client: ' + clientIdentifier);
clients[clientIdentifier] = Client(host, port, port + '-' + clientIdentifier);
}, function(err){
console.log('UPSSS! Error!');
});
}
function isHAProxyPort(defaultHAProxyPort, port) {
return port === defaultHAProxyPort;
} | var fork = require('child_process').fork;
var async = require('async');
var amountConcurrentUsers = process.argv[2] || 200;
var host = process.argv[3] || 'http://localhost';
var initialPort = process.argv[4] || 3000;
var totalServers = process.argv[5] || 50;
var Client = require('./client');
var defaultHAProxyPort = 80;
var clientIdentifiers = [];
var clients = [];
for(var i = 0; i < amountConcurrentUsers; i++) {
clientIdentifiers.push(i);
};
console.log('Here we go');
console.log('amountConcurrentUsers: ' + amountConcurrentUsers);
console.log('Host: ' + host);
console.log('Initial port: ' + initialPort);
for(var j = 0; j < totalServers; j++) {
var port = (isHAProxyPort(defaultHAProxyPort, port)) ? defaultHAProxyPort : initialPort + j;
console.log('Connecting to port: ' + port);
async.each(clientIdentifiers, function(clientIdentifier) {
// clients[clientIdentifier] = fork('client.js', [host, port, clientIdentifier] );
console.log('Client: ' + clientIdentifier);
clients[clientIdentifier] = Client(host, port, port + '-' + clientIdentifier);
}, function(err){
console.log('UPSSS! Error!');
});
}
function isHAProxyPort(defaultHAProxyPort, port) {
return port === defaultHAProxyPort;
} |
Fix Link function coming from controller, not module | <?php
/**
* Created by PhpStorm.
* User: Conrad
* Date: 24/06/2016
* Time: 9:06 AM
*/
class ModuleController extends Controller
{
/**
* @var ContentModule
*/
protected $dataRecord;
protected $currentController;
public function __construct(ContentModule $dataRecord, ContentController $curr = null)
{
$this->dataRecord = $dataRecord;
$this->currentController = $curr;
$this->setFailover($this->dataRecord);
parent::__construct();
}
public function init()
{
parent::init();
}
public function handleRequest(SS_HTTPRequest $request, DataModel $model)
{
return parent::handleRequest($request, $model);
}
public function data()
{
return $this->dataRecord;
}
public function currController()
{
return $this->currentController;
}
/**
* Overwrite the link function from the Controller
*
* @param null $action
* @return mixed
*/
public function Link($action = null)
{
return $this->data()->Link($action);
}
} | <?php
/**
* Created by PhpStorm.
* User: Conrad
* Date: 24/06/2016
* Time: 9:06 AM
*/
class ModuleController extends Controller
{
/**
* @var ContentModule
*/
protected $dataRecord;
protected $currentController;
public function __construct(ContentModule $dataRecord, ContentController $curr = null)
{
$this->dataRecord = $dataRecord;
$this->currentController = $curr;
$this->setFailover($this->dataRecord);
parent::__construct();
}
public function init()
{
parent::init();
}
public function handleRequest(SS_HTTPRequest $request, DataModel $model)
{
return parent::handleRequest($request, $model);
}
public function data()
{
return $this->dataRecord;
}
public function currController()
{
return $this->currentController;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.