text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use shallowMount instead of mount
|
import RemoveModal from '~/components/RemoveModal'
import BaseModal from '~/components/BaseModal'
import { shallowMount } from 'helper'
describe('Remove modal component', () => {
let wrapper, baseModalWrapper
beforeEach(() => {
wrapper = shallowMount(RemoveModal, {})
baseModalWrapper = wrapper.find(BaseModal)
})
describe('Emitted show event from base-modal', () => {
beforeEach(() => {
wrapper.setMethods({
show: jest.fn()
})
const post = {}
baseModalWrapper.vm.$emit('show', post)
})
test('Called show()', () => {
expect(wrapper.vm.show).toHaveBeenCalled()
})
test('Shown the post', () => {
wrapper.vm.post = {}
expect(wrapper.find('post-stub').exists()).toBe(true)
})
})
describe('Emitted hidden event from base-modal', () => {
beforeEach(() => {
wrapper.setMethods({
hidden: jest.fn()
})
baseModalWrapper.vm.$emit('hidden')
})
test('Called hidden()', () => {
expect(wrapper.vm.hidden).toHaveBeenCalled()
})
test('The post is hidden', () => {
expect(wrapper.find('.list-group').exists()).toBe(false)
})
})
})
|
import RemoveModal from '~/components/RemoveModal'
import BaseModal from '~/components/BaseModal'
import { mount } from 'helper'
describe('Remove modal component', () => {
let wrapper, baseModalWrapper
beforeEach(() => {
wrapper = mount(RemoveModal, {
stubs: {
post: true
}
})
baseModalWrapper = wrapper.find(BaseModal)
})
describe('Emitted show event from base-modal', () => {
beforeEach(() => {
wrapper.setMethods({
show: jest.fn()
})
const post = {}
baseModalWrapper.vm.$emit('show', post)
})
test('Called show()', () => {
expect(wrapper.vm.show).toHaveBeenCalled()
})
test('Shown the post', () => {
wrapper.vm.post = {}
expect(wrapper.find('post-stub').exists()).toBe(true)
})
})
describe('Emitted hidden event from base-modal', () => {
beforeEach(() => {
wrapper.setMethods({
hidden: jest.fn()
})
baseModalWrapper.vm.$emit('hidden')
})
test('Called hidden()', () => {
expect(wrapper.vm.hidden).toHaveBeenCalled()
})
test('The post is hidden', () => {
expect(wrapper.find('.list-group').exists()).toBe(false)
})
})
})
|
Add function to populate storage
|
'use strict'
// Code thanks to MDN
export function storageAvailable (type) {
try {
let storage = window[type]
let x = '__storage_test__'
storage.setItem(x, x)
storage.removeItem(x)
return true
} catch (e) {
let storage = window[type]
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage.length !== 0
}
}
export function storagePopulated () {
if (window.localStorage.length !== 0) {
console.log('populated')
return true
}
}
export function populateStorage () {
window.localStorage.setItem('pomodoroTime', document.getElementById('pomodoroInput').value)
window.localStorage.setItem('shortBreakTime', document.getElementById('shortBreakInput').value)
window.localStorage.setItem('longBreakTime', document.getElementById('longBreakInput').value)
}
|
'use strict'
// Code thanks to MDN
export function storageAvailable (type) {
try {
let storage = window[type]
let x = '__storage_test__'
storage.setItem(x, x)
storage.removeItem(x)
return true
} catch (e) {
let storage = window[type]
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
storage.length !== 0
}
}
function storagePopulated () {
if (Storage.length !== 0) {
console.log('populated')
return true
}
}
|
Fix the ordering of stripping and transliteration
This was kind of a silly way to do this. First stripping everything that is not default, and then using iconv transliteration. At that point there would be no special chars left. This explains why i always lose my French éàç characters in the slug :)
Fixes #8
|
<?php
namespace Kunstmaan\UtilitiesBundle\Helper;
/**
* Sulgifier is a helper to slugify a certain string
*/
class Slugifier
{
/**
* Slugify a string
*
* @param string $text Text to slugify
* @param string $default Default return value (override when slugify would return an empty string)
*
* @return string
*/
public static function slugify($text, $default = 'n-a')
{
// transliterate
if (function_exists('iconv')) {
$previouslocale = setlocale(LC_CTYPE, 0);
setlocale(LC_CTYPE, 'en_US.UTF8');
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
setlocale(LC_CTYPE, $previouslocale);
}
$text = preg_replace('#[^\\pL\d\/]+#u', '-', $text); // replace non letter or digits by -
$text = trim($text, '-'); //trim
$text = strtolower($text); // lowercase
$text = preg_replace('#[^-\w\/]+#', '', $text); // remove unwanted characters
if (empty($text)) {
return empty($default) ? '' : $default;
}
return $text;
}
}
|
<?php
namespace Kunstmaan\UtilitiesBundle\Helper;
/**
* Sulgifier is a helper to slugify a certain string
*/
class Slugifier
{
/**
* Slugify a string
*
* @param string $text Text to slugify
* @param string $default Default return value (override when slugify would return an empty string)
*
* @return string
*/
public static function slugify($text, $default = 'n-a')
{
$text = preg_replace('#[^\\pL\d\/]+#u', '-', $text); // replace non letter or digits by -
$text = trim($text, '-'); //trim
// transliterate
if (function_exists('iconv')) {
$previouslocale = setlocale(LC_CTYPE, 0);
setlocale(LC_CTYPE, 'en_US.UTF8');
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
setlocale(LC_CTYPE, $previouslocale);
}
$text = strtolower($text); // lowercase
$text = preg_replace('#[^-\w\/]+#', '', $text); // remove unwanted characters
if (empty($text)) {
return empty($default) ? '' : $default;
}
return $text;
}
}
|
Improve string encoding in network protocols
Eliminate unnecessary memory allocation.
|
package org.jvirtanen.parity.net.poe;
import static java.nio.charset.StandardCharsets.*;
import java.nio.ByteBuffer;
class ByteBuffers {
private static final byte SPACE = ' ';
static String getString(ByteBuffer buffer, int length) {
byte[] bytes = new byte[length];
buffer.get(bytes);
return new String(bytes, US_ASCII);
}
static void putString(ByteBuffer buffer, String value, int length) {
int i = 0;
for (; i < Math.min(value.length(), length); i++)
buffer.put((byte)value.charAt(i));
for (; i < length; i++)
buffer.put(SPACE);
}
}
|
package org.jvirtanen.parity.net.poe;
import static java.nio.charset.StandardCharsets.*;
import java.nio.ByteBuffer;
class ByteBuffers {
private static final byte SPACE = ' ';
static String getString(ByteBuffer buffer, int length) {
byte[] bytes = new byte[length];
buffer.get(bytes);
return new String(bytes, US_ASCII);
}
static void putString(ByteBuffer buffer, String value, int length) {
byte[] bytes = value.getBytes(US_ASCII);
int i = 0;
for (; i < Math.min(bytes.length, length); i++)
buffer.put(bytes[i]);
for (; i < length; i++)
buffer.put(SPACE);
}
}
|
Change prefilled gray suggestiosn to black by adding class.
|
;(function(){//IFEE
angular.module('brewKeeper')
.controller('createNewRecipe', function($scope, $http, $location){
$scope.recipe = { }
$scope.recipe.orientation = "Standard";
$scope.createNew=function(){
var username = ""
$http.get('https://brew-keeper-api.herokuapp.com/api/whoami/')
.then(function(response){
$("form-placeholder").removeClass("changed")
username = response.data.username;
$http.post('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/', $scope.recipe)
.success(function (data) {
var id = data.id
$location.path('/users/' + username + '/recipes/' + id);
})
$scope.recipe= { };
})
} //end submit function
$(".form-placeholder").on("change", function(){
$(this).addClass("changed");
})
})//controller for creating new step
})();//END IFEE
|
;(function(){//IFEE
angular.module('brewKeeper')
.controller('createNewRecipe', function($scope, $http, $location){
$scope.recipe = { }
$scope.recipe.orientation = "Standard";
$scope.submit=function(){
var username = ""
$http.get('https://brew-keeper-api.herokuapp.com/api/whoami/')
.then(function(response){
username = response.data.username;
$http.post('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/', $scope.recipe)
.success(function (data) {
var id = data.id
$location.path('/users/' + username + '/recipes/' + id);
})
$scope.recipe= { };
})
} //end submit function
})//controller for creating new step
})();//END IFEE
|
Add code for recieving data
|
package in.co.sdslabs.cognizance;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class AlarmReciever extends BroadcastReceiver {
NotificationManager nm;
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
String eventname = intent.getStringExtra("event");
Intent myIntent = new Intent(context, EventActivity.class);
Bundle data = new Bundle();
data.putString("event", eventname);
myIntent.putExtras(data);
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Cognizance 2014";
CharSequence message = eventname;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
myIntent, 0);
Notification notif = new Notification(R.drawable.launcher_icon,
"enter name of event that needs to be notified about", System.currentTimeMillis());
notif.flags = Notification.FLAG_INSISTENT;
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
};
|
package in.co.sdslabs.cognizance;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReciever extends BroadcastReceiver {
NotificationManager nm;
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent arg1) {
Intent myIntent = new Intent(context, EventActivity.class);
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Cognizance 2014";
CharSequence message = "Your Today's Tasks are.....";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
myIntent, 0);
Notification notif = new Notification(R.drawable.launcher_icon,
"enter name of event that needs to be notified about", System.currentTimeMillis());
notif.flags = Notification.FLAG_INSISTENT;
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
};
|
Add wine type to the list.
|
from django.contrib import admin
from .models import Wine, Grape, Winery
class GrapeInline(admin.TabularInline):
model = Grape
extra = 0
@admin.register(Wine)
class WineAdmin(admin.ModelAdmin):
list_display = ["__str__", "year", "wine_type", "in_cellar",]
fieldsets = (
('Bottle', {
'fields': ('bottle_text', 'year', 'wine_type', 'winery',),
}),
('Purchase', {
'fields': ('date_purchased', 'price', 'store', 'importer'),
}),
('Consumption', {
'fields': ('date_consumed', 'liked_it', 'notes',),
})
)
inlines = [
GrapeInline,
]
admin.site.register(Winery)
|
from django.contrib import admin
from .models import Wine, Grape, Winery
class GrapeInline(admin.TabularInline):
model = Grape
extra = 0
@admin.register(Wine)
class WineAdmin(admin.ModelAdmin):
list_display = ["__str__", "year", "in_cellar",]
fieldsets = (
('Bottle', {
'fields': ('bottle_text', 'year', 'wine_type', 'winery',),
}),
('Purchase', {
'fields': ('date_purchased', 'price', 'store', 'importer'),
}),
('Consumption', {
'fields': ('date_consumed', 'liked_it', 'notes',),
})
)
inlines = [
GrapeInline,
]
admin.site.register(Winery)
|
Add TODO to broken test
|
"""
Plot to test logscale
TODO (@vladh): `sharex` and `sharey` seem to cause the tick labels to go nuts. This needs to
be fixed.
"""
import matplotlib.pyplot as plt
import numpy as np
import mpld3
def create_plot():
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2, sharey=ax1, xscale='log')
ax3 = fig.add_subplot(2, 2, 3, sharex=ax1, yscale='log')
ax4 = fig.add_subplot(2, 2, 4, sharex=ax2, sharey=ax3)
x = np.linspace(1, 1e2)
y = x ** 2
for ax in [ax1, ax2, ax3, ax4]:
ax.plot(x, y)
return fig
def test_logscale():
fig = create_plot()
html = mpld3.fig_to_html(fig)
plt.close(fig)
if __name__ == "__main__":
mpld3.show(create_plot())
|
"""Plot to test logscale"""
import matplotlib.pyplot as plt
import numpy as np
import mpld3
def create_plot():
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2, sharey=ax1, xscale='log')
ax3 = fig.add_subplot(2, 2, 3, sharex=ax1, yscale='log')
ax4 = fig.add_subplot(2, 2, 4, sharex=ax2, sharey=ax3)
x = np.linspace(1, 1e2)
y = x ** 2
for ax in [ax1, ax2, ax3, ax4]:
ax.plot(x, y)
return fig
def test_logscale():
fig = create_plot()
html = mpld3.fig_to_html(fig)
plt.close(fig)
if __name__ == "__main__":
mpld3.show(create_plot())
|
Remove setting REPORT_TYPE. Reformatted code. Remove ANYBAR_COLOR_FAIL.
|
{
'REPORT_RECIPIENTS': 'steven.knight@cashstar.com',
'JENKINS_USERNAME': 'sknight',
'JENKINS_API_TOKEN': '594849a68d4911d6c39a2cb5f700c385',
'FEATURES': {
'PASSWORD_DECRYPTION': False,
'AWS': False,
'ANYBAR': True
},
# 'LOG_DB_URL': 'sqlite:///Users/steven.knight/Projects/qa/cashbot.db',
# 'LOG_DB_URL': 'sqlite:/:memory:',
'LOG_DB_URL': "mysql://cashbot:jJT!3VK14&llVP0o@localhost:3306/cashbotdb",
# 'GNUPG_VERBOSE': True,
# 'LOG_DB_DEBUG': True,
# 'CONSOLE_LOG_LEVEL': 'DEBUG',
}
|
{
'REPORT_TYPE': 'HTML',
'REPORT_RECIPIENTS': 'steven.knight@cashstar.com',
'JENKINS_USERNAME': 'sknight',
'JENKINS_API_TOKEN': '594849a68d4911d6c39a2cb5f700c385',
'FEATURES': {'PASSWORD_DECRYPTION': False, 'AWS': False, 'ANYBAR': True},
# 'LOG_DB_URL': 'sqlite:///Users/steven.knight/Projects/qa/cashbot.db',
# 'LOG_DB_URL': 'sqlite:/:memory:',
'LOG_DB_URL': "mysql://cashbot:jJT!3VK14&llVP0o@localhost:3306/cashbotdb",
# 'ANYBAR_COLOR_FAIL': 'blue',
# 'GNUPG_VERBOSE': True,
# 'LOG_DB_DEBUG': True,
# 'CONSOLE_LOG_LEVEL': 'DEBUG',
}
|
Set correct headings for file responses
|
const express = require('express'),
router = express.Router(),
fs = require('fs'),
path = require('path'),
grid = require('gridfs-stream');
const db = require('../lib/db'),
mongoose = db.goose,
conn = db.rope;
grid.mongo = mongoose.mongo;
router.get('/', function(req, res) {
const name = path.basename(req.originalUrl),
gfs = grid(conn.db);
const query = {
filename: name,
root: 'media'
}
function sendFile() {
const stream = gfs.createReadStream(query);
gfs.findOne(query, function(err, meta) {
if (err) {
throw err;
}
res.writeHead(200, {
'Content-Type': meta.contentType,
'Content-Length': meta.length
});
stream.pipe(res);
});
}
gfs.exist(query, function(err, found) {
if (err) {
throw err;
}
found ? sendFile() : res.send('File doesn\'t exist!');
});
});
module.exports = router;
|
const express = require('express'),
router = express.Router(),
fs = require('fs'),
path = require('path'),
grid = require('gridfs-stream');
const db = require('../lib/db'),
mongoose = db.goose,
conn = db.rope;
grid.mongo = mongoose.mongo;
router.get('/', function(req, res) {
const name = path.basename(req.originalUrl),
gfs = grid(conn.db);
const query = {
filename: name,
root: 'media'
}
function sendFile() {
const stream = gfs.createReadStream(query);
res.writeHead(200, {
'Content-Type': 'image/png'
});
stream.pipe(res);
}
gfs.exist(query, function(err, found) {
if (err) {
throw err;
}
found ? sendFile() : res.send('File doesn\'t exist!');
});
});
module.exports = router;
|
Make KeychainItem _decode method static
|
from Crypto.Cipher import AES
from base64 import b64decode
import json
from openpassword.pkcs_utils import strip_byte_padding
from openpassword.openssl_utils import derive_openssl_key
class KeychainItem:
def __init__(self, item):
self.encrypted = b64decode(item["encrypted"])
def decrypt(self, decryption_key):
key = self._derive_decryption_key(decryption_key)
data = self._decrypt(self.encrypted[16:], key)
data = strip_byte_padding(data)
return json.loads(data.decode('utf8'))
def _derive_decryption_key(self, decryption_key):
return derive_openssl_key(decryption_key, self.encrypted[8:16])
@staticmethod
def _decrypt(data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
|
from Crypto.Cipher import AES
from base64 import b64decode
import json
from openpassword.pkcs_utils import strip_byte_padding
from openpassword.openssl_utils import derive_openssl_key
class KeychainItem:
def __init__(self, item):
self.encrypted = b64decode(item["encrypted"])
def decrypt(self, decryption_key):
key = self._derive_decryption_key(decryption_key)
data = self._decrypt(self.encrypted[16:], key)
data = strip_byte_padding(data)
return json.loads(data.decode('utf8'))
def _derive_decryption_key(self, decryption_key):
return derive_openssl_key(decryption_key, self.encrypted[8:16])
def _decrypt(self, data, key_iv):
key = key_iv[0:16]
iv = key_iv[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
return cipher.decrypt(data)
|
Update current user from props
|
import React, {Component} from 'react';
import {Table} from 'react-bootstrap';
import {connect} from 'react-redux';
import _ from 'lodash';
class UsersTable extends Component {
render() {
return (
<div className="tbl-scroll">
<Table responsive striped>
<tbody>
<tr>
<th> {this.props.heading} </th>
</tr>
{_.union(this.props.playerName, this.props.users)
.map(_.startCase).sort().map((x) => _renderUserRow(x))}
</tbody>
</Table>
</div>
);
}
}
function _renderUserRow(data) {
return (
<tr key={data}>
<td>{data}</td>
</tr>
)
}
function mapStateToProps(state) {
return {
users: state.users,
playerName: state.game.playerName,
};
}
export default connect(mapStateToProps)(UsersTable);
|
import React, {Component} from 'react';
import {Table} from 'react-bootstrap';
import {connect} from 'react-redux';
import _ from 'lodash';
class UsersTable extends Component {
render() {
return (
<div className="tbl-scroll">
<Table responsive striped>
<tbody>
<tr>
<th> {this.props.heading} </th>
</tr>
{this.props.users.map(_.startCase).sort().map((x) => _renderUserRow(x))}
</tbody>
</Table>
</div>
);
}
}
function _renderUserRow(data) {
return (
<tr key={data}>
<td>{data}</td>
</tr>
)
}
function mapStateToProps(state) {
return {
users: state.users
};
}
export default connect(mapStateToProps)(UsersTable);
|
Fix having special characters in login/password field.
Signed-off-by: thomnico <5d7b651831a7f5cf7c72a23146042589c88b16b7@googlemail.com>
|
#!/usr/bin/env python
from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(
name='fortiosapi',
version='0.10.6',
description=('Python modules to use Fortigate APIs'
'full configuration, monitoring, lifecycle rest and ssh'),
long_description=readme(),
# Valid Classifiers are here:
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python ',
'Topic :: Security',
],
keywords='Fortinet fortigate fortios rest api',
install_requires=['requests', 'paramiko', 'oyaml', 'copy', 'json'],
author='Nicolas Thomas',
author_email='nthomas@fortinet.com',
url='https://github.com/fortinet-solutions-cse/fortiosapi',
include_package_data=True,
packages=['fortiosapi'],
)
|
#!/usr/bin/env python
from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(
name='fortiosapi',
version='0.10.5',
description=('Python modules to use Fortigate APIs'
'full configuration, monitoring, lifecycle rest and ssh'),
long_description=readme(),
# Valid Classifiers are here:
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python ',
'Topic :: Security',
],
keywords='Fortinet fortigate fortios rest api',
install_requires=['requests', 'paramiko', 'oyaml'],
author='Nicolas Thomas',
author_email='nthomas@fortinet.com',
url='https://github.com/fortinet-solutions-cse/fortiosapi',
include_package_data=True,
packages=['fortiosapi'],
)
|
Use Bluebird's nodeify to handle resulting promise
|
var Promise = require('bluebird');
var mapObj = require('map-obj');
var assign = require('object-assign');
function FileWebpackPlugin(files) {
this.files = files || {};
}
FileWebpackPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('emit', function(compiler, done) {
var data = {};
var assetPromises = mapObj(self.files, function(filename, asyncTemplate) {
var promise = Promise
.fromNode(asyncTemplate.bind(null, data))
.then(createAssetFromContents)
return [filename, promise];
});
Promise.props(assetPromises)
.then(function(assets) {
assign(compiler.assets, assets);
})
.nodeify(done);
});
};
function createAssetFromContents(contents) {
return {
source: function() {
return contents;
},
size: function() {
return contents.length;
}
};
}
module.exports = FileWebpackPlugin;
|
var Promise = require('bluebird');
var mapObj = require('map-obj');
var assign = require('object-assign');
function FileWebpackPlugin(files) {
this.files = files || {};
}
FileWebpackPlugin.prototype.apply = function(compiler) {
var self = this;
compiler.plugin('emit', function(compiler, done) {
var data = {};
var assetPromises = mapObj(self.files, function(filename, asyncTemplate) {
var promise = Promise
.fromNode(asyncTemplate.bind(null, data))
.then(createAssetFromContents)
return [filename, promise];
});
Promise.props(assetPromises)
.then(function(assets) {
assign(compiler.assets, assets);
done();
}, function(err) {
done(err);
});
});
};
function createAssetFromContents(contents) {
return {
source: function() {
return contents;
},
size: function() {
return contents.length;
}
};
}
module.exports = FileWebpackPlugin;
|
Handle worker with no options
|
var mongoose = require('mongoose');
var mubsub = require('mubsub');
var monq = module.exports = {};
monq.Job = require('./job');
monq.Queue = require('./queue');
monq.Worker = require('./worker');
monq.pubsub = mubsub.channel('events');
monq.worker = function(options) {
options || (options = {});
options.pubsub || (options.pubsub = monq.pubsub);
return new monq.Worker(options);
};
monq.queue = function(name) {
return new monq.Queue(name);
};
monq.subscribe = function(id, callback) {
return monq.pubsub.subscribe({ 'job._id': id }, callback);
};
monq.connect = function(db) {
mongoose.connect(db);
mubsub.connect(db);
return monq;
};
monq.disconnect = function() {
mongoose.disconnect();
mubsub.disconnect();
};
|
var mongoose = require('mongoose');
var mubsub = require('mubsub');
var monq = module.exports = {};
monq.Job = require('./job');
monq.Queue = require('./queue');
monq.Worker = require('./worker');
monq.pubsub = mubsub.channel('events');
monq.worker = function(options) {
options.pubsub || (options.pubsub = monq.pubsub);
return new monq.Worker(options);
};
monq.queue = function(name) {
return new monq.Queue(name);
};
monq.subscribe = function(id, callback) {
return monq.pubsub.subscribe({ 'job._id': id }, callback);
};
monq.connect = function(db) {
mongoose.connect(db);
mubsub.connect(db);
return monq;
};
monq.disconnect = function() {
mongoose.disconnect();
mubsub.disconnect();
};
|
Remove init in public api
|
const RunPluginScriptCommand = require('./src/commands/runPluginScript')
const CreateProjectCommand = require('./src/commands/createProject')
const AddPluginsCommand = require('./src/commands/addPlugins')
const RemovePluginsCommand = require('./src/commands/removePlugins')
const UpdatePluginsCommand = require('./src/commands/updatePlugins')
const GenerateCommand = require('./src/commands/generate')
const CommitCommand = require('./src/commands/commit')
const ReleaseCommand = require('./src/commands/release')
const AssembleCommand = require('./src/commands/assemble')
const commands = [
RunPluginScriptCommand,
CreateProjectCommand,
AddPluginsCommand,
RemovePluginsCommand,
UpdatePluginsCommand,
GenerateCommand,
CommitCommand,
AssembleCommand,
ReleaseCommand,
]
const runCommand = (commandName, argv, params, options) => {
const Command = commands.find(command => command.commandName === commandName)
if (!Command) {
throw new Error('Can\'t find command')
}
const command = new Command(argv, options)
return command.run(params)
}
module.exports = {
runCommand,
}
|
const RunPluginScriptCommand = require('./src/commands/runPluginScript')
const CreateProjectCommand = require('./src/commands/createProject')
const AddPluginsCommand = require('./src/commands/addPlugins')
const RemovePluginsCommand = require('./src/commands/removePlugins')
const UpdatePluginsCommand = require('./src/commands/updatePlugins')
const GenerateCommand = require('./src/commands/generate')
const CommitCommand = require('./src/commands/commit')
const ReleaseCommand = require('./src/commands/release')
const AssembleCommand = require('./src/commands/assemble')
const commands = [
RunPluginScriptCommand,
CreateProjectCommand,
AddPluginsCommand,
RemovePluginsCommand,
UpdatePluginsCommand,
GenerateCommand,
CommitCommand,
AssembleCommand,
ReleaseCommand,
]
const runCommand = (commandName, argv, params, options) => {
const Command = commands.find(command => command.commandName === commandName)
if (!Command) {
throw new Error('Can\'t find command')
}
const command = new Command(argv, options)
command.init()
return command.run(params)
}
module.exports = {
runCommand,
}
|
Fix up local.ini updater code to look specifically for 'xform_translate_path'
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
"""
The sole purpose of the following script is to update the
local.ini file used by the dimagi teamcity buildserver
so that xform_translate_path gets updated to point to the folder
{project.dir}/lib
"""
JAR_PATH_SETTING = 'xform_translate_path'
import sys, os
if 'RAPIDSMS_INI' not in os.environ:
print "RAPIDSMS_INI NOT FOUND"
sys.exit()
local_ini = os.environ['RAPIDSMS_INI']
filedir = os.path.dirname(__file__)
xform_jar_path = os.path.abspath(os.path.join(filedir,'..','..','lib'))
ini = ""
should_update = False
fin = open(local_ini,"r")
for line in fin:
if JAR_PATH_SETTING in line:
line = 'xform_translate_path=%s\n' % xform_jar_path
should_update = True
ini = ini + line
fin.close()
if should_update:
fin = open(local_ini,"w")
fin.write(ini)
fin.close()
print "Updated %s with %s" % (local_ini, xform_jar_path)
else:
print "Nothing to update"
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
"""
The sole purpose of the following script is to update the
local.ini file used by the dimagi teamcity buildserver
so that the path to xform_translate.jar is updated dynamically.
It does this by identifying the jar_path_placeholder in the file
identified by the environment variable RAPIDSMS_INI and replacing
it with the value of {project.dir}/lib
CONFIGURATION
jar_path_placeholder: the setting in local.build.ini which we
want to update dynamically
"""
jar_path_placeholder = 'DYNAMIC_PATH_TO_XFORM_TRANSLATE_JAR'
import sys, os
if 'RAPIDSMS_INI' not in os.environ:
print "RAPIDSMS_INI NOT FOUND"
sys.exit()
local_ini = os.environ['RAPIDSMS_INI']
fin = open(local_ini,"r")
ini = fin.read()
fin.close()
if jar_path_placeholder in ini:
filedir = os.path.dirname(__file__)
xform_jar_path = os.path.abspath(os.path.join(filedir,'..','..','lib'))
ini = ini.replace(jar_path_placeholder, xform_jar_path)
fin = open(local_ini,"w")
fin.write(ini)
fin.close()
print "Updated %s with %s" % (local_ini, xform_jar_path)
|
Use `find_packages()` and since we aren't building `package_data` anymore, we need to use `MANIFEST.in`. That's what it's there for and does a more obvious job. "Explicit is better than implicit." Using MANIFEST requires `include_package_data=True`.
|
# Nothing in this file should need to be edited.
# Use package.json to adjust metadata about this package.
# Use MANIFEST.in to include package-specific data files.
import os
import json
from setuptools import setup, find_packages
info = json.load(open("./package.json"))
def generate_namespaces(package):
i = package.count(".")
while i:
yield package.rsplit(".", i)[0]
i -= 1
NAMESPACE_PACKAGES = list(generate_namespaces(info['name']))
if os.path.exists("MANIFEST"):
os.unlink("MANIFEST")
setup_kwargs = {
"author": "Bay Citizen & Texas Tribune",
"author_email": "dev@armstrongcms.org",
"url": "http://github.com/armstrong/%s/" % info["name"],
"packages": find_packages(),
"namespace_packages": NAMESPACE_PACKAGES,
"include_package_data": True,
"classifiers": [
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
}
setup_kwargs.update(info)
setup(**setup_kwargs)
|
"""
setup.py file for building armstrong components.
Nothing in this file should need to be edited, please see accompanying
package.json file if you need to adjust metadata about this package.
"""
import os
import json
from setuptools import setup, find_packages
info = json.load(open("./package.json"))
def generate_namespaces(package):
i = package.count(".")
while i:
yield package.rsplit(".", i)[0]
i -= 1
NAMESPACE_PACKAGES = list(generate_namespaces(info['name']))
if os.path.exists("MANIFEST"):
os.unlink("MANIFEST")
setup_kwargs = {
"author": "Bay Citizen & Texas Tribune",
"author_email": "dev@armstrongcms.org",
"url": "http://github.com/armstrong/%s/" % info["name"],
"packages": find_packages(exclude=["*.tests", "*.tests.*"]),
"namespace_packages": NAMESPACE_PACKAGES,
"include_package_data": True,
"classifiers": [
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
}
setup_kwargs.update(info)
setup(**setup_kwargs)
|
[Security] Fix security.interactive_login event const doc block
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Http;
final class SecurityEvents
{
/**
* The INTERACTIVE_LOGIN event occurs after a user has actively logged
* into your website. It is important to distinguish this action from
* non-interactive authentication methods, such as:
* - authentication based on your session.
* - authentication using a HTTP basic or HTTP digest header.
*
* The event listener method receives a
* Symfony\Component\Security\Http\Event\InteractiveLoginEvent instance.
*
* @Event
*
* @var string
*/
const INTERACTIVE_LOGIN = 'security.interactive_login';
/**
* The SWITCH_USER event occurs before switch to another user and
* before exit from an already switched user.
*
* The event listener method receives a
* Symfony\Component\Security\Http\Event\SwitchUserEvent instance.
*
* @Event
*
* @var string
*/
const SWITCH_USER = 'security.switch_user';
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Http;
final class SecurityEvents
{
/**
* The INTERACTIVE_LOGIN event occurs after a user is logged in
* interactively for authentication based on http, cookies or X509.
*
* The event listener method receives a
* Symfony\Component\Security\Http\Event\InteractiveLoginEvent instance.
*
* @Event
*
* @var string
*/
const INTERACTIVE_LOGIN = 'security.interactive_login';
/**
* The SWITCH_USER event occurs before switch to another user and
* before exit from an already switched user.
*
* The event listener method receives a
* Symfony\Component\Security\Http\Event\SwitchUserEvent instance.
*
* @Event
*
* @var string
*/
const SWITCH_USER = 'security.switch_user';
}
|
Add total load time to cache debug options
|
package com.tisawesomeness.minecord.debug;
import com.google.common.cache.CacheStats;
import lombok.NonNull;
/**
* Debugs a Guava {@link com.google.common.cache.LoadingCache}.
*/
public abstract class CacheDebugOption implements DebugOption {
public @NonNull String debug() {
CacheStats stats = getCacheStats();
return String.format("**%s Stats**\n", getName()) +
String.format("Hits: `%s/%s %.2f%%`\n", stats.hitCount(), stats.requestCount(), stats.hitRate()) +
String.format("Load Exceptions: `%s/%s %.2f%%`\n", stats.loadExceptionCount(), stats.loadCount(), 100*stats.loadExceptionRate()) +
String.format("Eviction Count: `%s`\n", stats.evictionCount()) +
String.format("Average Load Penalty: `%.3fms`\n", stats.averageLoadPenalty() / 1_000_000) +
String.format("Total Load Time: `%sms`", stats.totalLoadTime() / 1_000_000);
}
/**
* @return The cache stats to be used in {@link #debug()}.
*/
public abstract @NonNull CacheStats getCacheStats();
}
|
package com.tisawesomeness.minecord.debug;
import com.google.common.cache.CacheStats;
import lombok.NonNull;
/**
* Debugs a Guava {@link com.google.common.cache.LoadingCache}.
*/
public abstract class CacheDebugOption implements DebugOption {
public @NonNull String debug() {
CacheStats stats = getCacheStats();
return String.format("**%s Stats**\n", getName()) +
String.format("Hits: `%s/%s %.2f%%`\n", stats.hitCount(), stats.requestCount(), stats.hitRate()) +
String.format("Load Exceptions: `%s/%s %.2f%%`\n", stats.loadExceptionCount(), stats.loadCount(), 100*stats.loadExceptionRate()) +
String.format("Eviction Count: `%s`\n", stats.evictionCount()) +
String.format("Average Load Penalty: `%.3fms`", stats.averageLoadPenalty() / 1_000_000);
}
/**
* @return The cache stats to be used in {@link #debug()}.
*/
public abstract @NonNull CacheStats getCacheStats();
}
|
Comment out Google Analytics init.
|
import React, { Component, PropTypes } from 'react';
import { Provider } from 'react-redux';
import { getRoutes } from '../routes';
import { Router, applyRouterMiddleware } from 'react-router';
import { useScroll } from 'react-router-scroll';
//import ReactGA from 'react-ga';
export default class Root extends Component { // eslint-disable-line react/prefer-stateless-function
componentDidMount() {
// Google Analytics init.
/*ReactGA.initialize('UA-73635552-1', {
debug: false
});*/
}
_logPageView() {
// Logs each page view to your Google Analytics account.
//ReactGA.set({ page: window.location.pathname });
//ReactGA.pageview(window.location.pathname);
}
render() {
const { store, history } = this.props;
return (
<Provider store={store}>
<Router
history={history}
routes={getRoutes(store)}
render={applyRouterMiddleware(useScroll())}
onUpdate={this._logPageView}
/>
</Provider>
);
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
|
import React, { Component, PropTypes } from 'react';
import { Provider } from 'react-redux';
import { getRoutes } from '../routes';
import { Router, applyRouterMiddleware } from 'react-router';
import { useScroll } from 'react-router-scroll';
import ReactGA from 'react-ga';
export default class Root extends Component { // eslint-disable-line react/prefer-stateless-function
componentDidMount() {
ReactGA.initialize('UA-73635552-1', {
debug: false
});
}
_logPageView() {
ReactGA.set({ page: window.location.pathname });
ReactGA.pageview(window.location.pathname);
}
render() {
const { store, history } = this.props;
return (
<Provider store={store}>
<Router
history={history}
routes={getRoutes(store)}
render={applyRouterMiddleware(useScroll())}
onUpdate={this._logPageView}
/>
</Provider>
);
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
|
Add name on register form submit input. Is usefull to select it in unit test.
|
@extends('app')
@section('content')
<div class="container-fluid">
@include('partials/hero')
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<h1>
{{ trans('messages.user.register') }}
<a href="/" class="btn btn-default pull-right">
{{ trans('messages.back') }}
</a>
</h1>
{{ Form::open(['role' => 'form', 'url' => 'auth/register', 'name' => 'register']) }}
@include('useradmin/registerform')
@include('partials/errors')
<div class='form-group'>
{{ Form::submit(trans('messages.user.register'), ['class' => 'btn btn-success']) }}
</div>
{{ Form::close() }}
</div>
</div>
</div>
@endsection
|
@extends('app')
@section('content')
<div class="container-fluid">
@include('partials/hero')
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<h1>
{{ trans('messages.user.register') }}
<a href="/" class="btn btn-default pull-right">
{{ trans('messages.back') }}
</a>
</h1>
{{ Form::open(['role' => 'form', 'url' => 'auth/register']) }}
@include('useradmin/registerform')
@include('partials/errors')
<div class='form-group'>
{{ Form::submit(trans('messages.user.register'), ['class' => 'btn btn-success']) }}
</div>
{{ Form::close() }}
</div>
</div>
</div>
@endsection
|
Add python 3.4 to trove classifiers
|
from setuptools import setup
version = '0.1'
setup(
name='python-editor',
version=version,
description="Programmatically open an editor, capture the result.",
#long_description='',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
keywords='editor library vim emacs',
author='Peter Ruibal',
author_email='ruibalp@gmail.com',
url='https://github.com/fmoo/python-editor',
license='Apache',
py_modules=[
'editor',
],
requires=[
#'six',
],
)
|
from setuptools import setup
version = '0.1'
setup(
name='python-editor',
version=version,
description="Programmatically open an editor, capture the result.",
#long_description='',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries',
],
keywords='editor library vim emacs',
author='Peter Ruibal',
author_email='ruibalp@gmail.com',
url='https://github.com/fmoo/python-editor',
license='Apache',
py_modules=[
'editor',
],
requires=[
#'six',
],
)
|
auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
|
# -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'category': "Tools",
'depends': [
'base',
],
'data': [
'security/ir.model.access.csv',
'data/ir_cron.xml',
'views/auditlog_view.xml',
'views/http_session_view.xml',
'views/http_request_view.xml',
],
'images': [],
'application': True,
'installable': True,
}
|
# -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'category': "Tools",
'depends': [
'base',
],
'data': [
'security/ir.model.access.csv',
'data/ir_cron.xml',
'views/auditlog_view.xml',
'views/http_session_view.xml',
'views/http_request_view.xml',
],
'images': [],
'application': True,
'installable': True,
'pre_init_hook': 'pre_init_hook',
}
|
Add footer fields to Attachment
|
package slack
// https://api.slack.com/docs/attachments
// It is possible to create more richly-formatted messages using Attachments.
type AttachmentField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
type Attachment struct {
Color string `json:"color,omitempty"`
Fallback string `json:"fallback"`
AuthorName string `json:"author_name,omitempty"`
AuthorSubname string `json:"author_subname,omitempty"`
AuthorLink string `json:"author_link,omitempty"`
AuthorIcon string `json:"author_icon,omitempty"`
Title string `json:"title,omitempty"`
TitleLink string `json:"title_link,omitempty"`
Pretext string `json:"pretext,omitempty"`
Text string `json:"text"`
ImageURL string `json:"image_url,omitempty"`
ThumbURL string `json:"thumb_url,omitempty"`
Footer string `json:"footer,omitempty"`
FooterIcon string `json:"footer_icon,omitempty"`
Fields []*AttachmentField `json:"fields,omitempty"`
MarkdownIn []string `json:"mrkdwn_in,omitempty"`
}
|
package slack
// https://api.slack.com/docs/attachments
// It is possible to create more richly-formatted messages using Attachments.
type AttachmentField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
type Attachment struct {
Color string `json:"color,omitempty"`
Fallback string `json:"fallback"`
AuthorName string `json:"author_name,omitempty"`
AuthorSubname string `json:"author_subname,omitempty"`
AuthorLink string `json:"author_link,omitempty"`
AuthorIcon string `json:"author_icon,omitempty"`
Title string `json:"title,omitempty"`
TitleLink string `json:"title_link,omitempty"`
Pretext string `json:"pretext,omitempty"`
Text string `json:"text"`
ImageURL string `json:"image_url,omitempty"`
ThumbURL string `json:"thumb_url,omitempty"`
Fields []*AttachmentField `json:"fields,omitempty"`
MarkdownIn []string `json:"mrkdwn_in,omitempty"`
}
|
Add helper to easily cancel AsyncMap tasks
|
/*
* Copyright 2016 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.tool;
import android.support.annotation.Nullable;
import timber.log.Timber;
public final class AsyncMapHelper {
private AsyncMapHelper() {
throw new RuntimeException("No instances");
}
public static void unsubscribe(@Nullable AsyncMap.Entry entry) {
if (entry == null) {
Timber.w("AsyncMap Entry is NULL");
} else {
if (!entry.isUnloaded()) {
entry.unload();
}
}
}
public static void unsubscribe(@Nullable AsyncMap.Entry... entries) {
if (entries == null) {
Timber.w("AsyncMap Entries are NULL");
return;
}
for (final AsyncMap.Entry entry : entries) {
unsubscribe(entry);
}
}
}
|
/*
* Copyright 2016 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.tool;
import android.support.annotation.Nullable;
import timber.log.Timber;
public final class AsyncMapHelper {
private AsyncMapHelper() {
throw new RuntimeException("No instances");
}
public static void unsubscribe(@Nullable AsyncMap.Entry entry) {
if (entry == null) {
Timber.w("AsyncMap Entry is NULL");
} else {
if (!entry.isUnloaded()) {
entry.unload();
}
}
}
}
|
Use compatible release versions for all dependencies
|
import os
from setuptools import setup, find_packages
src_dir = os.path.dirname(__file__)
install_requires = [
"troposphere~=1.8.0",
"awacs~=0.6.0",
"stacker~=0.6.3",
]
tests_require = [
"nose~=1.0",
"mock~=2.0.0",
]
def read(filename):
full_path = os.path.join(src_dir, filename)
with open(full_path) as fd:
return fd.read()
if __name__ == "__main__":
setup(
name="stacker_blueprints",
version="0.6.5",
author="Michael Barrett",
author_email="loki77@gmail.com",
license="New BSD license",
url="https://github.com/remind101/stacker_blueprints",
description="Default blueprints for stacker",
long_description=read("README.rst"),
packages=find_packages(),
install_requires=install_requires,
tests_require=tests_require,
test_suite="nose.collector",
)
|
import os
from setuptools import setup, find_packages
src_dir = os.path.dirname(__file__)
install_requires = [
"troposphere==1.7.0",
"awacs==0.6.0",
"stacker==0.6.3",
]
tests_require = [
"nose>=1.0",
"mock==1.0.1",
]
def read(filename):
full_path = os.path.join(src_dir, filename)
with open(full_path) as fd:
return fd.read()
if __name__ == "__main__":
setup(
name="stacker_blueprints",
version="0.6.5",
author="Michael Barrett",
author_email="loki77@gmail.com",
license="New BSD license",
url="https://github.com/remind101/stacker_blueprints",
description="Default blueprints for stacker",
long_description=read("README.rst"),
packages=find_packages(),
install_requires=install_requires,
tests_require=tests_require,
test_suite="nose.collector",
)
|
Add debug messages for all region actions..
|
package au.com.mineauz.minigamesregions.actions;
import java.util.Map;
import au.com.mineauz.minigames.Minigames;
import au.com.mineauz.minigames.minigame.Minigame;
import au.com.mineauz.minigames.script.ScriptObject;
import org.bukkit.configuration.file.FileConfiguration;
import au.com.mineauz.minigames.MinigamePlayer;
import au.com.mineauz.minigames.menu.Menu;
import au.com.mineauz.minigamesregions.Node;
import au.com.mineauz.minigamesregions.Region;
public abstract class ActionInterface {
public abstract String getName();
public abstract String getCategory();
public abstract void describe(Map<String, Object> out);
public abstract boolean useInRegions();
public abstract boolean useInNodes();
public abstract void executeRegionAction(MinigamePlayer player, Region region);
public abstract void executeNodeAction(MinigamePlayer player, Node node);
public abstract void saveArguments(FileConfiguration config, String path);
public abstract void loadArguments(FileConfiguration config, String path);
public abstract boolean displayMenu(MinigamePlayer player, Menu previous);
public void debug(MinigamePlayer p, ScriptObject obj){
if (Minigames.plugin.isDebugging()){
Minigames.plugin.getLogger().info("Debug: Execute on Obj:" + String.valueOf(obj) + " as Action: " + String.valueOf(this) + " Player: " +String.valueOf(p));
}
}
}
|
package au.com.mineauz.minigamesregions.actions;
import java.util.Map;
import org.bukkit.configuration.file.FileConfiguration;
import au.com.mineauz.minigames.MinigamePlayer;
import au.com.mineauz.minigames.menu.Menu;
import au.com.mineauz.minigamesregions.Node;
import au.com.mineauz.minigamesregions.Region;
public abstract class ActionInterface {
public abstract String getName();
public abstract String getCategory();
public abstract void describe(Map<String, Object> out);
public abstract boolean useInRegions();
public abstract boolean useInNodes();
public abstract void executeRegionAction(MinigamePlayer player, Region region);
public abstract void executeNodeAction(MinigamePlayer player, Node node);
public abstract void saveArguments(FileConfiguration config, String path);
public abstract void loadArguments(FileConfiguration config, String path);
public abstract boolean displayMenu(MinigamePlayer player, Menu previous);
}
|
Fix `sleep` test. How did this pass locally before?!
|
"""
Tests for POSIX-compatible `sleep`.
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sleep.html
"""
import time
from helpers import check_version, run
def test_version():
"""Check that we're using Boreutil's implementation."""
assert check_version("sleep")
def test_missing_args():
"""No args => error of the form `sleep: ...`"""
assert run(["sleep"]).stderr.startswith("sleep:")
assert run(["sleep"]).returncode > 0
def test_extra_args():
"""Too many args => error of the form `sleep: ...`"""
assert run(["sleep", "a", "b"]).stderr.startswith("sleep:")
assert run(["sleep", "a", "b"]).returncode > 0
def test_help():
"""Passing -h or --help should print help text."""
assert run(["sleep", "-h"]).stdout.split(' ')[0] == 'Usage:'
assert run(["sleep", "--help"]).stdout.split(' ')[0] == 'Usage:'
assert run(["sleep", "-h"]).returncode > 0
assert run(["sleep", "--help"]).returncode > 0
def test_main():
"""Running `sleep 1` should run successfully."""
start = time.time()
ret = run(["sleep", "1"])
end = time.time()
assert len(ret.stdout) == 0
assert len(ret.stderr) == 0
assert ret.returncode == 0
assert (end - start) >= 1.0
|
"""
Tests for POSIX-compatible `sleep`.
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sleep.html
"""
import time
from helpers import check_version, run
def test_version():
"""Check that we're using Boreutil's implementation."""
assert check_version("sleep")
def test_missing_args():
"""No args => error of the form `sleep: ...`"""
assert run(["sleep"]).stderr.startswith("sleep:")
assert run(["sleep"]).returncode > 0
def test_extra_args():
"""Too many args => error of the form `sleep: ...`"""
assert run(["sleep", "a", "b"]).stderr.startswith("sleep:")
assert run(["sleep", "a", "b"]).returncode > 0
def test_help():
"""Passing -h or --help should print help text."""
assert run(["sleep", "-h"]).stdout.split(' ')[0] == 'Usage:'
assert run(["sleep", "--help"]).stdout.split(' ')[0] == 'Usage:'
assert run(["sleep", "-h"]).returncode > 0
assert run(["sleep", "--help"]).returncode > 0
def test_main():
"""Running `sleep 1` should run successfully."""
start = time.time()
ret = run(["sleep", "1"])
end = time.time()
assert len(ret.stdout) == 0
assert len(ret.stderr) == 0
assert ret.returncode == 0
assert (end - start) >= 2.0
|
Use threshold for time boundary in manager
|
from dateutil.relativedelta import relativedelta
from django.apps import apps
from django.utils import timezone
user_deletion_config = apps.get_app_config('user_deletion')
class UserDeletionManagerMixin:
def users_to_notify(self):
"""Finds all users who have been inactive and not yet notified."""
threshold = timezone.now() - relativedelta(
months=user_deletion_config.MONTH_NOTIFICATION,
)
return self.filter(last_login__lte=threshold, notified=False)
def users_to_delete(self):
"""Finds all users who have been inactive and were notified."""
threshold = timezone.now() - relativedelta(
months=user_deletion_config.MONTH_DELETION,
)
return self.filter(last_login__lte=threshold, notified=True)
|
from dateutil.relativedelta import relativedelta
from django.apps import apps
from django.utils import timezone
user_deletion_config = apps.get_app_config('user_deletion')
class UserDeletionManagerMixin:
def users_to_notify(self):
"""Finds all users who have been inactive and not yet notified."""
inactive_boundary = timezone.now() - relativedelta(
months=user_deletion_config.MONTH_NOTIFICATION,
)
return self.filter(last_login__lte=inactive_boundary, notified=False)
def users_to_delete(self):
"""Finds all users who have been inactive and were notified."""
one_year = timezone.now() - relativedelta(
months=user_deletion_config.MONTH_DELETION,
)
return self.filter(last_login__lte=one_year, notified=True)
|
Fix colour not being set when a colour multiplier with white was added
|
package codechicken.lib.render;
import codechicken.lib.colour.ColourRGBA;
public class ColourMultiplier implements CCRenderState.IVertexOperation
{
private static ColourMultiplier instance = new ColourMultiplier(-1);
public static ColourMultiplier instance(int colour) {
instance.colour = colour;
return instance;
}
public static final int operationIndex = CCRenderState.registerOperation();
public int colour;
public ColourMultiplier(int colour) {
this.colour = colour;
}
@Override
public boolean load() {
if(colour == -1) {
CCRenderState.setColour(-1);
return false;
}
CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib);
return true;
}
@Override
public void operate() {
CCRenderState.setColour(ColourRGBA.multiply(CCRenderState.colour, colour));
}
@Override
public int operationID() {
return operationIndex;
}
}
|
package codechicken.lib.render;
import codechicken.lib.colour.ColourRGBA;
public class ColourMultiplier implements CCRenderState.IVertexOperation
{
private static ColourMultiplier instance = new ColourMultiplier(-1);
public static ColourMultiplier instance(int colour) {
instance.colour = colour;
return instance;
}
public static final int operationIndex = CCRenderState.registerOperation();
public int colour;
public ColourMultiplier(int colour) {
this.colour = colour;
}
@Override
public boolean load() {
if(colour == -1)
return false;
CCRenderState.pipeline.addDependency(CCRenderState.colourAttrib);
return true;
}
@Override
public void operate() {
CCRenderState.setColour(ColourRGBA.multiply(CCRenderState.colour, colour));
}
@Override
public int operationID() {
return operationIndex;
}
}
|
Use javascript redirect to break out from iframe
|
<?php
/**
* Mondido
*
* PHP version 5.6
*
* @category Mondido
* @package Mondido_Mondido
* @author Andreas Karlsson <andreas@kodbruket.se>
* @license MIT License https://opensource.org/licenses/MIT
* @link https://www.mondido.com
*/
namespace Mondido\Mondido\Controller\Checkout;
/**
* Error action
*
* @category Mondido
* @package Mondido_Mondido
* @author Andreas Karlsson <andreas@kodbruket.se>
* @license MIT License https://opensource.org/licenses/MIT
* @link https://www.mondido.com
*/
class Error extends \Mondido\Mondido\Controller\Checkout\Index
{
/**
* Execute
*
* @return @void
*/
public function execute()
{
$message = $this->getRequest()->getParam('error_name');
$this->messageManager->addError(__($message));
$url = $this->_url->getUrl('checkout/cart');
echo '<!doctype html>
<html>
<head>
<script>
var isInIframe = (window.location != window.parent.location) ? true : false;
if (isInIframe == true) {
window.top.location.href = "'.$url.'";
} else {
window.location.href = "'.$url.'";
}
</script>
</head>
<body></body>
</html>';
die;
}
}
|
<?php
/**
* Mondido
*
* PHP version 5.6
*
* @category Mondido
* @package Mondido_Mondido
* @author Andreas Karlsson <andreas@kodbruket.se>
* @license MIT License https://opensource.org/licenses/MIT
* @link https://www.mondido.com
*/
namespace Mondido\Mondido\Controller\Checkout;
/**
* Error action
*
* @category Mondido
* @package Mondido_Mondido
* @author Andreas Karlsson <andreas@kodbruket.se>
* @license MIT License https://opensource.org/licenses/MIT
* @link https://www.mondido.com
*/
class Error extends \Mondido\Mondido\Controller\Checkout\Index
{
/**
* Execute
*
* @return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$message = $this->getRequest()->getParam('error_name');
$this->messageManager->addError(__($message));
return $this->resultRedirectFactory->create()->setPath('mondido/cart');
}
}
|
Revert "Temporarily make talks visible only to committee"
This reverts commit 57050b7025acb3de66024fe01255849a5ba5f1fc.
|
from django.shortcuts import render, get_object_or_404
from config.utils import get_active_event
from .models import Talk
def list_talks(request):
event = get_active_event()
talks = event.talks.prefetch_related(
'applicants',
'applicants__user',
'skill_level',
'sponsor',
).order_by('-keynote', 'title')
return render(request, 'talks/list_talks.html', {
"talks": talks,
})
def view_talk(request, slug):
event = get_active_event()
talk = get_object_or_404(Talk, slug=slug, event=event)
return render(request, 'talks/view_talk.html', {
'talk': talk})
|
from django.shortcuts import render, get_object_or_404
from config.utils import get_active_event
from .models import Talk
def list_talks(request):
event = get_active_event()
talks = event.talks.prefetch_related(
'applicants',
'applicants__user',
'skill_level',
'sponsor',
).order_by('-keynote', 'title')
# Temporary hack to let only admins & committee members see the talks
user = request.user
permitted = user.is_authenticated and (user.is_superuser or user.is_talk_committee_member())
if not permitted:
talks = event.talks.none()
return render(request, 'talks/list_talks.html', {
"talks": talks,
})
def view_talk(request, slug):
event = get_active_event()
talk = get_object_or_404(Talk, slug=slug, event=event)
return render(request, 'talks/view_talk.html', {
'talk': talk})
|
Fix typo breaking PyPI push.
|
from distutils.core import setup
setup(
name = 'mustache',
packages = ['mustache'],
version = '0.1.3',
description = 'Mustache templating in Python',
author = 'Peter Downs',
author_email = 'peterldowns@gmail.com',
url = 'https://github.com/peterldowns/python-mustache',
download_url = 'https://github.com/peterldowns/python-mustache/tarball/v0.1.3',
install_requirements = open('requirements.txt').read(),
extras_require = {
'test' : open('tests/requirements.txt').read(),
},
keywords = [
'templating',
'template',
'mustache',
'web'],
classifiers = [
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Markup'],
)
|
from distutils.core import setup
setup(
name = 'mustache',
packages = ['mustache'],
version = '0.1.3',
description = 'Mustache templating in Python',
author = 'Peter Downs',
author_email = 'peterldowns@gmail.com',
url = 'https://github.com/peterldowns/python-mustache',
download_url = 'https://github.com/peterldowns/python-mustache/tarball/v0.1.3',
install_requirements = open('requirements.txt').read(),
extras_require = {
'test' : open('tests/requirements.txt').read(),
}
keywords = [
'templating',
'template',
'mustache',
'web'],
classifiers = [
'Programming Language :: Python',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Text Processing :: Markup'],
)
|
Fix: Return EmptyIterator when no subscribers have been added for type
Co-authored-by: Andreas Möller <96e8155732e8324ae26f64d4516eb6fe696ac84f@localheinz.com>
Co-authored-by: Arne Blankerts <2d7739f42ebd62662a710577d3d9078342a69dee@Blankerts.de>
|
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Event;
use function array_key_exists;
use ArrayIterator;
use EmptyIterator;
use Iterator;
final class Subscribers
{
/**
* @var array<string, array<int, Subscriber>>
*/
private array $subscribers = [];
public function add(Subscriber $subscriber): void
{
foreach ($subscriber->subscribesTo() as $type) {
$this->subscribers[$type->asString()][] = $subscriber;
}
}
/**
* @return Iterator<Subscriber>
*/
public function for(Type $type): Iterator
{
if (!array_key_exists($type->asString(), $this->subscribers)) {
return new EmptyIterator();
}
return new ArrayIterator($this->subscribers[$type->asString()]);
}
}
|
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Event;
use ArrayIterator;
use Iterator;
final class Subscribers
{
/**
* @var array<string, array<int, Subscriber>>
*/
private array $subscribers = [];
public function add(Subscriber $subscriber): void
{
foreach ($subscriber->subscribesTo() as $type) {
$this->subscribers[$type->asString()][] = $subscriber;
}
}
/**
* @return Iterator<Subscriber>
*/
public function for(Type $type): Iterator
{
return new ArrayIterator($this->subscribers[$type->asString()]);
}
}
|
Throw WrongOrientationException (resolving compile-time issues)
|
package edu.agh.tunev.model.cellular.agent;
import java.awt.geom.Point2D;
import edu.agh.tunev.model.AbstractPerson;
public final class Person extends AbstractPerson {
public static final class WrongOrientationException extends Exception {
private static final long serialVersionUID = 1L;
}
public enum Orientation{
E, NE, N, NW, W, SW, S, SE
}
public Person(Point2D.Double position) {
super(position);
}
public static Double orientToAngle(Orientation orient) throws WrongOrientationException{
//starting at east
Double angle = 0.0;
Person.Orientation[] orientValues = Person.Orientation.values();
//TODO: more sensible error handling
for(int i = 0; i < orientValues.length && orient != orientValues[i]; ++i){
angle += 45.0;
}
if(angle > 315)
throw new WrongOrientationException();
else
return angle;
}
}
|
package edu.agh.tunev.model.cellular.agent;
import java.awt.geom.Point2D;
import edu.agh.tunev.model.AbstractPerson;
public final class Person extends AbstractPerson {
public enum Orientation{
E, NE, N, NW, W, SW, S, SE
}
public Person(Point2D.Double position) {
super(position);
}
public static Double orientToAngle(Orientation orient) throws WrongOrientationException{
//starting at east
Double angle = 0.0;
Person.Orientation[] orientValues = Person.Orientation.values();
//TODO: more sensible error handling
for(int i = 0; i < orientValues.length && orient != orientValues[i]; ++i){
angle += 45.0;
}
if(angle > 315)
throw new WrongOrientationException();
else
return angle;
}
}
|
Remove unused initialization code from user list activity.
|
/**
* Copyright (C) 2014 android10.org. All rights reserved.
* @author Fernando Cejas (the android10 coder)
*/
package com.fernandocejas.android10.sample.presentation.view.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import com.fernandocejas.android10.sample.presentation.R;
import com.fernandocejas.android10.sample.presentation.model.UserModel;
import com.fernandocejas.android10.sample.presentation.view.fragment.UserListFragment;
/**
* Activity that shows a list of Users.
*/
public class UserListActivity extends BaseActivity implements UserListFragment.UserListListener {
public static Intent getCallingIntent(Context context) {
return new Intent(context, UserListActivity.class);
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_user_list);
}
@Override public void onUserClicked(UserModel userModel) {
this.navigator.navigateToUserDetails(this, userModel.getUserId());
}
}
|
/**
* Copyright (C) 2014 android10.org. All rights reserved.
* @author Fernando Cejas (the android10 coder)
*/
package com.fernandocejas.android10.sample.presentation.view.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import com.fernandocejas.android10.sample.presentation.R;
import com.fernandocejas.android10.sample.presentation.model.UserModel;
import com.fernandocejas.android10.sample.presentation.navigation.Navigator;
import com.fernandocejas.android10.sample.presentation.view.fragment.UserListFragment;
/**
* Activity that shows a list of Users.
*/
public class UserListActivity extends BaseActivity implements UserListFragment.UserListListener {
public static Intent getCallingIntent(Context context) {
return new Intent(context, UserListActivity.class);
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_user_list);
this.initialize();
}
@Override public void onUserClicked(UserModel userModel) {
this.navigator.navigateToUserDetails(this, userModel.getUserId());
}
/**
* Initializes activity's private members.
*/
private void initialize() {
//This initialization should be avoided by using a dependency injection framework.
//But this is an example and for testing purpose.
this.navigator = new Navigator();
}
}
|
Change refresh time to 4 seconds
|
<?php
class CodesController extends \BaseController {
public function process($code)
{
$code = Code::where('code', '=', $code)->first();
if(is_null($code) || $code->used == 1){
return Redirect::to('/');
} else {
//Snapchatty functions
//Refresh(disappear) after 4 seconds
header("Refresh: " . 4);
$code->used = 1;
$code->used_time = Carbon::now();
$code->used_ip = Request::getClientIp();
$mobileDetect = new Mobile_Detect();
//Check for facebook bots (done in robots.txt)
$code->used_useragent = $mobileDetect->getUserAgent();
$code->save();
$path = storage_path().'/memes/'.Meme::find($code->meme_id)->filename;
// Get the image
$image = Image::make($path)->widen(600, function ($constraint) {
$constraint->upsize();
})->encode('data-url');
return View::make('meme')->withMeme($code->meme)->withImage($image);
}
}
}
|
<?php
class CodesController extends \BaseController {
public function process($code)
{
$code = Code::where('code', '=', $code)->first();
if(is_null($code) || $code->used == 1){
return Redirect::to('/');
} else {
//Snapchatty functions
//Refresh(disappear) after 6 seconds
header("Refresh: " . 6);
$code->used = 1;
$code->used_time = Carbon::now();
$code->used_ip = Request::getClientIp();
$mobileDetect = new Mobile_Detect();
//Check for facebook bots (done in robots.txt)
$code->used_useragent = $mobileDetect->getUserAgent();
$code->save();
$path = storage_path().'/memes/'.Meme::find($code->meme_id)->filename;
// Get the image
$image = Image::make($path)->widen(600, function ($constraint) {
$constraint->upsize();
})->encode('data-url');
return View::make('meme')->withMeme($code->meme)->withImage($image);
}
}
}
|
Update individual income tax test case
|
package main
import (
"fmt"
"testing"
)
func TestTax2011QuickDeduction(t *testing.T) {
fmt.Println("Year 2011:")
rate := tax2011Rate()
beforeTax := []float64{
18000,
54000,
108000,
420000,
660000,
960000,
-1,
}
afterTax, qdWithTax := quickDeduction(0, beforeTax, rate)
fmt.Printf("Atfer Tax:%v\n", afterTax)
for k, v := range qdWithTax {
if k > 0 {
fmt.Printf("%v: %v\n", k/12.0, v)
}
}
afterTax, qdWithoutTax := quickDeduction(1, beforeTax, rate)
fmt.Printf("Atfer Tax:%v\n", afterTax)
for k, v := range qdWithoutTax {
if k > 0 {
fmt.Printf("%v: %v\n", k/12.0, v)
}
}
}
|
package main
import (
"fmt"
"testing"
)
func TestTax2011QuickDeduction(t *testing.T) {
fmt.Println("Year 2011:")
afterTax, qdWithTax := tax2011QuickDeduction(0)
fmt.Printf("Atfer Tax:%v\n", afterTax)
for k, v := range qdWithTax {
if k > 0 {
fmt.Printf("%v: %v\n", k/12.0, v)
}
}
afterTax, qdWithoutTax := tax2011QuickDeduction(1)
fmt.Printf("Atfer Tax:%v\n", afterTax)
for k, v := range qdWithoutTax {
if k > 0 {
fmt.Printf("%v: %v\n", k/12.0, v)
}
}
}
func TestTax2018QuickDeduction(t *testing.T) {
tqd := tax2018QuickDeduction()
fmt.Println("Year 2018:")
for k, v := range tqd {
if k > 0 {
fmt.Printf("%v: %v\n", k/12, v/12)
}
}
}
|
Add a final on a member variable.
|
package com.haskforce.jps;
/*
* Downloaded from https://github.com/ignatov/intellij-erlang on 7 May
* 2014.
*/
import org.jetbrains.jps.builders.BuildRootDescriptor;
import org.jetbrains.jps.builders.BuildTarget;
import java.io.File;
/**
*
*/
public class HaskellSourceRootDescriptor extends BuildRootDescriptor {
private final File root;
private final HaskellTarget target;
public HaskellSourceRootDescriptor(File inRoot, HaskellTarget inTarget) {
root = inRoot;
target = inTarget;
}
@Override
public String getRootId() {
return "SourceRootDescriptor";
}
@Override
public File getRootFile() {
return root;
}
@Override
public BuildTarget<?> getTarget() {
return target;
}
}
|
package com.haskforce.jps;
/*
* Downloaded from https://github.com/ignatov/intellij-erlang on 7 May
* 2014.
*/
import org.jetbrains.jps.builders.BuildRootDescriptor;
import org.jetbrains.jps.builders.BuildTarget;
import java.io.File;
/**
*
*/
public class HaskellSourceRootDescriptor extends BuildRootDescriptor {
private File root;
private final HaskellTarget target;
public HaskellSourceRootDescriptor(File inRoot, HaskellTarget inTarget) {
root = inRoot;
target = inTarget;
}
@Override
public String getRootId() {
return "SourceRootDescriptor";
}
@Override
public File getRootFile() {
return root;
}
@Override
public BuildTarget<?> getTarget() {
return target;
}
}
|
Append 'px' to end of image upload form resize field
|
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import FormActions, Div, AppendedText
from crispy_forms.layout import Layout, Field, HTML, Button, Submit, Reset
class UploadImageForm(forms.Form):
helper = FormHelper()
helper.form_tag = False
helper.form_class = 'form-horizontal'
helper.label_class = 'col-xs-3'
helper.field_class = 'col-xs-9'
title = forms.CharField(
label = "Alt. Title",
required = True,
max_length=50,
)
image = forms.FileField(
label = "Image",
required = True,
)
resize = forms.IntegerField(
label = "Resize to this width or height",
initial = 1000,
required = True,
)
helper.layout = Layout(
Field('title'),
Field('image'),
AppendedText('resize', 'px'),
Div(
FormActions(
HTML('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'),
Submit('save', 'Upload'),
),
css_class="modal-footer"
),
)
|
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import FormActions, Div
from crispy_forms.layout import Layout, Field, HTML, Button, Submit, Reset
class UploadImageForm(forms.Form):
helper = FormHelper()
helper.form_tag = False
helper.form_class = 'form-horizontal'
helper.label_class = 'col-xs-3'
helper.field_class = 'col-xs-9'
title = forms.CharField(
label = "Alt. Title",
required = True,
max_length=50,
)
image = forms.FileField(
label = "Image",
required = True,
)
resize = forms.IntegerField(
label = "Resize to this width or height",
initial = 1000,
required = True,
)
helper.layout = Layout(
Field('title'),
Field('image'),
Field('resize'),
Div(
FormActions(
HTML('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'),
Submit('save', 'Upload'),
),
css_class="modal-footer"
),
)
|
Unify AppData, attribute is 'fill_window' everywhere
TO maintain consistency with pack data, The fillWindow property should be fill_window, this is the style that all JSON in the API takes
|
pc.extend(pc.fw, function () {
/**
* @name pc.fw.AppData
* @class AppData contains global data about the application that is loaded from Entity or Exported data
* For Exported applications it comes from pc.content.data['application'], for development applications it comes from the designer Component in the initial Pack
* @constructor Create a new pc.fw.AppData instance either from the export data or from Component data
* @param {Object} source either pc.content.data['application'] or the designer Component in as a source
*/
var AppData = function (source) {
this.fillWindow = source['fill_window'];
this.width = source['width'];
this.height = source['height']
};
return {
AppData: AppData
};
}());
|
pc.extend(pc.fw, function () {
/**
* @name pc.fw.AppData
* @class AppData contains global data about the application that is loaded from Entity or Exported data
* For Exported applications it comes from pc.content.data['application'], for development applications it comes from the designer Component in the initial Pack
* @constructor Create a new pc.fw.AppData instance either from the export data or from Component data
* @param {Object} source either pc.content.data['application'] or the designer Component in as a source
*/
var AppData = function (source) {
this.fillWindow = source['fill_window'] || source['fillWindow'];
this.width = source['width'];
this.height = source['height']
};
return {
AppData: AppData
};
}());
|
Include node-interval-tree in debugger bundle
|
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: "./debugger",
module: {
rules: [{
test: /\.js$/,
loader: "babel-loader",
query: {
presets: [
[
'babel-preset-env',
{ targets: { "node": "6.14" } }
]
],
plugins: ['transform-object-rest-spread', 'transform-runtime'],
},
include: [
path.resolve(__dirname, "..", 'lib')
],
}],
},
target: 'node',
output: {
library: "Debugger",
libraryTarget: "umd",
umdNamedDefine: true,
filename: "debugger.js",
path: path.join(__dirname, "..", "dist"),
devtoolModuleFilenameTemplate: '[absolute-resource-path]',
devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]'
},
resolve: {
modules: [path.resolve(__dirname, ".."), "node_modules"]
},
// in order to ignore all modules in node_modules folder
externals: [nodeExternals({
modulesFromFile: true,
whitelist: [
"node-interval-tree"
]
})],
devtool: "inline-cheap-module-source-map",
}
|
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: "./debugger",
module: {
rules: [{
test: /\.js$/,
loader: "babel-loader",
query: {
presets: [
[
'babel-preset-env',
{ targets: { "node": "6.14" } }
]
],
plugins: ['transform-object-rest-spread', 'transform-runtime'],
},
include: [
path.resolve(__dirname, "..", 'lib')
],
}],
},
target: 'node',
output: {
library: "Debugger",
libraryTarget: "umd",
umdNamedDefine: true,
filename: "debugger.js",
path: path.join(__dirname, "..", "dist"),
devtoolModuleFilenameTemplate: '[absolute-resource-path]',
devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]'
},
resolve: {
modules: [path.resolve(__dirname, ".."), "node_modules"]
},
// in order to ignore all modules in node_modules folder
externals: [nodeExternals({
modulesFromFile: true,
})],
devtool: "inline-cheap-module-source-map",
}
|
Mark as python 3 compatable.
git-svn-id: c8188841f5432f3fe42d04dee4f87e556eb5cf84@19 99efc558-b41a-11dd-8714-116ca565c52f
|
#!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
import os
from setuptools import setup, find_packages
here = os.path.dirname(__file__)
version_file = os.path.join(here, 'src/iptools/__init__.py')
d = {}
execfile(version_file, d)
version = d['__version__']
setup(
name = 'iptools',
version = version,
description = 'Python utilites for manipulating IP addresses',
long_description = "Utilities for manipulating IP addresses including a class that can be used to include CIDR network blocks in Django's INTERNAL_IPS setting.",
url = 'http://python-iptools.googlecode.com',
download_url = '',
author = 'Bryan Davis',
author_email = 'casadebender+iptools@gmail.com',
license = 'BSD',
platforms = ['any',],
package_dir = {'': 'src'},
packages = find_packages('src'),
include_package_data = True,
test_suite='iptools.test_iptools',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Utilities',
'Topic :: Internet',
],
zip_safe=False,
)
|
#!/usr/bin/env python
from ez_setup import use_setuptools
use_setuptools()
import os
from setuptools import setup, find_packages
here = os.path.dirname(__file__)
version_file = os.path.join(here, 'src/iptools/__init__.py')
d = {}
execfile(version_file, d)
version = d['__version__']
setup(
name = 'iptools',
version = version,
description = 'Python utilites for manipulating IP addresses',
long_description = "Utilities for manipulating IP addresses including a class that can be used to include CIDR network blocks in Django's INTERNAL_IPS setting.",
url = 'http://python-iptools.googlecode.com',
download_url = '',
author = 'Bryan Davis',
author_email = 'casadebender+iptools@gmail.com',
license = 'BSD',
platforms = ['any',],
package_dir = {'': 'src'},
packages = find_packages('src'),
include_package_data = True,
test_suite='iptools.test_iptools',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Utilities',
'Topic :: Internet',
],
zip_safe=False,
)
|
Add message when email already exist
|
Template.register.events({
'submit #register-form': function(e, t) {
e.preventDefault();
var isValidPassword = function(val, field) {
if (val.length >= 6) {
return true;
} else {
return false;
}
}
var trimInput = function(val) {
return val.replace(/^\s*|\s*$/g, "");
}
var email = trimInput(t.find('#account-email').value),
password = t.find('#account-password').value;
if (isValidPassword(password)) {
Accounts.createUser({
email: email,
password: password
}, function(err) {
if (err) {
console.log(err);
DisplayErrorSubmit(err.reason);
// Inform the user that account creation failed
} else {
// Success. Account has been created and the user
// has logged in successfully.
Router.go('/home');
}
});
} else {
DisplayErrorSubmit("Invalid password");
}
return false;
}
});
|
Template.register.events({
'submit #register-form': function(e, t) {
e.preventDefault();
var isValidPassword = function(val, field) {
if (val.length >= 6) {
return true;
} else {
return false;
}
}
var trimInput = function(val) {
return val.replace(/^\s*|\s*$/g, "");
}
var email = trimInput(t.find('#account-email').value),
password = t.find('#account-password').value;
if (isValidPassword(password)) {
Accounts.createUser({
email: email,
password: password
}, function(err) {
if (err) {
// Inform the user that account creation failed
} else {
// Success. Account has been created and the user
// has logged in successfully.
Router.go('/home');
}
});
} else {
DisplayErrorSubmit("Invalid password");
}
return false;
}
});
|
Fix test failure on Python 2
|
import copy
import pkg_resources
from rwt import deps
def test_entry_points():
"""
Ensure entry points are visible after making packages visible
"""
with deps.on_sys_path('jaraco.mongodb'):
eps = pkg_resources.iter_entry_points('pytest11')
assert list(eps), "Entry points not found"
class TestInstallCheck:
def test_installed(self):
assert deps.pkg_installed('rwt')
def test_not_installed(self):
assert not deps.pkg_installed('not_a_package')
def test_installed_version(self):
assert not deps.pkg_installed('rwt==0.0')
def test_not_installed_args(self):
args = [
'-i', 'https://devpi.net',
'-r', 'requirements.txt',
'rwt',
'not_a_package',
'rwt==0.0',
]
expected = copy.copy(args)
expected.remove('rwt')
filtered = deps.not_installed(args)
assert list(filtered) == expected
|
import pkg_resources
from rwt import deps
def test_entry_points():
"""
Ensure entry points are visible after making packages visible
"""
with deps.on_sys_path('jaraco.mongodb'):
eps = pkg_resources.iter_entry_points('pytest11')
assert list(eps), "Entry points not found"
class TestInstallCheck:
def test_installed(self):
assert deps.pkg_installed('rwt')
def test_not_installed(self):
assert not deps.pkg_installed('not_a_package')
def test_installed_version(self):
assert not deps.pkg_installed('rwt==0.0')
def test_not_installed_args(self):
args = [
'-i', 'https://devpi.net',
'-r', 'requirements.txt',
'rwt',
'not_a_package',
'rwt==0.0',
]
expected = args.copy()
expected.remove('rwt')
filtered = deps.not_installed(args)
assert list(filtered) == expected
|
Simplify _getHostURL using Ternary operator
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
function _getHostURL(url) {
const host = url.match(/^(?:https?\:\/\/)(?:[^\/])+/);
return (host) ? host[0] : null;
}
function _addToCommaString(item, commaString) {
if (!item) {
return commaString;
}
if (!commaString) {
return item;
} else {
let arr = _arrayFromCommaString(commaString);
arr.push(item);
//remove any duplicates from the array
arr = [...new Set(arr)];
return arr.join(',');
}
}
function _arrayFromCommaString(commaString) {
return (commaString) ? commaString.replace(' ', '').split(',') : [];
}
module.exports = {
'getHostURL': _getHostURL,
'addToCommaString': _addToCommaString,
'arrayFromCommaString': _arrayFromCommaString
};
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
function _getHostURL(url) {
const host = url.match(/^(?:https?\:\/\/)(?:[^\/])+/);
if (host) {
return host[0];
}
return null;
}
function _addToCommaString(item, commaString) {
if (!item) {
return commaString;
}
if (!commaString) {
return item;
} else {
let arr = _arrayFromCommaString(commaString);
arr.push(item);
//remove any duplicates from the array
arr = [...new Set(arr)];
return arr.join(',');
}
}
function _arrayFromCommaString(commaString) {
return (commaString) ? commaString.replace(' ', '').split(',') : [];
}
module.exports = {
'getHostURL': _getHostURL,
'addToCommaString': _addToCommaString,
'arrayFromCommaString': _arrayFromCommaString
};
|
Add FLX to the release train
|
#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# See https://github.com/domokit/sky_engine/wiki/Release-process
import os
import subprocess
import sys
def main():
engine_root = os.path.abspath('.')
if not os.path.exists(os.path.join(engine_root, 'sky')):
print "Cannot find //sky. Is %s the Flutter engine repository?" % engine_root
return 1
pub_path = os.path.join(engine_root, 'third_party/dart-sdk/dart-sdk/bin/pub')
if args.publish:
subprocess.check_call([pub_path, 'publish', '--force'], cwd=os.path.join(engine_root, 'sky/packages/sky'))
subprocess.check_call([pub_path, 'publish', '--force'], cwd=os.path.join(engine_root, 'sky/packages/flx'))
subprocess.check_call([pub_path, 'publish', '--force'], cwd=os.path.join(engine_root, 'skysprites'))
if __name__ == '__main__':
sys.exit(main())
|
#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# See https://github.com/domokit/sky_engine/wiki/Release-process
import os
import subprocess
import sys
def main():
engine_root = os.path.abspath('.')
if not os.path.exists(os.path.join(engine_root, 'sky')):
print "Cannot find //sky. Is %s the Flutter engine repository?" % engine_root
return 1
pub_path = os.path.join(engine_root, 'third_party/dart-sdk/dart-sdk/bin/pub')
if args.publish:
subprocess.check_call([pub_path, 'publish', '--force'], cwd=os.path.join(engine_root, 'sky/packages/sky'))
subprocess.check_call([pub_path, 'publish', '--force'], cwd=os.path.join(engine_root, 'skysprites'))
if __name__ == '__main__':
sys.exit(main())
|
Adjust Javadoc for the exception.
|
/*
* Copyright 2015, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.lang;
import org.spine3.Event;
/**
* This exception is thrown on a discovery of an event class, which is not handled by any of
* the applier methods of an aggregate root class.
*
* @author Mikhail Melnik
*/
public class MissingEventApplierException extends RuntimeException {
public MissingEventApplierException(Event event) {
super("There is no registered applier for the event: " + event.getEventClass());
}
private static final long serialVersionUID = 0L;
}
|
/*
* Copyright 2015, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.lang;
import org.spine3.Event;
/**
* Exception that is thrown when unsupported event is obtained
* or in case there is no class for given Protobuf event message.
*
* @author Mikhail Melnik
*/
public class MissingEventApplierException extends RuntimeException {
public MissingEventApplierException(Event event) {
super("There is no registered applier for the event: " + event.getEventClass());
}
private static final long serialVersionUID = 0L;
}
|
Fix orthographic camera usage of the glViewport method
|
'use strict';
let gl = require('./gl');
let glm = require('gl-matrix');
let mat4 = glm.mat4;
let Camera = require('./Camera');
const _name = 'orthographic.camera';
const _left = -1;
const _bottom = -1;
const _near = 0.1;
const _far = 1;
class OrthographicCamera extends Camera
{
constructor({ name = _name, path, uniforms, background, left = _left, right, bottom = _bottom, top, near = _near, far = _far } = {})
{
super({ name, path, uniforms, background });
this.left = left;
this.right = right;
this.bottom = bottom;
this.top = top;
this.near = near;
this.far = far;
this.inheritance = ['Entity', 'Structure', 'Camera', 'OrthographicCamera'];
this.configure();
}
configure()
{
super.configure();
mat4.ortho(this.projectionMatrix, this.left, this.right, this.bottom, this.top, this.near, this.far);
mat4.identity(this.modelViewMatrix);
}
bind(program)
{
super.bind(program);
gl.disable(gl.DEPTH_TEST);
gl.viewport(0, 0, this.right, this.top);
}
}
module.exports = OrthographicCamera;
|
'use strict';
let gl = require('./gl');
let glm = require('gl-matrix');
let mat4 = glm.mat4;
let Camera = require('./Camera');
const _name = 'orthographic.camera';
const _left = -1;
const _top = -1;
const _near = 0.1;
const _far = 1;
class OrthographicCamera extends Camera
{
constructor({ name = _name, path, uniforms, background, left = _left, right, bottom, top = _top, near = _near, far = _far } = {})
{
super({ name, path, uniforms, background });
this.left = left;
this.right = right;
this.bottom = bottom;
this.top = top;
this.near = near;
this.far = far;
this.inheritance = ['Entity', 'Structure', 'Camera', 'OrthographicCamera'];
this.configure();
}
configure()
{
super.configure();
mat4.ortho(this.projectionMatrix, this.left, this.right, this.bottom, this.top, this.near, this.far);
mat4.identity(this.modelViewMatrix);
}
bind(program)
{
super.bind(program);
gl.disable(gl.DEPTH_TEST);
gl.viewport(this.left, this.top, this.right, this.bottom);
}
}
module.exports = OrthographicCamera;
|
Add test to check gear value
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
line = " 0:00 InitGame: \g_matchmode\1\g_gametype\7\g_allowvote\536871039\g_gear\KQ\mapname\ut4_dust2_v2\gamename\q3urt43\g_survivor\0\auth\0\g_modversion\4.3.4"
def test_initgame():
tmp = line.split()
assert tmp[1] == "InitGame:"
def test_mod43():
ret_val = 40
if "g_modversion\4.3" in line:
ret_val = 43
assert ret_val == 43
def test_mod42():
ret_val = 40
if "g_modversion\4.2" in line:
ret_val = 42
assert ret_val == 40
def test_ffa_gametype():
ret_val = None
if "g_gametype\0" in line:
ret_val = "FFA"
assert ret_val != "FFA"
def test_ctf_gametype():
ret_val = "FFA"
if "g_gametype\7" in line:
ret_val = "CTF"
assert ret_val == "CTF"
def test_gear_value():
gear = line.split('g_gear\\')[-1].split('\\')[0] if 'g_gear\\' in line else "%s" % ''
assert gear == "KQ"
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
line = " 0:00 InitGame: \g_matchmode\1\g_gametype\7\g_allowvote\536871039\g_gear\KQ\mapname\ut4_dust2_v2\gamename\q3urt43\g_survivor\0\auth\0\g_modversion\4.3.4"
def test_initgame():
tmp = line.split()
assert tmp[1] == "InitGame:"
def test_mod43():
ret_val = 40
if "g_modversion\4.3" in line:
ret_val = 43
assert ret_val == 43
def test_mod42():
ret_val = 40
if "g_modversion\4.2" in line:
ret_val = 42
assert ret_val == 40
def test_ffa_gametype():
ret_val = None
if "g_gametype\0" in line:
ret_val = "FFA"
assert ret_val != "FFA"
def test_ctf_gametype():
ret_val = "FFA"
if "g_gametype\7" in line:
ret_val = "CTF"
assert ret_val == "CTF"
|
Update the Portuguese example test
|
# Portuguese Language Test - Python 3 Only!
from seleniumbase.translate.portuguese import CasoDeTeste
class MinhaClasseDeTeste(CasoDeTeste):
def test_exemplo_1(self):
self.abrir_url("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
self.verificar_elemento('[title="Língua portuguesa"]')
self.atualizar_texto("#searchInput", "Rio de Janeiro")
self.clique("#searchButton")
self.verificar_texto("Rio de Janeiro", "#firstHeading")
self.verificar_elemento('img[alt*="edifícios"]')
self.atualizar_texto("#searchInput", "São Paulo")
self.clique("#searchButton")
self.verificar_texto("São Paulo", "h1#firstHeading")
self.verificar_elemento('img[src*="Monumento"]')
self.voltar()
self.verificar_verdade("Rio" in self.obter_url_atual())
self.atualizar_texto("#searchInput", "Florianópolis\n")
self.verificar_texto("Florianópolis", "h1#firstHeading")
self.verificar_elemento('img[alt*="Avenida Beira Mar"]')
|
# Portuguese Language Test - Python 3 Only!
from seleniumbase.translate.portuguese import CasoDeTeste
class MinhaClasseDeTeste(CasoDeTeste):
def test_exemplo_1(self):
self.abrir_url("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
self.verificar_elemento('[title="Visitar a página principal"]')
self.atualizar_texto("#searchInput", "Rio de Janeiro")
self.clique("#searchButton")
self.verificar_texto("Rio de Janeiro", "#firstHeading")
self.verificar_elemento('img[alt*="edifícios"]')
self.atualizar_texto("#searchInput", "São Paulo")
self.clique("#searchButton")
self.verificar_texto("São Paulo", "#firstHeading")
self.verificar_elemento('img[src*="Monumento"]')
self.voltar()
self.verificar_verdade("Janeiro" in self.obter_url_atual())
self.avançar() # noqa
self.verificar_verdade("Paulo" in self.obter_url_atual())
|
[tests/traffic] Fix tests for module traffic
|
import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_minwidth_str(self):
# default value (two digits after dot)
self.assertEqual(self.module.get_minwidth_str(), "1000.00KiB/s")
# integer value
self.module._format = "{:.0f}"
self.assertEqual(self.module.get_minwidth_str(), "1000KiB/s")
# just one digit after dot
self.module._format = "{:.1f}"
self.assertEqual(self.module.get_minwidth_str(), "1000.0KiB/s")
|
import mock
import unittest
import tests.mocks as mocks
from bumblebee.modules.traffic import Module
class TestTrafficModule(unittest.TestCase):
def setUp(self):
mocks.setup_test(self, Module)
def test_default_format(self):
self.assertEqual(self.module._format, "{:.2f}")
def test_get_minwidth_str(self):
# default value (two digits after dot)
self.assertEqual(self.module.get_minwidth_str(), "1000.00MB")
# integer value
self.module._format = "{:.0f}"
self.assertEqual(self.module.get_minwidth_str(), "1000MB")
# just one digit after dot
self.module._format = "{:.1f}"
self.assertEqual(self.module.get_minwidth_str(), "1000.0MB")
|
Switch to more visible touchablehighlight
|
import React, {
Component,
PropTypes,
} from 'react';
import {
TouchableHighlight,
View,
Text,
} from 'react-native';
import { add1Action } from './actions';
import styles from './styles';
import Random from './components/Random';
class Home extends Component {
static contextTypes = {
store: PropTypes.object,
};
handlePress = () => {
const {
dispatch,
} = this.context.store;
const action = add1Action(50);
if (action) {
dispatch(action);
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native
</Text>
<Text style={styles.instructions}>
To get started, edit index.*.js
</Text>
<Random />
<TouchableHighlight onPress={this.handlePress}>
<Text>{'Dispatch worker action'}</Text>
</TouchableHighlight>
</View>
);
}
}
export default Home;
|
import React, {
Component,
PropTypes,
} from 'react';
import {
Button,
View,
Text,
} from 'react-native';
import { add1Action } from './actions';
import styles from './styles';
import Random from './components/Random';
class Home extends Component {
static contextTypes = {
store: PropTypes.object,
};
handlePress = () => {
const {
dispatch,
} = this.context.store;
const action = add1Action(50);
if (action) {
dispatch(action);
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native
</Text>
<Text style={styles.instructions}>
To get started, edit index.*.js
</Text>
<Random />
<Button onPress={this.handlePress}>Dispatch worker action</Button>
</View>
);
}
}
export default Home;
|
Fix for ckeditor in dev
|
var CKEDITOR_BASEPATH = '/assets/ckeditor/';
CKEDITOR.config.ignoreEmptyParagraph = false;
CKEDITOR.config.allowedContent = true;
CKEDITOR.config.baseHref = '/assets/ckeditor/';
CKEDITOR.config.height = 400;
CKEDITOR.config.width = '95.5%';
CKEDITOR.config.toolbarStartupExpanded = false;
CKEDITOR.config.toolbarGroups = [
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ] },
{ name: 'links' },
{ name: 'insert' },
'/',
{ name: 'styles' },
{ name: 'colors' },
{ name: 'tools' },
{ name: 'others' }
];
|
CKEDITOR.config.ignoreEmptyParagraph = false;
CKEDITOR.config.allowedContent = true;
CKEDITOR.config.baseHref = '/assets/ckeditor/';
CKEDITOR.config.height = 400;
CKEDITOR.config.width = '95.5%';
CKEDITOR.config.toolbarStartupExpanded = false;
CKEDITOR.config.toolbarGroups = [
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ] },
{ name: 'links' },
{ name: 'insert' },
'/',
{ name: 'styles' },
{ name: 'colors' },
{ name: 'tools' },
{ name: 'others' }
];
|
Update test for GOVUK Frontend libraries parity
|
import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.14.0") == govuk_frontend_version
correct_govuk_frontend_jinja_version = Version("1.5.1") == govuk_frontend_jinja_version
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
|
import json
from importlib import metadata
from packaging.version import Version
def test_govuk_frontend_jinja_overrides_on_design_system_v3():
with open("package.json") as package_file:
package_json = json.load(package_file)
govuk_frontend_version = Version(package_json["dependencies"]["govuk-frontend"])
govuk_frontend_jinja_version = Version(metadata.version("govuk-frontend-jinja"))
# This should be checking govuk_frontend_version == 3.14.x, but we're not there yet. Update this when we are.
# Compatibility between these two libs is defined at https://github.com/LandRegistry/govuk-frontend-jinja/
correct_govuk_frontend_version = Version("3.0.0") <= govuk_frontend_version < Version("4.0.0")
correct_govuk_frontend_jinja_version = Version("1.5.0") <= govuk_frontend_jinja_version < Version("1.6.0")
assert correct_govuk_frontend_version and correct_govuk_frontend_jinja_version, (
"After upgrading either of the Design System packages, you must validate that "
"`app/templates/govuk_frontend_jinja_overrides/templates/components/*/template.html`"
"are all structurally-correct and up-to-date macros. If not, update the macros or retire them and update the "
"rendering process."
)
|
Improve code and remove line feed from host RegEx
|
(function() {
var __WS_send = WebSocket.prototype.send;
window.__WS_send = WebSocket.prototype.send;
WebSocket.prototype.send = function(data) {
var websocketURL = this.url;
console.log(websocketURL);
try {
var agarBaseURL = 'http://agar.io/?sip=';
var agarConnectedHost = /[^:\/]+\.agar\.io/.exec(websocketURL);
console.log(agarBaseURL + agarConnectedHost[0]);
} 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 domain = /([^:\/\n]+)\.*agar\.io/.exec(this.url);
console.log("http://agar.io/?sip=" + domain[0]);
} 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;
}
}
})();
|
Add fallback to no-icon so icons will show issues
|
import Ractive from "ractive";
import "../../static/fontawesome/js/fontawesome.js";
import "../../static/fontawesome/js/packs/brands.js";
import "../../static/fontawesome/js/packs/light.js";
import Templates from "../Templates.js";
var Icon = Ractive.extend( {
"template": Templates.getComponent( "Icon" ),
data(){
return {
"icon": "no-icon",
"type": "light"
};
},
"computed": {
weight(){
var type = this.get( "type" );
var weights = {
"light": "fal",
"brand": "fab"
};
var weight = "fal";
if( weights[ type ] ){
weight = weights[ type ];
}
return weight;
}
}
} );
export default Icon;
|
import Ractive from "ractive";
import "../../static/fontawesome/js/fontawesome.js";
import "../../static/fontawesome/js/packs/brands.js";
import "../../static/fontawesome/js/packs/light.js";
import Templates from "../Templates.js";
var Icon = Ractive.extend( {
"template": Templates.getComponent( "Icon" ),
data(){
return {
"icon": "",
"type": "light"
};
},
"computed": {
weight(){
var type = this.get( "type" );
var weights = {
"light": "fal",
"brand": "fab"
};
var weight = "fal";
if( weights[ type ] ){
weight = weights[ type ];
}
return weight;
}
}
} );
export default Icon;
|
Fix to parse 'now+1y' becase FormValue has already unescaped
|
package handler
import (
"net/http"
"net/url"
"time"
"github.com/yuuki/dynamond/log"
"github.com/yuuki/dynamond/timeparser"
)
const (
DAYTIME = time.Duration(24 * 60 * 60) * time.Second
)
func Render(w http.ResponseWriter, r *http.Request) {
until := time.Now()
from := until.Add(-DAYTIME)
if v := r.FormValue("from"); v != "" {
t, err := timeparser.ParseAtTime(url.QueryEscape(v))
if err != nil {
BadRequest(w, err.Error())
return
}
from = t
}
if v := r.FormValue("until"); v != "" {
t, err := timeparser.ParseAtTime(url.QueryEscape(v))
if err != nil {
BadRequest(w, err.Error())
return
}
until = t
}
log.Debugf("from:%d until:%d", from.Unix(), until.Unix())
return
}
|
package handler
import (
"net/http"
"time"
"github.com/yuuki/dynamond/log"
"github.com/yuuki/dynamond/timeparser"
)
const (
DAYTIME = time.Duration(24 * 60 * 60) * time.Second
)
func Render(w http.ResponseWriter, r *http.Request) {
until := time.Now()
from := until.Add(-DAYTIME)
if v := r.FormValue("from"); v != "" {
t, err := timeparser.ParseAtTime(v)
if err != nil {
BadRequest(w, err.Error())
return
}
from = t
}
if v := r.FormValue("until"); v != "" {
t, err := timeparser.ParseAtTime(v)
if err != nil {
BadRequest(w, err.Error())
return
}
until = t
}
log.Debugf("from:%d until:%d", from.Unix(), until.Unix())
return
}
|
Fix NPE when exporting JDO using maven plugin
|
/*
* Copyright 2012, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.query.maven;
import javax.jdo.annotations.EmbeddedOnly;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.persistence.Embedded;
import com.mysema.query.codegen.GenericExporter;
/**
* JDOExporterMojo calls the GenericExporter tool using the classpath of the module
*
* @goal jdo-export
* @requiresDependencyResolution test
* @author tiwe
*/
public class JDOExporterMojo extends AbstractExporterMojo {
@Override
protected void configure(GenericExporter exporter) {
exporter.setEmbeddableAnnotation(EmbeddedOnly.class);
exporter.setEmbeddedAnnotation(Embedded.class);
exporter.setEntityAnnotation(PersistenceCapable.class);
exporter.setSkipAnnotation(NotPersistent.class);
}
}
|
/*
* Copyright 2012, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.query.maven;
import javax.jdo.annotations.EmbeddedOnly;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.persistence.Embedded;
import com.mysema.query.codegen.GenericExporter;
/**
* JDOExporterMojo calls the GenericExporter tool using the classpath of the module
*
* @goal jdo-export
* @requiresDependencyResolution test
* @author tiwe
*/
public class JDOExporterMojo extends AbstractExporterMojo {
@Override
protected void configure(GenericExporter exporter) {
exporter.setEmbeddableAnnotation(EmbeddedOnly.class);
exporter.setEmbeddedAnnotation(Embedded.class);
exporter.setEntityAnnotation(PersistenceCapable.class);
exporter.setSkipAnnotation(NotPersistent.class);
exporter.setSupertypeAnnotation(null);
}
}
|
Add "last" property to enable the calling application to get the file path of the last loaded config file
|
"use strict";
var use = require("alamid-plugin/use.js");
var path = require("path"),
argv = require("minimist")(process.argv.slice(2));
function dynamicConfig(basePath, fileName) {
var env = dynamicConfig.getEnv(),
filePath = dynamicConfig.getFilePath(basePath, env, fileName),
config;
if (dynamicConfig.options.log) {
console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'");
}
config = dynamicConfig.loadConfig(filePath);
dynamicConfig.last = filePath;
return config;
}
dynamicConfig.getEnv = function() {
return argv.env || argv.ENV || process.env.env || dynamicConfig.options.defaultEnv;
};
dynamicConfig.getFilePath = function(basePath, env, fileName) {
return path.join(basePath, env, fileName);
};
dynamicConfig.loadConfig = function(filePath) {
var config;
try {
config = require(filePath);
}
catch (err) {
//handle only not found errors, throw the rest
if (err.code === "MODULE_NOT_FOUND") {
throw new Error("Config not found at '" + filePath + "'");
}
throw err;
}
return config;
};
dynamicConfig.options = {
defaultEnv: "develop",
log: false
};
dynamicConfig.use = use;
module.exports = dynamicConfig;
|
"use strict";
var use = require("alamid-plugin/use.js");
var path = require("path"),
argv = require("minimist")(process.argv.slice(2));
function dynamicConfig(basePath, fileName) {
var env = dynamicConfig.getEnv(),
filePath = dynamicConfig.getFilePath(basePath, env, fileName),
config;
if (dynamicConfig.options.log) {
console.log("Loading configuration '" + fileName + "' from path '" + filePath + "'");
}
config = dynamicConfig.loadConfig(filePath);
return config;
}
dynamicConfig.getEnv = function() {
return argv.env || argv.ENV || process.env.env || dynamicConfig.options.defaultEnv;
};
dynamicConfig.getFilePath = function(basePath, env, fileName) {
return path.join(basePath, env, fileName);
};
dynamicConfig.loadConfig = function(filePath) {
var config;
try {
config = require(filePath);
}
catch (err) {
//handle only not found errors, throw the rest
if (err.code === "MODULE_NOT_FOUND") {
throw new Error("Config not found at '" + filePath + "'");
}
throw err;
}
return config;
};
dynamicConfig.options = {
defaultEnv: "develop",
log: false
};
dynamicConfig.use = use;
module.exports = dynamicConfig;
|
Allow transition to exit route
Fixes issue where clicking the "Exit"
button on the exp-thank-you frame would
redirect to the 'participate.survey.index'
route, where the beforeModel hook would
then redirect to the consent form.
|
import Ember from 'ember';
export default Ember.Route.extend({
setupController(controller, session) {
this._super(controller, session);
controller.set('experiment', this.controllerFor('participate.survey').get('experiment'));
controller.set('session', session);
controller.set('pastSessions', []);
},
actions: {
willTransition(transition) {
this._super(transition);
if (transition.targetName === 'participate.survey.results' || transition.targetName === 'exit') {
return true;
}
var frameIndex = this.controllerFor('participate.survey.index').get('frameIndex');
var framePage = this.controllerFor('participate.survey.index').get('framePage');
if (frameIndex !== 0) {
this.replaceWith('participate.survey.index');
// Disable back button in qsort page 2, and rating-form page 1
if (!(frameIndex === 2 && framePage === 1) && frameIndex !== 3) {
this.controllerFor('participate.survey.index').set('frameIndex', frameIndex - 1);
}
// Update pages within the rating-form
if (frameIndex === 3 && framePage !== 0) {
this.controllerFor('participate.survey.index').set('framePage', framePage - 1);
}
}
}
}
});
|
import Ember from 'ember';
export default Ember.Route.extend({
setupController(controller, session) {
this._super(controller, session);
controller.set('experiment', this.controllerFor('participate.survey').get('experiment'));
controller.set('session', session);
controller.set('pastSessions', []);
},
actions: {
willTransition(transition) {
this._super(transition);
if (transition.targetName === 'participate.survey.results') {
return true;
}
var frameIndex = this.controllerFor('participate.survey.index').get('frameIndex');
var framePage = this.controllerFor('participate.survey.index').get('framePage');
if (frameIndex !== 0) {
this.replaceWith('participate.survey.index');
// Disable back button in qsort page 2, and rating-form page 1
if (!(frameIndex === 2 && framePage === 1) && frameIndex !== 3) {
this.controllerFor('participate.survey.index').set('frameIndex', frameIndex - 1);
}
// Update pages within the rating-form
if (frameIndex === 3 && framePage !== 0) {
this.controllerFor('participate.survey.index').set('framePage', framePage - 1);
}
}
}
}
});
|
Test delegation of options parsing
|
import test from 'tape'
import chunkify from './index'
import ChunkifyOptions from './options'
import sinon from 'sinon'
let spy_ChunkifyOptions_of = (callback) => {
let spy = sinon.spy(ChunkifyOptions, 'of');
callback(spy);
ChunkifyOptions.of.restore()
};
test('should require an array', t => {
t.throws(() => {
chunkify.array()
}, /Usage: chunkify.array\(Array array, Function fn, \[Object] options\) - bad array/);
t.end()
});
test('should require a function', t => {
t.throws(() => {
chunkify.array([])
}, /Usage: chunkify.array\(Array array, Function fn, \[Object] options\) - bad fn/);
t.end()
});
test('should delegate options deserialization', t => {
let options = {};
spy_ChunkifyOptions_of((chunkify_options) => {
chunkify.array([], function() {}, options);
t.ok(chunkify_options.calledWith(options));
});
t.end()
});
test.skip('should return a promise', t => {
});
test.skip('should not invoke fn when given an empty array', t => {
});
test.skip('should invoke fn successively between "chunk" iterations', t => {
});
test.skip('should yield after "chunk" iterations', t => {
});
test.skip('should start again after yielding in "delay" milliseconds', t => {
});
test.skip('should resolve with the array after processing completes', t => {
});
test.skip('should reject the promise if an error is thrown', t => {
});
test.skip('should not yield after "chunk" iterations if processing is complete', t => {
});
|
import test from 'tape'
import chunkify from './index'
test('should require an array', t => {
t.throws(() => {
chunkify.array()
}, /Usage: chunkify.array\(Array array, Function fn, \[Object] options\) - bad array/);
t.end()
});
test('should require a function', t => {
t.throws(() => {
chunkify.array([])
}, /Usage: chunkify.array\(Array array, Function fn, \[Object] options\) - bad fn/);
t.end()
});
test.skip('should delegate options deserialization', t => {
});
test.skip('should return a promise', t => {
});
test.skip('should not invoke fn when given an empty array', t => {
});
test.skip('should invoke fn successively between "chunk" iterations', t => {
});
test.skip('should yield after "chunk" iterations', t => {
});
test.skip('should start again after yielding in "delay" milliseconds', t => {
});
test.skip('should resolve with the array after processing completes', t => {
});
test.skip('should reject the promise if an error is thrown', t => {
});
test.skip('should not yield after "chunk" iterations if processing is complete', t => {
});
|
Fix for encoding bug during installation on Windows
|
from setuptools import setup, find_packages
from jamo import __version__
import sys
if sys.version_info <= (3, 0):
print("ERROR: jamo requires Python 3.0 or later "
"(bleeding edge preferred)", file=sys.stderr)
sys.exit(1)
with open('README.rst', encoding='utf8') as f:
long_description = f.read()
setup(
name="jamo",
version=__version__,
description="A Hangul syllable and jamo analyzer.",
long_description=long_description,
url="https://github.com/jdong820/python-jamo",
author="Joshua Dong",
author_email="jdong42@gmail.com",
license="http://www.apache.org/licenses/LICENSE-2.0",
classifiers=[
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
],
keywords="Korean Hangul jamo syllable nlp",
packages=find_packages(),
package_dir={'jamo': 'jamo'},
package_data={'jamo': ['data/*.json']},
)
|
from setuptools import setup, find_packages
from jamo import __version__
import sys
if sys.version_info <= (3, 0):
print("ERROR: jamo requires Python 3.0 or later "
"(bleeding edge preferred)", file=sys.stderr)
sys.exit(1)
with open('README.rst') as f:
long_description = f.read()
setup(
name="jamo",
version=__version__,
description="A Hangul syllable and jamo analyzer.",
long_description=long_description,
url="https://github.com/jdong820/python-jamo",
author="Joshua Dong",
author_email="jdong42@gmail.com",
license="http://www.apache.org/licenses/LICENSE-2.0",
classifiers=[
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
],
keywords="Korean Hangul jamo syllable nlp",
packages=find_packages(),
package_dir={'jamo': 'jamo'},
package_data={'jamo': ['data/*.json']},
)
|
Update stable channel builders to pull from 1.3
Review URL: https://codereview.chromium.org/225263024
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@262391 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + name
self.category_postfix = category_postfix
self.name = name
self.position = position
self.priority = priority
self.all_deps_path = '/' + branch + '/deps/all.deps'
self.standalone_deps_path = '/' + branch + '/deps/standalone.deps'
self.dartium_deps_path = '/' + branch + '/deps/dartium.deps'
# The channel names are replicated in the slave.cfg files for all
# dart waterfalls. If you change anything here please also change it there.
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 4),
Channel('dev', 'trunk', 1, '-dev', 2),
Channel('stable', 'branches/1.3', 2, '-stable', 1),
Channel('integration', 'branches/dartium_integration', 3, '-integration', 3),
]
CHANNELS_BY_NAME = {}
for c in CHANNELS:
CHANNELS_BY_NAME[c.name] = c
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + name
self.category_postfix = category_postfix
self.name = name
self.position = position
self.priority = priority
self.all_deps_path = '/' + branch + '/deps/all.deps'
self.standalone_deps_path = '/' + branch + '/deps/standalone.deps'
self.dartium_deps_path = '/' + branch + '/deps/dartium.deps'
# The channel names are replicated in the slave.cfg files for all
# dart waterfalls. If you change anything here please also change it there.
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 4),
Channel('dev', 'trunk', 1, '-dev', 2),
Channel('stable', 'branches/1.2', 2, '-stable', 1),
Channel('integration', 'branches/dartium_integration', 3, '-integration', 3),
]
CHANNELS_BY_NAME = {}
for c in CHANNELS:
CHANNELS_BY_NAME[c.name] = c
|
Fix bug where only PDF files in current directory can be found
|
"""Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
)
parser.add_argument(
'directory',
metavar='PATH',
type=str,
help='path to a directory'
)
def width_greater_than_height(page):
box = page.mediaBox
return box.getWidth() > box.getHeight()
if __name__ == '__main__':
args = parser.parse_args()
directory = args.directory
all_pdf_files = [os.path.join(directory, filename) for filename in all_pdf_files_in_directory(directory)]
opened_files = map(lambda path: open(path, 'rb'), all_pdf_files)
all_pages = concat_pdf_pages(opened_files)
for idx, pages in enumerate(split_on_condition(all_pages, predicate=width_greater_than_height), start=1):
pdf_writer = PdfFileWriter()
map(pdf_writer.addPage, pages)
output_filename = '{0:05}.pdf'.format(idx)
with open(output_filename, 'wb') as output_file:
pdf_writer.write(output_file)
output_file.flush()
os.fsync(output_file.fileno())
map(lambda f: f.close, opened_files)
|
"""Main Module of PDF Splitter"""
import argparse
import os
from PyPDF2 import PdfFileWriter
from Util import all_pdf_files_in_directory, split_on_condition, concat_pdf_pages
parser = \
argparse.ArgumentParser(
description='Split all the pages of multiple PDF files in a directory by document number'
)
parser.add_argument(
'directory',
metavar='PATH',
type=str,
help='path to a directory'
)
def width_greater_than_height(page):
box = page.mediaBox
return box.getWidth() > box.getHeight()
if __name__ == '__main__':
args = parser.parse_args()
all_pdf_files = all_pdf_files_in_directory(args.directory)
opened_files = map(lambda path: open(path, 'rb'), all_pdf_files)
all_pages = concat_pdf_pages(opened_files)
for idx, pages in enumerate(split_on_condition(all_pages, predicate=width_greater_than_height), start=1):
pdf_writer = PdfFileWriter()
map(pdf_writer.addPage, pages)
output_filename = '{0:05}.pdf'.format(idx)
with open(output_filename, 'wb') as output_file:
pdf_writer.write(output_file)
output_file.flush()
os.fsync(output_file.fileno())
map(lambda f: f.close, opened_files)
|
Update dancer's nginx.conf to find new test root
|
import subprocess
import sys
import setup_util
from os.path import expanduser
import os
import getpass
def start(args, logfile, errfile):
setup_util.replace_text("dancer/app.pl", "localhost", args.database_host)
setup_util.replace_text("dancer/nginx.conf", "USR", getpass.getuser())
setup_util.replace_text("dancer/nginx.conf", "server unix:.*\/FrameworkBenchmarks/dancer", "server unix:" + args.troot)
try:
subprocess.Popen("plackup -E production -s Starman --workers=" + str(args.max_threads) + " -l $TROOT/frameworks-benchmark.sock -a ./app.pl", shell=True, cwd="dancer", stderr=errfile, stdout=logfile)
subprocess.check_call("sudo /usr/local/nginx/sbin/nginx -c $TROOT/nginx.conf", shell=True, stderr=errfile, stdout=logfile)
return 0
except subprocess.CalledProcessError:
return 1
def stop(logfile, errfile):
try:
subprocess.call("sudo /usr/local/nginx/sbin/nginx -s stop", shell=True)
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'starman' in line:
pid = int(line.split(None, 2)[1])
os.kill(pid, 15)
return 0
except subprocess.CalledProcessError:
return 1
|
import subprocess
import sys
import setup_util
from os.path import expanduser
import os
import getpass
def start(args, logfile, errfile):
setup_util.replace_text("dancer/app.pl", "localhost", args.database_host)
setup_util.replace_text("dancer/nginx.conf", "USR", getpass.getuser())
setup_util.replace_text("dancer/nginx.conf", "server unix:.*\/FrameworkBenchmarks", "server unix:" + args.fwroot)
try:
subprocess.Popen("plackup -E production -s Starman --workers=" + str(args.max_threads) + " -l $TROOT/frameworks-benchmark.sock -a ./app.pl", shell=True, cwd="dancer", stderr=errfile, stdout=logfile)
subprocess.check_call("sudo /usr/local/nginx/sbin/nginx -c $TROOT/nginx.conf", shell=True, stderr=errfile, stdout=logfile)
return 0
except subprocess.CalledProcessError:
return 1
def stop(logfile, errfile):
try:
subprocess.call("sudo /usr/local/nginx/sbin/nginx -s stop", shell=True)
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'starman' in line:
pid = int(line.split(None, 2)[1])
os.kill(pid, 15)
return 0
except subprocess.CalledProcessError:
return 1
|
Update dropdown menu tests to use enzyme.
|
/* Copyright (C) 2017 Canonical Ltd. */
'use strict';
const React = require('react');
const enzyme = require('enzyme');
const DropdownMenu = require('./dropdown-menu');
describe('Dropdown Menu', function() {
const renderComponent = (options = {}) => enzyme.shallow(
<DropdownMenu.WrappedComponent
handleClickOutside={options.handleClickOutside || sinon.stub()}>
{options.children}
</DropdownMenu.WrappedComponent>
);
it('can render', () => {
const wrapper = renderComponent({
children: <li>child</li>
});
const expected = (
<ul className="dropdown-menu__list">
<li>child</li>
</ul>
);
assert.compareJSX(wrapper.find('.dropdown-menu__list'), expected);
});
});
|
/* Copyright (C) 2017 Canonical Ltd. */
'use strict';
const React = require('react');
const DropdownMenu = require('./dropdown-menu');
const Panel = require('../panel/panel');
const jsTestUtils = require('../../utils/component-test-utils');
describe('Dropdown Menu', function() {
function renderComponent(options={}) {
return jsTestUtils.shallowRender(
<DropdownMenu.WrappedComponent
handleClickOutside={options.handleClickOutside}>
{options.children}
</DropdownMenu.WrappedComponent>, true);
}
it('can render', () => {
const handleClickOutside = sinon.stub();
const renderer = renderComponent({
children: <li>child</li>,
handleClickOutside: handleClickOutside
});
const output = renderer.getRenderOutput();
const expected = (
<Panel instanceName="dropdown-menu" visible={true}>
<ul className="dropdown-menu__list">
<li>child</li>
</ul>
</Panel>
);
expect(output).toEqualJSX(expected);
});
});
|
Use $location.url() instead of $location.path() to remove url params.
|
"use strict";
angular.module("hikeio").
factory("navigation", ["$location", function($location) {
var NavigationService = function() {
};
NavigationService.prototype.toSearch = function(query) {
$location.url("/search?q=" + query);
};
NavigationService.prototype.toIndex = function() {
return $location.url("/");
};
NavigationService.prototype.onIndex = function() {
return $location.path() === "/";
};
NavigationService.prototype.toEntry = function(id) {
$location.url("/hikes/" + id);
};
NavigationService.prototype.onEntry = function() {
var regex = /\/hikes\/(?!.*\/edit$)/;
return regex.test($location.path());
};
NavigationService.prototype.onEntryEdit = function() {
var regex = /\/hikes\/.*?\/edit/;
return regex.test($location.path());
};
return new NavigationService();
}]);
|
"use strict";
angular.module("hikeio").
factory("navigation", ["$location", function($location) {
var NavigationService = function() {
};
NavigationService.prototype.toSearch = function(query) {
$location.url("/search?q=" + query);
};
NavigationService.prototype.toIndex = function() {
return $location.path("/");
};
NavigationService.prototype.onIndex = function() {
return $location.path() === "/";
};
NavigationService.prototype.toEntry = function(id) {
$location.path("/hikes/" + id);
};
NavigationService.prototype.onEntry = function() {
var regex = /\/hikes\/(?!.*\/edit$)/;
return regex.test($location.path());
};
NavigationService.prototype.onEntryEdit = function() {
var regex = /\/hikes\/.*?\/edit/;
return regex.test($location.path());
};
return new NavigationService();
}]);
|
Remove version bounds for elasticsearch dependency
|
from setuptools import setup, find_packages
setup(
name="elasticmagic",
version="0.0.0a0",
author="Alexander Koval",
author_email="kovalidis@gmail.com",
description=("Python orm for elasticsearch."),
license="Apache License 2.0",
keywords="elasticsearch dsl",
url="https://github.com/anti-social/elasticmagic",
packages=find_packages(exclude=["tests"]),
install_requires=[
"elasticsearch",
"python-dateutil",
],
extras_require={
"geo": [
"python-geohash",
],
"async": [
"elasticsearch-py-async",
],
},
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
from setuptools import setup, find_packages
setup(
name="elasticmagic",
version="0.0.0a0",
author="Alexander Koval",
author_email="kovalidis@gmail.com",
description=("Python orm for elasticsearch."),
license="Apache License 2.0",
keywords="elasticsearch dsl",
url="https://github.com/anti-social/elasticmagic",
packages=find_packages(exclude=["tests"]),
install_requires=[
"elasticsearch>=6.0.0,<8.0",
"python-dateutil",
],
extras_require={
"geo": [
"python-geohash",
],
"async": [
"elasticsearch-py-async",
],
},
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
|
Switch the blog handler over to POST
Makes the Discourse webhook actually work right.
|
// Copyright © 2017 Michael Howell. All rights reserved.
// The following code is covered by the AGPL-3.0 license.
const selfapi = require('selfapi');
const blog = require('../lib/blog');
const log = require('../lib/log');
// API resource to manage Janitor's Discourse-backed news section.
const blogAPI = module.exports = selfapi({
title: 'Blog'
});
blogAPI.post('/synchronize', {
title: 'Synchronize Blog',
description: 'Pull the blog section from Discourse.',
handler: async (_request, response) => {
try {
const { count } = await blog.synchronize();
log('synchronized blog', { count });
response.json({ count }, null, 2);
} catch (error) {
log('[fail] synchronized blog', error);
response.statusCode = 500; // Internal Server Error
response.json({ error: 'Could not synchronize' }, null, 2);
}
},
examples: [{
response: {
body: JSON.stringify({ count: 13 }, null, 2)
}
}]
});
|
// Copyright © 2017 Michael Howell. All rights reserved.
// The following code is covered by the AGPL-3.0 license.
const selfapi = require('selfapi');
const blog = require('../lib/blog');
const log = require('../lib/log');
// API resource to manage Janitor's Discourse-backed news section.
const blogAPI = module.exports = selfapi({
title: 'Blog'
});
blogAPI.get('/synchronize', {
title: 'Synchronize Blog',
description: 'Pull the blog section from Discourse.',
handler: async (_request, response) => {
try {
const { count } = await blog.synchronize();
log('synchronized blog', { count });
response.json({ count }, null, 2);
} catch (error) {
log('[fail] synchronized blog', error);
response.statusCode = 500; // Internal Server Error
response.json({ error: 'Could not synchronize' }, null, 2);
}
},
examples: [{
response: {
body: JSON.stringify({ count: 1 }, null, 2)
}
}]
});
|
Fix callback parameter as optional
|
"use strict";
var utils = require("../utils");
var log = require("npmlog");
module.exports = function(defaultFuncs, api, ctx) {
return function changeThreadEmoji(emoji, threadID, callback) {
if(!callback) {
callback = function() {};
}
var form = {
'emoji_choice' : emoji,
'thread_or_other_fbid' : threadID
};
defaultFuncs
.post("https://www.messenger.com/messaging/save_thread_emoji/?source=thread_settings&__pc=EXP1%3Amessengerdotcom_pkg", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx.jar, defaultFuncs))
.then(function(resData) {
if (resData.error === 1357031) {
throw {error: "Trying to change emoji of a chat that doesn't exist. Have at least one message in the thread before trying to change the emoji."};
}
if (resData.error) {
throw resData;
}
return callback();
})
.catch(function(err) {
log.error("Error in changeThreadEmoji", err);
return callback(err);
});
};
};
|
"use strict";
var utils = require("../utils");
var log = require("npmlog");
module.exports = function(defaultFuncs, api, ctx) {
return function changeThreadEmoji(emoji, threadID, callback) {
var form = {
'emoji_choice' : emoji,
'thread_or_other_fbid' : threadID
};
defaultFuncs
.post("https://www.messenger.com/messaging/save_thread_emoji/?source=thread_settings&__pc=EXP1%3Amessengerdotcom_pkg", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx.jar, defaultFuncs))
.then(function(resData) {
if (resData.error === 1357031) {
throw {error: "Trying to change emoji of a chat that doesn't exist. Have at least one message in the thread before trying to change the emoji."};
}
if (resData.error) {
throw resData;
}
return callback();
})
.catch(function(err) {
log.error("Error in changeThreadEmoji", err);
return callback(err);
});
};
};
|
Remove isRequired from header propTypes
|
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import Loader from '../Loader';
import './Header.scss';
export const Header = ({ isFetching }) => (
<div>
<nav className='navbar navbar-inverse container-fluid'>
<Link to='/' className='brand-title navbar-brand'>Tiedonohjausjärjestelmä Alpha v0.1.4</Link>
</nav>
{isFetching &&
<Loader />
}
</div>
);
Header.propTypes = {
isFetching: React.PropTypes.bool
};
const mapStateToProps = (state) => {
return {
isFetching: state.home.isFetching || state.navigation.isFetching || state.selectedTOS.isFetching
};
};
export default connect(mapStateToProps)(Header);
|
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import Loader from '../Loader';
import './Header.scss';
export const Header = ({ isFetching }) => (
<div>
<nav className='navbar navbar-inverse container-fluid'>
<Link to='/' className='brand-title navbar-brand'>Tiedonohjausjärjestelmä Alpha v0.1.4</Link>
</nav>
{isFetching &&
<Loader />
}
</div>
);
Header.propTypes = {
isFetching: React.PropTypes.bool.isRequired
};
const mapStateToProps = (state) => {
return {
isFetching: state.home.isFetching || state.navigation.isFetching || state.selectedTOS.isFetching
};
};
export default connect(mapStateToProps)(Header);
|
Correct project requirements (sklearn -> scikit-learn)
|
# coding: utf-8
from setuptools import setup, find_packages
import tom_lib
__author__ = "Adrien Guille, Pavel Soriano"
__email__ = "adrien.guille@univ-lyon2.fr"
version = tom_lib.__version__
setup(
name='tom_lib',
version=version,
packages=find_packages(),
author="Adrien Guille, Pavel Soriano",
author_email="adrien.guille@univ-lyon2.fr",
description="A library for topic modeling and browsing",
long_description=open('README.rst').read(),
url='http://mediamining.univ-lyon2.fr/people/guille/tom.php',
download_url='http://pypi.python.org/packages/source/t/tom_lib/tom_lib-%s.tar.gz' % version,
classifiers=[
'Programming Language :: Python',
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
"Operating System :: OS Independent",
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering',
'Topic :: Text Processing'
], requires=['nltk', 'scikit-learn', 'networkx', 'pandas', 'scipy', 'gensim', 'numpy'])
|
# coding: utf-8
from setuptools import setup, find_packages
import tom_lib
__author__ = "Adrien Guille, Pavel Soriano"
__email__ = "adrien.guille@univ-lyon2.fr"
version = tom_lib.__version__
setup(
name='tom_lib',
version=version,
packages=find_packages(),
author="Adrien Guille, Pavel Soriano",
author_email="adrien.guille@univ-lyon2.fr",
description="A library for topic modeling and browsing",
long_description=open('README.rst').read(),
url='http://mediamining.univ-lyon2.fr/people/guille/tom.php',
download_url='http://pypi.python.org/packages/source/t/tom_lib/tom_lib-%s.tar.gz' % version,
classifiers=[
'Programming Language :: Python',
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Research',
"Operating System :: OS Independent",
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering',
'Topic :: Text Processing'
], requires=['nltk', 'sklearn', 'networkx', 'pandas', 'scipy', 'gensim', 'numpy'])
|
Update StringIO import for Python3 compat
|
# USEFUL FUNCTIONS DESIGNED FOR TESTS ##############################################################
import glob
import os
import uuid
from PIL import Image
from django.core.files.base import ContentFile
from django.utils import six
def new_test_image():
"""
Creates an automatically generated test image.
In your testing `tearDown` method make sure to delete the test
image with the helper function `delete_test_image`.
The recommended way of using this helper function is as follows:
object_1.image_property.save(*new_test_image())
:return: Image name and image content file.
"""
image_name = 'test-{}.png'.format(uuid.uuid4())
image_buf = six.StringIO()
image = Image.new('RGBA', size=(50, 50), color=(256, 0, 0))
image.save(image_buf, 'png')
image_buf.seek(0)
return image_name, ContentFile(image_buf.read(), image_name)
def delete_test_image(image_field):
"""
Deletes test image generated as well as thumbnails if created.
The recommended way of using this helper function is as follows:
delete_test_image(object_1.image_property)
:param image_field: The image field on an object.
:return: None.
"""
# ensure all thumbs are deleted
for filename in glob.glob(
os.path.join('public', 'media', 'thumbs', image_field.name) + '*'):
os.unlink(filename)
# delete the saved file
image_field.delete()
|
# USEFUL FUNCTIONS DESIGNED FOR TESTS ##############################################################
import glob
import os
import uuid
from django.core.files.base import ContentFile
from PIL import Image
from StringIO import StringIO
def new_test_image():
"""
Creates an automatically generated test image.
In your testing `tearDown` method make sure to delete the test
image with the helper function `delete_test_image`.
The recommended way of using this helper function is as follows:
object_1.image_property.save(*new_test_image())
:return: Image name and image content file.
"""
image_name = 'test-{}.png'.format(uuid.uuid4())
image_buf = StringIO()
image = Image.new('RGBA', size=(50, 50), color=(256, 0, 0))
image.save(image_buf, 'png')
image_buf.seek(0)
return image_name, ContentFile(image_buf.read(), image_name)
def delete_test_image(image_field):
"""
Deletes test image generated as well as thumbnails if created.
The recommended way of using this helper function is as follows:
delete_test_image(object_1.image_property)
:param image_field: The image field on an object.
:return: None.
"""
# ensure all thumbs are deleted
for filename in glob.glob(
os.path.join('public', 'media', 'thumbs', image_field.name) + '*'):
os.unlink(filename)
# delete the saved file
image_field.delete()
|
Use small tdb in wikipedia example
|
import traildb.*;
import java.io.FileNotFoundException;
public class Wikipedia {
public static long SESSION_LIMIT = 30 * 60;
public static void sessions(TrailDB tdb) {
TrailDBCursor cursor = tdb.cursorNew();
long n = tdb.numTrails();
long totalSessions = 0;
long totalEvents = 0;
for (long i = 0; i < n; i++) {
TrailDBEvent event;
cursor.getTrail(i);
event = cursor.next();
long prevTime = event.timestamp;
long numSessions = 1;
long numEvents = 1;
while ((event = cursor.next()) != null) {
if (event.timestamp - prevTime > SESSION_LIMIT)
numSessions++;
prevTime = event.timestamp;
numEvents++;
}
totalSessions += numSessions;
totalEvents += numEvents;
}
System.out.println("Trails: " + n + "Sessions: " + totalSessions + " Events: " + totalEvents);
}
public static void main(String[] args) throws FileNotFoundException {
TrailDB tdb = new TrailDB("wikipedia-history-small.tdb");
sessions(tdb);
}
}
|
import traildb.*;
import java.io.FileNotFoundException;
public class Wikipedia {
public static long SESSION_LIMIT = 3600;
public static void sessions(TrailDB tdb) {
TrailDBCursor cursor = tdb.cursorNew();
long n = tdb.numTrails();
long totalSessions = 0;
long totalEvents = 0;
for (long i = 0; i < n; i++) {
TrailDBEvent event;
cursor.getTrail(i);
event = cursor.next();
long prevTime = event.timestamp;
long numSessions = 1;
long numEvents = 1;
while ((event = cursor.next()) != null) {
if (event.timestamp - prevTime > SESSION_LIMIT)
numSessions++;
prevTime = event.timestamp;
numEvents++;
}
totalSessions += numSessions;
totalEvents += numEvents;
}
System.out.println("Trails: " + n + "Sessions: " + totalSessions + " Events: " + totalEvents);
}
public static void main(String[] args) throws FileNotFoundException {
TrailDB tdb = new TrailDB("wikipedia-history.tdb");
sessions(tdb);
}
}
|
Fix bug to only store the 30 most recent points
|
import pymodm
import slugify
class DevicePlot(pymodm.MongoModel):
device_name = pymodm.fields.CharField()
slug = pymodm.fields.CharField()
plot_title = pymodm.fields.CharField()
x_label = pymodm.fields.CharField()
y_label = pymodm.fields.CharField()
def save(self, *args, **kwargs):
if not self.pk:
self.slug = slugify.slugify(self.device_name)
super(DevicePlot, self).save(*args, **kwargs)
class PlotPoints(pymodm.MongoModel):
device_plot = pymodm.fields.ReferenceField(DevicePlot)
label = pymodm.fields.CharField()
points = pymodm.fields.ListField(default=[])
def save(self, *args, **kwargs):
# TODO: configurable setting...
if len(self.points) >= 30:
self.points = self.points[-30:]
super(PlotPoints, self).save(*args, **kwargs)
|
import pymodm
import slugify
class DevicePlot(pymodm.MongoModel):
device_name = pymodm.fields.CharField()
slug = pymodm.fields.CharField()
plot_title = pymodm.fields.CharField()
x_label = pymodm.fields.CharField()
y_label = pymodm.fields.CharField()
def save(self, *args, **kwargs):
if not self.pk:
self.slug = slugify.slugify(self.device_name)
super(DevicePlot, self).save(*args, **kwargs)
class PlotPoints(pymodm.MongoModel):
device_plot = pymodm.fields.ReferenceField(DevicePlot)
label = pymodm.fields.CharField()
points = pymodm.fields.ListField(default=[])
def save(self, *args, **kwargs):
# TODO: configurable setting...
if len(self.points) >= 30:
self.points = self.points[30:]
super(PlotPoints, self).save(*args, **kwargs)
|
Fix ClearCommand Unit Test Failing
|
package guitests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ClearCommandTest extends TaskManagerGuiTest {
@Test
public void clear() {
System.out.println(taskListPanel.getTask(4));
//verify a non-empty list can be cleared
assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
assertClearCommandSuccess();
//verify other commands can work after a clear command
commandBox.runCommand(td.getFit.getAddCommand());
assertTrue(taskListPanel.isListMatching(td.getFit));
commandBox.runCommand("delete 1");
assertListSize(0);
//verify clear command works when the list is empty
assertClearCommandSuccess();
}
private void assertClearCommandSuccess() {
commandBox.runCommand("clear");
assertListSize(0);
assertResultMessage("All tasks has been cleared!");
}
}
|
package guitests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ClearCommandTest extends TaskManagerGuiTest {
@Test
public void clear() {
//verify a non-empty list can be cleared
assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
assertClearCommandSuccess();
//verify other commands can work after a clear command
commandBox.runCommand(td.getFit.getAddCommand());
assertTrue(taskListPanel.isListMatching(td.getFit));
commandBox.runCommand("delete 1");
assertListSize(0);
//verify clear command works when the list is empty
assertClearCommandSuccess();
}
private void assertClearCommandSuccess() {
commandBox.runCommand("clear");
assertListSize(0);
assertResultMessage("All tasks has been cleared!");
}
}
|
Migrate to new Storage API
for Django 1.8
|
"""
A storage implementation that overwrites exiting files in the storage
See "Writing a custom storage system"
(https://docs.djangoproject.com/en/1.3/howto/custom-file-storage/) and
the discussion on stackoverflow on "ImageField overwrite image file"
(http://stackoverflow.com/questions/9522759/imagefield-overwrite-image-file)
"""
import os.path
from django.core.files.storage import FileSystemStorage
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name, max_length=None):
return name
def _save(self, name, content):
full_path = self.path(name)
# make sure an existing file is replaced by removing the
# original file first
if os.path.exists(full_path):
os.remove(full_path)
return super(OverwriteStorage, self)._save(name, content)
|
"""
A storage implementation that overwrites exiting files in the storage
See "Writing a custom storage system"
(https://docs.djangoproject.com/en/1.3/howto/custom-file-storage/) and
the discussion on stackoverflow on "ImageField overwrite image file"
(http://stackoverflow.com/questions/9522759/imagefield-overwrite-image-file)
"""
import os.path
from django.core.files.storage import FileSystemStorage
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name):
return name
def _save(self, name, content):
full_path = self.path(name)
# make sure an existing file is replaced by removing the
# original file first
if os.path.exists(full_path):
os.remove(full_path)
return super(OverwriteStorage, self)._save(name, content)
|
[tasks] Allow to modify the is_default flag
|
from zou.app.models.task_status import TaskStatus
from zou.app.services import tasks_service
from .base import BaseModelResource, BaseModelsResource
class TaskStatusesResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, TaskStatus)
def check_read_permissions(self):
return True
def post_creation(self, instance):
tasks_service.clear_task_status_cache(str(instance.id))
return instance.serialize()
class TaskStatusResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, TaskStatus)
def check_read_permissions(self, instance):
return True
def pre_update(self, instance_dict, data):
if data.get("is_default", False):
status = TaskStatus.get_by(is_default=True)
status.update({"is_default": None})
return instance_dict
def post_update(self, instance_dict):
tasks_service.clear_task_status_cache(instance_dict["id"])
return instance_dict
def post_delete(self, instance_dict):
tasks_service.clear_task_status_cache(instance_dict["id"])
return instance_dict
|
from zou.app.models.task_status import TaskStatus
from zou.app.services import tasks_service
from .base import BaseModelResource, BaseModelsResource
class TaskStatusesResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, TaskStatus)
def check_read_permissions(self):
return True
def post_creation(self, instance):
tasks_service.clear_task_status_cache(str(instance.id))
return instance.serialize()
class TaskStatusResource(BaseModelResource):
def __init__(self):
BaseModelResource.__init__(self, TaskStatus)
def check_read_permissions(self, instance):
return True
def post_update(self, instance_dict):
tasks_service.clear_task_status_cache(instance_dict["id"])
return instance_dict
def post_delete(self, instance_dict):
tasks_service.clear_task_status_cache(instance_dict["id"])
return instance_dict
|
Revert "Revert "Reduce the time we keep expired remotes sessions and fix comment""
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import java.time.Duration;
/**
* Removes inactive sessions
* <p>
* Note: Unit test is in ApplicationRepositoryTest
*
* @author hmusum
*/
public class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
// Start this maintainer immediately. It frees disk space, so if disk goes full and config server
// restarts this makes sure that cleanup will happen as early as possible
super(applicationRepository, curator, Duration.ZERO, interval);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
protected void maintain() {
applicationRepository.deleteExpiredLocalSessions();
// Expired remote sessions are sessions that belong to an application that have external deployments that
// are no longer active
if (hostedVespa) {
Duration expiryTime = Duration.ofDays(7);
applicationRepository.deleteExpiredRemoteSessions(expiryTime);
}
}
}
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;
import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import java.time.Duration;
/**
* Removes inactive sessions
* <p>
* Note: Unit test is in ApplicationRepositoryTest
*
* @author hmusum
*/
public class SessionsMaintainer extends ConfigServerMaintainer {
private final boolean hostedVespa;
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
// Start this maintainer immediately. It frees disk space, so if disk goes full and config server
// restarts this makes sure that cleanup will happen as early as possible
super(applicationRepository, curator, Duration.ZERO, interval);
this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
@Override
protected void maintain() {
applicationRepository.deleteExpiredLocalSessions();
// Expired remote sessions are not expected to exist, they should have been deleted when
// a deployment happened or when the application was deleted. We still see them from time to time,
// probably due to some race or another bug
if (hostedVespa) {
Duration expiryTime = Duration.ofDays(30);
applicationRepository.deleteExpiredRemoteSessions(expiryTime);
}
}
}
|
Fix first path check on builder helpers
|
/**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. 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. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
var fs = require('fs');
var path = require('path');
var root = path.join(__dirname, 'aws-sdk');
if (!fs.existsSync(root)) {
root = path.join(__dirname, '..', 'lib');
}
root = path.normalize(root);
module.exports = {
root: root,
mainFile: path.join(root, 'aws.js'),
defaultServices: 'dynamodb,s3,sts'
};
|
/**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. 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. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.
*/
var fs = require('fs');
var path = require('path');
var root = path.join(__dirname, 'lib');
if (!fs.existsSync(root)) {
root = path.join(__dirname, '..', 'lib');
}
root = path.normalize(root);
module.exports = {
root: root,
mainFile: path.join(root, 'aws.js'),
defaultServices: 'dynamodb,s3,sts'
};
|
Disable pull-to-refresh and overscroll glow
|
import React from 'react'
import ReactDOM from 'react-dom'
import { createGlobalStyle } from 'styled-components'
import { App } from './App'
import woff2 from './fonts/source-sans-pro-v11-latin-regular.woff2'
import woff from './fonts/source-sans-pro-v11-latin-regular.woff'
import registerServiceWorker from './registerServiceWorker'
const GlobalStyle = createGlobalStyle`
body {
margin: 0;
padding: 0;
font-family: 'Source Sans Pro', sans-serif;
overscroll-behavior-y: none;
}
/* source-sans-pro-regular - latin */
@font-face {
font-family: 'Source Sans Pro';
font-style: normal;
font-weight: 400;
font-display: optional;
src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'),
url(${woff2}) format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
url(${woff}) format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}
`
ReactDOM.render(
<>
<GlobalStyle />
<App />
</>,
document.getElementById('root')
)
registerServiceWorker()
|
import React from 'react'
import ReactDOM from 'react-dom'
import { createGlobalStyle } from 'styled-components'
import { App } from './App'
import woff2 from './fonts/source-sans-pro-v11-latin-regular.woff2'
import woff from './fonts/source-sans-pro-v11-latin-regular.woff'
import registerServiceWorker from './registerServiceWorker'
const GlobalStyle = createGlobalStyle`
body {
margin: 0;
padding: 0;
font-family: 'Source Sans Pro', sans-serif;
}
/* source-sans-pro-regular - latin */
@font-face {
font-family: 'Source Sans Pro';
font-style: normal;
font-weight: 400;
font-display: optional;
src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'),
url(${woff2}) format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */
url(${woff}) format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
}
`
ReactDOM.render(
<>
<GlobalStyle />
<App />
</>,
document.getElementById('root')
)
registerServiceWorker()
|
Update numpy array of tuples with np version
|
# Numpy converts a list of tuples *not* into an array of tuples, but into a 2D
# array instead.
import numpy as np # 1.11.1
list_of_tuples = [(1, 2), (3, 4)]
print('list of tuples:', list_of_tuples, 'type:', type(list_of_tuples))
A = np.array(list_of_tuples)
print('numpy array of tuples:', A, 'type:', type(A))
# It makes computing unique rows trickier than it should:
unique_A, indices_to_A = np.unique(list_of_tuples, return_inverse=True)
print('naive numpy unique:', unique_A, 'and indices:', indices_to_A) # WRONG!
# Workaround to do np.unique by row (http://stackoverflow.com/a/8024764/3438463)
A_by_row = np.empty(len(list_of_tuples), object)
A_by_row[:] = list_of_tuples
unique_A, indices_to_A = np.unique(A_by_row, return_inverse=True)
print('unique tuples:', unique_A, 'and indices:', indices_to_A)
|
# Numpy converts a list of tuples *not* into an array of tuples, but into a 2D
# array instead.
list_of_tuples = [(1, 2), (3, 4)]
import numpy as np
print('list of tuples:', list_of_tuples, 'type:', type(list_of_tuples))
A = np.array(list_of_tuples)
print('numpy array of tuples:', A, 'type:', type(A))
# It makes computing unique rows trickier than it should:
unique_A, indices_to_A = np.unique(list_of_tuples, return_inverse=True)
print('naive numpy unique:', unique_A, 'and indices:', indices_to_A) # WRONG!
# Workaround to do np.unique by row (http://stackoverflow.com/a/8024764/3438463)
A_by_row = np.empty(len(list_of_tuples), object)
A_by_row[:] = list_of_tuples
unique_A, indices_to_A = np.unique(A_by_row, return_inverse=True)
print('unique tuples:', unique_A, 'and indices:', indices_to_A)
|
Append slash to urls in example project
|
# Django settings for example_project project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'example_project.sqlite3',
}
}
SITE_ID = 1
SECRET_KEY = 'u%38dln@$1!7w#cxi4np504^sa3_skv5aekad)jy_u0v2mc+nr'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
APPEND_SLASH = True
ROOT_URLCONF = 'example_project.urls'
STATIC_URL = '/static/'
DJANGO_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
)
THIRD_PARTY_APPS = (
'embed_video',
)
LOCAL_APPS = (
'example_project',
'posts',
)
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
|
# Django settings for example_project project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'example_project.sqlite3',
}
}
SITE_ID = 1
SECRET_KEY = 'u%38dln@$1!7w#cxi4np504^sa3_skv5aekad)jy_u0v2mc+nr'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
ROOT_URLCONF = 'example_project.urls'
STATIC_URL = '/static/'
DJANGO_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
)
THIRD_PARTY_APPS = (
'embed_video',
)
LOCAL_APPS = (
'example_project',
'posts',
)
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
|
[NEW] Remove cart line can redirect to referer
|
<?php
class order_RemoveCartLineAction extends f_action_BaseAction
{
/**
* @param Context $context
* @param Request $request
*/
public function _execute($context, $request)
{
$cartService = order_CartService::getInstance();
$cart = $cartService->getDocumentInstanceFromSession();
$cartLineIndex = $request->getParameter('cartLineIndex');
if (!f_util_StringUtils::isEmpty($cartLineIndex) && !is_null($cart))
{
$cartService->removeLine($cart, $cartLineIndex);
$cartService->refresh($cart);
}
$pageId = $request->getParameter('pageref', null);
if (is_numeric($pageId))
{
$url = LinkHelper::getDocumentUrl(DocumentHelper::getDocumentInstance($pageId, 'modules_website/page'));
}
else
{
$url = $_SERVER['HTTP_REFERER'];
}
$context->getController()->redirectToUrl(str_replace('&', '&', $url));
return View::NONE;
}
/**
* @return boolean
*/
public function isSecure()
{
return false;
}
}
|
<?php
class order_RemoveCartLineAction extends f_action_BaseAction
{
/**
* @param Context $context
* @param Request $request
*/
public function _execute($context, $request)
{
$cartService = order_CartService::getInstance();
$cart = $cartService->getDocumentInstanceFromSession();
$cartLineIndex = $request->getParameter('cartLineIndex');
if (!f_util_StringUtils::isEmpty($cartLineIndex) && !is_null($cart))
{
$cartService->removeLine($cart, $cartLineIndex);
$cartService->refresh($cart);
}
$pageId = $request->getParameter('pageref', null);
$url = null;
if (is_numeric($pageId))
{
$url = LinkHelper::getDocumentUrl(DocumentHelper::getDocumentInstance($pageId, 'modules_website/page'));
}
$context->getController()->redirectToUrl(str_replace('&', '&', $url));
return View::NONE;
}
/**
* @return boolean
*/
public function isSecure()
{
return false;
}
}
|
Fix NullPointerException when restoring backup
|
package com.benny.openlauncher.widget;
import android.content.Context;
import android.support.v7.preference.PreferenceCategory;
import android.support.v7.preference.PreferenceViewHolder;
import android.util.AttributeSet;
import android.widget.TextView;
import com.benny.openlauncher.util.AppSettings;
public class ColorPreferenceCategory extends PreferenceCategory {
public ColorPreferenceCategory(Context context) {
super(context);
}
public ColorPreferenceCategory(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ColorPreferenceCategory(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onBindViewHolder(PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
TextView titleView = (TextView) holder.findViewById(android.R.id.title);
titleView.setTextColor(AppSettings.get().getPrimaryColor());
}
}
|
package com.benny.openlauncher.widget;
import android.content.Context;
import android.support.v7.preference.PreferenceCategory;
import android.support.v7.preference.PreferenceViewHolder;
import android.util.AttributeSet;
import android.widget.TextView;
import com.benny.openlauncher.manager.Setup;
public class ColorPreferenceCategory extends PreferenceCategory {
public ColorPreferenceCategory(Context context) {
super(context);
}
public ColorPreferenceCategory(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ColorPreferenceCategory(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onBindViewHolder(PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
TextView titleView = (TextView) holder.findViewById(android.R.id.title);
titleView.setTextColor(Setup.appSettings().getPrimaryColor());
}
}
|
Fix read articles by tag test
|
<?php
namespace Tests\Feature;
use Tests\IntegrationTestCase;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ReadArticlesByTagTest extends IntegrationTestCase
{
use DatabaseMigrations;
protected $article;
protected $tag;
public function setUp()
{
parent::setUp();
$this->article = factory('App\Article')->create();
$this->tag = factory('App\Tag')->create();
$this->article->tags()->attach($this->tag);
}
/** @test */
public function a_user_can_view_all_articles_with_tag()
{
$response = $this->get('/tag/' . $this->tag->name);
$response->assertSee($this->article->title);
}
}
|
<?php
namespace Tests\Feature;
use Tests\IntegrationTestCase;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ReadArticlesByTagTest extends IntegrationTestCase
{
use DatabaseMigrations;
protected $article;
protected $tag;
public function setUp()
{
parent::setUp();
$this->article = factory('App\Article')->create();
$this->tag = factory('App\Tag')->create();
$this->article->tags()->attach($this->tag);
}
/** @test */
public function a_user_can_view_all_articles_with_tag()
{
$response = $this->get('/tags/' . $this->tag->name);
$response->assertSee($this->article->title);
}
}
|
Fix property access mistake
Bootstrapping should work now
|
<?php
namespace Herzen\Admission\Orm;
use \Doctrine\ORM\Tools\Setup;
use \Doctrine\ORM\EntityManager;
abstract class Bootstrapper {
protected static $em;
public static function getEntityManager() {
return self::$em;
}
public static function bootstrap($connectionFile) {
$libRoot = __DIR__;
// Create a simple "default" Doctrine ORM configuration for Annotations
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration(array($libRoot), $isDevMode);
// mysql
// database configuration parameters
$conn = require_once $connectionFile;
// obtaining the entity manager
self::$em = EntityManager::create($conn, $config);
}
}
|
<?php
namespace Herzen\Admission\Orm;
use \Doctrine\ORM\Tools\Setup;
use \Doctrine\ORM\EntityManager;
abstract class Bootstrapper {
protected static $em;
public static function getEntityManager() {
return self::$em;
}
protected static function bootstrap($connectionFile) {
$libRoot = __DIR__;
// Create a simple "default" Doctrine ORM configuration for Annotations
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration(array($libRoot), $isDevMode);
// mysql
// database configuration parameters
$conn = require_once self::$connectionFile;
// obtaining the entity manager
self::$em = EntityManager::create($conn, $config);
}
}
|
Add a class to past stops for styling purposes
|
import Ember from 'ember';
import moment from 'moment';
import stringToHue from 'bus-detective/utils/string-to-hue';
var inject = Ember.inject;
export default Ember.Component.extend({
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
classNames: ['rt-arrival'],
classNameBindings: ['isPast:rt-arrival--past'],
timeFromNow: Ember.computed('clock.time', function() {
return moment(this.get('arrival.time')).fromNow();
}),
isPast: Ember.computed('clock.time', function() {
return new Date(this.get('arrival.time')) < new Date();
}),
style: Ember.computed('arrival.route_id', function() {
var hue = stringToHue(this.get('arrival.route_id').toString());
return `color: hsl(${hue}, 60%, 25%);
background-color: hsl(${hue}, 40%, 95%);
border-color: hsl(${hue}, 40%, 80%);`;
})
});
|
import Ember from 'ember';
import moment from 'moment';
import stringToHue from 'bus-detective/utils/string-to-hue';
var inject = Ember.inject;
export default Ember.Component.extend({
tagName: 'li',
clock: inject.service(),
attributeBindings: ['style'],
classNames: ['rt-arrival'],
timeFromNow: Ember.computed('clock.time', function() {
return moment(this.get('arrival.time')).fromNow();
}),
style: Ember.computed('arrival.route_id', function() {
var hue = stringToHue(this.get('arrival.route_id').toString());
return `color: hsl(${hue}, 60%, 25%);
background-color: hsl(${hue}, 40%, 95%);
border-color: hsl(${hue}, 40%, 80%);`;
})
});
|
Add more default args so tests pass in py3+
|
from __future__ import unicode_literals
from argparse import Namespace
import mock
import pytest
from kafka_utils.kafka_cluster_manager.cluster_info \
.partition_count_balancer import PartitionCountBalancer
from kafka_utils.kafka_cluster_manager.cmds import decommission
from tests.kafka_cluster_manager.helper import broker_range
@pytest.fixture
def command_instance():
cmd = decommission.DecommissionCmd()
cmd.args = mock.Mock(spec=Namespace)
cmd.args.force_progress = False
cmd.args.broker_ids = []
cmd.args.auto_max_movement_size = True
cmd.args.max_partition_movements = 10
cmd.args.max_leader_changes = 10
return cmd
def test_decommission_no_partitions_to_move(command_instance, create_cluster_topology):
cluster_one_broker_empty = create_cluster_topology(
assignment={('topic', 0): [0, 1]},
brokers=broker_range(3),
)
command_instance.args.brokers_ids = [2]
balancer = PartitionCountBalancer(cluster_one_broker_empty, command_instance.args)
command_instance.run_command(cluster_one_broker_empty, balancer)
|
from __future__ import unicode_literals
from argparse import Namespace
import mock
import pytest
from kafka_utils.kafka_cluster_manager.cluster_info \
.partition_count_balancer import PartitionCountBalancer
from kafka_utils.kafka_cluster_manager.cmds import decommission
from tests.kafka_cluster_manager.helper import broker_range
@pytest.fixture
def command_instance():
cmd = decommission.DecommissionCmd()
cmd.args = mock.Mock(spec=Namespace)
cmd.args.force_progress = False
cmd.args.broker_ids = []
cmd.args.auto_max_movement_size = True
return cmd
def test_decommission_no_partitions_to_move(command_instance, create_cluster_topology):
cluster_one_broker_empty = create_cluster_topology(
assignment={('topic', 0): [0, 1]},
brokers=broker_range(3),
)
command_instance.args.brokers_ids = [2]
balancer = PartitionCountBalancer(cluster_one_broker_empty, command_instance.args)
command_instance.run_command(cluster_one_broker_empty, balancer)
|
Fix for not setting Gofig config dirs (Rebased)
This patch was originally commit
d04023572e47e5c18fa549fe7f7de301e8470c63, but it failed to build in CI
as it was not rebased off of master prior to being merged. This is the
rebased patch.
This patch fixes the issue where the Gofig's global (/etc) and user
($HOME) directories were not set, resulting in the default config files
not being loaded.
|
package core
import (
"fmt"
"github.com/akutz/gofig"
"github.com/akutz/gotil"
"github.com/emccode/rexray/util"
)
func init() {
initDrivers()
gofig.SetGlobalConfigPath(util.EtcDirPath())
gofig.SetUserConfigPath(fmt.Sprintf("%s/.rexray", gotil.HomeDir()))
gofig.Register(globalRegistration())
gofig.Register(driverRegistration())
}
func globalRegistration() *gofig.Registration {
r := gofig.NewRegistration("Global")
r.Yaml(`
rexray:
host: tcp://:7979
logLevel: warn
`)
r.Key(gofig.String, "h", "tcp://:7979",
"The REX-Ray host", "rexray.host")
r.Key(gofig.String, "l", "warn",
"The log level (error, warn, info, debug)", "rexray.logLevel")
return r
}
func driverRegistration() *gofig.Registration {
r := gofig.NewRegistration("Driver")
r.Yaml(`
rexray:
osDrivers:
- linux
storageDrivers:
- libstorage
volumeDrivers:
- docker
`)
r.Key(gofig.String, "", "linux",
"The OS drivers to consider", "rexray.osDrivers")
r.Key(gofig.String, "", "",
"The storage drivers to consider", "rexray.storageDrivers")
r.Key(gofig.String, "", "docker",
"The volume drivers to consider", "rexray.volumeDrivers")
return r
}
|
package core
import (
"github.com/akutz/gofig"
)
func init() {
initDrivers()
gofig.Register(globalRegistration())
gofig.Register(driverRegistration())
}
func globalRegistration() *gofig.Registration {
r := gofig.NewRegistration("Global")
r.Yaml(`
rexray:
host: tcp://:7979
logLevel: warn
`)
r.Key(gofig.String, "h", "tcp://:7979",
"The REX-Ray host", "rexray.host")
r.Key(gofig.String, "l", "warn",
"The log level (error, warn, info, debug)", "rexray.logLevel")
return r
}
func driverRegistration() *gofig.Registration {
r := gofig.NewRegistration("Driver")
r.Yaml(`
rexray:
osDrivers:
- linux
storageDrivers:
- libstorage
volumeDrivers:
- docker
`)
r.Key(gofig.String, "", "linux",
"The OS drivers to consider", "rexray.osDrivers")
r.Key(gofig.String, "", "",
"The storage drivers to consider", "rexray.storageDrivers")
r.Key(gofig.String, "", "docker",
"The volume drivers to consider", "rexray.volumeDrivers")
return r
}
|
Fix incremental compilation for lua classes that require a superclass name resolution
|
package net.wizardsoflua.annotation;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Target;
/**
* We use class retention, because otherwise this annotation is not available on unchanged classes
* during eclipses incremental compilation.
*
* @author Adrodoc
*/
@Target(TYPE)
public @interface GenerateLuaDoc {
/**
* The name of the module. Required unless @{@link LuaClassAttributes} is present, in which case
* the name defaults to {@link LuaClassAttributes#name()}.
*/
String name() default "";
/**
* The subtitle of the module.
*/
String subtitle() default "";
/**
* The document type ({@code "module"}, {@code "class"} or {@code "event"}). Defaults to
* {@code "class"} when the type is also annotated with @{@link GenerateLuaClassTable}. Defaults
* to {@code "module"} when the type is also annotated with @{@link GenerateLuaModuleTable}.
*/
String type() default "";
}
|
package net.wizardsoflua.annotation;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(SOURCE)
@Target(TYPE)
public @interface GenerateLuaDoc {
/**
* The name of the module. Required unless @{@link LuaClassAttributes} is present, in which case
* the name defaults to {@link LuaClassAttributes#name()}.
*/
String name() default "";
/**
* The subtitle of the module.
*/
String subtitle() default "";
/**
* The document type ({@code "module"}, {@code "class"} or {@code "event"}). Defaults to
* {@code "class"} when the type is also annotated with @{@link GenerateLuaClassTable}. Defaults
* to {@code "module"} when the type is also annotated with @{@link GenerateLuaModuleTable}.
*/
String type() default "";
}
|
Use PORT environment variable when it is available because Heroku
|
import 'babel-polyfill'
import bodyParser from 'body-parser'
import express from 'express'
import log from './log'
import appRenderer from './middleware/app-renderer'
import { apolloServer } from 'apollo-server'
import { schema, resolvers } from './api/schema'
import mocks from './api/mocks'
process.on('uncaughtException', (ex) => {
log.error(ex)
process.exit(1)
})
const app = express()
const port = process.env.NODE_ENV === 'production' ? process.env.PORT : process.env.EXPRESS_PORT
// Don't rate limit heroku
app.enable('trust proxy')
// Parse bodies as JSON
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
// In development, we use webpack server
if (process.env.NODE_ENV === 'production') {
app.use(express.static(process.env.PUBLIC_DIR, {
maxAge: '180 days'
}))
}
app.use('/graphql', apolloServer(() => ({
graphiql: true,
pretty: true,
schema,
mocks,
resolvers,
allowUndefinedInResolve: false
})))
// This middleware should be last. Return the React app only if no other route is hit.
app.use(appRenderer)
app.listen(port, () => {
log.info(`Node app is running on port ${port}`)
})
|
import 'babel-polyfill'
import bodyParser from 'body-parser'
import express from 'express'
import log from './log'
import appRenderer from './middleware/app-renderer'
import { apolloServer } from 'apollo-server'
import { schema, resolvers } from './api/schema'
import mocks from './api/mocks'
process.on('uncaughtException', (ex) => {
log.error(ex)
process.exit(1)
})
const app = express()
const port = process.env.EXPRESS_PORT
// Don't rate limit heroku
app.enable('trust proxy')
// Parse bodies as JSON
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
// In development, we use webpack server
if (process.env.NODE_ENV === 'production') {
app.use(express.static(process.env.PUBLIC_DIR, {
maxAge: '180 days'
}))
}
app.use('/graphql', apolloServer(() => ({
graphiql: true,
pretty: true,
schema,
mocks,
resolvers,
allowUndefinedInResolve: false
})))
// This middleware should be last. Return the React app only if no other route is hit.
app.use(appRenderer)
app.listen(port, () => {
log.info(`Node app is running on port ${port}`)
})
|
Rewrite "The Perry Bible Fellowship" after feed change
|
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "The Perry Bible Fellowship"
language = "en"
url = "http://www.pbfcomics.com/"
start_date = "2001-01-01"
rights = "Nicholas Gurewitch"
class Crawler(CrawlerBase):
history_capable_date = "2019-06-12"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.pbfcomics.com/feed/feed.xml")
for entry in feed.for_date(pub_date):
page = self.parse_page(entry.link)
images = page.root.xpath("//div[@id='comic']/img")
crawler_images = []
for image in images:
title = entry.title
crawler_images.append(CrawlerImage(image.get("src"), title))
|
from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "The Perry Bible Fellowship"
language = "en"
url = "http://www.pbfcomics.com/"
start_date = "2001-01-01"
rights = "Nicholas Gurewitch"
class Crawler(CrawlerBase):
history_capable_date = "2001-01-01"
time_zone = "US/Eastern"
def crawl(self, pub_date):
feed = self.parse_feed("http://www.pbfcomics.com/feed/feed.xml")
for entry in feed.for_date(pub_date):
url = entry.summary.src('img[src*="/archive_b/"]')
title = entry.title
return CrawlerImage(url, title)
|
Add $in operator if object is an array
|
var methods = {};
methods.setRelated = function(relationName, value) {};
methods.getRelated = function(relationName) {
var doc = this;
var Class = doc.constructor;
// If there is already a reference to the relation object(s) stored in the
// "_references" object then we can take it without looking in collection.
if (_.has(this._references, relationName)) {
return this._references[relationName];
}
// Look for the relation definition.
var relation = Class.getRelation(relationName);
if (!relation) {
return;
}
// Get a collection defined in the relation.
var ForeignClass = Astro.getClass(relation.class);
var ForeignCollection = ForeignClass.getCollection();
// Prepare selector to select only these documents that much the relation.
var selector = {};
var localValue = this.get(relation.local);
selector[relation.foreign] = _.isArray(localValue) ? {$in: localValue} : localValue;
// Get a related object.
var related;
if (relation.type === 'one') {
related = ForeignCollection.findOne(selector);
} else if (relation.type === 'many') {
related = ForeignCollection.find(selector);
}
// Assing the related object to the "_references" object for further use.
return this._references[relationName] = related;
};
_.extend(Astro.BaseClass.prototype, methods);
|
var methods = {};
methods.setRelated = function(relationName, value) {};
methods.getRelated = function(relationName) {
var doc = this;
var Class = doc.constructor;
// If there is already a reference to the relation object(s) stored in the
// "_references" object then we can take it without looking in collection.
if (_.has(this._references, relationName)) {
return this._references[relationName];
}
// Look for the relation definition.
var relation = Class.getRelation(relationName);
if (!relation) {
return;
}
// Get a collection defined in the relation.
var ForeignClass = Astro.getClass(relation.class);
var ForeignCollection = ForeignClass.getCollection();
// Prepare selector to select only these documents that much the relation.
var selector = {};
selector[relation.foreign] = this.get(relation.local);
// Get a related object.
var related;
if (relation.type === 'one') {
related = ForeignCollection.findOne(selector);
} else if (relation.type === 'many') {
related = ForeignCollection.find(selector);
}
// Assing the related object to the "_references" object for further use.
return this._references[relationName] = related;
};
_.extend(Astro.BaseClass.prototype, methods);
|
Remove object from local storage hook
|
'use strict';
var AbstractStore = require('stores/AbstractStore');
var assign = require('object-assign');
var GeoAppDispatcher = require('../dispatcher/GeoAppDispatcher');
var GeoAppActionsConstants = require('constants/GeoAppActions');
var LocalStoreDataProvider = require('stores/LocalStorageDataProvider');
var GeoObjectsStore = assign({}, AbstractStore, {
/**
* Get all objects from store
* @returns {*}
*/
getAllGeoObjects: function () {
return LocalStoreDataProvider.read(GeoAppActionsConstants.GEO_OBJECTS_COLLECTION);
}
});
GeoObjectsStore.dispatchToken = GeoAppDispatcher.register(function (action) {
switch (action.actionType) {
case GeoAppActionsConstants.GEO_OBJECTS_CREATE:
LocalStoreDataProvider.addCollectionItem(GeoAppActionsConstants.GEO_OBJECTS_COLLECTION, action.rawData);
GeoObjectsStore.emitChange();
break;
case GeoAppActionsConstants.GEO_OBJECTS_DELETE:
LocalStoreDataProvider.deleteCollectionItem(GeoAppActionsConstants.GEO_OBJECTS_COLLECTION, action.rawData);
GeoObjectsStore.emitChange();
break;
default:
}
});
module.exports = GeoObjectsStore;
|
'use strict';
var AbstractStore = require('stores/AbstractStore');
var assign = require('object-assign');
var GeoAppDispatcher = require('../dispatcher/GeoAppDispatcher');
var GeoAppActionsConstants = require('constants/GeoAppActions');
var LocalStoreDataProvider = require('stores/LocalStorageDataProvider');
var GeoObjectsStore = assign({}, AbstractStore, {
/**
* Get all objects from store
* @returns {*}
*/
getAllGeoObjects: function () {
return LocalStoreDataProvider.read(GeoAppActionsConstants.GEO_OBJECTS_COLLECTION);
}
});
GeoObjectsStore.dispatchToken = GeoAppDispatcher.register(function (action) {
switch (action.actionType) {
case GeoAppActionsConstants.GEO_OBJECTS_CREATE:
LocalStoreDataProvider.addCollectionItem(GeoAppActionsConstants.GEO_OBJECTS_COLLECTION, action.rawData);
GeoObjectsStore.emitChange();
break;
default:
}
});
module.exports = GeoObjectsStore;
|
Remove lru-cache dependency from stylus
|
Package.describe({
summary: 'Expressive, dynamic, robust CSS',
version: "2.0.0_511"
});
Package.registerBuildPlugin({
name: 'compileStylusBatch',
use: ['ecmascript', 'caching-compiler'],
sources: [
'plugin/compile-stylus.js'
],
npmDependencies: {
stylus: "https://github.com/meteor/stylus/tarball/d4352c9cb4056faf238e6bd9f9f2172472b67c5b", // fork of 0.51.1
nib: "1.1.0"
}
});
Package.onUse(function (api) {
api.use('isobuild:compiler-plugin@1.0.0');
});
Package.onTest(function (api) {
api.use(['tinytest', 'stylus', 'test-helpers', 'templating']);
api.addFiles([
'stylus_tests.html',
'stylus_tests.styl',
'stylus_tests.import.styl',
'stylus_tests.js'
],'client');
});
|
Package.describe({
summary: 'Expressive, dynamic, robust CSS',
version: "2.0.0_511"
});
Package.registerBuildPlugin({
name: 'compileStylusBatch',
use: ['ecmascript', 'caching-compiler'],
sources: [
'plugin/compile-stylus.js'
],
npmDependencies: {
stylus: "https://github.com/meteor/stylus/tarball/d4352c9cb4056faf238e6bd9f9f2172472b67c5b", // fork of 0.51.1
nib: "1.1.0",
"lru-cache": "2.6.4"
}
});
Package.onUse(function (api) {
api.use('isobuild:compiler-plugin@1.0.0');
});
Package.onTest(function (api) {
api.use(['tinytest', 'stylus', 'test-helpers', 'templating']);
api.addFiles([
'stylus_tests.html',
'stylus_tests.styl',
'stylus_tests.import.styl',
'stylus_tests.js'
],'client');
});
|
Add clean task for package publishing
|
/// <binding AfterBuild='nuget-pack' />
"use strict";
var gulp = require('gulp'),
path = require('path'),
exec = require('child_process').exec,
fs = require('fs');
var solutionFolder = path.resolve(__dirname, '..');
var projectFolder = path.join(solutionFolder, 'MAB.SimpleMapper');
var distFolder = path.join(solutionFolder, 'dist');
if (!fs.existsSync(distFolder)) {
fs.mkdirSync(distFolder);
}
gulp.task('nuget-clean', function (callback) {
exec('del *.nupkg', { cwd: distFolder }, function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
callback(err);
});
});
gulp.task('nuget-pack', ['nuget-clean'], function (callback) {
exec('nuget pack MAB.SimpleMapper.csproj -Symbols -OutputDirectory ' + distFolder + ' -Prop Configuration=Release', { cwd: projectFolder }, function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
callback(err);
});
});
|
/// <binding AfterBuild='nuget-pack' />
"use strict";
var gulp = require('gulp'),
path = require('path'),
exec = require('child_process').exec,
fs = require('fs');
var solutionFolder = path.resolve(__dirname, '..');
var projectFolder = path.join(solutionFolder, 'MAB.SimpleMapper');
var distFolder = path.join(solutionFolder, 'dist');
if (!fs.existsSync(distFolder)) {
fs.mkdirSync(distFolder);
}
gulp.task('nuget-pack', function (callback) {
exec('nuget pack MAB.SimpleMapper.csproj -Symbols -OutputDirectory ' + distFolder + ' -Prop Configuration=Release', { cwd: projectFolder }, function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
callback(err);
});
});
|
Fix output stream and return code
|
<?php
if ( posix_geteuid() ) {
fwrite( STDERR, "\033[1;31mError:\033[0m Please run `ee` with root privileges." );
exit( 1 );
}
// Can be used by plugins/themes to check if EE is running or not
define( 'EE', true );
define( 'EE_VERSION', trim( file_get_contents( EE_ROOT . '/VERSION' ) ) );
define( 'EE_START_MICROTIME', microtime( true ) );
define( 'EE_CONF_ROOT', '/opt/easyengine' );
if ( file_exists( EE_ROOT . '/vendor/autoload.php' ) ) {
define( 'EE_VENDOR_DIR', EE_ROOT . '/vendor' );
} elseif ( file_exists( dirname( dirname( EE_ROOT ) ) . '/autoload.php' ) ) {
define( 'EE_VENDOR_DIR', dirname( dirname( EE_ROOT ) ) );
} else {
define( 'EE_VENDOR_DIR', EE_ROOT . '/vendor' );
}
require_once EE_ROOT . '/php/bootstrap.php';
\EE\bootstrap();
|
<?php
if( posix_geteuid() ) {
echo "\033[1;31mError:\033[0m Please run `ee` with root privileges.";
return;
}
// Can be used by plugins/themes to check if EE is running or not
define( 'EE', true );
define( 'EE_VERSION', trim( file_get_contents( EE_ROOT . '/VERSION' ) ) );
define( 'EE_START_MICROTIME', microtime( true ) );
define( 'EE_CONF_ROOT', '/opt/easyengine' );
if ( file_exists( EE_ROOT . '/vendor/autoload.php' ) ) {
define( 'EE_VENDOR_DIR', EE_ROOT . '/vendor' );
} elseif ( file_exists( dirname( dirname( EE_ROOT ) ) . '/autoload.php' ) ) {
define( 'EE_VENDOR_DIR', dirname( dirname( EE_ROOT ) ) );
} else {
define( 'EE_VENDOR_DIR', EE_ROOT . '/vendor' );
}
require_once EE_ROOT . '/php/bootstrap.php';
\EE\bootstrap();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.