text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Revert "Update random number generator test"
This reverts commit b63bda37aa2e9b5251cf6c54d59785d2856659ca.
|
import os
import mxnet as mx
import numpy as np
def same(a, b):
return np.sum(a != b) == 0
def check_with_device(device):
with mx.Context(device):
a, b = -10, 10
mu, sigma = 10, 2
shape = (100, 100)
mx.random.seed(128)
ret1 = mx.random.normal(mu, sigma, shape)
un1 = mx.random.uniform(a, b, shape)
mx.random.seed(128)
ret2 = mx.random.normal(mu, sigma, shape)
un2 = mx.random.uniform(a, b, shape)
assert same(ret1.asnumpy(), ret2.asnumpy())
assert same(un1.asnumpy(), un2.asnumpy())
assert abs(np.mean(ret1.asnumpy()) - mu) < 0.1
assert abs(np.std(ret1.asnumpy()) - sigma) < 0.1
assert abs(np.mean(un1.asnumpy()) - (a+b)/2) < 0.1
def test_random():
check_with_device(mx.cpu())
if __name__ == '__main__':
test_random()
|
import os
import mxnet as mx
import numpy as np
def same(a, b):
return np.sum(a != b) == 0
def check_with_device(device):
with mx.Context(device):
a, b = -10, 10
mu, sigma = 10, 2
for i in range(5):
shape = (100 + i, 100 + i)
mx.random.seed(128)
ret1 = mx.random.normal(mu, sigma, shape)
un1 = mx.random.uniform(a, b, shape)
mx.random.seed(128)
ret2 = mx.random.normal(mu, sigma, shape)
un2 = mx.random.uniform(a, b, shape)
assert same(ret1.asnumpy(), ret2.asnumpy())
assert same(un1.asnumpy(), un2.asnumpy())
assert abs(np.mean(ret1.asnumpy()) - mu) < 0.1
assert abs(np.std(ret1.asnumpy()) - sigma) < 0.1
assert abs(np.mean(un1.asnumpy()) - (a+b)/2) < 0.1
def test_random():
check_with_device(mx.cpu())
if __name__ == '__main__':
test_random()
|
Remove unused code in loose.
|
//>>includeStart('strict', pragmas.strict);
define(['./isImmutable'], function (isImmutable) {
'use strict';
/**
* Extract meta data from a property.
*
* @param {Mixed} prop The property
* @param {String} name The name of the property
*
* @return {Object} An object containg the metadata
*/
function propertyMeta(prop, name) {
var ret = {};
// Is it undefined?
if (prop === undefined) {
return null;
}
// Analyze visibility
if (name) {
if (name.charAt(0) === '_') {
if (name.charAt(1) === '_') {
ret.isPrivate = true;
} else {
ret.isProtected = true;
}
} else {
ret.isPublic = true;
}
}
ret.isImmutable = isImmutable(prop);
ret.value = prop;
return ret;
}
return propertyMeta;
});
//>>includeEnd('strict');
|
define(['./isImmutable'], function (isImmutable) {
'use strict';
/**
* Extract meta data from a property.
*
* @param {Mixed} prop The property
* @param {String} name The name of the property
*
* @return {Object} An object containg the metadata
*/
function propertyMeta(prop, name) {
var ret = {};
// Is it undefined?
if (prop === undefined) {
return null;
}
// Analyze visibility
if (name) {
if (name.charAt(0) === '_') {
if (name.charAt(1) === '_') {
ret.isPrivate = true;
} else {
ret.isProtected = true;
}
} else {
ret.isPublic = true;
}
}
ret.isImmutable = isImmutable(prop);
ret.value = prop;
return ret;
}
return propertyMeta;
});
|
Format rollbar, add sourcemap in DEV env
|
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import postcss from 'rollup-plugin-postcss';
import uglify from 'rollup-plugin-uglify';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import pkg from './package.json';
const transformStyles = postcss({
extract: 'dist/aos.css',
plugins: [autoprefixer, cssnano]
});
const input = 'src/js/aos.js';
export default [
{
input,
output: {
file: pkg.browser,
name: 'AOS',
format: 'umd'
},
sourceMap: process.env.NODE_ENV === 'dev',
plugins: [
transformStyles,
resolve(),
commonjs(),
babel({
exclude: ['node_modules/**']
}),
uglify()
]
},
{
input,
external: Object.keys(pkg.dependencies),
output: [
{ file: pkg.main, format: 'cjs' },
{ file: pkg.module, format: 'es' }
],
plugins: [
transformStyles,
babel({
exclude: ['node_modules/**']
})
]
}
];
|
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import postcss from 'rollup-plugin-postcss';
import uglify from 'rollup-plugin-uglify';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import pkg from './package.json';
const transformStyles = postcss({
extract: 'dist/aos.css',
plugins: [
autoprefixer,
cssnano,
]
});
const input = 'src/js/aos.js';
export default [
{
input,
output: {
file: pkg.browser,
name: 'AOS',
format: 'umd',
},
plugins: [
transformStyles,
resolve(),
commonjs(),
babel({
exclude: ['node_modules/**']
}),
uglify(),
],
},
{
input,
external: Object.keys(pkg.dependencies),
output: [
{ file: pkg.main, format: 'cjs' },
{ file: pkg.module, format: 'es' },
],
plugins: [
transformStyles,
babel({
exclude: ['node_modules/**']
}),
],
},
];
|
Fix a bug after Last.fm site update
|
export function getTitle() {
var titleEl = document.querySelector('h1.header-title');
if (titleEl) {
var title = titleEl.textContent;
title = title.trim();
// remove song duration
title = title.replace(/ \(\d{1,2}:\d{1,2}\)$/, '');
title = title.trim();
return title;
}
return null;
}
function getCrumb() {
var crumbEl = document.querySelector('a.header-crumb');
return (crumbEl ? crumbEl.textContent.trim() : null);
}
export function getArtist(type) {
if (type === 'artist') {
return getTitle();
} else {
return getCrumb();
}
}
export function getAlbum() {
return getTitle();
}
export function getSong() {
return getTitle();
}
export function getUsername() {
var element = document.querySelector('img.auth-avatar-desktop');
return element.alt.trim();
}
|
export function getTitle() {
var titleEl = document.querySelector('h1.header-title');
if (titleEl) {
var title = titleEl.textContent;
title = title.trim();
// remove song duration
title = title.replace(/ \(\d{1,2}:\d{1,2}\)$/, '');
title = title.trim();
return title;
}
return null;
}
function getCrumb() {
var crumbEl = document.querySelector('a.header-crumb');
return (crumbEl ? crumbEl.textContent.trim() : null);
}
export function getArtist(type) {
if (type === 'artist') {
return getTitle();
} else {
return getCrumb();
}
}
export function getAlbum() {
return getTitle();
}
export function getSong() {
return getTitle();
}
export function getUsername() {
var element = document.querySelector('a.auth-link');
return element.textContent.trim();
}
|
Make wget use system dependent temp folder location
|
package com.jvm_bloggers.core.rss.fetchers;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import javaslang.control.Option;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.File;
@Component
@Slf4j
public class WgetFetcher implements Fetcher {
@Override
public Option<SyndFeed> fetch(String rssUrl) {
File tempFile = null;
try {
tempFile = File.createTempFile("jvm-bloggers", null);
String tmpPath = tempFile.getAbsolutePath();
Process process = new ProcessBuilder("wget", rssUrl, "-O", tmpPath).start();
process.waitFor();
return Option.of(new SyndFeedInput().build(tempFile));
} catch (Exception exc) {
log.warn("Exception during wget execution for url {}: {}", rssUrl, exc.getMessage());
return Option.none();
} finally {
if (tempFile != null) {
tempFile.delete();
}
}
}
}
|
package com.jvm_bloggers.core.rss.fetchers;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import javaslang.control.Option;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.UUID;
@Component
@Slf4j
public class WgetFetcher implements Fetcher {
@Override
public Option<SyndFeed> fetch(String rssUrl) {
String uid = UUID.randomUUID().toString();
try {
Process process = new ProcessBuilder("wget", rssUrl, "-O", "/tmp/" + uid).start();
process.waitFor();
File file = new File("/tmp/" + uid);
Option<SyndFeed> feed = Option.of(new SyndFeedInput().build(file));
file.delete();
return feed;
} catch (Exception exc) {
log.warn("Exception during wget execution for url {}: {}", rssUrl, exc.getMessage());
return Option.none();
}
}
}
|
Document that pop() might return Null
|
<?php
namespace Kue;
/**
* Interface for Queues
*
* @author Christoph Hochstrasser <christoph.hochstrasser@gmail.com>
*/
interface Queue
{
/**
* Blocks until a job is available, and returns it. This is used by the
* worker script that's shipped with Kue.
*
* @return Job|null Returns either a Job, or Null when the operation
* timed out.
*/
function pop();
/**
* Pushes the job onto the queue.
*
* @param Job $job
* @return void
*/
function push(Job $job);
/**
* Flushes the queue.
*
* This is mainly useful for queues which are clients to a 3rd party system
* which stores the jobs. This method should be called after the response has been sent
* to the client, and can be used to send all pushed jobs in one go
* without much notice of the user.
*
* @return void
*/
function flush();
}
|
<?php
namespace Kue;
/**
* Interface for Queues
*
* @author Christoph Hochstrasser <christoph.hochstrasser@gmail.com>
*/
interface Queue
{
/**
* Blocks until a job is available, and returns it. This is used by the
* worker script that's shipped with Spark.
*
* @return Job
*/
function pop();
/**
* Pushes the job onto the queue.
*
* @param Job $job
* @return void
*/
function push(Job $job);
/**
* Flushes the queue.
*
* This is mainly useful for queues which are clients to a 3rd party system
* which stores the jobs. This method is called after the response has been sent
* to the client, and can be used to send all pushed jobs in one go.
*
* @return void
*/
function flush();
}
|
Update AudioChannel to create nodes in member function instead of constructor
|
var AudioChannel = function(args) {
this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
if(args) {
this.frequency = args.freq ? args.freq : 220;
this.wave = args.wave ? args.wave : "triangle";
this.volume = args.gain ? args.gain : 0.05;
}
}
AudioChannel.prototype.setNodes = function() {
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
this.oscill.connect(this.gain);
this.gain.connect(this.context.destination);
this.oscill.frequency.value = this.frequency;
this.oscill.type = this.wave;
this.gain.gain.value = this.volume;
};
AudioChannel.prototype.playSong = function(song) {
this.oscill.start();
var playNextNote = function(song) {
this.oscill.frequency.value = song[0].freq;
if(song[1]) {
setTimeout(playNextNote.bind(this, song.slice(1)), song[0].length);
}
else {
setTimeout(function() {
this.gain.gain.value = 0;
}.bind(this), song[0].length);
}
}.bind(this);
playNextNote(song);
};
|
var AudioChannel = function(args) {
this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
this.oscill = this.context.createOscillator();
this.gain = this.context.createGain();
this.oscill.connect(this.gain);
this.gain.connect(this.context.destination);
if(args) {
this.oscill.frequency.value = args.freq ? args.freq : 220;
this.oscill.type = args.wave ? args.wave : "triangle";
this.gain.gain.value = args.gain ? args.gain : 0.05;
}
}
AudioChannel.prototype.playSong = function(song) {
this.oscill.start();
var playNextNote = function(song) {
this.oscill.frequency.value = song[0].freq;
if(song[1]) {
setTimeout(playNextNote.bind(this, song.slice(1)), song[0].length);
}
else {
setTimeout(function() {
this.gain.gain.value = 0;
}.bind(this), song[0].length);
}
}.bind(this);
playNextNote(song);
}
|
Convert umlaute in slugger urls
|
const mkdirp = require('mkdirp');
const fs = require('fs');
const dirname = require('path').dirname;
// Create "this-is-a-post" from "This is a Post"
exports.slugger = str => str
.toLowerCase()
.replace(/ä/g, 'ae')
.replace(/ö/g, 'oe')
.replace(/ü/g, 'ue')
.replace(/[^\w ]+/g, ' ')
.replace(/ +/g, '-');
// Random logo
exports.logoURL = () => `/img/bisnaer${Math.ceil(Math.random() * 31, 10)}.PNG`;
/**
* Safely write a file to disk
* @returns {Promise} File written promise
*/
exports.writefile = (filePath, content) => {
const fileContent = (typeof content === 'object') ? JSON.stringify(content) : content;
return new Promise((resolve, reject) => {
mkdirp(dirname(filePath), (err) => {
if (err) reject(err);
fs.writeFile(filePath, fileContent, { encoding: 'utf-8' }, resolve);
});
});
};
|
const mkdirp = require('mkdirp');
const fs = require('fs');
const dirname = require('path').dirname;
// Create "this-is-a-post" from "This is a Post"
exports.slugger = str => str.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-');
// Random logo
exports.logoURL = () => `/img/bisnaer${Math.ceil(Math.random() * 31, 10)}.PNG`;
/**
* Safely write a file to disk
* @returns {Promise} File written promise
*/
exports.writefile = (filePath, content) => {
const fileContent = (typeof content === 'object') ? JSON.stringify(content) : content;
return new Promise((resolve, reject) => {
mkdirp(dirname(filePath), (err) => {
if (err) reject(err);
fs.writeFile(filePath, fileContent, { encoding: 'utf-8' }, resolve);
});
});
};
|
Remove Keras from network splitter
Keras isn't as stable as h5py and json. This commit removes the keras dependency from the network splitting function.
|
#!/usr/bin/env python3
"""
Convert a keras model, saved with model.save(...) to a weights and
architecture component.
"""
import argparse
def get_args():
d = '(default: %(default)s)'
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('model')
parser.add_argument('-w','--weight-file-name', default='weights.h5',
help=d)
parser.add_argument('-a', '--architecture-file-name',
default='architecture.json', help=d)
return parser.parse_args()
def run():
args = get_args()
from h5py import File
import json
m = File(args.model,'r')
with File(args.weight_file_name,'w') as w:
for name, wt in w.items():
w.copy(wt, name)
arch = json.loads(m.attrs['model_config'])
with open(args.architecture_file_name,'w') as arch_file:
arch_file.write(json.dumps(arch,indent=2))
if __name__ == '__main__':
run()
|
#!/usr/bin/env python3
"""
Convert a keras model, saved with model.save(...) to a weights and
architecture component.
"""
import argparse
def get_args():
d = '(default: %(default)s)'
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('model')
parser.add_argument('-w','--weight-file-name', default='weights.h5',
help=d)
parser.add_argument('-a', '--architecture-file-name',
default='architecture.json', help=d)
return parser.parse_args()
def run():
args = get_args()
import keras
m = keras.models.load_model(args.model)
m.save_weights(args.weight_file_name)
with open(args.architecture_file_name,'w') as arch:
arch.write(m.to_json(indent=2))
if __name__ == '__main__':
run()
|
Correct selecting text by length when text is Unicode.
|
# This macro is to remove 1 character form selected line on the left.
# Useful to clean code copied from diff file.
#
# Author: Nguyễn Hồng Quân (ng.hong.quan@gmail.com)
from xpcom import components
viewSvc = components.classes["@activestate.com/koViewService;1"]\
.getService(components.interfaces.koIViewService)
view = viewSvc.currentView
view = view.queryInterface(components.interfaces.koIScintillaView)
sm = view.scimoz
# Make `start` the beginning position of the first selected line,
# and `end` the ending position of the last selected line.
if sm.anchor < sm.currentPos:
start = sm.positionFromLine(sm.lineFromPosition(sm.anchor))
end = sm.getLineEndPosition(sm.lineFromPosition(sm.currentPos))
else:
start = sm.positionFromLine(sm.lineFromPosition(sm.currentPos))
end = sm.getLineEndPosition(sm.lineFromPosition(sm.anchor))
lines = tuple(sm.getTextRange(start, end).splitlines())
# Cut one character from the left
lines = tuple(l[1:] for l in lines)
# Select part of document
sm.setSel(start, end)
# Replace selection content
text = '\n'.join(lines)
sm.replaceSel(text)
# Keep selection to let user continue to apply this macro
sm.setSel(start, start+len(text.encode('utf-8')))
|
# This macro is to remove 1 character form selected line on the left.
# Useful to clean code copied from diff file.
#
# Author: Nguyễn Hồng Quân (ng.hong.quan@gmail.com)
from xpcom import components
viewSvc = components.classes["@activestate.com/koViewService;1"]\
.getService(components.interfaces.koIViewService)
view = viewSvc.currentView
view = view.queryInterface(components.interfaces.koIScintillaView)
sm = view.scimoz
# Make `start` the beginning position of the first selected line,
# and `end` the ending position of the last selected line.
if sm.anchor < sm.currentPos:
start = sm.positionFromLine(sm.lineFromPosition(sm.anchor))
end = sm.getLineEndPosition(sm.lineFromPosition(sm.currentPos))
else:
start = sm.positionFromLine(sm.lineFromPosition(sm.currentPos))
end = sm.getLineEndPosition(sm.lineFromPosition(sm.anchor))
lines = tuple(sm.getTextRange(start, end).splitlines())
# Cut one character from the left
lines = tuple(l[1:] for l in lines)
# Select part of document
sm.setSel(start, end)
# Replace selection content
text = '\n'.join(lines)
sm.replaceSel(text)
# Keep selection to allow to continue to apply this macro if use wants
sm.setSel(start, start+len(text))
|
Stop looping when currentTarget becomes undefined
|
const EventKit = require('event-kit')
module.exports =
function listen (element, eventName, selector, handler) {
var innerHandler = function (event) {
if (selector) {
var currentTarget = event.target
while (currentTarget) {
if (currentTarget.matches && currentTarget.matches(selector)) {
handler({
type: event.type,
currentTarget: currentTarget,
target: event.target,
preventDefault: function () {
event.preventDefault()
},
originalEvent: event
})
}
if (currentTarget === element) break
currentTarget = currentTarget.parentNode
}
} else {
handler({
type: event.type,
currentTarget: event.currentTarget,
target: event.target,
preventDefault: function () {
event.preventDefault()
},
originalEvent: event
})
}
}
element.addEventListener(eventName, innerHandler)
return new EventKit.Disposable(function () {
element.removeEventListener(eventName, innerHandler)
})
}
|
const EventKit = require('event-kit')
module.exports =
function listen (element, eventName, selector, handler) {
var innerHandler = function (event) {
if (selector) {
var currentTarget = event.target
while (true) {
if (currentTarget.matches && currentTarget.matches(selector)) {
handler({
type: event.type,
currentTarget: currentTarget,
target: event.target,
preventDefault: function () {
event.preventDefault()
},
originalEvent: event
})
}
if (currentTarget === element) break
currentTarget = currentTarget.parentNode
}
} else {
handler({
type: event.type,
currentTarget: event.currentTarget,
target: event.target,
preventDefault: function () {
event.preventDefault()
},
originalEvent: event
})
}
}
element.addEventListener(eventName, innerHandler)
return new EventKit.Disposable(function () {
element.removeEventListener(eventName, innerHandler)
})
}
|
Initialize seq without type in drop test class
|
package com.jmonad.seq;
import org.junit.Test;
public class SeqDropTest {
private Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private Seq<Integer> elements = new Seq<>(numbers);
@Test public void dropListElementsTest() {
assert elements.drop(5).toArrayList().toString().equals("[6, 7, 8, 9, 10]");
}
@Test public void dropElementsWithNoAmountTest() {
assert elements.drop(0).toArrayList().toString().equals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]");
}
@Test public void dropElementsWithNegativeAmountTest() {
assert elements.drop(-1).toArrayList().toString().equals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]");
}
@Test public void dropElementsWithAmountHigherThanListSizeTest() {
assert elements.drop(20).toArrayList().toString().equals("[]");
}
}
|
package com.jmonad.seq;
import org.junit.Test;
public class SeqDropTest {
private Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private Seq<Integer> elements = new Seq<Integer>(numbers);
@Test public void dropListElementsTest() {
assert elements.drop(5).toArrayList().toString().equals("[6, 7, 8, 9, 10]");
}
@Test public void dropElementsWithNoAmountTest() {
assert elements.drop(0).toArrayList().toString().equals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]");
}
@Test public void dropElementsWithNegativeAmountTest() {
assert elements.drop(-1).toArrayList().toString().equals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]");
}
@Test public void dropElementsWithAmountHigherThanListSizeTest() {
assert elements.drop(20).toArrayList().toString().equals("[]");
}
}
|
Store more pings per transaction
|
import datetime
from django.core.management.base import BaseCommand, CommandError
from clowder_account.models import Company
from clowder_server.emailer import send_alert
from clowder_server.models import Alert, Ping
class Command(BaseCommand):
help = 'Checks and sends alerts'
def handle(self, *args, **options):
# delete old pings
for company in Company.objects.all():
pings_by_name = Ping.objects.filter(company=company).distinct('name')
if not pings_by_name:
continue
max_per_ping = 2000 / len(pings_by_name)
for name in pings_by_name:
pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping]
pings = list(pings.values_list("id", flat=True))
Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete()
# send alerts
alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now)
for alert in alerts:
send_alert(alert.company, alert.name)
alert.notify_at = None
alert.save()
|
import datetime
from django.core.management.base import BaseCommand, CommandError
from clowder_account.models import Company
from clowder_server.emailer import send_alert
from clowder_server.models import Alert, Ping
class Command(BaseCommand):
help = 'Checks and sends alerts'
def handle(self, *args, **options):
# delete old pings
for company in Company.objects.all():
pings_by_name = Ping.objects.filter(company=company).distinct('name')
if not pings_by_name:
continue
max_per_ping = 500 / len(pings_by_name)
for name in pings_by_name:
pings = Ping.objects.filter(company=company, name=name).order_by('-create')[:max_per_ping]
pings = list(pings.values_list("id", flat=True))
Ping.objects.filter(company=company, name=name).exclude(pk__in=pings).delete()
# send alerts
alerts = Alert.objects.filter(notify_at__lte=datetime.datetime.now)
for alert in alerts:
send_alert(alert.company, alert.name)
alert.notify_at = None
alert.save()
|
Handle un-loaded images when setting width
|
!(function () {
'use strict'
// Increase width of images on large screens
Array.from(document.querySelectorAll('.post__body p > img')).forEach(
(image) => {
if (image.naturalWidth) {
testImage(image)
} else {
image.onload = () => testImage(image)
}
}
)
function testImage(image) {
if (image.naturalWidth >= 760) {
image.parentNode.classList.add('post__wide-image')
}
}
// Don't cut off long lines of code
var codes = document.querySelectorAll('.post__body pre[class^="language-"]')
for (var i = 0; i < codes.length; i++) {
var maxLineLength = codes[i].innerHTML
.split('<br>')
.map((line) =>
line
.replace(/<[^>]+>/g, '') // Remove invisible HTML tags
.replace(/&[a-z0-9]{2,4};/g, '$') // Replace HTML entities w/ a single character
.trim()
)
.filter(Boolean)
.reduce((maxLength, line) => Math.max(maxLength, line.length), 0)
if (maxLineLength > 62) {
codes[i].classList.add('post__wide-pre')
}
}
})()
|
!(function () {
'use strict'
// Increase width of images on large screens
var images = document.querySelectorAll('.post__body p > img')
for (var i = 0; i < images.length; i++) {
// Only apply to wide images
if (images[i].clientWidth >= 518) {
var wrap = images[i].parentNode
if (wrap.nodeName === 'P') {
wrap.classList.add('post__wide-image')
}
}
}
// Don't cut off long lines of code
var codes = document.querySelectorAll('.post__body pre[class^="language-"]')
for (var i = 0; i < codes.length; i++) {
var maxLineLength = codes[i].innerHTML
.split('<br>')
.map((line) =>
line
.replace(/<[^>]+>/g, '') // Remove invisible HTML tags
.replace(/&[a-z0-9]{2,4};/g, '$') // Replace HTML entities w/ a single character
.trim()
)
.filter(Boolean)
.reduce((maxLength, line) => Math.max(maxLength, line.length), 0)
if (maxLineLength > 62) {
codes[i].classList.add('post__wide-pre')
}
}
})()
|
Index of the list should be an int
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPairs(len(data_list), sample_size)
return tuple((data_list[int(k1)], data_list[int(k2)]) for k1, k2 in random_pairs)
def blockData(data_d, blocker):
blocks = dedupe.core.OrderedDict({})
record_blocks = dedupe.core.OrderedDict({})
key_blocks = dedupe.core.OrderedDict({})
blocker.tfIdfBlocks(data_d.iteritems())
for (record_id, record) in data_d.iteritems():
for key in blocker((record_id, record)):
blocks.setdefault(key, {}).update({record_id : record})
blocked_records = tuple(block for block in blocks.values())
return blocked_records
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Convenience functions for in memory deduplication
"""
import collections
import dedupe.core
def dataSample(data, sample_size):
'''Randomly sample pairs of records from a data dictionary'''
data_list = data.values()
random_pairs = dedupe.core.randomPairs(len(data_list), sample_size)
return tuple((data_list[k1], data_list[k2]) for k1, k2 in random_pairs)
def blockData(data_d, blocker):
blocks = dedupe.core.OrderedDict({})
record_blocks = dedupe.core.OrderedDict({})
key_blocks = dedupe.core.OrderedDict({})
blocker.tfIdfBlocks(data_d.iteritems())
for (record_id, record) in data_d.iteritems():
for key in blocker((record_id, record)):
blocks.setdefault(key, {}).update({record_id : record})
blocked_records = tuple(block for block in blocks.values())
return blocked_records
|
Improve tag handling in criteria
|
<?php
namespace Sellsy\Criteria\Generic;
use Sellsy\Criteria\CriteriaInterface;
use Sellsy\Models\SmartTags\TagInterface;
/**
* Class GetListCriteria
* @package Sellsy\Criteria\Generic
*/
abstract class GetListCriteria implements CriteriaInterface
{
/**
* @var array
*/
protected $tags;
/**
* @param string $tag
* @return $this
*/
public function addTag($tag)
{
if ($tag instanceof TagInterface) {
$tag = $tag->getName();
}
$this->tags[] = $tag;
return $this;
}
/**
* @param array $tags
* @return $this
*/
public function setTags(array $tags)
{
$this->clearTags();
foreach($tags as $tag) {
$this->addTag($tag);
}
return $this;
}
/**
* @return $this
*/
public function clearTags()
{
$this->tags = array();
return $this;
}
/**
* @return array
*/
public function getTags()
{
return $this->tags;
}
}
|
<?php
namespace Sellsy\Criteria\Generic;
use Sellsy\Criteria\CriteriaInterface;
/**
* Class GetListCriteria
* @package Sellsy\Criteria\Generic
*/
abstract class GetListCriteria implements CriteriaInterface
{
/**
* @var array
*/
protected $tags;
/**
* @param string $tag
* @return $this
*/
public function addTag($tag)
{
$this->tags[] = $tag;
return $this;
}
/**
* @param array $tags
* @return $this
*/
public function setTags(array $tags)
{
$this->tags = $tags;
return $this;
}
/**
* @return $this
*/
public function clearTags()
{
$this->tags = array();
return $this;
}
/**
* @return array
*/
public function getTags()
{
return $this->tags;
}
}
|
Migrate code for express 4.0
|
var express = require('express');
var less = require('less-middleware');
var path = require('path');
exports.register = function(application, params) {
params = params || {};
var prefix = params.prefix || '';
prefix = prefix.replace(/\/$/, '');
var topDirectory = path.join(__dirname, '..', '..', '..');
application.set('views', path.join(topDirectory, 'views'));
application.set('view engine', 'jade');
application.use(prefix, express.favicon());
application.use(prefix, express.bodyParser());
application.use(prefix, express.methodOverride());
application.use(prefix, less(path.join(topDirectory, 'public')));
application.use(prefix, express.static(path.join(topDirectory, 'public')));
var env = process.env.NODE_ENV || 'development';
if (env == 'development') {
application.use(prefix, express.errorHandler());
}
application.get(prefix + '/dashboard', function(request, response) {
response.render('index', { title: '', prefix: prefix });
});
}
|
var express = require('express');
var less = require('less-middleware');
var path = require('path');
exports.register = function(application, params) {
params = params || {};
var prefix = params.prefix || '';
prefix = prefix.replace(/\/$/, '');
var topDirectory = path.join(__dirname, '..', '..', '..');
application.configure(function(){
application.set('views', path.join(topDirectory, 'views'));
application.set('view engine', 'jade');
application.use(prefix, express.favicon());
application.use(prefix, express.bodyParser());
application.use(prefix, express.methodOverride());
application.use(prefix, less(path.join(topDirectory, 'public')));
application.use(prefix, express.static(path.join(topDirectory, 'public')));
});
application.configure('development', function() {
application.use(prefix, express.errorHandler());
});
application.get(prefix + '/dashboard', function(request, response) {
response.render('index', { title: '', prefix: prefix });
});
}
|
Stop use of almanac() and altazimuth() functions for now.
|
#!/usr/bin/env python
import ephem
from sr_lib import altazimuth, almanac, ha, ho
datelist = ['2016/01/12 18:00:00', '2016/01/12 19:00:00',
'2016/01/12 20:00:00', '2016/01/12 21:00:00']
jackson = ephem.Observer()
jackson.lat = '42.2458'
jackson.lon = '-84.4014'
jackson.pressure = 0
jackson.elevation = 303.9 # meters = 997 feet. Doesn't affect sun much.
ap = jackson.copy()
ap.lat = '42'
ap.lon = '-84'
for p in [jackson, ap]:
p.date = datelist[0]
s = ephem.Sun(p)
print "Hc", s.alt, "Z", s.az
hs_1 = ephem.degrees('26')
print "hs", hs_1
ha_1 = ha(hs_1, ephem.degrees('0:1.2'), 'on', 15)
print "ha", ha_1
ho_1 = ho(ha_1, ephem.Date(datelist[0]), 'LL')
print "ho", ho_1
|
#!/usr/bin/env python
import ephem
from sr_lib import altazimuth, almanac, ha, ho
datelist = ['2016/01/12 18:00:00', '2016/01/12 19:00:00',
'2016/01/12 20:00:00', '2016/01/12 21:00:00']
jackson = ephem.Observer()
jackson.lat = '42.2458'
jackson.lon = '-84.4014'
jackson.pressure = 0
jackson.elevation = 303.9 # meters = 997 feet. Doesn't affect sun much.
ap = jackson.copy()
ap.lat = '42'
ap.lon = '-84'
for p in [jackson, ap]:
p.date = datelist[1]
s = ephem.Sun(p)
al = almanac(p.date)
aa = altazimuth(al['gha'], al['dec'], p.lon, p.lat)
print "PyEphem Hc ", s.alt, " Z", s.az
print " almanac and altazimuth:", aa
hs_1 = ephem.degrees('26')
print "hs", hs_1
ha_1 = ha(hs_1, ephem.degrees('0:1.2'), 'on', 15)
print "ha", ha_1
ho_1 = ho(ha_1, ephem.Date(datelist[0]), 'LL')
print "ho", ho_1
|
Refactor entity effect undo control
|
package com.elmakers.mine.bukkit.api.block;
import java.util.List;
import com.elmakers.mine.bukkit.api.entity.EntityData;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import com.elmakers.mine.bukkit.api.magic.Mage;
public interface UndoList extends BlockList, Comparable<UndoList> {
public void commit();
public void undo();
public void setEntityUndo(boolean undoEntityEffects);
public void setScheduleUndo(int ttl);
public int getScheduledUndo();
public boolean bypass();
public long getCreatedTime();
public long getModifiedTime();
public long getScheduledTime();
public boolean isScheduled();
public void prune();
public void add(Entity entity);
public void remove(Entity entity);
public EntityData modify(Entity entity);
public void add(Runnable runnable);
public void convert(Entity entity, Block block);
public void fall(Entity entity, Block block);
public void explode(Entity entity, List<Block> explodedBlocks);
public void cancelExplosion(Entity entity);
public boolean contains(Location location, int threshold);
public String getName();
public Mage getOwner();
}
|
package com.elmakers.mine.bukkit.api.block;
import java.util.List;
import com.elmakers.mine.bukkit.api.entity.EntityData;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import com.elmakers.mine.bukkit.api.magic.Mage;
public interface UndoList extends BlockList, Comparable<UndoList> {
public void commit();
public void undo();
public void undo(boolean undoEntityChanges);
public void setScheduleUndo(int ttl);
public int getScheduledUndo();
public boolean bypass();
public long getCreatedTime();
public long getModifiedTime();
public long getScheduledTime();
public boolean isScheduled();
public void prune();
public void add(Entity entity);
public void remove(Entity entity);
public EntityData modify(Entity entity);
public void add(Runnable runnable);
public void convert(Entity entity, Block block);
public void fall(Entity entity, Block block);
public void explode(Entity entity, List<Block> explodedBlocks);
public void cancelExplosion(Entity entity);
public boolean contains(Location location, int threshold);
public String getName();
public Mage getOwner();
}
|
Add support for CSV output
|
package batchgcd
import (
"fmt"
"github.com/ncw/gmp"
)
type Collision struct {
Modulus *gmp.Int
P *gmp.Int
Q *gmp.Int
}
func (x Collision) HavePrivate() bool {
return x.P != nil || x.Q != nil
}
func (x Collision) String() string {
if x.HavePrivate() {
if x.P.Cmp(x.Q) < 0 {
return fmt.Sprintf("COLLISION: N=%x P=%x Q=%x", x.Modulus, x.P, x.Q)
} else {
return fmt.Sprintf("COLLISION: N=%x P=%x Q=%x", x.Modulus, x.Q, x.P)
}
} else {
return fmt.Sprintf("DUPLICATE: %x", x.Modulus)
}
}
func (x Collision) Test() bool {
if !x.HavePrivate() {
return true
}
n := gmp.NewInt(0)
n.Mul(x.P, x.Q)
return n.Cmp(x.Modulus) == 0
}
func (x Collision) Csv() string {
if x.P.Cmp(x.Q) < 0 {
return fmt.Sprintf("%x,%x,%x", x.Modulus, x.P, x.Q)
} else {
return fmt.Sprintf("%x,%x,%x", x.Modulus, x.Q, x.P)
}
}
|
package batchgcd
import (
"fmt"
"github.com/ncw/gmp"
)
type Collision struct {
Modulus *gmp.Int
P *gmp.Int
Q *gmp.Int
}
func (x Collision) HavePrivate() bool {
return x.P != nil || x.Q != nil
}
func (x Collision) String() string {
if x.HavePrivate() {
if x.P.Cmp(x.Q) < 0 {
return fmt.Sprintf("COLLISION: N=%x P=%x Q=%x", x.Modulus, x.P, x.Q)
} else {
return fmt.Sprintf("COLLISION: N=%x P=%x Q=%x", x.Modulus, x.Q, x.P)
}
} else {
return fmt.Sprintf("DUPLICATE: %x", x.Modulus)
}
}
func (x Collision) Test() bool {
if !x.HavePrivate() {
return true
}
n := gmp.NewInt(0)
n.Mul(x.P, x.Q)
return n.Cmp(x.Modulus) == 0
}
|
Add test for getting/setting default encoding in preferences
|
package net.sf.jabref;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.nio.charset.StandardCharsets;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JabRefPreferencesTest {
private JabRefPreferences prefs;
private JabRefPreferences backup;
@Before
public void setUp() {
prefs = JabRefPreferences.getInstance();
backup = prefs;
}
@Test
public void testPreferencesImport() throws JabRefException {
// the primary sort field has been changed to "editor" in this case
File importFile = new File("src/test/resources/net/sf/jabref/customPreferences.xml");
prefs.importPreferences(importFile.getAbsolutePath());
String expected = "editor";
String actual = prefs.get(JabRefPreferences.SAVE_PRIMARY_SORT_FIELD);
assertEquals(expected, actual);
}
@Test
public void getDefaultEncodingReturnsPreviouslyStoredEncoding() {
prefs.setDefaultEncoding(StandardCharsets.UTF_16BE);
assertEquals(StandardCharsets.UTF_16BE, prefs.getDefaultEncoding());
}
@After
public void tearDown() {
//clean up preferences to default state
prefs.overwritePreferences(backup);
}
}
|
package net.sf.jabref;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JabRefPreferencesTest {
private JabRefPreferences prefs;
private JabRefPreferences backup;
@Before
public void setUp() {
prefs = JabRefPreferences.getInstance();
backup = prefs;
}
@Test
public void testPreferencesImport() throws JabRefException {
// the primary sort field has been changed to "editor" in this case
File importFile = new File("src/test/resources/net/sf/jabref/customPreferences.xml");
prefs.importPreferences(importFile.getAbsolutePath());
String expected = "editor";
String actual = prefs.get(JabRefPreferences.SAVE_PRIMARY_SORT_FIELD);
assertEquals(expected, actual);
}
@After
public void tearDown() {
//clean up preferences to default state
prefs.overwritePreferences(backup);
}
}
|
Refactor API to a more readable form
|
import sublime_plugin
DEFAULT_NAME = 'Find Results'
ALT_NAME = 'Find Results '
class OpenSearchInNewTab(sublime_plugin.EventListener):
# set a bit changed name
# so the tab won't be bothered
# during new search
def on_activated(self, view):
if self.is_search_view(view):
self.apply_alt_name(view)
# these hooks will help other plugins
# to understand that we are in search results file
def on_text_command(self, view, command_name, args):
if self.is_search_view(view):
view.set_name(DEFAULT_NAME)
def post_text_command(self, view, command_name, args):
if self.is_search_view(view):
self.apply_alt_name(view)
def apply_alt_name(self, view):
view.set_name(ALT_NAME)
def is_search_view(self, view):
name = view.name()
return name == ALT_NAME or name == DEFAULT_NAME
|
import sublime_plugin
DEFAULT_NAME = 'Find Results'
ALT_NAME = 'Find Results '
class OpenSearchInNewTab(sublime_plugin.EventListener):
# set a bit changed name
# so the tab won't be bothered
# during new search
def on_activated(self, view):
if view.name() == DEFAULT_NAME:
view.set_name(ALT_NAME)
# these hooks will help other plugins
# to understand that we are in search results file
def on_text_command(self, view, command_name, args):
if view.name() == ALT_NAME:
view.set_name(DEFAULT_NAME)
def post_text_command(self, view, command_name, args):
if view.name() == DEFAULT_NAME:
view.set_name(ALT_NAME)
|
Fix length calculation in the exception path
|
/*
Copyright 2011 Frederic Langlet
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 kanzi.entropy;
import kanzi.EntropyDecoder;
import kanzi.BitStream;
import kanzi.BitStreamException;
public abstract class AbstractDecoder implements EntropyDecoder
{
@Override
public abstract byte decodeByte();
@Override
public abstract BitStream getBitStream();
// Default implementation: fallback to decodeByte
@Override
public int decode(byte[] array, int blkptr, int len)
{
if ((array == null) || (blkptr + len > array.length) || (blkptr < 0) || (len < 0))
return -1;
int end = blkptr + len;
int i = blkptr;
try
{
while (i < end)
array[i++] = this.decodeByte();
}
catch (BitStreamException e)
{
return i - blkptr;
}
return len;
}
@Override
public void dispose()
{
}
}
|
/*
Copyright 2011 Frederic Langlet
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 kanzi.entropy;
import kanzi.EntropyDecoder;
import kanzi.BitStream;
import kanzi.BitStreamException;
public abstract class AbstractDecoder implements EntropyDecoder
{
@Override
public abstract byte decodeByte();
@Override
public abstract BitStream getBitStream();
// Default implementation: fallback to decodeByte
@Override
public int decode(byte[] array, int blkptr, int len)
{
if ((array == null) || (blkptr + len > array.length) || (blkptr < 0) || (len < 0))
return -1;
int end = blkptr + len;
int i = blkptr;
try
{
while (i < end)
array[i++] = this.decodeByte();
}
catch (BitStreamException e)
{
return i;
}
return len;
}
@Override
public void dispose()
{
}
}
|
Use the globalization object we already collected.
|
function startModule() {
// Get locale from phonegap
var globalization = navigator.globalization;
if (globalization) {
globalization.getLocaleName(
function (locale) {
setLocale(locale.value);
},
function () {
console.log("Failed to get locale from phonegap. Using default.");
setLocale();
}
);
}
else {
setLocale();
}
var appView = new AppView({ el: $('#page-map') });
appView.render();
$('#page-map').trigger("pagecreate");
document.addEventListener("searchbutton", function () {
this.openSearchPopup(null);
}, false);
}
function setLocale(locale) {
var options = {
useCookie: false,
fallbackLng: 'en',
resGetPath: 'locales/__lng__.json',
getAsync: false
};
if (locale) {
options.locale = locale;
}
i18n.init(options);
}
|
function startModule() {
// Get locale from phonegap
var globalization = navigator.globalization;
if (globalization) {
navigator.globalization.getLocaleName(
function (locale) {
setLocale(locale.value);
},
function () {
console.log("Failed to get locale from phonegap. Using default.");
setLocale();
}
);
}
else {
setLocale();
}
var appView = new AppView({ el:$('#page-map') });
appView.render();
$('#page-map').trigger("pagecreate");
document.addEventListener("searchbutton", function () {
this.openSearchPopup(null);
}, false);
}
function setLocale(locale) {
var options = {
useCookie:false,
fallbackLng:'en',
resGetPath:'locales/__lng__.json',
getAsync:false
};
if (locale) {
options.locale = locale;
}
i18n.init(options);
}
|
Clear query on component unmount
|
import { PureComponent, createElement } from 'react';
import Proptypes from 'prop-types';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import AutocompleteSearchComponent from './autocomplete-search-component';
import actions from './autocomplete-search-actions';
import { getFilteredCountriesWithPath } from './autocomplete-search-selectors';
export { default as component } from './autocomplete-search-component';
export { initialState } from './autocomplete-search-reducers';
export { default as reducers } from './autocomplete-search-reducers';
export { default as styles } from './autocomplete-search-styles';
export { default as actions } from './autocomplete-search-actions';
const mapStateToProps = (state) => {
const { autocompleteSearch } = state;
return {
query: getQueryUpper(autocompleteSearch),
searchList: getFilteredCountriesWithPath(autocompleteSearch)
};
};
class AutocompleteSearchContainer extends PureComponent {
componentWillUnmount() {
this.props.setAutocompleteSearch('');
}
onOptionClick = (selected) => {
const { history } = this.props;
if (selected) {
history.push(`ndcs/${selected.value}`);
}
};
render() {
return createElement(AutocompleteSearchComponent, {
...this.props,
onOptionClick: this.onOptionClick
});
}
}
AutocompleteSearchContainer.propTypes = {
history: Proptypes.object,
setAutocompleteSearch: Proptypes.func.isRequired
};
export default withRouter(
connect(mapStateToProps, actions)(AutocompleteSearchContainer)
);
|
import { createElement } from 'react';
import Proptypes from 'prop-types';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { deburrUpper } from 'app/utils';
import AutocompleteSearchComponent from './autocomplete-search-component';
import actions from './autocomplete-search-actions';
import { getFilteredCountriesWithPath } from './autocomplete-search-selectors';
export { default as component } from './autocomplete-search-component';
export { initialState } from './autocomplete-search-reducers';
export { default as reducers } from './autocomplete-search-reducers';
export { default as styles } from './autocomplete-search-styles';
export { default as actions } from './autocomplete-search-actions';
const mapStateToProps = (state) => {
const { query } = state.autocompleteSearch;
return {
query: deburrUpper(query),
searchList: getFilteredCountriesWithPath(state.autocompleteSearch)
};
};
const AutocompleteSearchContainer = (props) => {
const onOptionClick = (selected) => {
const { history } = props;
if (selected) {
history.push(`ndcs/${selected.value}`);
}
};
return createElement(AutocompleteSearchComponent, {
...props,
onOptionClick
});
};
AutocompleteSearchContainer.propTypes = {
query: Proptypes.string,
history: Proptypes.object
};
export default withRouter(
connect(mapStateToProps, actions)(AutocompleteSearchContainer)
);
|
Fix for nullable author in blogpost factory
|
# -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa. If not, see <http://www.gnu.org/licenses/>.
from pybossa.model import db
from pybossa.model.blogpost import Blogpost
from . import BaseFactory, factory
class BlogpostFactory(BaseFactory):
FACTORY_FOR = Blogpost
id = factory.Sequence(lambda n: n)
title = u'Blogpost title'
body = u'Blogpost body text'
app = factory.SubFactory('factories.AppFactory')
app_id = factory.LazyAttribute(lambda blogpost: blogpost.app.id)
owner = factory.SelfAttribute('app.owner')
user_id = factory.LazyAttribute(
lambda blogpost: blogpost.owner.id if blogpost.owner else None)
|
# -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PyBossa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with PyBossa. If not, see <http://www.gnu.org/licenses/>.
from pybossa.model import db
from pybossa.model.blogpost import Blogpost
from . import BaseFactory, factory
class BlogpostFactory(BaseFactory):
FACTORY_FOR = Blogpost
id = factory.Sequence(lambda n: n)
title = u'Blogpost title'
body = u'Blogpost body text'
app = factory.SubFactory('factories.AppFactory')
app_id = factory.LazyAttribute(lambda blogpost: blogpost.app.id)
owner = factory.SelfAttribute('app.owner')
user_id = factory.LazyAttribute(lambda blogpost: blogpost.owner.id)
|
Add placeholder to attribute bindings
|
import Ember from 'ember';
const {
Component,
get
} = Ember;
export default Component.extend({
tagName: 'input',
type: 'text',
attributeBindings: [
'accept',
'autocomplete',
'autosave',
'dir',
'formaction',
'formenctype',
'formmethod',
'formnovalidate',
'formtarget',
'height',
'inputmode',
'lang',
'list',
'max',
'min',
'multiple',
'name',
'pattern',
'placeholder',
'size',
'step',
'type',
'value',
'width'
],
_sanitizedValue: undefined,
input() { this._handleChangeEvent(); },
change() { this._handleChangeEvent(); },
_handleChangeEvent() {
this._processNewValue.call(this, this.readDOMAttr('value'));
},
_processNewValue(rawValue) {
const value = this.sanitizeInput(rawValue);
if (this._sanitizedValue !== value) {
this._sanitizedValue = value;
this.attrs.update(value);
}
},
sanitizeInput(input) {
return input;
},
didReceiveAttrs() {
this._super(...arguments);
if (!this.attrs.update) {
throw new Error(`You must provide an \`update\` action to \`{{${this.templateName}}}\`.`);
}
this._processNewValue.call(this, get(this, 'value'));
}
});
|
import Ember from 'ember';
const {
Component,
get
} = Ember;
export default Component.extend({
tagName: 'input',
type: 'text',
attributeBindings: [
'accept',
'autocomplete',
'autosave',
'dir',
'formaction',
'formenctype',
'formmethod',
'formnovalidate',
'formtarget',
'height',
'inputmode',
'lang',
'list',
'max',
'min',
'multiple',
'name',
'pattern',
'size',
'step',
'type',
'value',
'width'
],
_sanitizedValue: undefined,
input() { this._handleChangeEvent(); },
change() { this._handleChangeEvent(); },
_handleChangeEvent() {
this._processNewValue.call(this, this.readDOMAttr('value'));
},
_processNewValue(rawValue) {
const value = this.sanitizeInput(rawValue);
if (this._sanitizedValue !== value) {
this._sanitizedValue = value;
this.attrs.update(value);
}
},
sanitizeInput(input) {
return input;
},
didReceiveAttrs() {
this._super(...arguments);
if (!this.attrs.update) {
throw new Error(`You must provide an \`update\` action to \`{{${this.templateName}}}\`.`);
}
this._processNewValue.call(this, get(this, 'value'));
}
});
|
Order map by modified_at desc in list
|
from django.views.generic import TemplateView
from chickpea.models import Map
class Home(TemplateView):
template_name = "youmap/home.html"
list_template_name = "chickpea/map_list.html"
def get_context_data(self, **kwargs):
maps = Map.objects.order_by('-modified_at')[:100]
return {
"maps": maps
}
def get_template_names(self):
"""
Dispatch template according to the kind of request: ajax or normal.
"""
if self.request.is_ajax():
return [self.list_template_name]
else:
return [self.template_name]
home = Home.as_view()
|
from django.views.generic import TemplateView
from chickpea.models import Map
class Home(TemplateView):
template_name = "youmap/home.html"
list_template_name = "chickpea/map_list.html"
def get_context_data(self, **kwargs):
maps = Map.objects.all()[:100]
return {
"maps": maps
}
def get_template_names(self):
"""
Dispatch template according to the kind of request: ajax or normal.
"""
if self.request.is_ajax():
return [self.list_template_name]
else:
return [self.template_name]
home = Home.as_view()
|
Add Context parameter to onCardDelete to match SDK
|
package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.content.Context;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;
/**
* An extension of CmHomeCardChangeReceiver, that implements the callback for
* when a card is deleted.
*/
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
public static final String TAG = "CardDeletedBroadcastReceiver";
@Override
protected void onCardDeleted(Context context, DataCard.CardDeletedInfo cardDeletedInfo) {
Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
+ ", internalID: " + cardDeletedInfo.getInternalId()
+ ", authority: " + cardDeletedInfo.getAuthority()
+ ", globalID: " + cardDeletedInfo.getGlobalId()); }
}
|
package org.cyanogenmod.launcher.home.api.sdkexample.receiver;
import android.util.Log;
import org.cyanogenmod.launcher.home.api.cards.DataCard;
import org.cyanogenmod.launcher.home.api.receiver.CmHomeCardChangeReceiver;
/**
* An extension of CmHomeCardChangeReceiver, that implements the callback for
* when a card is deleted.
*/
public class CardDeletedBroadcastReceiver extends CmHomeCardChangeReceiver{
public static final String TAG = "CardDeletedBroadcastReceiver";
@Override
protected void onCardDeleted(DataCard.CardDeletedInfo cardDeletedInfo) {
Log.i(TAG, "CM Home API card was deleted: id: " + cardDeletedInfo.getId()
+ ", internalID: " + cardDeletedInfo.getInternalId()
+ ", authority: " + cardDeletedInfo.getAuthority()
+ ", globalID: " + cardDeletedInfo.getGlobalId());
}
}
|
Update IIFE to reference window directly
When using this polyfill as an ES2015 module (with a tool such as Rollup), it receives this error:
```
node_modules\window.requestanimationframe\requestanimationframe.js (49:2) The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten
```
This resolves the code to work as intended.
See https://github.com/rollup/rollup/wiki/Troubleshooting#this-is-undefined for more details
|
/**
* requestAnimationFrame polyfill v1.0.0
* requires Date.now
*
* © Polyfiller 2015
* Released under the MIT license
* github.com/Polyfiller/requestAnimationFrame
*/
window.requestAnimationFrame || function (window) {
'use strict';
window.requestAnimationFrame = window.msRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| function () {
var fps = 60;
var delay = 1000 / fps;
var animationStartTime = Date.now();
var previousCallTime = animationStartTime;
return function requestAnimationFrame(callback) {
var requestTime = Date.now();
var timeout = Math.max(0, delay - (requestTime - previousCallTime));
var timeToCall = requestTime + timeout;
previousCallTime = timeToCall;
return window.setTimeout(function onAnimationFrame() {
callback(timeToCall - animationStartTime);
}, timeout);
};
}();
window.cancelAnimationFrame = window.mozCancelAnimationFrame
|| window.webkitCancelAnimationFrame
|| window.cancelRequestAnimationFrame
|| window.msCancelRequestAnimationFrame
|| window.mozCancelRequestAnimationFrame
|| window.webkitCancelRequestAnimationFrame
|| function cancelAnimationFrame(id) {
window.clearTimeout(id);
};
}(window);
|
/**
* requestAnimationFrame polyfill v1.0.0
* requires Date.now
*
* © Polyfiller 2015
* Released under the MIT license
* github.com/Polyfiller/requestAnimationFrame
*/
window.requestAnimationFrame || function (window) {
'use strict';
window.requestAnimationFrame = window.msRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| function () {
var fps = 60;
var delay = 1000 / fps;
var animationStartTime = Date.now();
var previousCallTime = animationStartTime;
return function requestAnimationFrame(callback) {
var requestTime = Date.now();
var timeout = Math.max(0, delay - (requestTime - previousCallTime));
var timeToCall = requestTime + timeout;
previousCallTime = timeToCall;
return window.setTimeout(function onAnimationFrame() {
callback(timeToCall - animationStartTime);
}, timeout);
};
}();
window.cancelAnimationFrame = window.mozCancelAnimationFrame
|| window.webkitCancelAnimationFrame
|| window.cancelRequestAnimationFrame
|| window.msCancelRequestAnimationFrame
|| window.mozCancelRequestAnimationFrame
|| window.webkitCancelRequestAnimationFrame
|| function cancelAnimationFrame(id) {
window.clearTimeout(id);
};
}(this);
|
Fix bug in unit tests
|
import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
class TestOptionalParameters(unittest.TestCase):
def test_invalid_mode(self):
"""
Tests the is_valid_mode function for an invalid input
"""
with self.assertRaises(InvalidModeError):
requester.set_mode("flying")
def test_invalid_alternative(self):
"""
Tests for error handling when an invalid value is provided to
the set_alternative function
"""
with self.assertRaises(InvalidAlternativeError):
requester.set_alternatives('False')
class TestAPIKey(unittest.TestCase):
def test_invalid_api_key(self):
invalid_key = 123456
with self.assertRaises(InvalidAPIKeyError):
requester.set_api_key(invalid_key)
if __name__ == '__main__':
unittest.main()
|
import unittest
from pydirections.route_requester import DirectionsRequest
from pydirections.exceptions import InvalidModeError, InvalidAPIKeyError, InvalidAlternativeError
class TestOptionalParameters(unittest.TestCase):
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
def test_invalid_mode(self):
"""
Tests the is_valid_mode function for an invalid input
"""
with self.assertRaises(InvalidModeError):
requester.set_mode("flying")
def test_invalid_alternative(self):
"""
Tests for error handling when an invalid value is provided to
the set_alternative function
"""
with self.assertRaises(InvalidAlternativeError):
requester.set_alternatives('False')
class TestAPIKey(unittest.TestCase):
requester = DirectionsRequest(origin="San Francisco, CA", destination="Palo Alto, CA")
def test_invalid_api_key(self):
invalid_key = 123456
with self.assertRaises(InvalidAPIKeyError):
requester.set_api_key(invalid_key)
if __name__ == '__main__':
unittest.main()
|
Upgrade type and click versions
|
#!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.6',
'botocore>=1.4.8,<2.0.0',
'virtualenv>=15.0.0,<16.0.0',
'typing==3.5.3.0',
]
setup(
name='chalice',
version='0.5.0',
description="Microframework",
long_description=README,
author="James Saryerwinnie",
author_email='js@jamesls.com',
url='https://github.com/jamesls/chalice',
packages=find_packages(exclude=['tests']),
install_requires=install_requires,
license="Apache License 2.0",
package_data={'chalice': ['*.json']},
include_package_data=True,
zip_safe=False,
keywords='chalice',
entry_points={
'console_scripts': [
'chalice = chalice.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
],
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
README = readme_file.read()
install_requires = [
'click==6.2',
'botocore>=1.4.8,<2.0.0',
'virtualenv>=15.0.0,<16.0.0',
'typing==3.5.2.2',
]
setup(
name='chalice',
version='0.5.0',
description="Microframework",
long_description=README,
author="James Saryerwinnie",
author_email='js@jamesls.com',
url='https://github.com/jamesls/chalice',
packages=find_packages(exclude=['tests']),
install_requires=install_requires,
license="Apache License 2.0",
package_data={'chalice': ['*.json']},
include_package_data=True,
zip_safe=False,
keywords='chalice',
entry_points={
'console_scripts': [
'chalice = chalice.cli:main',
]
},
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
],
)
|
Fix bug in 'pure' due to operator precedence
|
<?php
namespace Phunkie\Functions\applicative;
use Phunkie\Cats\Applicative;
use Phunkie\Cats\Apply;
use function Phunkie\Functions\currying\applyPartially;
use Phunkie\Types\Kind;
/**
* F<A -> B> -> F<A> -> F<B>
*/
const ap = "\\Phunkie\\Functions\\applicative\\ap";
function ap(Kind $f)
{
return applyPartially([$f],func_get_args(),function(Applicative $applicative) use ($f) {
return $applicative->apply($f);
});
}
const pure = "\\Phunkie\\Functions\\applicative\\pure";
function pure($context)
{
return applyPartially([$context],func_get_args(),function($a) use ($context) {
if (($fa = $context($a)) instanceof Applicative) {
return $fa;
}
throw new \Error("$context is not an applicative context");
});
}
const map2 = "\\Phunkie\\Functions\\applicative\\map2";
function map2(callable $f)
{
return applyPartially([$f],func_get_args(), function(Apply $fa) use ($f) {
return function(Apply $fb) use ($fa, $f) {
return $fa->map2($fb, $f);
};
});
}
|
<?php
namespace Phunkie\Functions\applicative;
use Phunkie\Cats\Applicative;
use Phunkie\Cats\Apply;
use function Phunkie\Functions\currying\applyPartially;
use Phunkie\Types\Kind;
/**
* F<A -> B> -> F<A> -> F<B>
*/
const ap = "\\Phunkie\\Functions\\applicative\\ap";
function ap(Kind $f)
{
return applyPartially([$f],func_get_args(),function(Applicative $applicative) use ($f) {
return $applicative->apply($f);
});
}
const pure = "\\Phunkie\\Functions\\applicative\\pure";
function pure($context)
{
return applyPartially([$context],func_get_args(),function($a) use ($context) {
if ($fa = $context($a) instanceof Applicative) {
return $fa;
}
throw new \Error("$context is not an applicative context");
});
}
const map2 = "\\Phunkie\\Functions\\applicative\\map2";
function map2(callable $f)
{
return applyPartially([$f],func_get_args(), function(Apply $fa) use ($f) {
return function(Apply $fb) use ($fa, $f) {
return $fa->map2($fb, $f);
};
});
}
|
Update factory-boy's .generate to evaluate
Co-Authored-By: Timo Halbesma <98c2d5a1e48c998bd9ba9dbc53d6857beae1c9bd@halbesma.com>
|
from typing import Any, Sequence
from django.contrib.auth import get_user_model
from factory import Faker, post_generation
from factory.django import DjangoModelFactory
class UserFactory(DjangoModelFactory):
username = Faker("user_name")
email = Faker("email")
name = Faker("name")
@post_generation
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
password = (
extracted
if extracted
else Faker(
"password",
length=42,
special_chars=True,
digits=True,
upper_case=True,
lower_case=True,
).evaluate(None, None, extra={"locale": None})
)
self.set_password(password)
class Meta:
model = get_user_model()
django_get_or_create = ["username"]
|
from typing import Any, Sequence
from django.contrib.auth import get_user_model
from factory import Faker, post_generation
from factory.django import DjangoModelFactory
class UserFactory(DjangoModelFactory):
username = Faker("user_name")
email = Faker("email")
name = Faker("name")
@post_generation
def password(self, create: bool, extracted: Sequence[Any], **kwargs):
password = (
extracted
if extracted
else Faker(
"password",
length=42,
special_chars=True,
digits=True,
upper_case=True,
lower_case=True,
).generate(params={"locale": None})
)
self.set_password(password)
class Meta:
model = get_user_model()
django_get_or_create = ["username"]
|
Add new test domains for our test google suite instances
|
function (user, context, callback) {
if (!user) {
// If the user is not presented (i.e. a rule deleted it), just go on, since authenticate will always fail.
return callback(null, null, context);
}
if (context.clientID !== 'q0tFB9QyFIKqPOOKvkFnHMj2VwrLjX46') return callback(null, user, context); // Google (test.mozilla.com)
// This rule simply remaps @mozilla.com e-mail addresses to @test.mozilla.com to be used with the test.mozilla.com GSuite domain.
// Be careful when adding replacements not to do "double-replacements" where a replace replaces another rule. If that happens,
// you probably want to improve this code instead
user.myemail = user.email.replace("mozilla.com", "test.mozilla.com");
user.myemail = user.email.replace("mozillafoundation.org", "test.mozillafoundation.org");
user.myemail = user.email.replace("getpocket.com", "test-gsuite.getpocket.com");
context.samlConfiguration = context.samlConfiguration || {};
context.samlConfiguration.mappings = {
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "myemail",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "myemail",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email": "myemail",
};
context.samlConfiguration.nameIdentifierFormat = "urn:oasis:names:tc:SAML:2.0:nameid-format:email";
callback(null, user, context);
}
|
function (user, context, callback) {
if (!user) {
// If the user is not presented (i.e. a rule deleted it), just go on, since authenticate will always fail.
return callback(null, null, context);
}
if (context.clientID !== 'q0tFB9QyFIKqPOOKvkFnHMj2VwrLjX46') return callback(null, user, context); // Google (test.mozilla.com)
// This rule simply remaps @mozilla.com e-mail addresses to @test.mozilla.com to be used with the test.mozilla.com GSuite domain.
user.myemail = user.email.replace("mozilla.com", "test.mozilla.com");
context.samlConfiguration = context.samlConfiguration || {};
context.samlConfiguration.mappings = {
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier": "myemail",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "myemail",
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email": "myemail",
};
context.samlConfiguration.nameIdentifierFormat = "urn:oasis:names:tc:SAML:2.0:nameid-format:email";
callback(null, user, context);
}
|
Refactor equality function and add less function
|
package checkers
import (
"fmt"
"math"
)
type Point struct {
X, Y int
}
func (p Point) Add(q Point) Point {
return Point{p.X + q.X, p.Y + q.Y}
}
func (p Point) Sub(q Point) Point {
return Point{p.X - q.X, p.Y - q.Y}
}
func (p Point) Equal(q Point) bool {
return p.X == q.X && p.Y == q.Y
}
func (p Point) Less(q Point) bool {
return p.X < q.X || (p.Y < q.Y && p.X == q.X)
}
func (p Point) String() string {
return fmt.Sprintf("(%d,%d)", p.X, p.Y)
}
func (p Point) Manhattan() int {
return int(math.Abs(float64(0-p.X)) + math.Abs(float64(0-p.Y)))
}
func (p Point) ManhattanTo(q Point) int {
return int(math.Abs(float64(p.X-q.X)) + math.Abs(float64(p.Y-q.Y)))
}
func (p *Point) Scale(factor int) *Point {
p.X *= factor
p.Y *= factor
return p
}
func (p Point) Scaled(factor int) Point {
return Point{p.X * factor, p.Y * factor}
}
|
package checkers
import (
"fmt"
"math"
)
type Point struct {
X, Y int
}
func (p Point) Add(q Point) Point {
return Point{p.X + q.X, p.Y + q.Y}
}
func (p Point) Sub(q Point) Point {
return Point{p.X - q.X, p.Y - q.Y}
}
func (p Point) Equal(q Point) bool {
if p.X == q.X && p.Y == q.Y {
return true
}
return false
}
func (p Point) String() string {
return fmt.Sprintf("(%d,%d)", p.X, p.Y)
}
func (p Point) Manhattan() int {
return int(math.Abs(float64(0-p.X)) + math.Abs(float64(0-p.Y)))
}
func (p Point) ManhattanTo(q Point) int {
return int(math.Abs(float64(p.X-q.X)) + math.Abs(float64(p.Y-q.Y)))
}
func (p *Point) Scale(factor int) *Point {
p.X *= factor
p.Y *= factor
return p
}
func (p Point) Scaled(factor int) Point {
return Point{p.X * factor, p.Y * factor}
}
|
Use JSON for API GET /auth/test response
|
# Copyright (C) 2016 University of Zurich. All rights reserved.
#
# This file is part of MSRegistry Backend.
#
# MSRegistry Backend is free software: you can redistribute it and/or
# modify it under the terms of the version 3 of the GNU Affero General
# Public License as published by the Free Software Foundation, or any
# other later version.
#
# MSRegistry Backend is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the version
# 3 of the GNU Affero General Public License for more details.
#
# You should have received a copy of the version 3 of the GNU Affero
# General Public License along with MSRegistry Backend. If not, see
# <http://www.gnu.org/licenses/>.
__author__ = "Filippo Panessa <filippo.panessa@uzh.ch>"
__copyright__ = ("Copyright (c) 2016 S3IT, Zentrale Informatik,"
" University of Zurich")
from flask import jsonify
from . import auth
from ..decorators import requires_auth
@auth.route('/test')
@requires_auth
def authTest():
return jsonify({'code': 'authorization_success',
'description': "All good. You only get this message if you're authenticated."})
|
# Copyright (C) 2016 University of Zurich. All rights reserved.
#
# This file is part of MSRegistry Backend.
#
# MSRegistry Backend is free software: you can redistribute it and/or
# modify it under the terms of the version 3 of the GNU Affero General
# Public License as published by the Free Software Foundation, or any
# other later version.
#
# MSRegistry Backend is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the version
# 3 of the GNU Affero General Public License for more details.
#
# You should have received a copy of the version 3 of the GNU Affero
# General Public License along with MSRegistry Backend. If not, see
# <http://www.gnu.org/licenses/>.
__author__ = "Filippo Panessa <filippo.panessa@uzh.ch>"
__copyright__ = ("Copyright (c) 2016 S3IT, Zentrale Informatik,"
" University of Zurich")
from . import auth
from ..decorators import requires_auth
@auth.route('/test')
@requires_auth
def authTest():
return "All good. You only get this message if you're authenticated."
|
Prepare for Hapi 6 migration.
|
// Load modules
var Fs = require('fs');
var Path = require('path');
var HeapDump = require('heapdump');
var Hoek = require('hoek');
// Declare internals
var internals = {
initialized: false,
defaults: {
logPath: Path.join(__dirname, '..', 'poop.log')
}
};
exports.register = function (plugin, options, next) {
if (internals.initialized) {
return next();
}
internals.initialized = true;
var settings = Hoek.applyToDefaults(internals.defaults, options || {});
process.once('uncaughtException', function (err) {
HeapDump.writeSnapshot();
var log = Fs.createWriteStream(settings.logPath);
var formattedErr = {
message: err.message,
stack: err.stack,
timestamp: Date.now()
};
log.write(JSON.stringify(formattedErr), function () {
log.end();
process.exit(1);
});
});
process.on('SIGUSR1', function () {
HeapDump.writeSnapshot();
});
return next();
};
exports.register.attributes = {
pkg: require('../package.json')
};
|
// Load modules
var Fs = require('fs');
var Path = require('path');
var HeapDump = require('heapdump');
var Hoek = require('hoek');
// Declare internals
var internals = {
initialized: false,
defaults: {
logPath: Path.join(__dirname, '..', 'poop.log')
}
};
exports.register = function (plugin, options, next) {
if (internals.initialized) {
return next();
}
internals.initialized = true;
var settings = Hoek.applyToDefaults(internals.defaults, options || {});
process.once('uncaughtException', function (err) {
HeapDump.writeSnapshot();
var log = Fs.createWriteStream(settings.logPath);
var formattedErr = {
message: err.message,
stack: err.stack,
timestamp: Date.now()
};
log.write(JSON.stringify(formattedErr), function () {
log.end();
process.exit(1);
});
});
process.on('SIGUSR1', function () {
HeapDump.writeSnapshot();
});
return next();
};
|
Change url in dashboard administrador
|
from django.conf.urls import url
from .views import admin_main_dashboard, admin_users_dashboard, \
admin_users_create, admin_users_edit, admin_users_edit_form, \
admin_users_delete_modal, admin_users_delete, list_studies
app_name = 'administracion'
# Urls en espanol
urlpatterns = [
url(r'^principal/$', admin_main_dashboard, name='main'),
url(r'^usuarios/nuevo/', admin_users_create, name='users_add'),
url(r'^usuarios/editar/(\d+)/', admin_users_edit_form, name='users_edit_form'),
url(r'^usuarios/editar/guardar/', admin_users_edit, name='users_edit'),
url(r'^usuarios/borrar/(\d+)/', admin_users_delete_modal, name='users_delete_modal'),
url(r'^usuarios/borrar/confirmar/', admin_users_delete, name='users_delete'),
url(r'^usuarios/', admin_users_dashboard, name='users'),
url(r'^principal/(?P<status_study>[\w\-]+)/$', list_studies, name='main_estudios'),
]
|
from django.conf.urls import url
from .views import admin_main_dashboard, admin_users_dashboard, \
admin_users_create, admin_users_edit, admin_users_edit_form, \
admin_users_delete_modal, admin_users_delete, list_studies
app_name = 'administracion'
# Urls en espanol
urlpatterns = [
url(r'^principal/', admin_main_dashboard, name='main'),
url(r'^usuarios/nuevo/', admin_users_create, name='users_add'),
url(r'^usuarios/editar/(\d+)/', admin_users_edit_form, name='users_edit_form'),
url(r'^usuarios/editar/guardar/', admin_users_edit, name='users_edit'),
url(r'^usuarios/borrar/(\d+)/', admin_users_delete_modal, name='users_delete_modal'),
url(r'^usuarios/borrar/confirmar/', admin_users_delete, name='users_delete'),
url(r'^usuarios/', admin_users_dashboard, name='users'),
url(r'^principal/(?P<status_study>[\w\-]+)/$', list_studies, name='main_estudios'),
]
|
Expand the review if the user's at least entered a rating.
|
import template from './item-review.html';
import './item-review.scss';
function ItemReviewController($rootScope, dimSettingsService) {
'ngInject';
const vm = this;
vm.canReview = dimSettingsService.allowIdPostToDtr;
vm.submitted = false;
vm.hasUserReview = vm.item.userRating;
vm.expandReview = vm.hasUserReview;
vm.procon = false; // TODO: turn this back on..
vm.aggregate = {
pros: ['fast', 'lol'],
cons: ['ok']
};
// vm.item.writtenReviews.forEach((review) => {
// aggregate.pros.push(review.pros);
// aggregate.cons.push(review.cons);
// });
vm.toggleEdit = function() {
vm.expandReview = !vm.expandReview;
};
vm.submitReview = function() {
$rootScope.$broadcast('review-submitted', vm.item);
vm.expandReview = false;
vm.submitted = true;
};
vm.setRating = function(rating) {
if (rating) {
vm.item.userRating = rating;
}
vm.expandReview = true;
};
}
export const ItemReviewComponent = {
bindings: {
item: '<'
},
controller: ItemReviewController,
template: template
};
|
import template from './item-review.html';
import './item-review.scss';
function ItemReviewController($rootScope, dimSettingsService) {
'ngInject';
const vm = this;
vm.canReview = dimSettingsService.allowIdPostToDtr;
vm.expandReview = false;
vm.submitted = false;
vm.hasUserReview = vm.item.userRating;
vm.procon = false; // TODO: turn this back on..
vm.aggregate = {
pros: ['fast', 'lol'],
cons: ['ok']
};
// vm.item.writtenReviews.forEach((review) => {
// aggregate.pros.push(review.pros);
// aggregate.cons.push(review.cons);
// });
vm.toggleEdit = function() {
vm.expandReview = !vm.expandReview;
};
vm.submitReview = function() {
$rootScope.$broadcast('review-submitted', vm.item);
vm.expandReview = false;
vm.submitted = true;
};
vm.setRating = function(rating) {
if (rating) {
vm.item.userRating = rating;
}
vm.expandReview = true;
};
}
export const ItemReviewComponent = {
bindings: {
item: '<'
},
controller: ItemReviewController,
template: template
};
|
Update sendEvent function to force passing undefined if metadata is empty.
|
/**
* Analytics advanced tracking script to be inserted into the frontend via PHP.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
// This file should not use any dependencies because it is used in the frontend.
/**
* Internal dependencies
*/
import setUpAdvancedTracking from './analytics-advanced-tracking/set-up-advanced-tracking';
/**
* Sends a tracking event to Analytics via gtag.
*
* @since 1.18.0
*
* @param {string} action Event action / event name.
* @param {Object} metadata Additional event metadata to send, or `null`.
*/
function sendEvent( action, metadata ) {
window.gtag( 'event', action, metadata || undefined ); // eslint-disable-line no-restricted-globals
}
const events = window._googlesitekitAnalyticsTrackingData || []; // eslint-disable-line no-restricted-globals
if ( Array.isArray( events ) ) {
setUpAdvancedTracking( events, sendEvent );
}
|
/**
* Analytics advanced tracking script to be inserted into the frontend via PHP.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
// This file should not use any dependencies because it is used in the frontend.
/**
* Internal dependencies
*/
import setUpAdvancedTracking from './analytics-advanced-tracking/set-up-advanced-tracking';
/**
* Sends a tracking event to Analytics via gtag.
*
* @since 1.18.0
*
* @param {string} action Event action / event name.
* @param {Object} metadata Additional event metadata to send, or `null`.
*/
function sendEvent( action, metadata ) {
/* eslint-disable no-restricted-globals */
if ( window.gtag ) {
window.gtag( 'event', action, metadata );
}
/* eslint-enable */
}
const events = window._googlesitekitAnalyticsTrackingData || []; // eslint-disable-line no-restricted-globals
if ( Array.isArray( events ) ) {
setUpAdvancedTracking( events, sendEvent );
}
|
Update implementation as per spec
|
import { randomBytes } from 'crypto';
// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
function strongRandomNumber() {
return randomBytes(4).readUInt32LE() / 0xFFFFFFFF
}
function encodeTime(now, len) {
let arr = []
for (let x = len; x > 0; x--) {
let mod = now % ENCODING.length
arr[x] = ENCODING.charAt(mod)
now = (now - mod) / ENCODING.length
}
return arr
}
function encodeRandom(len) {
let arr = []
for (let x = len; x > 0; x--) {
let rando = Math.floor(ENCODING.length * strongRandomNumber())
arr[x] = ENCODING.charAt(rando)
}
return arr
}
function ulid() {
return []
.concat(encodeTime(Date.now(), 10))
.concat(encodeRandom(16))
.join('')
}
export {
strongRandomNumber,
encodeTime,
encodeRandom
}
export default ulid
|
// Crockford's Base32
// https://en.wikipedia.org/wiki/Base32
const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
if (ENCODING.length !== 32) throw new Error('ENCODING')
// Current Version of SUID
const VERSION = 1
function encodeVersion() {
if (VERSION >= 16) throw new Error('VERSION')
return VERSION.toString(16)
}
function encodeTime(len) {
let now = Date.now()
let arr = []
for (let x = len; x > 0; x--) {
let mod = now % ENCODING.length
arr[x] = ENCODING.charAt(mod)
now = (now - mod) / ENCODING.length
}
return arr
}
function encodeRandom(len) {
let arr = []
for (let x = len; x > 0; x--) {
let rando = Math.floor(ENCODING.length * Math.random())
arr[x] = ENCODING.charAt(rando)
}
return arr
}
function fixedChar() {
return "F"
}
function ulid() {
return []
.concat(encodeTime(10))
.concat(encodeRandom(16))
.join('')
+ fixedChar()
+ encodeVersion()
}
export default ulid
|
fix(api): Fix formatting of API error message
|
from __future__ import absolute_import
from rest_framework import serializers
from sentry.utils.http import parse_uri_match
class OriginField(serializers.CharField):
# Special case origins that don't fit the normal regex pattern, but are valid
WHITELIST_ORIGINS = ('*')
def from_native(self, data):
rv = super(OriginField, self).from_native(data)
if not rv:
return
if not self.is_valid_origin(rv):
raise serializers.ValidationError('%s is not an acceptable domain' % rv)
return rv
def is_valid_origin(self, value):
if value in self.WHITELIST_ORIGINS:
return True
bits = parse_uri_match(value)
# ports are not supported on matching expressions (yet)
if ':' in bits.domain:
return False
return True
|
from __future__ import absolute_import
from rest_framework import serializers
from sentry.utils.http import parse_uri_match
class OriginField(serializers.CharField):
# Special case origins that don't fit the normal regex pattern, but are valid
WHITELIST_ORIGINS = ('*')
def from_native(self, data):
rv = super(OriginField, self).from_native(data)
if not rv:
return
if not self.is_valid_origin(rv):
raise serializers.ValidationError('%r is not an acceptable domain' % rv)
return rv
def is_valid_origin(self, value):
if value in self.WHITELIST_ORIGINS:
return True
bits = parse_uri_match(value)
# ports are not supported on matching expressions (yet)
if ':' in bits.domain:
return False
return True
|
Fix utf-8 encoding error when saving the file.
|
#!/usr/bin/env python
from appkit.api.v0_2_8 import App
from flask import render_template, request
import os
import sys
import codecs
app = App(__name__)
try:
file_name = sys.argv[1]
if not os.path.exists(file_name):
open(file_name, 'w').close()
except:
file_name = None
app.file_name = file_name
print(app.file_name)
@app.route('/')
def index():
markdown = None
if app.file_name is not None:
markdown = codecs.open(file_name, 'r', 'utf-8').read()
return render_template(
'/ui.html',
file_name=app.file_name,
text=markdown)
@app.route('/save/', methods=['POST',])
def save():
"""save markdown content to the file"""
file_name = request.form.get('file', None)
text = request.form.get('text', None)
f = codecs.open(file_name, 'w', encoding='utf-8')
f.write(text)
f.close()
return 'Saved'
app.debug = True
app.run()
|
#!/usr/bin/env python
from appkit.api.v0_2_8 import App
from flask import render_template, request
import os
import sys
import codecs
app = App(__name__)
try:
file_name = sys.argv[1]
if not os.path.exists(file_name):
open(file_name, 'w').close()
except:
file_name = None
app.file_name = file_name
print(app.file_name)
@app.route('/')
def index():
markdown = None
if app.file_name is not None:
markdown = codecs.open(file_name, 'r', 'utf-8').read()
return render_template(
'/ui.html',
file_name=app.file_name,
text=markdown)
@app.route('/save/', methods=['POST',])
def save():
"""save markdown content to the file"""
file_name = request.form.get('file', None)
text = request.form.get('text', None)
f = open(file_name, 'w')
f.write(text)
f.close()
return 'Saved'
if __name__ == '__main__':
app.run()
|
Update before/after to be proper pseudo-elements.
|
/**
* Storybook main config.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = {
stories: [ '../stories/**/*.stories.js', '../assets/js/**/*.stories.js' ],
addons: [ '@storybook/addon-viewport', '@storybook/addon-postcss' ],
previewHead: ( head ) => {
if ( ! process.env.VRT ) {
return head;
}
return `${ head }
<style>
#root *,
#root *::before,
#root *::after {
animation-duration: 0ms !important;
transition-duration: 0ms !important;
}
</style>
`;
},
};
|
/**
* Storybook main config.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = {
stories: [ '../stories/**/*.stories.js', '../assets/js/**/*.stories.js' ],
addons: [ '@storybook/addon-viewport', '@storybook/addon-postcss' ],
previewHead: ( head ) => {
if ( ! process.env.VRT ) {
return head;
}
return `${ head }
<style>
#root *,
#root *:before,
#root *:after {
animation-duration: 0ms !important;
transition-duration: 0ms !important;
}
</style>
`;
},
};
|
Remove download URL since Github doesn't get his act together. Damnit
git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f
committer: leidel <leidel@12edf5ea-513a-0410-8a8c-37067077e60f>
--HG--
extra : convert_revision : aa256d6eb94fc5492608373969ed7c5826b2077a
|
from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://code.google.com/p/django-robots/',
packages=['robots'],
package_dir={'dbtemplates': 'dbtemplates'},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://code.google.com/p/django-robots/',
download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4',
packages=['robots'],
package_dir={'dbtemplates': 'dbtemplates'},
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
|
Add comments to HTTPError interface
This can be very confusing potentially
|
package errors
import "fmt"
type HttpError interface {
error
StatusCode() int // actual HTTP status code
ErrorCode() string // error code returned in response body from CC or UAA
Headers() string // see: known_error_codes.go
Body() string
}
type httpError struct {
statusCode int
headers string
body string
code string
description string
}
type HttpNotFoundError struct {
*httpError
}
func NewHttpError(statusCode int, header string, body string, code string, description string) HttpError {
err := httpError{
statusCode: statusCode,
headers: header,
body: body,
code: code,
description: description,
}
switch statusCode {
case 404:
return HttpNotFoundError{&err}
default:
return &err
}
}
func (err *httpError) StatusCode() int {
return err.statusCode
}
func (err *httpError) Headers() string {
return err.headers
}
func (err *httpError) Body() string {
return err.body
}
func (err *httpError) Error() string {
return fmt.Sprintf(
"Server error, status code: %d, error code: %s, message: %s",
err.statusCode,
err.code,
err.description,
)
}
func (err *httpError) ErrorCode() string {
return err.code
}
|
package errors
import "fmt"
type HttpError interface {
Error
StatusCode() int
Headers() string
Body() string
}
type httpError struct {
statusCode int
headers string
body string
code string
description string
}
type HttpNotFoundError struct {
*httpError
}
func NewHttpError(statusCode int, header string, body string, code string, description string) HttpError {
err := httpError{
statusCode: statusCode,
headers: header,
body: body,
code: code,
description: description,
}
switch statusCode {
case 404:
return HttpNotFoundError{&err}
default:
return &err
}
}
func (err *httpError) StatusCode() int {
return err.statusCode
}
func (err *httpError) Headers() string {
return err.headers
}
func (err *httpError) Body() string {
return err.body
}
func (err *httpError) Error() string {
return fmt.Sprintf(
"Server error, status code: %d, error code: %s, message: %s",
err.statusCode,
err.code,
err.description,
)
}
func (err *httpError) ErrorCode() string {
return err.code
}
|
Update API path of geting sensors
|
(function(){
$.ajax({
url: 'users/evanxd/sensors',
})
.done(function(sensors) {
var sensorList = $('#sensor-list ul');
var html = '';
sensors.forEach(function(sensor) {
var html = '<li class="collection-item">' +
'<div>' +
sensor.name + '<a href="sensor-detail.html?id=' + sensor._id +
'" class="secondary-content"><i class="material-icons">info</i></a>' +
'</div>' +
'</li>';
sensorList.append(html);
});
})
.fail(function(error) {
console.error(error);
})
})();
|
(function(){
$.ajax({
url: 'evanxd/sensors',
})
.done(function(sensors) {
var sensorList = $('#sensor-list ul');
var html = '';
sensors.forEach(function(sensor) {
var html = '<li class="collection-item">' +
'<div>' +
sensor.name + '<a href="sensor-detail.html?id=' + sensor._id +
'" class="secondary-content"><i class="material-icons">info</i></a>' +
'</div>' +
'</li>';
sensorList.append(html);
});
})
.fail(function(error) {
console.error(error);
})
})();
|
Simplify test case. Tweak logging.
|
package discord
import (
"fmt"
"testing"
"time"
)
func TestBasicTicker(t *testing.T) {
// t.Skip("TickOnce not implemented")
var counter = 1
var i = 0
f := func(to *Ticker) {
fmt.Printf("Iteration: %d\n", i)
if i >= 5 {
to.Done()
}
counter++
i++
}
cleanUp := func(to *Ticker) {
return
}
ticker := NewTicker(1, f, cleanUp)
time.AfterFunc(6, func() {
ticker.Done()
})
select {
case q := <-ticker.Quit:
if counter != 5 && q {
t.Errorf("Incorrect `counter` value.")
t.Errorf("Expected: %d | Received: %d", 5, counter)
}
}
}
func TestTickerStop(t *testing.T) {
t.Skip("TickerStop not impelemnted.")
}
|
package discord
import (
"fmt"
"sync"
"testing"
"time"
)
func TestBasicTicker(t *testing.T) {
// t.Skip("TickOnce not implemented")
var counter = 1
var i = 0
mu := sync.Mutex{}
f := func(to *Ticker) {
fmt.Println("Iteration: " + string(i))
mu.Lock()
defer mu.Unlock()
if i >= 5 {
to.Done()
}
counter++
i++
}
cleanUp := func(to *Ticker) {
return
}
ticker := NewTicker(1, f, cleanUp)
time.AfterFunc(6, func() {
ticker.Done()
})
select {
case q := <-ticker.Quit:
if counter != 5 && q {
t.Errorf("Incorrect `counter` value.")
t.Errorf("Expected: %d | Received: %d", 5, counter)
}
}
}
func TestTickerStop(t *testing.T) {
t.Skip("TickerStop not impelemnted.")
}
|
Fix pretty duration for null value
|
from datetime import datetime, timedelta
from django import template
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
register = template.Library()
@register.filter
def duration(value):
""" Returns a duration in hours to a human readable version (minutes, days, ...)
"""
if value is None:
return u""
seconds = timedelta(minutes=float(value) * 60)
duration = datetime(1, 1, 1) + seconds
days = duration.day - 1
if days >= 8:
return _("More than %s days") % 8
if days > 1:
return _("%s days") % days
if days <= 1:
hours = (settings.TREK_DAY_DURATION * days) + duration.hour
if hours > settings.TREK_DAY_DURATION:
return _("%s days") % 2
if duration.hour > 0 and duration.minute > 0:
return _("%(hour)s h %(min)s") % {'hour': duration.hour,
'min': duration.minute}
if duration.hour > 0:
return _("%(hour)s h") % {'hour': duration.hour}
return _("%s min") % duration.minute
|
from datetime import datetime, timedelta
from django import template
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
register = template.Library()
@register.filter
def duration(value):
""" Returns a duration in hours to a human readable version (minutes, days, ...)
"""
seconds = timedelta(minutes=float(value) * 60)
duration = datetime(1, 1, 1) + seconds
days = duration.day - 1
if days >= 8:
return _("More than %s days") % 8
if days > 1:
return _("%s days") % days
if days <= 1:
hours = (settings.TREK_DAY_DURATION * days) + duration.hour
if hours > settings.TREK_DAY_DURATION:
return _("%s days") % 2
if duration.hour > 0 and duration.minute > 0:
return _("%(hour)s h %(min)s") % {'hour': duration.hour,
'min': duration.minute}
if duration.hour > 0:
return _("%(hour)s h") % {'hour': duration.hour}
return _("%s min") % duration.minute
|
Fix condition to skip blacklisted extensions
|
'use strict';
var crypto = require('crypto');
var CustomStats = require('webpack-custom-stats-patch');
var DEFAULT_PARAMS = {
customStatsKey: 'sprockets',
ignore: /\.(gz|html)$/
};
function SprocketsStatsWebpackPlugin(options) {
var params = options || {};
this._customStatsKey = options.customStatsKey || DEFAULT_PARAMS.customStatsKey;
this._ignore = params.ignore || DEFAULT_PARAMS.ignore;
}
SprocketsStatsWebpackPlugin.prototype.apply = function(compiler) {
var customStatsKey = this._customStatsKey;
var blacklistRegex = this._ignore;
var sprockets = {};
compiler.plugin('this-compilation', function(compilation) {
compilation.plugin('optimize-assets', function(assets, callback) {
Object.keys(assets).forEach(function(file) {
var asset;
var content;
if (!file.match(blacklistRegex)) {
asset = assets[file];
content = asset.source();
sprockets[file] = {
size: asset.size(),
digest: crypto.createHash('md5').update(content).digest('hex')
};
}
});
callback();
});
});
compiler.plugin('after-emit', function(compilation, callback) {
var stats = new CustomStats(compilation);
stats.addCustomStat(customStatsKey, sprockets);
callback();
});
};
module.exports = SprocketsStatsWebpackPlugin;
|
'use strict';
var crypto = require('crypto');
var CustomStats = require('webpack-custom-stats-patch');
var DEFAULT_PARAMS = {
customStatsKey: 'sprockets',
ignore: /\.(gz|html)$/
};
function SprocketsStatsWebpackPlugin(options) {
var params = options || {};
this._customStatsKey = options.customStatsKey || DEFAULT_PARAMS.customStatsKey;
this._ignore = params.ignore || DEFAULT_PARAMS.ignore;
}
SprocketsStatsWebpackPlugin.prototype.apply = function(compiler) {
var customStatsKey = this._customStatsKey;
var blacklistRegex = this._ignore;
var sprockets = {};
compiler.plugin('this-compilation', function(compilation) {
compilation.plugin('optimize-assets', function(assets, callback) {
Object.keys(assets).forEach(function(file) {
var asset;
var content;
if (file.match(!blacklistRegex)) {
asset = assets[file];
content = asset.source();
sprockets[file] = {
size: asset.size(),
digest: crypto.createHash('md5').update(content).digest('hex')
};
}
});
callback();
});
});
compiler.plugin('after-emit', function(compilation, callback) {
var stats = new CustomStats(compilation);
stats.addCustomStat(customStatsKey, sprockets);
callback();
});
};
module.exports = SprocketsStatsWebpackPlugin;
|
Make PDO connections persistent and exceptional
|
<?php
/* Site-wide utility functions */
require_once('secureConstants.php');
function mysqliConn() {
$db = new mysqli(
$GLOBALS['DB']['SERVER'],
$GLOBALS['DB']['USERNAME'],
$GOLBALS['DB']['PASSWORD'],
$GLOBALS['DB']['DATABASE']
);
if ($db->connect_errno) {
header('HTTP/1.1 500 Internal Server Error');
exit('Database connection failed. Contact system administrator. Error code: ' . $db->connect_errno);
}
return $db;
}
function pdoConn() {
$dsn = "mysql:dbname={$GLOBALS['DB']['DATABASE']};host={$GLOBALS['DB']['SERVER']}";
try {
$db = new PDO($dsn, $GLOBALS['DB']['USERNAME'], $GOLBALS['DB']['PASSWORD'], [PDO::ATTR_PERSISTENT => true]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
exit('Database connection failed. Contact system administrator. Error code: ' . $e->getMessage());
}
return $db;
}
|
<?php
/* Site-wide utility functions */
require_once('secureConstants.php');
function mysqliConn() {
$db = new mysqli(
$GLOBALS['DB']['SERVER'],
$GLOBALS['DB']['USERNAME'],
$GOLBALS['DB']['PASSWORD'],
$GLOBALS['DB']['DATABASE']
);
if ($db->connect_errno) {
header('HTTP/1.1 500 Internal Server Error');
exit('Database connection failed. Contact system administrator. Error code: ' . $db->connect_errno);
}
return $db;
}
function pdoConn() {
$dsn = "mysql:dbname={$GLOBALS['DB']['DATABASE']};host={$GLOBALS['DB']['SERVER']}";
try {
$db = new PDO($dsn, $GLOBALS['DB']['USERNAME'], $GOLBALS['DB']['PASSWORD']);
} catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
exit('Database connection failed. Contact system administrator. Error code: ' . $e->getMessage());
}
return $db;
}
|
Update adapter find to return a promise.
|
/**
* External imports
*/
import _ from 'underscore';
import co from 'co';
import mingo from 'mingo';
import libdebug from 'debug';
// create debug logger
const debug = libdebug('storage-adapter');
export const ADAPTABLE_METHODS = [
'skip',
'sort',
'find',
'limit',
'insert',
'update',
'remove',
'aggregate',
];
function isAdaptable(storage) {
return typeof storage === 'object'
&& _.every(ADAPTABLE_METHODS, (method) => method in storage);
}
const PROTOTYPE = {
find(query, projection) {
debug('received query %j', query);
debug('received projection %j', projection);
const adapter = this;
return co(function* findInnerGen() {
return mingo.find(adapter.storage, query, projection).all();
});
},
};
export default function createAdapter(options = {}) {
debug('passed-in options (keys only): %j', Object.keys(options));
debug('passed-in storage (type): %j', typeof options.storage);
if (!options.storage) throw new Error('`options.storage` is missing.');
if (!(_.isArray(options.storage) || isAdaptable(options.storage))) {
throw new Error('`options.storage` should be an adaptable or an array.');
}
return Object.create(PROTOTYPE, {
storage: {
value: options.storage,
},
});
}
|
/**
* External imports
*/
import _ from 'underscore';
import mingo from 'mingo';
import libdebug from 'debug';
// create debug logger
const debug = libdebug('storage-adapter');
export const ADAPTABLE_METHODS = [
'skip',
'sort',
'find',
'limit',
'insert',
'update',
'remove',
'aggregate',
];
function isAdaptable(storage) {
return typeof storage === 'object'
&& _.every(ADAPTABLE_METHODS, (method) => method in storage);
}
const PROTOTYPE = {
find(query, projection) {
debug('received query %j', query);
debug('received projection %j', projection);
return mingo.find(this.storage, query, projection).all();
},
};
export default function createAdapter(options = {}) {
debug('passed-in options (keys only): %j', Object.keys(options));
debug('passed-in storage (type): %j', typeof options.storage);
if (!options.storage) throw new Error('`options.storage` is missing.');
if (!(_.isArray(options.storage) || isAdaptable(options.storage))) {
throw new Error('`options.storage` should be an adaptable or an array.');
}
return Object.create(PROTOTYPE, {
storage: {
value: options.storage,
},
});
}
|
Fix sorting on FOLV settings example
|
import ListFormRoute from 'ember-flexberry/routes/list-form';
export default ListFormRoute.extend({
/**
Name of model projection to be used as record's properties limitation.
@property modelProjection
@type String
@default 'SuggestionL'
*/
modelProjection: 'SuggestionL',
/**
developerUserSettings.
{
<componentName>: {
<settingName>: {
colsOrder: [ { propName :<colName>, hide: true|false }, ... ],
sorting: [{ propName: <colName>, direction: "asc"|"desc" }, ... ],
colsWidths: [ <colName>:<colWidth>, ... ],
},
...
},
...
}
For default userSetting use empty name ('').
<componentName> may contain any of properties: colsOrder, sorting, colsWidth or being empty.
@property developerUserSettings
@type Object
@default {}
*/
developerUserSettings: { FOLVSettingsExampleObjectListView: { } },
/**
Name of model to be used as list's records types.
@property modelName
@type String
@default 'ember-flexberry-dummy-suggestion'
*/
modelName: 'ember-flexberry-dummy-suggestion'
});
|
import ListFormRoute from 'ember-flexberry/routes/list-form';
export default ListFormRoute.extend({
/**
Name of model projection to be used as record's properties limitation.
@property modelProjection
@type String
@default 'SuggestionL'
*/
modelProjection: 'SuggestionL',
/**
developerUserSettings.
{
<componentName>: {
<settingName>: {
colsOrder: [ { propName :<colName>, hide: true|false }, ... ],
sorting: [{ propName: <colName>, direction: "asc"|"desc" }, ... ],
colsWidths: [ <colName>:<colWidth>, ... ],
},
...
},
...
}
For default userSetting use empty name ('').
<componentName> may contain any of properties: colsOrder, sorting, colsWidth or being empty.
@property developerUserSettings
@type Object
@default {}
*/
developerUserSettings: { FOLVSettingExampleObjectListView: { } },
/**
Name of model to be used as list's records types.
@property modelName
@type String
@default 'ember-flexberry-dummy-suggestion'
*/
modelName: 'ember-flexberry-dummy-suggestion'
});
|
Remove stray print statement O_o
|
# Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import, division, print_function
from lucid.misc.io.sanitizing import sanitize
from lucid.misc.io import load
import numpy as np
PATH_TEMPLATE = "gs://modelzoo/aligned-activations/{}/{}-{:05d}-of-01000.npy"
PAGE_SIZE = 10000
NUMBER_OF_AVAILABLE_SAMPLES = 100000
assert NUMBER_OF_AVAILABLE_SAMPLES % PAGE_SIZE == 0
NUMBER_OF_PAGES = NUMBER_OF_AVAILABLE_SAMPLES // PAGE_SIZE
def get_aligned_activations(layer):
activation_paths = [
PATH_TEMPLATE.format(sanitize(layer.model_class.name), sanitize(layer.name), page)
for page in range(NUMBER_OF_PAGES)
]
activations = [load(path) for path in activation_paths]
return np.vstack(activations)
|
# Copyright 2018 The Lucid Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import, division, print_function
from lucid.misc.io.sanitizing import sanitize
from lucid.misc.io import load
import numpy as np
PATH_TEMPLATE = "gs://modelzoo/aligned-activations/{}/{}-{:05d}-of-01000.npy"
PAGE_SIZE = 10000
NUMBER_OF_AVAILABLE_SAMPLES = 100000
assert NUMBER_OF_AVAILABLE_SAMPLES % PAGE_SIZE == 0
NUMBER_OF_PAGES = NUMBER_OF_AVAILABLE_SAMPLES // PAGE_SIZE
def get_aligned_activations(layer):
activation_paths = [
PATH_TEMPLATE.format(sanitize(layer.model_class.name), sanitize(layer.name), page)
for page in range(NUMBER_OF_PAGES)
]
print(activation_paths)
activations = [load(path) for path in activation_paths]
return np.vstack(activations)
|
Update classifiers to drop support for Python 2.7
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from setuptools import setup
setup(
name='pybreaker',
version='0.6.0',
description='Python implementation of the Circuit Breaker pattern',
long_description=open('README.rst', 'r').read(),
keywords=['design', 'pattern', 'circuit', 'breaker', 'integration'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
],
platforms=[
'Any',
],
license='BSD',
author='Daniel Fernandes Martins',
author_email='daniel.tritone@gmail.com',
url='http://github.com/danielfm/pybreaker',
package_dir={'': 'src'},
py_modules=['pybreaker'],
install_requires=[
'six',
],
include_package_data=True,
zip_safe=False,
test_suite='tests',
tests_require=['mock', 'fakeredis==0.16.0', 'redis==2.10.6', 'tornado'],
)
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from setuptools import setup
setup(
name='pybreaker',
version='0.6.0',
description='Python implementation of the Circuit Breaker pattern',
long_description=open('README.rst', 'r').read(),
keywords=['design', 'pattern', 'circuit', 'breaker', 'integration'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries',
],
platforms=[
'Any',
],
license='BSD',
author='Daniel Fernandes Martins',
author_email='daniel.tritone@gmail.com',
url='http://github.com/danielfm/pybreaker',
package_dir={'': 'src'},
py_modules=['pybreaker'],
install_requires=[
'six',
],
include_package_data=True,
zip_safe=False,
test_suite='tests',
tests_require=['mock', 'fakeredis==0.16.0', 'redis==2.10.6', 'tornado'],
)
|
Change path to mfr directory
|
"""PDF renderer module."""
from mfr.core import RenderResult
import PyPDF2
import urllib
import mfr
def is_valid(fp):
"""Tests file pointer for validity
:return: True if fp is a valid pdf, False if not
"""
try:
PyPDF2.PdfFileReader(fp)
return True
except PyPDF2.utils.PdfReadError:
return False
def render_pdf(fp, src=None):
"""A simple pdf renderer.
:param fp: File pointer
:param src: Path to file
:return: A RenderResult object containing html content and js assets for pdf rendering
"""
src = src or fp.name
url_encoded_src = urllib.quote_plus(src)
assets_uri_base = '{0}/pdf'.format(mfr.config['ASSETS_URL'])
if is_valid(fp):
content = (
'<iframe src="{base}/web/viewer.html?file={src}" width="100%" height="600px"></iframe>'
).format(src=url_encoded_src, base=assets_uri_base)
return RenderResult(content)
else:
return RenderResult("This is not a valid pdf file")
|
"""PDF renderer module."""
from mfr.core import RenderResult
import PyPDF2
import urllib
def is_valid(fp):
"""Tests file pointer for validity
:return: True if fp is a valid pdf, False if not
"""
try:
PyPDF2.PdfFileReader(fp)
return True
except PyPDF2.utils.PdfReadError:
return False
def render_pdf(fp, src=None):
"""A simple pdf renderer.
:param fp: File pointer
:param src: Path to file
:return: A RenderResult object containing html content and js assets for pdf rendering
"""
src = src or fp.name
url_encoded_src = urllib.quote_plus(src)
if is_valid(fp):
content = (
'<iframe src="/static/mfr/pdf/web/viewer.html?file={src}" width="100%" height="600px"></iframe>'
).format(src = url_encoded_src)
return RenderResult(content)
else:
return RenderResult("This is not a valid pdf file")
|
Work around a paralleltest crash
> ERRO [runner] Panic: paralleltest: package "main" (isInitialPkg: true, needAnalyzeSource: true): runtime error: index out of range [0] with length 0: goroutine 5859 [running]:
> ...
> github.com/kunwardeep/paralleltest/pkg/paralleltest.isTestFunction(0x1b7d8c0?)
> github.com/kunwardeep/paralleltest@v1.0.6/pkg/paralleltest/paralleltest.go:252 +0x165
Should not change behavior.
Signed-off-by: Miloslav Trmač <9c008e38982a5397deb855345fb164f0558459ae@redhat.com>
|
package main
import "testing"
func TestTree(_ *testing.T) {
nodes := []treeNode{
{"F", "H", []string{}},
{"F", "I", []string{}},
{"F", "J", []string{}},
{"A", "B", []string{}},
{"A", "C", []string{}},
{"A", "K", []string{}},
{"C", "F", []string{}},
{"C", "G", []string{"beware", "the", "scary", "thing"}},
{"C", "L", []string{}},
{"B", "D", []string{}},
{"B", "E", []string{}},
{"B", "M", []string{}},
{"K", "N", []string{}},
{"W", "X", []string{}},
{"Y", "Z", []string{}},
{"X", "Y", []string{}},
}
printTree(nodes)
}
|
package main
import "testing"
func TestTree(*testing.T) {
nodes := []treeNode{
{"F", "H", []string{}},
{"F", "I", []string{}},
{"F", "J", []string{}},
{"A", "B", []string{}},
{"A", "C", []string{}},
{"A", "K", []string{}},
{"C", "F", []string{}},
{"C", "G", []string{"beware", "the", "scary", "thing"}},
{"C", "L", []string{}},
{"B", "D", []string{}},
{"B", "E", []string{}},
{"B", "M", []string{}},
{"K", "N", []string{}},
{"W", "X", []string{}},
{"Y", "Z", []string{}},
{"X", "Y", []string{}},
}
printTree(nodes)
}
|
Make windows bigger in this test so the captions can be read.
Index: tests/window/WINDOW_CAPTION.py
===================================================================
--- tests/window/WINDOW_CAPTION.py (revision 777)
+++ tests/window/WINDOW_CAPTION.py (working copy)
@@ -19,8 +19,8 @@
class WINDOW_CAPTION(unittest.TestCase):
def test_caption(self):
- w1 = window.Window(200, 200)
- w2 = window.Window(200, 200)
+ w1 = window.Window(400, 200, resizable=True)
+ w2 = window.Window(400, 200, resizable=True)
count = 1
w1.set_caption('Window caption %d' % count)
w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
git-svn-id: d4fdfcd4de20a449196f78acc655f735742cd30d@781 14d46d22-621c-0410-bb3d-6f67920f7d95
|
#!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import time
import unittest
from pyglet import window
class WINDOW_CAPTION(unittest.TestCase):
def test_caption(self):
w1 = window.Window(400, 200, resizable=True)
w2 = window.Window(400, 200, resizable=True)
count = 1
w1.set_caption('Window caption %d' % count)
w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
last_time = time.time()
while not (w1.has_exit or w2.has_exit):
if time.time() - last_time > 1:
count += 1
w1.set_caption('Window caption %d' % count)
last_time = time.time()
w1.dispatch_events()
w2.dispatch_events()
w1.close()
w2.close()
if __name__ == '__main__':
unittest.main()
|
#!/usr/bin/env python
'''Test that the window caption can be set.
Expected behaviour:
Two windows will be opened, one with the caption "Window caption 1"
counting up every second; the other with a Unicode string including
some non-ASCII characters.
Press escape or close either window to finished the test.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import time
import unittest
from pyglet import window
class WINDOW_CAPTION(unittest.TestCase):
def test_caption(self):
w1 = window.Window(200, 200)
w2 = window.Window(200, 200)
count = 1
w1.set_caption('Window caption %d' % count)
w2.set_caption(u'\u00bfHabla espa\u00f1ol?')
last_time = time.time()
while not (w1.has_exit or w2.has_exit):
if time.time() - last_time > 1:
count += 1
w1.set_caption('Window caption %d' % count)
last_time = time.time()
w1.dispatch_events()
w2.dispatch_events()
w1.close()
w2.close()
if __name__ == '__main__':
unittest.main()
|
Rename new sequence search url
|
"""
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django.conf.urls import patterns, url, include
from django.views.generic import TemplateView
urlpatterns = patterns('',
# RNAcentral portal
url(r'', include('portal.urls')),
# REST API (use trailing slashes)
url(r'^api/current/', include('apiv1.urls')),
url(r'^api/v1/', include('apiv1.urls')),
# robots.txt
url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')),
# export metadata search results
url(r'^export/', include('export.urls')),
# sequence search
url(r'^sequence-search-nhmmer/', include('nhmmer.urls')),
)
|
"""
Copyright [2009-2014] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django.conf.urls import patterns, url, include
from django.views.generic import TemplateView
urlpatterns = patterns('',
# RNAcentral portal
url(r'', include('portal.urls')),
# REST API (use trailing slashes)
url(r'^api/current/', include('apiv1.urls')),
url(r'^api/v1/', include('apiv1.urls')),
# robots.txt
url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')),
# export metadata search results
url(r'^export/', include('export.urls')),
# sequence search
url(r'^sequence-search-new/', include('nhmmer.urls')),
)
|
[Discord] Remove unused bot attribute from Duelyst cog
|
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Duelyst())
class Duelyst(commands.Cog):
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.group(invoke_without_command = True, case_insensitive = True)
async def duelyst(self, ctx):
'''Duelyst'''
await ctx.send_help(ctx.command)
@duelyst.group(case_insensitive = True)
async def card(self, ctx, *, name: str):
'''Details of a specific card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"cardName": name}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
@card.command()
async def card_random(self, ctx):
'''Details of a random card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"random": 1}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
|
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Duelyst(bot))
class Duelyst(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.group(invoke_without_command = True, case_insensitive = True)
async def duelyst(self, ctx):
'''Duelyst'''
await ctx.send_help(ctx.command)
@duelyst.group(case_insensitive = True)
async def card(self, ctx, *, name: str):
'''Details of a specific card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"cardName": name}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
@card.command()
async def card_random(self, ctx):
'''Details of a random card'''
url = "https://duelyststats.info/scripts/carddata/get.php"
params = {"random": 1}
async with ctx.bot.aiohttp_session.get(url, params = params) as resp:
data = await resp.text()
await ctx.embed_reply(data)
|
Change environ.get → environ[] in scope of `if`
|
import os
class BaseConfig(object):
DEBUG_TB_INTERCEPT_REDIRECTS = False
SECRET_KEY = os.environ.get('SECRET_KEY', 'change me in production')
db_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data/database.db'))
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'sqlite:///' + db_path)
SQLALCHEMY_ECHO = True if os.environ.get('SQLALCHEMY_ECHO') else False
SQLALCHEMY_TRACK_MODIFICATIONS = False
TZ = os.environ.get('TZ', 'US/Eastern')
if 'GITHUB_CLIENT_ID' in os.environ:
REQUIRE_LOGIN = True
GITHUB_CLIENT_ID = os.environ['GITHUB_CLIENT_ID']
GITHUB_CLIENT_SECRET = os.environ['GITHUB_CLIENT_SECRET']
else:
REQUIRE_LOGIN = False
if 'REDIS_HOST' in os.environ:
REDIS_HOST = os.environ['REDIS_HOST']
|
import os
class BaseConfig(object):
DEBUG_TB_INTERCEPT_REDIRECTS = False
SECRET_KEY = os.environ.get('SECRET_KEY', 'change me in production')
db_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data/database.db'))
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'sqlite:///' + db_path)
SQLALCHEMY_ECHO = True if os.environ.get('SQLALCHEMY_ECHO') else False
SQLALCHEMY_TRACK_MODIFICATIONS = False
TZ = os.environ.get('TZ', 'US/Eastern')
if 'GITHUB_CLIENT_ID' in os.environ:
REQUIRE_LOGIN = True
GITHUB_CLIENT_ID = os.environ['GITHUB_CLIENT_ID']
GITHUB_CLIENT_SECRET = os.environ['GITHUB_CLIENT_SECRET']
else:
REQUIRE_LOGIN = False
if 'REDIS_HOST' in os.environ:
REDIS_HOST = os.environ.get('REDIS_HOST')
|
Fix the name of arguments for PHP 8
|
<?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.
*/
use Symfony\Polyfill\Php70 as p;
if (PHP_VERSION_ID >= 70000) {
return;
}
if (!defined('PHP_INT_MIN')) {
define('PHP_INT_MIN', ~PHP_INT_MAX);
}
if (!function_exists('intdiv')) {
function intdiv($num1, $num2) { return p\Php70::intdiv($num1, $num2); }
}
if (!function_exists('preg_replace_callback_array')) {
function preg_replace_callback_array(array $pattern, $subject, $limit = -1, &$count = 0, $flags = null) { return p\Php70::preg_replace_callback_array($pattern, $subject, $limit, $count); }
}
if (!function_exists('error_clear_last')) {
function error_clear_last() { return p\Php70::error_clear_last(); }
}
|
<?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.
*/
use Symfony\Polyfill\Php70 as p;
if (PHP_VERSION_ID >= 70000) {
return;
}
if (!defined('PHP_INT_MIN')) {
define('PHP_INT_MIN', ~PHP_INT_MAX);
}
if (!function_exists('intdiv')) {
function intdiv($dividend, $divisor) { return p\Php70::intdiv($dividend, $divisor); }
}
if (!function_exists('preg_replace_callback_array')) {
function preg_replace_callback_array(array $patterns, $subject, $limit = -1, &$count = 0) { return p\Php70::preg_replace_callback_array($patterns, $subject, $limit, $count); }
}
if (!function_exists('error_clear_last')) {
function error_clear_last() { return p\Php70::error_clear_last(); }
}
|
Fix Undertow static handler package name, as it was renamed
|
package org.wildfly.swarm.undertow;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Node;
/**
* @author Bob McWhirter
*/
public interface StaticContentContainer<T extends Archive<T>> extends Archive<T> {
default T staticContent() {
return staticContent( "/", "." );
}
default T staticContent(String context) {
return staticContent( context, "." );
}
default T staticContent(String context, String base) {
as(WARArchive.class).addModule("org.wildfly.swarm.undertow", "runtime");
as(WARArchive.class).addAsServiceProvider("io.undertow.server.handlers.builder.HandlerBuilder", "org.wildfly.swarm.undertow.runtime.StaticHandlerBuilder");
Node node = as(WARArchive.class).get("WEB-INF/undertow-handlers.conf");
UndertowHandlersAsset asset = null;
if ( node == null ) {
asset = new UndertowHandlersAsset();
as(WARArchive.class).add( asset, "WEB-INF/undertow-handlers.conf" );
} else {
asset = (UndertowHandlersAsset) node.getAsset();
}
asset.staticContent( context, base );
return (T) this;
}
}
|
package org.wildfly.swarm.undertow;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Node;
/**
* @author Bob McWhirter
*/
public interface StaticContentContainer<T extends Archive<T>> extends Archive<T> {
default T staticContent() {
return staticContent( "/", "." );
}
default T staticContent(String context) {
return staticContent( context, "." );
}
default T staticContent(String context, String base) {
as(WARArchive.class).addModule("org.wildfly.swarm.undertow", "runtime");
as(WARArchive.class).addAsServiceProvider("io.undertow.server.handlers.builder.HandlerBuilder", "org.wildfly.swarm.runtime.undertow.StaticHandlerBuilder");
Node node = as(WARArchive.class).get("WEB-INF/undertow-handlers.conf");
UndertowHandlersAsset asset = null;
if ( node == null ) {
asset = new UndertowHandlersAsset();
as(WARArchive.class).add( asset, "WEB-INF/undertow-handlers.conf" );
} else {
asset = (UndertowHandlersAsset) node.getAsset();
}
asset.staticContent( context, base );
return (T) this;
}
}
|
Normalize all to spinal-case before other convertions. Added toSpaceCase.
|
var p = String.prototype;
// normalize always returns the string in spinal-case
function normalize(str) {
var arr = str.split(/[\s-_.]/);
if(arr.length > 1)
return arr.map(function(part) { return part.toLowerCase(); }).join('-');
else
return (str.charAt(0).toLowerCase() + str.slice(1)).replace(/([A-Z])/, '-$&').toLowerCase();
}
// Converts spinal-case, snake_case or space case to camelCase
p.toCamelCase = function(pascalCase) {
var str = this.toLowerCase();
var arr = str.split(/[\s-_]/);
for(var i = pascalCase ? 0 : 1; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
return arr.join('');
};
// Converts spinal-case, snake_case or space case to PascalCase
p.toPascalCase = function() {
return normalize(this).toCamelCase(true);
};
// converts camelCase or PascalCase to spinal-case/
p.toSpinalCase = function() {
return normalize(this);
};
// converts camelCase or PascalCase to snake_case/
p.toSnakeCase = function() {
return normalize(this).split('-').join('_');
};
p.toSpaceCase = function(capitals) {
return normalize(this).split('-').map(function(part) {
return capitals ? part.charAt(0).toUpperCase() + part.slice(1) : part;
}).join(' ');
};
|
var p = String.prototype;
// Converts spinal-case, snake_case or space case to camelCase
p.toCamelCase = function(pascalCase) {
var str = this.toLowerCase();
var arr = str.split(/[\s-_]/);
for(var i = pascalCase ? 0 : 1; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
return arr.join('');
};
// Converts spinal-case, snake_case or space case to PascalCase
p.toPascalCase = function() {
return this.toCamelCase(true);
};
// converts camelCase or PascalCase to spinal-case/
p.toSpinalCase = function() {
return (this.charAt(0).toLowerCase() + this.slice(1)).replace(/([A-Z])/, '-$&').toLowerCase();
};
// converts camelCase or PascalCase to snake_case/
p.toSnakeCase = function() {
return (this.charAt(0).toLowerCase() + this.slice(1)).replace(/([A-Z])/, '_$&').toLowerCase();
};
|
jobs-041: Fix browsable API index regexp
|
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from jobs_backend.views import APIRoot
api_urlpatterns = [
# All api endpoints should be included here
url(r'^users/', include('jobs_backend.users.urls.users', namespace='users')),
url(r'^account/', include('jobs_backend.users.urls.account', namespace='account')),
url(r'^vacancies/', include('jobs_backend.vacancies.urls', namespace='vacancies')),
]
urlpatterns = [
url(r'^api/', include(api_urlpatterns, namespace='api')),
url(settings.ADMIN_URL, admin.site.urls),
url(r'^api/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
urlpatterns += [
url(r'^api/$', APIRoot.as_view(urlpatterns=urlpatterns, app_namespace='api_v1'), name='api_root')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
if 'debug_toolbar' in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
|
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from jobs_backend.views import APIRoot
api_urlpatterns = [
# All api endpoints should be included here
url(r'^users/', include('jobs_backend.users.urls.users', namespace='users')),
url(r'^account/', include('jobs_backend.users.urls.account', namespace='account')),
url(r'^vacancies/', include('jobs_backend.vacancies.urls', namespace='vacancies')),
]
urlpatterns = [
url(r'^api/', include(api_urlpatterns, namespace='api')),
url(settings.ADMIN_URL, admin.site.urls),
url(r'^api/api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
urlpatterns += [
url(r'^$', APIRoot.as_view(urlpatterns=urlpatterns, app_namespace='api_v1'), name='api_root')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
if 'debug_toolbar' in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
|
Add Array of responsive dates for navDates display
|
/* global GuardianAPI, NYTAPI, DomUpdater */
function main() {
const today = new Date(Date.now());
console.log(today);
const datesLastWeek = Array.from({ length: 7 }, (_, idx) => new Date(today - (idx + 1) * (8.64 * Math.pow(10, 7))));
console.log(datesLastWeek);
const navDates = datesLastWeek.map(el => el.toDateString().slice(4, 10));
console.log(navDates);
const guardianContentNode = document.getElementById('GuardianContent');
const NYTContentNode = document.getElementById('NYTimesContent');
GuardianAPI.getArticles(formatGuardianDate(today))
.then(DomUpdater.buildArticleNodes)
.then(DomUpdater.displayArticleNodes(guardianContentNode));
NYTAPI.getArticles(formatNYTDate(today))
.then(DomUpdater.buildArticleNodes)
.then(DomUpdater.displayArticleNodes(NYTContentNode));
}
main();
function fillZero(num) {
return num < 10 ? `0${num}` : num;
}
function formatGuardianDate(date) {
return `${date.getFullYear()}-${fillZero(date.getMonth() + 1)}-${fillZero(date.getDate())}`;
}
function formatNYTDate(date) {
return `${date.getFullYear()}${fillZero(date.getMonth() + 1)}${fillZero(date.getDate())}`;
}
|
/* global GuardianAPI, NYTAPI, DomUpdater */
function fillZero(num) {
return num < 10 ? `0${num}` : num;
}
function formatGuardianDate(date) {
return `${date.getFullYear()}-${fillZero(date.getMonth() + 1)}-${fillZero(date.getDate())}`;
}
function formatNYTDate(date) {
return `${date.getFullYear()}${fillZero(date.getMonth() + 1)}${fillZero(date.getDate())}`;
}
function main() {
const guardianContentNode = document.getElementById('GuardianContent');
const NYTContentNode = document.getElementById('NYTimesContent');
const today = new Date(Date.now());
console.log(today);
// const yesterday = new Date(Date.now() - (8.64 * Math.pow(10, 7)));
// console.log(yesterday);
//
const datesOfLastWeek = Array.from({ length: 6 }, (_, idx) => new Date(Date.now() - (idx +1) * (8.64 * Math.pow(10, 7))))
//
// const vs = Array.from({length: 6}, (_, idx) => idx + 1);
// console.log(vs);
console.log(datesOfLastWeek);
GuardianAPI.getArticles(formatGuardianDate(today))
.then(DomUpdater.buildArticleNodes)
.then(DomUpdater.displayArticleNodes(guardianContentNode));
NYTAPI.getArticles(formatNYTDate(today))
.then(DomUpdater.buildArticleNodes)
.then(DomUpdater.displayArticleNodes(NYTContentNode));
}
main();
|
Make it module loaders compatible
|
(function (root, factory) {
if (typeof exports === 'object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
root.f = factory();
}
})(this, function () {
var lambdaRegex = /\((.*)\)[\s]*=>[\s]*(.+)/;
function f(x) { return function() { return x; } };
f.property = function(propertyName) {
if(propertyName[0] === '!')
return function(obj) { return !obj[propertyName.substring(1)]; };
else
return function(obj) { return obj[propertyName]; };
}
f.method = function(methodName) {
if(methodName[0] === '!')
return function(obj) { return !obj[methodName.substring(1)](); };
else
return function(obj) { return obj[methodName](); };
}
f.n = function() {
var args = arguments;
if(args.length) args[args.length - 1] = "return " + args[args.length - 1];
return Function.apply({}, args);
}
f.y = function(expression){
var match = lambdaRegex.exec(expression);
var argsString = match[1];
var body = match[2];
var args = argsString.split(',').map(f.method('trim'));
return f.n.apply(f, args.concat(body));
}
return f;
});
|
var f = function(x) { return function() {return x}; ; };
var lambdaRegex = /\((.*)\)[\s]*=>[\s]*(.+)/;
f.property = function(propertyName) {
if(propertyName[0] === '!')
return function(obj) { return !obj[propertyName.substring(1)]; };
else
return function(obj) { return obj[propertyName]; };
}
f.method = function(methodName) {
if(methodName[0] === '!')
return function(obj) { return !obj[methodName.substring(1)](); };
else
return function(obj) { return obj[methodName](); };
}
f.n = function() {
var args = arguments;
if(args.length) args[args.length - 1] = "return " + args[args.length - 1];
return Function.apply({}, args);
}
f.y = function(expression){
var match = lambdaRegex.exec(expression);
var argsString = match[1];
var body = match[2];
var args = argsString.split(',').map(f.method('trim'));
return f.n.apply(f, args.concat(body));
}
|
Remove superflous settings option on dredd command
|
import { lazyFunctionRequire } from 'roc';
import config from '../config/roc.config.js';
import meta from '../config/roc.config.meta.js';
const lazyRequire = lazyFunctionRequire(require);
export default {
config,
meta,
actions: [
{
hook: 'server-started',
description: 'Run dredd tests',
action: lazyRequire('../actions/dredd'),
},
],
commands: {
development: {
dredd: {
command: lazyRequire('../commands/dredd'),
description: 'Runs dredd in current project',
},
},
},
hooks: {
'run-dev-command': {
description: 'Used to start dev server used for dredd testing',
},
},
};
|
import { lazyFunctionRequire } from 'roc';
import config from '../config/roc.config.js';
import meta from '../config/roc.config.meta.js';
const lazyRequire = lazyFunctionRequire(require);
export default {
config,
meta,
actions: [
{
hook: 'server-started',
description: 'Run dredd tests',
action: lazyRequire('../actions/dredd'),
},
],
commands: {
development: {
dredd: {
command: lazyRequire('../commands/dredd'),
description: 'Runs dredd in current project',
settings: true,
},
},
},
hooks: {
'run-dev-command': {
description: 'Used to start dev server used for dredd testing',
},
},
};
|
Add PUT/POST handling to ClassyResource
This resolves #1.
Data can be passed into a resource method call by including it
as the final parameter. For example, in this commit I have added
support for the following:
classy.organizations.createCampaign(##, {});
classy.campaigns.update(##, {});
|
/** Just for testing */
import Classy from '../src/Classy';
let classy = new Classy({
clientId: 'fbnwFsTgUox9VAPTsHfJXk5KiyScSU',
clientSecret: 'XlX9sSH0sHHxTVIoBilbxcEYbQrrtLsYhtwNSrwuN0vgID0164xYY',
baseUrl: 'https://dev-gateway.classy-test.org'
});
let app = classy.app();
app.then((response) => {
classy.oauth.auth({
username: 'mlingner@classy.org',
password: 'classydev!'
}).then((response) => {
classy.organizations.createCampaign(34, {
name: 'Node-SDK Campaign',
goal: 3.50,
type: "crowdfunding",
started_at: '2016-03-23 07:00:00',
timezone_identifier:"US/Central"
}).then((response) => {
classy.campaigns.update(response.id, {
name: "Edited Node-SDK Campaign!"
});
});
});
});
|
/** Just for testing */
import Classy from '../dist/Classy';
let classy = new Classy({
clientId: 'fbnwFsTgUox9VAPTsHfJXk5KiyScSU',
clientSecret: 'XlX9sSH0sHHxTVIoBilbxcEYbQrrtLsYhtwNSrwuN0vgID0164xYY',
baseUrl: 'https://dev-gateway.classy-test.org'
});
let app = classy.app();
app.then((response) => {
classy.oauth.auth({
username: 'mlingner@classy.org',
password: 'classydev!'
}).then((response) => {
classy.me.retrieve().then((response) => {
console.log(response);
});
classy.campaigns.retrieve(2355).then((response) => {
console.log(response);
});
});
});
|
Clear $LANGUAGE before running tests
|
#!/usr/bin/env python
import unittest, os, sys
for x in ['LANGUAGE', 'LANG']:
if x in os.environ:
del os.environ[x]
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
sys.argv.append('-v')
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') and f.endswith('.py')]
suite_names.remove('testall')
suite_names.sort()
alltests = unittest.TestSuite()
for name in suite_names:
m = __import__(name, globals(), locals(), [])
alltests.addTest(m.suite)
a = unittest.TextTestRunner(verbosity=2).run(alltests)
if coverage:
coverage.stop()
else:
print "Coverage module not found. Skipping coverage report."
print "\nResult", a
if not a.wasSuccessful():
sys.exit(1)
if coverage:
all_sources = []
def incl(d):
for x in os.listdir(d):
if x.endswith('.py'):
all_sources.append(os.path.join(d, x))
incl('..')
coverage.report(all_sources + ['../0publish'])
|
#!/usr/bin/env python
import unittest, os, sys
try:
import coverage
coverage.erase()
coverage.start()
except ImportError:
coverage = None
my_dir = os.path.dirname(sys.argv[0])
if not my_dir:
my_dir = os.getcwd()
sys.argv.append('-v')
suite_names = [f[:-3] for f in os.listdir(my_dir)
if f.startswith('test') and f.endswith('.py')]
suite_names.remove('testall')
suite_names.sort()
alltests = unittest.TestSuite()
for name in suite_names:
m = __import__(name, globals(), locals(), [])
alltests.addTest(m.suite)
a = unittest.TextTestRunner(verbosity=2).run(alltests)
if coverage:
coverage.stop()
else:
print "Coverage module not found. Skipping coverage report."
print "\nResult", a
if not a.wasSuccessful():
sys.exit(1)
if coverage:
all_sources = []
def incl(d):
for x in os.listdir(d):
if x.endswith('.py'):
all_sources.append(os.path.join(d, x))
incl('..')
coverage.report(all_sources + ['../0publish'])
|
Add simple login form in the API.
This is usefull for developers to explore the Browlable api directly
on the browser.
|
"""snowman URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import RedirectView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('api.router')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^.*$', RedirectView.as_view(pattern_name='api-root', permanent=True), name='index')
]
|
"""snowman URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import RedirectView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('api.router')),
url(r'^.*$', RedirectView.as_view(pattern_name='api-root', permanent=True), name='index')
]
|
Make the Registry use the manager option
|
<?php
/**
* This file is part of the PierstovalCharacterManagerBundle package.
*
* (c) Alexandre Rock Ancelet <pierstoval@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pierstoval\Bundle\CharacterManagerBundle\Registry;
use Pierstoval\Bundle\CharacterManagerBundle\Action\StepActionInterface;
class ActionsRegistry implements ActionsRegistryInterface
{
/**
* @var StepActionInterface[][]
*/
private $actions = [];
public function addStepAction(string $manager, StepActionInterface $action): void
{
$this->actions[$manager][$action->getStep()->getName()] = $action;
}
/**
* @return StepActionInterface[]
*/
public function getActions(): array
{
return $this->actions;
}
public function getAction(string $stepName, string $manager = null): StepActionInterface
{
if (!$manager) {
$manager = array_keys($this->actions)[0];
}
if (!isset($this->actions[$manager][$stepName])) {
throw new \InvalidArgumentException('Step "'.$stepName.'" not found in registry.');
}
return $this->actions[$manager][$stepName];
}
}
|
<?php
/**
* This file is part of the PierstovalCharacterManagerBundle package.
*
* (c) Alexandre Rock Ancelet <pierstoval@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pierstoval\Bundle\CharacterManagerBundle\Registry;
use Pierstoval\Bundle\CharacterManagerBundle\Action\StepActionInterface;
class ActionsRegistry
{
/**
* @var StepActionInterface[]
*/
private $actions = [];
public function addStepAction(StepActionInterface $action): void
{
$this->actions[$action->getStep()->getName()] = $action;
}
/**
* @return StepActionInterface[]
*/
public function getActions(): array
{
return $this->actions;
}
public function getAction(string $stepName): StepActionInterface
{
if (!array_key_exists($stepName, $this->actions)) {
throw new \InvalidArgumentException('Step "'.$stepName.'" not found in registry.');
}
return $this->actions[$stepName];
}
}
|
Change json file to sample one
|
#coding=utf-8
#imports
import pystache as ps
import sys
import json
import imp
views = imp.load_source('views', 'swedish/views.py')
#from views import Invoice
def main():
configFile = "invoice.sample.json"
htmlFile = "invoice.html"
if len(sys.argv) == 2 :
configFile = sys.argv[1]
htmlFile = configFile[:-4] + "html"
f = open(configFile, "r")
file_content = f.read()
content = json.loads(file_content)
invoice = views.Invoice(content)
renderer = ps.Renderer(file_encoding="utf-8", string_encoding="utf-8")
html = renderer.render(invoice)
fout = open(htmlFile, "w")
fout.write(html.encode("UTF-8"))
if __name__ == "__main__":
main()
|
#coding=utf-8
#imports
import pystache as ps
import sys
import json
import imp
views = imp.load_source('views', 'swedish/views.py')
#from views import Invoice
def main():
configFile = "invoice.json"
htmlFile = "invoice.html"
if len(sys.argv) == 2 :
configFile = sys.argv[1]
htmlFile = configFile[:-4] + "html"
f = open(configFile, "r")
file_content = f.read()
content = json.loads(file_content)
invoice = views.Invoice(content)
renderer = ps.Renderer(file_encoding="utf-8", string_encoding="utf-8")
html = renderer.render(invoice)
fout = open(htmlFile, "w")
fout.write(html.encode("UTF-8"))
if __name__ == "__main__":
main()
|
Refactor to avoid dynamic module resolution
|
'use strict';
/**
* Node version.
*
* @module @stdlib/process/node-version
* @type {(string|null)}
*
* @example
* var semver = require( 'semver' );
* var VERSION = require( '@stdlib/process/node-version' );
*
* if ( semver.lt( VERSION, '1.0.0' ) ) {
* console.log( 'Running on a pre-io.js version...' );
* }
* else if ( semver.lt( VERSION, '4.0.0' ) ) {
* console.log( 'Running on an io.js version...' );
* }
* else {
* console.log( 'Running on a post-io.js version...' );
* }
*/
// MODULES //
var IS_NODE = require( '@stdlib/assert/is-node' );
var node = require( './version.js' );
var browser = require( './browser.js' );
// MAIN //
var VERSION;
if ( IS_NODE ) {
VERSION = node;
} else {
VERSION = browser;
}
// EXPORTS //
module.exports = VERSION;
|
'use strict';
/**
* Node version.
*
* @module @stdlib/process/node-version
* @type {(string|null)}
*
* @example
* var semver = require( 'semver' );
* var VERSION = require( '@stdlib/process/node-version' );
*
* if ( semver.lt( VERSION, '1.0.0' ) ) {
* console.log( 'Running on a pre-io.js version...' );
* }
* else if ( semver.lt( VERSION, '4.0.0' ) ) {
* console.log( 'Running on an io.js version...' );
* }
* else {
* console.log( 'Running on a post-io.js version...' );
* }
*/
// MODULES //
var IS_NODE = require( '@stdlib/assert/is-node' );
// MAIN //
var VERSION;
if ( IS_NODE ) {
VERSION = require( './version.js' );
} else {
VERSION = require( './browser.js' );
}
// EXPORTS //
module.exports = VERSION;
|
Fix minor issue with Contributor component
|
import React, { Component, PropTypes } from "react"
import cx from "classnames"
import Avatar from "../Avatar"
export default class Contributor extends Component {
static propTypes = {
author: PropTypes.string.isRequired,
commits: PropTypes.number,
size: PropTypes.string,
}
render() {
const {
author,
commits,
size,
} = this.props
return (
<div
key={ author }
className={ cx(
"putainde-Contributor",
"r-Tooltip",
"r-Tooltip--bottom",
"r-Tooltip--allowNewLines"
) }
data-r-tooltip={ [
author,
`(${ commits } commit${ commits > 1 ? "s" : "" })`,
].join("\n") }
>
<Avatar
author={ author }
className={
`putainde-Contributor-avatar${ size ? `--${ size }` : "" }`
}
/>
</div>
)
}
}
|
import React, { Component, PropTypes } from "react"
import cx from "classnames"
import Avatar from "../Avatar"
export default class Contributors extends Component {
static propTypes = {
author: PropTypes.string.isRequired,
commits: PropTypes.string,
size: PropTypes.string,
}
render() {
const {
author,
commits,
size,
} = this.props
return (
<div
key={ author }
className={ cx(
"putainde-Contributor",
"r-Tooltip",
"r-Tooltip--bottom",
"r-Tooltip--allowNewLines"
) }
data-r-tooltip={ [
author,
`(${ commits } commit${ commits > 1 ? "s" : "" })`,
].join("\n") }
>
<Avatar
author={ author }
className={
`putainde-Contributor-avatar${ size ? `--${ size }` : "" }`
}
/>
</div>
)
}
}
|
Use pathlib for path segmentation
|
from collections import defaultdict
from pathlib import Path
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
segments = src.parts[1:-1]
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
node = root
for s in segments:
node = node[s]
def walk(node, parent='.', level=0):
elems = sorted((k, v) for k, v in node.items())
for name, subs in elems:
indent = ' ' * level
path = f'{parent}/{name}'
link = f'[[{path}][{name}]]'
yield f'{indent}- {link}'
yield from walk(subs, path, level + 1)
with open('README.org') as f:
head = f.read()
with open('templates/index.org') as f:
template = Template(f.read())
index = '\n'.join(walk(root))
body = template.safe_substitute(index=index)
TARGET = sys.argv[1]
content = '\n'.join([head, body])
with open(TARGET, 'w') as f:
f.write(content)
|
Add socket echo util function for adminBroadcast
|
const { ERROR } = require('../common/actionTypes/error');
const mergePermanentAndMetadata = (perm, meta) => Object.assign(perm, meta);
const createSocketObject = (channel, payload, metadata) => {
const obj = mergePermanentAndMetadata({
type: channel,
}, metadata);
obj.data = payload;
return obj;
};
const broadcast = (socket, channel, payload, metadata) => {
socket.broadcast.emit('action', createSocketObject(channel, payload, metadata));
};
const emit = (socket, channel, payload, metadata) => {
socket.emit('action', createSocketObject(channel, payload, metadata));
};
const broadcastAndEmit = (socket, channel, payload, metadata) => {
broadcast(socket, channel, payload, metadata);
emit(socket, channel, payload, metadata);
};
const adminBroadcast = (socket, channel, payload, metadata) => {
socket.to('admin').emit('action', createSocketObject(channel, payload, metadata));
};
function adminBroadcastAndEmit(socket, channel, payload, metadata) {
adminBroadcast(socket, channel, payload, metadata);
emit(socket, channel, payload, metadata);
}
let errorCounter = 0;
const emitError = (socket, error) => {
emit(socket, ERROR, {
message: error.message,
id: errorCounter,
});
// Hack to produce deterministic snapshots
if (process.env.NODE_ENV !== 'test') {
errorCounter += 1;
}
};
module.exports = {
broadcast,
emit,
broadcastAndEmit,
adminBroadcast,
adminBroadcastAndEmit,
emitError,
};
|
const { ERROR } = require('../common/actionTypes/error');
const mergePermanentAndMetadata = (perm, meta) => Object.assign(perm, meta);
const createSocketObject = (channel, payload, metadata) => {
const obj = mergePermanentAndMetadata({
type: channel,
}, metadata);
obj.data = payload;
return obj;
};
const broadcast = (socket, channel, payload, metadata) => {
socket.broadcast.emit('action', createSocketObject(channel, payload, metadata));
};
const emit = (socket, channel, payload, metadata) => {
socket.emit('action', createSocketObject(channel, payload, metadata));
};
const broadcastAndEmit = (socket, channel, payload, metadata) => {
broadcast(socket, channel, payload, metadata);
emit(socket, channel, payload, metadata);
};
const adminBroadcast = (socket, channel, payload, metadata) => {
socket.to('admin').emit('action', createSocketObject(channel, payload, metadata));
};
let errorCounter = 0;
const emitError = (socket, error) => {
emit(socket, ERROR, {
message: error.message,
id: errorCounter,
});
// Hack to produce deterministic snapshots
if (process.env.NODE_ENV !== 'test') {
errorCounter += 1;
}
};
module.exports = {
broadcast,
emit,
broadcastAndEmit,
adminBroadcast,
emitError,
};
|
Fix test by actually setting package source to have no name
|
from nose.tools import istest, assert_equal
from whack.naming import PackageNamer
@istest
def package_with_unnamed_source_has_name_equal_to_install_identifier():
package_source = PackageSource("/tmp/nginx-src", None)
package_name = _name_package(package_source, {})
assert_equal("install-id(/tmp/nginx-src, {})", package_name)
def _name_package(package_source, params):
package_namer = PackageNamer(_generate_install_id)
return package_namer.name_package(package_source, {})
def _generate_install_id(source_dir_path, params):
return "install-id({0}, {1})".format(source_dir_path, params)
class PackageSource(object):
def __init__(self, path, name):
self.path = path
self._name = name
def name(self):
return self._name
|
from nose.tools import istest, assert_equal
from whack.naming import PackageNamer
@istest
def package_with_unnamed_source_has_name_equal_to_install_identifier():
package_source = PackageSource("/tmp/nginx-src", "nginx")
package_name = _name_package(package_source, {})
assert_equal("install-id(/tmp/nginx-src, {})", package_name)
def _name_package(package_source, params):
package_namer = PackageNamer(_generate_install_id)
return package_namer.name_package(package_source, {})
def _generate_install_id(source_dir_path, params):
return "install-id({0}, {1})".format(source_dir_path, params)
class PackageSource(object):
def __init__(self, path, name):
self.path = path
self._name = name
def name(self):
return self._name
|
Remove some extraneous comments and fix a spacing problem.
|
var ABTestHelper = require('../ABTestHelper.js');
module.exports['Test Input'] = {
setUp: function(callback) {
this.abTestHelper = new ABTestHelper();
this.abTestHelper.addVersion('A', { name: 'Original', eventCount: 1356, totalCount: 3150 });
this.abTestHelper.addVersion('B', { name: 'Original', eventCount: 1356, totalCount: 0 });
callback();
},
'Has Enough Data - Test existence of version': function(test) {
test.ok(this.abTestHelper);
var that = this;
test.throws(function() {
that.abTestHelper.hasEnoughData('F');
}, Error, 'Version F should not have existed.');
test.doesNotThrow(function() {
that.abTestHelper.hasEnoughData('A');
}, Error, 'Version A should have existed.');
test.done();
},
'Get Rate - Divide by zero': function(test) {
test.ok(this.abTestHelper);
var that = this;
test.throws(function() {
that.abTestHelper.getRate('B');
}, Error, 'Total is zero: cannot divide by zero to produce rate.');
test.done();
},
};
|
var ABTestHelper = require('../ABTestHelper.js');
module.exports['Test Input'] = {
setUp: function(callback) {
// Put test setup here
// Test wildly varying input on existing functions and see if
// the expected result is obtained.
// Get Results - no data, lots of data,
// initialize vars and stuff
this.abTestHelper = new ABTestHelper();
this.abTestHelper.addVersion('A', { name: 'Original', eventCount: 1356, totalCount: 3150 });
this.abTestHelper.addVersion('B', { name: 'Original', eventCount: 1356, totalCount: 0 });
callback();
},
'Has Enough Data - Test existence of version': function(test) {
test.ok(this.abTestHelper);
var that = this;
test.throws(function() {
that.abTestHelper.hasEnoughData('F');
}, Error, 'Version F should not have existed.');
test.doesNotThrow(function() {
that.abTestHelper.hasEnoughData('A');
}, Error, 'Version A should have existed.');
test.done();
},
'Get Rate - Divide by zero': function(test) {
test.ok(this.abTestHelper);
var that = this;
test.throws(function() {
that.abTestHelper.getRate('B');
}, Error, 'Total is zero: cannot divide by zero to produce rate.');
test.done();
},
};
|
Format migration for Django 1.7
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('cms', '0011_auto_20150419_1006'),
]
operations = [
migrations.AlterField(
model_name='globalpagepermission',
name='sites',
field=models.ManyToManyField(help_text='If none selected, user haves granted permissions to all sites.', to='sites.Site', verbose_name='sites', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='usersettings',
name='user',
field=models.OneToOneField(related_name='djangocms_usersettings', editable=False, to=settings.AUTH_USER_MODEL),
preserve_default=True,
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import django.contrib.auth.models
class Migration(migrations.Migration):
dependencies = [
('cms', '0011_auto_20150419_1006'),
]
operations = [
migrations.AlterModelManagers(
name='pageuser',
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.AlterField(
model_name='globalpagepermission',
name='sites',
field=models.ManyToManyField(blank=True, to='sites.Site', verbose_name='sites', help_text='If none selected, user haves granted permissions to all sites.'),
),
migrations.AlterField(
model_name='usersettings',
name='user',
field=models.OneToOneField(to=settings.AUTH_USER_MODEL, editable=False, related_name='djangocms_usersettings'),
),
]
|
Make deleting build plan and repository default when deleting participation
|
(function () {
'use strict';
angular
.module('exerciseApplicationApp')
.controller('ParticipationDeleteController', ParticipationDeleteController);
ParticipationDeleteController.$inject = ['$uibModalInstance', 'entity', 'Participation'];
function ParticipationDeleteController($uibModalInstance, entity, Participation) {
var vm = this;
vm.participation = entity;
vm.deleteBuildPlan = true;
vm.deleteRepository = true;
vm.clear = clear;
vm.confirmDelete = confirmDelete;
function clear() {
$uibModalInstance.dismiss('cancel');
}
function confirmDelete(id, deleteBuildPlan, deleteRepository) {
Participation.delete({
id: id,
deleteBuildPlan: deleteBuildPlan,
deleteRepository: deleteRepository
},
function () {
$uibModalInstance.close(true);
});
}
}
})();
|
(function () {
'use strict';
angular
.module('exerciseApplicationApp')
.controller('ParticipationDeleteController', ParticipationDeleteController);
ParticipationDeleteController.$inject = ['$uibModalInstance', 'entity', 'Participation'];
function ParticipationDeleteController($uibModalInstance, entity, Participation) {
var vm = this;
vm.participation = entity;
vm.clear = clear;
vm.confirmDelete = confirmDelete;
function clear() {
$uibModalInstance.dismiss('cancel');
}
function confirmDelete(id, deleteBuildPlan, deleteRepository) {
Participation.delete({
id: id,
deleteBuildPlan: deleteBuildPlan,
deleteRepository: deleteRepository
},
function () {
$uibModalInstance.close(true);
});
}
}
})();
|
Test out the live transport.
|
"use babel";
import async from "async";
import GitHubClient from "node-github";
import package from "../../../package.json";
import Fork from "../../models/fork";
var github = new GitHubClient({
version: "3.0.0",
debug: true,
headers: {
"user-agent": `atom-pull-request/${package.version}` // GitHub is happy with a unique user agent
}
});
module.exports = {
getImportantForks: function (repository, callback) {
let makeFork = function (repo) {
return new Fork(repository, repo.full_name, repo.default_branch);
};
async.waterfall([
(cb) => repository.originID(cb),
(repoID, cb) => github.repos.get(repoID, cb)
], (err, repo) => {
if (err) return callback(err);
callback(null, {
current: makeFork(repo),
source: makeFork(repo.source || repo)
});
});
},
getAvailableForks: function (repository, callback) {
},
getAvailableBranches: function (fork, callback) {
}
};
|
"use babel";
import async from "async";
import GitHubClient from "node-github";
import package from "../../../package.json";
import Fork from "../../models/fork";
var github = new GitHubClient({
version: "3.0.0",
debug: true,
headers: {
"user-agent": `atom-pull-request/${package.version}` // GitHub is happy with a unique user agent
}
});)
module.exports = {
getImportantForks: function (repository, callback) {
let makeFork = function (repo) {
return new Fork(repository, repo.full_name, repo.default_branch);
};
async.waterfall([
(cb) => repository.originID(cb),
(repoID, cb) => github.repos.get(repoID, cb)
], (err, repo) => {
if (err) return callback(err);
callback(null, {
current: makeFork(repo),
source: makeFork(repo.source)
});
});
},
getAvailableForks: function (repository, callback) {
},
getAvailableBranches: function (fork, callback) {
}
};
|
Add left and right margin for spacing
|
@extends('components.content-area')
@section('content')
<img class="w-full block" src="/styleguide/image/1600x580?text=Full%20Width%20Image" />
<div class="bg-grey-lightest mb-4">
<div class="row py-4">
<p class="mx-4 py-2 text-4xl text-grey-darkest font-serif text-center">"{{ $faker->paragraph(3) }}"</p>
</div>
</div>
<div class="row content mx-4">
<h2>{{ $faker->words(2, true) }}</h2>
<p>{{ $faker->paragraph(10) }}</p>
<p>{{ $faker->paragraph(10) }}</p>
<p>{{ $faker->paragraph(10) }}</p>
</div>
@endsection
|
@extends('components.content-area')
@section('content')
<img class="w-full block" src="/styleguide/image/1600x580?text=Full%20Width%20Image" />
<div class="bg-grey-lightest mb-4">
<div class="row py-4">
<p class="py-2 text-4xl text-grey-darkest font-serif text-center">"{{ $faker->paragraph(3) }}"</p>
</div>
</div>
<div class="row content">
<h2>{{ $faker->words(2, true) }}</h2>
<p>{{ $faker->paragraph(10) }}</p>
<p>{{ $faker->paragraph(10) }}</p>
<p>{{ $faker->paragraph(10) }}</p>
</div>
@endsection
|
Add @Issue to reference JENKINS-44052
|
package jenkins.util;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static jenkins.util.TimeDuration.*;
@Issue("JENKINS-44052")
public class TimeDurationTest {
@Test
public void fromString() throws Exception {
assertEquals(1, TimeDuration.fromString("1").getTimeInMillis());
assertEquals(1000, TimeDuration.fromString("1sec").getTimeInMillis());
assertEquals(1000, TimeDuration.fromString("1secs").getTimeInMillis());
assertEquals(1000, TimeDuration.fromString("1 secs ").getTimeInMillis());
assertEquals(1000, TimeDuration.fromString(" 1 secs ").getTimeInMillis());
assertEquals(1, TimeDuration.fromString(" 1 secs ").getTimeInSeconds());
assertEquals(21000, TimeDuration.fromString(" 21 secs ").getTimeInMillis());
assertEquals(21, TimeDuration.fromString(" 21 secs ").getTimeInSeconds());
}
}
|
package jenkins.util;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static jenkins.util.TimeDuration.*;
public class TimeDurationTest {
@Test
public void fromString() throws Exception {
assertEquals(1, TimeDuration.fromString("1").getTimeInMillis());
assertEquals(1000, TimeDuration.fromString("1sec").getTimeInMillis());
assertEquals(1000, TimeDuration.fromString("1secs").getTimeInMillis());
assertEquals(1000, TimeDuration.fromString("1 secs ").getTimeInMillis());
assertEquals(1000, TimeDuration.fromString(" 1 secs ").getTimeInMillis());
assertEquals(1, TimeDuration.fromString(" 1 secs ").getTimeInSeconds());
assertEquals(21000, TimeDuration.fromString(" 21 secs ").getTimeInMillis());
assertEquals(21, TimeDuration.fromString(" 21 secs ").getTimeInSeconds());
}
}
|
Rebase most recent alembic change onto HEAD
|
"""add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
|
"""add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '28e56bf6f62c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
|
Update ApiRequest to not pass -d for empty data
'cf curl' has changed such that passing -d for empty data is an error.
Signed-off-by: Kris Hicks <6d3f751023bc04266d4da2ff94804f4240839fe2@pivotal.io>
|
package cf
import (
"encoding/json"
"strings"
"time"
. "github.com/onsi/gomega"
"github.com/cloudfoundry-incubator/cf-test-helpers/runner"
)
//var CfApiTimeout = 30 * time.Second
type GenericResource struct {
Metadata struct {
Guid string `json:"guid"`
} `json:"metadata"`
}
type QueryResponse struct {
Resources []GenericResource `struct:"resources"`
}
var ApiRequest = func(method, endpoint string, response interface{}, timeout time.Duration, data ...string) {
args := []string{
"curl",
endpoint,
"-X", method,
}
dataArg := strings.Join(data, "")
if len(dataArg) > 0 {
args = append(args, "-d", dataArg)
}
request := Cf(args...)
runner.NewCmdRunner(request, timeout).Run()
if response != nil {
err := json.Unmarshal(request.Out.Contents(), response)
Expect(err).ToNot(HaveOccurred())
}
}
|
package cf
import (
"encoding/json"
"strings"
"time"
. "github.com/onsi/gomega"
"github.com/cloudfoundry-incubator/cf-test-helpers/runner"
)
//var CfApiTimeout = 30 * time.Second
type GenericResource struct {
Metadata struct {
Guid string `json:"guid"`
} `json:"metadata"`
}
type QueryResponse struct {
Resources []GenericResource `struct:"resources"`
}
var ApiRequest = func(method, endpoint string, response interface{}, timeout time.Duration, data ...string) {
request := Cf(
"curl",
endpoint,
"-X", method,
"-d", strings.Join(data, ""),
)
runner.NewCmdRunner(request, timeout).Run()
if response != nil {
err := json.Unmarshal(request.Out.Contents(), response)
Expect(err).ToNot(HaveOccurred())
}
}
|
Fix missing opts in registerChannel
|
// Setup
const HTTPServer = require('./lib/http_server')
// Exports
module.exports = Oacp
// Oacp Constructor
function Oacp (namespace) {
var self = this
self.models = {}
self.channels = {}
self.controllers = {}
self.config = require('./config/app')(namespace)
self._ns = self.config.app.namespace
self.server = {http: new HTTPServer(self)}
return self
}
/* COMPONENT REGISTRATION */
// Register model, returning the new model's Class
Oacp.prototype.registerModel = function (model) {
var app = this
var Model = require('./lib/model')(app, model)
app.models[Model.name] = Model
return Model
}
// Register channel, returning instance of new channel
Oacp.prototype.registerChannel = function (channel, opts) {
var app = this
var Channel = require('./lib/channel')(app, channel)
var thisChannel = Channel.new(opts)
app.channels[Channel.name] = thisChannel
return thisChannel
}
// Register controller, returning instance of new controller
Oacp.prototype.registerController = function (controller, whitelist) {
var app = this
var Controller = require('./lib/controller')(app, controller, whitelist)
var thisController = Controller.new()
app.controllers[Controller.name] = thisController
return thisController
}
|
// Setup
const HTTPServer = require('./lib/http_server')
// Exports
module.exports = Oacp
// Oacp Constructor
function Oacp (namespace) {
var self = this
self.models = {}
self.channels = {}
self.controllers = {}
self.config = require('./config/app')(namespace)
self._ns = self.config.app.namespace
self.server = {http: new HTTPServer(self)}
return self
}
/* COMPONENT REGISTRATION */
// Register model, returning the new model's Class
Oacp.prototype.registerModel = function (model) {
var app = this
var Model = require('./lib/model')(app, model)
app.models[Model.name] = Model
return Model
}
// Register channel, returning instance of new channel
Oacp.prototype.registerChannel = function (channel) {
var app = this
var Channel = require('./lib/channel')(app, channel)
var thisChannel = Channel.new()
app.channels[Channel.name] = thisChannel
return thisChannel
}
// Register controller, returning instance of new controller
Oacp.prototype.registerController = function (controller, whitelist) {
var app = this
var Controller = require('./lib/controller')(app, controller, whitelist)
var thisController = Controller.new()
app.controllers[Controller.name] = thisController
return thisController
}
|
Make pubmed hash accessible to API
|
from pubrunner.command_line import *
from pubrunner.upload import *
from pubrunner.FTPClient import *
from pubrunner.getresource import *
from pubrunner.pubrun import pubrun,cleanWorkingDirectory
from pubrunner.convert import *
from pubrunner.pubmed_hash import pubmed_hash
def loadYAML(yamlFilename):
yamlData = None
with open(yamlFilename,'r') as f:
try:
yamlData = yaml.load(f)
except yaml.YAMLError as exc:
print(exc)
raise
return yamlData
def findSettingsFile():
possibilities = [ os.getcwd(), os.path.expanduser("~") ]
for directory in possibilities:
settingsPath = os.path.join(directory,'.pubrunner.settings.yml')
if os.path.isfile(settingsPath):
return settingsPath
raise RuntimeError("Unable to find .pubrunner.settings.yml file. Tried current directory first, then home directory")
globalSettings = None
def getGlobalSettings():
global globalSettings
if globalSettings is None:
settingsYamlFile = findSettingsFile()
globalSettings = loadYAML(settingsYamlFile)
return globalSettings
|
from pubrunner.command_line import *
from pubrunner.upload import *
from pubrunner.FTPClient import *
from pubrunner.getresource import *
from pubrunner.pubrun import pubrun,cleanWorkingDirectory
from pubrunner.convert import *
def loadYAML(yamlFilename):
yamlData = None
with open(yamlFilename,'r') as f:
try:
yamlData = yaml.load(f)
except yaml.YAMLError as exc:
print(exc)
raise
return yamlData
def findSettingsFile():
possibilities = [ os.getcwd(), os.path.expanduser("~") ]
for directory in possibilities:
settingsPath = os.path.join(directory,'.pubrunner.settings.yml')
if os.path.isfile(settingsPath):
return settingsPath
raise RuntimeError("Unable to find .pubrunner.settings.yml file. Tried current directory first, then home directory")
globalSettings = None
def getGlobalSettings():
global globalSettings
if globalSettings is None:
settingsYamlFile = findSettingsFile()
globalSettings = loadYAML(settingsYamlFile)
return globalSettings
|
Update PyPI classifiers and test requirements
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='bandicoot',
author='Yves-Alexandre de Montjoye',
author_email='yvesalexandre@demontjoye.com',
version="0.4",
url="https://github.com/yvesalexandre/bandicoot",
license="MIT",
packages=[
'bandicoot',
'bandicoot.helper',
'bandicoot.tests',
'bandicoot.special'
],
description="A toolbox to analyze mobile phone metadata.",
classifiers=[
'Environment :: Plugins',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Scientific/Engineering :: Mathematics'
],
extras_require={
'tests': ['numpy', 'scipy', 'networkx']
})
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='bandicoot',
author='Yves-Alexandre de Montjoye',
author_email='yvesalexandre@demontjoye.com',
version="0.4",
url="https://github.com/yvesalexandre/bandicoot",
license="MIT",
packages=[
'bandicoot',
'bandicoot.helper',
'bandicoot.tests',
'bandicoot.special'
],
description="A toolbox to analyze mobile phone metadata.",
classifiers=[
'Environment :: Plugins',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Scientific/Engineering :: Mathematics'
])
|
Add missing value for sml:axis
|
package com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.sml;
import com.google.gwt.core.shared.GWT;
import com.sensia.relaxNG.RNGElement;
import com.sensia.relaxNG.RNGTag;
import com.sensia.tools.client.swetools.editors.sensorml.panels.IPanel;
import com.sensia.tools.client.swetools.editors.sensorml.panels.line.AbstractGenericLinePanel;
public class SMLEditAxisPanel extends AbstractGenericLinePanel<RNGElement>{
public SMLEditAxisPanel(RNGElement tag) {
super(tag);
}
@Override
protected void addInnerElement(IPanel<? extends RNGTag> element) {
if(element.getName().equals("definition")) {
defPanel.add(element.getPanel());
} else if(element.getName().equals("name")){
labelPanel.add(element.getPanel());
} else if(element.getName().equals("label")){
labelPanel.add(element.getPanel());
} else {
// should be RNGValue or RNGData
afterDotsPanel.add(element.getPanel());
}
}
}
|
package com.sensia.tools.client.swetools.editors.sensorml.renderer.editor.panels.sml;
import com.google.gwt.core.shared.GWT;
import com.sensia.relaxNG.RNGElement;
import com.sensia.relaxNG.RNGTag;
import com.sensia.tools.client.swetools.editors.sensorml.panels.IPanel;
import com.sensia.tools.client.swetools.editors.sensorml.panels.line.AbstractGenericLinePanel;
public class SMLEditAxisPanel extends AbstractGenericLinePanel<RNGElement>{
public SMLEditAxisPanel(RNGElement tag) {
super(tag);
}
@Override
protected void addInnerElement(IPanel<? extends RNGTag> element) {
if(element.getName().equals("definition")) {
defPanel.add(element.getPanel());
} else if(element.getName().equals("name")){
labelPanel.add(element.getPanel());
GWT.log(""+element.getClass());
} else if(element.getName().equals("label")){
labelPanel.add(element.getPanel());
}
}
}
|
test: Add test for double assertion
|
/* eslint-env mocha */
const {expect} = chai;
import React from './React';
import TestUtils from './TestUtils';
describe('React components', () => {
it('should find valid xpath in react component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//blink');
});
it('should find valid xpath in react component twice', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//blink');
expect(component).to.have.xpath('//blink');
});
describe('when it does not find valid xpath in react component', () => {
it('should throw', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(() => {
expect(component).to.have.xpath('//h1');
}).to.throw('to have xpath \'//h1\'');
});
it('should throw with outerHTML of the component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(() => {
expect(component).to.have.xpath('//h1');
}).to.throw('hi</blink>');
});
});
});
|
/* eslint-env mocha */
const {expect} = chai;
import React from './React';
import TestUtils from './TestUtils';
describe('React components', () => {
it('should find valid xpath in react component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//blink');
});
describe('when it does not find valid xpath in react component', () => {
it('should throw', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(() => {
expect(component).to.have.xpath('//h1');
}).to.throw('to have xpath \'//h1\'');
});
it('should throw with outerHTML of the component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(() => {
expect(component).to.have.xpath('//h1');
}).to.throw('hi</blink>');
});
});
});
|
Add logo to command help information
|
/**
* Copyright 2017-present, Callstack.
* All rights reserved.
*
* @flow
*/
const program = require("commander");
const pjson = require("../../package.json");
const logger = require("../utils/logger")(false);
import type { Command, Context } from "../types";
const commands: Array<Command> = [require("./start")];
const ctx: Context = {
console: console,
};
commands.forEach((command: Command) => {
const options = command.options || [];
const cmd = program
.command(command.name)
.description(command.description)
.action(function run() {
logger.clear();
logger.printLogo();
const options = this.opts();
const argv: Array<string> = Array.from(arguments).slice(0, -1);
command.action(ctx, argv, options);
});
options
.forEach(opt => cmd.option(
opt.name,
opt.description,
opt.parse || ((val) => val),
typeof opt.default === 'function' ? opt.default(ctx) : opt.default,
));
cmd._helpInformation = cmd.helpInformation.bind(cmd);
cmd.helpInformation = function() {
logger.clear();
logger.printLogo(2);
return this._helpInformation();
};
});
program
.command('*', null, { noHelp: true })
.action((cmd) => {
logger.clear();
logger.printLogo();
logger.error(`:x: Command '${cmd}' not recognized`);
program.help();
});
program.version(pjson.version).parse(process.argv);
|
/**
* Copyright 2017-present, Callstack.
* All rights reserved.
*
* @flow
*/
const program = require("commander");
const pjson = require("../../package.json");
const logger = require("../utils/logger")(false);
import type { Command, Context } from "../types";
const commands: Array<Command> = [require("./start")];
const ctx: Context = {
console: console,
};
commands.forEach((command: Command) => {
const options = command.options || [];
const cmd = program
.command(command.name)
.description(command.description)
.action(function run() {
logger.clear();
logger.printLogo();
const options = this.opts();
const argv: Array<string> = Array.from(arguments).slice(0, -1);
command.action(ctx, argv, options);
});
options
.forEach(opt => cmd.option(
opt.name,
opt.description,
opt.parse || ((val) => val),
typeof opt.default === 'function' ? opt.default(ctx) : opt.default,
));
});
program
.command('*', null, { noHelp: true })
.action((cmd) => {
logger.clear();
logger.printLogo();
logger.error(`:x: Command '${cmd}' not recognized`);
program.help();
});
program.version(pjson.version).parse(process.argv);
|
Change prompt to just '>'.
|
function eval_clojure(code) {
var data;
$.ajax({
url: "eval.json",
data: { expr : code },
async: false,
success: function(res) { data = res; }
});
return data;
}
function html_escape(val) {
var result = val;
result = result.replace(/\n/g, "<br/>");
result = result.replace(/[<]/g, "<");
result = result.replace(/[>]/g, ">");
return result;
}
function onValidate(input) {
return (input != "");
}
function onHandle(line, report) {
var input = $.trim(line);
// perform evaluation
var data = eval_clojure(input);
// handle error
if (data.error) {
return [{msg: data.message, className: "jquery-console-message-error"}];
}
// display expr results
return [{msg: data.result, className: "jquery-console-message-value"}];
}
var controller;
$(document).ready(function() {
controller = $("#console").console({
welcomeMessage:'',
promptLabel: '> ',
commandValidate: onValidate,
commandHandle: onHandle,
autofocus:true,
animateScroll:true,
promptHistory:true
});
});
|
function eval_clojure(code) {
var data;
$.ajax({
url: "eval.json",
data: { expr : code },
async: false,
success: function(res) { data = res; }
});
return data;
}
function html_escape(val) {
var result = val;
result = result.replace(/\n/g, "<br/>");
result = result.replace(/[<]/g, "<");
result = result.replace(/[>]/g, ">");
return result;
}
function onValidate(input) {
return (input != "");
}
function onHandle(line, report) {
var input = $.trim(line);
// perform evaluation
var data = eval_clojure(input);
// handle error
if (data.error) {
return [{msg: data.message, className: "jquery-console-message-error"}];
}
// display expr results
return [{msg: data.result, className: "jquery-console-message-value"}];
}
var controller;
$(document).ready(function() {
controller = $("#console").console({
welcomeMessage:'',
promptLabel: 'isla> ',
commandValidate: onValidate,
commandHandle: onHandle,
autofocus:true,
animateScroll:true,
promptHistory:true
});
});
|
Remove useless parenthesis in qrcode python demo
|
#!/usr/bin/env python
import StringIO
import angus
import cv2
import numpy as np
if __name__ == '__main__':
### Web cam index might be different from 0 on your setup.
stream_index = 0
cap = cv2.VideoCapture(stream_index)
if not cap.isOpened():
print "Cannot open stream of index " + str(stream_index)
exit(1)
print "Video stream is of resolution " + str(cap.get(3)) + " x " + str(cap.get(4))
conn = angus.connect()
service = conn.services.get_service("qrcode_decoder", version=1)
service.enable_session()
while cap.isOpened():
ret, frame = cap.read()
if frame is None:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret, buff = cv2.imencode(".jpg", gray)
buff = StringIO.StringIO(np.array(buff).tostring())
job = service.process({"image": buff})
if "data" in job.result:
print job.result["data"]
cv2.imshow('original', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
service.disable_session()
cap.release()
cv2.destroyAllWindows()
|
#!/usr/bin/env python
import StringIO
import angus
import cv2
import numpy as np
if __name__ == '__main__':
### Web cam index might be different from 0 on your setup.
stream_index = 0
cap = cv2.VideoCapture(stream_index)
if not cap.isOpened():
print "Cannot open stream of index " + str(stream_index)
exit(1)
print "Video stream is of resolution " + str(cap.get(3)) + " x " + str(cap.get(4))
conn = angus.connect()
service = conn.services.get_service("qrcode_decoder", version=1)
service.enable_session()
while(cap.isOpened()):
ret, frame = cap.read()
if frame is None:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret, buff = cv2.imencode(".jpg", gray)
buff = StringIO.StringIO(np.array(buff).tostring())
job = service.process({"image": buff})
if "data" in job.result:
print job.result["data"]
cv2.imshow('original', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
service.disable_session()
cap.release()
cv2.destroyAllWindows()
|
Comment out heapdump for now.
|
#!/usr/bin/env node
/* eslint no-unused-expressions:0 */
'use strict';
// require('heapdump');
require('./lib/configure');
const yargs = require('yargs');
yargs
.strict()
.wrap(Math.min(120, yargs.terminalWidth()))
.version().alias('version', 'v')
.help('help').alias('help', 'h')
.usage('npms-analyzer command line, choose one of the available commands.\n\nUsage: $0 <command> .. [options]')
.option('log-level', {
type: 'string',
default: 'warn',
alias: 'll',
choices: ['fatal', 'error', 'warn', 'info', 'debug', 'trace'],
describe: 'The log level to use',
global: true,
})
.commandDir('./cmd')
.demandCommand(1, 'Please supply a valid command')
.argv;
|
#!/usr/bin/env node
/* eslint no-unused-expressions:0 */
'use strict';
require('heapdump');
require('./lib/configure');
const yargs = require('yargs');
yargs
.strict()
.wrap(Math.min(120, yargs.terminalWidth()))
.version().alias('version', 'v')
.help('help').alias('help', 'h')
.usage('npms-analyzer command line, choose one of the available commands.\n\nUsage: $0 <command> .. [options]')
.option('log-level', {
type: 'string',
default: 'warn',
alias: 'll',
choices: ['fatal', 'error', 'warn', 'info', 'debug', 'trace'],
describe: 'The log level to use',
global: true,
})
.commandDir('./cmd')
.demandCommand(1, 'Please supply a valid command')
.argv;
|
Fix STPA modeling elements can't be loaded from saved model
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
|
"""The RAAML Modeling Language module is the entrypoint for RAAML related
assets."""
import gaphor.SysML.propertypages # noqa
from gaphor.abc import ModelingLanguage
from gaphor.core import gettext
from gaphor.diagram.diagramtoolbox import ToolboxDefinition
from gaphor.RAAML import diagramitems, raaml
from gaphor.RAAML.toolbox import raaml_toolbox_actions
class RAAMLModelingLanguage(ModelingLanguage):
@property
def name(self) -> str:
return gettext("RAAML")
@property
def toolbox_definition(self) -> ToolboxDefinition:
return raaml_toolbox_actions
def lookup_element(self, name):
element_type = getattr(raaml, name, None)
if not element_type:
element_type = getattr(diagramitems, name, None)
return element_type
|
"""The RAAML Modeling Language module is the entrypoint for RAAML related
assets."""
import gaphor.SysML.propertypages # noqa
from gaphor.abc import ModelingLanguage
from gaphor.core import gettext
from gaphor.diagram.diagramtoolbox import ToolboxDefinition
from gaphor.RAAML import diagramitems
from gaphor.RAAML import fta as raaml
from gaphor.RAAML.toolbox import raaml_toolbox_actions
class RAAMLModelingLanguage(ModelingLanguage):
@property
def name(self) -> str:
return gettext("RAAML")
@property
def toolbox_definition(self) -> ToolboxDefinition:
return raaml_toolbox_actions
def lookup_element(self, name):
element_type = getattr(raaml, name, None)
if not element_type:
element_type = getattr(diagramitems, name, None)
return element_type
|
Fix typo in search listener
|
package com.uservoice.uservoicesdk.ui;
import android.widget.SearchView;
import com.uservoice.uservoicesdk.activity.SearchActivity;
public class SearchQueryListener implements SearchView.OnQueryTextListener {
private final SearchActivity searchActivity;
public SearchQueryListener(SearchActivity searchActivity) {
this.searchActivity = searchActivity;
}
@Override
public boolean onQueryTextSubmit(String query) {
searchActivity.getSearchAdapter().performSearch(query);
return true;
}
@Override
public boolean onQueryTextChange(String query) {
searchActivity.getSearchAdapter().performSearch(query);
if (query.length() > 0) {
searchActivity.showSearch();
} else {
searchActivity.hideSearch();
}
return true;
}
}
|
package com.uservoice.uservoicesdk.ui;
import android.widget.SearchView;
import com.uservoice.uservoicesdk.activity.SearchActivity;
public class SearchQueryListener implements SearchView.OnQueryTextListener {
private final SearchActivity searchActivity;
public SearchQueryListener(SearchActivity searchActivity) {
this.searchActivity = searchActivity;
}
@Override
public boolean onQueryTextSubmit(String query) {
searchActivity.getSearchAdapter().performSearch(query);
return true;
}
@Override
public boolean onQueryTextChange(String query) {
searchActivity.getSearchAdapter().performSearch(query);
if (query.length() == 0) {
searchActivity.showSearch();
} else {
searchActivity.hideSearch();
}
return true;
}
}
|
Add configuration flag to enable addon
|
/* jshint node: true */
'use strict';
var fs = require('fs');
var path = require('path');
function readSnippet() {
try {
return fs.readFileSync(path.join(process.cwd(), 'vendor/newrelic-snippet.html'), {
encoding: 'UTF-8'
});
} catch(error) {
if (error.code === 'ENOENT') {
return '';
} else {
throw error;
}
}
}
module.exports = {
name: 'ember-newrelic',
contentFor: function(type, config) {
var content = '';
var enabled = config.newrelicEnabled || config.environment === 'production';
// Warn when no snippet found in development regardless of whether new relic
// is enabled.
if (config.environment === 'development' && !readSnippet()) {
console.warn('No New Relic snippet found, run `ember generate newrelic-license <app-name> <api-key>`');
}
if (enabled && type === 'head') {
content = readSnippet();
}
return content;
}
};
|
/* jshint node: true */
'use strict';
var fs = require('fs');
var path = require('path');
function readSnippet() {
try {
return fs.readFileSync(path.join(process.cwd(), 'vendor/newrelic-snippet.html'), {
encoding: 'UTF-8'
});
} catch(error) {
if (error.code === 'ENOENT') {
return '';
} else {
throw error;
}
}
}
module.exports = {
name: 'ember-newrelic',
contentFor: function(type, config) {
var content = '';
if (config.environment !== 'test' && type === 'head') {
var content = readSnippet();
if (!content) {
console.warn('New Relic disabled: no snippet found, run `ember generate newrelic-license <app-name> <api-key>`');
}
}
return content;
}
};
|
Load files using the new `pack` scene configuration.
|
import files from '@/constants/assets';
import fontConfig from '@/constants/bitmap-fonts';
export default class Loader extends Phaser.Scene {
/**
* Takes care of loading the main game assets.
*
* @extends Phaser.Scene
*/
constructor() {
super({key: 'Loader', pack: {files}});
}
/**
* Called when this scene is initialized.
*
* @protected
* @param {object} [data={}] - Initialization parameters.
*/
init(/* data */) {
// Register our custom bitmap font in he game system cache.
this.cache.bitmapFont.add(
fontConfig.image,
Phaser.GameObjects.RetroFont.Parse(this, fontConfig)
);
// We are done here. Launch the game menu.
this.scene.start('Menu');
}
}
|
import files from '@/constants/assets';
import fontConfig from '@/constants/bitmap-fonts';
export default class Loader extends Phaser.Scene {
/**
* Takes care of loading the main game assets.
*
* @extends Phaser.Scene
*/
constructor() {
super({key: 'Loader', files});
}
/**
* Called when this scene is initialized.
*
* @protected
* @param {object} [data={}] - Initialization parameters.
*/
init(/* data */) {
// Register our custom bitmap font in he game system cache.
this.cache.bitmapFont.add(
fontConfig.image,
Phaser.GameObjects.RetroFont.Parse(this, fontConfig)
);
// We are done here. Launch the game menu.
this.scene.start('Menu');
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.