text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add logging to helper method. | """Helper method for getting artifactory information."""
import logging
from .artifactory import Artifactory
def get_artifactory_info(repo_name=None, repo_type='local'):
"""Get storage info from Artifactory.
Args:
repo_name (tuple, optional): Name of artifactory repo.
repo_type (str): Type of artifactory repo.
Returns:
keys (dict, optional): Dictionary of repo data.
storage_info (dict): Storage information api call.
"""
artifactory = Artifactory(repo_name=repo_name)
storage_info = artifactory.list(repo_type=repo_type)
if repo_name:
keys = repo_name
else:
keys = storage_info.keys()
logging.debug('Storage info: %s', storage_info)
logging.debug('Keys: %s', keys)
return storage_info, keys
| """Helper method for getting artifactory information."""
from .artifactory import Artifactory
def get_artifactory_info(repo_name=None, repo_type='local'):
"""Get storage info from Artifactory.
Args:
repo_name (tuple, optional): Name of artifactory repo.
repo_type (str): Type of artifactory repo.
Returns:
keys (dict, optional): Dictionary of repo data.
storage_info (dict): Storage information api call.
"""
artifactory = Artifactory(repo_name=repo_name)
storage_info = artifactory.list(repo_type=repo_type)
if repo_name:
keys = repo_name
else:
keys = storage_info.keys()
return storage_info, keys
|
Disable p2p exploration in HTTP mode | var assert = require('assert');
var expect = require('chai').expect;
var Fabric = require('../');
describe('App', function () {
it('should expose a constructor', function () {
assert.equal(typeof Fabric.App, 'function');
});
it('should create an application smoothly', async function () {
var app = new Fabric.App();
await app.tips.close();
await app.stash.close();
assert.ok(app);
});
it('should load data from an oracle', async function () {
var oracle = new Fabric.Oracle({
path: './data/oracle'
});
await oracle._load('./resources');
var app = new Fabric.App();
await app._defer(oracle);
//await app._explore();
await app.tips.close();
await app.stash.close();
await oracle.storage.close();
assert.ok(oracle);
assert.ok(app);
});
});
| var assert = require('assert');
var expect = require('chai').expect;
var Fabric = require('../');
describe('App', function () {
it('should expose a constructor', function () {
assert.equal(typeof Fabric.App, 'function');
});
it('should create an application smoothly', async function () {
var app = new Fabric.App();
await app.tips.close();
await app.stash.close();
assert.ok(app);
});
it('should load data from an oracle', async function () {
var oracle = new Fabric.Oracle({
path: './data/oracle'
});
await oracle._load('./resources');
var app = new Fabric.App();
await app._defer(oracle);
await app._explore();
await app.tips.close();
await app.stash.close();
await oracle.storage.close();
assert.ok(oracle);
assert.ok(app);
});
});
|
Make typeable test compatible with IE<=8
[].indexOf is not defined on IE<=8 | steal("src/synthetic.js", function (Syn) {
module("synthetic/typeable");
var isTypeable = Syn.typeable.test;
test("Inputs and textareas", function () {
var input = document.createElement("input");
var textarea = document.createElement("textarea");
equal(isTypeable(input), true, "Input element is typeable.");
equal(isTypeable(textarea), true, "Text area is typeable.");
});
test("Normal divs", function () {
var div = document.createElement("div");
equal(isTypeable(div), false, "Divs are not typeable.");
});
test("Contenteditable div", function () {
var div = document.createElement("div");
// True
div.setAttribute("contenteditable", "true");
equal(isTypeable(div), true, "Divs with contenteditable true");
// Empty string
div.setAttribute("contenteditable", "");
equal(isTypeable(div), true, "Divs with contenteditable as empty string.");
});
test("User defined typeable function", function () {
// We're going to define a typeable with a class of foo.
Syn.typeable(function (node) {
return node.className === "foo";
});
var div = document.createElement("div");
div.className = "foo";
equal(isTypeable(div), true, "Custom function works.");
});
});
| steal("src/synthetic.js", function (Syn) {
module("synthetic/typeable");
var isTypeable = Syn.typeable.test;
test("Inputs and textareas", function () {
var input = document.createElement("input");
var textarea = document.createElement("textarea");
equal(isTypeable(input), true, "Input element is typeable.");
equal(isTypeable(textarea), true, "Text area is typeable.");
});
test("Normal divs", function () {
var div = document.createElement("div");
equal(isTypeable(div), false, "Divs are not typeable.");
});
test("Contenteditable div", function () {
var div = document.createElement("div");
// True
div.setAttribute("contenteditable", "true");
equal(isTypeable(div), true, "Divs with contenteditable true");
// Empty string
div.setAttribute("contenteditable", "");
equal(isTypeable(div), true, "Divs with contenteditable as empty string.");
});
test("User defined typeable function", function () {
// We're going to define a typeable with a class of foo.
Syn.typeable(function (node) {
return node.className.split(" ")
.indexOf("foo") !== -1;
});
var div = document.createElement("div");
div.className = "foo";
equal(isTypeable(div), true, "Custom function works.");
});
});
|
Stop getwork store from displaying Not Founds | #License#
#bitHopper by Colin Rice is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#Based on a work at github.com.
import time
from twisted.internet.task import LoopingCall
class Getwork_store:
def __init__(self, bitHopper):
self.data = {}
self.bitHopper = bitHopper
call = LoopingCall(self.prune)
call.start(60)
def add(self, server, merkle_root):
self.data[merkle_root] = [server, time.time()]
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
#self.bitHopper.log_msg('[' + merkle_root + '] found => ' + self.bitHopper.pool.servers[self.data[merkle_root][0]]['name'])
return self.data[merkle_root][0]
#self.bitHopper.log_msg('[' + merkle_root + '] NOT FOUND!')
return None
def prune(self):
for key, work in self.data.items():
if work[1] < (time.time() - (60*5)):
del self.data[key]
| #License#
#bitHopper by Colin Rice is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
#Based on a work at github.com.
import time
from twisted.internet.task import LoopingCall
class Getwork_store:
def __init__(self, bitHopper):
self.data = {}
self.bitHopper = bitHopper
call = LoopingCall(self.prune)
call.start(60)
def add(self, server, merkle_root):
self.data[merkle_root] = [server, time.time()]
def get_server(self, merkle_root):
if self.data.has_key(merkle_root):
#self.bitHopper.log_msg('[' + merkle_root + '] found => ' + self.bitHopper.pool.servers[self.data[merkle_root][0]]['name'])
return self.data[merkle_root][0]
self.bitHopper.log_msg('[' + merkle_root + '] NOT FOUND!')
return None
def prune(self):
for key, work in self.data.items():
if work[1] < (time.time() - (60*5)):
del self.data[key]
|
Set Content-Type header for S3 uploads
Current document updates do not preserve the content type - it is reset to "application/octet-stream"
We should set the correct content type so that browsers know what to do when users access the documents. | import os
import boto
import datetime
import mimetypes
class S3(object):
def __init__(self, bucket_name=None, host='s3-eu-west-1.amazonaws.com'):
conn = boto.connect_s3(host=host)
self.bucket_name = bucket_name
self.bucket = conn.get_bucket(bucket_name)
def save(self, path, name, file, acl='public-read'):
timestamp = datetime.datetime.utcnow().isoformat()
full_path = os.path.join(path, name)
if self.bucket.get_key(full_path):
self.bucket.copy_key(
os.path.join(path, '{}-{}'.format(timestamp, name)),
self.bucket_name,
full_path
)
key = self.bucket.new_key(full_path)
mimetype, _ = mimetypes.guess_type(key.name)
key.set_contents_from_file(file, headers={'Content-Type': mimetype})
key.set_acl(acl)
| import os
import boto
import datetime
class S3(object):
def __init__(self, bucket_name=None, host='s3-eu-west-1.amazonaws.com'):
conn = boto.connect_s3(host=host)
self.bucket_name = bucket_name
self.bucket = conn.get_bucket(bucket_name)
def save(self, path, name, file, acl='public-read'):
timestamp = datetime.datetime.utcnow().isoformat()
full_path = os.path.join(path, name)
if self.bucket.get_key(full_path):
self.bucket.copy_key(
os.path.join(path, '{}-{}'.format(timestamp, name)),
self.bucket_name,
full_path
)
key = self.bucket.new_key(full_path)
key.set_contents_from_file(file)
key.set_acl(acl)
|
Update sample good page to test changes from 1 to 2 digits | import pytest
from mangacork import utils
@pytest.fixture
def sample_page_bad_format():
sample_page = {'chapter': "chapter1", 'page': 3}
return sample_page
@pytest.fixture
def sample_page_good_format():
sample_page = {'chapter':'manga_ch1', 'page':'x_v001-009'}
return sample_page
def test_build_img_path(sample_page_bad_format):
chapter = sample_page_bad_format["chapter"]
page = sample_page_bad_format["page"]
expected_output = "/chapter1/3"
assert utils.build_img_path(chapter,page) == expected_output
def test_increment_page_number_bad_format(sample_page_bad_format):
with pytest.raises(ValueError):
current_page = utils.build_img_path(sample_page_bad_format["chapter"],
sample_page_bad_format["page"])
utils.increment_page_number(current_page)
def test_increment_page_number_good_format(sample_page_good_format):
chapter = sample_page_good_format["chapter"]
page = sample_page_good_format["page"]
current_page = utils.build_img_path(chapter, page)
next_page = utils.increment_page_number(current_page)
expected_output = '/manga_ch1/x_v001-010'
assert next_page == expected_output
| import pytest
from mangacork import utils
@pytest.fixture
def sample_page_bad_format():
sample_page = {'chapter': "chapter1", 'page': 3}
return sample_page
@pytest.fixture
def sample_page_good_format():
sample_page = {'chapter':'manga_ch1', 'page':'x_v001-001'}
return sample_page
def test_build_img_path(sample_page_bad_format):
chapter = sample_page_bad_format["chapter"]
page = sample_page_bad_format["page"]
expected_output = "/chapter1/3"
assert utils.build_img_path(chapter,page) == expected_output
def test_increment_page_number_bad_format(sample_page_bad_format):
with pytest.raises(ValueError):
current_page = utils.build_img_path(sample_page_bad_format["chapter"],
sample_page_bad_format["page"])
utils.increment_page_number(current_page)
def test_increment_page_number_good_format(sample_page_good_format):
chapter = sample_page_good_format["chapter"]
page = sample_page_good_format["page"]
current_page = utils.build_img_path(chapter, page)
next_page = utils.increment_page_number(current_page)
expected_output = '/manga_ch1/x_v001-002'
assert next_page == expected_output
|
Add join between Subscroptions and Users | RocketChat.cache.Rooms.hasMany('Subscriptions', {
field: 'usernames',
link: {
local: '_id',
remote: 'rid',
transform(room, subscription) {
return subscription.u.username;
},
remove(arr, subscription) {
if (arr.indexOf(subscription.u.username) > -1) {
arr.splice(arr.indexOf(subscription.u.username), 1);
}
}
}
});
RocketChat.cache.Subscriptions.hasOne('Rooms', {
field: '_room',
link: {
local: 'rid',
remote: '_id'
}
});
RocketChat.cache.Subscriptions.hasOne('Users', {
field: '_user',
link: {
local: 'u._id',
remote: '_id'
}
});
RocketChat.cache.Users.load();
RocketChat.cache.Rooms.load();
RocketChat.cache.Subscriptions.load();
RocketChat.cache.Settings.load();
RocketChat.cache.Users.addDynamicView('highlights').applyFind({
'settings.preferences.highlights': {$size: {$gt: 0}}
});
RocketChat.cache.Subscriptions.addDynamicView('notifications').applyFind({
$or: [
{desktopNotifications: {$in: ['all', 'nothing']}},
{mobilePushNotifications: {$in: ['all', 'nothing']}}
]
});
| RocketChat.cache.Rooms.hasMany('Subscriptions', {
field: 'usernames',
link: {
local: '_id',
remote: 'rid',
transform(room, subscription) {
return subscription.u.username;
},
remove(arr, subscription) {
if (arr.indexOf(subscription.u.username) > -1) {
arr.splice(arr.indexOf(subscription.u.username), 1);
}
}
}
});
RocketChat.cache.Subscriptions.hasOne('Rooms', {
field: '_room',
link: {
local: 'rid',
remote: '_id'
}
});
RocketChat.cache.Users.load();
RocketChat.cache.Rooms.load();
RocketChat.cache.Subscriptions.load();
RocketChat.cache.Settings.load();
RocketChat.cache.Users.addDynamicView('highlights').applyFind({
'settings.preferences.highlights': {$size: {$gt: 0}}
});
RocketChat.cache.Subscriptions.addDynamicView('notifications').applyFind({
$or: [
{desktopNotifications: {$in: ['all', 'nothing']}},
{mobilePushNotifications: {$in: ['all', 'nothing']}}
]
});
|
Replace vars with consts and add better comments | // Load the markdown-it regex plugin
const mdRegex = require('markdown-it-regexp')
// Set our chord's identifier regex pattern and replacement string
const chordPattern = mdRegex(
// regexp to match
// Assuming anything within square brackets to be a chord
/\[(\w+)\]/,
// this function will be called when something's in square brackets
function(match, utils) {
return '<span class="chord"><span class="inner">' + match[1] + '</span></span>';
}
)
// Import markdown-it and configure it to use our chordpattern
const md = require('markdown-it')({
html: false, // Enable HTML tags in source
xhtmlOut: true, // Use '/' to close single tags (<br />).
// This is only for full CommonMark compatibility.
breaks: true, // Convert '\n' in paragraphs into <br>
linkify: true, // Autoconvert URL-like text to links
// Enable some language-neutral replacement + quotes beautification
typographer: false,
// Double + single quotes replacement pairs, when typographer enabled,
// and smartquotes on. Could be either a String or an Array.
quotes: '“”‘’'
}).use(chordPattern)
// Export our plugin
module.exports = function generateHtml(chordMarkdownText) {
if(chordMarkdownText === undefined) {
throw new Error('Argument chordMarkdownText is required.');
}
return md.render(data)
} | // Load required plugins
const mdRegex = require('markdown-it-regexp')
var chordPattern = mdRegex(
// regexp to match
// Assuming anything within square brackets to be a chord
/\[(\w+)\]/,
// this function will be called when something's in square brackets
function(match, utils) {
return '<span class="chord"><span class="inner">' + match[1] + '</span></span>';
}
)
var md = require('markdown-it')({
html: false, // Enable HTML tags in source
xhtmlOut: true, // Use '/' to close single tags (<br />).
// This is only for full CommonMark compatibility.
breaks: true, // Convert '\n' in paragraphs into <br>
linkify: true, // Autoconvert URL-like text to links
// Enable some language-neutral replacement + quotes beautification
typographer: false,
// Double + single quotes replacement pairs, when typographer enabled,
// and smartquotes on. Could be either a String or an Array.
quotes: '“”‘’'
}).use(chordPattern);
module.exports = function generateHtml(chordMarkdownText) {
if(chordMarkdownText === undefined) {
throw new Error('Argument chordMarkdownText is required.');
}
return md.render(data)
} |
Update binaries path with private repo | import nose
import driller
import logging
l = logging.getLogger("driller.tests.test_driller")
import os
bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries-private'))
def test_drilling_cgc():
'''
test drilling on the cgc binary, palindrome.
'''
binary = "cgc_scored_event_1/cgc/0b32aa01_01"
# fuzzbitmap says every transition is worth satisfying
d = driller.Driller(os.path.join(bin_location, binary), "AAAA", "\xff"*65535, "whatever~")
new_inputs = d.drill()
nose.tools.assert_equal(len(new_inputs), 7)
# make sure driller produced a new input which hits the easter egg
nose.tools.assert_true(any(filter(lambda x: x[1].startswith('^'), new_inputs)))
def run_all():
functions = globals()
all_functions = dict(filter((lambda (k, v): k.startswith('test_')), functions.items()))
for f in sorted(all_functions.keys()):
if hasattr(all_functions[f], '__call__'):
all_functions[f]()
if __name__ == "__main__":
run_all()
| import nose
import driller
import logging
l = logging.getLogger("driller.tests.test_driller")
import os
bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries'))
def test_drilling_cgc():
'''
test drilling on the cgc binary, palindrome.
'''
binary = "cgc_scored_event_1/cgc/0b32aa01_01"
# fuzzbitmap says every transition is worth satisfying
d = driller.Driller(os.path.join(bin_location, binary), "AAAA", "\xff"*65535, "whatever~")
new_inputs = d.drill()
nose.tools.assert_equal(len(new_inputs), 7)
# make sure driller produced a new input which hits the easter egg
nose.tools.assert_true(any(filter(lambda x: x[1].startswith('^'), new_inputs)))
def run_all():
functions = globals()
all_functions = dict(filter((lambda (k, v): k.startswith('test_')), functions.items()))
for f in sorted(all_functions.keys()):
if hasattr(all_functions[f], '__call__'):
all_functions[f]()
if __name__ == "__main__":
run_all()
|
Introduce version: 0.4.0, this is a fourth edition so far | package main
import (
"log"
"os"
docker "github.com/fsouza/go-dockerclient"
)
const VERSION = "0.4.0"
func getEnvVar(name, defval string) string {
val := os.Getenv(name)
if val == "" {
val = defval
}
return val
}
func main() {
host := os.Getenv("DOCKER_HOST")
if host == "" {
log.Fatalln("Please provide DOCKER_HOST environment variable!")
}
client, err := docker.NewClient(host)
if err != nil {
log.Fatalln(err)
}
gateway := NewGateway(client)
if gateway.DefaultDomain == "" {
log.Fatalln("Please provide GW_DOMAIN environment variable!")
}
listener := NewListener(client, gateway)
listener.Init()
go listener.Start()
listenHost := getEnvVar("GW_HOST", "0.0.0.0")
listenPort := getEnvVar("GW_PORT", "2377")
err = gateway.Start(listenHost + ":" + listenPort)
if err != nil {
log.Fatalln(err)
}
}
| package main
import (
"log"
"os"
docker "github.com/fsouza/go-dockerclient"
)
func getEnvVar(name, defval string) string {
val := os.Getenv(name)
if val == "" {
val = defval
}
return val
}
func main() {
host := os.Getenv("DOCKER_HOST")
if host == "" {
log.Fatalln("Please provide DOCKER_HOST environment variable!")
}
client, err := docker.NewClient(host)
if err != nil {
log.Fatalln(err)
}
gateway := NewGateway(client)
if gateway.DefaultDomain == "" {
log.Fatalln("Please provide GW_DOMAIN environment variable!")
}
listener := NewListener(client, gateway)
listener.Init()
go listener.Start()
listenHost := getEnvVar("GW_HOST", "0.0.0.0")
listenPort := getEnvVar("GW_PORT", "2377")
err = gateway.Start(listenHost + ":" + listenPort)
if err != nil {
log.Fatalln(err)
}
}
|
Fix motion blur for Processing 3 | package com.haxademic.core.image;
import java.util.ArrayList;
import processing.core.PGraphics;
import processing.core.PImage;
import com.haxademic.core.draw.util.DrawUtil;
public class MotionBlurPGraphics {
int _blurFrames = 1;
protected ArrayList<PImage> _pastFrames;
public MotionBlurPGraphics(int frames) {
_blurFrames = frames;
_pastFrames = new ArrayList<PImage>();
}
public void updateToCanvas(PImage img, PGraphics canvas, float maxAlpha) {
// save current frame to buffer
_pastFrames.add(img.copy());
if(_pastFrames.size() > _blurFrames) {
_pastFrames.remove(0);
}
// draw all frames to screen
for (int f=0; f < _pastFrames.size(); f++) {
float alpha = (f+1f) * maxAlpha / _pastFrames.size();
PImage pastFrame = _pastFrames.get(f);
DrawUtil.setPImageAlpha(canvas, alpha);
canvas.image(pastFrame, 0, 0);
}
}
public void clearFrames() {
_pastFrames.clear();
}
} | package com.haxademic.core.image;
import java.util.ArrayList;
import processing.core.PGraphics;
import processing.core.PImage;
import com.haxademic.core.draw.util.DrawUtil;
public class MotionBlurPGraphics {
int _blurFrames = 1;
protected ArrayList<PImage> _pastFrames;
public MotionBlurPGraphics(int frames) {
_blurFrames = frames;
_pastFrames = new ArrayList<PImage>();
}
public void updateToCanvas(PImage img, PGraphics canvas, float maxAlpha) {
// save current frame to buffer
_pastFrames.add(img);
if(_pastFrames.size() > _blurFrames) {
_pastFrames.remove(0);
}
// draw all frames to screen
for (int f=0; f < _pastFrames.size(); f++) {
float alpha = (f+1f) * maxAlpha / _pastFrames.size();
PImage pastFrame = _pastFrames.get(f);
DrawUtil.setPImageAlpha(canvas, alpha);
canvas.image(pastFrame, 0, 0);
}
}
public void clearFrames() {
_pastFrames.clear();
}
} |
Change way of exports MainHeader Components
For: https://github.com/falmar/react-adm-lte/issues/2 | import MainHeader from './MainHeader'
import Logo from './Logo'
import LogoText from './LogoText'
import Navbar from './Navbar'
import NavbarMenu from './NavbarMenu'
import SidebarToggle from './SidebarToggle'
import ControlSidebarToggle from './ControlSidebarToggle'
import Messages from './Messages'
import MessageItem from './MessageItem'
import Notifications from './Notifications'
import NotificationItem from './NotificationItem'
import Tasks from './Tasks'
import TaskItem from './TaskItem'
import User from './User'
import UserHeader from './UserHeader'
import UserBody from './UserBody'
import UserBodyItem from './UserBodyItem'
import UserFooter from './UserFooter'
import UserFooterItem from './UserFooterItem'
MainHeader.MainHeader = MainHeader
MainHeader.Logo = Logo
MainHeader.LogoText = LogoText
MainHeader.Navbar = Navbar
MainHeader.NavbarMenu = NavbarMenu
MainHeader.SidebarToggle = SidebarToggle
MainHeader.ControlSidebarToggle = ControlSidebarToggle
MainHeader.Messages = Messages
MainHeader.MessageItem = MessageItem
MainHeader.Notifications = Notifications
MainHeader.NotificationItem = NotificationItem
MainHeader.Tasks = Tasks
MainHeader.TaskItem = TaskItem
MainHeader.User = User
MainHeader.UserHeader = UserHeader
MainHeader.UserBody = UserBody
MainHeader.UserBodyItem = UserBodyItem
MainHeader.UserFooter = UserFooter
MainHeader.UserFooterItem = UserFooterItem
export default MainHeader
| import MainHeader from './MainHeader'
import Logo from './Logo'
import LogoText from './LogoText'
import Navbar from './Navbar'
import NavbarMenu from './NavbarMenu'
import SidebarToggle from './SidebarToggle'
import ControlSidebarToggle from './ControlSidebarToggle'
import Messages from './Messages'
import MessageItem from './MessageItem'
import Notifications from './Notifications'
import NotificationItem from './NotificationItem'
import Tasks from './Tasks'
import TaskItem from './TaskItem'
import User from './User'
import UserHeader from './UserHeader'
import UserBody from './UserBody'
import UserBodyItem from './UserBodyItem'
import UserFooter from './UserFooter'
import UserFooterItem from './UserFooterItem'
export default {
MainHeader,
Logo,
LogoText,
Navbar,
NavbarMenu,
SidebarToggle,
ControlSidebarToggle,
Messages,
MessageItem,
Notifications,
NotificationItem,
Tasks,
TaskItem,
User,
UserHeader,
UserBody,
UserBodyItem,
UserFooter,
UserFooterItem
}
|
Add `curious.ext` as a namespace package correctly. | from setuptools import setup
setup(
name='discord-curious',
version='0.1.1',
packages=['curious', 'curious.http', 'curious.commands', 'curious.dataclasses'],
namespace_packages=['curious.ext'],
url='https://github.com/SunDwarf/curious',
license='MIT',
author='Laura Dickinson',
author_email='l@veriny.tf',
description='A curio library for the Discord API',
install_requires=[
"cuiows>=0.1.10",
"curio==0.4.0",
"h11==0.7.0",
"multidict==2.1.4",
"pylru==1.0.9",
"yarl==0.8.1",
],
extras_require={
"voice": ["opuslib==1.1.0",
"PyNaCL==1.0.1",]
}
)
| from setuptools import setup
setup(
name='discord-curious',
version='0.1.1',
packages=['curious', 'curious.http', 'curious.commands', 'curious.dataclasses', 'curious.ext'],
url='https://github.com/SunDwarf/curious',
license='MIT',
author='Laura Dickinson',
author_email='l@veriny.tf',
description='A curio library for the Discord API',
install_requires=[
"cuiows>=0.1.10",
"curio==0.4.0",
"h11==0.7.0",
"multidict==2.1.4",
"pylru==1.0.9",
"yarl==0.8.1",
],
extras_require={
"voice": ["opuslib==1.1.0",
"PyNaCL==1.0.1",]
}
)
|
Make this component more smarter | import React, { Component } from 'react';
import { connect } from 'react-redux';
import {weaveOn, weaveOff, threadingOn, threadingOff} from '../actions/scheme4';
import Threading from './Threading';
import Weave from './Weave';
import TieUp from './TieUp';
import Treadling from './Treadling';
import '../styles/Scheme4.css';
class Scheme4 extends Component {
render() {
const {dispatch, switcher4} = this.props;
return (
<div className='Scheme4'>
<span className='spanRow'>
<span className='spanCell'>
<Threading currentState={switcher4} />
</span>
<span className='spanCell'><TieUp /></span>
</span>
<span className='spanRow'>
<span className='spanCell'>
<Weave currentState={switcher4} />
</span>
<span className='spanCell'><Treadling /></span>
</span>
</div>
);
}
}
function select(state) {
return state;
}
export default connect(select)(Scheme4);
| import React, { Component } from 'react';
import Threading from './Threading';
import Weave from './Weave';
import TieUp from './TieUp';
import Treadling from './Treadling';
import '../styles/Scheme4.css';
class Scheme4 extends Component {
render() {
return (
<div className='Scheme4'>
<span className='spanRow'>
<span className='spanCell'><Threading /></span>
<span className='spanCell'><TieUp /></span>
</span>
<span className='spanRow'>
<span className='spanCell'><Weave /></span>
<span className='spanCell'><Treadling /></span>
</span>
</div>
);
}
}
export default Scheme4;
|
Change default command to timeline | package com.tmitim.twittercli;
import com.github.rvesse.airline.annotations.Cli;
import com.github.rvesse.airline.help.Help;
import com.tmitim.twittercli.commands.DirectMessage;
import com.tmitim.twittercli.commands.Favorite;
import com.tmitim.twittercli.commands.Location;
import com.tmitim.twittercli.commands.TimeLineCommand;
import com.tmitim.twittercli.commands.Trend;
import com.tmitim.twittercli.commands.Tweet;
import com.tmitim.twittercli.commands.Search;
@Cli(
name = "twitter",
description = "Twitter CLI", defaultCommand = TimeLineCommand.class,
commands = { Tweet.class, TimeLineCommand.class, Location.class, Trend.class, Search.class, DirectMessage.class,
Favorite.class, Help.class }
)
public class TwitterCli {
public static void main(String[] args) {
com.github.rvesse.airline.Cli<Runnable> cli = new com.github.rvesse.airline.Cli<>(TwitterCli.class);
try {
Runnable cmd = cli.parse(args);
cmd.run();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
| package com.tmitim.twittercli;
import com.github.rvesse.airline.annotations.Cli;
import com.github.rvesse.airline.help.Help;
import com.tmitim.twittercli.commands.DirectMessage;
import com.tmitim.twittercli.commands.Favorite;
import com.tmitim.twittercli.commands.Location;
import com.tmitim.twittercli.commands.TimeLineCommand;
import com.tmitim.twittercli.commands.Trend;
import com.tmitim.twittercli.commands.Tweet;
import com.tmitim.twittercli.commands.Search;
@Cli(
name = "twitter",
description = "Provides a basic example CLI",
defaultCommand = Help.class,
commands = { Tweet.class, TimeLineCommand.class, Location.class, Trend.class, Search.class, DirectMessage.class,
Favorite.class, Help.class }
)
public class TwitterCli {
public static void main(String[] args) {
com.github.rvesse.airline.Cli<Runnable> cli = new com.github.rvesse.airline.Cli<>(TwitterCli.class);
try {
Runnable cmd = cli.parse(args);
cmd.run();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
Save repositories back to the configuration directory | package main
import (
"flag"
"fmt"
"os"
"time"
)
func fatalf(format interface{}, a ...interface{}) {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], fmt.Sprintf(fmt.Sprint(format), a...))
os.Exit(1)
}
func main() {
configDir := flag.String("config", "~/.svnwatch", "the configuration directory for svnwatch")
interval := flag.Int("interval", 0, "how often to check for updates (0 disables this and exists after a single check)")
flag.Parse()
watcher, err := LoadWatcher(*configDir)
if *interval < 0 {
fatalf("%s: invalid interval: %d", os.Args[0], *interval)
}
if err != nil {
fatalf(err)
}
for {
if err := watcher.Update(); err != nil {
fatalf(err)
}
if err := watcher.Save(*configDir); err != nil {
fatalf(err)
}
if *interval > 0 {
time.Sleep(time.Duration(*interval) * time.Second)
} else {
break
}
}
}
| package main
import (
"flag"
"fmt"
"os"
"time"
)
func fatalf(format interface{}, a ...interface{}) {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], fmt.Sprintf(fmt.Sprint(format), a...))
os.Exit(1)
}
func main() {
configDir := flag.String("config", "~/.svnwatch", "the configuration directory for svnwatch")
interval := flag.Int("interval", 0, "how often to check for updates (0 disables this and exists after a single check)")
flag.Parse()
watcher, err := LoadWatcher(*configDir)
if *interval < 0 {
fatalf("%s: invalid interval: %d", os.Args[0], *interval)
}
if err != nil {
fatalf(err)
}
for {
if err := watcher.Update(); err != nil {
fatalf(err)
}
watcher.Save("./config")
if *interval > 0 {
time.Sleep(time.Duration(*interval) * time.Second)
} else {
break
}
}
}
|
Remove express reference, send only app object | var studentsController = require('../controllers/students');
var teachersController = require('../controllers/teachers');
var authenticationController = require('../controllers/authenticate');
module.exports = function(app, io) {
app.get('/login', authenticationController.login);
app.get('/signup', authenticationController.signup);
//app.get('/teachers/poll', teachersController.pollClass);
//app.get('/teachers/thumbs', teachersController.thumbsCheck);
app.get('/teachers/thumbs', teachersController.thumbsCheck(io));
// app.post('/teachers/poll', teachersController.pollClass);
app.get('/teachers/lessons/:classId', teachersController.getLessons);
app.get('/teachers/polls/:lessonId', teachersController.getPolls);
app.post('/teachers/polls', teachersController.newPoll);
//app.get('/classDismissed', teachersController.endClass);
app.get('/students/ready', studentsController.readyStage(io));
}; | var studentsController = require('../controllers/students');
var teachersController = require('../controllers/teachers');
var authenticationController = require('../controllers/authenticate');
module.exports = function(app, express, io) {
app.get('/login', authenticationController.login);
app.get('/signup', authenticationController.signup);
//app.get('/teachers/poll', teachersController.pollClass);
//app.get('/teachers/thumbs', teachersController.thumbsCheck);
app.get('/teachers/thumbs', teachersController.thumbsCheck.bind(this, io));
// app.post('/teachers/poll', teachersController.pollClass);
app.get('/teachers/lessons/:classId', teachersController.getLessons);
app.get('/teachers/polls/:lessonId', teachersController.getPolls);
app.post('/teachers/polls', teachersController.newPoll);
//app.get('/classDismissed', teachersController.endClass);
app.get('/students/ready', studentsController.readyStage.bind(this, io));
}; |
Update README with new owner. | import setuptools
# How do we keep this in sync with requirements.pip?
#
REQUIREMENTS = [
"nose==1.3.0",
"python-dateutil==1.5",
]
if __name__ == "__main__":
setuptools.setup(
name="jsond",
version="0.0.1",
author="EDITD",
author_email="engineering@editd.com",
packages=setuptools.find_packages(),
scripts=[],
url="https://github.com/EDITD/jsond",
license="LICENSE.txt",
description="JSON (with dates)",
long_description="View the github page (https://github.com/EDITD/jsond) for more details.",
install_requires=REQUIREMENTS
)
| import setuptools
# How do we keep this in sync with requirements.pip?
#
REQUIREMENTS = [
"nose==1.3.0",
"python-dateutil==1.5",
]
if __name__ == "__main__":
setuptools.setup(
name="jsond",
version="0.0.1",
author="Sujay Mansingh",
author_email="sujay.mansingh@gmail.com",
packages=setuptools.find_packages(),
scripts=[],
url="https://github.com/sujaymansingh/jsond",
license="LICENSE.txt",
description="JSON (with dates)",
long_description="View the github page (https://github.com/sujaymansingh/jsond) for more details.",
install_requires=REQUIREMENTS
)
|
Fix Heroku script (calling npm build) | 'use strict';
if ('HEROKU' in process.env || ('DYNO' in process.env && process.env.HOME === '/app')) {
const pkg = require('../package.json');
const ChildProcess = require('child_process');
let deps = pkg.devDependencies;
let packages = "";
Object.keys(deps).forEach((key) => {
packages += `${key}@${deps[key]} `; // note space at end to separate entries
});
try {
console.time("install");
console.log("starting npm install of dev dependencies");
ChildProcess.execSync(`npm install ${packages}`);
console.timeEnd("install");
console.time("build");
console.log("starting npm build");
ChildProcess.execSync(`npm run build`);
console.timeEnd("build");
console.time("uninstall");
console.log("starting npm uninstall of dev dependencies");
ChildProcess.execSync(`npm uninstall ${packages}`);
console.timeEnd("uninstall");
}
catch (err) {
console.error(err.message);
}
} else {
console.log("Not Heroku, skipping postinstall build");
} | 'use strict';
if ('HEROKU' in process.env || ('DYNO' in process.env && process.env.HOME === '/app')) {
const pkg = require('../package.json');
const ChildProcess = require('child_process');
let deps = pkg.devDependencies;
let packages = "";
Object.keys(deps).forEach((key) => {
packages += `${key}@${deps[key]} `; // note space at end to separate entries
});
try {
console.time("install");
console.log("starting npm install of dev dependencies");
ChildProcess.execSync(`npm install ${packages}`);
console.timeEnd("install");
console.time("build");
console.log("starting npm build");
ChildProcess.execSync(`npm run build:all`);
console.timeEnd("build");
console.time("uninstall");
console.log("starting npm uninstall of dev dependencies");
ChildProcess.execSync(`npm uninstall ${packages}`);
console.timeEnd("uninstall");
}
catch (err) {
console.error(err.message);
}
} else {
console.log("Not Heroku, skipping postinstall build");
} |
Update for circles and new sample data | import React, { Component } from 'react'
import Circles from './analytics/Circles'
export default class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
data: {
url: './data/sample.json',
elementDelay: 100
},
startDelay: 2000
};
}
componentDidMount() {
console.log('rendering');
}
render() {
return (
<div className="dashboard-container">
<Circles
startDelay={this.state.startDelay}
elementDelay={this.state.data.elementDelay}
json={this.state.data.url}
/>
</div>
)
}
} | import React, { Component } from 'react'
import Affirmations from './analytics/Affirmations'
export default class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
data: {
url: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/98887/d3pack-flare-short.json',
elementDelay: 100
},
startDelay: 2000
};
}
componentDidMount() {
console.log('rendering');
}
render() {
var style = {
width: '100%',
height: '100%'
};
return (
<div style={style}>
<Affirmations
startDelay={this.state.startDelay}
elementDelay={this.state.data.elementDelay}
json={this.state.data.url}
/>
</div>
)
}
} |
Update branch for git updater | <?php
/**
* Plugin Name: Culture Object
* Plugin URI: http://cultureobject.co.uk
* Description: A framework as a plugin to enable sync of culture objects into WordPress.
* Version: 3.0.0-beta.1
* Author: Liam Gladdy / Thirty8 Digital
* Text Domain: culture-object
* Author URI: https://github.com/lgladdy
* GitHub Plugin URI: Thirty8Digital/CultureObject
* GitHub Branch: master
* License: Apache 2 License
*/
require_once('CultureObject/CultureObject.class.php');
$cos = new \CultureObject\CultureObject();
/* General Functions. These need to go into their own file one day. */
function cos_get_remapped_field_name($field_key) {
global $cos;
return $cos->helper->cos_get_remapped_field_name($field_key);
}
function cos_remapped_field_name($field_key) {
global $cos;
return $cos->helper->cos_remapped_field_name($field_key);
}
function cos_get_field($field_key) {
$id = get_the_ID();
if (!$id) return false;
return get_post_meta($id, $field_key, true);
}
function cos_the_field($field_key) {
echo cos_get_field($field_key);
}
| <?php
/**
* Plugin Name: Culture Object
* Plugin URI: http://cultureobject.co.uk
* Description: A framework as a plugin to enable sync of culture objects into WordPress.
* Version: 3.0.0-beta.1
* Author: Liam Gladdy / Thirty8 Digital
* Text Domain: culture-object
* Author URI: https://github.com/lgladdy
* GitHub Plugin URI: Thirty8Digital/CultureObject
* GitHub Branch: dev
* License: Apache 2 License
*/
require_once('CultureObject/CultureObject.class.php');
$cos = new \CultureObject\CultureObject();
/* General Functions. These need to go into their own file one day. */
function cos_get_remapped_field_name($field_key) {
global $cos;
return $cos->helper->cos_get_remapped_field_name($field_key);
}
function cos_remapped_field_name($field_key) {
global $cos;
return $cos->helper->cos_remapped_field_name($field_key);
}
function cos_get_field($field_key) {
$id = get_the_ID();
if (!$id) return false;
return get_post_meta($id, $field_key, true);
}
function cos_the_field($field_key) {
echo cos_get_field($field_key);
}
|
Add docstring to recaptcha check | from functools import wraps
from django.conf import settings
import requests
def check_recaptcha(view_func):
"""Chech that the entered recaptcha data is correct"""
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':
recaptcha_response = request.POST.get('g-recaptcha-response')
data = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
result = r.json()
if result['success']:
request.recaptcha_is_valid = True
else:
request.recaptcha_is_valid = False
print('Invalid reCAPTCHA. Please try again. '+str(result['error-codes']))
return view_func(request, *args, **kwargs)
return _wrapped_view
| from functools import wraps
from django.conf import settings
import requests
def check_recaptcha(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':
recaptcha_response = request.POST.get('g-recaptcha-response')
data = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
result = r.json()
if result['success']:
request.recaptcha_is_valid = True
else:
request.recaptcha_is_valid = False
print('Invalid reCAPTCHA. Please try again. '+str(result['error-codes']))
return view_func(request, *args, **kwargs)
return _wrapped_view
|
Add recaptchaSiteKey model attribute not if its a redirect | package com.github.dtrunk90.recaptcha.spring.web.servlet.handler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.view.RedirectView;
public class RecaptchaHandlerInterceptor extends HandlerInterceptorAdapter {
public static final String RECAPTCHA_SITE_KEY_ATTRIBUTE_NAME = "recaptchaSiteKey";
@Value("${recaptcha.site-key}")
private String recaptchaSiteKey;
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
if (modelAndView != null && modelAndView.hasView() && !(modelAndView.getView() instanceof RedirectView) && !modelAndView.getViewName().startsWith("redirect:")) {
modelAndView.addObject(RECAPTCHA_SITE_KEY_ATTRIBUTE_NAME, recaptchaSiteKey);
}
}
}
| package com.github.dtrunk90.recaptcha.spring.web.servlet.handler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class RecaptchaHandlerInterceptor extends HandlerInterceptorAdapter {
public static final String RECAPTCHA_SITE_KEY_ATTRIBUTE_NAME = "recaptchaSiteKey";
@Value("${recaptcha.site-key}")
private String recaptchaSiteKey;
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
if (modelAndView != null) {
modelAndView.addObject(RECAPTCHA_SITE_KEY_ATTRIBUTE_NAME, recaptchaSiteKey);
}
}
}
|
Write output to text file | # -*- coding: utf-8 -*-
import sys, datetime, getopt
from reddit_user import RedditUser
longopts, shortopts = getopt.getopt(sys.argv[2:], shortopts="", longopts=["file="])
args = dict(longopts)
file_mode = ""
if len(sys.argv) < 2:
sys.exit("Usage: python sherlock.py <username> --file=(read|write)")
if args.has_key("--file") and args["--file"] == "write":
file_mode = "write"
elif args.has_key("--file") and args["--file"] == "read":
file_mode = "read"
start = datetime.datetime.now()
u = RedditUser(sys.argv[1])
print "Processing user %s" % u.username
if file_mode == "write":
u.save_comments_to_file()
u.process_comments_from_file()
elif file_mode == "read":
u.process_comments_from_file()
else:
u.process_all_submissions()
u.process_all_comments()
with open("results/%s.txt" % u.username,"w") as o:
o.write(str(u))
print
print u
print "\nProcessing complete... %s" % (datetime.datetime.now()-start) | # -*- coding: utf-8 -*-
import sys, datetime, getopt
from reddit_user import RedditUser
longopts, shortopts = getopt.getopt(sys.argv[2:], shortopts="", longopts=["file="])
args = dict(longopts)
file_mode = ""
if len(sys.argv) < 2:
sys.exit("Usage: python sherlock.py <username> --file=(read|write)")
if args.has_key("--file") and args["--file"] == "write":
file_mode = "write"
elif args.has_key("--file") and args["--file"] == "read":
file_mode = "read"
start = datetime.datetime.now()
u = RedditUser(sys.argv[1])
if file_mode == "write":
u.save_comments_to_file()
u.process_comments_from_file()
elif file_mode == "read":
u.process_comments_from_file()
else:
u.process_all_comments()
print u
print "Processing complete... %s" % (datetime.datetime.now()-start) |
Fix typo in entry point name | #!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = ['robotframework']
if sys.version_info < (2, 7):
install_requires.append('argparse')
setup(
name='pre_commit_robotframework_tidy',
description='A pre-commit hook to run Robot Framework\'s tidy tool.',
url='https://github.com/guykisel/pre-commit-robotframework-tidy',
version='0.0.1dev0',
author='Guy Kisel',
author_email='guy.kisel@gmail.com',
platforms='any',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Operating System :: OS Independent',
],
packages=find_packages('.', exclude=('tests*', 'testing*')),
install_requires=install_requires,
entry_points={
'console_scripts': [
('python-robotframework-tidy = '
'pre_commit_robotframework_tidy.rf_tidy:main'),
],
},
)
| #!/usr/bin/env python
import sys
from setuptools import find_packages, setup
install_requires = ['robotframework']
if sys.version_info < (2, 7):
install_requires.append('argparse')
setup(
name='pre_commit_robotframework_tidy',
description='A pre-commit hook to run Robot Framework\'s tidy tool.',
url='https://github.com/guykisel/pre-commit-robotframework-tidy',
version='0.0.1dev0',
author='Guy Kisel',
author_email='guy.kisel@gmail.com',
platforms='any',
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Operating System :: OS Independent',
],
packages=find_packages('.', exclude=('tests*', 'testing*')),
install_requires=install_requires,
entry_points={
'console_scripts': [
('python-robotframework-tidy = '
'pre_commit_robotframework_tidy.rf_tify:main'),
],
},
)
|
Add theme version number to favicons | <link rel="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/favicon.ico">
<?php
$template_dir = get_template_directory_uri();
$sizes = array(
'', // 57 x 57
'57x57',
'72x72',
'76x76',
'114x114',
'120x120',
'144x144',
'152x152',
);
foreach($sizes as $size) {
$sizes_attr = (strlen($size))
? 'sizes="'.$size.'"'
: null;
$size_suffix = (strlen($size))
? '-'.$size
: null;
echo sprintf(
'<link rel="apple-touch-icon" %s href="%s/img/apple-touch-icon%s.png%s">',
$sizes_attr,
$template_dir,
$size_suffix,
THEME_SUFFIX
);
}
?> | <link rel="shortcut icon" href="<?php echo get_template_directory_uri(); ?>/favicon.ico" />
<?php
$template_dir = get_template_directory_uri();
$sizes = array(
'',
'57x57',
'72x72',
'76x76',
'114x114',
'120x120',
'144x144',
'152x152',
);
foreach($sizes as $size) {
$sizes_attr = (strlen($size))
? 'sizes="'.$size.'"'
: null;
$size_suffix = (strlen($size))
? '-'.$size
: null;
echo sprintf(
'<link rel="apple-touch-icon" %s href="%s/img/apple-touch-icon%s.png" />',
$sizes_attr,
$template_dir,
$size_suffix
);
}
?> |
Fix in pricing rule patch | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils.nestedset import get_root_of
def execute():
frappe.reload_doc("accounts", "doctype", "pricing_rule")
frappe.db.auto_commit_on_many_writes = True
default_item_group = get_root_of("Item Group")
for d in frappe.db.sql("""select * from `tabCustomer Discount`
where ifnull(parent, '') != ''""", as_dict=1):
if not d.discount:
continue
frappe.get_doc({
"doctype": "Pricing Rule",
"apply_on": "Item Group",
"item_group": d.item_group or default_item_group,
"applicable_for": "Customer",
"customer": d.parent,
"price_or_discount": "Discount Percentage",
"discount_percentage": d.discount,
"selling": 1
}).insert()
frappe.db.auto_commit_on_many_writes = False
frappe.delete_doc("DocType", "Customer Discount")
| # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils.nestedset import get_root_of
def execute():
frappe.reload_doc("accounts", "doctype", "pricing_rule")
frappe.db.auto_commit_on_many_writes = True
default_item_group = get_root_of("Item Group")
for d in frappe.db.sql("""select * from `tabCustomer Discount`
where ifnull(parent, '') != ''""", as_dict=1):
if not d.discount:
continue
frappe.get_doc({
"doctype": "Pricing Rule",
"apply_on": "Item Group",
"item_group": d.item_group or default_item_group,
"applicable_for": "Customer",
"customer": d.parent,
"price_or_discount": "Discount Percentage",
"discount_percentage": d.discount
}).insert()
frappe.db.auto_commit_on_many_writes = False
frappe.delete_doc("DocType", "Customer Discount")
|
android: Make event naming more flexible | package com.sogilis.ReactNativeBluetooth.events;
public class EventNames {
public static final String STATE_CHANGED = name("STATE_CHANGED");
public static final String SCAN_STARTED = name("SCAN_STARTED");
public static final String SCAN_STOPPED = name("SCAN_STOPPED");
public static final String DEVICE_DISCOVERED = name("DEVICE_DISCOVERED");
public static final String DEVICE_CONNECTED = name("DEVICE_CONNECTED");
public static final String DEVICE_DISCONNECTED = name("DEVICE_DISCONNECTED");
public static final String SERVICE_DISCOVERY_STARTED = name("SERVICE_DISCOVERY_STARTED");
public static final String SERVICE_DISCOVERED = name("SERVICE_DISCOVERED");
private static final String name(String customNamePart) {
return EventNames.class.getCanonicalName() + "." + customNamePart;
}
}
| package com.sogilis.ReactNativeBluetooth.events;
public class EventNames {
private static final String BASE = EventNames.class.getCanonicalName() + ".EVENT_";
public static final String STATE_CHANGED = BASE + "STATE_CHANGED";
public static final String SCAN_STARTED = BASE + "SCAN_STARTED";
public static final String SCAN_STOPPED = BASE + "SCAN_STOPPED";
public static final String DEVICE_DISCOVERED = BASE + "DEVICE_DISCOVERED";
public static final String DEVICE_CONNECTED = BASE + "DEVICE_CONNECTED";
public static final String DEVICE_DISCONNECTED = BASE + "DEVICE_DISCONNECTED";
public static final String SERVICE_DISCOVERY_STARTED = BASE + "SERVICE_DISCOVERY_STARTED";
public static final String SERVICE_DISCOVERED = BASE + "SERVICE_DISCOVERED";
}
|
Fix Android package name to make it build | package jugendmusiziert.jumunordost;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
| package com.jumunordost;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
|
Use new version of js files | <footer>
<div class="row colors">
<div class="three columns mobile-one yellow"> </div>
<div class="three columns mobile-one light-blue"> </div>
<div class="three columns mobile-one red"> </div>
<div class="three columns mobile-one dark-blue"> </div>
</div>
<div class="row about">
<div class="three columns">
<img class="logo" alt="AxisPhilly" src="<?php bloginfo('template_directory'); ?>/images/logo-just-name-white.png"/>
<p class="copyright">© 2013</p>
</div>
<div class="nine columns">
<ul>
<li><a href="/about">About Us</a></li>
<li><a href="/about#mission">Mission</a></li>
<li><a href="/about#staff">Staff</a></li>
<li><a href="/about#board">Board</a></li>
<li><a href="/about#jobs">Jobs</a></li>
</ul>
</div>
</div>
</footer>
<script src="<?php bloginfo('template_directory'); ?>/javascripts/foundation.min.js" type="text/javascript"></script>
<script src="<?php bloginfo('template_directory'); ?>/javascripts/site.0.9.0.min.js" type="text/javascript"></script>
</body>
</html> | <footer>
<div class="row colors">
<div class="three columns mobile-one yellow"> </div>
<div class="three columns mobile-one light-blue"> </div>
<div class="three columns mobile-one red"> </div>
<div class="three columns mobile-one dark-blue"> </div>
</div>
<div class="row about">
<div class="three columns">
<img class="logo" alt="AxisPhilly" src="<?php bloginfo('template_directory'); ?>/images/logo-just-name-white.png"/>
<p class="copyright">© 2013</p>
</div>
<div class="nine columns">
<ul>
<li><a href="/about">About Us</a></li>
<li><a href="/about#mission">Mission</a></li>
<li><a href="/about#staff">Staff</a></li>
<li><a href="/about#board">Board</a></li>
<li><a href="/about#jobs">Jobs</a></li>
</ul>
</div>
</div>
</footer>
<script src="<?php bloginfo('template_directory'); ?>/javascripts/foundation.js" type="text/javascript"></script>
<script src="<?php bloginfo('template_directory'); ?>/javascripts/site.js" type="text/javascript"></script>
</body>
</html> |
Make final the findRank method in ENS-SS. | package ru.ifmo.nds.ens;
public final class ENS_SS extends ENSBase {
public ENS_SS(int maximumPoints, int maximumDimension) {
super(maximumPoints, maximumDimension);
}
@Override
final int findRank(double[][] points, double[] point, int maxRank) {
int currRank = 0;
while (currRank <= maxRank) {
if (frontDominates(currRank, points, point)) {
++currRank;
} else {
break;
}
}
return currRank;
}
@Override
public String getName() {
return "ENS-SS";
}
}
| package ru.ifmo.nds.ens;
public final class ENS_SS extends ENSBase {
public ENS_SS(int maximumPoints, int maximumDimension) {
super(maximumPoints, maximumDimension);
}
@Override
int findRank(double[][] points, double[] point, int maxRank) {
int currRank = 0;
while (currRank <= maxRank) {
if (frontDominates(currRank, points, point)) {
++currRank;
} else {
break;
}
}
return currRank;
}
@Override
public String getName() {
return "ENS-SS";
}
}
|
Use sysconfig to find the include directory. | from __future__ import unicode_literals, print_function
import os
import argparse
import sys
import shutil
import sysconfig
def main():
target = os.path.dirname(sysconfig.get_config_h_filename())
try:
source = os.readlink(target)
except:
print(target, "is not a symlink. Perhaps this script has already been run.")
sys.exit(1)
tmp = target + ".tmp"
if os.path.exists(tmp):
shutil.rmtree(tmp)
os.mkdir(tmp)
for i in os.listdir(source):
if i == "pygame_sdl2":
continue
os.symlink(os.path.join(source, i), os.path.join(tmp, i))
os.unlink(target)
os.rename(tmp, target)
if __name__ == "__main__":
main()
| from __future__ import unicode_literals, print_function
import os
import argparse
import sys
import shutil
def main():
ap = argparse.ArgumentParser()
ap.add_argument("virtualenv", help="The path to the virtual environment.")
args = ap.parse_args()
target = "{}/include/python{}.{}".format(args.virtualenv, sys.version_info.major, sys.version_info.minor)
try:
source = os.readlink(target)
except:
print(target, "is not a symlink. Perhaps this script has already been run.")
sys.exit(1)
tmp = target + ".tmp"
if os.path.exists(tmp):
shutil.rmtree(tmp)
os.mkdir(tmp)
for i in os.listdir(source):
if i == "pygame_sdl2":
continue
os.symlink(os.path.join(source, i), os.path.join(tmp, i))
os.unlink(target)
os.rename(tmp, target)
if __name__ == "__main__":
main()
|
Add comment for HTML string | import { createButton } from './Button';
export default {
title: 'Example/Button',
argTypes: {
label: { control: 'text' },
primary: { control: 'boolean' },
backgroundColor: { control: 'color' },
size: {
control: { type: 'select', options: ['small', 'medium', 'large'] },
},
onClick: { action: 'onClick' },
},
};
const Template = ({ label, ...args }) => {
// You can either use a function to create DOM elements or use a plain html string!
// return `<div>${label}</div>`;
return createButton({ label, ...args });
};
export const Primary = Template.bind({});
Primary.args = {
primary: true,
label: 'Button',
};
export const Secondary = Template.bind({});
Secondary.args = {
label: 'Button',
};
export const Large = Template.bind({});
Large.args = {
size: 'large',
label: 'Button',
};
export const Small = Template.bind({});
Small.args = {
size: 'small',
label: 'Button',
};
| import { createButton } from './Button';
export default {
title: 'Example/Button',
argTypes: {
label: { control: 'text' },
primary: { control: 'boolean' },
backgroundColor: { control: 'color' },
size: {
control: { type: 'select', options: ['small', 'medium', 'large'] },
},
onClick: { action: 'onClick' },
},
};
const Template = (args) => createButton(args);
export const Primary = Template.bind({});
Primary.args = {
primary: true,
label: 'Button',
};
export const Secondary = Template.bind({});
Secondary.args = {
label: 'Button',
};
export const Large = Template.bind({});
Large.args = {
size: 'large',
label: 'Button',
};
export const Small = Template.bind({});
Small.args = {
size: 'small',
label: 'Button',
};
|
Add error highlightening in B Console | package de.prob2.ui.consoles.b;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import de.prob2.ui.consoles.Console;
import de.prob2.ui.consoles.ConsoleExecResult;
import de.prob2.ui.consoles.ConsoleExecResultType;
@Singleton
public class BConsole extends Console {
private BInterpreter interpreter;
@Inject
private BConsole(BInterpreter interpreter) {
super();
this.interpreter = interpreter;
this.appendText("Prob 2.0 B Console \n >");
}
@Override
protected void handleEnter() {
super.handleEnterAbstract();
String currentLine = getCurrentLine();
if(currentLine.isEmpty()) {
this.appendText("\nnull");
} else {
ConsoleExecResult execResult = interpreter.exec(instructions.get(posInList));
this.appendText("\n" + execResult);
if(execResult.getResultType() == ConsoleExecResultType.ERROR) {
int begin = this.getText().length() - execResult.toString().length();
int end = this.getText().length();
this.setStyleClass(begin, end, "error");
}
}
this.appendText("\n >");
this.setStyleClass(this.getText().length() - 2, this.getText().length(), "current");
this.setEstimatedScrollY(Double.MAX_VALUE);
}
}
| package de.prob2.ui.consoles.b;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import de.prob2.ui.consoles.Console;
@Singleton
public class BConsole extends Console {
private BInterpreter interpreter;
@Inject
private BConsole(BInterpreter interpreter) {
super();
this.interpreter = interpreter;
this.appendText("Prob 2.0 B Console \n >");
}
@Override
protected void handleEnter() {
super.handleEnterAbstract();
String currentLine = getCurrentLine();
if(currentLine.isEmpty()) {
this.appendText("\nnull");
} else {
this.appendText("\n" + interpreter.exec(instructions.get(posInList)));
}
this.appendText("\n >");
this.setEstimatedScrollY(Double.MAX_VALUE);
}
}
|
Load XBlockToXModuleShim for Studio Tabs page
The studio tabs page had a race condition when loading many static tabs.
The result was that those tabs couldn't be deleted. By requiring the
`xmodule` module, we force the EditTabsFactory to load
XBlockToXModuleShim before it's needed. | import * as TabsModel from 'js/models/explicit_url';
import * as TabsEditView from 'js/views/tabs';
import * as xmoduleLoader from 'xmodule';
import './base';
import 'cms/js/main';
import 'xblock/cms.runtime.v1';
import 'xmodule/js/src/xmodule'; // Force the XBlockToXModuleShim to load for Static Tabs
'use strict';
export default function EditTabsFactory(courseLocation, explicitUrl) {
xmoduleLoader.done(function() {
var model = new TabsModel({
id: courseLocation,
explicit_url: explicitUrl
}),
editView;
editView = new TabsEditView({
el: $('.tab-list'),
model: model,
mast: $('.wrapper-mast')
});
});
};
export {EditTabsFactory}
| import * as TabsModel from 'js/models/explicit_url';
import * as TabsEditView from 'js/views/tabs';
import * as xmoduleLoader from 'xmodule';
import './base';
import 'cms/js/main';
import 'xblock/cms.runtime.v1';
'use strict';
export default function EditTabsFactory(courseLocation, explicitUrl) {
xmoduleLoader.done(function() {
var model = new TabsModel({
id: courseLocation,
explicit_url: explicitUrl
}),
editView;
editView = new TabsEditView({
el: $('.tab-list'),
model: model,
mast: $('.wrapper-mast')
});
});
};
export {EditTabsFactory}
|
Fix applying changed function names | import React from 'react';
import PropTypes from 'prop-types';
import { styled, lighten, darken } from '@storybook/theming';
import { Link } from '@storybook/router';
const baseStyle = ({ theme }) => ({
display: 'block',
padding: '16px 20px',
borderRadius: 10,
fontSize: theme.typography.size.s1,
fontWeight: theme.typography.weight.bold,
lineHeight: `16px`,
boxShadow: '0 5px 15px 0 rgba(0, 0, 0, 0.1), 0 2px 5px 0 rgba(0, 0, 0, 0.05)',
color: theme.color.inverseText,
backgroundColor:
theme.base === 'light' ? darken(theme.background.app) : lighten(theme.background.app),
textDecoration: 'none',
});
const NotificationLink = styled(Link)(baseStyle);
const Notification = styled.div(baseStyle);
export const NotificationItemSpacer = styled.div({
height: 48,
});
export default function NotificationItem({ notification: { content, link } }) {
return link ? (
<NotificationLink to={link}>{content}</NotificationLink>
) : (
<Notification>{content}</Notification>
);
}
NotificationItem.propTypes = {
notification: PropTypes.shape({
content: PropTypes.string.isRequired,
link: PropTypes.string,
}).isRequired,
};
| import React from 'react';
import PropTypes from 'prop-types';
import { styled, lightenColor, darken } from '@storybook/theming';
import { Link } from '@storybook/router';
const baseStyle = ({ theme }) => ({
display: 'block',
padding: '16px 20px',
borderRadius: 10,
fontSize: theme.typography.size.s1,
fontWeight: theme.typography.weight.bold,
lineHeight: `16px`,
boxShadow: '0 5px 15px 0 rgba(0, 0, 0, 0.1), 0 2px 5px 0 rgba(0, 0, 0, 0.05)',
color: theme.color.inverseText,
backgroundColor:
theme.base === 'light' ? darken(theme.background.app) : lightenColor(theme.background.app),
textDecoration: 'none',
});
const NotificationLink = styled(Link)(baseStyle);
const Notification = styled.div(baseStyle);
export const NotificationItemSpacer = styled.div({
height: 48,
});
export default function NotificationItem({ notification: { content, link } }) {
return link ? (
<NotificationLink to={link}>{content}</NotificationLink>
) : (
<Notification>{content}</Notification>
);
}
NotificationItem.propTypes = {
notification: PropTypes.shape({
content: PropTypes.string.isRequired,
link: PropTypes.string,
}).isRequired,
};
|
Fix typo in getting superclass of AutoID | from __future__ import absolute_import
from __future__ import unicode_literals
import datetime as dt
from sqlalchemy.types import DateTime
from sqlalchemy.ext.declarative import declared_attr
from .datetime import DateTime
from .datetime import utc
from .. import db
class AutoID(object):
"""Mixin adding a primary key integer column named 'id'."""
id = db.Column(db.Integer, primary_key=True)
def _json(self, extended=False):
try:
parent = super(AutoID, self)._json(extended)
except AttributeError:
parent = {}
parent[u'id'] = self.id
return parent
def _utcnow(arg):
return dt.datetime.now(utc)
class Timestamped(object):
"""Mixin adding a timestamp column.
The timestamp defaults to the current time.
"""
timestamp = db.Column(DateTime, nullable=False,
default=_utcnow)
class AutoName(object):
@declared_attr
def __tablename__(cls):
"""SQLAlchemy late-binding attribute to set the table name.
Implemented this way so subclasses do not need to specify a table name
themselves.
"""
return cls.__name__.lower()
| from __future__ import absolute_import
from __future__ import unicode_literals
import datetime as dt
from sqlalchemy.types import DateTime
from sqlalchemy.ext.declarative import declared_attr
from .datetime import DateTime
from .datetime import utc
from .. import db
class AutoID(object):
"""Mixin adding a primary key integer column named 'id'."""
id = db.Column(db.Integer, primary_key=True)
def _json(self, extended=False):
try:
parent = super(AutoName, self)._json(extended)
except AttributeError:
parent = {}
parent[u'id'] = self.id
return parent
def _utcnow(arg):
return dt.datetime.now(utc)
class Timestamped(object):
"""Mixin adding a timestamp column.
The timestamp defaults to the current time.
"""
timestamp = db.Column(DateTime, nullable=False,
default=_utcnow)
class AutoName(object):
@declared_attr
def __tablename__(cls):
"""SQLAlchemy late-binding attribute to set the table name.
Implemented this way so subclasses do not need to specify a table name
themselves.
"""
return cls.__name__.lower()
|
Use callback instead of htmlCallback | /* jshint node: true */
'use strict';
var replace = require('broccoli-replace');
var favicons = require('broccoli-favicon');
var htmlCache = null;
module.exports = {
name: 'ember-cli-favicon',
included: function(app) {
this.options = app.favicons || {};
this.options.callback = function(html) {
htmlCache = html;
};
},
postprocessTree: function(type, tree) {
if (type === 'all') {
return replace(tree, {
files: [ 'index.html' ],
patterns: [{
match: /<\/head>/i,
replacement: function() {
return htmlCache + '\n</head>';
}
}]
});
}
return tree;
},
treeForPublic: function(tree) {
if (this.options.persistCache !== false) {
this.options.persistentCacheDir = this.options.persistentCacheDir || 'tmp/.favicon-cache';
}
return favicons(tree || 'public', this.options);
}
};
| /* jshint node: true */
'use strict';
var replace = require('broccoli-replace');
var favicons = require('broccoli-favicon');
var htmlCache = null;
module.exports = {
name: 'ember-cli-favicon',
included: function(app) {
this.options = app.favicons || {};
this.options.htmlCallback = function(html) {
htmlCache = html;
};
},
postprocessTree: function(type, tree) {
if (type === 'all') {
return replace(tree, {
files: [ 'index.html' ],
patterns: [{
match: /<\/head>/i,
replacement: function() {
return htmlCache + '\n</head>';
}
}]
});
}
return tree;
},
treeForPublic: function(tree) {
if (this.options.persistCache !== false) {
this.options.persistentCacheDir = this.options.persistentCacheDir || 'tmp/.favicon-cache';
}
return favicons(tree || 'public', this.options);
}
};
|
Use authExpired action; fix session timeout notification logic | // import {replace} from 'react-router-redux'
import {authExpired} from 'shared/actions/auth'
import {publishNotification as notify} from 'shared/actions/notifications'
import {HTTP_FORBIDDEN} from 'shared/constants'
const errorsMiddleware = store => next => action => {
if (action.type === 'ERROR_THROWN') {
const {error, error: {status, auth}} = action
console.error(error)
if (status === HTTP_FORBIDDEN) {
const {auth: {me}} = store.getState()
const wasSessionTimeout = me !== null
next(authExpired(auth))
if (wasSessionTimeout) {
store.dispatch(notify('error', 'Session timed out. Please login again.'))
} else {
store.dispatch(notify('error', 'Please login to use Chronograf.'))
}
} else {
store.dispatch(notify('error', 'Cannot communicate with server.'))
}
}
next(action)
}
export default errorsMiddleware
| // import {replace} from 'react-router-redux'
import {authReceived, meReceived} from 'shared/actions/auth'
import {publishNotification as notify} from 'shared/actions/notifications'
import {HTTP_FORBIDDEN} from 'shared/constants'
const errorsMiddleware = store => next => action => {
if (action.type === 'ERROR_THROWN') {
const {error, error: {status, auth}} = action
console.error(error)
if (status === HTTP_FORBIDDEN) {
const {auth: {me}} = store.getState()
const wasSessionTimeout = me === null
store.dispatch(authReceived(auth))
store.dispatch(meReceived(null))
if (wasSessionTimeout) {
store.dispatch(notify('error', 'Please login to use Chronograf.'))
} else {
store.dispatch(notify('error', 'Session timed out. Please login again.'))
}
} else {
store.dispatch(notify('error', 'Cannot communicate with server.'))
}
}
next(action)
}
export default errorsMiddleware
|
Migrate UpdatingPopover component to functional
It is forwarding a ref since it needs a reference to the DOM
instance for this example. | const UpdatingPopover = React.forwardRef(
({ scheduleUpdate, children, ...props }, ref) => {
useEffect(() => {
console.log('updating!');
scheduleUpdate();
}, [children, scheduleUpdate]);
return (
<Popover ref={ref} {...props}>
{children}
</Popover>
);
},
);
const longContent = `
Very long
Multiline content
that is engaging and what-not
`;
const shortContent = 'Short and sweet!';
function Example() {
const [content, setContent] = useState(shortContent);
useEffect(() => {
const timerId = setInterval(() => {
setContent(content === shortContent ? longContent : shortContent);
}, 3000);
return () => clearInterval(timerId);
});
return (
<OverlayTrigger
trigger="click"
overlay={
<UpdatingPopover id="popover-contained">{content}</UpdatingPopover>
}
>
<Button>Holy guacamole!</Button>
</OverlayTrigger>
);
}
render(<Example />);
| class UpdatingPopover extends React.Component {
componentDidUpdate(prevProps) {
if (prevProps.children !== this.props.children) {
console.log('updating!');
this.props.scheduleUpdate();
}
}
render() {
return <Popover {...this.props} />;
}
}
const longContent = `
Very long
Multiline content
that is engaging and what-not
`;
const shortContent = 'Short and sweet!';
function Example() {
const [content, setContent] = useState(shortContent);
useEffect(() => {
const timerId = setInterval(() => {
setContent(content === shortContent ? longContent : shortContent);
}, 3000);
return () => clearInterval(timerId);
});
return (
<OverlayTrigger
trigger="click"
overlay={
<UpdatingPopover id="popover-contained">{content}</UpdatingPopover>
}
>
<Button>Holy guacamole!</Button>
</OverlayTrigger>
);
}
render(<Example />);
|
Sort sources by distance to controller
The logic here is that we want creeps to start with the closer sources
(that way the first creep spawned will be able to fill the controller
up faster). To save CPU it looks for the controller rather than doing a
check for all spawns (this is taking advantage of the fact that the
quorum code prioritizes putting the spawn close to the controller). |
class MetaRole {
recharge(creep) {
if (creep.carry[RESOURCE_ENERGY] <= 0) {
creep.memory.recharge = true
}
if (creep.carry[RESOURCE_ENERGY] >= creep.carryCapacity) {
creep.memory.recharge = false
}
if (creep.memory.recharge) {
var sources = creep.room.find(FIND_SOURCES_ACTIVE)
sources.sort((a, b) => a.pos.getRangeTo(a.room.controller) - b.pos.getRangeTo(b.room.controller))
let idx = parseInt(creep.name[creep.name.length - 1], 36)
var source = sources[idx % sources.length]
if (!creep.pos.isNearTo(source)) {
creep.moveTo(source)
}
if (creep.pos.isNearTo(source)) {
creep.harvest(source)
}
return true
}
return false
}
}
module.exports = MetaRole
|
class MetaRole {
recharge(creep) {
if (creep.carry[RESOURCE_ENERGY] <= 0) {
creep.memory.recharge = true
}
if (creep.carry[RESOURCE_ENERGY] >= creep.carryCapacity) {
creep.memory.recharge = false
}
if (creep.memory.recharge) {
var sources = creep.room.find(FIND_SOURCES_ACTIVE)
let idx = parseInt(creep.name[creep.name.length - 1], 36)
var source = sources[idx % sources.length]
if (!creep.pos.isNearTo(source)) {
creep.moveTo(source)
}
if (creep.pos.isNearTo(source)) {
creep.harvest(source)
}
return true
}
return false
}
}
module.exports = MetaRole
|
Change vendor key to vendor_id. | import unittest
from vendcrawler.scripts.vendpageparser import VendPageParser
class TestVendPageParserMethods(unittest.TestCase):
def test_feed(self):
with open('test_vendcrawler.html', 'r') as f:
data = f.read()
vendpageparser = VendPageParser()
vendpageparser.feed(str(data))
self.assertEqual(vendpageparser.items[0]['id'], '2221')
self.assertEqual(vendpageparser.items[1]['name'], 'Buckler [1]')
self.assertEqual(vendpageparser.items[3]['amount'], '12')
self.assertEqual(vendpageparser.items[4]['vendor_id'], '186612')
if __name__ == '__main__':
unittest.main()
| import unittest
from vendcrawler.scripts.vendpageparser import VendPageParser
class TestVendPageParserMethods(unittest.TestCase):
def test_feed(self):
with open('test_vendcrawler.html', 'r') as f:
data = f.read()
vendpageparser = VendPageParser()
vendpageparser.feed(str(data))
self.assertEqual(vendpageparser.items[0]['id'], '2221')
self.assertEqual(vendpageparser.items[1]['name'], 'Buckler [1]')
self.assertEqual(vendpageparser.items[3]['amount'], '12')
self.assertEqual(vendpageparser.items[4]['vendor'], '186612')
if __name__ == '__main__':
unittest.main()
|
Add shell=True to make sure that sdb does exist | #!/usr/bin/env python3
# Copyright 2015-2016 Samsung Electronics Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from configparser import RawConfigParser
from litmus.core.util import call
def load_project_list(projects):
"""docstring for load_project_list"""
configparser = RawConfigParser()
configparser.read(projects)
project_list = []
for section in configparser.sections():
item = dict(configparser.items(section))
item['name'] = section
project_list.append(item)
return project_list
def sdb_does_exist():
help_url = 'https://github.com/dhs-shine/litmus#prerequisite'
try:
call('sdb version', shell=True, timeout=10)
except FileNotFoundError:
raise Exception('Please install sdb. Refer to {}'.format(help_url))
return
| #!/usr/bin/env python3
# Copyright 2015-2016 Samsung Electronics Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from configparser import RawConfigParser
from litmus.core.util import call
def load_project_list(projects):
"""docstring for load_project_list"""
configparser = RawConfigParser()
configparser.read(projects)
project_list = []
for section in configparser.sections():
item = dict(configparser.items(section))
item['name'] = section
project_list.append(item)
return project_list
def sdb_does_exist():
help_url = 'https://github.com/dhs-shine/litmus#prerequisite'
try:
call('sdb version', timeout=10)
except FileNotFoundError:
raise Exception('Please install sdb. Refer to {}'.format(help_url))
return
|
Update Root with CollectModuleData for legacy compat. | /**
* Root component.
*
* 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.
*/
/**
* External dependencies
*/
import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import ErrorHandler from '../ErrorHandler';
import PermissionsModal from '../permissions-modal';
import RestoreSnapshots from '../restore-snapshots';
import CollectModuleData from '../data/collect-module-data';
export default function Root( {
children,
registry,
dataAPIContext,
dataAPIModuleArgs,
} ) {
return (
<Data.RegistryProvider value={ registry }>
<ErrorHandler>
<RestoreSnapshots>
{ children }
{ dataAPIContext && (
// Legacy dataAPI support.
<CollectModuleData context={ dataAPIContext } args={ dataAPIModuleArgs } />
) }
</RestoreSnapshots>
<PermissionsModal />
</ErrorHandler>
</Data.RegistryProvider>
);
}
Root.propTypes = {
children: PropTypes.node.isRequired,
registry: PropTypes.object,
};
Root.defaultProps = {
registry: Data,
};
| /**
* Root component.
*
* 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.
*/
/**
* External dependencies
*/
import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import ErrorHandler from '../ErrorHandler';
import PermissionsModal from '../permissions-modal';
export default function Root( { children, registry } ) {
return (
<Data.RegistryProvider value={ registry }>
<ErrorHandler>
{ children }
<PermissionsModal />
</ErrorHandler>
</Data.RegistryProvider>
);
}
Root.propTypes = {
children: PropTypes.node.isRequired,
registry: PropTypes.object,
};
Root.defaultProps = {
registry: Data,
};
|
Add contact info to next steps
as per MoH feedback | module.exports = {
pageTitle: '<i class="fa fa-check success" aria-hidden="true"></i> Your application has been submitted',
secondTitle: 'What happens next',
printEmailInstructions: '<a>Print your application</a> for your records',
emailAddressLabel: 'Email address',
sendEmailButton: 'Send a copy',
generalInstructions1: '<strong>If you qualify</strong>, the monthly premium you need to pay will be adjusted. Depending on the level of assistance you\'re qualified for, you may still need to pay a small amount - a monthly invoice will be sent to you.<br><br>If there\'s a credit on your account, it will be applied to your monthly premium until the credit is used up. A refund cheque will only be mailed to you if there\'s a credit on your account and you do not owe a monthly premium',
generalInstructions2: '<strong>File your taxes</strong> by April 30 every year so that you do not have to reapply for assistance.',
generalInstructions3: '<strong>If you do not qualify</strong>, you will continue to receive an invoice to pay your monthly premium.',
generalInstructions4: 'If you have questions, please contact <a href="http://www2.gov.bc.ca/gov/content/health/health-drug-coverage/msp/bc-residents-contact-us" target="_blank">Health Insurance BC</a>.'
}
| module.exports = {
pageTitle: '<i class="fa fa-check success" aria-hidden="true"></i> Your application has been submitted',
secondTitle: 'What happens next',
printEmailInstructions: '<a>Print your application</a> for your records',
emailAddressLabel: 'Email address',
sendEmailButton: 'Send a copy',
generalInstructions1: '<strong>If you qualify</strong>, the monthly premium you need to pay will be adjusted. Depending on the level of assistance you\'re qualified for, you may still need to pay a small amount - a monthly invoice will be sent to you.<br><br>If there\'s a credit on your account, it will be applied to your monthly premium until the credit is used up. A refund cheque will only be mailed to you if there\'s a credit on your account and you do not owe a monthly premium',
generalInstructions2: '<strong>File your taxes</strong> by April 30 every year so that you do not have to reapply for assistance.',
generalInstructions3: '<strong>If you do not qualify</strong>, you will continue to receive an invoice to pay your monthly premium.',
}
|
Use eval for more flexibility | var fs = require('fs')
tests = String(fs.readFileSync('tests.tsv')).split('\n').splice(1)
;['array.vector.min.js','array.vector.js'].forEach(function (file) {
failures = 0
try {
var content = String(fs.readFileSync(file))
} catch(e) {
console.log(file + " failed to load")
return
}
eval(content)
tests.forEach(function (test, i) {
test = test.split('\t')
test[1] = eval(`[${test[1]}]`)
test[2] = eval(`[${test[2]}]`)
test[3] = eval(test[3])
var result = test[1][test[0]].apply(test[1], test[2])
if (JSON.stringify(result) != JSON.stringify(test[3])) {
console.log(`Test ${i+1} Failed (${test[0]} got ${result}, expect ${test[3]})`)
failures += 1
}
})
console.log(`${file} ${tests.length - failures}/${tests.length} tests passed`)
})
process.exit(failures) | var fs = require('fs')
tests = String(fs.readFileSync('tests.tsv')).split('\n').splice(1)
;['array.vector.min.js','array.vector.js'].forEach(function (file) {
failures = 0
try {
var content = String(fs.readFileSync(file))
} catch(e) {
console.log(file + " failed to load")
return
}
eval(content)
tests.forEach(function (test, i) {
test = test.split('\t')
test[1] = JSON.parse(`[${test[1]}]`)
test[2] = JSON.parse(`[${test[2]}]`)
test[3] = JSON.parse(test[3])
var result = test[1][test[0]].apply(test[1], test[2])
if (JSON.stringify(result) != JSON.stringify(test[3])) {
console.log(`Test ${i+1} Failed (${test[0]} got ${result}, expect ${test[3]})`)
failures += 1
}
})
console.log(`${file} ${tests.length - failures}/${tests.length} tests passed`)
})
process.exit(failures) |
Check if checkbox is not checked. | import WrapperBuilder from './wrapper';
import { shallow, mount } from 'enzyme';
import React from 'react';
const CheckedFixture = () => (
<input type="checkbox" defaultChecked value="coffee" />
);
const NotCheckedFixture = () => (
<input type="checkbox" value="coffee" />
);
describe('Checkbox', () => {
const methodNames = ['shallow', 'mount'];
[shallow, mount].forEach((renderMethod, i) => {
let checkedInput, notCheckedInput;
before(() => {
checkedInput = WrapperBuilder(renderMethod(<CheckedFixture />));
notCheckedInput = WrapperBuilder(renderMethod(<NotCheckedFixture />));
});
context(methodNames[i], () => {
it(`should be checked`, () => {
checkedInput.checked().should.be.true();
});
it(`should NOT be checked`, () => {
notCheckedInput.checked().should.be.false();
});
});
});
}); | import WrapperBuilder from './wrapper';
import { shallow, mount } from 'enzyme';
import React from 'react';
const CheckedFixture = () => (
<input type="checkbox" defaultChecked value="coffee" />
);
// const NotCheckedFixture = () => (
// <input type="checkbox" value="coffee" />
// );
describe('Checkbox', () => {
const methodNames = ['shallow', 'mount'];
[shallow, mount].forEach((renderMethod, i) => {
let checkedInput;
// notCheckedInput;
before(() => {
checkedInput = WrapperBuilder(renderMethod(<CheckedFixture />));
// notCheckedInput = WrapperBuilder(renderMethod(<NotCheckedFixture />));
});
context(methodNames[i], () => {
it(`should be checked`, () => {
checkedInput.checked().should.be.true();
});
});
});
}); |
Support MEP-6.1.0 which has version containing 4 numbers like mapr-spark-2.3.2.0 while the version directory contains still 3 numbers | #!/usr/bin/env python
import sys
import subprocess
mep_version = "MEP_VERSION"
os_family = "OS_FAMILY"
output = subprocess.check_output( [
"curl", "-s",
"http://package.mapr.com/releases/MEP/MEP-%s/%s/" % (mep_version, os_family)
] )
for line in output.splitlines():
index1 = line.find('"mapr')
if index1 < 0: continue
index2 = line.find('rpm"')
if index2 < 0: continue
package_version = line[index1+1:index2+3]
pvitems = package_version.split('-')
package = '-'.join( pvitems[0:-2] )
version = pvitems[-2]
vitems = []
for item in version.split("."):
if len(item) <= 2:
vitems.append(item)
else:
# ignore build number which like: 201901301208
break
# Starting with MEP-6.1.0, versions can contains 4 numbers like '2.3.2.0' in
# mapr-spark-2.3.2.0.201901301208-1.noarch
# but the version directory contains still 3 numbers. Let us take only the
# first 3 numbers.
version = ".".join(vitems[0:3])
print "%s=%s" % (package+":version", version)
| #!/usr/bin/env python
import sys
import subprocess
mep_version = "MEP_VERSION"
os_family = "OS_FAMILY"
output = subprocess.check_output( [
"curl", "-s",
"http://package.mapr.com/releases/MEP/MEP-%s/%s/" % (mep_version, os_family)
] )
for line in output.splitlines():
index1 = line.find('"mapr')
if index1 < 0: continue
index2 = line.find('rpm"')
if index2 < 0: continue
package_version = line[index1+1:index2+3]
pvitems = package_version.split('-')
package = '-'.join( pvitems[0:-2] )
version = pvitems[-2]
vitems = []
for item in version.split("."):
if len(item) <= 2:
vitems.append(item)
else:
break
version = ".".join(vitems)
print "%s=%s" % (package+":version", version)
|
Enable cloud persistence for rehub | package de.retest.recheck;
import java.util.prefs.Preferences;
import de.retest.recheck.Properties.FileOutputFormat;
import de.retest.recheck.auth.RehubAuthenticationHandler;
import de.retest.recheck.auth.RetestAuthentication;
import de.retest.recheck.persistence.CloudPersistence;
public class Rehub {
private Rehub() {
}
public static void init() {
final RetestAuthentication auth = RetestAuthentication.getInstance();
if ( !auth.isAuthenticated( getToken() ) ) {
auth.login( new RehubAuthenticationHandler() );
}
System.setProperty( Properties.FILE_OUTPUT_FORMAT_PROPERTY, FileOutputFormat.CLOUD.toString() );
}
private static String getToken() {
final String tokenFromEnvironment = System.getenv( CloudPersistence.RECHECK_API_KEY );
final String tokenFromPreferences =
Preferences.userNodeForPackage( Rehub.class ).get( CloudPersistence.RECHECK_API_KEY, null );
return tokenFromEnvironment != null ? tokenFromEnvironment : tokenFromPreferences;
}
}
| package de.retest.recheck;
import java.util.prefs.Preferences;
import de.retest.recheck.auth.RehubAuthenticationHandler;
import de.retest.recheck.auth.RetestAuthentication;
import de.retest.recheck.persistence.CloudPersistence;
public class Rehub {
private Rehub() {
}
public static void init() {
final RetestAuthentication auth = RetestAuthentication.getInstance();
if ( !auth.isAuthenticated( getToken() ) ) {
auth.login( new RehubAuthenticationHandler() );
}
}
private static String getToken() {
final String tokenFromEnvironment = System.getenv( CloudPersistence.RECHECK_API_KEY );
final String tokenFromPreferences =
Preferences.userNodeForPackage( Rehub.class ).get( CloudPersistence.RECHECK_API_KEY, null );
return tokenFromEnvironment != null ? tokenFromEnvironment : tokenFromPreferences;
}
}
|
Add some protection to default url provider | package me.shoutto.sdk.internal.http;
import me.shoutto.sdk.StmBaseEntity;
/**
* Implementation of URL provider for Shout to Me API service endpoints
*/
public class DefaultUrlProvider implements StmUrlProvider {
private String baseApiUrl;
public DefaultUrlProvider(String baseApiUrl) {
this.baseApiUrl = baseApiUrl;
}
@Override
public String getUrl(StmBaseEntity entity, HttpMethod httpMethod) {
String url = String.format("%s%s", baseApiUrl, entity.getBaseEndpoint());
if (httpMethod.equals(HttpMethod.DELETE) || httpMethod.equals(HttpMethod.PUT)
|| httpMethod.equals(HttpMethod.GET)) {
if (entity.getId() != null) {
url = url.concat(String.format("/%s", entity.getId()));
}
}
return url;
}
}
| package me.shoutto.sdk.internal.http;
import me.shoutto.sdk.StmBaseEntity;
/**
* Implementation of URL provider for Shout to Me API service endpoints
*/
public class DefaultUrlProvider implements StmUrlProvider {
private String baseApiUrl;
public DefaultUrlProvider(String baseApiUrl) {
this.baseApiUrl = baseApiUrl;
}
@Override
public String getUrl(StmBaseEntity entity, HttpMethod httpMethod) {
String url = String.format("%s%s", baseApiUrl, entity.getBaseEndpoint());
if (httpMethod.equals(HttpMethod.DELETE) || httpMethod.equals(HttpMethod.PUT)
|| httpMethod.equals(HttpMethod.GET)) {
url = url.concat(String.format("/%s", entity.getId()));
}
return url;
}
}
|
Correct Go test package name. | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package lucy
import "git-wip-us.apache.org/repos/asf/lucy-clownfish.git/runtime/go/clownfish"
import "testing"
func TestStuff(t *testing.T) {
NewSchema()
}
func TestOpenIndexer(t *testing.T) {
_, err := OpenIndexer(&OpenIndexerArgs{Index: "notalucyindex"})
if _, ok := err.(clownfish.Err); !ok {
t.Error("Didn't catch exception opening indexer")
}
}
| /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package lucy_test
import "git-wip-us.apache.org/repos/asf/lucy.git/go/lucy"
import "git-wip-us.apache.org/repos/asf/lucy-clownfish.git/runtime/go/clownfish"
import "testing"
func TestStuff(t *testing.T) {
lucy.NewSchema()
}
func TestOpenIndexer(t *testing.T) {
_, err := lucy.OpenIndexer(&lucy.OpenIndexerArgs{Index: "notalucyindex"})
if _, ok := err.(clownfish.Err); !ok {
t.Error("Didn't catch exception opening indexer")
}
}
|
Add missing underscore on query param to contacts | const { getContact } = require('../../contacts/repos')
function setInteractionsDetails (req, res, next) {
res.locals.interactions = {
returnLink: `/contacts/${req.params.contactId}/interactions/`,
entityName: `${res.locals.contact.first_name} ${res.locals.contact.last_name}`,
query: { contacts__id: req.params.contactId },
view: 'contacts/views/interactions',
canAdd: true,
}
next()
}
async function setCompanyDetails (req, res, next) {
try {
const contact = await getContact(req.session.token, req.params.contactId)
res.locals.company = contact.company
next()
} catch (error) {
next(error)
}
}
module.exports = {
setInteractionsDetails,
setCompanyDetails,
}
| const { getContact } = require('../../contacts/repos')
function setInteractionsDetails (req, res, next) {
res.locals.interactions = {
returnLink: `/contacts/${req.params.contactId}/interactions/`,
entityName: `${res.locals.contact.first_name} ${res.locals.contact.last_name}`,
query: { contacts_id: req.params.contactId },
view: 'contacts/views/interactions',
canAdd: true,
}
next()
}
async function setCompanyDetails (req, res, next) {
try {
const contact = await getContact(req.session.token, req.params.contactId)
res.locals.company = contact.company
next()
} catch (error) {
next(error)
}
}
module.exports = {
setInteractionsDetails,
setCompanyDetails,
}
|
Fix typo in automatic email | from django.core.mail import send_mail
# TODO: check whether this should be sent from Phuxivator
def mailApplicantSubmission(context, sender='phuxivator@tf.fi'):
name = context['name']
receiver = context['email']
subject = 'Tack för din medlemsansökan till Teknologföreningen!'
message = '''Hej {name},
Tack för din medlemsansökan till Teknologföreningen!
För att bli en fullständig medlem så är nästa steg att delta i ett Nationsmöte (Namö).
Detta informeras mera senare.
Vid frågor eller ifall du inte ansökt om medlemskap, kontakta {sender}
Detta är ett automatiskt meddelande, du behöver inte svara på det.
'''.format(name=name, sender=sender)
return send_mail(
subject,
message,
sender,
[receiver],
fail_silently=False)
| from django.core.mail import send_mail
# TODO: check whether this should be sent from Phuxivator
def mailApplicantSubmission(context, sender='phuxivator@tf.fi'):
name = context['name']
receiver = context['email']
subject = 'Tack för din medlemsansökan till Teknologföreningen!'
message = '''Hej {name},
Tack för din medlemsansökan till Teknologföreningen!
För att bli en fullständig medlem så är nästa steg att delta i ett Nationsmöte (Namö).
Detta informeras mera senare.
Vid frågor eller ifall du inte ansökt om medlemskap, kontakt {sender}
Detta är ett automatiskt meddelande, du behöver inte svara på det.
'''.format(name=name, sender=sender)
return send_mail(
subject,
message,
sender,
[receiver],
fail_silently=False)
|
Fix dependency regex in logTasks | 'use strict';
var archy = require('archy');
var chalk = require('chalk');
var gutil = require('gulp-util');
function logTasks(tree, getDescription) {
var padding = 0;
var rdependency = /[ │] [├└]/;
archy(tree)
.split('\n')
.filter(function(v, i) {
// Log first line as is
if (i === 0) {
gutil.log(v);
return false;
}
// Search for longest line
if (v.length > padding) {
padding = v.length;
}
return v.trim().length !== 0;
}).forEach(function(v) {
var line = v.split(' ');
var task = line.slice(1).join(' ');
// Log dependencies as is
if (rdependency.test(v)) {
gutil.log(v);
return;
}
// Pretty task with optionnal description
gutil.log(
line[0] + ' ' + chalk.cyan(task) +
Array(padding + 3 - v.length).join(' ') +
(getDescription(task) || '')
);
});
}
module.exports = logTasks;
| 'use strict';
var archy = require('archy');
var chalk = require('chalk');
var gutil = require('gulp-util');
function logTasks(tree, getDescription) {
var padding = 0;
archy(tree)
.split('\n')
.filter(function(v, i) {
// Log first line as is
if (i === 0) {
gutil.log(v);
return false;
}
// Search for longest line
if (v.length > padding) {
padding = v.length;
}
return v.trim().length !== 0;
}).forEach(function(v) {
var line = v.split(' ');
var task = line.slice(1).join(' ');
if (/.└/.test(v)) {
// Log dependencies as is
gutil.log(v);
} else {
// Pretty task with optionnal description
gutil.log(
line[0] + ' ' + chalk.cyan(task) +
Array(padding + 3 - v.length).join(' ') +
(getDescription(task) || '')
);
}
});
}
module.exports = logTasks;
|
Replace integer indices with ellipsis | import numpy as np
from sklearn import preprocessing as pp
print('normalization function imported')
#normalize data in respect with keys in dictionary
def normalize_data(data):
# get keys from original data
gestures = list(data)
# create empty dictionary to store normalized data with gestures
gdata = {}
# get max/min of x/y across samples and frames
for gesture in gestures:
data_gesture = np.asarray(data[gesture])
max_x = np.max(data_gesture[...,0])
min_x = np.min(data_gesture[...,0])
max_y = np.max(data_gesture[...,1])
min_y = np.min(data_gesture[...,1])
data_gesture[...,0]=(data_gesture[...,0]-min_x)/(max_x - min_x)
data_gesture[...,1]=(data_gesture[...,1]-min_y)/(max_y - min_y)
#store normalized data into dictionary
gdata[gesture] = data_gesture
data = gdata
return data
return print('data normalized')
| import numpy as np
from sklearn import preprocessing as pp
print('normalization function imported')
#normalize data in respect with keys in dictionary
def normalize_data(data):
# get keys from original data
gestures = list(data)
# create empty dictionary to store normalized data with gestures
gdata = {}
# get max/min of x/y across samples and frames
for gesture in gestures:
data_gesture = np.asarray(data[gesture])
max_x = np.max(data_gesture[:,:,:,:,0])
min_x = np.min(data_gesture[:,:,:,:,0])
max_y = np.max(data_gesture[:,:,:,:,1])
min_y = np.min(data_gesture[:,:,:,:,1])
data_gesture[:,:,:,:,0]=(data_gesture[:,:,:,:,0]-min_x)/(max_x - min_x)
data_gesture[:,:,:,:,1]=(data_gesture[:,:,:,:,1]-min_y)/(max_y - min_y)
#store normalized data into dictionary
gdata[gesture] = data_gesture
data = gdata
return data
return print('data normalized')
|
Allow throwing of exception when yiitter is mocked in unit tests | <?php
namespace Yiitter;
/**
* Creates an exception from a tmhOAuth instance based on its last response data.
*
* @author Shiki <bj@basanes.net>
*/
class ClientException extends \Exception
{
public $statusCode;
/**
* Create an instance of self.
*
* @param \tmhOAuth $client
*/
public function __construct(\tmhOAuth $client)
{
if (!empty($client->response['response'])) {
$response = json_decode($client->response['response'], true);
if (array_key_exists('errors', $response)) {
$message = $response['errors'][0]['message'];
$code = $response['errors'][0]['code'];
}
}
if (!isset($message))
$message = $client->response['error'];
if (!isset($code))
$code = $client->response['errno'];
$this->statusCode = $client->response['info']['http_code'];
parent::__construct($message, $code);
}
/**
* Creates an instance of self only if the \tmhOAuth instance's response is an error.
* This only allows non-tmhOAuth for unit testing.
*
* @param \tmhOAuth $client
* @return self
*/
public static function createIfFailed($client)
{
if ($client->response['info']['http_code'] == 200
|| $client->response['info']['http_code'] == 201) {
return null;
}
return new self($client);
}
}
| <?php
namespace Yiitter;
/**
* Creates an exception from a tmhOAuth instance based on its last response data.
*
* @author Shiki <bj@basanes.net>
*/
class ClientException extends \Exception
{
public $statusCode;
/**
* Create an instance of self.
*
* @param \tmhOAuth $client
*/
public function __construct(\tmhOAuth $client)
{
if (!empty($client->response['response'])) {
$response = json_decode($client->response['response'], true);
if (array_key_exists('errors', $response)) {
$message = $response['errors'][0]['message'];
$code = $response['errors'][0]['code'];
}
}
if (!isset($message))
$message = $client->response['error'];
if (!isset($code))
$code = $client->response['errno'];
$this->statusCode = $client->response['info']['http_code'];
parent::__construct($message, $code);
}
/**
* Creates an instance of self only if the \tmhOAuth instance's response is an error.
*
* @param \tmhOAuth $client
* @return self
*/
public static function createIfFailed(\tmhOAuth $client)
{
if ($client->response['info']['http_code'] == 200
|| $client->response['info']['http_code'] == 201) {
return null;
}
return new self($client);
}
}
|
Validate that token parameter is set and abort program if it is not | package cmd
import (
"fmt"
"io"
"log"
"net/url"
"os"
"github.com/bkittelmann/pinboard-checker/pinboard"
"github.com/spf13/cobra"
)
func init() {
exportCmd.Flags().StringP("token", "t", "", "The pinboard API token")
exportCmd.Flags().String("endpoint", pinboard.DefaultEndpoint.String(), "URL of pinboard API endpoint")
RootCmd.AddCommand(exportCmd)
}
var exportCmd = &cobra.Command{
Use: "export",
Short: "Download your bookmarks",
Long: "...",
Run: func(cmd *cobra.Command, args []string) {
token, _ := cmd.Flags().GetString("token")
if len(token) == 0 {
fmt.Println("ERROR: Token flag is mandatory for export command")
os.Exit(1)
}
endpoint, _ := cmd.Flags().GetString("endpoint")
endpointUrl, _ := url.Parse(endpoint)
client := pinboard.NewClient(token, endpointUrl)
readCloser, err := client.DownloadBookmarks()
if err != nil {
log.Fatal(err)
}
io.Copy(os.Stdout, readCloser)
readCloser.Close()
},
}
| package cmd
import (
"io"
"log"
"net/url"
"os"
"github.com/bkittelmann/pinboard-checker/pinboard"
"github.com/spf13/cobra"
)
func init() {
exportCmd.Flags().StringP("token", "t", "", "The pinboard API token")
exportCmd.Flags().String("endpoint", pinboard.DefaultEndpoint.String(), "URL of pinboard API endpoint")
RootCmd.AddCommand(exportCmd)
}
var exportCmd = &cobra.Command{
Use: "export",
Short: "Download your bookmarks",
Long: "...",
Run: func(cmd *cobra.Command, args []string) {
token, _ := cmd.Flags().GetString("token")
endpoint, _ := cmd.Flags().GetString("endpoint")
endpointUrl, _ := url.Parse(endpoint)
client := pinboard.NewClient(token, endpointUrl)
readCloser, err := client.DownloadBookmarks()
if err != nil {
log.Fatal(err)
}
io.Copy(os.Stdout, readCloser)
readCloser.Close()
},
}
|
Add isSourceType to base template object | var CustomListItemView = require('cartodb3/components/custom-list/custom-list-item-view');
var _ = require('underscore');
module.exports = CustomListItemView.extend({
render: function () {
this.$el.empty();
this.clearSubViews();
this.$el.append(
this.options.template(
_.extend(
{
typeLabel: this.options.typeLabel,
isSelected: this.model.get('selected'),
isSourceType: this.model.get('isSourceType'),
name: this.model.getName(),
val: this.model.getValue()
},
this.model.attributes
)
)
);
this.$el
.attr('data-val', this.model.getValue())
.toggleClass('is-disabled', !!this.model.get('disabled'));
return this;
}
});
| var CustomListItemView = require('cartodb3/components/custom-list/custom-list-item-view');
var _ = require('underscore');
module.exports = CustomListItemView.extend({
render: function () {
this.$el.empty();
this.clearSubViews();
this.$el.append(
this.options.template(
_.extend(
{
typeLabel: this.options.typeLabel,
isSelected: this.model.get('selected'),
name: this.model.getName(),
val: this.model.getValue()
},
this.model.attributes
)
)
);
this.$el
.attr('data-val', this.model.getValue())
.toggleClass('is-disabled', !!this.model.get('disabled'));
return this;
}
});
|
Add sso id to user | <?php
namespace Da\OAuthClientBundle\OAuth\Response;
use HWI\Bundle\OAuthBundle\OAuth\Response\PathUserResponse;
/**
* Class parsing the properties by given path options with raw data.
*
* @author Thomas Prelot <thomas.prelot@tessi.fr>
*/
class UserResponse extends PathUserResponse
{
/**
* Constructor.
*/
public function __construct()
{
$this->setPaths(array('id' => 'id'));
$this->setPaths(array('roles' => 'roles'));
$this->setPaths(array('raw' => 'raw'));
}
/**
* Get the sso id of the user.
*
* @return string The sso id of the user.
*/
public function getId()
{
return $this->getValueForPath('id');
}
/**
* Get the roles of the user.
*
* @return string The json encoded roles of the user.
*/
public function getRoles()
{
return $this->getValueForPath('roles');
}
/**
* Get the raw data of the user.
*
* @return string The json encoded raw data of the user.
*/
public function getRaw()
{
return $this->getValueForPath('raw');
}
}
| <?php
namespace Da\OAuthClientBundle\OAuth\Response;
use HWI\Bundle\OAuthBundle\OAuth\Response\PathUserResponse;
/**
* Class parsing the properties by given path options with raw data.
*
* @author Thomas Prelot <thomas.prelot@tessi.fr>
*/
class UserResponse extends PathUserResponse
{
/**
* Constructor.
*/
public function __construct()
{
$this->setPaths(array('roles' => 'roles'));
$this->setPaths(array('raw' => 'raw'));
}
/**
* Get the roles of the user.
*
* @return string The json encoded roles of the user.
*/
public function getRoles()
{
return $this->getValueForPath('roles');
}
/**
* Get the raw data of the user.
*
* @return string The json encoded raw data of the user.
*/
public function getRaw()
{
return $this->getValueForPath('raw');
}
}
|
Fix loading of socket.io.js when in development mode | var fs = require('fs'),
_ = require('lodash'),
yaml = require('js-yaml'),
bundles = yaml.safeLoad(fs.readFileSync('bundles.yml', 'utf8')),
settings = require('./config');
function getTag(key, asset) {
if (key.indexOf('_js') > -1) {
return '<script type="text/javascript" src="' + asset + '"></script>';
} else {
return '<link rel="stylesheet" type="text/css" href="' + asset + '" />';
}
}
function production(value, key) {
return [key, getTag(key, value.dest)];
}
function development(value, key) {
var tags = value.src.map(function(asset) {
if (asset.indexOf('socket.io.js') > -1) {
asset ='socket.io/socket.io.js';
}
return getTag(key, asset);
});
return [key, tags.join('')];
}
var map = settings.env === 'production' ? production : development;
module.exports = _.object(_.map(bundles, map));
| var fs = require('fs'),
_ = require('lodash'),
yaml = require('js-yaml'),
bundles = yaml.safeLoad(fs.readFileSync('bundles.yml', 'utf8')),
settings = require('./config');
function getTag(key, asset) {
if (key.indexOf('_js') > -1) {
return '<script type="text/javascript" src="' + asset + '"></script>';
} else {
return '<link rel="stylesheet" type="text/css" href="' + asset + '" />';
}
}
function production(value, key) {
return [key, getTag(key, value.dest)];
}
function development(value, key) {
var tags = value.src.map(function(asset) {
return getTag(key, asset);
});
return [key, tags.join('')];
}
var map = settings.env === 'production' ? production : development;
module.exports = _.object(_.map(bundles, map));
|
Add the mandatory semicolon after class property | import React from 'react';
export default class Line extends React.Component {
static propTypes = {
from: React.PropTypes.shape({
x: React.PropTypes.number.isRequired,
y: React.PropTypes.number.isRequired,
}),
to: React.PropTypes.shape({
x: React.PropTypes.number.isRequired,
y: React.PropTypes.number.isRequired,
}),
style: React.PropTypes.string
};
render() {
let from = this.props.from;
let to = this.props.to;
if (to.x < from.x) {
from = this.props.to;
to = this.props.from;
}
const len = Math.sqrt(Math.pow(from.x - to.x, 2) + Math.pow(from.y - to.y, 2));
const angle = Math.atan((to.y - from.y) / (to.x - from.x));
const style = {
position: 'absolute',
transform: `translate(${from.x - .5 * len * (1 - Math.cos(angle))}px, ${from.y + .5 * len * Math.sin(angle)}px) rotate(${angle}rad)`,
width: `${len}px`,
height: `${0}px`,
borderBottom: this.props.style || '1px solid black'
};
return <div style={style}></div>;
}
}
| import React from 'react';
export default class Line extends React.Component {
static propTypes = {
from: React.PropTypes.shape({
x: React.PropTypes.number.isRequired,
y: React.PropTypes.number.isRequired,
}),
to: React.PropTypes.shape({
x: React.PropTypes.number.isRequired,
y: React.PropTypes.number.isRequired,
}),
style: React.PropTypes.string
}
render() {
let from = this.props.from;
let to = this.props.to;
if (to.x < from.x) {
from = this.props.to;
to = this.props.from;
}
const len = Math.sqrt(Math.pow(from.x - to.x, 2) + Math.pow(from.y - to.y, 2));
const angle = Math.atan((to.y - from.y) / (to.x - from.x));
const style = {
position: 'absolute',
transform: `translate(${from.x - .5 * len * (1 - Math.cos(angle))}px, ${from.y + .5 * len * Math.sin(angle)}px) rotate(${angle}rad)`,
width: `${len}px`,
height: `${0}px`,
borderBottom: this.props.style || '1px solid black'
};
return <div style={style}></div>;
}
}
|
Mark ubuntupkg tests as flaky | # MIT licensed
# Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.
from flaky import flaky
import pytest
pytestmark = pytest.mark.asyncio
@flaky
async def test_ubuntupkg(get_version):
assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None}) == "0.1.3-1"
@flaky
async def test_ubuntupkg_strip_release(get_version):
assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "strip-release": 1}) == "0.1.3"
@flaky
async def test_ubuntupkg_suite(get_version):
assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "suite": "xenial"}) == "0.1.2-1"
@flaky
async def test_ubuntupkg_suite_with_paging(get_version):
assert await get_version("ffmpeg", {"ubuntupkg": None, "suite": "vivid"}) == "7:2.5.10-0ubuntu0.15.04.1"
| # MIT licensed
# Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.
import pytest
pytestmark = pytest.mark.asyncio
async def test_ubuntupkg(get_version):
assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None}) == "0.1.3-1"
async def test_ubuntupkg_strip_release(get_version):
assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "strip-release": 1}) == "0.1.3"
async def test_ubuntupkg_suite(get_version):
assert await get_version("sigrok-firmware-fx2lafw", {"ubuntupkg": None, "suite": "xenial"}) == "0.1.2-1"
async def test_ubuntupkg_suite_with_paging(get_version):
assert await get_version("ffmpeg", {"ubuntupkg": None, "suite": "vivid"}) == "7:2.5.10-0ubuntu0.15.04.1"
|
Add a guard clause to ResponseNewWindow | function ResponsesNewWindow(surveyID) {
try {
var ResponsesIndexView = require('ui/common/responses/ResponsesIndexView');
var ResponsesNewView = require('ui/common/responses/ResponsesNewView');
var ConfirmDialog = require('ui/common/components/ConfirmDialog');
var self = Ti.UI.createWindow({
navBarHidden : true,
backgroundColor : "#fff"
});
var view = new ResponsesNewView(surveyID);
self.add(view);
view.addEventListener('ResponsesNewView:savedResponse', function() {
Ti.App.fireEvent('ResponseNewWindow:closed');
view.cleanup();
view = null;
self.close();
});
var confirmDialog = new ConfirmDialog(L("confirm"), L("confirm_clear_answers"), onConfirm = function(e) {
if(view) {
view.cleanup();
}
view = null;
self.close();
});
self.addEventListener('android:back', function() {
confirmDialog.show();
});
return self;
}
catch(e) {
var auditor = require('helpers/Auditor');
auditor.writeIntoAuditFile(arguments.callee.name + " - " + e.toString());
}
}
module.exports = ResponsesNewWindow;
| function ResponsesNewWindow(surveyID) {
try {
var ResponsesIndexView = require('ui/common/responses/ResponsesIndexView');
var ResponsesNewView = require('ui/common/responses/ResponsesNewView');
var ConfirmDialog = require('ui/common/components/ConfirmDialog');
var self = Ti.UI.createWindow({
navBarHidden : true,
backgroundColor : "#fff"
});
var view = new ResponsesNewView(surveyID);
self.add(view);
view.addEventListener('ResponsesNewView:savedResponse', function() {
Ti.App.fireEvent('ResponseNewWindow:closed');
view.cleanup();
view = null;
self.close();
});
var confirmDialog = new ConfirmDialog(L("confirm"), L("confirm_clear_answers"), onConfirm = function(e) {
view.cleanup();
view = null;
self.close();
});
self.addEventListener('android:back', function() {
confirmDialog.show();
});
return self;
}
catch(e) {
var auditor = require('helpers/Auditor');
auditor.writeIntoAuditFile(arguments.callee.name + " - " + e.toString());
}
}
module.exports = ResponsesNewWindow;
|
Remove dependency on templating module | package groovy.io;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import junit.framework.TestCase;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
public class PlatformLineWriterTest extends TestCase {
public void testPlatformLineWriter() throws IOException, ClassNotFoundException {
String LS = System.getProperty("line.separator");
Binding binding = new Binding();
binding.setVariable("first", "Tom");
binding.setVariable("last", "Adams");
StringWriter stringWriter = new StringWriter();
Writer platformWriter = new PlatformLineWriter(stringWriter);
GroovyShell shell = new GroovyShell(binding);
platformWriter.write(shell.evaluate("\"$first\\n$last\\n\"").toString());
assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString());
stringWriter = new StringWriter();
platformWriter = new PlatformLineWriter(stringWriter);
platformWriter.write(shell.evaluate("\"$first\\r\\n$last\\r\\n\"").toString());
assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString());
}
}
| package groovy.io;
import groovy.text.SimpleTemplateEngine;
import groovy.text.Template;
import junit.framework.TestCase;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
public class PlatformLineWriterTest extends TestCase {
public void testPlatformLineWriter() throws IOException, ClassNotFoundException {
String LS = System.getProperty("line.separator");
Map binding = new HashMap();
binding.put("first", "Tom");
binding.put("last", "Adams");
Template template = new SimpleTemplateEngine().createTemplate("<%= first %>\n<% println last %>");
StringWriter stringWriter = new StringWriter();
Writer platformWriter = new PlatformLineWriter(stringWriter);
template.make(binding).writeTo(platformWriter);
assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString());
}
}
|
Fix first io adapter being called twice. | from .io import IOAdapter
class MultiIOAdapter(IOAdapter):
def __init__(self, **kwargs):
super(MultiIOAdapter, self).__init__(**kwargs)
self.adapters = []
def process_input(self, *args, **kwargs):
"""
Returns data retrieved from the input source.
"""
if self.adapters is not []:
return self.adapters[0].process_input(*args, **kwargs)
def process_response(self, statement):
"""
Takes an input value.
Returns an output value.
"""
for i in range(1, len(self.adapters)):
self.adapters[i].process_response(statement)
return self.adapters[0].process_response(statement)
def add_adapter(self, adapter):
self.adapters.append(adapter)
def set_context(self, context):
"""
Set the context for each of the contained io adapters.
"""
super(MultiIOAdapter, self).set_context(context)
for adapter in self.adapters:
adapter.set_context(context)
| from .io import IOAdapter
class MultiIOAdapter(IOAdapter):
def __init__(self, **kwargs):
super(MultiIOAdapter, self).__init__(**kwargs)
self.adapters = []
def process_input(self, *args, **kwargs):
"""
Returns data retrieved from the input source.
"""
if self.adapters is not []:
return self.adapters[0].process_input(*args, **kwargs)
def process_response(self, statement):
"""
Takes an input value.
Returns an output value.
"""
for adapter in self.adapters:
adapter.process_response(statement)
return self.adapters[0].process_response(statement)
def add_adapter(self, adapter):
self.adapters.append(adapter)
def set_context(self, context):
"""
Set the context for each of the contained io adapters.
"""
super(MultiIOAdapter, self).set_context(context)
for adapter in self.adapters:
adapter.set_context(context)
|
Check for ZF2_PATH env var when including ZF2 AutoloaderFactory | <?php
chdir(dirname(__DIR__));
require_once (getenv('ZF2_PATH') ?: 'vendor/ZendFramework/library') . '/Zend/Loader/AutoloaderFactory.php';
Zend\Loader\AutoloaderFactory::factory(array('Zend\Loader\StandardAutoloader' => array()));
$appConfig = include 'config/application.config.php';
$listenerOptions = new Zend\Module\Listener\ListenerOptions($appConfig['module_listener_options']);
$defaultListeners = new Zend\Module\Listener\DefaultListenerAggregate($listenerOptions);
$defaultListeners->getConfigListener()->addConfigGlobPath('config/autoload/*.config.php');
$moduleManager = new Zend\Module\Manager($appConfig['modules']);
$moduleManager->events()->attachAggregate($defaultListeners);
$moduleManager->loadModules();
// Create application, bootstrap, and run
$bootstrap = new Zend\Mvc\Bootstrap($defaultListeners->getConfigListener()->getMergedConfig());
$application = new Zend\Mvc\Application;
$bootstrap->bootstrap($application);
$application->run()->send();
| <?php
chdir(dirname(__DIR__));
require_once 'vendor/ZendFramework/library/Zend/Loader/AutoloaderFactory.php';
Zend\Loader\AutoloaderFactory::factory(array('Zend\Loader\StandardAutoloader' => array()));
$appConfig = include 'config/application.config.php';
$listenerOptions = new Zend\Module\Listener\ListenerOptions($appConfig['module_listener_options']);
$defaultListeners = new Zend\Module\Listener\DefaultListenerAggregate($listenerOptions);
$defaultListeners->getConfigListener()->addConfigGlobPath('config/autoload/*.config.php');
$moduleManager = new Zend\Module\Manager($appConfig['modules']);
$moduleManager->events()->attachAggregate($defaultListeners);
$moduleManager->loadModules();
// Create application, bootstrap, and run
$bootstrap = new Zend\Mvc\Bootstrap($defaultListeners->getConfigListener()->getMergedConfig());
$application = new Zend\Mvc\Application;
$bootstrap->bootstrap($application);
$application->run()->send();
|
Add test number to assertion | package indexing
import (
"bytes"
"testing"
)
var testWrites = []struct {
docs []Document
out string
}{
{[]Document{},
// Header | End of Docs
"searchme\x00\x00"}, // terminator + doc terminator
{[]Document{{"path", "content"}},
// Header | Doc paths + Terminator | term + terminator + doc id (0)
"searchme\x00path\x00\x00content\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
}
func TestWrite(t *testing.T) {
for testNum, testCase := range testWrites {
i := NewIndex()
buf := new(bytes.Buffer)
for _, doc := range testCase.docs {
i.Add(doc)
}
i.Write(buf)
result := string(buf.Bytes())
if testCase.out != result {
t.Fatalf("%d. Expected: %q Actual %q", testNum, testCase.out, result)
}
}
}
| package indexing
import (
"bytes"
"testing"
)
var testWrites = []struct {
docs []Document
out string
}{
{[]Document{},
// Header | End of Docs
"searchme\x00\x00"}, // terminator + doc terminator
{[]Document{{"path", "content"}},
// Header | Doc paths + Terminator | term + terminator + doc id (0)
"searchme\x00path\x00\x00content\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"},
}
func TestWrite(t *testing.T) {
for _, testCase := range testWrites {
i := NewIndex()
buf := new(bytes.Buffer)
for _, doc := range testCase.docs {
i.Add(doc)
}
i.Write(buf)
result := string(buf.Bytes())
if testCase.out != result {
t.Fatalf("Expected: %q Actual %q", testCase.out, result)
}
}
}
|
Clarify on command class casing | from sublime_plugin import ApplicationCommand
# The print calls show what sublime_plugin.Command.name
# translates the class names to.
class not_pascal_case_command(ApplicationCommand):
def run(self):
print("not_pascal_case")
class not_PascalCaseCommand(ApplicationCommand):
def run(self):
print("not__pascal_case")
class not_PASCALcase_command(ApplicationCommand):
def run(self):
print("not__pASCALcase")
class NotPascalCase_command(ApplicationCommand):
def run(self):
print("not_pascal_case")
class NotPASCALCaseCommand(ApplicationCommand):
def run(self):
print("not_pASCALCase")
class PascalCaseCommand(ApplicationCommand):
def run(self):
print("pascal_case")
| from sublime_plugin import ApplicationCommand
class not_pascal_case_command(ApplicationCommand):
def run(self):
print("not_pascal_case")
class not_PascalCaseCommand(ApplicationCommand):
def run(self):
print("not_PascalCaseCommand")
class not_PASCALcase_command(ApplicationCommand):
def run(self):
print("not_PASCALcase_command")
class NotPascalCase_command(ApplicationCommand):
def run(self):
print("NotPascalCase_command")
# Maybe this should pass:
# A name like HTTPDownloadCommand is translated to "http_download" by ST
class NotPASCALCaseCommand(ApplicationCommand):
def run(self):
print("PASCALCaseCommand")
class PascalCaseCommand(ApplicationCommand):
def run(self):
print("PascalCaseCommand")
|
Set up for v0.26.0 release | """SoCo (Sonos Controller) is a simple library to control Sonos speakers."""
# There is no need for all strings here to be unicode, and Py2 cannot import
# modules with unicode names so do not use from __future__ import
# unicode_literals
# https://github.com/SoCo/SoCo/issues/98
#
import logging
from .core import SoCo
from .discovery import discover
from .exceptions import SoCoException, UnknownSoCoException
# Will be parsed by setup.py to determine package metadata
__author__ = "The SoCo-Team <python-soco@googlegroups.com>"
# Please increment the version number and add the suffix "-dev" after
# a release, to make it possible to identify in-development code
__version__ = "0.26.0-dev"
__website__ = "https://github.com/SoCo/SoCo"
__license__ = "MIT License"
# You really should not `import *` - it is poor practice
# but if you do, here is what you get:
__all__ = [
"discover",
"SoCo",
"SoCoException",
"UnknownSoCoException",
]
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
logging.getLogger(__name__).addHandler(logging.NullHandler())
| """SoCo (Sonos Controller) is a simple library to control Sonos speakers."""
# There is no need for all strings here to be unicode, and Py2 cannot import
# modules with unicode names so do not use from __future__ import
# unicode_literals
# https://github.com/SoCo/SoCo/issues/98
#
import logging
from .core import SoCo
from .discovery import discover
from .exceptions import SoCoException, UnknownSoCoException
# Will be parsed by setup.py to determine package metadata
__author__ = "The SoCo-Team <python-soco@googlegroups.com>"
# Please increment the version number and add the suffix "-dev" after
# a release, to make it possible to identify in-development code
__version__ = "0.25.0"
__website__ = "https://github.com/SoCo/SoCo"
__license__ = "MIT License"
# You really should not `import *` - it is poor practice
# but if you do, here is what you get:
__all__ = [
"discover",
"SoCo",
"SoCoException",
"UnknownSoCoException",
]
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
Fix "Legend Position and Visibility" example. | var options = {
container: document.getElementById('myChart'),
data: [
{ label: 'Android', value: 56.9 },
{ label: 'iOS', value: 22.5 },
{ label: 'BlackBerry', value: 6.8 },
{ label: 'Symbian', value: 8.5 },
{ label: 'Bada', value: 2.6 },
{ label: 'Windows', value: 1.9 }
],
series: [{
type: 'pie',
angleKey: 'value',
labelKey: 'label',
strokeWidth: 3
}],
legend: {
position: 'right'
}
};
var chart = agCharts.AgChart.create(options);
function updateLegendPosition(value) {
options.legend.position = value;
agCharts.AgChart.update(chart, options);
}
function setLegendEnabled(enabled) {
options.legend.enabled = enabled;
agCharts.AgChart.update(chart, options);
}
| var options = {
container: document.getElementById('myChart'),
data: [
{ label: 'Android', value: 56.9 },
{ label: 'iOS', value: 22.5 },
{ label: 'BlackBerry', value: 6.8 },
{ label: 'Symbian', value: 8.5 },
{ label: 'Bada', value: 2.6 },
{ label: 'Windows', value: 1.9 }
],
series: [{
type: 'pie',
angleKey: 'value',
labelKey: 'label',
strokeWidth: 3
}],
legend: {
position: 'right'
}
};
var chart = agCharts.AgChart.create(options);
function updateLegendPosition(value) {
chart.legend.position = value;
}
function setLegendEnabled(enabled) {
chart.legend.enabled = enabled;
}
|
Use short array deconstruction syntax. | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Process\Tests;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Process;
require \dirname(__DIR__).'/vendor/autoload.php';
['e' => $php] = getopt('e:') + ['e' => 'php'];
try {
$process = new Process("exec $php -r \"echo 'ready'; trigger_error('error', E_USER_ERROR);\"");
$process->start();
$process->setTimeout(0.5);
while (false === strpos($process->getOutput(), 'ready')) {
usleep(1000);
}
$process->signal(\SIGSTOP);
$process->wait();
return $process->getExitCode();
} catch (ProcessTimedOutException $t) {
echo $t->getMessage().\PHP_EOL;
return 1;
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Process\Tests;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Process;
require \dirname(__DIR__).'/vendor/autoload.php';
list('e' => $php) = getopt('e:') + ['e' => 'php'];
try {
$process = new Process("exec $php -r \"echo 'ready'; trigger_error('error', E_USER_ERROR);\"");
$process->start();
$process->setTimeout(0.5);
while (false === strpos($process->getOutput(), 'ready')) {
usleep(1000);
}
$process->signal(\SIGSTOP);
$process->wait();
return $process->getExitCode();
} catch (ProcessTimedOutException $t) {
echo $t->getMessage().\PHP_EOL;
return 1;
}
|
Add missing test cases to mark a todo | const chai = require('chai');
const expect = chai.expect;
const xcode = require('xcode');
const createGroup = require('../../src/ios/createGroup');
const last = require('lodash').last;
const project = xcode.project('test/fixtures/project.pbxproj');
describe('ios::createGroup', () => {
beforeEach(() => {
project.parseSync();
});
it('should create a group with given name', () => {
const createdGroup = createGroup(project, 'Resources').group;
expect(createdGroup.name).to.equals('Resources');
});
it('should attach group to main project group', () => {
const mainGroupId = project.getFirstProject().firstProject.mainGroup;
const createdGroup = createGroup(project, 'Resources');
const mainGroup = project.getPBXGroupByKey(mainGroupId);
expect(
last(mainGroup.children).value
).to.equals(createdGroup.uuid);
});
it.skip('should create a nested group with given path', () => {
const createdGroup = createGroup(project, 'NewGroup/NewNestedGroup').group;
});
it.skip('should-not create already created groups', () => {
const createdGroup = createGroup(project, 'Libraries/NewNestedGroup').group;
});
});
| const chai = require('chai');
const expect = chai.expect;
const xcode = require('xcode');
const createGroup = require('../../src/ios/createGroup');
const last = require('lodash').last;
const project = xcode.project('test/fixtures/project.pbxproj');
describe('ios::createGroup', () => {
beforeEach(() => {
project.parseSync();
});
it('should create a group with given name', () => {
const createdGroup = createGroup(project, 'Resources').group;
expect(createdGroup.name).to.equals('Resources');
});
it('should attach group to main project group', () => {
const mainGroupId = project.getFirstProject().firstProject.mainGroup;
const createdGroup = createGroup(project, 'Resources');
const mainGroup = project.getPBXGroupByKey(mainGroupId);
expect(
last(mainGroup.children).value
).to.equals(createdGroup.uuid);
});
});
|
Set created time with default callback
auto_now is evil, as any editing and overriding is
almost completely impossible (e.g. unittesting) | from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = fields.CharField(max_length=255)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES)
created = fields.DateTimeField(default=timezone.now, editable=False)
modified = fields.DateTimeField(default=timezone.now)
user = models.ForeignKey(User)
def __str__(self):
return "{}".format(self.title)
| from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Transaction(models.Model):
EXPENSE = 'exp'
INCOME = 'inc'
CATEGORY_CHOICES = (
(EXPENSE, 'expense'),
(INCOME, 'income'),
)
title = fields.CharField(max_length=255)
amount = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.CharField(max_length=3, choices=CATEGORY_CHOICES)
created = fields.DateTimeField(auto_now=True)
modified = fields.DateTimeField(default=timezone.now)
user = models.ForeignKey(User)
def __str__(self):
return "{}".format(self.title)
|
Change action creator name to changeGridAction | import {changeGridAction, GRID_CHANGED} from "../../src/actions/GameActions.js";
describe("Game Actions", () => {
it("should exist", () => {
changeGridAction.should.exist;
});
it("should be a function", () => {
changeGridAction.should.be.function;
});
it("should create action of type GRID_CHANGED", () => {
const action = changeGridAction();
action.type.should.be.equal(GRID_CHANGED);
});
it("should have props x, y equal to function arguments", () => {
var action = changeGridAction(0,0);
const gridChangedAt00 = {
x: 0,
y: 0,
type: GRID_CHANGED
};
action.should.be.eql(gridChangedAt00);
action = changeGridAction(2,1);
const gridChangedAt21 = {
x: 2,
y: 1,
type: GRID_CHANGED
};
action.should.be.eql(gridChangedAt21);
});
});
| import {gridChangedAction, GRID_CHANGED} from "../../src/actions/GameActions.js";
describe("Game Actions", () => {
it("should exist", () => {
gridChangedAction.should.exist;
});
it("should be a function", () => {
gridChangedAction.should.be.function;
});
it("should create action of type GRID_CHANGED", () => {
const action = gridChangedAction();
action.type.should.be.equal(GRID_CHANGED);
});
it("should have props x, y equal to function arguments", () => {
var action = gridChangedAction(0,0);
const gridChangedAt00 = {
x: 0,
y: 0,
type: GRID_CHANGED
};
action.should.be.eql(gridChangedAt00);
action = gridChangedAction(2,1);
const gridChangedAt21 = {
x: 2,
y: 1,
type: GRID_CHANGED
};
action.should.be.eql(gridChangedAt21);
});
});
|
Add RuntimeAdapter for API22. Attach has one new String parameter "referrer" | package org.robolectric.internal.runtime;
import android.os.Build;
import org.robolectric.RuntimeEnvironment;
public class RuntimeAdapterFactory {
public static RuntimeAdapter getInstance() {
int apiLevel = RuntimeEnvironment.getApiLevel();
if (apiLevel <= Build.VERSION_CODES.JELLY_BEAN) {
return new Api16RuntimeAdapter();
} else if (apiLevel <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return new Api17RuntimeAdapter();
} else if (apiLevel <= Build.VERSION_CODES.KITKAT) {
return new Api19RuntimeAdapter();
} else if (apiLevel <= Build.VERSION_CODES.LOLLIPOP) {
return new Api21RuntimeAdapter();
} else if (apiLevel <= Build.VERSION_CODES.LOLLIPOP_MR1) {
return new Api22RuntimeAdapter();
} else {
throw new RuntimeException("Could not find AndroidRuntimeAdapter for API level: " + apiLevel);
}
}
}
| package org.robolectric.internal.runtime;
import android.os.Build;
import org.robolectric.RuntimeEnvironment;
public class RuntimeAdapterFactory {
public static RuntimeAdapter getInstance() {
int apiLevel = RuntimeEnvironment.getApiLevel();
if (apiLevel <= Build.VERSION_CODES.JELLY_BEAN) {
return new Api16RuntimeAdapter();
} else if (apiLevel <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return new Api17RuntimeAdapter();
} else if (apiLevel <= Build.VERSION_CODES.KITKAT) {
return new Api19RuntimeAdapter();
} else if (apiLevel <= Build.VERSION_CODES.LOLLIPOP) {
return new Api21RuntimeAdapter();
} else {
throw new RuntimeException("Could not find AndroidRuntimeAdapter for API level: " + apiLevel);
}
}
}
|
Change assertion to be slightly more flexible | const assert = require("assert");
const CommandRunner = require("../commandrunner");
const MemoryLogger = require("../memorylogger");
let config = {};
describe("truffle help", () => {
const logger = new MemoryLogger();
beforeEach("set up config for logger", () => {
config.logger = logger;
});
describe("when run without arguments", () => {
it("displays general help", function(done) {
CommandRunner.run("help", config, (error) => {
const output = logger.contents();
assert(output.includes("Usage: truffle <command> [options]"));
done();
});
});
})
describe("when run with an argument", () => {
it("tells the user if it doesn't recognize the given command", function(done) {
CommandRunner.run("help eggplant", config, (error) => {
const output = logger.contents();
assert(output.includes("Cannot find the given command 'eggplant'"));
done();
});
});
it("displays help for the given command when valid", function(done) {
CommandRunner.run("help compile", config, (error) => {
const output = logger.contents();
assert(output.includes("Description: Compile contract source files"));
done();
});
});
});
});
| const assert = require("assert");
const CommandRunner = require("../commandrunner");
const MemoryLogger = require("../memorylogger");
let config = {};
describe("truffle help", () => {
const logger = new MemoryLogger();
beforeEach("set up config for logger", () => {
config.logger = logger;
});
describe("when run without arguments", () => {
it("displays general help", function(done) {
CommandRunner.run("help", config, (error) => {
const output = logger.contents();
assert(output.includes("Usage: truffle <command> [options]"));
done();
});
});
})
describe("when run with an argument", () => {
it("tells the user if it doesn't recognize the given command", function(done) {
CommandRunner.run("help eggplant", config, (error) => {
const output = logger.contents();
assert(output.includes("Cannot find the given command 'eggplant'"));
done();
});
});
it("displays help for the given command when valid", function(done) {
CommandRunner.run("help compile", config, (error) => {
const output = logger.contents();
assert(output.includes("truffle compile [--list <prereleases|releases|docker>] [--all] [--network <name>]"));
done();
});
});
});
});
|
Append scss outside of recursive function calls | var sass = require('node-sass'),
path = require('path'),
fs = require('fs');
var handledBaseFolderNames = {
'bower_components': 'bower_components',
'node_modules': 'node_modules'
};
function customImporter (url, prev, done) {
var baseFolderName = url.split(path.sep)[0];
if (handledBaseFolderNames[baseFolderName]) {
if (!endsWith(url, '.scss')) {
url += '.scss';
}
return findInParentDir(url, prev, done);
}
return sass.NULL;
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function findInParentDir(relativePath, startingDirPath, done) {
var dirToTry = path.join(startingDirPath, '..');
var pathToTry = path.join(dirToTry, relativePath);
try {
fs.access(pathToTry, fs.R_OK, function(err) {
if (err) {
return findInParentDir(relativePath, dirToTry, done);
} else {
done({ file: pathToTry });
}
});
} catch (e) {
return sass.NULL;
}
}
module.exports = customImporter;
| var sass = require('node-sass'),
path = require('path'),
fs = require('fs');
var handledBaseFolderNames = {
'bower_components': 'bower_components',
'node_modules': 'node_modules'
};
function customImporter (url, prev, done) {
var baseFolderName = url.split(path.sep)[0];
if (handledBaseFolderNames[baseFolderName]) {
return findInParentDir(url, prev, done);
}
return sass.NULL;
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function findInParentDir(relativePath, startingDirPath, done) {
if (!endsWith(relativePath, '.scss')) {
relativePath += '.scss';
}
var dirToTry = path.join(startingDirPath, '..');
var pathToTry = path.join(dirToTry, relativePath);
try {
fs.access(pathToTry, fs.R_OK, function(err) {
if (err) {
return findInParentDir(relativePath, dirToTry, done);
} else {
done({ file: pathToTry });
}
});
} catch (e) {
return sass.NULL;
}
}
module.exports = customImporter;
|
Refactor panel triggers for speed | "use strict";
// Generators for Arethusa code for things such as
// - useful directives
function ArethusaGenerator() {
this.panelTrigger = function panelTrigger(service, trsl, trslKey, template) {
return {
restrict: 'A',
compile: function(element) {
var parent = element.parent();
function updateTitle(translation) {
parent.attr('title', translation);
}
return function link(scope, element, attrs) {
function toggle() {
scope.$apply(service.toggle());
}
trsl(trslKey, updateTitle);
element.bind('click', toggle);
};
},
template: template
};
};
}
var arethusaGenerator = new ArethusaGenerator();
var aG = arethusaGenerator;
| "use strict";
// Generators for Arethusa code for things such as
// - useful directives
function ArethusaGenerator() {
this.panelTrigger = function panelTrigger(service, trsl, trslKey, template) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
function toggle() {
scope.$apply(service.toggle());
}
var parent = element.parent();
trsl(trslKey, function(translation) {
parent.attr('title', translation);
});
element.bind('click', toggle);
},
template: template
};
};
}
var arethusaGenerator = new ArethusaGenerator();
var aG = arethusaGenerator;
|
Remove children via uid rather than name | #!/usr/bin/env python
import functools
import os
import signal
import sys
import docker_utils
def handler(name, signum, frame):
print('Should kill', name)
try:
cid = open('/child_{}'.format(name)).read().strip()
docker_utils.client.remove_container(cid, force=True)
except Exception:
pass
sys.exit(0)
def launch(name, args):
try:
cid = open('/child_{}'.format(name)).read().strip()
except IOError:
cid = name
try:
os.unlink('/child_{}'.format(name))
except OSError:
pass
try:
docker_utils.client.remove_container(cid, force=True)
except Exception:
pass
args.insert(0, '--cidfile=/child_{}'.format(name))
docker_utils.docker('run', *args)
if __name__ == '__main__':
name = sys.argv[1]
args = sys.argv[2:]
signal.signal(signal.SIGINT, functools.partial(handler, name))
launch(name, args)
| #!/usr/bin/env python
import functools
import os
import signal
import sys
import docker_utils
def handler(name, signum, frame):
print('Should kill', name)
try:
docker_utils.client.remove_container(name, force=True)
except Exception:
pass
sys.exit(0)
def launch(name, args):
try:
os.unlink('/child_{}'.format(name))
except OSError:
pass
try:
docker_utils.client.remove_container(name, force=True)
except Exception:
pass
args.insert(0, '--cidfile=/child_{}'.format(name))
docker_utils.docker('run', *args)
if __name__ == '__main__':
name = sys.argv[1]
args = sys.argv[2:]
signal.signal(signal.SIGINT, functools.partial(handler, name))
launch(name, args)
|
Make node callback friendly and catch errors
This commit makes the callback given to the `calculate()` function node friendly.
This commit also wraps the `ffmpeg.ffprobe()` function in a `try/catch` expression
to catch errors thrown in that function and propagate them to the callback. | /*jshint node:true */
/*jshint esversion:6*/
/**_________LITTLSTAR/BITS-PER-PIXEL______________
* BITRATE / (HEIGHT X WIDTH X FPS) calculator
* @author Andrew Grathwohl <andrew@littlstar.com>
*/
'use strict';
const ffmpeg = require("fluent-ffmpeg");
ffmpeg.setFfprobePath(process.env.FFPROBE || '/usr/bin/ffprobe');
ffmpeg.setFfmpegPath(process.env.FFMPEG || '/usr/bin/ffmpeg');
exports.calculate = function calculate (videoFile, cb) {
try { ffmpeg.ffprobe(videoFile, onprobe); }
catch (err) { return cb(err); }
function onprobe(err, metadata) {
if (err) { return cb(err); }
const height = metadata.streams[0].height;
const width = metadata.streams[0].width;
const fpsVal = metadata.streams[0].r_frame_rate.split('/');
const bits = metadata.streams[0].bit_rate;
const fps = parseFloat(fpsVal[0]) / parseFloat(fpsVal[1]);
const bpp = bits / (height * width * fps);
cb(null, bpp);
}
};
| /*jshint node:true */
/*jshint esversion:6*/
/**_________LITTLSTAR/BITS-PER-PIXEL______________
* BITRATE / (HEIGHT X WIDTH X FPS) calculator
* @author Andrew Grathwohl <andrew@littlstar.com>
*/
'use strict';
const ffmpeg = require("fluent-ffmpeg");
ffmpeg.setFfprobePath(process.env.FFPROBE || '/usr/bin/ffprobe');
ffmpeg.setFfmpegPath(process.env.FFMPEG || '/usr/bin/ffmpeg');
exports.calculate = function calcBpp (videoFile, cb) {
ffmpeg.ffprobe(videoFile, function(err, metadata) {
const height = metadata.streams[0].height;
const width = metadata.streams[0].width;
const fpsVal = metadata.streams[0].r_frame_rate.split('/');
const bits = metadata.streams[0].bit_rate;
const fps = parseFloat(fpsVal[0]) / parseFloat(fpsVal[1]);
const bpp = bits / (height * width * fps);
cb(bpp);
});
};
|
Use a more meaningful test | 'use strict'
var CachedUserItems = require('../../src/GooglePlus/CachedUserItems')
var assert = require('assert')
describe("CachedUserItems", function () {
describe("_getCacheAgePerUser", function () {
it("is ~4 hours for current values", function () {
var googlePlus = {} // TODO Don't stub
var cachedUserItems = new CachedUserItems(googlePlus) // TODO Avoid this dependency
var age = cachedUserItems._getCacheAgePerUser({
maxDailyUsers: 10000,
dailyRequestsLimit: 50000
})
assert.equal(age, 4.8 /* hours */ * 60 * 60 * 1000)
})
})
})
| 'use strict'
var CachedUserItems = require('../../src/GooglePlus/CachedUserItems')
var assert = require('assert')
describe("CachedUserItems", function () {
describe("_getCacheAgePerUser", function () {
it("is 24h with as much requests as user feeds", function () {
var googlePlus = {} // TODO Don't stub
var cachedUserItems = new CachedUserItems(googlePlus) // TODO Avoid this dependency
var age = cachedUserItems._getCacheAgePerUser({
maxDailyUsers: 100,
dailyRequestsLimit: 100
})
assert.equal(age, 24 /* hours */ * 60 * 60 * 1000)
})
})
})
|
Fix path where the images are saved. | from django.db import models
from tinymce import models as tinymce_models
photos_path = "simple-faq/"
class Topic(models.Model):
text = models.CharField(max_length=200)
number = models.IntegerField()
class Meta:
ordering = ['number']
def __unicode__(self):
return u'(%s) %s' % (self.number, self.text, )
class Question(models.Model):
text = models.CharField(max_length=200)
answer_text = tinymce_models.HTMLField()
topic = models.ForeignKey(Topic, related_name="questions")
header_picture = models.ImageField(upload_to=photos_path, blank=True)
number = models.IntegerField()
related_questions = models.ManyToManyField("self", related_name="related_questions", blank=True, null=True)
class Meta:
ordering = ['number']
def __unicode__(self):
return u'(%s) %s' % (self.number, self.text, )
| from django.db import models
from tinymce import models as tinymce_models
photos_path = "/simple-faq/"
class Topic(models.Model):
text = models.CharField(max_length=200)
number = models.IntegerField()
class Meta:
ordering = ['number']
def __unicode__(self):
return u'(%s) %s' % (self.number, self.text, )
class Question(models.Model):
text = models.CharField(max_length=200)
answer_text = tinymce_models.HTMLField()
topic = models.ForeignKey(Topic, related_name="questions")
header_picture = models.ImageField(upload_to=photos_path, blank=True)
number = models.IntegerField()
related_questions = models.ManyToManyField("self", related_name="related_questions", blank=True, null=True)
class Meta:
ordering = ['number']
def __unicode__(self):
return u'(%s) %s' % (self.number, self.text, )
|
Fix changelog versioning to include date only after final release | #!/usr/bin/env node
// Sets the release date of the current release in the changelog.
// This is run automatically when npm version is run.
const fs = require('fs');
const cp = require('child_process');
const suffix = process.env.PRERELEASE_SUFFIX || 'rc';
const changelog = fs.readFileSync('CHANGELOG.md', 'utf8');
// The changelog entry to be updated looks like this:
// ## Unreleased
// We need to add the version and release date in a YYYY-MM-DD format, so that it looks like this:
// ## 2.5.3 (2019-04-25)
const pkg = require('../../package.json');
const version = pkg.version.replace(new RegExp('-' + suffix + '\\..*'), '');
const header = new RegExp(`^## (Unreleased|${version})$`, 'm');
if (!header.test(changelog)) {
console.error('Missing changelog entry');
process.exit(1);
}
const newHeader = pkg.version.indexOf(suffix) === -1
? `## ${version} (${new Date().toISOString().split('T')[0]})`
: `## ${version}`;
fs.writeFileSync('CHANGELOG.md',
changelog.replace(header, newHeader)
);
cp.execSync('git add CHANGELOG.md', { stdio: 'inherit' });
| #!/usr/bin/env node
// Sets the release date of the current release in the changelog.
// This is run automatically when npm version is run.
const fs = require('fs');
const cp = require('child_process');
const suffix = process.env.PRERELEASE_SUFFIX || 'rc';
const changelog = fs.readFileSync('CHANGELOG.md', 'utf8');
// The changelog entry to be updated looks like this:
// ## Unreleased
// We need to add the version and release date in a YYYY-MM-DD format, so that it looks like this:
// ## 2.5.3 (2019-04-25)
const pkg = require('../../package.json');
const version = pkg.version.replace(new RegExp('-' + suffix + '\\..*'), '');
const unreleased = /^## Unreleased$/im;
const released = new RegExp(`^## ${version} \\([-\\d]*\\)$`, 'm');
if (released.test(changelog)) {
process.exit(0);
}
if (!unreleased.test(changelog)) {
console.error('Missing changelog entry');
process.exit(1);
}
fs.writeFileSync('CHANGELOG.md', changelog.replace(
unreleased,
`## ${version} (${new Date().toISOString().split('T')[0]})`),
);
cp.execSync('git add CHANGELOG.md', { stdio: 'inherit' });
|
Update to load the .env file using existing technologies. | <?php
if (!getenv('DATABASE_PATH')) {
// crank up the Composer autoloading
require __DIR__.'/../vendor/autoload.php';
// load environment variables
\Lib\Framework\EnvVarsLoader::loadEnvVars();
}
return [
/*
* Database connections
* Currently only SQLite & mySQL are set up
* others to come soon
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => getenv('DATABASE_PATH'),
],
'mysql' => [
'driver' => 'pdo_mysql',
'user' => getenv('DATABASE_USER'),
'password' => getenv('DATABASE_PASSWORD'),
'host' => getenv('DATABASE_HOST'),
'dbname' => getenv('DATABASE_NAME'),
],
],
];
| <?php
return [
/*
* Database connections
* Currently only SQLite & mySQL are set up
* others to come soon
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => getenv('DATABASE_PATH'),
],
'mysql' => [
'driver' => 'pdo_mysql',
'user' => getenv('DATABASE_USER'),
'password' => getenv('DATABASE_PASSWORD'),
'host' => getenv('DATABASE_HOST'),
'dbname' => getenv('DATABASE_NAME'),
],
],
];
|
Add support for a single string destination | /* jshint node: true */
var PLUGIN_NAME = 'gulp-multi-dest';
var through = require('through2');
var gulp = require('gulp');
var async = require('async');
module.exports = function(paths, options) {
options = options || {};
var files = [];
if (typeof (paths) === 'string') { paths = [paths]; }
var dests = paths.map(function(path) {
return gulp.dest(path, options);
});
function writeFilesToMultipleDestinations(file, done) {
async.each(dests, function(dest, wroteOne) {
dest.write(file, wroteOne);
}, done);
}
var holdFile = function(file, encoding, done) {
files.push(file);
done();
};
var flushAllFiles = function(done) {
var transform = this;
function outputFiles() {
files.forEach(function(file) {
transform.push(file);
});
done();
}
async.each(files, writeFilesToMultipleDestinations, outputFiles);
};
return through.obj(holdFile, flushAllFiles);
}; | /* jshint node: true */
var PLUGIN_NAME = 'gulp-multi-dest';
var through = require('through2');
var gulp = require('gulp');
var async = require('async');
module.exports = function(paths, options) {
options = options || {};
var files = [];
var dests = paths.map(function(path) {
return gulp.dest(path, options);
});
function writeFilesToMultipleDestinations(file, done) {
async.each(dests, function(dest, wroteOne) {
dest.write(file, wroteOne);
}, done);
}
var holdFile = function(file, encoding, done) {
files.push(file);
done();
};
var flushAllFiles = function(done) {
var transform = this;
function outputFiles() {
files.forEach(function(file) {
transform.push(file);
});
done();
}
async.each(files, writeFilesToMultipleDestinations, outputFiles);
};
return through.obj(holdFile, flushAllFiles);
}; |
Update parser to the changes in the report format | # This is an example of how to parse ooniprobe reports
import yaml
import sys
print "Opening %s" % sys.argv[1]
f = open(sys.argv[1])
yamloo = yaml.safe_load_all(f)
report_header = yamloo.next()
print "ASN: %s" % report_header['probe_asn']
print "CC: %s" % report_header['probe_cc']
print "IP: %s" % report_header['probe_ip']
print "Start Time: %s" % report_header['start_time']
print "Test name: %s" % report_header['test_name']
print "Test version: %s" % report_header['test_version']
for report_entry in yamloo:
print "Test: %s" % report_entry['test_name']
print "Input: %s" % report_entry['input']
print "Report: %s" % report_entry['report']
f.close()
| # This is an example of how to parse ooniprobe reports
import yaml
import sys
print "Opening %s" % sys.argv[1]
f = open(sys.argv[1])
yamloo = yaml.safe_load_all(f)
report_header = yamloo.next()
print "ASN: %s" % report_header['probe_asn']
print "CC: %s" % report_header['probe_cc']
print "IP: %s" % report_header['probe_ip']
print "Start Time: %s" % report_header['start_time']
print "Test name: %s" % report_header['test_name']
print "Test version: %s" % report_header['test_version']
for report_entry in yamloo:
print "Test: %s" % report_entry['test']
print "Input: %s" % report_entry['input']
print "Report: %s" % report_entry['report']
f.close()
|
Use six to add meta class | import abc
import os
from pkg_resources import DistributionNotFound, get_distribution
from six.moves.configparser import SafeConfigParser, add_metaclass
from . import log_utils
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
pass
__license__ = 'Apache 2.0'
PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
# Read the configuration files
_cfgs = ('worker.dist.cfg', 'worker.local.cfg')
config = SafeConfigParser({
'RABBITMQ_USER': os.environ.get('RABBITMQ_USER', 'guest'),
'RABBITMQ_PASS': os.environ.get('RABBITMQ_PASS', 'guest'),
'RABBITMQ_HOST': os.environ.get('RABBITMQ_HOST', 'localhost')
})
config.read([os.path.join(PACKAGE_DIR, f) for f in _cfgs])
# Create and configure our logger
logger = log_utils.setupLogger(config)
@add_metaclass(abc.ABCMeta)
class GirderWorkerPluginABC(object):
""" """
@abc.abstractmethod
def __init__(self, app, *args, **kwargs):
""" """
@abc.abstractmethod
def task_imports(self):
""" """
class GirderWorkerPlugin(GirderWorkerPluginABC):
def __init__(self, app, *args, **kwargs):
self.app = app
def task_imports(self):
return ['girder_worker.tasks']
| import abc
import os
from pkg_resources import DistributionNotFound, get_distribution
from six.moves.configparser import SafeConfigParser
from . import log_utils
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
pass
__license__ = 'Apache 2.0'
PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
# Read the configuration files
_cfgs = ('worker.dist.cfg', 'worker.local.cfg')
config = SafeConfigParser({
'RABBITMQ_USER': os.environ.get('RABBITMQ_USER', 'guest'),
'RABBITMQ_PASS': os.environ.get('RABBITMQ_PASS', 'guest'),
'RABBITMQ_HOST': os.environ.get('RABBITMQ_HOST', 'localhost')
})
config.read([os.path.join(PACKAGE_DIR, f) for f in _cfgs])
# Create and configure our logger
logger = log_utils.setupLogger(config)
class GirderWorkerPluginABC(object):
""" """
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __init__(self, app, *args, **kwargs):
""" """
@abc.abstractmethod
def task_imports(self):
""" """
class GirderWorkerPlugin(GirderWorkerPluginABC):
def __init__(self, app, *args, **kwargs):
self.app = app
def task_imports(self):
return ['girder_worker.tasks']
|
Update CSociety Webpage to include more info | <?php
$page_title = 'Home';
$site_title = 'Computer Society';
$site_index = '/csociety';
include '../header.php';
?>
<link href="/assets/bootstrap.csociety.css" rel="stylesheet">
<!-- Content Row -->
<div class="well card-1">
<div class="row">
<!-- Content Column -->
<div class="col-md-8 text-dark col-md-offset-2 text-dark">
<h2>Computer Society</h2>
<p>We are a group of highly curious people with quirks in the science of computation. We do cool stuff with computers and try to spread the enlightenment with who-so-ever matches the level of curiosity of the group. 3D printing, web developing, cyber security, high performance computing, machine learning, graphics and everything you've heard of as tech-y is discussed, talked and made here, feel free to drop by. Contact <a href="mailto:shah255@purdue.edu">Sid Shah</a> for more details.</p><br>
<a href="https://twitter.com/PurdueCSociety"><i class="fa fa-twitter-square fa-4x"></i></a>
</div>
</div>
</div>
<!-- /.well -->
<?php include '../footer.php';?>
| <?php
$page_title = 'Home';
$site_title = 'Computer Society';
$site_index = '/csociety';
include '../header.php';
?>
<link href="/assets/bootstrap.csociety.css" rel="stylesheet">
<!-- Content Row -->
<div class="well card-1">
<div class="row">
<!-- Content Column -->
<div class="col-md-8 text-dark col-md-offset-2 text-dark">
<h2>Computer Society</h2>
<p>The Computer Society does fun projects with computers! Contact <a href="mailto:shah255@purdue.edu">Sid Shah</a> for more details.</p><br>
<a href="https://twitter.com/PurdueCSociety"><i class="fa fa-twitter-square fa-4x"></i></a>
</div>
</div>
</div>
<!-- /.well -->
<?php include '../footer.php';?>
|
Set release version to 1.0 | # Copyright 2013 TellApart, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# =============================================================================
#
# setup.py for the commandr package.
#
from distutils.core import setup
setup(
name='commandr',
version='1.0',
packages=['commandr'],
author='Kevin Ballard',
author_email='kevin@tellapart.com',
url='http://pypi.python.org/pypi/commandr/',
license='')
| # Copyright 2013 TellApart, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# =============================================================================
#
# setup.py for the commandr package.
#
from distutils.core import setup
setup(
name='commandr',
version='1.0dev',
packages=['commandr'],
author='Kevin Ballard',
author_email='kevin@tellapart.com',
url='http://pypi.python.org/pypi/commandr/',
license='') |
Add yt_auth module again. Was taken off by mistake. | var youtubeApp = angular.module('youtubeApp',
[
'ngRoute',
'ngResource',
'pascalprecht.translate',
'reactTo',
require('./yt_result').name,
require('./yt_search').name,
require('./cw_revealLabel').name,
require('./yt_auth').name
]);
youtubeApp.config(function ($provide, $routeProvider, $translateProvider, $httpProvider, $locationProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
template: require('./mainTemplate.html')
})
.otherwise({
redirectTo: '/'
});
$translateProvider.translations('en', {
});
$translateProvider.preferredLanguage('en');
});
youtubeApp.constant("SERVERPATHS", {
youtubeUrl: "/playlist"
})
| var youtubeApp = angular.module('youtubeApp',
[
'ngRoute',
'ngResource',
'pascalprecht.translate',
'reactTo',
require('./yt_result').name,
require('./yt_search').name,
require('./cw_revealLabel').name
]);
youtubeApp.config(function ($provide, $routeProvider, $translateProvider, $httpProvider, $locationProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
template: require('./mainTemplate.html')
})
.otherwise({
redirectTo: '/'
});
$translateProvider.translations('en', {
});
$translateProvider.preferredLanguage('en');
});
youtubeApp.constant("SERVERPATHS", {
youtubeUrl: "/playlist"
})
|
Fix the headerFormat locale for range calendar
closes #93 | import React from 'react';
import {withImmutableProps} from '../utils';
import defaultSelectionRenderer from './defaultSelectionRenderer';
import styles from './Header.scss';
export default withImmutableProps(({renderSelection}) => ({
renderSelection: (values, props) => {
if (!values || !values.start && !values.end) {
return null;
}
if (values.start === values.end) {
return defaultSelectionRenderer(values.start, props);
}
const dateFormat = props.locale && props.locale.headerFormat ? props.locale.headerFormat : 'MMM Do';
return (
<div className={styles.range} style={{color: props.theme.headerColor}}>
{defaultSelectionRenderer(values.start, {...props, dateFormat, key: 'start', shouldAnimate: false})}
{defaultSelectionRenderer(values.end, {...props, dateFormat, key: 'end', shouldAnimate: false})}
</div>
);
},
}));
| import React from 'react';
import {withImmutableProps} from '../utils';
import defaultSelectionRenderer from './defaultSelectionRenderer';
import styles from './Header.scss';
export default withImmutableProps(({renderSelection}) => ({
renderSelection: (values, props) => {
if (!values || !values.start && !values.end) {
return null;
}
if (values.start === values.end) {
return defaultSelectionRenderer(values.start, props);
}
const dateFormat = 'MMM Do';
return (
<div className={styles.range} style={{color: props.theme.headerColor}}>
{defaultSelectionRenderer(values.start, {...props, dateFormat, key: 'start', shouldAnimate: false})}
{defaultSelectionRenderer(values.end, {...props, dateFormat, key: 'end', shouldAnimate: false})}
</div>
);
},
}));
|
Upgrade Localstack docker image to version 0.12.5 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.infra.aws2.services;
public class AWSSQSLocalContainerService extends AWSLocalContainerService {
public AWSSQSLocalContainerService() {
super("localstack/localstack:0.12.5", Service.SQS);
}
}
| /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.infra.aws2.services;
public class AWSSQSLocalContainerService extends AWSLocalContainerService {
public AWSSQSLocalContainerService() {
super("localstack/localstack:0.12.3", Service.SQS);
}
}
|
Fix lack of private constructor in utility method. | /*
* Copyright 2016, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.tools.codestyle;
/**
* @author Alexander Aleksandrov
*/
public class JavaSources {
private JavaSources(){}
private static final String ext = ".java";
private static final String readFileErrMsg = "Cannot read the contents of the file: ";
public static String javaExt(){
return ext;
}
public static String getReadFileErrMsg(){
return readFileErrMsg;
}
}
| /*
* Copyright 2016, TeamDev Ltd. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.spine3.tools.codestyle;
/**
* @author Alexander Aleksandrov
*/
public class JavaSources {
private static final String ext = ".java";
private static final String readFileErrMsg = "Cannot read the contents of the file: ";
public static String javaExt(){
return ext;
}
public static String getReadFileErrMsg(){
return readFileErrMsg;
}
}
|
Use uuid as file name | import os
import boto
import boto.s3
from boto.s3.key import Key
import requests
import uuid
# http://stackoverflow.com/a/42493144
def upload_url_to_s3(image_url):
image_res = requests.get(image_url, stream=True)
image = image_res.raw
image_data = image.read()
fname = str(uuid.uuid4())
conn = boto.connect_s3(os.environ['AWS_ACCESS_KEY_ID_DIVERSEUI'],
os.environ['AWS_SECRET_KEY_DIVERSEUI'])
bucket = conn.get_bucket('diverse-ui')
k = Key(bucket, 'faces/{}'.format(fname))
k.set_contents_from_string(image_data)
k.make_public()
return 'https://d3iw72m71ie81c.cloudfront.net/{}'.format(fname)
| import os
import boto
import boto.s3
from boto.s3.key import Key
import requests
import uuid
# http://stackoverflow.com/a/42493144
def upload_url_to_s3(image_url):
image_res = requests.get(image_url, stream=True)
image = image_res.raw
image_data = image.read()
fname = '{}.jpg'.format(str(uuid.uuid4()))
conn = boto.connect_s3(os.environ['AWS_ACCESS_KEY_ID_DIVERSEUI'],
os.environ['AWS_SECRET_KEY_DIVERSEUI'])
bucket = conn.get_bucket('diverse-ui')
k = Key(bucket, 'faces/{}'.format(fname))
k.set_contents_from_string(image_data)
k.make_public()
return 'https://d3iw72m71ie81c.cloudfront.net/{}'.format(fname)
|
Add JS hack cuz Bootstrap don't work right with collapsible. | /* expand_contract_toggle.js: Support for show more/hide more in lists of umlaut content.
The JS needs to swap out the image for expand/contract toggle. AND we need
the URL it swaps in to be an ABSOLUTE url when we're using partial html
widget.
So we swap in a non-fingerprinted URL, even if the original was asset
pipline fingerprinted. sorry, best way to make it work!
*/
jQuery(document).ready(function($) {
$(".collapse-toggle").live("click", function(event) {
event.preventDefault();
$(this).collapse('toggle');
return false;
});
$(".collapse").live("shown", function(event) {
// Hack cuz collapse don't work right
if($(this).hasClass('in')) {
// Update the icon
$(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-closed").addClass("umlaut_icons-list-open");
// Update the action label
$(this).parent().find(".expand_contract_action_label").text("Hide ");
}
});
$(".collapse").live("hidden", function(event) {
// Hack cuz collapse don't work right
if(!$(this).hasClass('in')) {
// Update the icon
$(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-open").addClass("umlaut_icons-list-closed");
// Update the action label
$(this).parent().find(".expand_contract_action_label").text("Show ");
}
});
}); | /* expand_contract_toggle.js: Support for show more/hide more in lists of umlaut content.
The JS needs to swap out the image for expand/contract toggle. AND we need
the URL it swaps in to be an ABSOLUTE url when we're using partial html
widget.
So we swap in a non-fingerprinted URL, even if the original was asset
pipline fingerprinted. sorry, best way to make it work!
*/
jQuery(document).ready(function($) {
$(".collapse-toggle").live("click", function(event) {
$(this).collapse('toggle');
event.preventDefault();
return false;
});
$(".collapse").live("shown", function(event) {
// Update the icon
$(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-closed").addClass("umlaut_icons-list-open");
// Update the action label
$(this).parent().find(".expand_contract_action_label").text("Hide ");
});
$(".collapse").live("hidden", function(event) {
// Update the icon
$(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-open").addClass("umlaut_icons-list-closed");
// Update the action label
$(this).parent().find(".expand_contract_action_label").text("Show ");
});
}); |
Set image max limit for proto | const $answer = $('.answer')
const {makeRichText} = require('./rich-text-editor')
const save = ($elem, async = true) => $.post({
url: '/save',
data: {text: $elem.html(), answerId: $elem.attr('id')},
async
})
function saveScreenshot(questionId) {
return ({data, type}) => {
return $.post({
type: 'POST',
url: `/saveImg?answerId=${questionId}`,
data: data,
processData: false,
contentType: type
}).then(res => {
return res.url
})
}
}
const richTextOptions = id => ({
screenshot: {
saver: data => saveScreenshot(id)(data),
limit: 10
}
})
$answer.each((i, answer) => {
makeRichText(answer, richTextOptions(answer.id))
$.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html))
}).on('keypress', e => {
if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') {
e.preventDefault()
save($(e.target))
}
})
$('#answer1').focus()
| const $answer = $('.answer')
const {makeRichText} = require('./rich-text-editor')
const save = ($elem, async = true) => $.post({
url: '/save',
data: {text: $elem.html(), answerId: $elem.attr('id')},
async
})
function saveScreenshot(questionId) {
return ({data, type}) => {
return $.post({
type: 'POST',
url: `/saveImg?answerId=${questionId}`,
data: data,
processData: false,
contentType: type
}).then(res => {
return res.url
})
}
}
const richTextOptions = id => ({
screenshot: {
saver: data => saveScreenshot(id)(data)
}
})
$answer.each((i, answer) => {
makeRichText(answer, richTextOptions(answer.id))
$.get(`/load?answerId=${answer.id}`, data => data && $(answer).html(data.html))
}).on('keypress', e => {
if (e.ctrlKey && !e.altKey && !e.shiftKey && e.key === 's') {
e.preventDefault()
save($(e.target))
}
})
$('#answer1').focus()
|
Use spaces instead of tabs | from terroroftinytown.services.base import BaseService
from terroroftinytown.services.status import URLStatus
import re
class GooglService(BaseService):
def process_response(self, response):
status_code = response.status_code
if status_code in self.params['redirect_codes']:
if self.ratelimited(response):
return self.process_banned(response)
return self.process_redirect(response)
elif status_code in self.params['no_redirect_codes']:
return self.process_no_redirect(response)
elif status_code in self.params['unavailable_codes']:
return self.process_unavailable(response)
elif status_code in self.params['banned_codes']:
return self.process_banned(response)
else:
return self.process_unknown_code(response)
def ratelimited(self, response):
if 'Location' not in response.headers:
return False
result_url = response.headers['Location']
response.content # read the response to allow connection reuse
return not not re.search('^https?://(?:www\.)?google\.com/sorry', result_url)
|
from terroroftinytown.services.base import BaseService
from terroroftinytown.services.status import URLStatus
import re
class GooglService(BaseService):
def process_response(self, response):
status_code = response.status_code
if status_code in self.params['redirect_codes']:
if self.ratelimited(response):
return self.process_banned(response)
return self.process_redirect(response)
elif status_code in self.params['no_redirect_codes']:
return self.process_no_redirect(response)
elif status_code in self.params['unavailable_codes']:
return self.process_unavailable(response)
elif status_code in self.params['banned_codes']:
return self.process_banned(response)
else:
return self.process_unknown_code(response)
def ratelimited(self, response):
if 'Location' not in response.headers:
return False
result_url = response.headers['Location']
response.content # read the response to allow connection reuse
return not not re.search('^https?://(?:www\.)?google\.com/sorry', result_url)
|
Move to user (move to seperate file later) | import API from '../api';
/** Action Creators */
const setDrivers = drivers => {
return {
type: "SET_DRIVERS",
drivers
}
}
export const showModal = driver => {
return {
type: "SHOW_DRIVER_MODAL",
driver
}
}
export const hideModal = () => {
return {
type: "CLEAR_DRIVER_MODAL",
}
}
/** Async Actions */
export const getDrivers = () => {
return dispatch => {
return API.get(`/users/drivers`)
.then(drivers => dispatch(setDrivers(drivers)));
}
}
export const getUsers = () => {
return dispatch => {
return API.get("/users/all")
.then(users => dispatch(setDrivers(users)))
}
}
export const submitUser = driver => {
return dispatch => {
// set the defaults
let url = "/users"
let request = API.post
// check if it is an update (we have an id)
if (driver.id) {
url += `/${driver.id}`;
request = API.patch;
}
// Push it up to the server
return request(url, {user: driver})
.then(result => dispatch(getUsers()))
}
}
export const deleteUser = (id) => {
return dispatch => {
API.delete(`/users/${id}`)
.catch(() => dispatch(getUsers())) // no content throws error since json is invalid
}
} | import API from '../api';
/** Action Creators */
const setDrivers = drivers => {
return {
type: "SET_DRIVERS",
drivers
}
}
export const showModal = driver => {
return {
type: "SHOW_DRIVER_MODAL",
driver
}
}
export const hideModal = () => {
return {
type: "CLEAR_DRIVER_MODAL",
}
}
/** Async Actions */
export const getDrivers = () => {
return dispatch => {
return API.get(`/users/drivers`)
.then(drivers => dispatch(setDrivers(drivers)));
}
}
export const submitDriver = driver => {
return dispatch => {
// set the defaults
let url = "/users"
let request = API.post
// check if it is an update (we have an id)
if (driver.id) {
url += `/${driver.id}`;
request = API.patch;
}
// Push it up to the server
return request(url, driver)
.then(result => dispatch(getDrivers()))
}
}
export const deleteDriver = (id) => {
return dispatch => {
API.delete(`/users/${id}`)
.catch(() => dispatch(getDrivers())) // no content throws error since json is invalid
}
} |
Use array instead of PHP 5.4. [] syntax | <?php
/**
* Class VersionedReadingMode
*/
class VersionedReadingMode
{
/**
* @var String
*/
private static $originalReadingMode;
/**
* Set the reading mode to 'Stage' so that all data objects are displayed for lists whether or not they have
* been published
*/
public static function setStageReadingMode()
{
self::$originalReadingMode = Versioned::current_stage();
Versioned::reading_stage('Stage');
}
/**
* Set the reading mode to 'Live'
*/
public static function setLiveReadingMode()
{
self::$originalReadingMode = Versioned::current_stage();
Versioned::reading_stage('Live');
}
/**
* Restore the reading mode to what's been set originally in the CMS
*/
public static function restoreOriginalReadingMode()
{
if (
isset(self::$originalReadingMode) &&
in_array(self::$originalReadingMode, array('Stage', 'Live'))
) {
Versioned::reading_stage(self::$originalReadingMode);
}
}
}
| <?php
/**
* Class VersionedReadingMode
*/
class VersionedReadingMode
{
/**
* @var String
*/
private static $originalReadingMode;
/**
* Set the reading mode to 'Stage' so that all data objects are displayed for lists whether or not they have
* been published
*/
public static function setStageReadingMode()
{
self::$originalReadingMode = Versioned::current_stage();
Versioned::reading_stage('Stage');
}
/**
* Set the reading mode to 'Live'
*/
public static function setLiveReadingMode()
{
self::$originalReadingMode = Versioned::current_stage();
Versioned::reading_stage('Live');
}
/**
* Restore the reading mode to what's been set originally in the CMS
*/
public static function restoreOriginalReadingMode()
{
if (isset(self::$originalReadingMode) && in_array(self::$originalReadingMode, ['Stage', 'Live'])) {
Versioned::reading_stage(self::$originalReadingMode);
}
}
}
|
Fix broken test.. was testing the old way of validation of the reconsent command.
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@1321 0d517254-b314-0410-acde-c619094fa49f | package edu.northwestern.bioinformatics.studycalendar.web.schedule;
import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import gov.nih.nci.cabig.ctms.lang.NowFactory;
import static org.easymock.EasyMock.expect;
import org.springframework.validation.Errors;
import org.springframework.validation.BindException;
import java.util.Calendar;
public class ScheduleReconsentCommandTest extends StudyCalendarTestCase {
private ScheduleReconsentCommand command;
private StudyService studyService;
private NowFactory nowFactory;
protected void setUp() throws Exception {
super.setUp();
studyService = registerMockFor(StudyService.class);
nowFactory = registerMockFor(NowFactory.class);
command = new ScheduleReconsentCommand(studyService, nowFactory);
}
public void testValidate() throws Exception {
BindException errors = new BindException(command, "startDate");
command.setStartDate(DateTools.createTimestamp(2005, Calendar.AUGUST, 3));
expect(nowFactory.getNow()).andReturn(DateTools.createDate(2007, Calendar.AUGUST, 3));
replayMocks();
command.validate(errors);
verifyMocks();
assertEquals("There should be one error: ", 1, errors.getAllErrors().size());
}
}
| package edu.northwestern.bioinformatics.studycalendar.web.schedule;
import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import gov.nih.nci.cabig.ctms.lang.NowFactory;
import static org.easymock.EasyMock.expect;
import java.util.Calendar;
public class ScheduleReconsentCommandTest extends StudyCalendarTestCase {
private ScheduleReconsentCommand command;
private StudyService studyService;
private NowFactory nowFactory;
protected void setUp() throws Exception {
super.setUp();
studyService = registerMockFor(StudyService.class);
nowFactory = registerMockFor(NowFactory.class);
command = new ScheduleReconsentCommand(studyService, nowFactory);
}
public void testValidate() throws Exception {
command.setStartDate(DateTools.createTimestamp(2005, Calendar.AUGUST, 3));
expect(nowFactory.getNow()).andReturn(DateTools.createDate(2007, Calendar.AUGUST, 3)).times(2);
replayMocks();
command.validate(null);
verifyMocks();
assertSameDay("Expected Date different than actual", DateTools.createDate(2007, Calendar.AUGUST, 3), command.getStartDate());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.