text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Improve example, start pystray in main thread and webview in new process
|
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
import multiprocessing
if sys.platform == 'darwin':
ctx = multiprocessing.get_context('spawn')
Process = ctx.Process
Queue = ctx.Queue
else:
Process = multiprocessing.Process
Queue = multiprocessing.Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
webview_process = None
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
if __name__ == '__main__':
def start_webview_process():
global webview_process
webview_process = Process(target=run_webview)
webview_process.start()
def on_open(icon, item):
global webview_process
if not webview_process.is_alive():
start_webview_process()
def on_exit(icon, item):
icon.stop()
start_webview_process()
image = Image.open('logo/logo.png')
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon('Pystray', image, menu=menu)
icon.run()
webview_process.terminate()
|
from PIL import Image
from pystray import Icon, Menu, MenuItem
import webview
import sys
if sys.platform == 'darwin':
raise NotImplementedError('This example does not work on macOS.')
from threading import Thread
from queue import Queue
"""
This example demonstrates running pywebview alongside with pystray to display a system tray icon.
"""
def run_webview():
window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello')
webview.start()
def run_pystray(queue: Queue):
def on_open(icon, item):
queue.put('open')
def on_exit(icon, item):
icon.stop()
queue.put('exit')
image = Image.open('logo/logo.png')
menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit))
icon = Icon('Pystray', image, "Pystray", menu)
icon.run()
if __name__ == '__main__':
queue = Queue()
icon_thread = Thread(target=run_pystray, args=(queue,))
icon_thread.start()
run_webview()
while True:
event = queue.get()
if event == 'open':
run_webview()
if event == 'exit':
break
icon_thread.join()
|
Fix out of date path in a test case.
|
var fs = require("fs");
var path = require("path");
var utils = require("../utils");
var chai = require("chai");
var expect = chai.expect;
var exec = utils.exec;
var simpleAddonPath = path.join(__dirname, "..", "addons", "simple-addon");
describe("jpm xpi", function () {
beforeEach(utils.setup);
afterEach(utils.tearDown);
it("creates a xpi of the cwd", function (done) {
process.chdir(simpleAddonPath);
var proc = exec("xpi", { cwd: simpleAddonPath });
proc.on("close", function () {
var xpiPath = path.join(simpleAddonPath, "@simple-addon.xpi");
utils.unzipTo(xpiPath, utils.tmpOutputDir, function () {
utils.compareDirs(simpleAddonPath, utils.tmpOutputDir, done);
});
});
});
});
|
var fs = require("fs");
var path = require("path");
var utils = require("../utils");
var chai = require("chai");
var expect = chai.expect;
var exec = utils.exec;
var simpleAddonPath = path.join(__dirname, "..", "addons", "simple-addon");
describe("jpm xpi", function () {
beforeEach(utils.setup);
afterEach(utils.tearDown);
it("creates a xpi of the cwd", function (done) {
process.chdir(simpleAddonPath);
var proc = exec("xpi", { cwd: simpleAddonPath });
proc.on("close", function () {
var xpiPath = path.join(simpleAddonPath, "simple-addon@jetpack.xpi");
utils.unzipTo(xpiPath, utils.tmpOutputDir, function () {
utils.compareDirs(simpleAddonPath, utils.tmpOutputDir, done);
});
});
});
});
|
Fix video URL from PlaylistItem
|
const duration = require('iso8601-duration');
class Video {
constructor(youtube, data) {
this.youtube = youtube;
this.title = data.snippet.title;
this.id = data.id.videoId ? data.id.videoId : data.id;
this.description = data.snippet.description;
this.publishedAt = data.snippet.publishedAt;
this.channel = {
title: data.snippet.channelTitle,
id: data.snippet.channelId
};
if(data.contentDetails) {
this.id = data.contentDetails.videoId || this.id;
this.duration = data.contentDetails.duration ? duration.parse(data.contentDetails.duration) : null;
this.duration_seconds = this.duration ? duration.toSeconds(this.duration) : -1;
}
this.url = `https://www.youtube.com/watch?v=${this.id}`;
}
}
module.exports = Video;
|
const duration = require('iso8601-duration');
class Video {
constructor(youtube, data) {
this.youtube = youtube;
this.title = data.snippet.title;
this.id = data.id.videoId ? data.id.videoId : data.id;
this.description = data.snippet.description;
this.url = `https://www.youtube.com/watch?v=${this.id}`;
this.publishedAt = data.snippet.publishedAt;
this.channel = {
title: data.snippet.channelTitle,
id: data.snippet.channelId
};
if(data.contentDetails) {
this.id = data.contentDetails.videoId || this.id;
this.duration = data.contentDetails.duration ? duration.parse(data.contentDetails.duration) : null;
this.duration_seconds = this.duration ? duration.toSeconds(this.duration) : -1;
}
}
}
module.exports = Video;
|
Fix tests for correct environment config
|
/*global $, assert, trigger*/
'use strict';
describe('Albums create dialog', function () {
this.timeout(20000);
it('should create new album', function (done) {
var user;
TEST.browser
// Authorize
.auth('users_album_create', function (usr) {
user = usr;
})
// Navigate to albums page
.goto(function () {
return TEST.N.router.linkTo('users.albums_root', { user_hid: user.hid });
})
.evaluateAsync(function (done) {
TEST.N.wire.once('users.album.create:shown', { priority: 999 }, function () {
$('input[name="album_name"]').val('new test album!');
$('.modal-dialog button[type="submit"]').click();
});
trigger('[data-on-click="users.albums_root.create_album"]', function () {
assert.equal($('.user-albumlist li:last .thumb-caption__line:first').text(), 'new test album!');
done();
});
})
// Run test
.run(done);
});
});
|
/*global $, assert, trigger*/
'use strict';
describe('Albums create dialog', function () {
this.timeout(20000);
it('should create new album', function (done) {
var user;
TEST.browser
// Authorize
.auth('users_album_create', function (usr) {
user = usr;
})
// Navigate to albums page
.goto(function () {
return 'http://localhost:3000' + TEST.N.router.linkTo('users.albums_root', { user_hid: user.hid });
})
.evaluateAsync(function (done) {
TEST.N.wire.once('users.album.create:shown', { priority: 999 }, function () {
$('input[name="album_name"]').val('new test album!');
$('.modal-dialog button[type="submit"]').click();
});
trigger('[data-on-click="users.albums_root.create_album"]', function () {
assert.equal($('.user-albumlist li:last .thumb-caption__line:first').text(), 'new test album!');
done();
});
})
// Run test
.run(done);
});
});
|
Fix avatar url encoding (whitespace was encoded with + rather than %20)
|
package com.faforever.api.data.listeners;
import com.faforever.api.config.FafApiProperties;
import com.faforever.api.data.domain.Avatar;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriUtils;
import javax.inject.Inject;
import javax.persistence.PostLoad;
import java.nio.charset.StandardCharsets;
@Component
public class AvatarEnricherListener {
private static FafApiProperties fafApiProperties;
@Inject
public void init(FafApiProperties fafApiProperties) {
AvatarEnricherListener.fafApiProperties = fafApiProperties;
}
@PostLoad
public void enrich(Avatar avatar) {
String url = String.format(fafApiProperties.getAvatar().getDownloadUrlFormat(), avatar.getFilename());
avatar.setUrl(UriUtils.encodePath(url, StandardCharsets.UTF_8));
}
}
|
package com.faforever.api.data.listeners;
import com.faforever.api.config.FafApiProperties;
import com.faforever.api.data.domain.Avatar;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import javax.persistence.PostLoad;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@Component
public class AvatarEnricherListener {
private static FafApiProperties fafApiProperties;
@Inject
public void init(FafApiProperties fafApiProperties) {
AvatarEnricherListener.fafApiProperties = fafApiProperties;
}
@PostLoad
public void enrich(Avatar avatar) throws UnsupportedEncodingException {
String encodedFileName = URLEncoder.encode(avatar.getFilename(), StandardCharsets.UTF_8.toString());
String url = String.format(fafApiProperties.getAvatar().getDownloadUrlFormat(), encodedFileName);
avatar.setUrl(url);
}
}
|
Fix broken RegExp in Travis mentions
|
// PiscoBot Script
var commandDescription = {
name: 'Travis CI Build Fails',
author: 'Daniel Gallegos [@that_taco_guy]',
trigger: '',
version: 1.0,
description: 'Have the bot react to a build failing on Travis CI.',
module: 'Core'
};
global.botHelp.push(commandDescription);
var _ = require('underscore');
global.piscobot.on('bot_message', function(bot, message) {
if(!_.isEmpty(message.attachments)) {
var botMessage = message.attachments[0];
var regex = /Build.*of.*by .* (failed|errored) in/g;
if(!_.isEmpty(botMessage.text) && regex.test(botMessage.text)) {
bot.api.reactions.add({
timestamp: message.ts,
channel: message.channel,
name: 'poop'
}, function(err) {
if(err) {
bot.botkit.log('Failed to add emoji reaction :(', err);
}
});
}
}
});
|
// PiscoBot Script
var commandDescription = {
name: 'Travis CI Build Fails',
author: 'Daniel Gallegos [@that_taco_guy]',
trigger: '',
version: 1.0,
description: 'Have the bot react to a build failing on Travis CI.',
module: 'Core'
};
global.botHelp.push(commandDescription);
var _ = require('underscore');
global.piscobot.on('bot_message', function(bot, message) {
if(!_.isEmpty(message.attachments)) {
var botMessage = message.attachments[0];
var regex = new RegExp(/Build.*of.*by .* (failed|errored) in/, 'g');
if(!_.isEmpty(botMessage.text) && regex.test(botMessage.text)) {
bot.api.reactions.add({
timestamp: message.ts,
channel: message.channel,
name: 'poop'
}, function(err) {
if(err) {
bot.botkit.log('Failed to add emoji reaction :(', err);
}
});
}
}
});
|
Clean up udevd zombie process
|
package control
import (
"os"
"os/exec"
"github.com/rancher/os/pkg/log"
"github.com/codegangsta/cli"
)
func udevSettleAction(c *cli.Context) {
if err := UdevSettle(); err != nil {
log.Fatal(err)
}
}
func UdevSettle() error {
cmd := exec.Command("udevd", "--daemon")
defer exec.Command("killall", "udevd").Run()
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
cmd = exec.Command("udevadm", "trigger", "--action=add")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
cmd = exec.Command("udevadm", "settle")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
|
package control
import (
"os"
"os/exec"
"github.com/rancher/os/pkg/log"
"github.com/codegangsta/cli"
)
func udevSettleAction(c *cli.Context) {
if err := UdevSettle(); err != nil {
log.Fatal(err)
}
}
func UdevSettle() error {
cmd := exec.Command("udevd", "--daemon")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
cmd = exec.Command("udevadm", "trigger", "--action=add")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
cmd = exec.Command("udevadm", "settle")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
|
Use io.open with encoding='utf-8' and flake8 compliance
|
import io
from setuptools import setup, find_packages
long_description = '\n'.join((
io.open('README.rst', encoding='utf-8').read(),
io.open('CHANGES.txt', encoding='utf-8').read()
))
tests_require = [
'pytest >= 2.0',
'pytest-cov',
'WebTest >= 2.0.14',
'mock',
]
setup(
name='bowerstatic',
version='0.10.dev0',
description="A Bower-centric static file server for WSGI",
long_description=long_description,
author="Martijn Faassen",
author_email="faassen@startifact.com",
license="BSD",
url='http://bowerstatic.readthedocs.org',
keywords='wsgi bower',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'WebOb',
],
tests_require=tests_require,
extras_require=dict(
test=tests_require,
)
)
|
from setuptools import setup, find_packages
long_description = (
open('README.rst').read()
+ '\n' +
open('CHANGES.txt').read())
tests_require = [
'pytest >= 2.0',
'pytest-cov',
'WebTest >= 2.0.14',
'mock',
]
setup(
name='bowerstatic',
version='0.10.dev0',
description="A Bower-centric static file server for WSGI",
long_description=long_description,
author="Martijn Faassen",
author_email="faassen@startifact.com",
license="BSD",
url='http://bowerstatic.readthedocs.org',
keywords='wsgi bower',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'WebOb',
],
tests_require=tests_require,
extras_require=dict(
test=tests_require,
)
)
|
Revert "Change calculateReserves minimum value to zero"
This reverts commit d84468b7631cf9c08d1f9d185f59f36c79d16d68.
|
import {
fromPairs,
head,
last,
max,
mapObjIndexed,
sortBy,
toPairs,
} from 'ramda'
export function calculateReserves (cumulative, reserveData, mineral, column, series) {
const reserves = getReserves(reserveData, mineral)
if (!reserves) {
// console.debug('No reserves!')
return {}
}
const [reserveYear, reserveAmount] = last(sortBy(head, toPairs(reserves)))
const cumulativeOnReserveYear = cumulative.data[reserveYear][column]
return mapObjIndexed((row, year) => {
return fromPairs([
['Year', year],
[series, max(1, reserveAmount - (row[column] - cumulativeOnReserveYear))]
])
}, cumulative.data)
}
export function getReserves (reserves, mineral) {
return reserves.data && reserves.data[mineral]
}
|
import {
fromPairs,
head,
last,
max,
mapObjIndexed,
sortBy,
toPairs,
} from 'ramda'
export function calculateReserves (cumulative, reserveData, mineral, column, series) {
const reserves = getReserves(reserveData, mineral)
if (!reserves) {
// console.debug('No reserves!')
return {}
}
const [reserveYear, reserveAmount] = last(sortBy(head, toPairs(reserves)))
const cumulativeOnReserveYear = cumulative.data[reserveYear][column]
return mapObjIndexed((row, year) => {
return fromPairs([
['Year', year],
[series, max(0, reserveAmount - (row[column] - cumulativeOnReserveYear))]
])
}, cumulative.data)
}
export function getReserves (reserves, mineral) {
return reserves.data && reserves.data[mineral]
}
|
Fix deploy button for second player
|
"use strict";
var _ = require('mori');
var Router = require('react-router');
var React = require('react');
var mori = require("mori");
var UnitCell = require('../board/UnitCell.react.js');
var GameStore = require('../../stores/GameStore.js');
var ProfileLink = require('../common/ProfileLink.react.js');
var GameActions = require('../../actions/GameActions.js');
module.exports = React.createClass({
render: function () {
var game = this.props.game;
var stash = _.getIn(game, ["board", "stash", this.props.playerCode]);
var originalGame = this.props.originalGame;
var state = _.getIn(originalGame, ["board", "state"]);
var originalStash = _.getIn(originalGame, ["board", "stash", this.props.playerCode]);
console.log(state)
var css = "btn btn-info";
if("deploy" === state) {
if(_.isEmpty(originalStash)) {
css = "hide";
} else if(!_.isEmpty(stash)) {
css = "btn btn-default disabled";
}
} else {
css = "hide";
}
return (
<a onClick={this.click} className={css}>Deploy</a>
);
},
click: function click(ev) {
GameActions.deployGame(this.props.game);
}
});
|
"use strict";
var _ = require('mori');
var Router = require('react-router');
var React = require('react');
var mori = require("mori");
var UnitCell = require('../board/UnitCell.react.js');
var GameStore = require('../../stores/GameStore.js');
var ProfileLink = require('../common/ProfileLink.react.js');
var GameActions = require('../../actions/GameActions.js');
module.exports = React.createClass({
render: function () {
var game = this.props.game;
var state = _.getIn(game, ["board", "state"]);
var stash = _.getIn(game, ["board", "stash", this.props.playerCode]);
var originalStash = _.getIn(this.props.originalGame, ["board", "stash", this.props.playerCode]);
var css = "btn btn-info";
if("deploy" === state) {
if(_.isEmpty(originalStash)) {
css = "hide";
} else if(!_.isEmpty(stash)) {
css = "btn btn-default disabled";
}
} else {
css = "hide";
}
return (
<a onClick={this.click} className={css}>Deploy</a>
);
},
click: function click(ev) {
GameActions.deployGame(this.props.game);
}
});
|
Add test case for 404 on docs pages
|
import os
from django.test import Client, TestCase
from django.core.urlresolvers import reverse
from django.core.management import call_command
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.index))
self.assertEqual(response.status_code, 200)
def test_doc_pages(self):
names = os.listdir("docs/other")
pages = [x.replace("_plain", "").replace(".md", "") for x in names]
pages += ["technical"]
for page in pages:
response = self.client.get(reverse(views.docs_pages, args=(page, )))
self.assertEqual(response.status_code, 200)
def test_doc_pages_404(self):
response = self.client.get(reverse(views.docs_pages, args=("notarealpage", )))
self.assertEqual(response.status_code, 404)
def test_make_docs(self):
call_command("make_docs")
|
import os
from django.test import Client, TestCase
from django.core.urlresolvers import reverse
from django.core.management import call_command
import views
class DocsTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_index(self):
response = self.client.get(reverse(views.index))
self.assertEqual(response.status_code, 200)
def test_doc_pages(self):
names = os.listdir("docs/other")
pages = [x.replace("_plain", "").replace(".md", "") for x in names]
pages += ["technical"]
for page in pages:
response = self.client.get(reverse(views.docs_pages, args=(page, )))
self.assertEqual(response.status_code, 200)
def test_make_docs(self):
call_command("make_docs")
|
Rewrite lib error with ES6
|
exports default {
'lrc_notfound': '抱歉, 没找到歌词',
'account_missing': '请先设置豆瓣账户再操作: $ douban.fm config',
'setup_fail': '啊哦,启动出错了,请检查配置文件 ~/.douban.fm.profile.json',
'love_fail': '未知曲目无法加心',
'normal': '出错了, 请稍后再试...',
'last_song': '这是最后一首了哦,回车以加载最新列表',
'turn_to_local_mode': '获取豆瓣电台频道出错,切换为本地电台...',
'mkdir_fail': '创建歌曲文件夹出错,请检查权限',
'localsongs_notfound': '没有找到本地音乐'
}
|
module.exports = {
lrc_notfound: '抱歉, 没找到歌词',
account_missing: '请先设置豆瓣账户再操作: $ douban.fm config',
setup_fail: '啊哦,启动出错了,请检查配置文件 ~/.douban.fm.profile.json',
love_fail: '未知曲目无法加心',
normal: '出错了, 请稍后再试...',
last_song: '这是最后一首了哦,回车以加载最新列表',
turn_to_local_mode: '获取豆瓣电台频道出错,切换为本地电台...',
mkdir_fail: '创建歌曲文件夹出错,请检查权限',
localsongs_notfound: '没有找到本地音乐'
};
|
Document the fix for FreeBSD.
|
// +build !windows
package runtime
import (
"io/ioutil"
"syscall"
"github.com/codahale/metrics"
)
func getFDLimit() (uint64, error) {
var rlimit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {
return 0, err
}
// rlimit.Cur's type is platform-dependent, so here we widen it as far as Go
// will allow by converting it to a uint64.
return uint64(rlimit.Cur), nil
}
func getFDUsage() (uint64, error) {
fds, err := ioutil.ReadDir("/proc/self/fd")
if err != nil {
return 0, err
}
return uint64(len(fds)), nil
}
func init() {
metrics.Gauge("FileDescriptors.Max").SetFunc(func() int64 {
v, err := getFDLimit()
if err != nil {
return 0
}
return int64(v)
})
metrics.Gauge("FileDescriptors.Used").SetFunc(func() int64 {
v, err := getFDUsage()
if err != nil {
return 0
}
return int64(v)
})
}
|
// +build !windows
package runtime
import (
"io/ioutil"
"syscall"
"github.com/codahale/metrics"
)
func getFDLimit() (uint64, error) {
var rlimit syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlimit); err != nil {
return 0, err
}
return uint64(rlimit.Cur), nil
}
func getFDUsage() (uint64, error) {
fds, err := ioutil.ReadDir("/proc/self/fd")
if err != nil {
return 0, err
}
return uint64(len(fds)), nil
}
func init() {
metrics.Gauge("FileDescriptors.Max").SetFunc(func() int64 {
v, err := getFDLimit()
if err != nil {
return 0
}
return int64(v)
})
metrics.Gauge("FileDescriptors.Used").SetFunc(func() int64 {
v, err := getFDUsage()
if err != nil {
return 0
}
return int64(v)
})
}
|
Improve format of logging output.
|
"""
@copyright: 2013 Single D Software - All Rights Reserved
@summary: Debugging console interface for Light Maestro.
"""
# Standard library imports
import logging
import threading
import time
# Application imports
import console
# Named logger for this module
_logger = logging.getLogger(__name__)
class LoggingConsole(console.Console):
"""Provide a generic console class that's useful for deubgging."""
def _channellogger(self):
while True:
time.sleep(self._polldelay)
values = (v for c, v in self._channels.items() if int(c) <= self._maxchannels)
valuesstr = ' '.join('{0:5.1f}'.format(v) for v in values)
_logger.info(valuesstr)
def __init__(self, parameter):
params = parameter.split(',')
self._maxchannels = int(params[0])
self._polldelay = 1.0 / float(params[1])
super().__init__()
threading.Thread(target=self._channellogger).start()
|
"""
@copyright: 2013 Single D Software - All Rights Reserved
@summary: Debugging console interface for Light Maestro.
"""
# Standard library imports
import logging
import threading
import time
# Application imports
import console
# Named logger for this module
_logger = logging.getLogger(__name__)
class LoggingConsole(console.Console):
"""Provide a generic console class that's useful for deubgging."""
def _channellogger(self):
while True:
time.sleep(self._polldelay)
values = (int(v) for c, v in self._channels.items() if int(c) <= self._maxchannels)
valuesstr = ' '.join('{0:03}'.format(v) for v in values)
_logger.info(valuesstr)
def __init__(self, parameter):
params = parameter.split(',')
self._maxchannels = int(params[0])
self._polldelay = 1.0 / float(params[1])
super().__init__()
threading.Thread(target=self._channellogger).start()
|
Configure an explicit timeout for Mocha
|
exports.config = {
host: 'selenium',
specs: [
'./tests/acceptance/specs/**/*.spec.js'
],
maxInstances: 10,
capabilities: [{
browserName: 'chrome'
}],
sync: true,
logLevel: 'error',
coloredLogs: true,
bail: 0,
screenshotPath: './tests/acceptance/results/',
baseUrl: 'http://app:3000',
waitforTimeout: 10 * 1000,
connectionRetryTimeout: 90 * 1000,
connectionRetryCount: 3,
framework: 'mocha',
mochaOpts: {
ui: 'bdd',
timeout: 10 * 1000
},
reporters: ['dot'],
beforeTest: function resetApp() {
browser.url('http://app:3000')
.waitForVisible('.todoapp', 5 * 1000);
}
};
// Enable ES6.
// https://github.com/webdriverio/webdriverio/issues/600#issuecomment-126233086
require('babel-register');
|
exports.config = {
host: 'selenium',
specs: [
'./tests/acceptance/specs/**/*.spec.js'
],
maxInstances: 10,
capabilities: [{
browserName: 'chrome'
}],
sync: true,
logLevel: 'error',
coloredLogs: true,
bail: 0,
screenshotPath: './tests/acceptance/results/',
baseUrl: 'http://app:3000',
waitforTimeout: 10 * 1000,
connectionRetryTimeout: 90 * 1000,
connectionRetryCount: 3,
framework: 'mocha',
mochaOpts: {
ui: 'bdd'
},
reporters: ['dot'],
beforeTest: function resetApp() {
browser.url('http://app:3000')
.waitForVisible('.todoapp', 5 * 1000);
}
};
// Enable ES6.
// https://github.com/webdriverio/webdriverio/issues/600#issuecomment-126233086
require('babel-register');
|
Remove application extensions from optimized image
|
'use strict';
const execBuffer = require('exec-buffer');
const gifsicle = require('gifsicle');
const isGif = require('is-gif');
module.exports = opts => buf => {
opts = Object.assign({}, opts);
if (!Buffer.isBuffer(buf)) {
return Promise.reject(new TypeError('Expected a buffer'));
}
if (!isGif(buf)) {
return Promise.resolve(buf);
}
const args = ['--no-warnings', '--no-app-extensions'];
if (opts.interlaced) {
args.push('--interlace');
}
if (opts.optimizationLevel) {
args.push(`--optimize=${opts.optimizationLevel}`);
}
if (opts.colors) {
args.push(`--colors=${opts.colors}`);
}
args.push('--output', execBuffer.output, execBuffer.input);
return execBuffer({
input: buf,
bin: gifsicle,
args
}).catch(err => {
err.message = err.stderr || err.message;
throw err;
});
};
|
'use strict';
const execBuffer = require('exec-buffer');
const gifsicle = require('gifsicle');
const isGif = require('is-gif');
module.exports = opts => buf => {
opts = Object.assign({}, opts);
if (!Buffer.isBuffer(buf)) {
return Promise.reject(new TypeError('Expected a buffer'));
}
if (!isGif(buf)) {
return Promise.resolve(buf);
}
const args = ['--no-warnings'];
if (opts.interlaced) {
args.push('--interlace');
}
if (opts.optimizationLevel) {
args.push(`--optimize=${opts.optimizationLevel}`);
}
if (opts.colors) {
args.push(`--colors=${opts.colors}`);
}
args.push('--output', execBuffer.output, execBuffer.input);
return execBuffer({
input: buf,
bin: gifsicle,
args
}).catch(err => {
err.message = err.stderr || err.message;
throw err;
});
};
|
Fix test error with YamlSource
|
<?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
/**
* Loads the specified configuration file and returns its content as an
* array. If the file does not exist or could not be loaded, an empty
* array is returned
*
* @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
* @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
* @return array
* @throws \Neos\Flow\Configuration\Exception\ParseErrorException
*/
public function load($pathAndFilename, $allowSplitSource = false): array
{
if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
return [];
} else {
return parent::load($pathAndFilename, $allowSplitSource);
}
}
}
|
<?php
namespace Neos\Flow\Tests\Functional\Configuration\Fixtures;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
class RootDirectoryIgnoringYamlSource extends \Neos\Flow\Configuration\Source\YamlSource
{
/**
* Loads the specified configuration file and returns its content as an
* array. If the file does not exist or could not be loaded, an empty
* array is returned
*
* @param string $pathAndFilename Full path and filename of the file to load, excluding the file extension (ie. ".yaml")
* @param boolean $allowSplitSource If TRUE, the type will be used as a prefix when looking for configuration files
* @return array
* @throws \Neos\Flow\Configuration\Exception\ParseErrorException
*/
public function load($pathAndFilename, $allowSplitSource = false)
{
if (strpos($pathAndFilename, FLOW_PATH_CONFIGURATION) === 0) {
return [];
} else {
return parent::load($pathAndFilename, $allowSplitSource);
}
}
}
|
Update 0.7.0
- specified try-block to check the status
- changed except block
- allowed .gif format but only up to 3MP (Twitter limitation)
|
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
# check if website is accessible
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
apod_data.raise_for_status()
apod_data = apod_data.json()
# check if image is accessible
image_url = apod_data["url"]
image_data = requests.get(image_url, stream=True)
image_data.raise_for_status()
except requests.HTTPError:
return
with open(os.path.join("APODs", os.path.basename(image_url)), "wb") as imagefile:
for chunk in image_data.iter_content(100000):
imagefile.write(chunk)
# Twitter limitation: .gif must be smaller than 3MB
if image_url.endswith(".gif") and os.path.getsize(os.path.join("APODs", os.path.basename(image_url))) >= 3145728:
return
else:
return os.path.abspath((os.path.join("APODs", os.path.basename(image_url))))
|
import requests
import os
def get_apod():
os.makedirs("APODs", exist_ok=True)
try:
apod_data = requests.get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY").json()
image_url = apod_data["url"]
if image_url.endswith(".gif"):
raise TypeError
image_data = requests.get(image_url, stream=True)
except (requests.HTTPError or TypeError):
return
with open(os.path.join("APODs", os.path.basename(image_url)), "wb") as imagefile:
for chunk in image_data.iter_content(100000):
imagefile.write(chunk)
return os.path.abspath((os.path.join("APODs", os.path.basename(image_url))))
|
Fix video jumping to fullscreen on iPhones
|
import {Video} from '@thiagopnts/kaleidoscope';
import {ContainerPlugin, Mediator, Events} from 'clappr';
export default class Video360 extends ContainerPlugin {
constructor(container) {
super(container);
Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this);
let {height, width, autoplay} = container.options;
container.playback.el.setAttribute('crossorigin', 'anonymous');
container.playback.el.setAttribute('preload', 'metadata');
container.playback.el.setAttribute('playsinline', 'true');
container.el.style.touchAction = "none";
container.el.addEventListener("touchmove", function(event) {
event.preventDefault();
}, false);
this.viewer = new Video({height: isNaN(height) ? 300 : height, width: isNaN(width) ? 400 : width, container: this.container.el, source: this.container.playback.el});
this.viewer.render();
}
get name() {
return 'Video360';
}
updateSize() {
setTimeout(() =>
this.viewer.setSize({height: this.container.$el.height(), width: this.container.$el.width()})
, 250)
}
}
|
import {Video} from '@thiagopnts/kaleidoscope';
import {ContainerPlugin, Mediator, Events} from 'clappr';
export default class Video360 extends ContainerPlugin {
constructor(container) {
super(container);
Mediator.on(`${this.options.playerId}:${Events.PLAYER_RESIZE}`, this.updateSize, this);
let {height, width, autoplay} = container.options;
container.playback.el.setAttribute('crossorigin', 'anonymous');
container.el.style.touchAction = "none";
container.el.addEventListener("touchmove", function(event) {
event.preventDefault();
}, false);
this.viewer = new Video({height: isNaN(height) ? 300 : height, width: isNaN(width) ? 400 : width, container: this.container.el, source: this.container.playback.el});
this.viewer.render();
}
get name() {
return 'Video360';
}
updateSize() {
setTimeout(() =>
this.viewer.setSize({height: this.container.$el.height(), width: this.container.$el.width()})
, 250)
}
}
|
Make bot respond to mentions.
|
#!/usr/bin/python3
import asyncio
import configparser
import discord
import os
import logging
from discord.ext import commands
logging.basicConfig(level=logging.INFO)
# Parse the config and stick in global "config" var
config = configparser.ConfigParser()
for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','bayohwoolph.local.ini','bayohwoolph.ini']:
if os.path.isfile(inifile):
config.read(inifile)
break # First config file wins
MAIN = config['MAIN']
description = '''Dark Echo's barkeep'''
bot = commands.Bot(command_prefix=commands.when_mentioned_or('$'), description=description)
@bot.event
@asyncio.coroutine
def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
bot.run(MAIN.get('login_token'))
|
#!/usr/bin/python3
import asyncio
import configparser
import discord
import os
import logging
from discord.ext import commands
logging.basicConfig(level=logging.INFO)
# Parse the config and stick in global "config" var
config = configparser.ConfigParser()
for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','bayohwoolph.local.ini','bayohwoolph.ini']:
if os.path.isfile(inifile):
config.read(inifile)
break # First config file wins
MAIN = config['MAIN']
description = '''Dark Echo's barkeep'''
bot = commands.Bot(command_prefix='$', description=description)
@bot.event
@asyncio.coroutine
def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
bot.run(MAIN.get('login_token'))
|
Fix queue not showing correct times
|
@section("content")
<div class="container main">
<h1 class="text-center">Queue</h1>
<ul class="list-group col-md-8 col-md-offset-2">
@foreach ($queue as $q)
@if ($q["type"] > 0)
<li class="list-group-item list-group-item-success">
@else
<li class="list-group-item">
@endif
<time datetime="{{{ date(DATE_ISO8601, $q["time"]) }}}">{{{ date("H:i:s", $q["time"]) }}}</time>
<span style="padding-left: 25px">{{{ $q["meta"] }}}</span>
</li>
@endforeach
</ul>
<div class="text-center">
{{ $queue->links() }}
</div>
</div>
@stop
|
@section("content")
<div class="container main">
<h1 class="text-center">Queue</h1>
<ul class="list-group col-md-8 col-md-offset-2">
@foreach ($queue as $q)
@if ($q["type"] > 0)
<li class="list-group-item list-group-item-success">
@else
<li class="list-group-item">
@endif
<span>{{{ date("H:m:i", $q["time"]) }}}</span>
<span style="padding-left: 25px">{{{ $q["meta"] }}}</span>
</li>
@endforeach
</ul>
<div class="text-center">
{{ $queue->links() }}
</div>
</div>
@stop
|
Fix wrong parameter on fail message in init game
|
/* global angular */
import {web3, Chess} from '../../contract/Chess.sol';
angular.module('dappChess').controller('InitializeGameCtrl',
function ($rootScope, $scope) {
$scope.availableAccounts = web3.eth.accounts;
$scope.selectedAccount = web3.eth.defaultAccount;
$scope.startcolor = 'white';
$scope.username = null;
$scope.isSelectedAccount = function (account) {
return $scope.selectedAccount === account;
};
$scope.selectAccount = function (account) {
$scope.selectedAccount = account;
};
function initializeGame() {
$rootScope.$broadcast('message', 'Your game is being created, please wait a moment...',
'loading', 'startgame');
try {
Chess.initGame($scope.username, $scope.startcolor === 'white',
{ from: $scope.selectedAccount });
}
catch(e) {
$rootScope.$broadcast('message', 'Could not initialize the game', 'loading', 'startgame');
}
}
$scope.initializeGame = function (form) {
if(form.$valid) {
initializeGame();
}
};
});
|
/* global angular */
import {web3, Chess} from '../../contract/Chess.sol';
angular.module('dappChess').controller('InitializeGameCtrl',
function ($rootScope, $scope) {
$scope.availableAccounts = web3.eth.accounts;
$scope.selectedAccount = web3.eth.defaultAccount;
$scope.startcolor = 'white';
$scope.username = null;
$scope.isSelectedAccount = function (account) {
return $scope.selectedAccount === account;
};
$scope.selectAccount = function (account) {
$scope.selectedAccount = account;
};
function initializeGame() {
$rootScope.$broadcast('message', 'Your game is being created, please wait a moment...',
'loading', 'startgame');
try {
Chess.initGame($scope.username, $scope.startcolor === 'white',
{ from: $scope.selectedAccount });
}
catch(e) {
$rootScope.$broadcast('message', 'Could not initialize the game', 'loading', 'joingame');
}
}
$scope.initializeGame = function (form) {
if(form.$valid) {
initializeGame();
}
};
});
|
Tweak default sorting once more
Sort all collections by least recent update. These have been waiting
for attention the longest. We initially used least recent response,
but the metadata for that doesn't seem to match what you would
expect.
|
/* Shaka Team Triage Party - Extra JS for Collection View
*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
// This is loaded on collection views in Triage Party. We can inject custom JS
// here.
(() => {
const onLoaded = () => {
// Sort all collections by least recent update.
// These have been waiting for attention the longest.
// NOTE: We initially used least recent response, but the metadata for that
// doesn't seem to match what you would expect.
document.querySelectorAll('.hd.col-update.sorting').forEach(x => x.click());
};
// Wait for the page to finish loading before executing the code above.
if (document.readyState == 'complete') {
onLoaded();
} else {
window.addEventListener('load', onLoaded);
}
})();
|
/* Shaka Team Triage Party - Extra JS for Collection View
*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
// This is loaded on collection views in Triage Party. We can inject custom JS
// here.
(() => {
const onLoaded = () => {
// Sort all collections by least recent response.
// These have been waiting for attention the longest.
document.querySelectorAll('.hd.col-response.sorting').forEach(x => x.click());
};
// Wait for the page to finish loading before executing the code above.
if (document.readyState == 'complete') {
onLoaded();
} else {
window.addEventListener('load', onLoaded);
}
})();
|
Rename to invalidate possible grunt caches
|
module.exports = function(grunt) {
require('wf-grunt').init(grunt, {
options: {
requireConfig: {
paths: {
modernizr: 'bower_components/modernizr/modernizr',
'wf-js-common': './src',
'test': './test'
},
shim: {
modernizr: {
exports: 'Modernizr'
}
}
},
wwwPort: 9200,
coverageThresholds: {
statements: 85,
branches: 75,
functions: 80,
lines: 85
},
}
});
};
|
module.exports = function(grunt) {
require('wf-js-grunt').init(grunt, {
options: {
requireConfig: {
paths: {
modernizr: 'bower_components/modernizr/modernizr',
'wf-js-common': './src',
'test': './test'
},
shim: {
modernizr: {
exports: 'Modernizr'
}
}
},
wwwPort: 9200,
coverageThresholds: {
statements: 85,
branches: 75,
functions: 80,
lines: 85
},
}
});
};
|
Watch task not re-symlinking template indexes
The watch task does that now.
|
'use strict';
(() => {
const debounce = (func, wait, immediate) => {
let timeout;
return () => {
const context = this;
const args = arguments;
const later = () => {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) { func.apply(context, args); }
};
};
module.exports = (gulp, plugins, config) => {
return () => {
gulp.watch(['./rocketbelt/**/*.scss', './templates/scss/**/*.scss'], ['styles']);
gulp.watch(['./templates/**/*.pug'], ['views', 'link-templates']);
gulp.watch(['./rocketbelt/**/*.js'], ['copy-js', 'uglify']);
gulp.watch(config.buildPath + '/**/*.html')
.on('change', plugins.browserSync.reload);
gulp.watch(config.buildPath + '/**/*.js')
.on('change', plugins.browserSync.reload);
global.isWatching = true;
return true;
}
};
})();
|
'use strict';
(() => {
const debounce = (func, wait, immediate) => {
let timeout;
return () => {
const context = this;
const args = arguments;
const later = () => {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) { func.apply(context, args); }
};
};
module.exports = (gulp, plugins, config) => {
return () => {
gulp.watch(['./rocketbelt/**/*.scss', './templates/scss/**/*.scss'], ['styles']);
gulp.watch(['./templates/**/*.pug'], ['views']);
gulp.watch(['./rocketbelt/**/*.js'], ['copy-js', 'uglify']);
gulp.watch(config.buildPath + '/**/*.html')
.on('change', plugins.browserSync.reload);
gulp.watch(config.buildPath + '/**/*.js')
.on('change', plugins.browserSync.reload);
global.isWatching = true;
return true;
}
};
})();
|
Add battery API detection. Lint code.
|
(function() {
'use strict';
function toTime(sec) {
sec = parseInt(sec, 10);
var hours = Math.floor(sec / 3600),
minutes = Math.floor((sec - (hours * 3600)) / 60),
seconds = sec - (hours * 3600) - (minutes * 60);
if (hours < 10) { hours = '0' + hours; }
if (minutes < 10) { minutes = '0' + minutes; }
if (seconds < 10) { seconds = '0' + seconds; }
return hours + ':' + minutes;
}
function readBattery(battery) {
console.log(battery);
console.log(toTime(battery.chargingTime));
console.log(toTime(battery.dischargingTime));
var percentage = parseFloat((battery.level * 100).toFixed(2)) + '%';
document.styleSheets[0].insertRule('.battery:before{width:' + percentage + '}', 0);
}
if (navigator.battery) {
readBattery(navigator.battery);
} else if (navigator.getBattery) {
navigator.getBattery().then(readBattery);
} else {
console.log('Your browser don\'t support Battery API.');
}
}());
|
(function(window) {
'use strict';
function toTime(sec) {
sec = parseInt(sec, 10);
var hours = Math.floor(sec / 3600);
var minutes = Math.floor((sec - (hours * 3600)) / 60);
var seconds = sec - (hours * 3600) - (minutes * 60);
if (hours < 10) { hours = '0' + hours; }
if (minutes < 10) { minutes = '0' + minutes; }
if (seconds < 10) { seconds = '0' + seconds; }
return hours + ':' + minutes;
}
function readBattery(battery) {
console.log(battery);
console.log(toTime(battery.chargingTime));
console.log(toTime(battery.dischargingTime));
var percentage = parseFloat((battery.level * 100).toFixed(2)) + '%';
document.styleSheets[0].insertRule('.battery:before{width:' + percentage + '}', 0);
}
if ('battery' in navigator) {
readBattery(navigator.battery);
} else {
navigator.getBattery().then(readBattery);
}
}(this));
|
Reimplement auto scroll to bottom
|
import React, { Component, PropTypes } from 'react';
import styles from '../chat.scss';
import Message from './message/Message';
export default class ChatArea extends Component {
componentDidMount() {
setTimeout(this.updateScrollTop, 0);
}
componentDidUpdate() {
this.updateScrollTop();
}
getRef = node => {
this.node = node;
this.updateScrollTop();
};
updateScrollTop = () => {
if (!this.node) return;
this.node.scrollTop = this.node.scrollHeight;
};
render() {
const { messages, ...rest } = this.props;
return (
<div ref={this.getRef} className={styles.container}>
{messages.map(message =>
<Message
key={message._id}
message={message}
{...rest}
/>
)}
</div>
);
}
}
ChatArea.propTypes = {
messages: PropTypes.array.isRequired,
user: PropTypes.shape({
id: PropTypes.any
}).isRequired,
showAvatars: PropTypes.bool,
avatarPreviewPosition: PropTypes.string,
updateInputValue: PropTypes.func
};
|
import React, { Component, PropTypes } from 'react';
import styles from '../chat.scss';
import Message from './message/Message';
export default class ChatArea extends Component {
render() {
const { messages, ...rest } = this.props;
return (
<div id="container" className={styles.container}>
{messages.map(message =>
<Message
key={message._id}
message={message}
{...rest}
/>
)}
</div>
);
}
}
ChatArea.propTypes = {
messages: PropTypes.array.isRequired,
user: PropTypes.shape({
id: PropTypes.any
}).isRequired,
showAvatars: PropTypes.bool,
avatarPreviewPosition: PropTypes.string,
updateInputValue: PropTypes.func
};
|
Add action item to TODO.
|
/**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.GENMODEL({
package: 'foam.nanos.client',
name: 'Client',
implements: [ 'foam.box.Context' ],
requires: [
// TODO This is just for the build part. Without it, there's no way of
// knowing that this class uses ClientBuilder so it won't get built by build
// tool without explicitly listing it. Think of a better place for this.
'foam.nanos.client.ClientBuilder',
'foam.box.HTTPBox',
'foam.dao.RequestResponseClientDAO',
'foam.dao.ClientDAO',
'foam.dao.EasyDAO'
],
build: function(X) {
return X.classloader.load('foam.nanos.client.ClientBuilder').then(function(cls) {
return new Promise(function(resolve, reject) {
var b = cls.create(null, X);
b.then(resolve);
});
});
}
});
|
/**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.GENMODEL({
package: 'foam.nanos.client',
name: 'Client',
implements: [ 'foam.box.Context' ],
requires: [
// TODO This is just for the build part. Without it, there's no way of
// knowing that this class uses ClientBuilder so it won't get built by build
// tool without explicitly listing it.
'foam.nanos.client.ClientBuilder',
'foam.box.HTTPBox',
'foam.dao.RequestResponseClientDAO',
'foam.dao.ClientDAO',
'foam.dao.EasyDAO'
],
build: function(X) {
return X.classloader.load('foam.nanos.client.ClientBuilder').then(function(cls) {
return new Promise(function(resolve, reject) {
var b = cls.create(null, X);
b.then(resolve);
});
});
}
});
|
Simplify updating of locale field in user account.
|
// Store the preference locale in cookies and (if available) session to use
// on next requests.
'use strict';
var _ = require('lodash');
var LOCALE_COOKIE_MAX_AGE = 0xFFFFFFFF; // Maximum 32-bit unsigned integer.
module.exports = function (N, apiPath) {
N.validate(apiPath, {
locale: { type: 'string' }
});
N.wire.on(apiPath, function set_language(env, callback) {
var locale = env.params.locale;
if (!_.contains(N.config.locales.enabled, env.params.locale)) {
// User sent a non-existent or disabled locale - reply with the default.
locale = N.config.locales['default'];
}
env.extras.setCookie('locale', locale, {
path: '/'
, maxAge: LOCALE_COOKIE_MAX_AGE
});
if (env.session) {
env.session.locale = locale;
}
if (env.session && env.session.user_id) {
N.models.users.User.findByIdAndUpdate(env.session.user_id, { locale: locale }, callback);
} else {
callback();
}
});
};
|
// Store the preference locale in cookies and (if available) session to use
// on next requests.
'use strict';
var _ = require('lodash');
var LOCALE_COOKIE_MAX_AGE = 0xFFFFFFFF; // Maximum 32-bit unsigned integer.
module.exports = function (N, apiPath) {
N.validate(apiPath, {
locale: { type: 'string' }
});
N.wire.on(apiPath, function set_language(env, callback) {
var locale = env.params.locale;
if (!_.contains(N.config.locales.enabled, env.params.locale)) {
// User sent a non-existent or disabled locale - reply with the default.
locale = N.config.locales['default'];
}
env.extras.setCookie('locale', locale, {
path: '/'
, maxAge: LOCALE_COOKIE_MAX_AGE
});
if (env.session) {
env.session.locale = locale;
}
if (env.session && env.session.user_id) {
N.models.users.User.findById(env.session.user_id, function (err, user) {
if (err) {
callback(err);
return;
}
user.locale = locale;
user.save(callback);
});
} else {
callback();
}
});
};
|
Fix issue where demo text does not autosize textarea.
Closes #8
|
import autosize from "autosize"
const script = String.raw`<script type="text/javascript">
var emojis = "tada, fire, grinning"
var selector = "body"
var url = window.location.href.replace(/(http:\/\/|https:\/\/)/gi, '').replace(/^\/|\/$/g, '');
var iframe = document.createElement("iframe")
iframe.src = "https://emojireact.com/embed?emojis=" + emojis.replace(/\s/g, "") + "&url=" + url
iframe.scrolling = "no"
iframe.frameBorder = "0"
iframe.style = "border:none; overflow:hidden; height:35px;"
var container = document.querySelector(selector)
container.insertBefore(iframe, container.firstChild || container)
</script>`
export default function runDemo(app) {
const {embedCodeInput} = app.refs
embedCodeInput.autofocus = false
embedCodeInput.value = script
autosize.update(embedCodeInput)
app.parseInput()
const {option_2} = app.entities
option_2.title = "Comma separated list of emoji names"
app.toggleEntityTracking(option_2.element)
app.route = "embed-code"
}
|
const script = String.raw`<script type="text/javascript">
var emojis = "tada, fire, grinning"
var selector = "body"
var url = window.location.href.replace(/(http:\/\/|https:\/\/)/gi, '').replace(/^\/|\/$/g, '');
var iframe = document.createElement("iframe")
iframe.src = "https://emojireact.com/embed?emojis=" + emojis.replace(/\s/g, "") + "&url=" + url
iframe.scrolling = "no"
iframe.frameBorder = "0"
iframe.style = "border:none; overflow:hidden; height:35px;"
var container = document.querySelector(selector)
container.insertBefore(iframe, container.firstChild || container)
</script>`
export default function runDemo(app) {
const {embedCodeInput} = app.refs
embedCodeInput.autofocus = false
embedCodeInput.value = script
app.parseInput()
const {option_2} = app.entities
option_2.title = "Comma separated list of emoji names"
app.toggleEntityTracking(option_2.element)
app.route = "embed-code"
}
|
Remove bad use of profiling step
|
module.exports = function authorize (authApi) {
return function authorizeMiddleware (req, res, next) {
authApi.authorize(req, res, (err, authorized) => {
req.profiler.done('authorize');
if (err) {
return next(err);
}
if(!authorized) {
err = new Error("Sorry, you are unauthorized (permission denied)");
err.http_status = 403;
return next(err);
}
return next();
});
};
};
|
module.exports = function authorize (authApi) {
return function authorizeMiddleware (req, res, next) {
req.profiler.done('req2params.setup');
authApi.authorize(req, res, (err, authorized) => {
req.profiler.done('authorize');
if (err) {
return next(err);
}
if(!authorized) {
err = new Error("Sorry, you are unauthorized (permission denied)");
err.http_status = 403;
return next(err);
}
return next();
});
};
};
|
Fix regression on 6269f48ba356c4e7f in cygwin.
signal.SIGBREAK is not defined on cygwin, causing an exception.
R=vadimsh@chromium.org
BUG=
Review URL: https://codereview.chromium.org/1349183005
|
# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Utilities."""
import logging
import os
import signal
import sys
from utils import subprocess42
def exec_python(args):
"""Executes a python process, replacing the current process if possible.
On Windows, it returns the child process code. The caller must exit at the
earliest opportunity.
"""
cmd = [sys.executable] + args
if sys.platform not in ('cygwin', 'win32'):
os.execv(cmd[0], cmd)
return 1
try:
# On Windows, we cannot sanely exec() so shell out the child process
# instead. But we need to forward any signal received that the bot may care
# about. This means processes accumulate, sadly.
# TODO(maruel): If stdin closes, it tells the child process that the parent
# process died.
proc = subprocess42.Popen(cmd, detached=True, stdin=subprocess42.PIPE)
def handler(sig, _):
logging.info('Got signal %s', sig)
# Always send SIGTERM, which is properly translated.
proc.send_signal(signal.SIGTERM)
sig = signal.SIGBREAK if sys.platform == 'win32' else signal.SIGTERM
with subprocess42.set_signal_handler([sig], handler):
proc.wait()
return proc.returncode
except Exception as e:
logging.exception('failed to start: %s', e)
# Swallow the exception.
return 1
|
# Copyright 2015 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
"""Utilities."""
import logging
import os
import signal
import sys
from utils import subprocess42
def exec_python(args):
"""Executes a python process, replacing the current process if possible.
On Windows, it returns the child process code. The caller must exit at the
earliest opportunity.
"""
cmd = [sys.executable] + args
if sys.platform not in ('cygwin', 'win32'):
os.execv(cmd[0], cmd)
return 1
try:
# On Windows, we cannot sanely exec() so shell out the child process
# instead. But we need to forward any signal received that the bot may care
# about. This means processes accumulate, sadly.
# TODO(maruel): If stdin closes, it tells the child process that the parent
# process died.
proc = subprocess42.Popen(cmd, detached=True, stdin=subprocess42.PIPE)
def handler(sig, _):
logging.info('Got signal %s', sig)
# Always send SIGTERM, which is properly translated.
proc.send_signal(signal.SIGTERM)
with subprocess42.set_signal_handler([signal.SIGBREAK], handler):
proc.wait()
return proc.returncode
except Exception as e:
logging.exception('failed to start: %s', e)
# Swallow the exception.
return 1
|
Fix error in getting mouse posititions.
|
import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos()[0], mouse.get_pos()[1]):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen)
|
import pygame
LEFT = 1
class Gui:
def __init__(self):
self.gui_elements = list()
def update(self, mouse, events):
curr_element = None
for element in self.gui_elements:
if element.contains(mouse.get_pos):
curr_element = element
element.on_hover()
if curr_element is not None:
for event in events:
# Check onMouseDown for left mouse button.
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
curr_element.on_mouse_down()
# Check onMouseUp for left mouse button.
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
curr_element.on_mouse_up()
curr_element = None
def add_gui_element(self, gui_element):
self.gui_elements.append(gui_element)
def draw(self, screen):
for element in self.gui_elements:
element.draw(screen)
|
Load all source files in Karma
|
'use strict';
module.exports = function(config) {
config.set({
'basePath': '',
'frameworks': ['jasmine'],
'files': [
'bower_components/jquery/dist/jquery.js',
'bower_components/ScrollToFixed/jquery-scrolltofixed.js',
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'src/*.js',
'test/**/*_test.js'
],
'exclude': [],
'preprocessors': {},
'reporters': ['progress'],
'port': 9876,
'colors': true,
'logLevel': config.LOG_INFO,
'autoWatch': false,
'browsers': ['PhantomJS'],
'singleRun': true,
});
};
|
'use strict';
module.exports = function(config) {
config.set({
'basePath': '',
'frameworks': ['jasmine'],
'files': [
'bower_components/jquery/dist/jquery.js',
'bower_components/ScrollToFixed/jquery-scrolltofixed.js',
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'src/scrollToFixed.js',
'test/**/*_test.js'
],
'exclude': [],
'preprocessors': {},
'reporters': ['progress'],
'port': 9876,
'colors': true,
'logLevel': config.LOG_INFO,
'autoWatch': false,
'browsers': ['PhantomJS'],
'singleRun': true,
});
};
|
Remove createJSModules from Package java file - RN 0.47 compatibility
|
package com.b8ne.RNPusherPushNotifications;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNPusherPushNotificationsPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new RNPusherPushNotificationsModule(reactContext));
}
// Deprecated in RN 0.47
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
package com.b8ne.RNPusherPushNotifications;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNPusherPushNotificationsPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new RNPusherPushNotificationsModule(reactContext));
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
Fix javascript access in spring security
|
package org.example.shelf.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/secure/**", "/users/**").hasRole("USER")
.anyRequest().permitAll()
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("testuser").password("password").roles("USER");
}
}
|
package org.example.shelf.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/secure/**", "/users/**").hasRole("USER")
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("testuser").password("password").roles("USER");
}
}
|
Add auto branch checkout functionality
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from ..utils import DEVNULL, change_working_directory
from .base import DOWNLOAD_CONTAINER
def _checkout(name):
with change_working_directory(DOWNLOAD_CONTAINER):
subprocess.call(
('git', 'checkout', name),
stdout=DEVNULL, stderr=subprocess.STDOUT,
)
def download(source_info):
url = source_info['git']
subprocess.call(
('git', 'clone', url, DOWNLOAD_CONTAINER),
stdout=DEVNULL, stderr=subprocess.STDOUT,
)
if 'tag' in source_info:
_checkout(source_info['tag'])
elif 'branch' in source_info:
_checkout(source_info['branch'])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from ..utils import DEVNULL, change_working_directory
from .base import DOWNLOAD_CONTAINER
def download(source_info):
url = source_info['git']
subprocess.call(
('git', 'clone', url, DOWNLOAD_CONTAINER),
stdout=DEVNULL, stderr=subprocess.STDOUT,
)
if 'tag' in source_info:
with change_working_directory(DOWNLOAD_CONTAINER):
subprocess.call(
('git', 'checkout', source_info['tag']),
stdout=DEVNULL, stderr=subprocess.STDOUT,
)
|
Change time difference assert from > to >= 0
diff == 0 occurs on when executing trivial code in a cell. Updating the
assert to include this.
|
from __future__ import print_function
import time
from IPython.core.magics.execution import _format_time as format_delta
class LineWatcher(object):
"""Class that implements a basic timer.
Notes
-----
* Register the `start` and `stop` methods with the IPython events API.
"""
def __init__(self):
self.start_time = 0.0
def start(self):
self.start_time = time.time()
def stop(self):
stop_time = time.time()
if self.start_time:
diff = stop_time - self.start_time
assert diff >= 0
print('time: {}'.format(format_delta(diff)))
timer = LineWatcher()
def load_ipython_extension(ip):
ip.events.register('pre_run_cell', timer.start)
ip.events.register('post_run_cell', timer.stop)
def unload_ipython_extension(ip):
ip.events.unregister('pre_run_cell', timer.start)
ip.events.unregister('post_run_cell', timer.stop)
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
from __future__ import print_function
import time
from IPython.core.magics.execution import _format_time as format_delta
class LineWatcher(object):
"""Class that implements a basic timer.
Notes
-----
* Register the `start` and `stop` methods with the IPython events API.
"""
def __init__(self):
self.start_time = 0.0
def start(self):
self.start_time = time.time()
def stop(self):
stop_time = time.time()
if self.start_time:
diff = stop_time - self.start_time
assert diff > 0
print('time: {}'.format(format_delta(diff)))
timer = LineWatcher()
def load_ipython_extension(ip):
ip.events.register('pre_run_cell', timer.start)
ip.events.register('post_run_cell', timer.stop)
def unload_ipython_extension(ip):
ip.events.unregister('pre_run_cell', timer.start)
ip.events.unregister('post_run_cell', timer.stop)
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
Set user service to always create a display name if one is not supplied
|
'use strict';
const bcrypt = require('bcrypt-nodejs');
class UsersService {
constructor(options, usersRepository) {
const self = this;
self._options = options;
self.usersRepository = usersRepository;
}
getUserById(id, callback) {
const self = this;
self.usersRepository.findUserById(id, callback);
}
createUser(user, password, callback) {
const self = this;
bcrypt.genSalt(self._options.saltIterations(), function (saltErr, salt) {
if (saltErr) {
return callback(saltErr);
}
bcrypt.hash(password, salt, null, function (hashErr, hashedPassword) {
if (hashErr) {
return callback(hashErr);
}
user.displayName = user.displayName || user.username;
user.password = hashedPassword;
self.usersRepository.saveUser(user, callback);
});
});
}
}
module.exports = UsersService;
|
'use strict';
const bcrypt = require('bcrypt-nodejs');
class UsersService {
constructor(options, usersRepository) {
const self = this;
self._options = options;
self.usersRepository = usersRepository;
}
getUserById(id, callback) {
const self = this;
self.usersRepository.findUserById(id, callback);
}
createUser(user, password, callback) {
const self = this;
bcrypt.genSalt(self._options.saltIterations(), function (saltErr, salt) {
if (saltErr) {
return callback(saltErr);
}
bcrypt.hash(password, salt, null, function (hashErr, hashedPassword) {
if (hashErr) {
return callback(hashErr);
}
user.password = hashedPassword;
self.usersRepository.saveUser(user, callback);
});
});
}
}
module.exports = UsersService;
|
Fix for when using python3.5. Don't install enum34 if enum already exists (python35)
|
import os
from setuptools import setup
readme_path = os.path.join(os.path.dirname(
os.path.abspath(__file__)),
'README.rst',
)
long_description = open(readme_path).read()
version_path = os.path.join(os.path.dirname(
os.path.abspath(__file__)),
'VERSION',
)
version = open(version_path).read()
requires = ['ldap3' ,'Flask', 'Flask-wtf']
try:
import enum
except Exception as e:
requires.append('enum34')
setup(
name='flask-ldap3-login',
version=version,
packages=['flask_ldap3_login'],
author="Nick Whyte",
author_email='nick@nickwhyte.com',
description="LDAP Support for Flask in Python3/2",
long_description=long_description,
url='https://github.com/nickw444/flask-ldap3-login',
zip_safe=False,
install_requires=requires,
classifiers=[
'Intended Audience :: Developers',
'Programming Language :: Python',
'Environment :: Web Environment',
'Framework :: Flask',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 2.6',
],
test_suite="flask_ldap3_login_tests",
)
|
import os
from setuptools import setup
readme_path = os.path.join(os.path.dirname(
os.path.abspath(__file__)),
'README.rst',
)
long_description = open(readme_path).read()
version_path = os.path.join(os.path.dirname(
os.path.abspath(__file__)),
'VERSION',
)
version = open(version_path).read()
setup(
name='flask-ldap3-login',
version=version,
packages=['flask_ldap3_login'],
author="Nick Whyte",
author_email='nick@nickwhyte.com',
description="LDAP Support for Flask in Python3/2",
long_description=long_description,
url='https://github.com/nickw444/flask-ldap3-login',
zip_safe=False,
install_requires=[
"ldap3",
"Flask",
"Flask-wtf",
"enum34"
],
classifiers=[
'Intended Audience :: Developers',
'Programming Language :: Python',
'Environment :: Web Environment',
'Framework :: Flask',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 2.6',
],
test_suite="flask_ldap3_login_tests",
)
|
[trunk] Convert line endings for .h, .c and .cpp files as well as .cs
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def processPath(dirPath, ext):
for dirpath, dirnames, filenames in os.walk(dirPath):
for file in filenames:
if os.path.splitext(file)[1] == ext:
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
processPath('.', '.cs')
processPath('testpackages', '.h')
processPath('testpackages', '.c')
processPath('testpackages', '.cpp')
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
|
Correct imports in loc package.
|
import re
from pypods.datasource import DataSource
from pypods.loc.locchannelhandler import LocChannelHandler
class LocDataSource(DataSource):
def __init__(self):
super(LocDataSource, self).__init__()
self.channels = dict()
def create_channel(self, channel_name):
"""Creates a channel handler for the given name"""
n, v = self.parse_name(channel_name)
# TODO: create and return channelhandler
if n in self.channels.keys():
self.channels[n].set_initial_value(v)
else:
newchan = LocChannelHandler(n)
newchan.set_initial_value(v)
self.channels[n] = newchan
return self.channels[n]
def parse_name(self, name):
# Name should be of format like test31(3)
m = re.match("(.+)\((.+)\)", name)
if m is not None:
return m.groups()
else:
raise Exception("Name format is invalid")
if __name__ == "__main__":
l = LocDataSource()
l.create_channel("test(5)")
|
import re
from pypods.datasource import DataSource
from pypods.loc.locchannelhandler import LocChannelHandler
class LocDataSource(DataSource):
def __init__(self):
super(LocDataSource, self).__init__()
self.channels = dict()
def create_channel(self, channel_name):
"""Creates a channel handler for the given name"""
n, v = self.parse_name(channel_name)
# TODO: create and return channelhandler
if n in self.channels.keys():
self.channels[n].set_initial_value(v)
else:
newchan = LocChannelHandler(n)
newchan.set_initial_value(v)
self.channels[n] = newchan
return self.channels[n]
def parse_name(self, name):
# Name should be of format like test31(3)
m = re.match("(.+)\((.+)\)", name)
if m is not None:
return m.groups()
else:
raise Exception("Name format is invalid")
if __name__ == "__main__":
l = LocDataSource()
l.create_channel("test(5)")
|
Use Stream instead of StringUtils
|
package org.kepennar.aproc.complicatebusiness;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.util.List;
import java.util.stream.Stream;
import javax.inject.Inject;
import org.kepennar.aproc.tasks.Task;
import org.kepennar.aproc.tasks.TaskRepository;
import org.springframework.stereotype.Service;
@Service
public class ComplicateBusinessService {
private final TaskRepository taskRepository;
@Inject
public ComplicateBusinessService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
public List<Task> getAllTransformedTasks() {
return taskRepository.findAll().parallelStream()
.map(t -> {
return new Task(sort(t.getName()), sort(t.getDescription()));
})
.collect(toList());
}
private final static String sort(String word) {
return Stream.of(word.split(""))
.sorted(naturalOrder())
.collect(joining());
}
}
|
package org.kepennar.aproc.complicatebusiness;
import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.util.List;
import java.util.stream.Stream;
import javax.inject.Inject;
import org.kepennar.aproc.tasks.Task;
import org.kepennar.aproc.tasks.TaskRepository;
import org.springframework.stereotype.Service;
@Service
public class ComplicateBusinessService {
private final TaskRepository taskRepository;
@Inject
public ComplicateBusinessService(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
public List<Task> getAllTransformedTasks() {
return taskRepository.findAll().parallelStream()
.map(t -> {
return new Task(sort2(t.getName()), sort2(t.getDescription()));
})
.collect(toList());
}
private final static String sort2(String word) {
return Stream.of(word.split(""))
.sorted(naturalOrder())
.collect(joining());
}
}
|
Use /etc/hosts to find redis
|
import collections
import pickle
import redis
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = 'redis', 6379
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
|
import collections
import pickle
import redis
from .tools import location
class Store(collections.MutableMapping):
def __init__(self, db=0):
host, port = location('redis', 6379)
self._db = redis.StrictRedis(host=host, port=port, db=db)
def __getitem__(self, key):
obj = self._db.get(key)
if obj is None:
raise KeyError('"{}" not found'.format(key))
return pickle.loads(obj)
def __setitem__(self, key, value):
obj = pickle.dumps(value)
self._db.set(key, obj)
def __delitem__(self, key):
self._db.delete(key)
def __iter__(self):
return self._db.scan_iter()
def __len__(self):
return self._db.dbsize()
store = Store()
|
Set depth for Lake Superior
|
#!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 10:42:40 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import Int
class WindDrivenModel(ShallowWaterModel):
"""Class for wind driven model
Set flat initial conditions on Lake Superior
"""
def __init__(self):
self.nx = 151
self.ny = 151
self.Lbump = 0.0
self.Lx = 600e3
self.Ly = 600e3
self.lat = 43 # Latitude of Lake Superior
self.H = 150
super(WindDrivenModel, self).__init__()
def set_mask(self):
n = netcdf_file('superior_mask.grd', 'r')
z = n.variables['z']
self.msk = z.data
def main():
swm = WindDrivenModel()
plot = OceanPlot(swm)
swm.set_plot(plot)
import enaml
with enaml.imports():
from wind_view import WindView
view = WindView(model=swm, plot=plot)
view.show()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 08:44:50 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import Int
class WindDrivenModel(ShallowWaterModel):
"""Class for wind driven model
Set flat initial conditions on Lake Superior
"""
def __init__(self):
self.nx = 151
self.ny = 151
self.Lbump = 0.0
self.Lx = 600e3
self.Ly = 600e3
self.lat = 43 # Latitude of Lake Superior
super(WindDrivenModel, self).__init__()
def set_mask(self):
n = netcdf_file('superior_mask.grd', 'r')
z = n.variables['z']
self.msk = z.data
def main():
swm = WindDrivenModel()
plot = OceanPlot(swm)
swm.set_plot(plot)
import enaml
with enaml.imports():
from wind_view import WindView
view = WindView(model=swm, plot=plot)
view.show()
if __name__ == '__main__':
main()
|
Modify export to allow importing selectively
|
import rms from './extractors/rms';
import energy from './extractors/energy';
import spectralSlope from './extractors/spectralSlope';
import spectralCentroid from './extractors/spectralCentroid';
import spectralRolloff from './extractors/spectralRolloff';
import spectralFlatness from './extractors/spectralFlatness';
import spectralSpread from './extractors/spectralSpread';
import spectralSkewness from './extractors/spectralSkewness';
import spectralKurtosis from './extractors/spectralKurtosis';
import zcr from './extractors/zcr';
import loudness from './extractors/loudness';
import perceptualSpread from './extractors/perceptualSpread';
import perceptualSharpness from './extractors/perceptualSharpness';
import mfcc from './extractors/mfcc';
import powerSpectrum from './extractors/powerSpectrum';
import spectralFlux from './extractors/spectralFlux';
let buffer = function(args) {
return args.signal;
};
let complexSpectrum = function (args) {
return args.complexSpectrum;
};
let amplitudeSpectrum = function (args) {
return args.ampSpectrum;
};
export {
buffer,
rms,
energy,
complexSpectrum,
spectralSlope,
spectralCentroid,
spectralRolloff,
spectralFlatness,
spectralSpread,
spectralSkewness,
spectralKurtosis,
amplitudeSpectrum,
zcr,
loudness,
perceptualSpread,
perceptualSharpness,
powerSpectrum,
mfcc,
spectralFlux
};
|
import rms from './extractors/rms';
import energy from './extractors/energy';
import spectralSlope from './extractors/spectralSlope';
import spectralCentroid from './extractors/spectralCentroid';
import spectralRolloff from './extractors/spectralRolloff';
import spectralFlatness from './extractors/spectralFlatness';
import spectralSpread from './extractors/spectralSpread';
import spectralSkewness from './extractors/spectralSkewness';
import spectralKurtosis from './extractors/spectralKurtosis';
import zcr from './extractors/zcr';
import loudness from './extractors/loudness';
import perceptualSpread from './extractors/perceptualSpread';
import perceptualSharpness from './extractors/perceptualSharpness';
import mfcc from './extractors/mfcc';
import powerSpectrum from './extractors/powerSpectrum';
import spectralFlux from './extractors/spectralFlux';
export default {
buffer: function (args) {
return args.signal;
},
rms,
energy,
complexSpectrum: function (args) {
return args.complexSpectrum;
},
spectralSlope,
spectralCentroid,
spectralRolloff,
spectralFlatness,
spectralSpread,
spectralSkewness,
spectralKurtosis,
amplitudeSpectrum: function (args) {
return args.ampSpectrum;
},
zcr,
loudness,
perceptualSpread,
perceptualSharpness,
powerSpectrum,
mfcc,
spectralFlux,
};
|
Fix test_email_url() after changes to email templating for sharing emails
|
import urlparse
from django.test import TestCase, override_settings
from mock import patch, Mock
from opendebates.context_processors import global_vars
from opendebates.tests.factories import SubmissionFactory
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
mock_request = Mock()
with patch('opendebates.utils.cache') as mock_cache:
mock_cache.get.return_value = 2
context = global_vars(mock_request)
self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
class ThemeTests(TestCase):
def setUp(self):
self.idea = SubmissionFactory()
@override_settings(SITE_THEME={
'EMAIL_SUBJECT': 'THE EMAIL SUBJECT',
'EMAIL_BODY': 'THE EMAIL BODY\nAND SECOND LINE',
})
def test_email_url(self):
email_url = self.idea.email_url()
fields = urlparse.parse_qs(urlparse.urlparse(email_url).query)
self.assertTrue('subject' in fields, fields)
self.assertEqual('THE EMAIL SUBJECT', fields['subject'][0], fields['subject'][0])
self.assertEqual('THE EMAIL BODY\nAND SECOND LINE', fields['body'][0], fields['body'][0])
|
import urlparse
from django.test import TestCase, override_settings
from mock import patch, Mock
from opendebates.context_processors import global_vars
from opendebates.tests.factories import SubmissionFactory
class NumberOfVotesTest(TestCase):
def test_number_of_votes(self):
mock_request = Mock()
with patch('opendebates.utils.cache') as mock_cache:
mock_cache.get.return_value = 2
context = global_vars(mock_request)
self.assertEqual(2, int(context['NUMBER_OF_VOTES']))
class ThemeTests(TestCase):
def setUp(self):
self.idea = SubmissionFactory()
@override_settings(SITE_THEME={'HASHTAG': 'TestHashtag'})
def test_email_url(self):
email_url = self.idea.email_url()
fields = urlparse.parse_qs(urlparse.urlparse(email_url).query)
self.assertTrue('subject' in fields, fields)
self.assertTrue('#TestHashtag' in fields['subject'][0], fields['subject'][0])
|
[LIB-464] Remove Raw import from Admin model
|
import stampit from 'stampit';
import {Meta, Model} from './base';
import {BaseQuerySet, Get, List, First, PageSize} from '../querySet';
const AdminQuerySet = stampit().compose(
BaseQuerySet,
Get,
List,
First,
PageSize
);
const AdminMeta = Meta({
name: 'admin',
pluralName: 'admins',
endpoints: {
'detail': {
'methods': ['delete', 'patch', 'put', 'get'],
'path': '/v1/instances/{instanceName}/admins/{id}/'
},
'list': {
'methods': ['get'],
'path': '/v1/instances/{instanceName}/admins/'
}
}
});
const Admin = stampit()
.compose(Model)
.setQuerySet(AdminQuerySet)
.setMeta(AdminMeta);
export default Admin;
|
import stampit from 'stampit';
import {Meta, Model} from './base';
import {BaseQuerySet, Get, List, First, PageSize, Raw} from '../querySet';
const AdminQuerySet = stampit().compose(
BaseQuerySet,
Get,
List,
First,
PageSize
);
const AdminMeta = Meta({
name: 'admin',
pluralName: 'admins',
endpoints: {
'detail': {
'methods': ['delete', 'patch', 'put', 'get'],
'path': '/v1/instances/{instanceName}/admins/{id}/'
},
'list': {
'methods': ['get'],
'path': '/v1/instances/{instanceName}/admins/'
}
}
});
const Admin = stampit()
.compose(Model)
.setQuerySet(AdminQuerySet)
.setMeta(AdminMeta);
export default Admin;
|
Remove slash already present in APP_URL
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'steam' => [
'client_id' => null,
'client_secret' => null,
'redirect' => env('APP_URL').'auth/steam/callback',
'api_key' => env('STEAM_API_KEY'),
],
];
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'steam' => [
'client_id' => null,
'client_secret' => null,
'redirect' => env('APP_URL').'/auth/steam/callback',
'api_key' => env('STEAM_API_KEY'),
],
];
|
Clean command - tool help fix
|
# Copyright 2014-2015 0xc0170
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import logging
from ..generate import Generator
help = 'Clean generated projects'
def run(args):
if os.path.exists(args.file):
generator = Generator(args.file)
for project in generator.generate(args.project):
project.clean(args.tool)
else:
# not project known by progen
logging.warning("%s not found." % args.file)
return -1
return 0
def setup(subparser):
subparser.add_argument("-f", "--file", help="YAML projects file", default='projects.yaml')
subparser.add_argument("-p", "--project", required = True, help="Specify which project to be removed")
subparser.add_argument(
"-t", "--tool", help="Clean project files for this tool")
|
# Copyright 2014-2015 0xc0170
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import logging
from ..generate import Generator
help = 'Clean generated projects'
def run(args):
if os.path.exists(args.file):
generator = Generator(args.file)
for project in generator.generate(args.project):
project.clean(args.tool)
else:
# not project known by progen
logging.warning("%s not found." % args.file)
return -1
return 0
def setup(subparser):
subparser.add_argument("-f", "--file", help="YAML projects file", default='projects.yaml')
subparser.add_argument("-p", "--project", required = True, help="Specify which project to be removed")
subparser.add_argument(
"-t", "--tool", help="Clean project files")
|
Add encoding hint (and which python version is required).
|
# -*- coding: UTF-8 -*-
# REQUIRES: Python >= 3.5
from behave import given, then, step
from behave.api.async_step import use_or_create_async_context, AsyncContext
from hamcrest import assert_that, equal_to, empty
import asyncio
@asyncio.coroutine
def async_func(param):
yield from asyncio.sleep(0.2)
return str(param).upper()
@given('I dispatch an async-call with param "{param}"')
def step_dispatch_async_call(context, param):
async_context = use_or_create_async_context(context, "async_context1")
task = async_context.loop.create_task(async_func(param))
async_context.tasks.append(task)
@then('the collected result of the async-calls is "{expected}"')
def step_collected_async_call_result_is(context, expected):
async_context = context.async_context1
done, pending = async_context.loop.run_until_complete(
asyncio.wait(async_context.tasks, loop=async_context.loop))
parts = [task.result() for task in done]
joined_result = ", ".join(sorted(parts))
assert_that(joined_result, equal_to(expected))
assert_that(pending, empty())
|
from behave import given, then, step
from behave.api.async_step import use_or_create_async_context, AsyncContext
from hamcrest import assert_that, equal_to, empty
import asyncio
@asyncio.coroutine
def async_func(param):
yield from asyncio.sleep(0.2)
return str(param).upper()
@given('I dispatch an async-call with param "{param}"')
def step_dispatch_async_call(context, param):
async_context = use_or_create_async_context(context, "async_context1")
task = async_context.loop.create_task(async_func(param))
async_context.tasks.append(task)
@then('the collected result of the async-calls is "{expected}"')
def step_collected_async_call_result_is(context, expected):
async_context = context.async_context1
done, pending = async_context.loop.run_until_complete(
asyncio.wait(async_context.tasks, loop=async_context.loop))
parts = [task.result() for task in done]
joined_result = ", ".join(sorted(parts))
assert_that(joined_result, equal_to(expected))
assert_that(pending, empty())
|
Break after receiving no bytes to prevent hanging
|
from pymogilefs.response import Response
from pymogilefs.request import Request
import socket
BUFSIZE = 4096
TIMEOUT = 10
class Connection:
def __init__(self, host, port):
self._host = host
self._port = int(port)
def _connect(self):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.connect((self._host, self._port))
self._sock.settimeout(TIMEOUT)
def _recv_all(self):
response_text = b''
while True:
received = self._sock.recv(BUFSIZE)
if received == b'':
break
response_text += received
if response_text[-2:] == b'\r\n':
break
return response_text.decode()
def do_request(self, request):
assert isinstance(request, Request)
self._sock.send(bytes(request))
response_text = self._recv_all()
self._sock.close()
return Response(response_text, request.config)
|
from pymogilefs.response import Response
from pymogilefs.request import Request
import socket
BUFSIZE = 4096
TIMEOUT = 10
class Connection:
def __init__(self, host, port):
self._host = host
self._port = int(port)
def _connect(self):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock.connect((self._host, self._port))
self._sock.settimeout(TIMEOUT)
def _recv_all(self):
response_text = b''
while True:
response_text += self._sock.recv(BUFSIZE)
if response_text[-2:] == b'\r\n':
break
return response_text.decode()
def do_request(self, request):
assert isinstance(request, Request)
self._sock.send(bytes(request))
response_text = self._recv_all()
self._sock.close()
return Response(response_text, request.config)
|
fix(macro): Delete the desks settings for macro
|
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
|
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import re
import requests
USD_TO_CAD = 1.3139 # backup
def get_rate():
"""Get USD to CAD rate."""
try:
r = requests.get('http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=nl1d1', timeout=5)
return float(r.text.split(',')[1])
except Exception:
return USD_TO_CAD
def usd_to_cad(item, **kwargs):
"""Convert USD to CAD."""
rate = get_rate()
if os.environ.get('BEHAVE_TESTING'):
rate = USD_TO_CAD
def convert(match):
usd = float(match.group(1))
cad = rate * usd
return 'CAD %d' % cad
item['body_html'] = re.sub('\$([0-9]+)', convert, item['body_html'])
return item
name = 'usd_to_cad'
label = 'Convert USD to CAD'
shortcut = 'd'
callback = usd_to_cad
desks = ['SPORTS DESK', 'POLITICS']
|
Make App a context manager
This means it can be used either as it is now unchanged or like this:
with libui.App():
... # code
Note that (1) the build instructions for libui appear to be wrong "make" vs "cmake ."; and (2) I can't build libui because of a bug in it or Ubuntu 14.04's cmake I don't know which. So this change is untested.
|
"""
Python wrapper for libui.
"""
from . import libui
class App:
def __init__(self):
"""
Creates a new pylibui app.
"""
options = libui.uiInitOptions()
libui.uiInit(options)
def __enter__(self):
self.start()
def start(self):
"""
Starts the application main loop.
:return: None
"""
libui.uiMain()
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop()
self.close()
def stop(self):
"""
Stops the application main loop.
:return: None
"""
libui.uiQuit()
def close(self):
"""
Closes the application and frees resources.
:return: None
"""
libui.uiUninit()
|
"""
Python wrapper for libui.
"""
from . import libui
class App:
def __init__(self):
"""
Creates a new pylibui app.
"""
options = libui.uiInitOptions()
libui.uiInit(options)
def start(self):
"""
Starts the application main loop.
:return: None
"""
libui.uiMain()
def stop(self):
"""
Stops the application main loop.
:return: None
"""
libui.uiQuit()
def close(self):
"""
Closes the application and frees resources.
:return: None
"""
libui.uiUninit()
|
Make sure HTML entities are converted to the symbols they represent before passing them to the Markdown parser.
|
// From https://gist.github.com/1343518
// Modified by Hakim to handle markdown indented with tabs
(function(){
var slides = document.querySelectorAll('[data-markdown]');
for( var i = 0, len = slides.length; i < len; i++ ) {
var elem = slides[i];
// strip leading whitespace so it isn't evaluated as code
var text = elem.innerHTML;
text = text.replace(/&/, "&").replace(/</, "<").replace(/>/, ">");
var leadingWs = text.match(/^\n?(\s*)/)[1].length,
leadingTabs = text.match(/^\n?(\t*)/)[1].length;
if( leadingTabs > 0 ) {
text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
}
else if( leadingWs > 1 ) {
text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
}
// here, have sum HTML
elem.innerHTML = (new Showdown.converter()).makeHtml(text);
}
})();
|
// From https://gist.github.com/1343518
// Modified by Hakim to handle markdown indented with tabs
(function(){
var slides = document.querySelectorAll('[data-markdown]');
for( var i = 0, len = slides.length; i < len; i++ ) {
var elem = slides[i];
// strip leading whitespace so it isn't evaluated as code
var text = elem.innerHTML;
var leadingWs = text.match(/^\n?(\s*)/)[1].length,
leadingTabs = text.match(/^\n?(\t*)/)[1].length;
if( leadingTabs > 0 ) {
text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
}
else if( leadingWs > 1 ) {
text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
}
// here, have sum HTML
elem.innerHTML = (new Showdown.converter()).makeHtml(text);
}
})();
|
Modify tests to implement the required rules property.
|
<?php
use Mockery as m;
use Samrap\Validation\Validator;
class ValidatorTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
m::close();
}
public function testValidatorPasses()
{
$validator = $this->getValidator();
$rules = ['foo' => 'bar'];
$this->assertEmpty($validator->validate($rules)->errors());
}
public function testValidatorFails()
{
$errors = ['foo' => 'baz'];
$validator = $this->getValidator($errors);
$rules = ['foo' => 'bar'];
$this->assertEquals($errors, $validator->validate($rules)->errors());
}
protected function getValidator($errors = [])
{
$laravelValidator = m::mock('\Illuminate\Validation\Validator');
$laravelValidator->shouldReceive('errors')->andReturn($errors);
$factory = m::mock('Illuminate\Validation\Factory');
$factory->shouldReceive('make')->andReturn($laravelValidator);
$validator = new Validator($factory);
$validator->rules = ['foo' => 'bar'];
return $validator;
}
}
|
<?php
use Mockery as m;
use Samrap\Validation\Validator;
class ValidatorTest extends PHPUnit_Framework_TestCase
{
public function tearDown()
{
m::close();
}
public function testValidatorPasses()
{
$validator = $this->getValidator();
$rules = ['foo' => 'bar'];
$this->assertEmpty($validator->validate($rules)->errors());
}
public function testValidatorFails()
{
$errors = ['foo' => 'baz'];
$validator = $this->getValidator($errors);
$rules = ['foo' => 'bar'];
$this->assertEquals($errors, $validator->validate($rules)->errors());
}
protected function getValidator($errors = [])
{
$laravelValidator = m::mock('\Illuminate\Validation\Validator');
$laravelValidator->shouldReceive('errors')->andReturn($errors);
$factory = m::mock('Illuminate\Validation\Factory');
$factory->shouldReceive('make')->andReturn($laravelValidator);
$validator = new Validator($factory);
return $validator;
}
}
|
Allow running tests without Django.
|
#!/usr/bin/env python
import os
import sys
import unittest
from huey import tests
def _requirements_installed():
try:
import django
return True
except Exception:
return False
def run_tests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=1).run(suite)
if os.path.exists('huey.db'):
os.unlink('huey.db')
if result.failures:
sys.exit(1)
elif result.errors:
sys.exit(2)
def run_django_tests(*test_args):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "huey.contrib.djhuey.tests.settings")
from django.core.management import execute_from_command_line
args = sys.argv
args.insert(1, "test")
args.append('huey.contrib.djhuey.tests')
execute_from_command_line(args)
if __name__ == '__main__':
run_tests(*sys.argv[1:])
if _requirements_installed():
run_django_tests(*sys.argv[1:])
else:
print('Django not installed, skipping Django tests.')
sys.exit(0)
|
#!/usr/bin/env python
import os
import sys
import unittest
from huey import tests
def _requirements_installed():
try:
import django
return True
except Exception:
return False
def run_tests(*test_args):
suite = unittest.TestLoader().loadTestsFromModule(tests)
result = unittest.TextTestRunner(verbosity=1).run(suite)
if os.path.exists('huey.db'):
os.unlink('huey.db')
if result.failures:
sys.exit(1)
elif result.errors:
sys.exit(2)
def run_django_tests(*test_args):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "huey.contrib.djhuey.tests.settings")
from django.core.management import execute_from_command_line
args = sys.argv
args.insert(1, "test")
args.append('huey.contrib.djhuey.tests')
execute_from_command_line(args)
if __name__ == '__main__':
if not _requirements_installed():
print('Requirements are not installed. Run "pip install -r test_requirements.txt" to install all dependencies.')
sys.exit(2)
run_tests(*sys.argv[1:])
run_django_tests(*sys.argv[1:])
sys.exit(0)
|
Remove Python 3 incompatible print statement
|
#!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
# Copyright (C) 2004 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
from networkx import *
z=[5,3,3,3,3,2,2,2,1,1,1]
print(is_valid_degree_sequence(z))
print("Configuration model")
G=configuration_model(z) # configuration model
degree_sequence=list(degree(G).values()) # degree sequence
print("Degree sequence %s" % degree_sequence)
print("Degree histogram")
hist={}
for d in degree_sequence:
if d in hist:
hist[d]+=1
else:
hist[d]=1
print("degree #nodes")
for d in hist:
print('%d %d' % (d,hist[d]))
|
#!/usr/bin/env python
"""
Random graph from given degree sequence.
"""
__author__ = """Aric Hagberg (hagberg@lanl.gov)"""
__date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $"
__credits__ = """"""
__revision__ = "$Revision: 503 $"
# Copyright (C) 2004 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
from networkx import *
z=[5,3,3,3,3,2,2,2,1,1,1]
print is_valid_degree_sequence(z)
print("Configuration model")
G=configuration_model(z) # configuration model
degree_sequence=list(degree(G).values()) # degree sequence
print("Degree sequence %s" % degree_sequence)
print("Degree histogram")
hist={}
for d in degree_sequence:
if d in hist:
hist[d]+=1
else:
hist[d]=1
print("degree #nodes")
for d in hist:
print('%d %d' % (d,hist[d]))
|
Use array for benchmark bytes
|
#!/usr/bin/env node
const crypto = require('crypto');
const b64 = require('../');
const prettyBytes = require('pretty-bytes');
const bytesToBenchmark = [10000, 100000, 1000000, 10000000];
const timer = {
reset: () => timer.startTime = process.hrtime(),
duration: () => process.hrtime(timer.startTime)[1] / 1000000
};
const bench = noOfBytes => Promise.resolve().then(async () => {
const results = {};
console.log(`Generating ${prettyBytes(noOfBytes)} of random binary data...`);
const randomBytes = crypto.randomBytes(noOfBytes);
console.log('Encoding sync...');
timer.reset();
const randomBytesBase64 = randomBytes.toString('base64');
results.encodeSync = timer.duration();
console.log('Decoding sync...');
timer.reset();
Buffer.from(randomBytesBase64, 'base64').toString();
results.decodeSync = timer.duration();
console.log('Encoding async...');
timer.reset();
await b64(randomBytes);
results.encodeAsync = timer.duration();
console.log('Decoding async...');
timer.reset();
await b64(randomBytesBase64);
results.decodeAsync = timer.duration();
console.log();
return results;
});
(async () => {
for(noOfBytes of bytesToBenchmark) {
await bench(noOfBytes);
}
})();
|
#!/usr/bin/env node
const crypto = require('crypto');
const b64 = require('../');
const prettyBytes = require('pretty-bytes');
const timer = {
reset: () => timer.startTime = process.hrtime(),
duration: () => process.hrtime(timer.startTime)[1] / 1000000
};
const bench = noOfBytes => Promise.resolve().then(async () => {
const results = {};
console.log(`Generating ${prettyBytes(noOfBytes)} of random binary data...`);
const randomBytes = crypto.randomBytes(noOfBytes);
console.log('Encoding sync...');
timer.reset();
const randomBytesBase64 = randomBytes.toString('base64');
results.encodeSync = timer.duration();
console.log('Decoding sync...');
timer.reset();
Buffer.from(randomBytesBase64, 'base64').toString();
results.decodeSync = timer.duration();
console.log('Encoding async...');
timer.reset();
await b64(randomBytes);
results.encodeAsync = timer.duration();
console.log('Decoding async...');
timer.reset();
await b64(randomBytesBase64);
results.decodeAsync = timer.duration();
console.log();
return results;
});
(async () => {
await bench(10000)
await bench(100000);
await bench(1000000);
await bench(10000000);
})();
|
Allow SDK location to be overridden by environment variable.
|
import os
import logging
class PblCommand:
name = ''
help = ''
def run(args):
pass
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
parser.add_argument('--debug', action='store_true',
help = 'Enable debugging output')
def sdk_path(self, args):
"""
Tries to guess the location of the Pebble SDK
"""
sdk_path = os.getenv('PEBBLE_SDK_PATH')
if args.sdk:
return args.sdk
elif sdk_path:
if not os.path.exists(sdk_path):
raise Exception("SDK path {} doesn't exist!".format(sdk_path))
logging.info("Overriding Pebble SDK Path with '%s'", sdk_path)
return sdk_path
else:
return os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
import os
class PblCommand:
name = ''
help = ''
def run(args):
pass
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
parser.add_argument('--debug', action='store_true',
help = 'Enable debugging output')
def sdk_path(self, args):
"""
Tries to guess the location of the Pebble SDK
"""
if args.sdk:
return args.sdk
else:
return os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
Remove del fetched_tweets (now a generator)
|
from apscheduler.schedulers.blocking import BlockingScheduler
from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins,
update_status)
from memory_profiler import profile
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=16)
@profile
def twinsy_finder(fetch_size=10000):
print("Running twinsy finder...")
fetched_tweets = fetch_tweets('Kanye', fetch_size=fetch_size)
tweets = dig_for_twins(fetched_tweets)
if tweets:
print("Twins found, updating status.")
update_status(tweets)
else:
print("No twins found.")
if __name__ == '__main__':
twinsy_finder()
print("Starting scheduler")
sched.start()
|
from apscheduler.schedulers.blocking import BlockingScheduler
from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins,
update_status)
from memory_profiler import profile
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=16)
@profile
def twinsy_finder(fetch_size=10000):
print("Running twinsy finder...")
fetched_tweets = fetch_tweets('Kanye', fetch_size=fetch_size)
tweets = dig_for_twins(fetched_tweets)
del fetched_tweets
if tweets:
print("Twins found, updating status.")
update_status(tweets)
else:
print("No twins found.")
if __name__ == '__main__':
twinsy_finder()
print("Starting scheduler")
sched.start()
|
Fix issue with path variable
|
import os
from setuptools import setup
PACKAGE_VERSION = '0.3'
def version():
def version_file(mode='r'):
return open(os.path.dirname(os.path.abspath(__file__), 'version.txt'), mode)
if os.getenv('TRAVIS'):
with version_file('w') as verfile:
verfile.write('{0}.{1}'.format(PACKAGE_VERSION, os.getenv('TRAVIS_BUILD_NUMBER')))
with version_file() as verfile:
data = verfile.readlines()
return data[0].strip()
setup(
name='osaapi',
version=version(),
author='apsliteteam, oznu',
author_email='aps@odin.com',
packages=['osaapi'],
url='https://aps.odin.com',
license='Apache License',
description='A python client for the Odin Service Automation (OSA) and billing APIs.',
long_description=open('README.md').read(),
)
|
import os
from setuptools import setup
PACKAGE_VERSION = '0.3'
def version():
def version_file(mode='r'):
return open(os.path.join(__path__, 'version.txt'), mode)
if os.getenv('TRAVIS'):
with version_file('w') as verfile:
verfile.write('{0}.{1}'.format(PACKAGE_VERSION, os.getenv('TRAVIS_BUILD_NUMBER')))
with version_file() as verfile:
data = verfile.readlines()
return data[0].strip()
setup(
name='osaapi',
version_getter=version,
author='apsliteteam, oznu',
author_email='aps@odin.com',
packages=['osaapi'],
url='https://aps.odin.com',
license='Apache License',
description='A python client for the Odin Service Automation (OSA) and billing APIs.',
long_description=open('README.md').read(),
)
|
Update install_requires to support future django versions
|
#!/usr/bin/env python
from setuptools import setup
setup(name='django_emarsys',
version='0.34',
description='Django glue for Emarsys events',
license="MIT",
author='Markus Bertheau',
author_email='mbertheau@gmail.com',
long_description=open('README.md').read(),
packages=['django_emarsys',
'django_emarsys.management',
'django_emarsys.management.commands',
'django_emarsys.migrations'
],
include_package_data=True,
install_requires=[
'python-emarsys==0.2',
'jsonfield==2.0.2',
])
|
#!/usr/bin/env python
from setuptools import setup
setup(name='django_emarsys',
version='0.34',
description='Django glue for Emarsys events',
license="MIT",
author='Markus Bertheau',
author_email='mbertheau@gmail.com',
long_description=open('README.md').read(),
packages=['django_emarsys',
'django_emarsys.management',
'django_emarsys.management.commands',
'django_emarsys.migrations'
],
include_package_data=True,
install_requires=[
'python-emarsys==0.2',
'jsonfield==1.0.3',
])
|
Remove writing to Zookeeper when kafka is selected as offset storage and dual.commit is false.
|
/*
* 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 com.pinterest.secor.reader;
import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.common.TopicPartition;
import com.pinterest.secor.message.Message;
import java.net.UnknownHostException;
public interface KafkaMessageIterator {
boolean hasNext();
Message next();
void init(SecorConfig config) throws UnknownHostException;
void commit(TopicPartition topicPartition, long offset);
long getKafkaCommitedOffsetCount(TopicPartition topicPartition);
}
|
/*
* 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 com.pinterest.secor.reader;
import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.common.TopicPartition;
import com.pinterest.secor.message.Message;
import java.net.UnknownHostException;
public interface KafkaMessageIterator {
boolean hasNext();
Message next();
void init(SecorConfig config) throws UnknownHostException;
void commit(TopicPartition topicPartition, long offset);
}
|
Refactor translation downloads according to downloadFile service
|
import Controller from '@ember/controller';
export default Controller.extend({
isLoading: false,
actions: {
translationsDownload() {
this.set('isLoading', true);
this.get('loader')
.downloadFile('/admin/content/translations/all')
.then(res => {
const anchor = document.createElement('a');
anchor.style.display = 'none';
anchor.href = `data:text/plain;charset=utf-8,${encodeURIComponent(res)}`;
anchor.download = 'Translations.zip';
anchor.click();
this.get('notify').success(this.get('l10n').t('Translations Zip generated successfully.'));
})
.catch(e => {
console.warn(e);
this.get('notify').error(this.get('l10n').t('Unexpected error occurred.'));
})
.finally(() => {
this.set('isLoading', false);
});
}
}
});
|
import Controller from '@ember/controller';
export default Controller.extend({
isLoading: false,
actions: {
translationsDownload() {
this.set('isLoading', true);
this.get('loader')
.downloadFile('/admin/content/translations/all')
.then(() => {
this.get('notify').success(this.get('l10n').t('Translations Zip generated successfully.'));
})
.catch(e => {
console.warn(e);
this.get('notify').error(this.get('l10n').t('Unexpected error occurred.'));
})
.finally(() => {
this.set('isLoading', false);
});
}
}
});
|
Make it more obvious that values initialize at 0
|
import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
assert stats.cache_hits == 1000
|
import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUInt64Field(label="sys.gid", value=os.getgid)
errors = mmstats.UIntStat(label="com.urbanairship.app.errors")
warnings = mmstats.UIntStat(label="com.urbanairship.app.warnings")
queries = mmstats.UIntStat(label="com.urbanairship.app.queries")
cache_hits = mmstats.UIntStat(label="com.urbanairship.app.cache_hits")
cache_misses = mmstats.UIntStat(label="com.urbanairship.app.cache_misses")
degraded = mmstats.BoolStat(label="com.urbanairship.app.degraded")
stats = MyStats(filename="mmstats-test-mystats")
stats.degraded = True
stats.errors += 1
stats.cache_hits += 1000
stats.queries = 50
|
Use plat_specific site-packages dir in CI script
|
import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackagesdir = distutils.sysconfig.get_python_lib(plat_specific=True)
print("site packages dir:", sitepackagesdir)
hdf5_path = os.environ.get("HDF5_DIR")
print("HDF5_DIR", hdf5_path)
if platform.startswith('win'):
for f in glob(pjoin(hdf5_path, 'lib/*.dll')):
copy(f, pjoin(sitepackagesdir, 'h5py', basename(f)))
print("Copied", f)
print("In installed h5py:", os.listdir(pjoin(sitepackagesdir, 'h5py')))
if __name__ == '__main__':
main()
|
import distutils.sysconfig
from glob import glob
import os
from os.path import join as pjoin, basename
from shutil import copy
from sys import platform
def main():
"""
Copy HDF5 DLLs into installed h5py package
"""
# This is the function Tox also uses to locate site-packages (Apr 2019)
sitepackagesdir = distutils.sysconfig.get_python_lib()
print("site packages dir:", sitepackagesdir)
hdf5_path = os.environ.get("HDF5_DIR")
print("HDF5_DIR", hdf5_path)
if platform.startswith('win'):
for f in glob(pjoin(hdf5_path, 'lib/*.dll')):
copy(f, pjoin(sitepackagesdir, 'h5py', basename(f)))
print("Copied", f)
print("In installed h5py:", os.listdir(pjoin(sitepackagesdir, 'h5py')))
if __name__ == '__main__':
main()
|
Add order in nodes in topic creation form
|
# -*- coding:utf-8 -*-
from flask.ext.sqlalchemy import models_committed
from gather.extensions import db, cache
class Node(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False, unique=True, index=True)
slug = db.Column(db.String(100), nullable=False, unique=True, index=True)
description = db.Column(db.String(500), nullable=True, default="")
icon = db.Column(db.String(100), nullable=True, default="")
def __str__(self):
return self.name
def __repr__(self):
return '<Node: %s>' % self.name
@classmethod
def query_all(cls):
return cls.query.order_by(Node.name.asc()).all()
def to_dict(self):
return dict(
id=self.id,
name=self.name,
slug=self.slug,
description=self.description,
icon=self.icon
)
def save(self):
db.session.add(self)
db.session.commit()
return self
|
# -*- coding:utf-8 -*-
from flask.ext.sqlalchemy import models_committed
from gather.extensions import db, cache
class Node(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False, unique=True, index=True)
slug = db.Column(db.String(100), nullable=False, unique=True, index=True)
description = db.Column(db.String(500), nullable=True, default="")
icon = db.Column(db.String(100), nullable=True, default="")
def __str__(self):
return self.name
def __repr__(self):
return '<Node: %s>' % self.name
@classmethod
def query_all(cls):
return cls.query.all()
def to_dict(self):
return dict(
id=self.id,
name=self.name,
slug=self.slug,
description=self.description,
icon=self.icon
)
def save(self):
db.session.add(self)
db.session.commit()
return self
|
Change code style to use single-quoted strings instead of double-quoted strings.
|
/*
* Copyright (c) 2015 Steven Soloff
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
'use strict';
var bodyParser = require('body-parser');
var express = require('express');
var http = require('http');
var path = require('path');
var evaluateController = require('./controllers/evaluate-controller.js');
var app = express();
app.use(express.static(path.join(__dirname, '/public')));
app.use(bodyParser.urlencoded({extended: true}));
http.createServer(app).listen(3000);
app.post('/evaluate', evaluateController.evaluate);
|
/*
* Copyright (c) 2015 Steven Soloff
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
"use strict";
var bodyParser = require("body-parser");
var express = require("express");
var http = require("http");
var path = require("path");
var evaluateController = require("./controllers/evaluate-controller.js");
var app = express();
app.use(express.static(path.join(__dirname, "/public")));
app.use(bodyParser.urlencoded({extended: true}));
http.createServer(app).listen(3000);
app.post("/evaluate", evaluateController.evaluate);
|
Add default port to database connection script
The default port is used if the ~/.catmaid-db file doesn't contain it. This
fixes #454.
|
import sys
import psycopg2
import os
import yaml
if 'CATMAID_CONFIGURATION' in os.environ:
path = os.environ['CATMAID_CONFIGURATION']
else:
path = os.path.join(os.environ['HOME'], '.catmaid-db')
try:
conf = yaml.load(open(path))
except:
print >> sys.stderr, '''Your %s file should look like:
host: localhost
port: 5432
database: catmaid
username: catmaid_user
password: password_of_your_catmaid_user''' % (path,)
sys.exit(1)
# Make a variable for each of these so that they can be imported:
db_host = conf['host']
db_port = conf['port'] if 'port' in conf else 5432
db_database = conf['database']
db_username = conf['username']
db_password = conf['password']
db_connection = psycopg2.connect(host=db_host,
port=db_port,
database=db_database,
user=db_username,
password=db_password)
|
import sys
import psycopg2
import os
import yaml
if 'CATMAID_CONFIGURATION' in os.environ:
path = os.environ['CATMAID_CONFIGURATION']
else:
path = os.path.join(os.environ['HOME'], '.catmaid-db')
try:
conf = yaml.load(open(path))
except:
print >> sys.stderr, '''Your %s file should look like:
host: localhost
port: 5432
database: catmaid
username: catmaid_user
password: password_of_your_catmaid_user''' % (path,)
sys.exit(1)
# Make a variable for each of these so that they can be imported:
db_host = conf['host']
db_port = conf['port']
db_database = conf['database']
db_username = conf['username']
db_password = conf['password']
db_connection = psycopg2.connect(host=db_host,
port=db_port,
database=db_database,
user=db_username,
password=db_password)
|
Fix typo with expected metric
|
"""
Contains tests for the timer metric.
"""
from statsite.metrics import Timer
class TestTimerMetric(object):
def test_fold_sum(self):
"""
Tests that folding generates a sum of the timers.
"""
now = 10
metrics = [Timer("k", 10),
Timer("k", 15),
Timer("j", 7),
Timer("j", 8)]
result = Timer.fold(metrics, now)
assert ("timers.k.sum", 25, now) == self._get_metric("timers.k.sum", result)
assert ("timers.j.sum", 15, now) == self._get_metric("timers.j.sum", result)
def _get_metric(self, key, metrics):
"""
This will extract a specific metric out of an array of metrics.
"""
for metric in metrics:
if metric[0] == key:
return metric
return None
|
"""
Contains tests for the timer metric.
"""
from statsite.metrics import Timer
class TestTimerMetric(object):
def test_fold_sum(self):
"""
Tests that folding generates a sum of the timers.
"""
now = 10
metrics = [Timer("k", 10),
Timer("k", 15),
Timer("j", 7),
Timer("j", 8)]
result = Timer.fold(metrics, now)
assert ("k", 25, now) == self._get_metric("timers.k.sum", result)
assert ("j", 15, now) == self._get_metric("timers.j.sum", result)
def _get_metric(self, key, metrics):
"""
This will extract a specific metric out of an array of metrics.
"""
for metric in metrics:
if metric[0] == key:
return metric
return None
|
Disable the unifier until the hint is passed to the StramChild about the type of the unifier.
|
/*
* Copyright (c) 2012-2013 Malhar, Inc.
* All Rights Reserved.
*/
package com.malhartech.lib.stream;
import com.malhartech.api.Context.OperatorContext;
import com.malhartech.api.DefaultInputPort;
import com.malhartech.api.DefaultOutputPort;
import com.malhartech.api.Operator;
import com.malhartech.api.Operator.Unifier;
/**
* Counter counts the number of tuples delivered to it in each window and emits the count.
*
* @author Chetan Narsude <chetan@malhar-inc.com>
*/
public class Counter implements Operator//, Unifier<Integer>
{
public final transient DefaultInputPort<Object> input = new DefaultInputPort<Object>(this)
{
@Override
public void process(Object tuple)
{
count++;
}
};
public final transient DefaultOutputPort<Integer> output = new DefaultOutputPort<Integer>(this)
{
// @Override
// public Unifier<Integer> getUnifier()
// {
// return Counter.this;
// }
};
@Override
public void beginWindow(long windowId)
{
count = 0;
}
// @Override
public void merge(Integer tuple)
{
count += tuple;
}
@Override
public void endWindow()
{
output.emit(count);
}
@Override
public void setup(OperatorContext context)
{
}
@Override
public void teardown()
{
}
private transient int count;
}
|
/*
* Copyright (c) 2012-2013 Malhar, Inc.
* All Rights Reserved.
*/
package com.malhartech.lib.stream;
import com.malhartech.api.Context.OperatorContext;
import com.malhartech.api.DefaultInputPort;
import com.malhartech.api.DefaultOutputPort;
import com.malhartech.api.Operator;
import com.malhartech.api.Operator.Unifier;
/**
* Counter counts the number of tuples delivered to it in each window and emits the count.
*
* @author Chetan Narsude <chetan@malhar-inc.com>
*/
public class Counter implements Operator, Unifier<Integer>
{
public final transient DefaultInputPort<Object> input = new DefaultInputPort<Object>(this)
{
@Override
public void process(Object tuple)
{
count++;
}
};
public final transient DefaultOutputPort<Integer> output = new DefaultOutputPort<Integer>(this)
{
@Override
public Unifier<Integer> getUnifier()
{
return Counter.this;
}
};
@Override
public void beginWindow(long windowId)
{
count = 0;
}
@Override
public void merge(Integer tuple)
{
count += tuple;
}
@Override
public void endWindow()
{
output.emit(count);
}
@Override
public void setup(OperatorContext context)
{
}
@Override
public void teardown()
{
}
private transient int count;
}
|
Update to use new computed property syntax
|
import Ember from 'ember';
export default Ember.ArrayController.extend({
queryParams: ['query', 'offset'],
query: null,
offset: 0,
increment: 20,
queryField: Ember.computed.oneWay('query'),
meta: Ember.computed('content.[]', function() {
return this.get("content.meta");
}),
resultsAvailable: Ember.computed('content.[]', function() {
let total = this.get('meta').total - this.get('increment');
return (this.get('offset') <= total);
}),
actions: {
search: function() {
this.set('query', this.get('queryField'));
this.set('offset', 0);
},
next: function() {
var next = this.get('increment') + this.get('meta').offset;
this.set('offset', next);
}
}
});
|
import Ember from 'ember';
export default Ember.ArrayController.extend({
queryParams: ['query', 'offset'],
query: null,
offset: 0,
increment: 20,
queryField: Ember.computed.oneWay('query'),
meta: function() {
return this.get("content.meta");
}.property('content.[]'),
resultsAvailable: Ember.computed('content.[]', function() {
let total = this.get('meta').total - this.get('increment');
return (this.get('offset') <= total);
}),
actions: {
search: function() {
this.set('query', this.get('queryField'));
this.set('offset', 0);
},
next: function() {
var next = this.get('increment') + this.get('meta').offset;
this.set('offset', next);
}
}
});
|
Add dependency on little scrapy autoresponse tool
|
#!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='Bug importers for the OpenHatch project',
install_requires=[
'gdata',
'lxml',
'pyopenssl',
'unicodecsv',
'feedparser',
'twisted',
'python-dateutil',
'decorator',
'scrapy',
'argparse',
'mock',
'PyYAML',
'importlib',
'autoresponse',
],
)
if __name__ == '__main__':
from setuptools import setup
setup(**setup_params)
|
#!/usr/bin/env python
from setuptools import find_packages, Command
setup_params = dict(
name='bugimporters',
version=0.1,
author='Various contributers to the OpenHatch project, Berry Phillips',
author_email='all@openhatch.org, berryphillips@gmail.com',
packages=find_packages(),
description='Bug importers for the OpenHatch project',
install_requires=[
'gdata',
'lxml',
'pyopenssl',
'unicodecsv',
'feedparser',
'twisted',
'python-dateutil',
'decorator',
'scrapy',
'argparse',
'mock',
'PyYAML',
'importlib',
],
)
if __name__ == '__main__':
from setuptools import setup
setup(**setup_params)
|
Update to User.save api references.
|
(function (module) {
module.controller("AccountSettingsController", AccountSettingsController);
AccountSettingsController.$inject = ["mcapi", "User", "toastr"];
/* @ngInject */
function AccountSettingsController(mcapi, User, toastr) {
var ctrl = this;
ctrl.fullname = User.attr().fullname;
ctrl.updateName = updateName;
///////////////////////////
function updateName() {
mcapi('/users/%', ctrl.mcuser.email)
.success(function () {
User.attr.fullname = ctrl.fullname;
User.save();
toastr.success('User name updated', 'Success', {
closeButton: true
});
}).error(function () {
}).put({fullname: ctrl.fullname});
}
}
}(angular.module('materialscommons')));
|
(function (module) {
module.controller("AccountSettingsController", AccountSettingsController);
AccountSettingsController.$inject = ["mcapi", "User", "toastr"];
/* @ngInject */
function AccountSettingsController(mcapi, User, toastr) {
var ctrl = this;
ctrl.fullname = User.attr().fullname;
ctrl.updateName = updateName;
///////////////////////////
function updateName() {
mcapi('/users/%', ctrl.mcuser.email)
.success(function () {
User.save(ctrl.mcuser);
toastr.success('User name updated', 'Success', {
closeButton: true
});
}).error(function () {
}).put({fullname: ctrl.fullname});
}
}
}(angular.module('materialscommons')));
|
Use a theme instead of vanilla twbs. Add padding.
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
@section('title')
{{ Lang::get('messages.page-title') }}
@stop
</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.2/united/bootstrap.min.css">
<style>
body {
padding-top: 60px;
padding-bottom: 80px;
}
</style>
@yield('css')
</head>
<body>
<div class="container">
@yield('body')
</div>
@yield('js')
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
@section('title')
{{ Lang::get('messages.page-title') }}
@stop
</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css">
@yield('css')
</head>
<body>
<div class="container">
@yield('body')
</div>
@yield('js')
</body>
</html>
|
Mark the sub-package server as deprecated
|
// +build go1.9
// Package server is deprecated. which is migrated into net2.
package server
import (
"github.com/xgfone/go-tools/net2"
)
type (
// THandle is the type alias of net2.THandle.
//
// DEPRECATED!!! Please the package net2.
THandle = net2.THandle
// THandleFunc is the type alias of net2.THandleFunc.
//
// DEPRECATED!!! Please the package net2.
THandleFunc = net2.THandleFunc
)
var (
// TCPWrapError is the alias of net2.TCPWrapError.
//
// DEPRECATED!!! Please the package net2.
TCPWrapError = net2.TCPWrapError
// TCPServerForever is the alias of net2.TCPServerForever.
//
// DEPRECATED!!! Please the package net2.
TCPServerForever = net2.TCPServerForever
// DialTCP is the alias of net2.DialTCP.
//
// DEPRECATED!!! Please the package net2.
DialTCP = net2.DialTCP
// DialTCPWithAddr is the alias of net2.DialTCPWithAddr.
//
// DEPRECATED!!! Please the package net2.
DialTCPWithAddr = net2.DialTCPWithAddr
)
|
// +build go1.9
package server
import (
"github.com/xgfone/go-tools/net2"
)
type (
// THandle is the type alias of net2.THandle.
//
// DEPRECATED!!! Please the package net2.
THandle = net2.THandle
// THandleFunc is the type alias of net2.THandleFunc.
//
// DEPRECATED!!! Please the package net2.
THandleFunc = net2.THandleFunc
)
var (
// TCPWrapError is the alias of net2.TCPWrapError.
//
// DEPRECATED!!! Please the package net2.
TCPWrapError = net2.TCPWrapError
// TCPServerForever is the alias of net2.TCPServerForever.
//
// DEPRECATED!!! Please the package net2.
TCPServerForever = net2.TCPServerForever
// DialTCP is the alias of net2.DialTCP.
//
// DEPRECATED!!! Please the package net2.
DialTCP = net2.DialTCP
// DialTCPWithAddr is the alias of net2.DialTCPWithAddr.
//
// DEPRECATED!!! Please the package net2.
DialTCPWithAddr = net2.DialTCPWithAddr
)
|
Change node-dir options to disable recursion to have a more predictable behaviour
|
import safeEval from 'safe-eval';
import dir from 'node-dir';
import path from 'path';
import {ipcRenderer} from 'electron';
const babel = require('babel-core');
const babelOptions = {
presets: ['es2015']
}
let scriptDirectory = process.env.script;
let options = {
match: /.js$/,
exclude: /^\./,
recursive: false
}
if (path.isAbsolute(scriptDirectory)) {
dir.readFiles(scriptDirectory, options, parseFile, success);
} else {
throw new Error('Path for user script is not absolute.');
}
function parseFile (err, content, next) {
if(err)
throw err;
let code;
try {
code = babel.transform(content, babelOptions).code;
} catch(e) {
if(e.name === 'TypeError') {
// TODO: Handle syntax error and show it to the user
console.log(e);
} else {
throw e;
}
} finally {
ipcRenderer.send('code', {code});
}
next();
}
function success (err, files) {
if(err)
throw err;
console.log("Finished reading all files!");
}
|
import safeEval from 'safe-eval';
import dir from 'node-dir';
import path from 'path';
import {ipcRenderer} from 'electron';
const babel = require('babel-core');
const babelOptions = {
presets: ['es2015']
}
let scriptDirectory = process.env.script;
let options = {
match: /.js$/,
exclude: /^\./
}
if (path.isAbsolute(scriptDirectory)) {
dir.readFiles(scriptDirectory, options, parseFile, success);
} else {
throw new Error('Path for user script is not absolute.');
}
function parseFile (err, content, next) {
if(err)
throw err;
let code;
try {
code = babel.transform(content, babelOptions).code;
} catch(e) {
if(e.name === 'TypeError') {
// TODO: Handle syntax error and show it to the user
console.log(e);
} else {
throw e;
}
} finally {
ipcRenderer.send('code', {code});
}
next();
}
function success (err, files) {
if(err)
throw err;
console.log("Finished reading all files!");
}
|
Add a missing annotation for a package and fix structure of comments
|
/*
* Copyright 2017, 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.
*/
/**
* Base classes and interfaces for Spine Gradle plugins.
*
* @author Alex Tymchenko
*/
@ParametersAreNonnullByDefault
package io.spine.gradle;
import javax.annotation.ParametersAreNonnullByDefault;
|
/*
* Copyright 2017, 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.
*
*
* Base classes and interfaces for Spine Gradle plugins.
*
* @author Alex Tymchenko
*/
package io.spine.gradle;
|
Update service provider to use bindShared.
Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
|
<?php namespace Orchestra\Memory;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class MemoryServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bindShared('orchestra.memory', function ($app) {
return new MemoryManager($app);
});
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Orchestra\Memory', 'Orchestra\Support\Facades\Memory');
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$path = realpath(__DIR__.'/../../');
$this->package('orchestra/memory', 'orchestra/memory', $path);
$this->registerMemoryEvent();
}
/**
* Register memory events during booting.
*
* @return void
*/
protected function registerMemoryEvent()
{
$app = $this->app;
$app->after(function () use ($app) {
$app['orchestra.memory']->finish();
});
}
}
|
<?php namespace Orchestra\Memory;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;
class MemoryServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['orchestra.memory'] = $this->app->share(function ($app) {
return new MemoryManager($app);
});
$this->app->booting(function () {
$loader = AliasLoader::getInstance();
$loader->alias('Orchestra\Memory', 'Orchestra\Support\Facades\Memory');
});
}
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$path = realpath(__DIR__.'/../../');
$this->package('orchestra/memory', 'orchestra/memory', $path);
$this->registerMemoryEvent();
}
/**
* Register memory events during booting.
*
* @return void
*/
protected function registerMemoryEvent()
{
$app = $this->app;
$app->after(function () use ($app) {
$app['orchestra.memory']->finish();
});
}
}
|
FRIN23-284: Add option to disable adding target blank to full urls
Uses the same behaviour as in frg -> external.js
|
/*jslint browser: true, indent: 2, todo: true, unparam: true */
/*global jQuery,Ornament */
(function (document, window, Orn, $) {
"use strict";
var query = [];
// Add suffixes to query.
$.each(Orn.externalLinkExtensions, function (i, v) {
query.push("[href$='." + v + "']");
query.push("[href$='." + v.toUpperCase() + "']");
});
// Add prefixes to query.
$.each([ "http://", "https://" ], function (i, v) {
query.push("[href^='" + v + "']");
});
$(document).on("ornament:refresh", function () {
// Handle clicks.
$(query.join(", ")).each(function(){
if(!this.is("[data-same-window]")) {
$(this).attr("target", "_blank");
// Add noopener to external links programatically
// https://mathiasbynens.github.io/rel-noopener/
if (!this.is("[rel]")) {
this.attr("rel", "noopener");
}
}
});
});
}(document, window, Ornament, jQuery));
|
/*jslint browser: true, indent: 2, todo: true, unparam: true */
/*global jQuery,Ornament */
(function (document, window, Orn, $) {
"use strict";
var query = [];
// Add suffixes to query.
$.each(Orn.externalLinkExtensions, function (i, v) {
query.push("[href$='." + v + "']");
query.push("[href$='." + v.toUpperCase() + "']");
});
// Add prefixes to query.
$.each([ "http://", "https://" ], function (i, v) {
query.push("[href^='" + v + "']");
});
$(document).on("ornament:refresh", function () {
// Handle clicks.
$(query.join(", ")).each(function(){
$(this).attr("target","_blank");
});
});
}(document, window, Ornament, jQuery));
|
Fix format constant for PHP 7.1
|
<?php namespace Limoncello\Flute\Types;
/**
* Copyright 2015-2017 info@neomerx.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use DateTimeImmutable;
use JsonSerializable;
/**
* Wrapper class for `DateTimeInterface` value with JSON serialization support.
*
* @package Limoncello\Flute
*/
class DateTime extends DateTimeImmutable implements JsonSerializable
{
/** DateTime format */
const JSON_API_FORMAT = \DateTime::ISO8601;
/**
* @inheritdoc
*/
public function jsonSerialize()
{
return $this->format(static::JSON_API_FORMAT);
}
}
|
<?php namespace Limoncello\Flute\Types;
/**
* Copyright 2015-2017 info@neomerx.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use DateTimeImmutable;
use JsonSerializable;
/**
* Wrapper class for `DateTimeInterface` value with JSON serialization support.
*
* @package Limoncello\Flute
*/
class DateTime extends DateTimeImmutable implements JsonSerializable
{
/** DateTime format */
const JSON_API_FORMAT = self::ISO8601;
/**
* @inheritdoc
*/
public function jsonSerialize()
{
return $this->format(static::JSON_API_FORMAT);
}
}
|
Drop buffers with under-used capacity in order to reduce memory waste
|
package bytebufferpool
import "sync"
const (
minBitSize = 8
steps = 20
minSize = 1 << minBitSize
maxSize = 1 << (minBitSize + steps - 1)
)
type byteBufferPool struct {
// Pools are segemented into power-of-two sized buffers
// from minSize bytes to maxSize.
//
// This allows reducing fragmentation of ByteBuffer objects.
pools [steps]sync.Pool
}
func (p *byteBufferPool) Acquire() *ByteBuffer {
pools := &p.pools
for i := 0; i < steps; i++ {
v := pools[i].Get()
if v != nil {
return v.(*ByteBuffer)
}
}
return &ByteBuffer{
B: make([]byte, 0, minSize),
}
}
func (p *byteBufferPool) Release(b *ByteBuffer) {
n := cap(b.B)
if n > maxSize {
// Oversized buffer.
// Drop it.
return
}
if (n >> 2) > len(b.B) {
// Under-used buffer capacity.
// Drop it.
return
}
b.B = b.B[:0]
idx := bitSize(n-1) >> minBitSize
p.pools[idx].Put(b)
}
func bitSize(n int) int {
s := 0
for n > 0 {
n >>= 1
s++
}
return s
}
|
package bytebufferpool
import "sync"
const (
minBitSize = 8
steps = 20
minSize = 1 << minBitSize
maxSize = 1 << (minBitSize + steps - 1)
)
type byteBufferPool struct {
// Pools are segemented into power-of-two sized buffers
// from minSize bytes to maxSize.
//
// This allows reducing fragmentation of ByteBuffer objects.
pools [steps]sync.Pool
}
func (p *byteBufferPool) Acquire() *ByteBuffer {
pools := &p.pools
for i := 0; i < steps; i++ {
v := pools[i].Get()
if v != nil {
return v.(*ByteBuffer)
}
}
return &ByteBuffer{
B: make([]byte, 0, minSize),
}
}
func (p *byteBufferPool) Release(b *ByteBuffer) {
n := cap(b.B)
if n > maxSize {
// Just drop oversized buffers.
return
}
b.B = b.B[:0]
idx := bitsize(n-1) >> minBitSize
p.pools[idx].Put(b)
}
func bitsize(n int) int {
s := 0
for n > 0 {
n >>= 1
s++
}
return s
}
|
[AllBundles] Fix codestyle issues after 5.7 upmerge
|
<?php
namespace Kunstmaan\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
class WysiwygType extends AbstractType
{
/**
* @var DataTransformerInterface
*/
private $mediaTokenTransformer;
public function __construct(DataTransformerInterface $mediaTokenTransformer)
{
$this->mediaTokenTransformer = $mediaTokenTransformer;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addModelTransformer($this->mediaTokenTransformer);
}
/**
* @return string
*/
public function getParent()
{
return TextareaType::class;
}
/**
* @return string
*/
public function getBlockPrefix()
{
return 'wysiwyg';
}
}
|
<?php
namespace Kunstmaan\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
class WysiwygType extends AbstractType
{
/**
* @var DataTransformerInterface
*/
private $mediaTokenTransformer;
public function __construct(DataTransformerInterface $mediaTokenTransformer)
{
$this->mediaTokenTransformer = $mediaTokenTransformer;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addModelTransformer($this->mediaTokenTransformer);
}
/**
* @return string
*/
public function getParent()
{
return TextareaType::class;
}
/**
* @return string
*/
public function getBlockPrefix()
{
return 'wysiwyg';
}
}
|
Fix import following namespace movement
Docker-DCO-1.1-Signed-off-by: Mangled Deutz <olivier@webitup.fr> (github: dmp42)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from .app import app
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT_WWW', 5000))
app.debug = True
app.run(host='0.0.0.0', port=port)
# Or you can run:
# gunicorn --access-logfile - --log-level debug --debug -b 0.0.0.0:5000 \
# -w 1 wsgi:application
else:
# For uwsgi
app.logger.setLevel(logging.INFO)
stderr_logger = logging.StreamHandler()
stderr_logger.setLevel(logging.INFO)
stderr_logger.setFormatter(
logging.Formatter('%(asctime)s %(levelname)s: %(message)s'))
app.logger.addHandler(stderr_logger)
application = app
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
from . import app
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT_WWW', 5000))
app.debug = True
app.run(host='0.0.0.0', port=port)
# Or you can run:
# gunicorn --access-logfile - --log-level debug --debug -b 0.0.0.0:5000 \
# -w 1 wsgi:application
else:
# For uwsgi
app.logger.setLevel(logging.INFO)
stderr_logger = logging.StreamHandler()
stderr_logger.setLevel(logging.INFO)
stderr_logger.setFormatter(
logging.Formatter('%(asctime)s %(levelname)s: %(message)s'))
app.logger.addHandler(stderr_logger)
application = app
|
Change label text of second view
|
/* ************************************************************************
coretest
Copyright:
2009 Deutsche Telekom AG, Germany, http://telekom.com
************************************************************************ */
/**
* Start View
*/
core.Class("coretest.view.Test", {
include : [unify.view.StaticView],
construct : function() {
unify.view.StaticView.call(this);
},
members :
{
// overridden
getTitle : function(type, param) {
return "My Own";
},
/**
* #asset(coretest/clock.png)
*/
// overridden
getIcon : function(type, param) {
return "coretest/clock.png";
},
// overridden
_createView : function()
{
var navbar = new unify.ui.container.NavigationBar(this);
this.add(navbar, {flex: 1});
var content = new unify.ui.basic.Label("Another test view");
this.add(content);
}
}
});
unify.core.Singleton.annotate(coretest.view.Test);
|
/* ************************************************************************
coretest
Copyright:
2009 Deutsche Telekom AG, Germany, http://telekom.com
************************************************************************ */
/**
* Start View
*/
core.Class("coretest.view.Test", {
include : [unify.view.StaticView],
construct : function() {
unify.view.StaticView.call(this);
},
members :
{
// overridden
getTitle : function(type, param) {
return "My Own";
},
/**
* #asset(coretest/clock.png)
*/
// overridden
getIcon : function(type, param) {
return "coretest/clock.png";
},
// overridden
_createView : function()
{
var navbar = new unify.ui.container.NavigationBar(this);
this.add(navbar, {flex: 1});
var content = new unify.ui.basic.Label("Hello World");
this.add(content);
}
}
});
unify.core.Singleton.annotate(coretest.view.Test);
|
Annotate clean classes as @Nullsafe:: (4/14) libraries/components/litho-core/src/main/java/com/facebook/litho/
Reviewed By: pasqualeanatriello
Differential Revision: D28505758
fbshipit-source-id: 2bb4c97a1d166c4090db5edb7e6178719f0c2a5d
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho;
import androidx.annotation.Nullable;
import com.facebook.infer.annotation.Nullsafe;
@Nullsafe(Nullsafe.Mode.LOCAL)
public class ArrayBatchAllocator {
private static int batchSize = 200;
@Nullable private static int[][] arrays = null;
private static int index = 0;
/** same as calling new int[2]; */
public static int[] newArrayOfSize2() {
if (arrays == null || arrays.length == index) {
arrays = new int[batchSize][2];
index = 0;
}
int[] toReturn = arrays[index];
arrays[index++] = null;
return toReturn;
}
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho;
import androidx.annotation.Nullable;
public class ArrayBatchAllocator {
private static int batchSize = 200;
@Nullable private static int[][] arrays = null;
private static int index = 0;
/** same as calling new int[2]; */
public static int[] newArrayOfSize2() {
if (arrays == null || arrays.length == index) {
arrays = new int[batchSize][2];
index = 0;
}
int[] toReturn = arrays[index];
arrays[index++] = null;
return toReturn;
}
}
|
test: Check transform definitions are well set
|
/* global describe, it, expect */
import { filterByKeys, transform } from '../src/transform'
import * as mocks from './mocks'
describe('Transform suite', () => {
const keys = Object.keys(mocks.defs.simple)
it('should filter by keys two objects', () => {
expect(filterByKeys(keys, mocks.defs.complex)).toEqual(mocks.defs.simple)
})
it('should transform a definition into a fulfilled object', () => {
expect(transform(mocks.defs.simple, mocks.fulfilled)).toEqual(mocks.fulfilled)
})
it('should transform a definition using mutators', () => {
expect(transform(mocks.defs.simple, mocks.fulfilled, mocks.mutators)).toMatchSnapshot()
})
it('should be able to define agent mutators', () => {
const mutator = { foo: 'bar' }
transform.mutators = mutator
expect(transform(mocks.defs.simple, mocks.fulfilled)).toMatchSnapshot()
expect(transform.mutators).toEqual(mutator)
})
it('should be able to define keys declaratively', () => {
transform.keys = keys
expect(transform.keys).toEqual(keys)
})
})
|
/* global describe, it, expect */
import { filterByKeys, transform } from '../src/transform'
import * as mocks from './mocks'
describe('Transform suite', () => {
it('should filter by keys two objects', () => {
const keys = Object.keys(mocks.defs.simple)
expect(filterByKeys(keys, mocks.defs.complex)).toEqual(mocks.defs.simple)
})
it('should transform a definition into a fulfilled object', () => {
expect(transform(mocks.defs.simple, mocks.fulfilled)).toEqual(mocks.fulfilled)
})
it('should transform a definition using mutators', () => {
expect(transform(mocks.defs.simple, mocks.fulfilled, mocks.mutators)).toMatchSnapshot()
})
it('should be able to define agent mutators', () => {
transform.mutators = { foo: 'bar' }
expect(transform(mocks.defs.simple, mocks.fulfilled)).toMatchSnapshot()
})
})
|
Clarify something in the docs.
|
package com.raoulvdberge.refinedstorage.api.storage.externalstorage;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import javax.annotation.Nonnull;
import java.util.function.Supplier;
/**
* Provides an external storage handler to the external storage block.
*
* @param <T>
*/
public interface IExternalStorageProvider<T> {
/**
* @param tile the tile
* @param direction the direction of the external storage
* @return true if the provider can provide, false otherwise
*/
boolean canProvide(TileEntity tile, EnumFacing direction);
/**
* @param context the context of the external storage
* @param tile the tile supplier
* @param direction the direction of the external storage
* @return the external storage handler
*/
@Nonnull
IStorageExternal<T> provide(IExternalStorageContext context, Supplier<TileEntity> tile, EnumFacing direction);
/**
* Returns the priority of this external storage provider.
* The one with the highest priority is chosen.
* Refined Storage's default handlers for {@link net.minecraftforge.items.IItemHandler} and {@link net.minecraftforge.fluids.capability.IFluidHandler} return 0.
* This value can't be dynamic (only fixed), since the sorted order is cached.
*
* @return the priority
*/
int getPriority();
}
|
package com.raoulvdberge.refinedstorage.api.storage.externalstorage;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import javax.annotation.Nonnull;
import java.util.function.Supplier;
/**
* Provides an external storage handler to the external storage block.
*
* @param <T>
*/
public interface IExternalStorageProvider<T> {
/**
* @param tile the tile
* @param direction the direction of the external storage
* @return true if the provider can provide, false otherwise
*/
boolean canProvide(TileEntity tile, EnumFacing direction);
/**
* @param context the context of the external storage
* @param tile the tile supplier
* @param direction the direction of the external storage
* @return the external storage handler
*/
@Nonnull
IStorageExternal<T> provide(IExternalStorageContext context, Supplier<TileEntity> tile, EnumFacing direction);
/**
* Returns the priority of this external storage provider.
* The one with the highest priority is chosen.
* Refined Storage's default handlers for {@link net.minecraftforge.items.IItemHandler} and {@link net.minecraftforge.fluids.capability.IFluidHandler} return 0.
*
* @return the priority
*/
int getPriority();
}
|
Add a todo for statsd gauges.
|
// Copyright 2015 Google Inc. All Rights Reserved.
// This file is available under the Apache license.
package exporter
import (
"expvar"
"flag"
"fmt"
"github.com/google/mtail/metrics"
)
var (
statsdHostPort = flag.String("statsd_hostport", "",
"Host:port to statsd server to write metrics to.")
statsdExportTotal = expvar.NewInt("statsd_export_total")
statsdExportSuccess = expvar.NewInt("statsd_export_success")
)
func metricToStatsd(hostname string, m *metrics.Metric, l *metrics.LabelSet) string {
// TODO(jaq): handle units better, send timing as |ms
m.RLock()
defer m.RUnlock()
// TODO(jaq): handle gauge types
return fmt.Sprintf("%s.%s:%d|c",
m.Program,
formatLabels(m.Name, l.Labels, ".", "."),
l.Datum.Get())
}
|
// Copyright 2015 Google Inc. All Rights Reserved.
// This file is available under the Apache license.
package exporter
import (
"expvar"
"flag"
"fmt"
"github.com/google/mtail/metrics"
)
var (
statsdHostPort = flag.String("statsd_hostport", "",
"Host:port to statsd server to write metrics to.")
statsdExportTotal = expvar.NewInt("statsd_export_total")
statsdExportSuccess = expvar.NewInt("statsd_export_success")
)
func metricToStatsd(hostname string, m *metrics.Metric, l *metrics.LabelSet) string {
// TODO(jaq): handle units better, send timing as |ms
m.RLock()
defer m.RUnlock()
return fmt.Sprintf("%s.%s:%d|c",
m.Program,
formatLabels(m.Name, l.Labels, ".", "."),
l.Datum.Get())
}
|
Update test to run only against sdk 23, since the new method doesn't exist on older versions of android and the tests are compiled against the latest version of the sdk. The test still fails because it is missing
|
// Copyright 2015 Google Inc. All Rights Reserved.
package org.robolectric.shadows;
import android.os.Build;
import android.text.format.DateUtils;
import libcore.icu.DateIntervalFormat;
import android.icu.util.TimeZone;
import android.icu.util.ULocale;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.TestRunners;
import org.robolectric.annotation.Config;
import java.util.Calendar;
import static org.junit.Assert.assertEquals;
@RunWith(TestRunners.MultiApiWithDefaults.class)
@Config(sdk = {
Build.VERSION_CODES.M })
public class ShadowDateIntervalFormatTest {
@Test
public void testDateInterval_FormatDateRange() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2013);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 20);
long timeInMillis = calendar.getTimeInMillis();
String actual = DateIntervalFormat.formatDateRange(ULocale.getDefault(), TimeZone.getDefault(), timeInMillis, timeInMillis, DateUtils.FORMAT_NUMERIC_DATE);
assertEquals("1/20/2013", actual);
}
}
|
// Copyright 2015 Google Inc. All Rights Reserved.
package org.robolectric.shadows;
import android.os.Build;
import android.text.format.DateUtils;
import libcore.icu.DateIntervalFormat;
import android.icu.util.TimeZone;
import android.icu.util.ULocale;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.TestRunners;
import org.robolectric.annotation.Config;
import java.util.Calendar;
import static org.junit.Assert.assertEquals;
@RunWith(TestRunners.MultiApiWithDefaults.class)
@Config(sdk = {
Build.VERSION_CODES.KITKAT,
Build.VERSION_CODES.LOLLIPOP })
public class ShadowDateIntervalFormatTest {
@Test
public void testDateInterval_FormatDateRange() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2013);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 20);
long timeInMillis = calendar.getTimeInMillis();
String actual = DateIntervalFormat.formatDateRange(ULocale.getDefault(), TimeZone.getDefault(), timeInMillis, timeInMillis, DateUtils.FORMAT_NUMERIC_DATE);
assertEquals("1/20/2013", actual);
}
}
|
Remove the static pin fir analog read
|
#Creating a key value store for all the urls
BASE_URL = 'http://cloud.boltiot.com/remote/'
url_list = {
'digitalWrite' : '{}/digitalWrite?pin={}&state={}&deviceName={}',
'digitalRead' : '{}/digitalRead?pin={}&deviceName={}',
'analogWrite' : '{}/analogWrite?pin={}&value={}&deviceName={}',
'analogRead' : '{}/analogRead?pin={}&deviceName={}',
'serialBegin' : '{}/serialBegin?baud={}&deviceName={}',
'serialWrite' : '{}/serialWrite?data={}&deviceName={}',
'serialRead' : '{}/serialRead?till={}&deviceName={}',
'version' : '{}/version?&deviceName={}',
'restart' : '{}/restart?&deviceName={}',
'isAlive' : '{}/isAlive?&deviceName={}',
}
def url(operation):
return BASE_URL+url_list[operation]
|
#Creating a key value store for all the urls
BASE_URL = 'http://cloud.boltiot.com/remote/'
url_list = {
'digitalWrite' : '{}/digitalWrite?pin={}&state={}&deviceName={}',
'digitalRead' : '{}/digitalRead?pin={}&deviceName={}',
'analogWrite' : '{}/analogWrite?pin=1&value={}&state={}&deviceName={}',
'analogRead' : '{}/analogRead?pin={}&deviceName={}',
'serialBegin' : '{}/serialBegin?baud={}&deviceName={}',
'serialWrite' : '{}/serialWrite?data={}&deviceName={}',
'serialRead' : '{}/serialRead?till={}&deviceName={}',
'version' : '{}/version?&deviceName={}',
'restart' : '{}/restart?&deviceName={}',
'isAlive' : '{}/isAlive?&deviceName={}',
}
def url(operation):
return BASE_URL+url_list[operation]
|
Fix system.setting does not exist
Signed-off-by: SamPoyigi <f16bed56189e249fe4ca8ed10a1ecae60e8ceac0@sampoyigi.com>
|
<?php
namespace Igniter\Flame\Setting;
use Igniter\Flame\Setting\Middleware\SaveSetting;
use Illuminate\Support\ServiceProvider;
class SettingServiceProvider extends ServiceProvider
{
protected $defer = TRUE;
/**
* Register the service provider.
* @return void
*/
public function register()
{
$this->registerManager();
$this->registerStores();
$this->app->singleton(SaveSetting::class);
}
protected function registerManager()
{
$this->app->singleton('setting.manager', function ($app) {
return new SettingManager($app);
});
}
protected function registerStores()
{
$this->app->singleton('system.setting', function ($app) {
return $app['setting.manager']->driver();
});
$this->app->singleton('system.parameter', function ($app) {
return $app['setting.manager']->driver('prefs');
});
}
public function provides()
{
return ['setting.manager', 'system.setting', 'system.parameter', SaveSetting::class];
}
}
|
<?php
namespace Igniter\Flame\Setting;
use Igniter\Flame\Setting\Middleware\SaveSetting;
use Illuminate\Support\ServiceProvider;
class SettingServiceProvider extends ServiceProvider
{
protected $defer = TRUE;
/**
* Register the service provider.
* @return void
*/
public function register()
{
$this->registerManager();
$this->registerStores();
$this->app->singleton(SaveSetting::class);
}
protected function registerManager()
{
$this->app->singleton('setting.manager', function ($app) {
return new SettingManager($app);
});
}
protected function registerStores()
{
$this->app->singleton('system.setting', function ($app) {
return $app['setting.manager']->driver();
});
$this->app->singleton('system.parameter', function ($app) {
return $app['setting.manager']->driver('prefs');
});
}
}
|
Make sure we don't miss "low" confidence warnings
git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@14961 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
|
package sfBugsNew;
import edu.umd.cs.findbugs.annotations.Confidence;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;
public class Bug1219 {
interface A {
}
interface B {
}
interface C {
}
interface D {
}
static class CC implements C {}
static class DC implements D {}
A objectA;
@NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
@ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.LOW)
public boolean compare(B objectB) {
return (objectA == objectB);
}
@NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
@ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.LOW)
public boolean compare(C objectC) {
return (objectA == objectC);
}
@ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
public static boolean compare(C objectC, D objectD) {
return (objectC == objectD);
}
}
|
package sfBugsNew;
import edu.umd.cs.findbugs.annotations.Confidence;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;
public class Bug1219 {
interface A {
}
interface B {
}
interface C {
}
interface D {
}
static class CC implements C {}
static class DC implements D {}
A objectA;
@NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
public boolean compare(B objectB) {
return (objectA == objectB);
}
@NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
public boolean compare(C objectC) {
return (objectA == objectC);
}
@ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
public static boolean compare(C objectC, D objectD) {
return (objectC == objectD);
}
}
|
Fix spacing between month names
|
Datepicker.language['pt-br'] = {
days: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
daysShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
daysMin: ['Do', 'Se', 'Te', 'Qu', 'Qu', 'Se', 'Sa'],
months: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
monthsShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
today: 'Hoje',
clear: 'Limpar',
dateFormat: 'dd/mm/yyyy',
firstDay: 0
};
|
Datepicker.language['pt-br'] = {
days: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
daysShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
daysMin: ['Do', 'Se', 'Te', 'Qu', 'Qu', 'Se', 'Sa'],
months: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho', 'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
monthsShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
today: 'Hoje',
clear: 'Limpar',
dateFormat: 'dd/mm/yyyy',
firstDay: 0
};
|
Fix a typo that make the setup fail for localfs
|
<?php
/**
* Interface for the file system models.
*
* This defines the interface for any model that wants to interact with a remote file system.
* @author Jaisen Mathai <jaisen@jmathai.com>
*/
interface FileSystemInterface
{
public function deletePhoto($id);
public function getPhoto($filename);
public function putPhoto($localFile, $remoteFile);
public function putPhotos($files);
public function getHost();
public function initialize();
}
/**
* The public interface for instantiating a file system obect.
* This returns the appropriate type of object by reading the config.
* Accepts a set of params that must include a type and targetType
*
* @param string $type Optional type parameter which defines the type of file system.
* @return object A file system object that implements FileSystemInterface
*/
function getFs(/*$type*/)
{
static $filesystem, $type;
if($filesystem)
return $filesystem;
if(func_num_args() == 1)
$type = func_get_arg(0);
// load configs only once
if(!$type)
$type = getConfig()->get('systems')->fileSystem;
switch($type)
{
case 'S3':
$filesystem = new FileSystemS3();
break;
case 'LocalFs':
$filesystem = new FileSystemLocal();
break;
}
if($filesystem)
return $filesystem;
throw new Exception("FileSystem Provider {$type} does not exist", 404);
}
|
<?php
/**
* Interface for the file system models.
*
* This defines the interface for any model that wants to interact with a remote file system.
* @author Jaisen Mathai <jaisen@jmathai.com>
*/
interface FileSystemInterface
{
public function deletePhoto($id);
public function getPhoto($filename);
public function putPhoto($localFile, $remoteFile);
public function putPhotos($files);
public function getHost();
public function initialize();
}
/**
* The public interface for instantiating a file system obect.
* This returns the appropriate type of object by reading the config.
* Accepts a set of params that must include a type and targetType
*
* @param string $type Optional type parameter which defines the type of file system.
* @return object A file system object that implements FileSystemInterface
*/
function getFs(/*$type*/)
{
static $filesystem, $type;
if($filesystem)
return $filesystem;
if(func_num_args() == 1)
$type = func_get_arg(0);
// load configs only once
if(!$type)
$type = getConfig()->get('systems')->fileSystem;
switch($type)
{
case 'S3':
$filesystem = new FileSystemS3();
break;
case 'localfs':
$filesystem = new FileSystemLocal();
break;
}
if($filesystem)
return $filesystem;
throw new Exception("FileSystem Provider {$type} does not exist", 404);
}
|
Fix error in telemetry task
A condition had been changed to always match for debugging purposes, and
was accidentally committed that way.
|
from django.core.cache import cache
from celery.utils.log import get_task_logger
from enhydris.celery import app
from enhydris.telemetry.models import Telemetry
FETCH_TIMEOUT = 300
LOCK_TIMEOUT = FETCH_TIMEOUT + 60
logger = get_task_logger(__name__)
@app.task
def fetch_all_telemetry_data():
for telemetry in Telemetry.objects.all():
if telemetry.is_due:
fetch_telemetry_data.delay(telemetry.id)
@app.task(bind=True, soft_time_limit=FETCH_TIMEOUT, time_limit=FETCH_TIMEOUT + 10)
def fetch_telemetry_data(self, telemetry_id):
telemetry = Telemetry.objects.get(id=telemetry_id)
lock_id = f"telemetry-{telemetry_id}"
acquired_lock = cache.add(lock_id, self.app.oid, LOCK_TIMEOUT)
if acquired_lock:
telemetry.fetch()
cache.delete(lock_id)
else:
lock_owner = cache.get(lock_id)
logger.error(
f"Cannot acquire lock for fetching telemetry with id={telemetry.id}; "
f"apparently the lock is owned by {lock_owner}."
)
|
from django.core.cache import cache
from celery.utils.log import get_task_logger
from enhydris.celery import app
from enhydris.telemetry.models import Telemetry
FETCH_TIMEOUT = 300
LOCK_TIMEOUT = FETCH_TIMEOUT + 60
logger = get_task_logger(__name__)
@app.task
def fetch_all_telemetry_data():
for telemetry in Telemetry.objects.all():
if True:
fetch_telemetry_data.delay(telemetry.id)
@app.task(bind=True, soft_time_limit=FETCH_TIMEOUT, time_limit=FETCH_TIMEOUT + 10)
def fetch_telemetry_data(self, telemetry_id):
telemetry = Telemetry.objects.get(id=telemetry_id)
lock_id = f"telemetry-{telemetry_id}"
acquired_lock = cache.add(lock_id, self.app.oid, LOCK_TIMEOUT)
if acquired_lock:
telemetry.fetch()
cache.delete(lock_id)
else:
lock_owner = cache.get(lock_id)
logger.error(
f"Cannot acquire lock for fetching telemetry with id={telemetry.id}; "
f"apparently the lock is owned by {lock_owner}."
)
|
Move sleep call to begining of loop
|
<?php
define("SECONDS_BETWEEN_ALERTS", rand(10, 60));
$alerts = array(
"Coldest Air of the Season Sweeping Through Central and Southern States",
"Belgium on 'high alert'",
"Multiple raids in Brussels as police seek ISIS terrorists",
"Syria fighters may be fueled by amphetamines",
"Alien invasion? Strange sightings in Hong Kong",
"Experts criticise WHO delay in sounding alarm over Ebola outbreak"
);
date_default_timezone_set("Europe/Madrid");
header("Content-Type: text/event-stream\n\n");
while (true) {
sleep(SECONDS_BETWEEN_ALERTS);
sendAlert($alerts[rand(0, 5)]);
ob_end_flush();
flush();
}
function sendAlert($message) {
$date = date_create();
$timestamp = date_timestamp_get($date);
echo "data: { \"message\": \"$message\", \"timestamp\": $timestamp }\n\n";
}
?>
|
<?php
define("SECONDS_BETWEEN_ALERTS", rand(10, 60));
$alerts = array(
"Coldest Air of the Season Sweeping Through Central and Southern States",
"Belgium on 'high alert'",
"Multiple raids in Brussels as police seek ISIS terrorists",
"Syria fighters may be fueled by amphetamines",
"Alien invasion? Strange sightings in Hong Kong",
"Experts criticise WHO delay in sounding alarm over Ebola outbreak"
);
date_default_timezone_set("Europe/Madrid");
header("Content-Type: text/event-stream\n\n");
while (true) {
sendAlert($alerts[rand(0, 5)]);
ob_end_flush();
flush();
sleep(SECONDS_BETWEEN_ALERTS);
}
function sendAlert($message) {
$date = date_create();
$timestamp = date_timestamp_get($date);
echo "data: { \"message\": \"$message\", \"timestamp\": $timestamp }\n\n";
}
?>
|
Modify pyauto test ChromeosPrivateViewTest to use 2.2.28 data file.
BUG=none
TEST=This is a test.
Review URL: https://chromiumcodereview.appspot.com/10389084
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@136454 0039d316-1c4b-4281-b951-d872f2087c98
|
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import pyauto_functional # must be imported before pyauto
import pyauto
class ChromeosPrivateViewTest(pyauto.PyUITest):
"""Basic tests for ChromeOS Private View.
Requires ChromeOS to be logged in.
"""
def _GetExtensionInfoById(self, extensions, id):
for x in extensions:
if x['id'] == id:
return x
return None
def testInstallPrivateViewExtension(self):
"""Basic installation test for Private View on ChromeOS."""
crx_file_path = os.path.abspath(
os.path.join(self.DataDir(), 'pyauto_private', 'apps',
'privateview-chrome-2.2.28_RELEASE.crx'))
ext_id = self.InstallExtension(crx_file_path)
self.assertTrue(ext_id, 'Failed to install extension.')
extension = self._GetExtensionInfoById(self.GetExtensionsInfo(), ext_id)
self.assertTrue(extension['is_enabled'],
msg='Extension was not enabled on installation')
self.assertFalse(extension['allowed_in_incognito'],
msg='Extension was allowed in incognito on installation.')
if __name__ == '__main__':
pyauto_functional.Main()
|
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import pyauto_functional # must be imported before pyauto
import pyauto
class ChromeosPrivateViewTest(pyauto.PyUITest):
"""Basic tests for ChromeOS Private View.
Requires ChromeOS to be logged in.
"""
def _GetExtensionInfoById(self, extensions, id):
for x in extensions:
if x['id'] == id:
return x
return None
def testInstallPrivateViewExtension(self):
"""Basic installation test for Private View on ChromeOS."""
crx_file_path = os.path.abspath(
os.path.join(self.DataDir(), 'pyauto_private', 'apps',
'privateview-chrome-1.0.800_RELEASE.crx'))
ext_id = self.InstallExtension(crx_file_path)
self.assertTrue(ext_id, 'Failed to install extension.')
extension = self._GetExtensionInfoById(self.GetExtensionsInfo(), ext_id)
self.assertTrue(extension['is_enabled'],
msg='Extension was not enabled on installation')
self.assertFalse(extension['allowed_in_incognito'],
msg='Extension was allowed in incognito on installation.')
if __name__ == '__main__':
pyauto_functional.Main()
|
Change to use boxed type
|
/*-
* Copyright 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.dawnsci.analysis.api.processing;
import java.util.List;
/**
* Interface to set up an operation processing run
*/
public interface IOperationBean {
public void setDataKey(String dataKey);
public void setFilePath(String filePath);
public String getFilePath();
public void setOutputFilePath(String outputFilePath);
public String getOutputFilePath();
public void setDatasetPath(String datasetPath);
public void setSlicing(String slicing);
public void setProcessingPath(String processingPath);
public void setAxesNames(List<String>[] axesNames);
public void setDeleteProcessingFile(boolean deleteProcessingFile);
public void setXmx(String xmx);
public void setDataDimensions(int[] dataDimensions);
public void setScanRank(Integer scanRank);
public void setReadable(boolean readable);
public void setName(String name);
public void setRunDirectory(String runDirectory);
public void setNumberOfCores(int numberOfCores);
}
|
/*-
* Copyright 2016 Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.dawnsci.analysis.api.processing;
import java.util.List;
/**
* Interface to set up an operation processing run
*/
public interface IOperationBean {
public void setDataKey(String dataKey);
public void setFilePath(String filePath);
public String getFilePath();
public void setOutputFilePath(String outputFilePath);
public String getOutputFilePath();
public void setDatasetPath(String datasetPath);
public void setSlicing(String slicing);
public void setProcessingPath(String processingPath);
public void setAxesNames(List<String>[] axesNames);
public void setDeleteProcessingFile(boolean deleteProcessingFile);
public void setXmx(String xmx);
public void setDataDimensions(int[] dataDimensions);
public void setScanRank(int scanRank);
public void setReadable(boolean readable);
public void setName(String name);
public void setRunDirectory(String runDirectory);
public void setNumberOfCores(int numberOfCores);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.