text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix byContractName to support either name name
const Config = require("truffle-config"); const expect = require("truffle-expect"); const Resolver = require("truffle-resolver"); const Artifactor = require("truffle-artifactor"); function prepareConfig(options) { expect.options(options, ["contracts_build_directory"]); expect.one(options, ["contracts_directory", "files"]); // Use a config object to ensure we get the default sources. const config = Config.default().merge(options); config.compilersInfo = {}; if (!config.resolver) config.resolver = new Resolver(config); if (!config.artifactor) { config.artifactor = new Artifactor(config.contracts_build_directory); } return config; } function multiPromisify(func) { return (...args) => new Promise((accept, reject) => { const callback = (err, ...results) => { if (err) reject(err); accept(results); }; func(...args, callback); }); } function byContractName(contracts) { return contracts .map(contract => ({ [contract.contractName || contract.contract_name]: contract })) .reduce((a, b) => Object.assign({}, a, b), {}); } module.exports = { prepareConfig, multiPromisify, byContractName };
const Config = require("truffle-config"); const expect = require("truffle-expect"); const Resolver = require("truffle-resolver"); const Artifactor = require("truffle-artifactor"); function prepareConfig(options) { expect.options(options, ["contracts_build_directory"]); expect.one(options, ["contracts_directory", "files"]); // Use a config object to ensure we get the default sources. const config = Config.default().merge(options); config.compilersInfo = {}; if (!config.resolver) config.resolver = new Resolver(config); if (!config.artifactor) { config.artifactor = new Artifactor(config.contracts_build_directory); } return config; } function multiPromisify(func) { return (...args) => new Promise((accept, reject) => { const callback = (err, ...results) => { if (err) reject(err); accept(results); }; func(...args, callback); }); } function byContractName(contracts) { return contracts .map(contract => ({ [contract.contractName]: contract })) .reduce((a, b) => Object.assign({}, a, b), {}); } module.exports = { prepareConfig, multiPromisify, byContractName };
Change ttl_skew to 50%, to allow a task to run twice before riemann notices that it never checked in.
import time import logging log = logging.getLogger(__name__) class TaskSchedule(): def __init__(self): self.tasks = [] log.debug("TaskSchedule created") def add(self, task, ttl_skew=0.5): offset = ((ttl_skew * task.ttl) - task.skew()) log.info("Scheduling '%s' for %ss from now" % (task.name, offset)) if task.skew() > (task.ttl * ttl_skew): log.warning("Task skew of %s is > %s%% of TTL(%s) for '%s'" % (task.skew(), (ttl_skew*100), task.ttl, task.name)) else: log.debug("Task skew for '%s' is %s" % ( task.name, task.skew())) deadline = time.time() + offset self.tasks.append((task, deadline)) def update(self): self.tasks.sort(key=lambda task: task[1], reverse=True) def next(self): task, deadline = self.tasks.pop() log.info("Next task is '%s' scheduled to run in %ss" % (task.name, deadline-time.time())) return (task, deadline) def ready(self, deadline, grace=1.1): now = time.time() return (deadline - now) < grace def waiting(self): self.update() return len([t for t in self.tasks if self.ready(t[1])])
import time import logging log = logging.getLogger(__name__) class TaskSchedule(): def __init__(self): self.tasks = [] log.debug("TaskSchedule created") def add(self, task, ttl_skew=0.8): offset = ((ttl_skew * task.ttl) - task.skew()) log.info("Scheduling '%s' for %ss from now" % (task.name, offset)) if task.skew() > (task.ttl * 0.5): log.warning("Task skew of %s is > 50%% of TTL(%s) for '%s'" % (task.skew(), task.ttl, task.name)) else: log.debug("Task skew for '%s' is %s" % ( task.name, task.skew())) deadline = time.time() + offset self.tasks.append((task, deadline)) def update(self): self.tasks.sort(key=lambda task: task[1], reverse=True) def next(self): task, deadline = self.tasks.pop() log.info("Next task is '%s' scheduled to run in %ss" % (task.name, deadline-time.time())) return (task, deadline) def ready(self, deadline, grace=1.1): now = time.time() return (deadline - now) < grace def waiting(self): self.update() return len([t for t in self.tasks if self.ready(t[1])])
Disable setting thread_name_prefix in ThreadPoolExecutor (only supported in Python >= 3.6)
import os, queue, concurrent.futures class ThreadPoolExecutor(concurrent.futures.ThreadPoolExecutor): """ThreadPoolExecutor which allows setting max. work queue size""" def __init__(self, max_workers=0, thread_name_prefix='', max_queue_size=0): #super().__init__(max_workers or os.cpu_count() or 1, thread_name_prefix) super().__init__(max_workers or os.cpu_count() or 1) self.max_queue_size = max_queue_size or self._max_workers * 10 if self.max_queue_size > 0: self._work_queue = queue.Queue(self.max_queue_size) self.max_queue_size_reached = 0 def submit(self, fn, *args, **kwargs): """Submits a callable to be executed with the given arguments. Count maximum reached work queue size in ThreadPoolExecutor.max_queue_size_reached. """ future = super().submit(fn, *args, **kwargs) work_queue_size = self._work_queue.qsize() if work_queue_size > self.max_queue_size_reached: self.max_queue_size_reached = work_queue_size return future
import os, queue, concurrent.futures class ThreadPoolExecutor(concurrent.futures.ThreadPoolExecutor): """ThreadPoolExecutor which allows setting max. work queue size""" def __init__(self, max_workers=0, thread_name_prefix='', max_queue_size=0): super().__init__(max_workers or os.cpu_count() or 1, thread_name_prefix) self.max_queue_size = max_queue_size or self._max_workers * 10 if self.max_queue_size > 0: self._work_queue = queue.Queue(self.max_queue_size) self.max_queue_size_reached = 0 def submit(self, fn, *args, **kwargs): """Submits a callable to be executed with the given arguments. Count maximum reached work queue size in ThreadPoolExecutor.max_queue_size_reached. """ future = super().submit(fn, *args, **kwargs) work_queue_size = self._work_queue.qsize() if work_queue_size > self.max_queue_size_reached: self.max_queue_size_reached = work_queue_size return future
Make sure 'end' is dispatched only once
var stream = require('stream') function BufferStream(source, encoding, options) { stream.Duplex.call(this, options) this.__buffer = typeof source === 'string' || source instanceof Buffer ? new Buffer(source, encoding) : new Buffer(0) this.__cursor = 0 } BufferStream.prototype = new stream.Duplex() BufferStream.prototype.constructor = BufferStream BufferStream.prototype._read = function (size) { if (this.__cursor === this.__buffer.length) { this.push(null) return } var chunk = this.__buffer.slice(this.__cursor, size) this.__cursor += chunk.length this.push(chunk) } BufferStream.prototype._write = function (chunk, encoding, callback) { try { this.__buffer = Buffer.concat([ this.__buffer, typeof chunk === 'string' ? new Buffer(chunk, encoding) : chunk ]) callback() } catch (error) { callback(error) } } module.exports = BufferStream // vim: et ts=2 sw=2
var stream = require('stream') function BufferStream(source, encoding, options) { stream.Duplex.call(this, options) this.__buffer = typeof source === 'string' || source instanceof Buffer ? new Buffer(source, encoding) : new Buffer(0) this.__cursor = 0 } BufferStream.prototype = new stream.Duplex() BufferStream.prototype.constructor = BufferStream BufferStream.prototype._read = function (size) { var chunk = this.__buffer.slice(this.__cursor, size) if (chunk.length > 0) { this.__cursor += chunk.length this.push(chunk) } if (this.__cursor === this.__buffer.length) { this.push(null) } } BufferStream.prototype._write = function (chunk, encoding, callback) { try { this.__buffer = Buffer.concat([ this.__buffer, typeof chunk === 'string' ? new Buffer(chunk, encoding) : chunk ]) callback() } catch (error) { callback(error) } } module.exports = BufferStream // vim: et ts=2 sw=2
Remove no-console rule from estlint configuration
module.exports = { root: true, env: { node: true, "jest/globals": true }, plugins: ["jest"], 'extends': [ 'plugin:vue/essential', '@vue/standard' ], rules: { 'no-console': 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'vue/no-use-v-if-with-v-for': 'off', 'jest/no-disabled-tests': 'warn', 'jest/no-focused-tests': 'error', 'jest/no-identical-title': 'error', 'jest/prefer-to-have-length': 'warn', 'jest/valid-expect': 'error' }, parserOptions: { parser: 'babel-eslint' } }
module.exports = { root: true, env: { node: true, "jest/globals": true }, plugins: ["jest"], 'extends': [ 'plugin:vue/essential', '@vue/standard' ], rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'vue/no-use-v-if-with-v-for': 'off', 'jest/no-disabled-tests': 'warn', 'jest/no-focused-tests': 'error', 'jest/no-identical-title': 'error', 'jest/prefer-to-have-length': 'warn', 'jest/valid-expect': 'error' }, parserOptions: { parser: 'babel-eslint' } }
Make the Install core plugin loadable
<?php use Cake\Core\Configure; use Cake\Core\Plugin; use Croogo\Croogo; require_once 'croogo_bootstrap.php'; if (Configure::read('Croogo.installed')) { return; } // Load Install plugin if (Configure::read('Security.salt') == 'f78b12a5c38e9e5c6ae6fbd0ff1f46c77a1e3' || Configure::read('Security.cipherSeed') == '60170779348589376') { $_securedInstall = false; } Configure::write('Install.secured', !isset($_securedInstall)); Configure::write('Croogo.installed', file_exists(APP . 'Config' . DS . 'database.php') && file_exists(APP . 'Config' . DS . 'settings.json') && file_exists(APP . 'Config' . DS . 'croogo.php') ); if (!Configure::read('Croogo.installed') || !Configure::read('Install.secured')) { Plugin::load('Croogo/Install', ['routes' => true, 'path' => Plugin::path('Croogo/Croogo') . '..' . DS . 'Install' . DS]); }
<?php use Cake\Core\Configure; use Cake\Core\Plugin; use Croogo\Croogo; require_once 'croogo_bootstrap.php'; if (Configure::read('Croogo.installed')) { return; } // Load Install plugin if (Configure::read('Security.salt') == 'f78b12a5c38e9e5c6ae6fbd0ff1f46c77a1e3' || Configure::read('Security.cipherSeed') == '60170779348589376') { $_securedInstall = false; } Configure::write('Install.secured', !isset($_securedInstall)); Configure::write('Croogo.installed', file_exists(APP . 'Config' . DS . 'database.php') && file_exists(APP . 'Config' . DS . 'settings.json') && file_exists(APP . 'Config' . DS . 'croogo.php') ); if (!Configure::read('Croogo.installed') || !Configure::read('Install.secured')) { Plugin::load('Install', array('routes' => true)); }
Store connection and missing self
try: from trello import TrelloCommand from output import Output except ImportError: from .trello import TrelloCommand from .output import Output class TrelloNotificationsCommand(TrelloCommand): def work(self, connection): self.options = [ { 'name': "Unread", 'action': self.show_unread }, { 'name': "Read all", 'action': self.read_all }, { 'name': "Exit", 'action': self.noop } ] self.show_quick_panel(self.items(), self.callback) self.connection = connection def items(self): return [option['name'] for option in self.options] def callback(self, index): option = self.options[index] if not option is None: option['action']() def show_unread(self): self.view.run_command("trello_unread_notifications") def read_all(self): pass def noop(self): pass class TrelloUnreadNotificationsCommand(TrelloCommand): def work(self, connection): member = connection.me output = Output.notifications(member.unread_notifications()) self.show_output_panel(output)
try: from trello import TrelloCommand from output import Output except ImportError: from .trello import TrelloCommand from .output import Output class TrelloNotificationsCommand(TrelloCommand): def work(self, connection): self.options = [ { 'name': "Unread", 'action': self.show_unread }, { 'name': "Read all", 'action': self.read_all }, { 'name': "Exit", 'action': self.noop } ] self.show_quick_panel(self.items(), self.callback) def items(self): return [option['name'] for option in self.options] def callback(self, index): option = self.options[index] if not option is None: option['action']() def show_unread(self): self.view.run_command("trello_unread_notifications") def read_all(): pass def noop(): pass class TrelloUnreadNotificationsCommand(TrelloCommand): def work(self, connection): member = connection.me output = Output.notifications(member.unread_notifications()) self.show_output_panel(output)
Use object notation to insert values to the db, looks nicer.
var request = require('request') var Q = require('Q') var xml2js = require('xml2js') var requestQ = function(url) { var defer = Q.defer() request(url, function(err, res, body) { if (err) { err.url = url return defer.reject(err) } return defer.resolve(body) }) return defer.promise } var parseRSS = function(string) { var defer = Q.defer() xml2js.parseString(string, function(err, data) { if (err) { return defer.reject(err) } return defer.resolve(data) }) return defer.promise } var add = function(db, url, group, title) { return requestQ(url).then(parseRSS).then(function(data) { var rss = data.rss.channel[0] var query = 'INSERT INTO Channels SET last_update = NOW() - 1, ?' var vals = { title: title || rss.title[0], group_id: group || 0, description: rss.description[0], ttl: (rss.ttl != null ? rss.ttl[0] : 5) * 60, url: url, link: rss.link[0] } console.log(vals) return db.query(query, vals) }) } module.exports = { add: add, parseRSS: parseRSS }
var request = require('request') var Q = require('Q') var xml2js = require('xml2js') var requestQ = function(url) { var defer = Q.defer() request(url, function(err, res, body) { if (err) { return defer.reject } return defer.resolve(body, res) }) return defer.promise } var parseRSS = function(string) { var defer = Q.defer() xml2js.parseString(string, function(err, data) { if (err) { return defer.reject(err) } return defer.resolve(data) }) return defer.promise } var add = function(db, url) { return requestQ(url).then(parseRSS).then(function(data) { var rss = data.rss.channel[0] var vals = [rss.title[0], rss.description[0], ((rss != null ? (ref$ = rss.ttl) != null ? ref$[0] : void 8 : void 8) || 30) * 60, url, rss.link[0]] var query = 'INSERT INTO Channels(title, description, ttl, url, link, last_update) VALUES(?, ?, ?, ?, ?, NOW() - 1)' return db.query(query, vals) }) } module.exports = { add: add, parseRSS: parseRSS }
Allow extended class to access $options
<?php namespace Phug\Util\Partial; trait OptionTrait { protected $options = []; public function getOptions() { return $this->options; } public function setOptions(array $options) { $this->options = array_replace($this->options, $options); return $this; } public function setOptionsRecursive(array $options) { $this->options = array_replace_recursive($this->options, $options); return $this; } public function getOption($name) { return $this->options[$name]; } public function setOption($name, $value) { $this->options[$name] = $value; return $this; } }
<?php namespace Phug\Util\Partial; trait OptionTrait { private $options = []; public function getOptions() { return $this->options; } public function setOptions(array $options) { $this->options = array_replace($this->options, $options); return $this; } public function setOptionsRecursive(array $options) { $this->options = array_replace_recursive($this->options, $options); return $this; } public function getOption($name) { return $this->options[$name]; } public function setOption($name, $value) { $this->options[$name] = $value; return $this; } }
Change to previous Char format
const bleno = require('bleno') const TestCharacteristic = require('./characteristics/test') const LightCharacteristic = require('./characteristics/light') const AntiTheftCharacteristic = require('./characteristics/antiTheft') const ids = require('../global/ble').bleIds const testCharacteristic = new TestCharacteristic() const lightCharacteristic = new LightCharacteristic() const antiTheftCharacteristic = new AntiTheftCharacteristic() const bikeService = new bleno.PrimaryService({ uuid: ids.get('SERVICE').uuid, characteristics: [ testCharacteristic, lightCharacteristic, antiTheftCharacteristic ] }); bleno.on('stateChange', function(state) { console.log('State changed to: ' + state) if (state === 'poweredOn') { bleno.startAdvertising(ids.get('PI').name, [ids.get('PI').uuid]) bleno.startAdvertising(ids.get('SERVICE').name, [bikeService.uuid]) } else { bleno.stopAdvertising() } }) bleno.on('advertisingStart', function(error) { console.log('Advertising started: ' + (error ? 'error ' + error : 'success')) if (!error) { bleno.setServices([bikeService]) console.log('Advertising ' + ids.get('SERVICE').name + ' with UUID ' + bikeService.uuid) } }) process.on('SIGTERM', function () { bleno.stopAdvertising() })
const bleno = require('bleno') const TestCharacteristic = require('./characteristics/test') const LightCharacteristic = require('./characteristics/light') const AntiTheftCharacteristic = require('./characteristics/antiTheft') const ids = require('../global/ble').bleIds const bikeService = new bleno.PrimaryService({ uuid: ids.get('SERVICE').uuid, characteristics: [ new TestCharacteristic(), new LightCharacteristic(), new AntiTheftCharacteristic() ] }); bleno.on('stateChange', function(state) { console.log('State changed to: ' + state) if (state === 'poweredOn') { bleno.startAdvertising(ids.get('PI').name, [ids.get('PI').uuid]) bleno.startAdvertising(ids.get('SERVICE').name, [bikeService.uuid]) } else { bleno.stopAdvertising() } }) bleno.on('advertisingStart', function(error) { console.log('Advertising started: ' + (error ? 'error ' + error : 'success')) if (!error) { bleno.setServices([bikeService]) console.log('Advertising ' + ids.get('SERVICE').name + ' with UUID ' + bikeService.uuid) } }) process.on('SIGTERM', function () { bleno.stopAdvertising() })
Load BrowserHistory adapter in production, HashHistory on webpack-dev-server
import React from 'react'; import ReactDOM from 'react-dom'; import {Router, Route} from 'react-router'; import AsyncProps from 'react-router/lib/experimental/AsyncProps'; const adapter = 'production' !== process.env.NODE_ENV ? 'HashHistory' : 'BrowserHistory'; let { history } = require('react-router/lib/' + adapter); var rootRoute = { component: AsyncProps, renderInitialLoad() { return <div>loading...</div> }, childRoutes: [{ path: '/', component: require('./components/master'), childRoutes: [ require('./components/routes/gettingstarted'), require('./components/routes/core'), require('./components/routes/components') ]} ] }; ReactDOM.render(( <Router routes={rootRoute} history={history} createElement={AsyncProps.createElement} /> ), document.getElementById('hotzone'));
import React from 'react'; import ReactDOM from 'react-dom'; import {Router, Route} from 'react-router'; import { history } from 'react-router/lib/HashHistory'; import AsyncProps from 'react-router/lib/experimental/AsyncProps'; var rootRoute = { component: AsyncProps, renderInitialLoad() { return <div>loading...</div> }, childRoutes: [{ path: '/', component: require('./components/master'), childRoutes: [ require('./components/routes/gettingstarted'), require('./components/routes/core'), require('./components/routes/components') ]} ] }; ReactDOM.render(( <Router routes={rootRoute} history={history} createElement={AsyncProps.createElement} /> ), document.getElementById('hotzone'));
Fix unnecessary type parameter hiding
package com.trello.navi2.rx; import android.support.annotation.NonNull; import com.trello.navi2.Event; import com.trello.navi2.Listener; import com.trello.navi2.NaviComponent; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.functions.Cancellable; final class NaviOnSubscribe<T> implements ObservableOnSubscribe<T>{ private final NaviComponent component; private final Event<T> event; NaviOnSubscribe(NaviComponent component, Event<T> event) { this.component = component; this.event = event; } @Override public void subscribe(final ObservableEmitter<T> emitter) throws Exception { EmitterListener listener = new EmitterListener(emitter); emitter.setCancellable(listener); component.addListener(event, listener); } class EmitterListener implements Listener<T>, Cancellable { private final ObservableEmitter<T> emitter; public EmitterListener(ObservableEmitter<T> emitter) { this.emitter = emitter; } @Override public void call(@NonNull T t) { emitter.onNext(t); } @Override public void cancel() throws Exception { component.removeListener(this); } } }
package com.trello.navi2.rx; import android.support.annotation.NonNull; import com.trello.navi2.Event; import com.trello.navi2.Listener; import com.trello.navi2.NaviComponent; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.functions.Cancellable; final class NaviOnSubscribe<T> implements ObservableOnSubscribe<T>{ private final NaviComponent component; private final Event<T> event; NaviOnSubscribe(NaviComponent component, Event<T> event) { this.component = component; this.event = event; } @Override public void subscribe(final ObservableEmitter<T> emitter) throws Exception { EmitterListener<T> listener = new EmitterListener<>(emitter); emitter.setCancellable(listener); component.addListener(event, listener); } class EmitterListener<T> implements Listener<T>, Cancellable { private final ObservableEmitter<T> emitter; public EmitterListener(ObservableEmitter<T> emitter) { this.emitter = emitter; } @Override public void call(@NonNull T t) { emitter.onNext(t); } @Override public void cancel() throws Exception { component.removeListener(this); } } }
Fix bug where the service was added as a destination one time too many.
""" Output an Eliot message to a log file using the threaded log writer. """ from __future__ import unicode_literals, print_function from twisted.internet.task import react from eliot.logwriter import ThreadedFileWriter from eliot import Message, Logger _logger = Logger() def main(reactor): print("Logging to example-eliot.log...") logWriter = ThreadedFileWriter(open("example-eliot.log", "ab"), reactor) # Manually start the service, which will add it as a # destination. Normally we'd register ThreadedFileWriter with the usual # Twisted Service/Application infrastructure. logWriter.startService() # Log a message: Message.new(value="hello", another=1).write(_logger) # Manually stop the service. done = logWriter.stopService() return done if __name__ == '__main__': react(main, [])
""" Output an Eliot message to a log file using the threaded log writer. """ from __future__ import unicode_literals, print_function from twisted.internet.task import react from eliot.logwriter import ThreadedFileWriter from eliot import Message, Logger, addDestination _logger = Logger() def main(reactor): print("Logging to example-eliot.log...") logWriter = ThreadedFileWriter(open("example-eliot.log", "ab"), reactor) addDestination(logWriter) # Manually start the service. Normally we'd register ThreadedFileWriter # with the usual Twisted Service/Application infrastructure. logWriter.startService() # Log a message: Message.new(value="hello", another=1).write(_logger) # Manually stop the service. done = logWriter.stopService() return done if __name__ == '__main__': react(main, [])
Fix site bar decorate example - specify correct accessors and pad x-domain
var width = 500, height = 250; var container = d3.select('#decorate-bars') .append('svg') .attr({'width': width, 'height': height}); var dataGenerator = fc.data.random.financial() .startDate(new Date(2014, 1, 1)); var data = dataGenerator(20); var xScale = fc.scale.dateTime() .domain(fc.util.extent().fields('date').pad(0.1)(data)) .range([0, width]); var yScale = d3.scale.linear() .domain(fc.util.extent().fields(['high', 'low'])(data)) .range([height, 0]); //START var color = d3.scale.category10(); var bar = fc.series.bar() .xScale(xScale) .yScale(yScale) .xValue(function(d) { return d.date; }) .yValue(function(d) { return d.close; }) .decorate(function(s) { s.enter() .select('.bar > path') .style('fill', function(d, i) { return color(i); }); }); //END container.append('g') .datum(data) .call(bar);
var width = 500, height = 250; var container = d3.select('#decorate-bars') .append('svg') .attr({'width': width, 'height': height}); var dataGenerator = fc.data.random.financial() .startDate(new Date(2014, 1, 1)); var data = dataGenerator(20); var xScale = fc.scale.dateTime() .domain(fc.util.extent().fields('date')(data)) .range([0, width]); var yScale = d3.scale.linear() .domain(fc.util.extent().fields(['high', 'low'])(data)) .range([height, 0]); //START var color = d3.scale.category10(); var bar = fc.series.bar() .xScale(xScale) .yScale(yScale) .decorate(function(s) { s.enter() .select('.bar > path') .style('fill', function(d, i) { return color(i); }); }); //END container.append('g') .datum(data) .call(bar);
Drop threadmarks table when uninstalling
<?php class Sidane_Threadmarks_Install { public static function install($existingAddOn, $addOnData) { if ($existingAddOn['version_id'] > 1) { return; } $db = XenForo_Application::get('db'); $db->query(" CREATE TABLE IF NOT EXISTS threadmarks ( threadmark_id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, thread_id INT UNSIGNED NOT NULL, post_id INT UNSIGNED NOT NULL, label VARCHAR(100) NOT NULL, KEY thread_id (thread_id) ) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci "); try { $db->query("ALTER TABLE xf_thread ADD COLUMN has_threadmarks INT UNSIGNED DEFAULT 0 NOT NULL AFTER prefix_id"); } catch (Zend_Db_Exception $e) {} } public static function uninstall() { $db = XenForo_Application::get('db'); $db->query("ALTER TABLE xf_thread DROP COLUMN has_threadmarks"); $db->query("DROP TABLE threadmarks"); } } ?>
<?php class Sidane_Threadmarks_Install { public static function install($existingAddOn, $addOnData) { if ($existingAddOn['version_id'] > 1) { return; } $db = XenForo_Application::get('db'); $db->query(" CREATE TABLE IF NOT EXISTS threadmarks ( threadmark_id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, thread_id INT UNSIGNED NOT NULL, post_id INT UNSIGNED NOT NULL, label VARCHAR(100) NOT NULL, KEY thread_id (thread_id) ) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci "); try { $db->query("ALTER TABLE xf_thread ADD COLUMN has_threadmarks INT UNSIGNED DEFAULT 0 NOT NULL AFTER prefix_id"); } catch (Zend_Db_Exception $e) {} } public static function uninstall() { $db = XenForo_Application::get('db'); $db->query("ALTER TABLE xf_thread DROP COLUMN has_threadmarks"); } } ?>
tests/login: Use Polly.js instead of Pretender
import { module, test } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import { visit, click } from '@ember/test-helpers'; import { setupPolly } from 'skylines/tests/helpers/setup-polly'; module('Acceptance | login', function(hooks) { setupApplicationTest(hooks); setupPolly(hooks, { recordIfMissing: false }); const LOGIN_DROPDOWN = '[data-test-login-dropdown]'; const LOGIN_DROPDOWN_TOGGLE = `${LOGIN_DROPDOWN} a`; const LOGIN_EMAIL = '[data-test-input="login-email"]'; test('login dropdown form stays visible when fields are focused', async function(assert) { await visit('/'); await click(LOGIN_DROPDOWN_TOGGLE); assert.dom(LOGIN_DROPDOWN).hasClass('open'); await click(LOGIN_EMAIL); assert.dom(LOGIN_DROPDOWN).hasClass('open'); }); });
import { module, test } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import { visit, click } from '@ember/test-helpers'; import { setupPretender } from 'skylines/tests/helpers/setup-pretender'; module('Acceptance | login', function(hooks) { setupApplicationTest(hooks); setupPretender(hooks); const LOGIN_DROPDOWN = '[data-test-login-dropdown]'; const LOGIN_DROPDOWN_TOGGLE = `${LOGIN_DROPDOWN} a`; const LOGIN_EMAIL = '[data-test-input="login-email"]'; test('login dropdown form stays visible when fields are focused', async function(assert) { await visit('/'); await click(LOGIN_DROPDOWN_TOGGLE); assert.dom(LOGIN_DROPDOWN).hasClass('open'); await click(LOGIN_EMAIL); assert.dom(LOGIN_DROPDOWN).hasClass('open'); }); });
Allow signout in `forceUpgrade` state
import Route from '@ember/routing/route'; import {inject as service} from '@ember/service'; Route.reopen({ config: service(), billing: service(), router: service(), actions: { willTransition(transition) { if (this.get('upgradeStatus.isRequired')) { transition.abort(); this.upgradeStatus.requireUpgrade(); return false; } else if (this.config.get('hostSettings.forceUpgrade') && transition.to?.name !== 'signout') { transition.abort(); // Catch and redirect every route in a force upgrade state this.billing.openBillingWindow(this.router.currentURL, '/pro'); return false; } else { return true; } } } });
import Route from '@ember/routing/route'; import {inject as service} from '@ember/service'; Route.reopen({ config: service(), billing: service(), router: service(), actions: { willTransition(transition) { if (this.get('upgradeStatus.isRequired')) { transition.abort(); this.upgradeStatus.requireUpgrade(); return false; } else if (this.config.get('hostSettings.forceUpgrade')) { transition.abort(); // Catch and redirect every route in a force upgrade state this.billing.openBillingWindow(this.router.currentURL, '/pro'); return false; } else { return true; } } } });
Add lodash to production build.
/*jshint node:true*/ /* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var app = new EmberApp(defaults, { // Add options here }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/d3/d3.js'); app.import('bower_components/lodash/lodash.min.js'); // Customized version of nvd3 app.import('vendor/nvd3/build/nv.d3.css'); app.import('vendor/nvd3/build/nv.d3.js'); return app.toTree(); };
/*jshint node:true*/ /* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var app = new EmberApp(defaults, { // Add options here }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/d3/d3.js'); // Customized version of nvd3 app.import('vendor/nvd3/build/nv.d3.css'); app.import('vendor/nvd3/build/nv.d3.js'); return app.toTree(); };
Use removeObject instead of popObject
import Ember from 'ember'; import DS from 'ember-data'; export default DS.Model.extend({ vendor: DS.belongsTo('vendor'), location: DS.attr('string'), manager: DS.belongsTo('account'), time: DS.attr('string'), money: DS.attr({ defaultValue: () => ({}) }), portions: DS.hasMany('portion'), active: DS.attr('boolean', { defaultValue: true }), isReady: Ember.computed('money.total', 'money.required', function() { return this.get('money.total') >= this.get('money.required'); }), addPortion(portion) { const total = this.get('money.total'); const cost = portion.get('cost'); this.set('money.total', total + cost); this.get('portions').pushObject(portion); }, removePortion(portion) { const available = this.get('money.available'); const total = this.get('money.total'); const cost = portion.get('cost'); this.set('money.total', total - cost); if (portion.get('paid')) { this.set('money.available', available - cost); } this.get('portions').removeObject(portion); } });
import Ember from 'ember'; import DS from 'ember-data'; export default DS.Model.extend({ vendor: DS.belongsTo('vendor'), location: DS.attr('string'), manager: DS.belongsTo('account'), time: DS.attr('string'), money: DS.attr({ defaultValue: () => ({}) }), portions: DS.hasMany('portion'), active: DS.attr('boolean', { defaultValue: true }), isReady: Ember.computed('money.total', 'money.required', function() { return this.get('money.total') >= this.get('money.required'); }), addPortion(portion) { const total = this.get('money.total'); const cost = portion.get('cost'); this.set('money.total', total + cost); this.get('portions').pushObject(portion); }, removePortion(portion) { const available = this.get('money.available'); const total = this.get('money.total'); const cost = portion.get('cost'); this.set('money.total', total - cost); if (portion.get('paid')) { this.set('money.available', available - cost); } this.get('portions').popObject(portion); } });
Exit if a server thread died
import logging import optparse as op import Queue import bucky.carbon as carbon import bucky.collectd as collectd import bucky.statsd as statsd logging.basicConfig(format="[%(levelname)s] %(message)s", level=logging.DEBUG) __usage__ = "%prog [OPTIONS]" def options(): return [] def main(): parser = op.OptionParser(usage=__usage__, option_list=options()) opts, args = parser.parse_args() sampleq = Queue.Queue() cdsrv = collectd.CollectDServer(sampleq) cdsrv.start() stsrv = statsd.StatsDServer(sampleq) stsrv.start() cli = carbon.CarbonClient() while True: try: stat, value, time = sampleq.get(True, 1) cli.send(stat, value, time) except Queue.Empty: pass if not cdsrv.is_alive(): log.error("collectd server died") break if not stsrv.is_alive(): log.error("statsd server died") break if __name__ == '__main__': try: main() except KeyboardInterrupt: pass except Exception, e: raise # debug print e
import logging import optparse as op import Queue import bucky.carbon as carbon import bucky.collectd as collectd import bucky.statsd as statsd logging.basicConfig(format="[%(levelname)s] %(message)s", level=logging.DEBUG) __usage__ = "%prog [OPTIONS]" def options(): return [] def main(): parser = op.OptionParser(usage=__usage__, option_list=options()) opts, args = parser.parse_args() sampleq = Queue.Queue() cdsrv = collectd.CollectDServer(sampleq) cdsrv.start() stsrv = statsd.StatsDServer(sampleq) stsrv.start() cli = carbon.CarbonClient() while True: try: stat, value, time = sampleq.get(True, 1) cli.send(stat, value, time) except Queue.Empty: pass if __name__ == '__main__': try: main() except KeyboardInterrupt: pass except Exception, e: raise # debug print e
Move global variable to the top
'use strict' angular.module('pathwayApp') .controller('PathwayController', function ($scope, $http, $stateParams, $cookieStore, $state) { $scope.user = $cookieStore.get('pathway_user') $http({method: 'GET', url: '/api/pathways/' + $stateParams.id }).success(function(data, status){ $scope.pathway = data }) $scope.create = function() { $http({method: 'POST', url: '/api/pathways', data: {pathway: $scope.pathway, user: $scope.user.id } }).success(function(data, status){ console.log("hello from create() pathway") $state.go('showPathway', {'id': data.id }) }).error(function(data){ console.log(data) }) } });
'use strict' angular.module('pathwayApp') .controller('PathwayController', function ($scope, $http, $stateParams, $cookieStore, $state) { $http({method: 'GET', url: '/api/pathways/' + $stateParams.id }).success(function(data, status){ $scope.pathway = data }) $scope.user = $cookieStore.get('pathway_user') $scope.create = function() { $http({method: 'POST', url: '/api/pathways', data: {pathway: $scope.pathway, user: $scope.user.id } }).success(function(data, status){ console.log("hello from create() pathway") $state.go('showPathway', {'id': data.id }) }).error(function(data){ console.log(data) }) } });
Configure CardView based on `owner`
(function() { var CardView = Backbone.View.extend({ tagName: 'li', className: 'dc-card', template: (function() { var source = $('#card-view-template').html(); var template = Handlebars.compile(source); return function() { return template(this.model.attributes); }; }()), render: function() { this.$el.html(this.template()); return this; }, appendToDeck: function(selector) { var $deck = $(selector); if ($deck.length) { this.$el.appendTo($deck.get(0).$__retargetRoot); } }, appendToOwner: function() { var owner = this.model.get('owner'); var selector; if (this.model.isInHand()) { var id = owner.get( 'identifier' ); selector = '#player-' + id; } else { selector = '#board'; } return this.appendToDeck(selector); } }); window.CardView = CardView; }());
(function() { var CardView = Backbone.View.extend({ tagName: 'li', className: 'dc-card', template: (function() { var source = $('#card-view-template').html(); var template = Handlebars.compile(source); return function() { return template(this.model.attributes); }; }()), render: function() { this.$el.html(this.template()); return this; }, appendToDeck: function(selector) { var $deck = $(selector); if ($deck.length) { this.$el.appendTo($deck.get(0).$__retargetRoot); } }, appendToOwner: function() { var owner = this.model.get('owner'); var selector = '#' + owner; return this.appendToDeck(selector); } }); window.CardView = CardView; }());
Add test for conditional elses
import pytest from thinglang.runner import run def test_simple_conditionals(): assert run(""" thing Program does start if "dog" eq "dog" Output.write("dog is dog") if "dog" eq "cat" Output.write("dog is cat") """).output == """dog is dog""".strip() def test_unconditional_else(): assert run(""" thing Program does start if "dog" eq "dog" Output.write("dog is dog") otherwise Output.write("dog is not dog") if "dog" eq "cat" Output.write("dog is cat") otherwise Output.write("dog is not cat") """).output == """dog is dog\ndog is not cat""".strip() def test_conditional_else(): assert run(""" thing Program does start if "dog" eq "cat" Output.write("dog is cat") otherwise if "dog" eq "dog" Output.write("dog is dog") otherwise Output.write("dog is not dog and not cat") """).output == """dog is dog\ndog is not cat""".strip()
import pytest from thinglang.runner import run def test_simple_conditionals(): assert run(""" thing Program does start if "dog" eq "dog" Output.write("dog is dog") if "dog" eq "cat" Output.write("dog is cat") """).output == """dog is dog""".strip() def test_unconditional_else(): assert run(""" thing Program does start if "dog" eq "dog" Output.write("dog is dog") otherwise Output.write("dog is not dog") if "dog" eq "cat" Output.write("dog is cat") otherwise Output.write("dog is not cat") """).output == """dog is dog\ndog is not cat""".strip()
Detach SoundsView's table before modifying it for better performance.
define([ "underscore", "backbone", "baseView", "./soundView" ], function(_, Backbone, BaseView, SoundView) { var SoundsView = BaseView.extend({ initialize: function (options) { this.columns = 7; this.rows = 4; this.table = $("<table></table>"); }, render: function (collection) { var column, row, rowElement, view, i = 0; this.removeAllChildViews(); this.table.detach(); this.table.empty(); var collectionIterator = _.bind(function () { var model = collection && collection.models[i]; if (model) { view = this.addChildView(SoundView, { model: model }); i++; return view.render().$el; } else { return $("<td class='empty-sound'></td>"); } }, this); for (row = 0; row < this.rows; row++) { rowElement = $("<tr></tr>"); this.table.append(rowElement); for (column = 0; column < this.columns; column++) { rowElement.append(collectionIterator()); } } this.$el.append(this.table); return this; } }); return SoundsView; });
define([ "underscore", "backbone", "baseView", "./soundView" ], function(_, Backbone, BaseView, SoundView) { var SoundsView = BaseView.extend({ initialize: function (options) { this.columns = 7; this.rows = 4; this.table = $("<table></table>"); this.$el.append(this.table); }, render: function (collection) { var column, row, rowElement, view, i = 0; this.removeAllChildViews(); this.table.empty(); var collectionIterator = _.bind(function () { var model = collection && collection.models[i]; if (model) { view = this.addChildView(SoundView, { model: model }); i++; return view.render().$el; } else { return $("<td class='empty-sound'></td>"); } }, this); for (row = 0; row < this.rows; row++) { rowElement = $("<tr></tr>"); this.table.append(rowElement); for (column = 0; column < this.columns; column++) { rowElement.append(collectionIterator()); } } return this; } }); return SoundsView; });
Fix request id ctx key
package middleware import ( "context" "net/http" "github.com/nats-io/nuid" ) type ctxRequestIDKeyType int const CtxRequestIDKey ctxRequestIDKeyType = 0 const ( headerXRequestID = "X-Request-ID" ) type RequestID struct { SetHeader bool n *nuid.NUID } func NewRequestID() *RequestID { return &RequestID{ SetHeader: true, n: nuid.New(), } } func (rid *RequestID) ServeNext(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { requestid := rid.n.Next() if rid.SetHeader { w.Header().Set(headerXRequestID, requestid) } ctx := context.WithValue(r.Context(), CtxRequestIDKey, requestid) next.ServeHTTP(w, r.WithContext(ctx)) } return http.HandlerFunc(fn) }
package middleware import ( "context" "net/http" "github.com/nats-io/nuid" ) type ctxRequestIDKeyType int const CtxRequestIDKey int = 0 const ( headerXRequestID = "X-Request-ID" ) type RequestID struct { SetHeader bool n *nuid.NUID } func NewRequestID() *RequestID { return &RequestID{ SetHeader: true, n: nuid.New(), } } func (rid *RequestID) ServeNext(next http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { requestid := rid.n.Next() if rid.SetHeader { w.Header().Set(headerXRequestID, requestid) } ctx := context.WithValue(r.Context(), CtxRequestIDKey, requestid) next.ServeHTTP(w, r.WithContext(ctx)) } return http.HandlerFunc(fn) }
Remove clock granularity sensitive test assertion. TestRequestTime already verifies that the request time is properly recorded.
package api import ( "testing" ) func assertQueryMeta(t *testing.T, qm *QueryMeta) { if qm.LastIndex == 0 { t.Fatalf("bad index: %d", qm.LastIndex) } if !qm.KnownLeader { t.Fatalf("expected known leader, got none") } } func assertWriteMeta(t *testing.T, wm *WriteMeta) { if wm.LastIndex == 0 { t.Fatalf("bad index: %d", wm.LastIndex) } } func testJob() *Job { task := NewTask("task1", "exec"). Require(&Resources{MemoryMB: 256}) group := NewTaskGroup("group1", 1). AddTask(task) job := NewBatchJob("job1", "redis", "region1", 1). AddDatacenter("dc1"). AddTaskGroup(group) return job }
package api import ( "testing" ) func assertQueryMeta(t *testing.T, qm *QueryMeta) { if qm.LastIndex == 0 { t.Fatalf("bad index: %d", qm.LastIndex) } if !qm.KnownLeader { t.Fatalf("expected known leader, got none") } } func assertWriteMeta(t *testing.T, wm *WriteMeta) { if wm.LastIndex == 0 { t.Fatalf("bad index: %d", wm.LastIndex) } if wm.RequestTime == 0 { t.Fatalf("bad request time: %d", wm.RequestTime) } } func testJob() *Job { task := NewTask("task1", "exec"). Require(&Resources{MemoryMB: 256}) group := NewTaskGroup("group1", 1). AddTask(task) job := NewBatchJob("job1", "redis", "region1", 1). AddDatacenter("dc1"). AddTaskGroup(group) return job }
Change README content type to markdown for pypi
#!/usr/bin/env python from setuptools import setup import setuptools with open("README.md", 'r') as f: long_description = f.read() setup( name='chess_py', version='2.8.1', description='Python chess client', long_description=long_description, long_description_content_type='text/markdown', platforms='MacOS X, Windows, Linux', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 2.7', ], author='Aubhro Sengupta', author_email='aubhrosengupta@gmail.com', url='https://github.com/LordDarkula/chess_py', license='MIT', packages=setuptools.find_packages() )
#!/usr/bin/env python from setuptools import setup import setuptools with open("README.md", 'r') as f: long_description = f.read() setup( name='chess_py', version='2.8.0', description='Python chess client', long_description=long_description, platforms='MacOS X, Windows, Linux', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 2.7', ], author='Aubhro Sengupta', author_email='aubhrosengupta@gmail.com', url='https://github.com/LordDarkula/chess_py', license='MIT', packages=setuptools.find_packages() )
Add 01 to function name
from evalset.test_funcs import TestFunction, lzip import numpy class MultioptTestFunction(TestFunction): def __init__(self, dim): super(MultioptTestFunction, self).__init__(dim) self.local_minima_loc = [] # Sorted in increasing order of function value at the local minima class LowDMixtureOfGaussians01(MultioptTestFunction): def __init__(self, dim=2): assert dim == 2 super(LowDMixtureOfGaussians01, self).__init__(dim) self.bounds = lzip([-1] * self.dim, [1] * self.dim) self.fmin = -0.502124885135 self.fmax = 0 self.local_minima_loc = [(-0.2, -0.5), (0.8, 0.3)] def do_evaluate(self, x): x1, x2 = x return -( .5 * numpy.exp(-10 * (.8 * (x1 + .2) ** 2 + .7 * (x2 + .5) ** 2)) + .5 * numpy.exp(-8 * (.3 * (x1 - .8) ** 2 + .6 * (x2 - .3) ** 2)) )
from evalset.test_funcs import TestFunction, lzip import numpy class MultioptTestFunction(TestFunction): def __init__(self, dim): super(MultioptTestFunction, self).__init__(dim) self.local_minima_loc = [] # Sorted in increasing order of function value at the local minima class LowDMixtureOfGaussians(MultioptTestFunction): def __init__(self, dim=2): assert dim == 2 super(LowDMixtureOfGaussians, self).__init__(dim) self.bounds = lzip([-1] * self.dim, [1] * self.dim) self.fmin = -0.502124885135 self.fmax = 0 self.local_minima_loc = [(-0.2, -0.5), (0.8, 0.3)] def do_evaluate(self, x): x1, x2 = x return -( .5 * numpy.exp(-10 * (.8 * (x1 + .2) ** 2 + .7 * (x2 + .5) ** 2)) + .5 * numpy.exp(-8 * (.3 * (x1 - .8) ** 2 + .6 * (x2 - .3) ** 2)) )
Expand Keys enum to include the escape key. Key values reference: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values RELNOTES: KeyboardEvent.key now includes escape key. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=213994507
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Constant declarations for common key values. * */ goog.provide('goog.events.Keys'); /** * Key values for common characters. * * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key * @enum {string} */ goog.events.Keys = { ALT: 'Meta', ALTGRAPH: 'AltGraph', CTRL: 'Control', DOWN: 'ArrowDown', END: 'End', ENTER: 'Enter', ESCAPE: 'Escape', HOME: 'Home', LEFT: 'ArrowLeft', PAGE_DOWN: 'PageDown', PAGE_UP: 'PageUp', RIGHT: 'ArrowRight', SHIFT: 'Shift', SPACE: ' ', TAB: 'Tab', UP: 'ArrowUp', };
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Constant declarations for common key values. * */ goog.provide('goog.events.Keys'); /** * Key values for common characters. * * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key * @enum {string} */ goog.events.Keys = { ALT: 'Meta', ALTGRAPH: 'AltGraph', CTRL: 'Control', DOWN: 'ArrowDown', END: 'End', ENTER: 'Enter', HOME: 'Home', LEFT: 'ArrowLeft', PAGE_DOWN: 'PageDown', PAGE_UP: 'PageUp', RIGHT: 'ArrowRight', SHIFT: 'Shift', SPACE: ' ', TAB: 'Tab', UP: 'ArrowUp', };
Reduce number of placed ships
package pw.scho.battleship.model; import java.util.Random; public class BoardRandomizer { private final Random random = new Random(); private Board board; public Board randomizeWithStandardShips() { return randomize(new int[]{2, 2, 3, 3, 4, 5}); } public Board randomize(int[] shipSizes) { board = new Board(); for (int size : shipSizes) { placeShip(size); } return board; } private void placeShip(int size) { while (true) { Ship ship = createRandomShip(size); if (board.shipIsPlaceable(ship)) { board.placeShip(ship); break; } } } private Ship createRandomShip(int size) { int x = random.nextInt(Board.WIDTH - 1); int y = random.nextInt(Board.HEIGHT - 1); Position position = new Position(x, y); if (random.nextBoolean()) { return Ship.createHorizontal(position, size); } else { return Ship.createVertical(position, size); } } }
package pw.scho.battleship.model; import java.util.Random; public class BoardRandomizer { private final Random random = new Random(); private Board board; public Board randomizeWithStandardShips() { return randomize(new int[]{2, 2, 2, 2, 3, 3, 3, 4, 4, 5}); } public Board randomize(int[] shipSizes) { board = new Board(); for (int size : shipSizes) { placeShip(size); } return board; } private void placeShip(int size) { while (true) { Ship ship = createRandomShip(size); if (board.shipIsPlaceable(ship)) { board.placeShip(ship); break; } } } private Ship createRandomShip(int size) { int x = random.nextInt(Board.WIDTH - 1); int y = random.nextInt(Board.HEIGHT - 1); Position position = new Position(x, y); if (random.nextBoolean()) { return Ship.createHorizontal(position, size); } else { return Ship.createVertical(position, size); } } }
Use hash_maps for student.studies and student.schedules
var Fluxy = require('fluxy') var Promise = require('bluebird') var uuid = require('node-uuid') var _ = require('lodash') var mori = require('mori') var StudyStore = require('../stores/StudyStore') var ScheduleStore = require('../stores/ScheduleStore') var StudentService = { create: function(student) { return new Promise(function(resolve, reject) { var s = { id: student.id || uuid.v4(), name: student.name || '', active: student.active || false, enrollment: student.enrollment || 0, graduation: student.graduation || 0, creditsNeeded: student.creditsNeeded || 0, studies: student.studies.length > 0 ? mori.hash_map(student.studies) : mori.hash_map(), schedules: student.schedules.length > 0 ? mori.hash_map(student.schedules) : mori.hash_map(), // overrides: new OverrideStore(), // fabrications: new FabricationStore(), } console.log('called StudentService.create', s) resolve(mori.js_to_clj(s)) }) }, encode: function(student) { }, decode: function(encodedStudent) { // decode stuff var decodedStudent = encodedStudent this.create(decodedStudent) } } module.exports = StudentService
var Fluxy = require('fluxy') var Promise = require('bluebird') var uuid = require('node-uuid') var _ = require('lodash') var mori = require('mori') var StudyStore = require('../stores/StudyStore') var ScheduleStore = require('../stores/ScheduleStore') var StudentService = { create: function(student) { return new Promise(function(resolve, reject) { var s = { id: student.id || uuid.v4(), name: student.name || '', active: student.active || false, enrollment: student.enrollment || 0, graduation: student.graduation || 0, creditsNeeded: student.creditsNeeded || 0, studies: student.studies.length > 0 ? mori.vector(student.studies) : mori.vector(), schedules: student.schedules.length > 0 ? mori.vector(student.schedules) : mori.vector(), // overrides: new OverrideStore(), // fabrications: new FabricationStore(), } console.log('called StudentService.create', s) resolve(mori.js_to_clj(s)) }) }, encode: function(student) { }, decode: function(encodedStudent) { // decode stuff var decodedStudent = encodedStudent this.create(decodedStudent) } } module.exports = StudentService
[AC-9556]: Remove program role from bucket list
from django.db import migrations def remove_bucket_list_program_roles(apps, schema_editor): BucketState = apps.get_model('accelerator', 'BucketState') ProgramRole = apps.get_model('accelerator', 'ProgramRole') ProgramRoleGrant = apps.get_model('accelerator', 'ProgramRoleGrant') NodePublishedFor = apps.get_model('accelerator', 'NodePublishedFor') program_role_ids = BucketState.objects.values_list('program_role_id', flat=True) NodePublishedFor.objects.filter( published_for_id__in=program_role_ids).delete() ProgramRoleGrant.objects.filter( program_role_id__in=program_role_ids).delete() BucketState.objects.all().delete() ProgramRole.objects.filter(pk__in=program_role_ids).delete() class Migration(migrations.Migration): dependencies = [ ('accelerator', '0109_remove_interest_fields_20220705_0425'), ] operations = [ migrations.RunPython(remove_bucket_list_program_roles, migrations.RunPython.noop) ]
from django.db import migrations def remove_bucket_list_program_roles(apps, schema_editor): BucketState = apps.get_model('accelerator', 'BucketState') ProgramRole = apps.get_model('accelerator', 'ProgramRole') ProgramRoleGrant = apps.get_model('accelerator', 'ProgramRoleGrant') NodePublishedFor = apps.get_model('accelerator', 'NodePublishedFor') program_role_ids = BucketState.objects.values_list('program_role_id', flat=True) NodePublishedFor.objects.filter( published_for_id__in=program_role_ids).delete() ProgramRoleGrant.objects.filter( program_role_id__in=program_role_ids).delete() BucketState.objects.all().delete() ProgramRole.objects.filter(pk__in=program_role_ids).delete() class Migration(migrations.Migration): dependencies = [ ('accelerator', '0109_remove_interest_fields_20220705_0425'), ] operations = [ migrations.RunPython(remove_bucket_list_program_roles, migrations.RunPython.noop) ]
Allow BeautifulSoup object being passed into hCalendar
from vcalendar import vCalendar from bs4 import BeautifulSoup class hCalendar(object): def __init__(self, markup, value=None, key='id'): if isinstance(markup, BeautifulSoup): self._soup = markup else: self._soup = BeautifulSoup(markup) if value: self._soup = self._soup.find(**{key: value}) self._cals = self._soup.findAll(attrs='vcalendar') if self._cals: self._cals = map(vCalendar, self._cals) else: self._cals = [vCalendar(self._soup)] def __len__(self): return len(self._cals) def __iter__(self): return iter(self._cals) def __getitem__(self, key): return self._cals[key] def getCalendar(self): return self._cals
import bs4 from vcalendar import vCalendar class hCalendar(object): def __init__(self, markup, value=None, key='id'): self._soup = bs4.BeautifulSoup(markup) if value: self._soup = self._soup.find(**{key: value}) self._cals = self._soup.findAll(attrs='vcalendar') if self._cals: self._cals = map(vCalendar, self._cals) else: self._cals = [vCalendar(self._soup)] def __len__(self): return len(self._cals) def __iter__(self): return iter(self._cals) def __getitem__(self, key): return self._cals[key] def getCalendar(self): return self._cals
Add twitter location and description fields
<?php namespace Laravel\Socialite\One; use InvalidArgumentException; class TwitterProvider extends AbstractProvider { /** * {@inheritdoc} */ public function user() { if (! $this->hasNecessaryVerifier()) { throw new InvalidArgumentException('Invalid request. Missing OAuth verifier.'); } $user = $this->server->getUserDetails($token = $this->getToken()); $extraDetails = [ 'location' => $user->location, 'description' => $user->description, ]; $instance = (new User)->setRaw(array_merge($user->extra, $user->urls, $extraDetails)) ->setToken($token->getIdentifier(), $token->getSecret()); return $instance->map([ 'id' => $user->uid, 'nickname' => $user->nickname, 'name' => $user->name, 'email' => $user->email, 'avatar' => $user->imageUrl, 'avatar_original' => str_replace('_normal', '', $user->imageUrl), ]); } }
<?php namespace Laravel\Socialite\One; use InvalidArgumentException; class TwitterProvider extends AbstractProvider { /** * {@inheritdoc} */ public function user() { if (! $this->hasNecessaryVerifier()) { throw new InvalidArgumentException('Invalid request. Missing OAuth verifier.'); } $user = $this->server->getUserDetails($token = $this->getToken()); $instance = (new User)->setRaw(array_merge($user->extra, $user->urls)) ->setToken($token->getIdentifier(), $token->getSecret()); return $instance->map([ 'id' => $user->uid, 'nickname' => $user->nickname, 'name' => $user->name, 'email' => $user->email, 'avatar' => $user->imageUrl, 'avatar_original' => str_replace('_normal', '', $user->imageUrl), ]); } }
Change hacking check to verify all oslo imports The hacking check was verifying that specific oslo imports weren't using the oslo-namespaced package. Since all the oslo libraries used by keystoneclient are now changed to use the new package name the hacking check can be simplified. bp drop-namespace-packages Change-Id: I6466e857c6eda0add6918e9fb14dc9296ed98600
# 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. """python-keystoneclient's pep8 extensions. In order to make the review process faster and easier for core devs we are adding some python-keystoneclient specific pep8 checks. This will catch common errors so that core devs don't have to. """ import re def check_oslo_namespace_imports(logical_line, blank_before, filename): oslo_namespace_imports = re.compile( r"(((from)|(import))\s+oslo\.)|(from\s+oslo\s+import\s+)") if re.match(oslo_namespace_imports, logical_line): msg = ("K333: '%s' must be used instead of '%s'.") % ( logical_line.replace('oslo.', 'oslo_'), logical_line) yield(0, msg) def factory(register): register(check_oslo_namespace_imports)
# 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. """python-keystoneclient's pep8 extensions. In order to make the review process faster and easier for core devs we are adding some python-keystoneclient specific pep8 checks. This will catch common errors so that core devs don't have to. """ import re def check_oslo_namespace_imports(logical_line, blank_before, filename): oslo_namespace_imports = re.compile( r"(((from)|(import))\s+oslo\." "((config)|(serialization)|(utils)|(i18n)))|" "(from\s+oslo\s+import\s+((config)|(serialization)|(utils)|(i18n)))") if re.match(oslo_namespace_imports, logical_line): msg = ("K333: '%s' must be used instead of '%s'.") % ( logical_line.replace('oslo.', 'oslo_'), logical_line) yield(0, msg) def factory(register): register(check_oslo_namespace_imports)
Patch settings from inside the command module
from __future__ import unicode_literals import os import mock from django import test from django.core.management import call_command BASE_DIR = os.path.dirname(os.path.dirname(__file__)) FIXTURE_DIR = os.path.abspath(os.path.join(BASE_DIR, 'tests', 'fixtures')) def mock_source(setting, short_name): # noqa return mock.patch( 'cities_light.management.commands.cities_light.%s_SOURCES' % setting.upper(), ['file://%s/%s.txt' % (FIXTURE_DIR, short_name)]) class TestUnicodeDecodeError(test.TransactionTestCase): """Test case which demonstrates UnicodeDecodeError.""" @mock_source('city', 'kemerovo_city') @mock_source('region', 'kemerovo_region') @mock_source('country', 'kemerovo_country') def test_unicode_decode_error(self): """.""" call_command('cities_light', force_import_all=True)
from __future__ import unicode_literals import os import mock from django import test from django.core.management import call_command BASE_DIR = os.path.dirname(os.path.dirname(__file__)) FIXTURE_DIR = os.path.abspath(os.path.join(BASE_DIR, 'tests', 'fixtures')) def mock_source(setting, short_name): # noqa return mock.patch( 'cities_light.settings.%s_SOURCES' % setting.upper(), ['file://%s/%s.txt' % (FIXTURE_DIR, short_name)]) class TestUnicodeDecodeError(test.TransactionTestCase): """Test case which demonstrates UnicodeDecodeError.""" @mock_source('city', 'kemerovo_city') @mock_source('region', 'kemerovo_region') @mock_source('country', 'kemerovo_country') def test_unicode_decode_error(self): """.""" call_command('cities_light', force_import_all=True)
Check Close() function on pool resources.
package resourcepool import ( "sync" "testing" ) type IntMaker struct{} var wg sync.WaitGroup = sync.WaitGroup{} func (*IntMaker) Create() (interface{}, error) { i := 1 return &i, nil } func (*IntMaker) Check(interface{}) error { return nil } func (*IntMaker) Destroy(interface{}) error { wg.Done() return nil } func TestResourcePool(t *testing.T) { wg.Add(2) pool, err := NewResourcePool( &IntMaker{}, 2, 2, 2, ) if err != nil { t.Error(err) } r1, err := pool.GetResource() if err != nil { t.Error(err) } r2, err := pool.GetResource() if err != nil { t.Error(err) } r1.Close() r2.Close() r1, err = pool.GetResource() if err != nil { t.Error(err) } r2, err = pool.GetResource() if err != nil { t.Error(err) } r1.Close() r2.Close() wg.Wait() }
package resourcepool import ( "sync" "testing" ) type IntMaker struct{} var wg sync.WaitGroup = sync.WaitGroup{} func (*IntMaker) Create() (interface{}, error) { i := 1 return &i, nil } func (*IntMaker) Check(interface{}) error { return nil } func (*IntMaker) Destroy(interface{}) error { wg.Done() return nil } func TestResourcePool(t *testing.T) { wg.Add(2) pool, err := NewResourcePool( &IntMaker{}, 2, 2, 2, ) if err != nil { t.Error(err) } r1, err := pool.GetResource() if err != nil { t.Error(err) } r2, err := pool.GetResource() if err != nil { t.Error(err) } pool.ReturnResource(r1) pool.ReturnResource(r2) r1, err = pool.GetResource() if err != nil { t.Error(err) } r2, err = pool.GetResource() if err != nil { t.Error(err) } pool.ReturnResource(r1) pool.ReturnResource(r2) wg.Wait() }
QuizBundle: Implement admin quiz edit form
<?php namespace QuizBundle\Form\Admin\Quiz; use CommonBundle\Component\Form\Admin\Element\Text, Doctrine\ORM\EntityManager, QuizBundle\Entity\Quiz, Zend\Form\Element\Submit; /** * Edits a quiz * @author Lars Vierbergen <vierbergenlars@gmail.com> */ class Edit extends Add { /** * @param \Doctrine\ORM\EntityManager $entityManager * @param \QuizBundle\Entity\Quiz $quiz The quiz to populate the form with * @param null|string|int $name Optional name for the form */ public function __construct(EntityManager $entityManager, Quiz $quiz, $name = null) { parent::__construct($entityManager, $name); $this->remove('submit'); $field = new Submit('submit'); $field->setValue('Edit') ->setAttribute('class', 'quiz_edit'); $this->add($field); $this->populateFromQuiz($quiz); } }
<?php namespace QuizBundle\Form\Admin\Quiz; use CommonBundle\Component\Form\Admin\Element\Text, Doctrine\ORM\EntityManager, QuizBundle\Entity\Quiz, Zend\Form\Element\Submit; /** * Edits a quiz * @author Lars Vierbergen <vierbergenlars@gmail.com> */ class Edit extends Add { /** * @param \Doctrine\ORM\EntityManager $entityManager * @param \QuizBundle\Entity\Quiz The quiz to populate the form with * @param null|string|int $name Optional name for the form */ public function __construct(EntityManager $entityManager, Quiz $quiz, $name = null) { parent::__construct($entityManager, $name); $this->remove('submit'); $field = new Submit('submit'); $field->setValue('Edit') ->setAttribute('class', 'quiz_edit'); $this->add($field); $this->populateFromQuiz($quiz); } }
Add empty default for STATUS_CHECK_FILES setting Given that: * The line caused an attribute error if the setting wasn't defined, * The use of getattr was pointless as written since normal attribute access would have worked fine, * `dict.get` has a default of `None` without having to specify it, and * The line was followed by a boolean test for the fetched attribute, I infer that this was the intended meaning. It should probably be documented somewhere that these settings are required and what they do.
import json from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) class JsonResponse(HttpResponse): def __init__(self, data, **kwargs): kwargs.setdefault('content_type', 'application/json') data = json.dumps(data) super(JsonResponse, self).__init__(content=data, **kwargs) class JsonResponseServerError(JsonResponse): status_code = 500 @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) files_to_check = getattr(settings, 'STATUS_CHECK_FILES', None) if files_to_check: checks.append(FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if ok and not details: details = 'There were no checks.' if not ok: return JsonResponseServerError(json.dumps(details)) return JsonResponse(details)
import json from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) class JsonResponse(HttpResponse): def __init__(self, data, **kwargs): kwargs.setdefault('content_type', 'application/json') data = json.dumps(data) super(JsonResponse, self).__init__(content=data, **kwargs) class JsonResponseServerError(JsonResponse): status_code = 500 @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) files_to_check = getattr(settings, 'STATUS_CHECK_FILES') if files_to_check: checks.append(FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if ok and not details: details = 'There were no checks.' if not ok: return JsonResponseServerError(json.dumps(details)) return JsonResponse(details)
aafig: Rename package as sphinxcontrib-aafig * * * aafig: Fix package name in PYPI URL
# -*- coding: utf-8 -*- from setuptools import setup, find_packages long_desc = ''' This package contains the aafigure Sphinx extension. Allow embeded ASCII art figure to be rendered as nice images. ''' requires = ['Sphinx>=0.6'] setup( name='sphinxcontrib-aafig', version='0.1', url='http://bitbucket.org/birkenfeld/sphinx-contrib', download_url='http://pypi.python.org/pypi/sphinxcontrib-aafig', license='BSD', author='Leandro Lucarella', author_email='llucax@gmail.com', description='Sphinx extension aafig', long_description=long_desc, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Utilities', ], platforms='any', packages=find_packages(), include_package_data=True, install_requires=requires, namespace_packages=['sphinxcontrib'], )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages long_desc = ''' This package contains the aafigure Sphinx extension. Allow embeded ASCII art figure to be rendered as nice images. ''' requires = ['Sphinx>=0.6'] setup( name='aafig', version='0.1', url='http://bitbucket.org/birkenfeld/sphinx-contrib', download_url='http://pypi.python.org/pypi/aafig', license='BSD', author='Leandro Lucarella', author_email='llucax@gmail.com', description='Sphinx extension aafig', long_description=long_desc, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Utilities', ], platforms='any', packages=find_packages(), include_package_data=True, install_requires=requires, namespace_packages=['sphinxcontrib'], )
Rename face parameter to image.
package nl.ekholabs.nlp.controller; import java.io.IOException; import nl.ekholabs.nlp.client.ElsieDeeSightFeignClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; @RestController public class FaceClassifierController { private final ElsieDeeSightFeignClient elsieDeeSightFeignClient; @Autowired public FaceClassifierController(final ElsieDeeSightFeignClient elsieDeeSightFeignClient) { this.elsieDeeSightFeignClient = elsieDeeSightFeignClient; } @PostMapping(consumes = MULTIPART_FORM_DATA_VALUE) public ResponseEntity<byte[]> processImage(final @RequestParam(value = "image") MultipartFile image) throws IOException { return elsieDeeSightFeignClient.process(image); } }
package nl.ekholabs.nlp.controller; import java.io.IOException; import nl.ekholabs.nlp.client.ElsieDeeSightFeignClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; @RestController public class FaceClassifierController { private final ElsieDeeSightFeignClient elsieDeeSightFeignClient; @Autowired public FaceClassifierController(final ElsieDeeSightFeignClient elsieDeeSightFeignClient) { this.elsieDeeSightFeignClient = elsieDeeSightFeignClient; } @PostMapping(consumes = MULTIPART_FORM_DATA_VALUE) public ResponseEntity<byte[]> processImage(final @RequestParam(value = "image") MultipartFile face) throws IOException { return elsieDeeSightFeignClient.process(face); } }
Remove outdated parameter from docstring
"""The Adventure game.""" def load_advent_dat(data): import os from .data import parse datapath = os.path.join(os.path.dirname(__file__), 'advent.dat') with open(datapath, 'r', encoding='ascii') as datafile: parse(data, datafile) def play(seed=None): """Turn the Python prompt into an Adventure game. With optional the `seed` argument the caller can supply an integer to start the Python random number generator at a known state. """ global _game from .game import Game from .prompt import install_words _game = Game(seed) load_advent_dat(_game) install_words(_game) _game.start() print(_game.output[:-1]) def resume(savefile, quiet=False): global _game from .game import Game from .prompt import install_words _game = Game.resume(savefile) install_words(_game) if not quiet: print('GAME RESTORED\n')
"""The Adventure game.""" def load_advent_dat(data): import os from .data import parse datapath = os.path.join(os.path.dirname(__file__), 'advent.dat') with open(datapath, 'r', encoding='ascii') as datafile: parse(data, datafile) def play(seed=None): """Turn the Python prompt into an Adventure game. With `seed` the caller can supply an integer to start the random number generator at a known state. When `quiet` is true, no output is printed as the game is played; the caller of a command has to manually check `_game.output` for the result, which makes it possible to write very quiet tests. """ global _game from .game import Game from .prompt import install_words _game = Game(seed) load_advent_dat(_game) install_words(_game) _game.start() print(_game.output[:-1]) def resume(savefile, quiet=False): global _game from .game import Game from .prompt import install_words _game = Game.resume(savefile) install_words(_game) if not quiet: print('GAME RESTORED\n')
Remove dev logging, don't need it. Console.log like in the old days!
var express = require('express'); var http = require('http'); var path = require('path'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io').listen(server); var spotify = require('spotify-node-applescript'); var SpotifyRemoteServer = require('./lib/spotify_remote_server'); io.enable('browser client minification'); io.enable('browser client etag'); io.enable('browser client gzip'); io.set('log level', 1); app.configure(function() { app.set('port', process.env.PORT || 3000); app.use(express.favicon()); app.use(express.static(path.join(__dirname, 'public'))); }); app.get('/', function(req, res) { res.sendfile(__dirname + '/public/index.html'); }); server.listen(app.get('port'), function() { console.log('Your spotify remote is awaiting commands on: http://localhost:' + app.get('port')); }); new SpotifyRemoteServer(io, spotify);
var express = require('express'); var http = require('http'); var path = require('path'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io').listen(server); var spotify = require('spotify-node-applescript'); var SpotifyRemoteServer = require('./lib/spotify_remote_server'); io.enable('browser client minification'); io.enable('browser client etag'); io.enable('browser client gzip'); io.set('log level', 1); app.configure(function() { app.set('port', process.env.PORT || 3000); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function() { app.use(express.errorHandler()); }); app.get('/', function(req, res) { res.sendfile(__dirname + '/public/index.html'); }); server.listen(app.get('port'), function() { console.log('Your spotify remote is awaiting commands on: http://localhost:' + app.get('port')); }); new SpotifyRemoteServer(io, spotify);
Remove api_token from users table
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id')->unsigned(); $table->string('name'); $table->string('password', 60); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id')->unsigned(); $table->string('name'); $table->string('password', 60); $table->string('api_token', 60)->unique(); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Update exception message in run listener rather than just sysoutting the report.
package hu.advancedweb.scott.runtime; import java.lang.reflect.Field; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; /** * An alternative way to produce the detailed failure reports is to register this JUnit listener. * * @see ScottReportingRule * @author David Csakvari */ public class ScottRunListener extends RunListener { private Description description; @Override public void testStarted(Description description) throws Exception { this.description = description; super.testStarted(description); } @Override public void testFailure(Failure failure) throws Exception { String scottReport = FailureRenderer.render(description, failure.getException()); setExceptionMessage(failure.getException(), scottReport); super.testFailure(failure); } private void setExceptionMessage(Object object, Object fieldValue) { final String fieldName = "detailMessage"; Class<?> clazz = object.getClass(); while (clazz != null) { try { Field field = clazz.getDeclaredField(fieldName); field.setAccessible(true); field.set(object, fieldValue); return; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } catch (Exception e) { throw new IllegalStateException(e); } } } }
package hu.advancedweb.scott.runtime; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; /** * An alternative way to produce the detailed failure reports is to register this JUnit listener. * * @see ScottReportingRule * @author David Csakvari */ public class ScottRunListener extends RunListener { private Description description; @Override public void testStarted(Description description) throws Exception { this.description = description; super.testStarted(description); } @Override public void testFailure(Failure failure) throws Exception { // TODO: the simple System.out.println really not fits nicely into the test reports. // try changing the original exception's message with reflection. See issue #8. System.out.println(failure.getTestHeader() + " FAILED!"); System.out.println(FailureRenderer.render(description, failure.getException())); super.testFailure(failure); } }
Add dvb_subtitle to the bad codec list.
valid_input_extensions = ['mkv', 'avi', 'ts', 'mov', 'vob', 'mpg', 'mts'] valid_output_extensions = ['mp4', 'm4v'] valid_audio_codecs = ['aac', 'ac3', 'dts', 'eac3'] valid_poster_extensions = ['jpg', 'png'] valid_subtitle_extensions = ['srt', 'vtt', 'ass'] valid_formats = ['mp4', 'mov'] bad_subtitle_codecs = ['pgssub', 'dvdsub', 's_hdmv/pgs', 'hdmv_pgs_subtitle', 'dvd_subtitle', 'pgssub', 'dvb_teletext', 'dvb_subtitle'] tmdb_api_key = "45e408d2851e968e6e4d0353ce621c66" valid_internal_subcodecs = ['mov_text'] valid_external_subcodecs = ['srt', 'webvtt', 'ass'] subtitle_codec_extensions = {'srt': 'srt', 'webvtt': 'vtt', 'ass': 'ass'} bad_post_files = ['resources', '.DS_Store'] bad_post_extensions = ['.txt', '.log', '.pyc']
valid_input_extensions = ['mkv', 'avi', 'ts', 'mov', 'vob', 'mpg', 'mts'] valid_output_extensions = ['mp4', 'm4v'] valid_audio_codecs = ['aac', 'ac3', 'dts', 'eac3'] valid_poster_extensions = ['jpg', 'png'] valid_subtitle_extensions = ['srt', 'vtt', 'ass'] valid_formats = ['mp4', 'mov'] bad_subtitle_codecs = ['pgssub', 'dvdsub', 's_hdmv/pgs', 'hdmv_pgs_subtitle', 'dvd_subtitle', 'pgssub', 'dvb_teletext'] tmdb_api_key = "45e408d2851e968e6e4d0353ce621c66" valid_internal_subcodecs = ['mov_text'] valid_external_subcodecs = ['srt', 'webvtt', 'ass'] subtitle_codec_extensions = {'srt': 'srt', 'webvtt': 'vtt', 'ass': 'ass'} bad_post_files = ['resources', '.DS_Store'] bad_post_extensions = ['.txt', '.log', '.pyc']
Fix incorrect VO for selected check-in date
import getPhrase from './getPhrase'; import { BLOCKED_MODIFIER } from '../constants'; export default function getCalendarDaySettings(day, ariaLabelFormat, daySize, modifiers, phrases) { const { chooseAvailableDate, dateIsUnavailable, dateIsSelected, } = phrases; const daySizeStyles = { width: daySize, height: daySize - 1, }; const useDefaultCursor = ( modifiers.has('blocked-minimum-nights') || modifiers.has('blocked-calendar') || modifiers.has('blocked-out-of-range') ); const selected = ( modifiers.has('selected') || modifiers.has('selected-start') || modifiers.has('selected-end') ); const hoveredSpan = !selected && ( modifiers.has('hovered-span') || modifiers.has('after-hovered-start') ); const isOutsideRange = modifiers.has('blocked-out-of-range'); const formattedDate = { date: day.format(ariaLabelFormat) }; let ariaLabel = getPhrase(chooseAvailableDate, formattedDate); if (modifiers.has(BLOCKED_MODIFIER) && selected) { ariaLabel = getPhrase(dateIsSelected, formattedDate); } else if (modifiers.has(BLOCKED_MODIFIER)) { ariaLabel = getPhrase(dateIsUnavailable, formattedDate); } else if (selected) { ariaLabel = getPhrase(dateIsSelected, formattedDate); } return { daySizeStyles, useDefaultCursor, selected, hoveredSpan, isOutsideRange, ariaLabel, }; }
import getPhrase from './getPhrase'; import { BLOCKED_MODIFIER } from '../constants'; export default function getCalendarDaySettings(day, ariaLabelFormat, daySize, modifiers, phrases) { const { chooseAvailableDate, dateIsUnavailable, dateIsSelected, } = phrases; const daySizeStyles = { width: daySize, height: daySize - 1, }; const useDefaultCursor = ( modifiers.has('blocked-minimum-nights') || modifiers.has('blocked-calendar') || modifiers.has('blocked-out-of-range') ); const selected = ( modifiers.has('selected') || modifiers.has('selected-start') || modifiers.has('selected-end') ); const hoveredSpan = !selected && ( modifiers.has('hovered-span') || modifiers.has('after-hovered-start') ); const isOutsideRange = modifiers.has('blocked-out-of-range'); const formattedDate = { date: day.format(ariaLabelFormat) }; let ariaLabel = getPhrase(chooseAvailableDate, formattedDate); if (modifiers.has(BLOCKED_MODIFIER)) { ariaLabel = getPhrase(dateIsUnavailable, formattedDate); } else if (selected) { ariaLabel = getPhrase(dateIsSelected, formattedDate); } return { daySizeStyles, useDefaultCursor, selected, hoveredSpan, isOutsideRange, ariaLabel, }; }
Use program arguments to specify ip and ip ranges.
import dto.LiveNode; import java.util.List; public class Client { public static void main(String[] args) { StringBuilder ipList = new StringBuilder(); for (String arg : args) { ipList.append(arg + " "); } String ips = ipList.toString().trim(); CommandExecutor commandExecutor = new CommandExecutor(); String nmapOutput = commandExecutor.execute("nmap --open " + ips + " -p 50070 -oX -"); XmlToJsonConverter converter = new XmlToJsonConverter(); PotentialNameNodeDiscoverer pnd = new PotentialNameNodeDiscoverer(); String jsonString = converter.process(nmapOutput); List<String> potentialNameNodes = pnd.getPotentialNameNodes(jsonString); for (String ip : potentialNameNodes) { String url = "http://" + ip + ":50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo"; HdfsNodeExtractor hdfsNodeExtractor = new HdfsNodeExtractor(url); List<LiveNode> liveDataNodes = hdfsNodeExtractor.getLiveDataNodes(); //hdfsNodeExtractor.prettyPrint(); System.out.print(liveDataNodes); } } }
import dto.LiveNode; import java.util.List; public class Client { public static void main(String[] args) { String ips = "109.231.122.0-100";//"109.231.122.54"; CommandExecutor commandExecutor = new CommandExecutor(); String nmapOutput = commandExecutor.execute("nmap --open " + ips + " -p 50070 -oX -"); XmlToJsonConverter converter = new XmlToJsonConverter(); PotentialNameNodeDiscoverer pnd = new PotentialNameNodeDiscoverer(); String jsonString = converter.process(nmapOutput); List<String> potentialNameNodes = pnd.getPotentialNameNodes(jsonString); for (String ip : potentialNameNodes) { String url = "http://" + ip + ":50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo"; HdfsNodeExtractor hdfsNodeExtractor = new HdfsNodeExtractor(url); List<LiveNode> liveDataNodes = hdfsNodeExtractor.getLiveDataNodes(); //hdfsNodeExtractor.prettyPrint(); System.out.print(liveDataNodes); } //"nmap --open 109.231.122.240 109.231.122.54 -p 50070" } }
Fix import path of PageContainer
import React, { Component } from "react" import { Route } from "react-router" import AppContainer from "./AppContainer" import { default as PhenomicPageContainer } from "phenomic/lib/PageContainer" import Page from "./layouts/Page" import PageError from "./layouts/PageError" import PageLoading from "./layouts/PageLoading" import Homepage from "./layouts/Homepage" import Archive from "./layouts/Archive" import Post from "./layouts/Post" import Tag from "./layouts/Tag" class MainPageContainer extends Component { render() { const { props } = this return ( <PhenomicPageContainer { ...props } layouts={ { Page, PageError, PageLoading, Homepage, Archive, Post, } } logger={ { ...console, info: () => {}, } } /> ) } } export default ( <Route component={ AppContainer }> <Route path="tag/:tag" component={ Tag } /> <Route path="*" component={ MainPageContainer } /> </Route> )
import React, { Component } from "react" import { Route } from "react-router" import AppContainer from "./AppContainer" import { PageContainer as PhenomicPageContainer } from "phenomic" import Page from "./layouts/Page" import PageError from "./layouts/PageError" import PageLoading from "./layouts/PageLoading" import Homepage from "./layouts/Homepage" import Archive from "./layouts/Archive" import Post from "./layouts/Post" import Tag from "./layouts/Tag" class PageContainer extends Component { render() { const { props } = this return ( <PhenomicPageContainer { ...props } layouts={ { Page, PageError, PageLoading, Homepage, Archive, Post, } } logger={ { ...console, info: () => {}, } } /> ) } } export default ( <Route component={ AppContainer }> <Route path="tag/:tag" component={ Tag } /> <Route path="*" component={ PageContainer } /> </Route> )
Add category path in category helper The path allows to make a category link with `url_for(category.path)`. Built from bbfd0979098c6e8588c95878a0b00a27bd08af55.
var _ = require('lodash'); var regexCache = { post: {} }; hexo.extend.helper.register('is_post', function() { var permalink = this.config.permalink; var r = regexCache.post[permalink]; if (!r) { var rUrl = permalink .replace(':lang', '[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*') .replace(':id', '\\d+') .replace(':category', '(\\w+\\/?)+') .replace(':year', '\\d{4}') .replace(/:(month|day)/g, '\\d{2}') .replace(/:i_(month|day)/g, '\\d{1,2}') .replace(/:title/, '[^\\/]+'); r = regexCache.post[permalink] = new RegExp(rUrl); } return r.test(this.path); }); hexo.extend.helper.register('get_categories_for_lang', function(lang) { var result = []; _.each(this.site.data.categories, function(category, title) { _.each(category, function(data, categoryLang) { if (lang == categoryLang) { result = result.concat({ title: data.name, path: lang + '/' + data.slug }); } }); }); return result; });
var _ = require('lodash'); var regexCache = { post: {} }; hexo.extend.helper.register('is_post', function() { var permalink = this.config.permalink; var r = regexCache.post[permalink]; if (!r) { var rUrl = permalink .replace(':lang', '[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*') .replace(':id', '\\d+') .replace(':category', '(\\w+\\/?)+') .replace(':year', '\\d{4}') .replace(/:(month|day)/g, '\\d{2}') .replace(/:i_(month|day)/g, '\\d{1,2}') .replace(/:title/, '[^\\/]+'); r = regexCache.post[permalink] = new RegExp(rUrl); } return r.test(this.path); }); hexo.extend.helper.register('get_categories_for_lang', function(lang) { var result = []; _.each(this.site.data.categories, function(category, title) { _.each(category, function(data, categoryLang) { if (lang == categoryLang) { result = result.concat({ title: data.name }); } }); }); return result; });
Reorder operations in email confirmation resolver.
import bind from "lib/helper/graphql/normalizeParams" import BadRequest from "lib/error/http/BadRequest" import waterfall from "lib/helper/array/runWaterfall" import db from "lib/db/connection" import {get, remove} from "lib/auth/tokens" import User from "model/User" import Session from "model/Session" const confirmEmail = ({args, ctx}) => db.transaction(async transaction => { const {client} = ctx.state const {hash} = args const id = await get(hash) if (!id) { throw new BadRequest("The user cannot be activated: Bad token signature.") } let user = await User.findByPk(id, {transaction}) if (!user) { throw new BadRequest("There's no such user.") } user = await waterfall([ () => Session.destroy({where: {userId: user.id}, transaction}), () => user.update({status: User.statuses.active}, {transaction}), () => remove(hash), () => user.reload({transaction}) ]) const tokens = await Session.sign({ client, user: user.toJSON() }, {transaction}) return user.update({lastVisited: new Date()}, {transaction}) .then(() => tokens) }) export default confirmEmail |> bind
import bind from "lib/helper/graphql/normalizeParams" import BadRequest from "lib/error/http/BadRequest" import waterfall from "lib/helper/array/runWaterfall" import db from "lib/db/connection" import {get, remove} from "lib/auth/tokens" import User from "model/User" import Session from "model/Session" const confirmEmail = ({args, ctx}) => db.transaction(async transaction => { const {client} = ctx.state const {hash} = args const id = await get(hash) if (!id) { throw new BadRequest("The user cannot be activated: Bad token signature.") } let user = await User.findByPk(id, {transaction}) if (!user) { throw new BadRequest("There's no such user.") } user = await waterfall([ () => remove(hash), () => Session.destroy({where: {userId: user.id}, transaction}), () => user.update({status: User.statuses.active}, {transaction}), () => user.reload({transaction}) ]) const tokens = await Session.sign({ client, user: user.toJSON() }, {transaction}) return user.update({lastVisited: new Date()}, {transaction}) .then(() => tokens) }) export default confirmEmail |> bind
Make Node syncs a noop
import os from django.db import models from core.models import PlCoreBase from core.models.plcorebase import StrippedCharField from core.models import Site, SiteDeployment, SitePrivilege from core.models import Tag from django.contrib.contenttypes import generic # Create your models here. class Node(PlCoreBase): name = StrippedCharField(max_length=200, unique=True, help_text="Name of the Node") site_deployment = models.ForeignKey(SiteDeployment, related_name='nodes') site = models.ForeignKey(Site, null=True, blank=True, related_name='nodes') tags = generic.GenericRelation(Tag) def __unicode__(self): return u'%s' % (self.name) def __init__(self, *args, **kwargs): super(Node, self).__init__(*args, **kwargs) self.no_sync=True def save(self, *args, **kwds): if self.site is None and self.site_deployment is not None: self.site = self.site_deployment.site super(Node, self).save(*args, **kwds) def can_update(self, user): return user.can_update_site(self.site, allow=['tech'])
import os from django.db import models from core.models import PlCoreBase from core.models.plcorebase import StrippedCharField from core.models import Site, SiteDeployment, SitePrivilege from core.models import Tag from django.contrib.contenttypes import generic # Create your models here. class Node(PlCoreBase): name = StrippedCharField(max_length=200, unique=True, help_text="Name of the Node") site_deployment = models.ForeignKey(SiteDeployment, related_name='nodes') site = models.ForeignKey(Site, null=True, blank=True, related_name='nodes') tags = generic.GenericRelation(Tag) def __unicode__(self): return u'%s' % (self.name) def save(self, *args, **kwds): if self.site is None and self.site_deployment is not None: self.site = self.site_deployment.site super(Node, self).save(*args, **kwds) def can_update(self, user): return user.can_update_site(self.site, allow=['tech'])
Delete board_slug parameter on 'delete_post' url
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'), url(r'^(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'), url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'), url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'), url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'), ]
# Created by JHJ on 2016. 10. 5. from django.conf.urls import url from . import views app_name = 'board' urlpatterns = [ url(r'^$', views.board_list, name='board_list'), url(r'^(?P<board_slug>[-\w]+)/$', views.post_list, name='post_list'), url(r'^(?P<board_slug>[-\w]+)/new/$', views.new_post, name='new_post'), url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/delete/$', views.delete_post, name='delete_post'), url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/$', views.view_post, name='view_post'), url(r'^(?P<board_slug>[-\w]+)/(?P<post_id>\d+)/comment/new/$', views.new_comment, name='new_comment'), url(r'^(?P<post_id>\d+)/comment/delete/$', views.delete_comment, name='delete_comment'), ]
Fix typo for infringement link in footer Fixes #1619
const React = require("react"); exports.Footer = class Footer extends React.Component { render() { return ( <div className="footer"> <div className="responsive-wrapper row-space"> <div className="legal-links"> <a href="/terms">Terms</a> <a href="/privacy">Privacy Notice</a> <a href="https://www.mozilla.org/en-US/about/legal/report-infringement/" target="_blank">Report IP Infringement</a> <a href={ `mailto:pageshot-feedback@mozilla.com?subject=Page%20Shot%20Feedback&body=Feedback%20regarding:%20${this.props.forUrl}` } target="_blank">Send Feedback</a> <a href="/leave-page-shot">Leave Page Shot</a> </div> </div> </div> ); } };
const React = require("react"); exports.Footer = class Footer extends React.Component { render() { return ( <div className="footer"> <div className="responsive-wrapper row-space"> <div className="legal-links"> <a href="/terms">Terms</a> <a href="/privacy">Privacy Notice</a> <a href="https://www.mozilla.org/en-US/about/legal/report-infringement/" target="_blank">Report IP Infrigement</a> <a href={ `mailto:pageshot-feedback@mozilla.com?subject=Page%20Shot%20Feedback&body=Feedback%20regarding:%20${this.props.forUrl}` } target="_blank">Send Feedback</a> <a href="/leave-page-shot">Leave Page Shot</a> </div> </div> </div> ); } };
Document @cache-store and @config-store used.
<?php /** * SimpleComplex PHP Config * @link https://github.com/simplecomplex/php-config * @copyright Copyright (c) 2017 Jacob Friis Mathiasen * @license https://github.com/simplecomplex/php-config/blob/master/LICENSE (MIT License) */ declare(strict_types=1); namespace SimpleComplex\Config; /** * Convenience class. * * Consider sub-classing, to make it easier shifting to another * SectionedConfigInterface implementation. * Then to shift, simply extend another class than this. * * @dependency-injection-container config * Suggested ID of the Config 'global' instance. * * @cache-store config.global * Name of cache store used by this class (effectively). * * @config-store global * Name of config store used by this class (effectively). * * @package SimpleComplex\Config */ class Config extends IniSectionedConfig { /** * @var IniSectionedConfig[] */ protected static $instances = []; /** * First object instantiated via this method and with that arg name, * disregarding class called on. * * @deprecated Use a dependency injection container instead. * @see \SimpleComplex\Utils\Dependency * @see \Slim\Container * * @param string $name * Default: global * * @return IniSectionedConfig|static */ public static function getInstance($name = 'global') { return static::$instances[$name] ?? (static::$instances[$name] = new static($name)); } }
<?php /** * SimpleComplex PHP Config * @link https://github.com/simplecomplex/php-config * @copyright Copyright (c) 2017 Jacob Friis Mathiasen * @license https://github.com/simplecomplex/php-config/blob/master/LICENSE (MIT License) */ declare(strict_types=1); namespace SimpleComplex\Config; /** * Convenience class. * * Consider sub-classing, to make it easier shifting to another * SectionedConfigInterface implementation. * Then to shift, simply extend another class than this. * * @dependency-injection-container config * Suggested ID of the Config 'global' instance. * * @package SimpleComplex\Config */ class Config extends IniSectionedConfig { /** * @var IniSectionedConfig[] */ protected static $instances = []; /** * First object instantiated via this method and with that arg name, * disregarding class called on. * * @deprecated Use a dependency injection container instead. * @see \SimpleComplex\Utils\Dependency * @see \Slim\Container * * @param string $name * Default: global * * @return IniSectionedConfig|static */ public static function getInstance($name = 'global') { return static::$instances[$name] ?? (static::$instances[$name] = new static($name)); } }
fix: Print error to avoid silent failure
const sass = require('node-sass'); const fs = require('fs'); const path = require('path'); const { apps_list, get_app_path, get_public_path, get_options_for_scss } = require('./rollup/rollup.utils'); const output_path = process.argv[2]; let scss_content = process.argv[3]; scss_content = scss_content.replace(/\\n/g, '\n'); sass.render({ data: scss_content, outputStyle: 'compressed', importer: function(url) { if (url.startsWith('~')) { // strip ~ so that it can resolve from node_modules return { file: url.slice(1) }; } // normal file, let it go return { file: url }; }, ...get_options_for_scss() }, function(err, result) { if (err) { console.error(err.formatted); // eslint-disable-line return; } fs.writeFile(output_path, result.css, function(err) { if (!err) { console.log(output_path); // eslint-disable-line } else { console.error(err); } }); });
const sass = require('node-sass'); const fs = require('fs'); const path = require('path'); const { apps_list, get_app_path, get_public_path, get_options_for_scss } = require('./rollup/rollup.utils'); const output_path = process.argv[2]; let scss_content = process.argv[3]; scss_content = scss_content.replace(/\\n/g, '\n'); sass.render({ data: scss_content, outputStyle: 'compressed', importer: function(url) { if (url.startsWith('~')) { // strip ~ so that it can resolve from node_modules return { file: url.slice(1) }; } // normal file, let it go return { file: url }; }, ...get_options_for_scss() }, function(err, result) { if (err) { console.error(err.formatted); // eslint-disable-line return; } fs.writeFile(output_path, result.css, function(err) { if (!err) { console.log(output_path); // eslint-disable-line } }); });
Replace deprecated attr call with get
module.exports = function(can){ return function(data){ // If this is not a CanJS project if(typeof can === "undefined" || !can.view) { return {}; } var oldCanImport; var canImport = function(el, tagData){ var moduleName = el.getAttribute("from"); var templateModule = tagData.options.get("helpers.module"); var parentName = templateModule ? templateModule.id : undefined; var isAPage = !!tagData.subtemplate; var loader = doneSsr.loader; loader.normalize(moduleName, parentName).then(function(name){ if(isAPage) { loader.__ssrParentMap[name] = false; } var pages = data.pages; if(!pages) { pages = data.pages = []; } pages.push(name); }); oldCanImport.apply(this, arguments); }; return { beforeTask: function(){ oldCanImport = can.view.callbacks._tags["can-import"]; can.view.callbacks._tags["can-import"] = canImport; }, afterTask: function(){ can.view.callbacks._tags["can-import"] = oldCanImport; } }; }; };
module.exports = function(can){ return function(data){ // If this is not a CanJS project if(typeof can === "undefined" || !can.view) { return {}; } var oldCanImport; var canImport = function(el, tagData){ var moduleName = el.getAttribute("from"); var templateModule = tagData.options.attr("helpers.module"); var parentName = templateModule ? templateModule.id : undefined; var isAPage = !!tagData.subtemplate; var loader = doneSsr.loader; loader.normalize(moduleName, parentName).then(function(name){ if(isAPage) { loader.__ssrParentMap[name] = false; } var pages = data.pages; if(!pages) { pages = data.pages = []; } pages.push(name); }); oldCanImport.apply(this, arguments); }; return { beforeTask: function(){ oldCanImport = can.view.callbacks._tags["can-import"]; can.view.callbacks._tags["can-import"] = canImport; }, afterTask: function(){ can.view.callbacks._tags["can-import"] = oldCanImport; } }; }; };
Fix eventDispatcher version helper to work with symfony 5 dev
<?php namespace Overblog\GraphQLBundle\Event; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpKernel\Kernel; /** * @internal * TODO(mcg-web): delete hack after migrating Symfony >= 4.3 */ final class EventDispatcherVersionHelper { /** * @return bool */ public static function isForLegacy() { return Kernel::VERSION_ID < 403000; } /** * @param EventDispatcherInterface $dispatcher * @param object $event * @param string|null $eventName * * @return object the event */ public static function dispatch(EventDispatcherInterface $dispatcher, $event, $eventName) { if (self::isForLegacy()) { return $dispatcher->dispatch($eventName, $event); } else { return $dispatcher->dispatch($event, $eventName); } } }
<?php namespace Overblog\GraphQLBundle\Event; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpKernel\Kernel; /** * @internal * TODO(mcg-web): delete hack after migrating Symfony >= 4.3 */ final class EventDispatcherVersionHelper { private static $isForLegacy; /** * @return bool */ public static function isForLegacy() { if (null === self::$isForLegacy) { self::$isForLegacy = \version_compare(Kernel::VERSION, '4.3.0', '<'); } return self::$isForLegacy; } /** * @param EventDispatcherInterface $dispatcher * @param object $event * @param string|null $eventName * * @return object the event */ public static function dispatch(EventDispatcherInterface $dispatcher, $event, $eventName) { if (self::isForLegacy()) { return $dispatcher->dispatch($eventName, $event); } else { return $dispatcher->dispatch($event, $eventName); } } }
Fix some things for code smell
package main import ( "log" "runtime" "github.com/hashicorp/terraform/helper/schema" "github.com/keybase/go-keychain" ) func passwordRetrievalFunc(envVar string, dv interface{}) schema.SchemaDefaultFunc { return func() (interface{}, error) { if runtime.GOOS == "darwin" { log.Println("[INFO] On macOS so trying the keychain") query := keychain.NewItem() query.SetSecClass(keychain.SecClassGenericPassword) query.SetService("alkscli") query.SetAccount("alksuid") query.SetMatchLimit(keychain.MatchLimitOne) query.SetReturnData(true) results, err := keychain.QueryItem(query) if err != nil { log.Println("[WARN] Error accessing the macOS keychain. Falling back to environment variables") log.Println(err) } else { return string(results[0].Data), nil } } return schema.EnvDefaultFunc(envVar, dv)() } }
package main import ( "github.com/hashicorp/terraform/helper/schema" "github.com/keybase/go-keychain" "log" "runtime" ) func passwordRetrievalFunc(env_var string, dv interface{}) schema.SchemaDefaultFunc { return func() (interface{}, error) { if runtime.GOOS == "darwin" { log.Println("[INFO] On macOS so trying the keychain") query := keychain.NewItem() query.SetSecClass(keychain.SecClassGenericPassword) query.SetService("alkscli") query.SetAccount("alksuid") query.SetMatchLimit(keychain.MatchLimitOne) query.SetReturnData(true) results, err := keychain.QueryItem(query) if err != nil { log.Println("[WARN] Error accessing the macOS keychain. Falling back to environment variables") log.Println(err) } else { return string(results[0].Data), nil } } return schema.EnvDefaultFunc(env_var, dv)() } }
Fix service provider not registering SQS FIFO connector
<?php namespace Maqe\LaravelSqsFifo; use Illuminate\Support\ServiceProvider; use Maqe\LaravelSqsFifo\Connectors\SqsFifoConnector; class LaravelSqsFifoServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app->afterResolving('queue', function ($manager) { $this->registerSqsFifoConnector($manager); }); } /** * Register the Amazon SQS FIFO queue connector. * * @param \Illuminate\Queue\QueueManager $manager * @return void */ protected function registerSqsFifoConnector($manager) { $manager->addConnector('sqsfifo', function () { return new SqsFifoConnector; }); } }
<?php namespace Maqe\LaravelSqsFifo; use Illuminate\Support\ServiceProvider; use Maqe\LaravelSqsFifo\Connectors\SqsFifoConnector; class LaravelSqsFifoServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $queueManager = $this->app['queue']; $this->registerSqsFifoConnector($queueManager); } /** * Register the Amazon SQS FIFO queue connector. * * @param \Illuminate\Queue\QueueManager $manager * @return void */ protected function registerSqsFifoConnector($manager) { $manager->addConnector('sqsfifo', function () { return new SqsFifoConnector; }); } }
Make globalName nullable for now.
#!/usr/bin/python3 import os import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Member(Base): __tablename__ = 'member' id = Column(Integer, primary_key=True) globalName = Column(String(250), nullable=True) nickname = Column(String(250), nullable=True) role = Column(String(250), nullable=True) points = Column(Integer, nullable=True) def __init__(self,id,globalAccountName,serverNickname,role,points): self.id = id self.globalAccountName = globalAccountName self.serverNickname = serverNickname self.role = role self.points = points #Display member method. def displayMember(self): print ("ID:", self.id, "GlobalAccount:", self.globalName, "Nickname:", self.Nickname, "Role:", self.role, "Points:", self.points) #Example of creating one object, changing value of an object and displaying an object using a method. '''mem1 = Member(43344454,"larry","doessuck","officer",150) mem1.globalAccountName="Jack" mem1.displayMember()''' engine = create_engine('sqlite:///bayohwoolph.db') Base.metadata.create_all(engine)
#!/usr/bin/python3 import os import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Member(Base): __tablename__ = 'member' id = Column(Integer, primary_key=True) globalName = Column(String(250), nullable=False) nickname = Column(String(250), nullable=True) role = Column(String(250), nullable=True) points = Column(Integer, nullable=True) def __init__(self,id,globalAccountName,serverNickname,role,points): self.id = id self.globalAccountName = globalAccountName self.serverNickname = serverNickname self.role = role self.points = points #Display member method. def displayMember(self): print ("ID:", self.id, "GlobalAccount:", self.globalName, "Nickname:", self.Nickname, "Role:", self.role, "Points:", self.points) #Example of creating one object, changing value of an object and displaying an object using a method. '''mem1 = Member(43344454,"larry","doessuck","officer",150) mem1.globalAccountName="Jack" mem1.displayMember()''' engine = create_engine('sqlite:///bayohwoolph.db') Base.metadata.create_all(engine)
Change autoprefix browser specific key
module.exports = () => { return { use: [ 'postcss-flexbugs-fixes', 'autoprefixer', ], map: { inline: false, annotation: true, sourcesContent: true, }, plugins: { autoprefixer: { cascade: false, // https://github.com/twbs/bootstrap/blob/v4.0.0/package.json#L136-L147 overrideBrowserslist: [ 'last 1 major version', '>= 1%', 'Chrome >= 45', 'Firefox >= 38', 'Edge >= 12', 'Explorer >= 10', 'iOS >= 9', 'Safari >= 9', 'Android >= 4.4', 'Opera >= 30', ], }, }, }; };
module.exports = () => { return { use: [ 'postcss-flexbugs-fixes', 'autoprefixer', ], map: { inline: false, annotation: true, sourcesContent: true, }, plugins: { autoprefixer: { cascade: false, // https://github.com/twbs/bootstrap/blob/v4.0.0/package.json#L136-L147 browsers: [ 'last 1 major version', '>= 1%', 'Chrome >= 45', 'Firefox >= 38', 'Edge >= 12', 'Explorer >= 10', 'iOS >= 9', 'Safari >= 9', 'Android >= 4.4', 'Opera >= 30', ], }, }, }; };
Support expanding prompting macro not from EDT (GO-9289) GitOrigin-RevId: fdded0455fbeb18873b49c90e2084b6fc2ecf487
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.macro; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Ref; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Eugene Zhuravlev */ public abstract class PromptingMacro extends Macro{ @Override public final String expand(@NotNull DataContext dataContext) throws ExecutionCancelledException { Ref<String> userInput = Ref.create(); ApplicationManager.getApplication().invokeAndWait(() -> userInput.set(promptUser(dataContext))); if (userInput.isNull()) { throw new ExecutionCancelledException(); } return userInput.get(); } /** * Called from expand() method * * @param dataContext * @return user input. If null is returned, ExecutionCancelledException is thrown by expand() method */ @Nullable protected abstract String promptUser(DataContext dataContext); }
/* * Copyright 2000-2011 JetBrains s.r.o. * * 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.intellij.ide.macro; import com.intellij.openapi.actionSystem.DataContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Eugene Zhuravlev */ public abstract class PromptingMacro extends Macro{ @Override public final String expand(@NotNull DataContext dataContext) throws ExecutionCancelledException { final String userInput = promptUser(dataContext); if (userInput == null) { throw new ExecutionCancelledException(); } return userInput; } /** * Called from expand() method * * @param dataContext * @return user input. If null is returned, ExecutionCancelledException is thrown by expand() method */ @Nullable protected abstract String promptUser(DataContext dataContext); }
Remove workaround for malformatted read all response.
angular.module('starter') .controller('DashCtrl', ["$scope", "Todo", function($scope, Todo) { $scope.todos = []; Todo.find() .$promise .then(function(todos){ $scope.todos = todos; //console.log($scope.todos); }); }]) .controller('ChatsCtrl', ["$scope", "Message", function($scope, Message) { $scope.chats = []; Message.find() .$promise .then(function(records){ $scope.chats = records; // console.log(records); }); }]) .controller('ChatDetailCtrl', ["$scope", "Chats", function($scope, $stateParams, Chats) { $scope.chat = Chats.get($stateParams.chatId); }]) .controller('GalleryCtrl', ["$scope", "Submissions", function($scope, Submissions) { $scope.submissions = Submissions.all(); }]) .controller('FriendsCtrl', ["$scope", "Friends", function($scope, Friends) { $scope.friends = Friends.all(); }]) .controller('FriendDetailCtrl', ["$scope", "Friends", function($scope, $stateParams, Friends) { $scope.friend = Friends.get($stateParams.friendId); }]) .controller('AccountCtrl', ["$scope", function($scope) { $scope.settings = { enableFriends: true }; }]);
function cleanRecords(records) { return records.map(function(item) { return item.rtd; }); } function cleanRecord(record) { return record.rtd; } angular.module('starter') .controller('DashCtrl', ["$scope", "Todo", function($scope, Todo) { $scope.todos = []; Todo.find() .$promise .then(function(todos){ $scope.todos = cleanRecords(todos); //console.log($scope.todos); }); }]) .controller('ChatsCtrl', ["$scope", "Message", function($scope, Message) { $scope.chats = []; Message.find() .$promise .then(function(records){ $scope.chats = cleanRecords(records); // console.log(records); }); }]) .controller('ChatDetailCtrl', ["$scope", "Chats", function($scope, $stateParams, Chats) { $scope.chat = Chats.get($stateParams.chatId); }]) .controller('GalleryCtrl', ["$scope", "Submissions", function($scope, Submissions) { $scope.submissions = Submissions.all(); }]) .controller('FriendsCtrl', ["$scope", "Friends", function($scope, Friends) { $scope.friends = Friends.all(); }]) .controller('FriendDetailCtrl', ["$scope", "Friends", function($scope, $stateParams, Friends) { $scope.friend = Friends.get($stateParams.friendId); }]) .controller('AccountCtrl', ["$scope", function($scope) { $scope.settings = { enableFriends: true }; }]);
Disable screensaver when playing videos
/* * Copyright 2017 Martin Kamp Jensen * * 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.github.mkjensen.tv.ondemand; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; import android.view.WindowManager; public class PlaybackActivity extends FragmentActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(android.R.id.content, new PlaybackFragment()) .commit(); } } }
/* * Copyright 2017 Martin Kamp Jensen * * 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.github.mkjensen.tv.ondemand; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; public class PlaybackActivity extends FragmentActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(android.R.id.content, new PlaybackFragment()) .commit(); } } }
Add min and max prop
import React, { Component } from 'react'; import AgileTextField from '../AgileTextField'; import numberValidator from '../Utils/Validators/number'; const styles = { }; class NumberField extends Component { render() { const {minValue, maxValue, ...passThroughProps} = this.props; return ( <AgileTextField type="text" validateInput={true} validator={numberValidator(minValue, maxValue)} {...passThroughProps} /> ); } }; NumberField.propTypes = { name: React.PropTypes.string, label: React.PropTypes.string.isRequired, hintText: React.PropTypes.string, onStateChange: React.PropTypes.func, onValueChange: React.PropTypes.func, feedbackElement: React.PropTypes.func, style: React.PropTypes.object, disabled: React.PropTypes.bool, minValue: React.PropTypes.number, maxValue: React.PropTypes.number }; // Specifies the default values for props: NumberField.defaultProps = { name: 'number', style: styles, minValue: -Infinity, maxValue: Infinity }; export default NumberField;
import React, { Component } from 'react'; import AgileTextField from '../AgileTextField'; import numberValidator from '../Utils/Validators/number'; const styles = { }; class NumberField extends Component { render() { const {...passThroughProps} = this.props; return ( <AgileTextField type="text" validateInput={true} {...passThroughProps} /> ); } }; NumberField.propTypes = { name: React.PropTypes.string, label: React.PropTypes.string.isRequired, hintText: React.PropTypes.string, onStateChange: React.PropTypes.func, onValueChange: React.PropTypes.func, feedbackElement: React.PropTypes.func, style: React.PropTypes.object, disabled: React.PropTypes.bool, }; // Specifies the default values for props: NumberField.defaultProps = { name: 'number', validator: numberValidator, style: styles, }; export default NumberField;
Convert non-200 fetch responses into errors
var util = require('./util'); module.exports = function fetchFeed(delegate) { // delegate.url: a url string // delegate.verbose: a bool // delegate.onError: an error handler // delegate.onResponse: a response and data handler var request = util.request(delegate.url); request.on('error', function(e) { util.log(e.message); delegate.onError(e); }); request.on('response', function(response) { util.log('status', response.statusCode); util.log('headers', JSON.stringify(response.headers)); if (response.statusCode !== 200) { delegate.onError({ code: response.statusCode, message: response.statusMessage }); return; } var data = ''; response.setEncoding('utf8'); response.on('data', function(chunk) { data += chunk; }).on('end', function() { if (delegate.verbose) { util.log('data', data); } delegate.onResponse(response, data); }); }); request.end(); };
var util = require('./util'); module.exports = function fetchFeed(delegate) { // delegate.url: a url string // delegate.verbose: a bool // delegate.onError: an error handler // delegate.onResponse: a response and data handler var request = util.request(delegate.url); request.on('error', function(e) { util.log(e.message); delegate.onError(e); }); request.on('response', function(response) { util.log('status', response.statusCode); util.log('headers', JSON.stringify(response.headers)); var data = ''; response.setEncoding('utf8'); response.on('data', function(chunk) { data += chunk; }).on('end', function() { if (delegate.verbose) { util.log('data', data); } delegate.onResponse(response, data); }); }); request.end(); };
Revert "Moved JS in front of HTML" This reverts commit 8b0164edde418138d4e28c20d63fa422931ae6a8.
"""Global configuration class.""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.utils.traitlets import List from IPython.config.configurable import LoggingConfigurable from IPython.utils.traitlets import Unicode #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- class NbConvertBase(LoggingConfigurable): """Global configurable class for shared config Useful for display data priority that might be use by many transformers """ display_data_priority = List(['html', 'javascript', 'application/pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text'], config=True, help= """ An ordered list of preferred output type, the first encountered will usually be used when converting discarding the others. """ ) default_language = Unicode('ipython', config=True, help='default highlight language') def __init__(self, **kw): super(NbConvertBase, self).__init__(**kw)
"""Global configuration class.""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.utils.traitlets import List from IPython.config.configurable import LoggingConfigurable from IPython.utils.traitlets import Unicode #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- class NbConvertBase(LoggingConfigurable): """Global configurable class for shared config Useful for display data priority that might be use by many transformers """ display_data_priority = List(['javascript', 'html', 'application/pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text'], config=True, help= """ An ordered list of preferred output type, the first encountered will usually be used when converting discarding the others. """ ) default_language = Unicode('ipython', config=True, help='default highlight language') def __init__(self, **kw): super(NbConvertBase, self).__init__(**kw)
Add a real roll command
import discord import duckbot_settings import random from discord.ext import commands _DESCRIPTION = '''quack''' bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) rand = random.SystemRandom() @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) print('Channels:') channels = bot.get_all_channels() for channel in channels: print('%s (%s)' % (channel.name, channel.id)) if channel.name == 'botspam': await bot.send_message(channel, 'quack!! (ready to roll)') @bot.command() async def roll(): lower_bound = 1 upper_boundb = 6 await bot.say('🎲 (%d-%d): %d' % (lower_bound, upper_bound, rand.randint(lower_bound, upper_bound))) bot.run(duckbot_settings.TOKEN)
import discord import duckbot_settings import random from discord.ext import commands _DESCRIPTION = '''quack''' bot = commands.Bot(command_prefix='/', description=_DESCRIPTION) @bot.event async def on_ready(): print('logged in: %s (%s)' % (bot.user.name, bot.user.id)) oauth_url = discord.utils.oauth_url(duckbot_settings.CLIENT_ID, permissions=discord.Permissions.text()) print('invite me: %s' % oauth_url) print('Channels:') channels = bot.get_all_channels() for channel in channels: print('%s (%s)' % (channel.name, channel.id)) if channel.name == 'botspam': await bot.send_message(channel, 'quack!! (ready to roll)') @bot.command() async def roll(): await bot.say('pretending to roll') bot.run(duckbot_settings.TOKEN)
Update api test util to create files to use target name instead
from blinker import ANY from urlparse import urlparse from contextlib import contextmanager from addons.osfstorage import settings as osfstorage_settings def create_test_file(target, user, filename='test_file', create_guid=True): osfstorage = target.get_addon('osfstorage') root_node = osfstorage.get_root() test_file = root_node.append_file(filename) if create_guid: test_file.get_guid(create=True) test_file.create_version(user, { 'object': '06d80e', 'service': 'cloud', osfstorage_settings.WATERBUTLER_RESOURCE: 'osf', }, { 'size': 1337, 'contentType': 'img/png' }).save() return test_file def urlparse_drop_netloc(url): url = urlparse(url) if url[4]: return url[2] + '?' + url[4] return url[2] @contextmanager def disconnected_from_listeners(signal): """Temporarily disconnect all listeners for a Blinker signal.""" listeners = list(signal.receivers_for(ANY)) for listener in listeners: signal.disconnect(listener) yield for listener in listeners: signal.connect(listener)
from blinker import ANY from urlparse import urlparse from contextlib import contextmanager from addons.osfstorage import settings as osfstorage_settings def create_test_file(node, user, filename='test_file', create_guid=True): osfstorage = node.get_addon('osfstorage') root_node = osfstorage.get_root() test_file = root_node.append_file(filename) if create_guid: test_file.get_guid(create=True) test_file.create_version(user, { 'object': '06d80e', 'service': 'cloud', osfstorage_settings.WATERBUTLER_RESOURCE: 'osf', }, { 'size': 1337, 'contentType': 'img/png' }).save() return test_file def urlparse_drop_netloc(url): url = urlparse(url) if url[4]: return url[2] + '?' + url[4] return url[2] @contextmanager def disconnected_from_listeners(signal): """Temporarily disconnect all listeners for a Blinker signal.""" listeners = list(signal.receivers_for(ANY)) for listener in listeners: signal.disconnect(listener) yield for listener in listeners: signal.connect(listener)
Add get retrieval of FormData
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import java.util.*; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet that takes in audio stream and retrieves ** user input string to display. */ @WebServlet("/audio-input") public class AudioInputServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { Object formdata = request.getParameter("file"); System.out.println(formdata); System.out.println("Got to servlet"); //response.setContentType("text/html;"); //response.getWriter().println("<h1>Hello world!</h1>"); } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.sps.servlets; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Servlet that takes in audio stream and retrieves ** user input string to display. */ @WebServlet("/audio-input") public class AudioInputServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;"); response.getWriter().println("<h1>Hello world!</h1>"); } }
Make sure tree is properly displayed on missing types
package com.redhat.ceylon.compiler.model; import com.redhat.ceylon.compiler.tree.Tree; import java.util.ArrayList; import java.util.List; public class Type extends Model { List<Type> typeArguments = new ArrayList<Type>(); GenericType genericType; public GenericType getGenericType() { return genericType; } public void setGenericType(GenericType type) { this.genericType = type; } public List<Type> getTypeArguments() { return typeArguments; } @Override public String toString() { return "Type[" + getProducedTypeName() + "]"; } public String getProducedTypeName() { if (genericType == null) { //unknown type return null; } String producedTypeName = genericType.getName(); if (!typeArguments.isEmpty()) { producedTypeName+="<"; for (Type t: typeArguments) { producedTypeName+=t.getProducedTypeName(); } producedTypeName+=">"; } return producedTypeName; } }
package com.redhat.ceylon.compiler.model; import java.util.ArrayList; import java.util.List; public class Type extends Model { List<Type> typeArguments = new ArrayList<Type>(); GenericType genericType; public GenericType getGenericType() { return genericType; } public void setGenericType(GenericType type) { this.genericType = type; } public List<Type> getTypeArguments() { return typeArguments; } @Override public String toString() { return "Type[" + getProducedTypeName() + "]"; } public String getProducedTypeName() { String producedTypeName = genericType.getName(); if (!typeArguments.isEmpty()) { producedTypeName+="<"; for (Type t: typeArguments) { producedTypeName+=t.getProducedTypeName(); } producedTypeName+=">"; } return producedTypeName; } }
Remove redundand props & imports
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import Loader from '../Loader'; import LoginContainer from '../Login/LoginContainer'; import './Header.scss'; export class Header extends React.Component { render () { const { isFetching } = this.props; return ( <div> <nav className='navbar navbar-inverse container-fluid'> <Link to='/' className='brand-title navbar-brand'> Tiedonohjausjärjestelmä v{VERSION} </Link> <LoginContainer /> </nav> <Loader show={isFetching}/> </div> ); } } Header.propTypes = { isFetching: React.PropTypes.bool }; const mapStateToProps = (state) => { return { isFetching: state.ui.isFetching || state.navigation.isFetching || state.selectedTOS.isFetching }; }; export default connect(mapStateToProps)(Header);
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { setNavigationVisibility } from '../Navigation/reducer'; import Loader from '../Loader'; import LoginContainer from '../Login/LoginContainer'; import './Header.scss'; export class Header extends React.Component { render () { const { isFetching } = this.props; return ( <div> <nav className='navbar navbar-inverse container-fluid'> <Link to='/' className='brand-title navbar-brand'> Tiedonohjausjärjestelmä v{VERSION} </Link> <LoginContainer /> </nav> <Loader show={isFetching}/> </div> ); } } Header.propTypes = { isFetching: React.PropTypes.bool, setNavigationVisibility: React.PropTypes.func }; const mapStateToProps = (state) => { return { isFetching: state.ui.isFetching || state.navigation.isFetching || state.selectedTOS.isFetching }; }; const mapDispatchToProps = (dispatch) => { return { setNavigationVisibility: bindActionCreators(setNavigationVisibility, dispatch) }; }; export default connect(mapStateToProps, mapDispatchToProps)(Header);
system: Fix wrongly redefining an already abstract method in the WebController
<?php /** * This file contains an abstract WebController class, * containing methods specifically targeted for the * Web Usage. * * PHP Version 5.3 * * @category Libraries * @package Core * @subpackage Libraries * @author M2Mobi <info@m2mobi.com> * @author Heinz Wiesinger <heinz@m2mobi.com> */ /** * Web Controller class * * @category Libraries * @package Core * @subpackage Libraries * @author M2Mobi <info@m2mobi.com> * @author Heinz Wiesinger <heinz@m2mobi.com> */ abstract class WebController extends Controller { /** * Constructor */ public function __construct() { parent::__construct(); } /** * Destructor */ public function __destruct() { parent::__destruct(); } /** * Handle unimplemented calls * * @param String $name Method name * @param array $arguments Arguments passed to the method * * @return String JSON encoded error String */ public function __call($name, $arguments) { return "<h1>Not implemented</h1>"; } } ?>
<?php /** * This file contains an abstract WebController class, * containing methods specifically targeted for the * Web Usage. * * PHP Version 5.3 * * @category Libraries * @package Core * @subpackage Libraries * @author M2Mobi <info@m2mobi.com> * @author Heinz Wiesinger <heinz@m2mobi.com> */ /** * Web Controller class * * @category Libraries * @package Core * @subpackage Libraries * @author M2Mobi <info@m2mobi.com> * @author Heinz Wiesinger <heinz@m2mobi.com> */ abstract class WebController extends Controller { /** * Constructor */ public function __construct() { parent::__construct(); } /** * Destructor */ public function __destruct() { parent::__destruct(); } /** * Handle unimplemented calls * * @param String $name Method name * @param array $arguments Arguments passed to the method * * @return String JSON encoded error String */ public function __call($name, $arguments) { return "<h1>Not implemented</h1>"; } /** * Default method as defined in conf.application.inc.php * * @return void */ abstract public function index(); } ?>
[Sf6] Add UserBundle mappings to Symfony6 support
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\UserBundle; use Sylius\Bundle\ResourceBundle\AbstractResourceBundle; use Sylius\Bundle\ResourceBundle\SyliusResourceBundle; use Sylius\Bundle\UserBundle\DependencyInjection\Compiler\RemoveUserPasswordEncoderPass; use Symfony\Component\DependencyInjection\ContainerBuilder; final class SyliusUserBundle extends AbstractResourceBundle { public function getSupportedDrivers(): array { return [ SyliusResourceBundle::DRIVER_DOCTRINE_ORM, ]; } public function build(ContainerBuilder $container): void { parent::build($container); $container->addCompilerPass(new RemoveUserPasswordEncoderPass()); } /** * @psalm-suppress MismatchingDocblockReturnType https://github.com/vimeo/psalm/issues/2345 */ protected function getModelNamespace(): string { return 'Sylius\Component\User\Model'; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\UserBundle; use Sylius\Bundle\ResourceBundle\AbstractResourceBundle; use Sylius\Bundle\ResourceBundle\SyliusResourceBundle; use Sylius\Bundle\UserBundle\DependencyInjection\Compiler\RemoveUserPasswordEncoderPass; use Symfony\Component\DependencyInjection\ContainerBuilder; final class SyliusUserBundle extends AbstractResourceBundle { public function getSupportedDrivers(): array { return [ SyliusResourceBundle::DRIVER_DOCTRINE_ORM, ]; } public function build(ContainerBuilder $container): void { $container->addCompilerPass(new RemoveUserPasswordEncoderPass()); } /** * @psalm-suppress MismatchingDocblockReturnType https://github.com/vimeo/psalm/issues/2345 */ protected function getModelNamespace(): string { return 'Sylius\Component\User\Model'; } }
Add new caps variable, fix line length
from zirc import Sasl, Caps # zIRC sasl = Sasl(username="BigWolfy1339", password="") caps = Caps(sasl, "multi-prefix") # IRC channels = ["##wolfy1339", "##powder-bots", "##jeffl35"] # Logging logFormat = '%(levelname)s %(asctime)s %(message)s' colorized = True timestampFormat = '%Y-%m-%dT%H:%M:%S' logLevel = 20 # INFO # Bot commandChar = '?' owners = ['botters/wolfy1339'] admins = [] trusted = [] bots = { 'hosts': ['botters/wolf1339/bot/bigwolfy1339'], 'channels': ['##jeffl35', '##wolfy1339'] } ignores = { 'global': [], 'channels': { "##powder-bots": [], "##wolfy1339": [], } } # Error messages noPerms = " ".join(["Sorry,", "you do not have the right permissions", "to execute this command"]) argsMissing = "Oops, looks like you forgot an argument there." invalidCmd = 'Invalid command {0}' tracebackPostError = "An error happened while trying to post the traceback"
from zirc import Sasl # zIRC sasl = Sasl(username="BigWolfy1339", password="") # IRC channels = ["##wolfy1339", "##powder-bots", "##jeffl35"] # Logging logFormat = '%(levelname)s %(asctime)s %(message)s' colorized = True timestampFormat = '%Y-%m-%dT%H:%M:%S' logLevel = 20 # INFO # Bot commandChar = '?' owners = ['botters/wolfy1339'] admins = [] trusted = [] bots = { 'hosts': ['botters/wolf1339/bot/bigwolfy1339'], 'channels': ['##jeffl35', '##wolfy1339'] } ignores = { 'global': [], 'channels': { "##powder-bots": [], "##wolfy1339": [], } } # Error messages noPerms = "Sorry, you do not have the right permissions to execute this command" argsMissing = "Oops, looks like you forgot an argument there." invalidCmd = 'Invalid command {0}' tracebackPostError = "An error happened while trying to post the traceback"
Extend is for objects, merge is for arrays.
'use strict'; /***** * Vain * * A view-first templating engine for Node.js. *****/ var jsdom = require('jsdom'), $ = require('jquery')(jsdom.jsdom().createWindow()), snippetRegistry = {}; /** * Register a snippet in the snippet registry. **/ exports.registerSnippet = function(snippetName, snippetFn) { snippetRegistry[snippetName] = snippetFn; }; /** * Process the given markup. **/ exports.render = function(input, options, fn) { if ('function' === typeof options) { fn = options; options = undefined; } options = options || {}; var $template = $("<div />").append(input), snippetHandlers = options.snippets || {}; $.extend(snippetHandlers, snippetRegistry); $template.find("[data-vain]").each(function() { var snippetName = $(this).data('vain'); if ('function' === typeof snippetHandlers[snippetName]) { snippetHandlers[snippetName]($, this); } $(this).removeAttr("data-vain"); }); return $template.html(); }; /** * Process a given file. **/ exports.renderFile = function(path, options, fn) { // }; // Express support. exports.__express = exports.renderFile;
'use strict'; /***** * Vain * * A view-first templating engine for Node.js. *****/ var jsdom = require('jsdom'), $ = require('jquery')(jsdom.jsdom().createWindow()), snippetRegistry = {}; /** * Register a snippet in the snippet registry. **/ exports.registerSnippet = function(snippetName, snippetFn) { snippetRegistry[snippetName] = snippetFn; }; /** * Process the given markup. **/ exports.render = function(input, options, fn) { if ('function' === typeof options) { fn = options; options = undefined; } options = options || {}; var $template = $("<div />").append(input), snippetHandlers = options.snippets || {}; $.merge(snippetHandlers, snippetRegistry); $template.find("[data-vain]").each(function() { var snippetName = $(this).data('vain'); if ('function' === typeof snippetHandlers[snippetName]) { snippetHandlers[snippetName]($, this); } $(this).removeAttr("data-vain"); }); return $template.html(); }; /** * Process a given file. **/ exports.renderFile = function(path, options, fn) { // }; // Express support. exports.__express = exports.renderFile;
Address PR comment. Made name consistent with others using camel case Former-commit-id: dd6877565ece23b153a6b4d26edc6a5d71ca1649
package org.innovateuk.ifs.finance.resource.cost; public enum OverheadRateType{ NONE(null, null, "None"), DEFAULT_PERCENTAGE(20, "defaultPercentage", "Default %"), TOTAL(null, "total", "Custom Amount"), CUSTOM_RATE(null, "customRate", "Custom Rate"); // NOTE: Now that competiton 1 is gone, there is no need to keep custom rate. TODO: Check with Rogier and remove if safe : INFUND-7322 private final Integer rate; private final String name; private final String label; OverheadRateType(Integer rate, String name, String label) { this.rate = rate; this.name = name; this.label = label; } public Integer getRate() { return rate; } public String getName() { return name; } public String getLabel() { return label; } }
package org.innovateuk.ifs.finance.resource.cost; public enum OverheadRateType{ NONE(null, null, "None"), DEFAULT_PERCENTAGE(20, "DEFAULT_PERCENTAGE", "Default %"), TOTAL(null, "total", "Custom Amount"), CUSTOM_RATE(null, "customRate", "Custom Rate"); // NOTE: Now that competiton 1 is gone, there is no need to keep custom rate. TODO: Check with Rogier and remove if safe : INFUND-7322 private final Integer rate; private final String name; private final String label; OverheadRateType(Integer rate, String name, String label) { this.rate = rate; this.name = name; this.label = label; } public Integer getRate() { return rate; } public String getName() { return name; } public String getLabel() { return label; } }
Make each test type a link to the edit page instead of using a form
<!-- resources/views/admin/testtype_index.blade.php --> @extends('layouts.app') @section('content') <h2>Test Types</h2> <p>Click a test type to edit</p> <table class="table"> <tbody> @foreach ($testtypes->chunk(2) as $chunk ) <tr> @foreach ($chunk as $testtype) <td>{{ $testtype->id }}</td> <td><a href="/admin/testtypes/{{ $testtype->id }}/edit">{{ $testtype->test_type }}</a></td> @endforeach </tr> @endforeach </tbody> </table> <h2>Add a Test Type</h2> <!-- Add a new test type --> <form class="form-inline" action="/admin/testtypes" method="POST"> <div class="form-group"> {{ csrf_field() }} <label for="testtype">New Test Type:</label> <input class="form-control" type="TEXT" id="testtype" name="testtype" size="30" /> <button class="btn btn-default" type="SUBMIT">Add test type</button> / <a href="/">Main</a> </div> </form> @endsection
<!-- resources/views/admin/testtype_index.blade.php --> @extends('layouts.app') @section('content') <h2>Test Types</h2> <table class="table"> <tbody> @foreach ($testtypes->chunk(2) as $chunk ) <tr> @foreach ($chunk as $testtype) <td>{{ $testtype->id }}</td> <td>{{ $testtype->test_type }}</td> <form action="/admin/testtypes/{{ $testtype->id }}/edit" method="POST"> <button type="submit">Edit</button> </form> @endforeach </tr> @endforeach </tbody> </table> <h2>Add a Test Type</h2> <!-- Add a new test type --> <form action="/admin/testtypes" method="POST"> {{ csrf_field() }} New Test Type: <input type="TEXT" name="testtype" size="30" /> <button type="SUBMIT">Add test type</button> / <a href="/">Main</a> </form> @endsection
Remove programmatically set <video> attributes Attributes added as HTML in 1a864376aab054ef7a90be41eeb50c28a2e43820
import { imageDataFromVideo } from './image-data.js' import { hasFired } from './promisify.js' class Camera { constructor (videoEl, stream) { this.videoEl = videoEl this.stream = stream } stop () { this.stream.getTracks().forEach( track => track.stop() ) } captureFrame () { return imageDataFromVideo(this.videoEl) } } export default async function (constraints, videoEl) { if (!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) { throw new Error('WebRTC API not supported in this browser') } const stream = await navigator.mediaDevices.getUserMedia(constraints) const streamLoaded = hasFired(videoEl, 'loadeddata', 'error') if (videoEl.srcObject !== undefined) { videoEl.srcObject = stream } else if (videoEl.mozSrcObject !== undefined) { videoEl.mozSrcObject = stream } else if (window.URL.createObjectURL) { videoEl.src = window.URL.createObjectURL(stream) } else if (window.webkitURL) { videoEl.src = window.webkitURL.createObjectURL(stream) } else { videoEl.src = stream } await streamLoaded return new Camera(videoEl, stream) }
import { imageDataFromVideo } from './image-data.js' import { hasFired } from './promisify.js' class Camera { constructor (videoEl, stream) { this.videoEl = videoEl this.stream = stream } stop () { this.stream.getTracks().forEach( track => track.stop() ) } captureFrame () { return imageDataFromVideo(this.videoEl) } } export default async function (constraints, videoEl) { if (!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) { throw new Error('WebRTC API not supported in this browser') } const stream = await navigator.mediaDevices.getUserMedia(constraints) const streamLoaded = hasFired(videoEl, 'loadeddata', 'error') if (videoEl.srcObject !== undefined) { videoEl.srcObject = stream } else if (videoEl.mozSrcObject !== undefined) { videoEl.mozSrcObject = stream } else if (window.URL.createObjectURL) { videoEl.src = window.URL.createObjectURL(stream) } else if (window.webkitURL) { videoEl.src = window.webkitURL.createObjectURL(stream) } else { videoEl.src = stream } videoEl.playsInline = true videoEl.play() // firefox does not emit `loadeddata` if video not playing await streamLoaded return new Camera(videoEl, stream) }
Use Meteor.setTimeout to re-run tryInsert function.
process.stdout.write("once test\n"); if (process.env.RUN_ONCE_OUTCOME === "exit") process.exit(123); if (process.env.RUN_ONCE_OUTCOME === "kill") { process.kill(process.pid, 'SIGKILL'); } if (process.env.RUN_ONCE_OUTCOME === "hang") { // The outstanding timeout will prevent node from exiting setTimeout(function () {}, 365 * 24 * 60 * 60); } if (process.env.RUN_ONCE_OUTCOME === "mongo") { var test = new Mongo.Collection('test'); var triesLeft = 10; function tryInsert() { try { test.insert({ value: 86 }); } catch (e) { if (--triesLeft <= 0) { throw e; } console.log("insert failed; retrying:", String(e.stack || e)); Meteor.setTimeout(tryInsert, 1000); return; } process.exit(test.findOne().value); } Meteor.startup(tryInsert); }
process.stdout.write("once test\n"); if (process.env.RUN_ONCE_OUTCOME === "exit") process.exit(123); if (process.env.RUN_ONCE_OUTCOME === "kill") { process.kill(process.pid, 'SIGKILL'); } if (process.env.RUN_ONCE_OUTCOME === "hang") { // The outstanding timeout will prevent node from exiting setTimeout(function () {}, 365 * 24 * 60 * 60); } if (process.env.RUN_ONCE_OUTCOME === "mongo") { var test = new Mongo.Collection('test'); var triesLeft = 10; function tryInsert() { try { test.insert({ value: 86 }); } catch (e) { if (--triesLeft <= 0) { throw e; } console.log("insert failed; retrying:", String(e.stack || e)); setTimeout(tryInsert, 1000); return; } process.exit(test.findOne().value); } Meteor.startup(tryInsert); }
Add date back to build display
"""Django admin interface for `~builds.models.Build` and related models. """ from django.contrib import admin from readthedocs.builds.models import Build, VersionAlias, Version, BuildCommandResult from guardian.admin import GuardedModelAdmin class BuildCommandResultInline(admin.TabularInline): model = BuildCommandResult fields = ('command', 'exit_code') class BuildAdmin(admin.ModelAdmin): fields = ('project', 'version', 'type', 'state', 'success', 'length') list_display = ('project', 'success', 'type', 'state', 'date') raw_id_fields = ('project', 'version') inlines = (BuildCommandResultInline,) class VersionAdmin(GuardedModelAdmin): search_fields = ('slug', 'project__name') list_filter = ('project', 'privacy_level') admin.site.register(Build, BuildAdmin) admin.site.register(VersionAlias) admin.site.register(Version, VersionAdmin)
"""Django admin interface for `~builds.models.Build` and related models. """ from django.contrib import admin from readthedocs.builds.models import Build, VersionAlias, Version, BuildCommandResult from guardian.admin import GuardedModelAdmin class BuildCommandResultInline(admin.TabularInline): model = BuildCommandResult fields = ('command', 'exit_code') class BuildAdmin(admin.ModelAdmin): fields = ('project', 'version', 'type', 'state', 'success', 'length') list_display = ('project', 'success', 'type', 'state') raw_id_fields = ('project', 'version') inlines = (BuildCommandResultInline,) class VersionAdmin(GuardedModelAdmin): search_fields = ('slug', 'project__name') list_filter = ('project', 'privacy_level') admin.site.register(Build, BuildAdmin) admin.site.register(VersionAlias) admin.site.register(Version, VersionAdmin)
Use 'slice' to clone an array
'use strict'; function createTree(list, rootNodes) { var tree = []; for (var prop in rootNodes) { if (!rootNodes.hasOwnProperty(prop)) { continue; } var node = rootNodes[prop]; if (list[node.id]) { node.children = createTree(list, list[node.id]); } tree.push(node); } return tree; } function orderByParents(list) { var parents = {}; list.forEach(function(item) { var parentID = item.parent_id || 0; parents[parentID] = parents[parentID] || []; parents[parentID].push(item); }); return parents; } module.exports = function(obj) { var cloned = obj.slice(); var ordered = orderByParents(cloned); return createTree(ordered, ordered[0]); };
'use strict'; function createTree(list, rootNodes) { var tree = []; for (var prop in rootNodes) { if (!rootNodes.hasOwnProperty(prop)) { continue; } var node = rootNodes[prop]; if (list[node.id]) { node.children = createTree(list, list[node.id]); } tree.push(node); } return tree; } function orderByParents(list) { var parents = {}; list.forEach(function(item) { var parentID = item.parent_id || 0; parents[parentID] = parents[parentID] || []; parents[parentID].push(item); }); return parents; } function clone(obj) { return JSON.parse(JSON.stringify(obj)); } module.exports = function(obj) { var cloned = clone(obj); var ordered = orderByParents(cloned); return createTree(ordered, ordered[0]); };
Adjust controller classifier to support lumen
<?php namespace Wnx\LaravelStats\Classifiers; use Wnx\LaravelStats\ReflectionClass; use Wnx\LaravelStats\Contracts\Classifier; class ControllerClassifier implements Classifier { public function getName() { return 'Controllers'; } public function satisfies(ReflectionClass $class) { return collect(app('router')->getRoutes()) ->reject(function ($route) { if (method_exists($route, 'getActionName')) { return $route->getActionName() === 'Closure'; } return data_get($route, 'action.uses') === null; }) ->map(function ($route) { if (method_exists($route, 'getController')) { return get_class($route->getController()); } return str_before(data_get($route, 'action.uses'), '@'); }) ->unique() ->contains($class->getName()); } }
<?php namespace Wnx\LaravelStats\Classifiers; use Illuminate\Routing\Router; use Wnx\LaravelStats\ReflectionClass; use Wnx\LaravelStats\Contracts\Classifier; class ControllerClassifier implements Classifier { public function getName() { return 'Controllers'; } public function satisfies(ReflectionClass $class) { return collect(resolve(Router::class)->getRoutes()) ->reject(function ($route) { return $route->getActionName() === 'Closure'; }) ->map(function ($route) { return get_class($route->getController()); }) ->unique() ->contains($class->getName()); } }
Format indent to 2 space.
var requestUrl = window.location.href; var autoRefresh = requestUrl.indexOf("autoRefresh=") != -1; function doAutoRefresh() { var refreshUrl = window.location.href; refreshUrl = refreshUrl.replace(window.location.hash, ""); if (refreshUrl.indexOf("?") == -1) { refreshUrl = refreshUrl + "?"; } refreshUrl = refreshUrl.replace(/(.+)&?autoRefresh=([^&]+)(.+)?/, "$1$3"); refreshUrl = refreshUrl + "&autoRefresh=1"; refreshUrl = refreshUrl.replace("?&", "?"); window.location.replace(refreshUrl); } var autoRefreshTimer; function toggleAutoRefresh() { if (autoRefresh) { autoRefresh = false; window.clearTimeout(autoRefreshTimer); $("#autorefresh-link").text("Enable Auto-Refresh"); } else { autoRefresh = true; autoRefreshTimer = window.setTimeout(doAutoRefresh, 15000); $("#autorefresh-link").text("Disable Auto-Refresh"); } } if (autoRefresh) { $("#autorefresh-link").text("Disable Auto-Refresh"); autoRefreshTimer = window.setTimeout(doAutoRefresh, 15000); } else { $("#autorefresh-link").text("Enable Auto-Refresh"); }
var requestUrl = window.location.href; var autoRefresh = requestUrl.indexOf("autoRefresh=") != -1; function doAutoRefresh() { var refreshUrl = window.location.href; refreshUrl = refreshUrl.replace(window.location.hash, ""); if (refreshUrl.indexOf("?") == -1) { refreshUrl = refreshUrl + "?"; } refreshUrl = refreshUrl.replace(/(.+)&?autoRefresh=([^&]+)(.+)?/, "$1$3"); refreshUrl = refreshUrl + "&autoRefresh=1"; refreshUrl = refreshUrl.replace("?&", "?"); window.location.replace(refreshUrl); } var autoRefreshTimer; function toggleAutoRefresh() { if (autoRefresh) { autoRefresh = false; window.clearTimeout(autoRefreshTimer); $("#autorefresh-link").text("Enable Auto-Refresh"); } else { autoRefresh = true; autoRefreshTimer = window.setTimeout(doAutoRefresh, 15000); $("#autorefresh-link").text("Disable Auto-Refresh"); } } if (autoRefresh) { $("#autorefresh-link").text("Disable Auto-Refresh"); autoRefreshTimer = window.setTimeout(doAutoRefresh, 15000); } else { $("#autorefresh-link").text("Enable Auto-Refresh"); }
Remove PlaybackProvider that does nothing
from __future__ import unicode_literals import logging import pykka from mopidy.backends import base from .library import VKLibraryProvider from .playlists import VKPlaylistsProvider from .session import VKSession logger = logging.getLogger('mopidy.backends.vkontakte.actor') class VKBackend(pykka.ThreadingActor, base.Backend): def __init__(self, config, audio): super(VKBackend, self).__init__() self.config = config self.session = VKSession(config=self.config) self.library = VKLibraryProvider(backend=self) self.playback = base.BasePlaybackProvider(audio=audio, backend=self) self.playlists = VKPlaylistsProvider(backend=self) self.uri_schemes = ['vkontakte']
from __future__ import unicode_literals import logging import pykka from mopidy.backends import base from .library import VKLibraryProvider from .playlists import VKPlaylistsProvider from .session import VKSession logger = logging.getLogger('mopidy.backends.vkontakte.actor') class VKBackend(pykka.ThreadingActor, base.Backend): def __init__(self, config, audio): super(VKBackend, self).__init__() self.config = config self.session = VKSession(config=self.config) self.library = VKLibraryProvider(backend=self) self.playback = VKPlaybackProvider(audio=audio, backend=self) self.playlists = VKPlaylistsProvider(backend=self) self.uri_schemes = ['vkontakte'] class VKPlaybackProvider(base.BasePlaybackProvider): def play(self, track): return super(VKPlaybackProvider, self).play(track)
Add link to MPX4250 spec sheet
package com.easternedgerobotics.rov.io; import com.easternedgerobotics.rov.io.pololu.PololuMaestroInputChannel; /** * A MPX4250 is an absolute pressure (AP) sensor. See also: <a href="http://goo.gl/n7c8tY">MPX4250</a>. */ public class MPX4250AP { /** * Scalar value for calculating pressure from voltage. */ private static final float PRESSURE_SCALAR = 0.264909785f; /** * Offset value for calculating pressure from voltage. */ private static final float PRESSURE_OFFSET = 54.20054200f; /** * The Pololu Maestro channel this device uses. */ private final PololuMaestroInputChannel channel; /** * Constructs a new MPX4250AP sensor on the given channel. * @param channel the channel this device uses */ public MPX4250AP(final PololuMaestroInputChannel channel) { this.channel = channel; } /** * Returns the pressure. * @return the pressure */ public final float read() { return channel.voltage() * PRESSURE_OFFSET - PRESSURE_SCALAR; } }
package com.easternedgerobotics.rov.io; import com.easternedgerobotics.rov.io.pololu.PololuMaestroInputChannel; public class MPX4250AP { /** * Scalar value for calculating pressure from voltage. */ private static final float PRESSURE_SCALAR = 0.264909785f; /** * Offset value for calculating pressure from voltage. */ private static final float PRESSURE_OFFSET = 54.20054200f; /** * The Pololu Maestro channel this device uses. */ private final PololuMaestroInputChannel channel; /** * Constructs a new MPX4250AP sensor on the given channel. * @param channel the channel this device uses */ public MPX4250AP(final PololuMaestroInputChannel channel) { this.channel = channel; } /** * Returns the pressure. * @return the pressure */ public final float read() { return channel.voltage() * PRESSURE_OFFSET - PRESSURE_SCALAR; } }
Disable pool generation by default
import urllib2 #Database settings database_connect = "dbname='ridprod'" kv1_database_connect = "dbname='kv1tmp'" iff_database_connect = "dbname='ifftmp'" pool_generation_enabled = False #NDOVLoket settings ndovloket_url = "data.ndovloket.nl" ndovloket_user = "voorwaarden" ndovloket_password = "geaccepteerd" auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm=ndovloket_url, uri=ndovloket_url, user=ndovloket_user, passwd=ndovloket_password) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener)
import urllib2 #Database settings database_connect = "dbname='ridprod'" kv1_database_connect = "dbname='kv1tmp'" iff_database_connect = "dbname='ifftmp'" pool_generation_enabled = True #NDOVLoket settings ndovloket_url = "data.ndovloket.nl" ndovloket_user = "voorwaarden" ndovloket_password = "geaccepteerd" auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm=ndovloket_url, uri=ndovloket_url, user=ndovloket_user, passwd=ndovloket_password) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener)
Update script for init seahub_settings.py in Windows
#!/usr/bin/env python # encoding: utf-8 import sys from hashlib import md5, sha1 from base64 import urlsafe_b64encode as b64encode import random random.seed() def random_string(): """ Generate a random string (currently a random number as a string) """ return str(random.randint(0,100000)) def generate_key(max_length, data, encoder=b64encode, digester=md5): """ Generate a Base64-encoded 'random' key by hashing the data. data is a tuple of seeding values. Pass arbitrary encoder and digester for specific hashing and formatting of keys """ base = '' for arg in data: base += str(arg) key = encoder(digester(base).digest()) return key[:max_length] if __name__ == "__main__": key = generate_key(40, (random_string(),)) if len(sys.argv) == 2: fp = open(sys.argv[1], 'w') fp.write("SECRET_KEY = \"%s\"\n" % key) fp.close() else: print key
#!/usr/bin/env python # encoding: utf-8 from hashlib import md5, sha1 from base64 import urlsafe_b64encode as b64encode import random random.seed() def random_string(): """ Generate a random string (currently a random number as a string) """ return str(random.randint(0,100000)) def generate_key(max_length, data, encoder=b64encode, digester=md5): """ Generate a Base64-encoded 'random' key by hashing the data. data is a tuple of seeding values. Pass arbitrary encoder and digester for specific hashing and formatting of keys """ base = '' for arg in data: base += str(arg) key = encoder(digester(base).digest()) return key[:max_length] if __name__ == "__main__": print generate_key(40, (random_string(),))
Fix update "WHERE WHERE" bug.
package ollie.internal; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.provider.BaseColumns; import ollie.Model; public abstract class ModelAdapter<T extends Model> { public abstract Class<? extends Model> getModelType(); public abstract String getTableName(); public abstract String getSchema(); public abstract void load(T entity, Cursor cursor); public abstract Long save(T entity, SQLiteDatabase db); public abstract void delete(T entity, SQLiteDatabase db); protected final Long insertOrUpdate(T entity, SQLiteDatabase db, ContentValues values) { if (entity.id == null) { entity.id = db.insert(getTableName(), null, values); } else { db.update(getTableName(), values, BaseColumns._ID + "=?", new String[]{entity.id.toString()}); } return entity.id; } }
package ollie.internal; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.provider.BaseColumns; import ollie.Model; public abstract class ModelAdapter<T extends Model> { public abstract Class<? extends Model> getModelType(); public abstract String getTableName(); public abstract String getSchema(); public abstract void load(T entity, Cursor cursor); public abstract Long save(T entity, SQLiteDatabase db); public abstract void delete(T entity, SQLiteDatabase db); protected final Long insertOrUpdate(T entity, SQLiteDatabase db, ContentValues values) { if (entity.id == null) { entity.id = db.insert(getTableName(), null, values); } else { db.update(getTableName(), values, "WHERE " + BaseColumns._ID + "=?", new String[]{entity.id.toString()}); } return entity.id; } }
[core] Update example for <Popover> to verify behavior
import React from 'react'; import { action } from '@storybook/addon-actions'; import Button from '@ichef/gypcrete/src/Button'; import List from '@ichef/gypcrete/src/List'; import ListRow from '@ichef/gypcrete/src/ListRow'; function DemoButton(props) { return ( <Button bold minified={false} color="black" {...props} /> ); } function DemoList() { return ( <List> <ListRow> <DemoButton basic="Row 1" onClick={action('click.1')} /> </ListRow> <ListRow> <DemoButton basic="Row 2" onClick={action('click.2')} /> </ListRow> <ListRow> <DemoButton basic="Row 3" onClick={action('click.3')} /> </ListRow> </List> ); } export default DemoList;
import React from 'react'; import List from '@ichef/gypcrete/src/List'; import ListRow from '@ichef/gypcrete/src/ListRow'; import TextLabel from '@ichef/gypcrete/src/TextLabel'; function DemoList() { return ( <List> <ListRow> <TextLabel basic="Row 1" /> </ListRow> <ListRow> <TextLabel basic="Row 2" /> </ListRow> <ListRow> <TextLabel basic="Row 3" /> </ListRow> </List> ); } export default DemoList;
BAP-11559: Move all bundles to the Oro namespace
<?php namespace Oro\Bundle\EntityBundle\Migrations\Schema; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\Installation; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class OroEntityBundleInstaller implements Installation { /** * {@inheritdoc} */ public function getMigrationVersion() { return 'v1_0'; } /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { /** Tables generation **/ $this->createOroEntityFallbackValueTable($schema); } /** * Create oro_entity_fallback_value table * * @param Schema $schema */ protected function createOroEntityFallbackValueTable(Schema $schema) { $table = $schema->createTable('oro_entity_fallback_value'); $table->addColumn('id', 'integer', ['autoincrement' => true]); $table->addColumn('fallback', 'string', ['notnull' => false, 'length' => 64]); $table->addColumn('scalar_value', 'string', ['notnull' => false, 'length' => 255]); $table->addColumn('array_value', 'array', ['notnull' => false, 'comment' => '(DC2Type:array)']); $table->setPrimaryKey(['id']); } }
<?php namespace Oro\EntityBundle\Migrations\Schema; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\Installation; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class OroEntityBundleInstaller implements Installation { /** * {@inheritdoc} */ public function getMigrationVersion() { return 'v1_0'; } /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { /** Tables generation **/ $this->createOroEntityFallbackValueTable($schema); } /** * Create oro_entity_fallback_value table * * @param Schema $schema */ protected function createOroEntityFallbackValueTable(Schema $schema) { $table = $schema->createTable('oro_entity_fallback_value'); $table->addColumn('id', 'integer', ['autoincrement' => true]); $table->addColumn('fallback', 'string', ['notnull' => false, 'length' => 64]); $table->addColumn('scalar_value', 'string', ['notnull' => false, 'length' => 255]); $table->addColumn('array_value', 'array', ['notnull' => false, 'comment' => '(DC2Type:array)']); $table->setPrimaryKey(['id']); } }
Add read only functionnality on published node
<?php namespace PHPOrchestra\ModelBundle\EventListener; use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs; use Doctrine\ODM\MongoDB\Event\PostFlushEventArgs; use PHPOrchestra\ModelBundle\Model\StatusInterface; use PHPOrchestra\ModelBundle\Model\StatusableInterface; /** * Class SavePublishedDocumentListener */ class SavePublishedDocumentListener { /** * @param LifecycleEventArgs $eventArgs */ public function preUpdate(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); if ($document instanceof StatusableInterface) { $status = $document->getStatus(); if (! empty($status) && $status->isPublished() && (!method_exists($document, 'isDeleted') || ! $document->isDeleted()) ) { $documentManager = $eventArgs->getDocumentManager(); $documentManager->getUnitOfWork()->detach($document); } } } }
<?php namespace PHPOrchestra\ModelBundle\EventListener; use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs; use Doctrine\ODM\MongoDB\Event\PostFlushEventArgs; use PHPOrchestra\ModelBundle\Model\StatusInterface; use PHPOrchestra\ModelBundle\Model\StatusableInterface; /** * Class SavePublishedDocumentListener */ class SavePublishedDocumentListener { /** * @param LifecycleEventArgs $eventArgs */ public function preUpdate(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); if ($document instanceof StatusableInterface) { $status = $document->getStatus(); if (! empty($status) && $status->isPublished() && (! method_exists($document, 'isDeleted') || ! $document->isDeleted())) { $documentManager = $eventArgs->getDocumentManager(); $documentManager->getUnitOfWork()->detach($document); } } } }
Check for auto reports send ever 5 min
import { Meteor } from 'meteor/meteor'; import moment from 'moment'; import { sendReports } from '../../lib/imports/sendReports'; const CHECK_INTERVAL = { minutes: 5, }; function autoSendReports() { const now = moment(); const gameState = Gamestate.findOne(); const lastAutoReportSend = moment(gameState.lastAutoReportSend || moment(now).subtract(2, 'day')); const waitingUntil = moment(lastAutoReportSend).add(1, 'day'); Meteor.logger.info(`Checking to send auto reports. now: ${now} .. waiting for ${waitingUntil}`); if (now.isAfter(waitingUntil)) { const sendTime = moment(now).startOf('hour'); Meteor.logger.info(`Sending auto reports at ${sendTime} to: ${gameState.sendReportsTo}`); sendReports(gameState.sendReportsTo); Gamestate.update({ _id: gameState._id}, { $set: { lastAutoReportSend: sendTime }}); } } Meteor.startup(() => { // On Startup, init Interval for puzzle timeout watcher. const interval = moment.duration(CHECK_INTERVAL).asMilliseconds(); Meteor.setInterval(autoSendReports, interval); });
import { Meteor } from 'meteor/meteor'; import moment from 'moment'; import { sendReports } from '../../lib/imports/sendReports'; const CHECK_INTERVAL = { minutes: 1, }; function autoSendReports() { const now = moment(); const gameState = Gamestate.findOne(); const lastAutoReportSend = moment(gameState.lastAutoReportSend || moment(now).subtract(2, 'day')); const waitingUntil = moment(lastAutoReportSend).add(1, 'day'); Meteor.logger.info(`Checking to send auto reports. now: ${now} .. waiting for ${waitingUntil}`); if (now.isAfter(waitingUntil)) { const sendTime = moment(now).startOf('hour'); Meteor.logger.info(`Sending auto reports at ${sendTime} to: ${gameState.sendReportsTo}`); sendReports(gameState.sendReportsTo); Gamestate.update({ _id: gameState._id}, { $set: { lastAutoReportSend: sendTime }}); } } Meteor.startup(() => { // On Startup, init Interval for puzzle timeout watcher. const interval = moment.duration(CHECK_INTERVAL).asMilliseconds(); Meteor.setInterval(autoSendReports, interval); });
Put basic info in one table
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): table = VeryPrettyTable() table.field_names = ['String', 'Length', '# Digits', '# Alpha', '# Punct.', '# Control'] for s in self.args['STRING']: table.add_row((s, len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) return str(table) + '\n'
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return result
Revert last JPA EA7 change per Jeremy/Panaki for further testing git-svn-id: 60e751271f50ec028ae56d425821c1c711e0b018@807385 13f79535-47bb-0310-9956-ffa450edef68
/* * 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. */ // // This source code implements specifications defined by the Java // Community Process. In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package javax.persistence; public interface TupleElement<X> { Class<X> getJavaType(); String getAlias(); }
/* * 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. */ // // This source code implements specifications defined by the Java // Community Process. In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package javax.persistence; public interface TupleElement<X> { Class<? extends X> getJavaType(); String getAlias(); }
Add some debug information to the server terminal.
package server.net; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import server.lobby.LobbyManager; import proto.Message.MessageWrapper; public class ServerHandler extends SimpleChannelInboundHandler<MessageWrapper> { private static final LobbyManager lobbyManager = new LobbyManager(); @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { lobbyManager.disconnectPlayer(ctx.channel()); } @Override public void handlerAdded(ChannelHandlerContext ctx) { lobbyManager.connectPlayer(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " has joined."); } @Override public void handlerRemoved(ChannelHandlerContext ctx) { lobbyManager.disconnectPlayer(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " has left."); } @Override public void channelRead0(ChannelHandlerContext ctx, MessageWrapper msg) { lobbyManager.handleAction(ctx.channel(), msg); } }
package server.net; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import server.LobbyManager; import proto.Message.MessageWrapper; public class ServerHandler extends SimpleChannelInboundHandler<MessageWrapper> { private static final LobbyManager lobbyManager = new LobbyManager(); @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { lobbyManager.disconnectPlayer(ctx.channel()); } @Override public void handlerAdded(ChannelHandlerContext ctx) { lobbyManager.connectPlayer(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " has joined."); } @Override public void handlerRemoved(ChannelHandlerContext ctx) { lobbyManager.disconnectPlayer(ctx.channel()); System.out.println(ctx.channel().remoteAddress() + " has left."); } @Override public void channelRead0(ChannelHandlerContext ctx, MessageWrapper msg) { lobbyManager.handleAction(ctx.channel(), msg); } }
Handle case when getting the width of a text, if a letter is not recognized, the width is not incremented instead of throwing a NullPointerException.
package com.web4enterprise.pdf.core.font; import java.util.HashMap; import java.util.Map; import com.web4enterprise.pdf.core.BoundingBox; public abstract class Font { protected static Map<String, Font> fonts = new HashMap<>(); protected static Map<Byte, Integer> widths = new HashMap<>(); protected static Map<Byte, BoundingBox> boxes = new HashMap<>(); public static Font TIMES_ROMAN = new TimesRoman(); static { fonts.put("Times-Roman", TIMES_ROMAN); } public int getWidth(Integer size, String string) { int fullWidth = 0; for(byte letter : string.getBytes()) { Integer width = widths.get(letter); if(width != null) { fullWidth += width; } } return (int) Math.round(fullWidth * size / 1000.0f); } public int getHeight(Integer size, String string) { int greaterHeight = 0; for(byte letter : string.getBytes()) { BoundingBox letterBox = boxes.get(letter); int height = letterBox.getHeight(); if(height > greaterHeight) { greaterHeight = height; } } return (int) Math.round(greaterHeight * size / 1000.0f); } public static Font getFont(String name) { return fonts.get(name); } }
package com.web4enterprise.pdf.core.font; import java.util.HashMap; import java.util.Map; import com.web4enterprise.pdf.core.BoundingBox; public abstract class Font { protected static Map<String, Font> fonts = new HashMap<>(); protected static Map<Byte, Integer> widths = new HashMap<>(); protected static Map<Byte, BoundingBox> boxes = new HashMap<>(); static { fonts.put("Times-Roman", new TimesRoman()); } public int getWidth(Integer size, String text) { int fullWidth = 0; for(byte letter : text.getBytes()) { fullWidth += widths.get(letter); } return (int) Math.round(fullWidth * size / 1000.0f); } public int getHeight(Integer size, String text) { int greaterHeight = 0; for(byte letter : text.getBytes()) { BoundingBox letterBox = boxes.get(letter); int height = letterBox.getHeight(); if(height > greaterHeight) { greaterHeight = height; } } return (int) Math.round(greaterHeight * size / 1000.0f); } public static Font getFont(String name) { return fonts.get(name); } }
Extend from the proper layer
var TC = require('tangram.cartodb'); var LeafletLayerView = require('./leaflet-layer-view'); var L = require('leaflet'); var LeafletCartoDBVectorLayerGroupView = L.Layer.extend({ includes: [ LeafletLayerView.prototype ], options: { minZoom: 0, maxZoom: 28, tileSize: 256, zoomOffset: 0, tileBuffer: 50 }, events: { featureOver: null, featureOut: null, featureClick: null }, initialize: function (layerGroupModel, map) { LeafletLayerView.call(this, layerGroupModel, this, map); layerGroupModel.bind('change:urls', this._onURLsChanged, this); this.tangram = new TC(map); layerGroupModel.each(this._onLayerAdded, this); layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this)); }, onAdd: function (map) { L.Layer.prototype.onAdd.call(this, map); }, _onLayerAdded: function (layer) { var self = this; layer.bind('change:meta', function (e) { self.tangram.addLayer(e.attributes); }); }, _onURLsChanged: function (e, res) { this.tangram.addDataSource(res.tiles[0]); } }); module.exports = LeafletCartoDBVectorLayerGroupView;
var TC = require('tangram.cartodb'); var LeafletLayerView = require('./leaflet-layer-view'); var LeafletCartoDBVectorLayerGroupView = window.L.TileLayer.extend({ includes: [ LeafletLayerView.prototype ], options: { minZoom: 0, maxZoom: 28, tileSize: 256, zoomOffset: 0, tileBuffer: 50 }, events: { featureOver: null, featureOut: null, featureClick: null }, initialize: function (layerGroupModel, map) { LeafletLayerView.call(this, layerGroupModel, this, map); layerGroupModel.bind('change:urls', this._onURLsChanged, this); this.tangram = new TC(map); layerGroupModel.each(this._onLayerAdded, this); layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this)); }, onAdd: function (map) { }, _onLayerAdded: function (layer) { var self = this; layer.bind('change:meta', function (e) { self.tangram.addLayer(e.attributes); }); }, _onURLsChanged: function (e, res) { this.tangram.addDataSource(res.tiles[0]); } }); module.exports = LeafletCartoDBVectorLayerGroupView;
Remove debug logging and rejection on invoke promise rejection
module.exports = function ( opt ) { opt = opt || {}; var vfs = require('vinyl-fs'), Promise = require('promise'); // Hook function return function ( context ) { var targetPath = opt.targetPath || context.targetPath; // Package hook function return function ( pkg, globs ) { // Promise return new Promise(function ( resolve, reject ) { context.invokedPromise.then(function ( ) { vfs.src(globs, {cwd: pkg.exportsAbsolutePath}) .pipe(vfs.dest(targetPath)) .on('end', resolve) .on('error', reject); }); }); } }; }
module.exports = function ( opt ) { opt = opt || {}; var vfs = require('vinyl-fs'), Promise = require('promise'); // Hook function return function ( context ) { var targetPath = opt.targetPath || context.targetPath; // Package hook function return function ( pkg, globs ) { // Promise return new Promise(function ( resolve, reject ) { context.invokedPromise.then(function ( ) { console.log(pkg); vfs.src(globs, {cwd: pkg.exportsAbsolutePath}) .pipe(vfs.dest(targetPath)) .on('end', resolve) .on('error', reject); }, reject); }); } }; }